agentix-cli 0.41.0 → 0.42.0

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.
@@ -1,34 +1,34 @@
1
- import{a as Gr,b as hn,g as zr}from"./chunk-SJPLXXCI.js";import{b as qr}from"./chunk-B5HKRYCU.js";import{a as Zo,b as Fr,f as fn,j as Hr}from"./chunk-REPZID5M.js";import{a as Wr,c as Br,d as Jr}from"./chunk-2TJ5L7CB.js";import{a as Xo}from"./chunk-GV7S5BAX.js";import{e as Wi}from"./chunk-GSX4NK2N.js";import{c as Bi}from"./chunk-SZDACK6O.js";import{$ as Ct,A as ds,B as ln,C as br,D as Qo,E as uo,F as $r,G as gs,H as ms,I as kr,J as vr,K as It,L as dn,M as xr,N as Sr,O as Er,P as gn,Q as Ar,R as Or,S as ps,T as mn,U as pn,V as jr,W as Ir,X as Cr,Y as Tr,Z as Ee,_ as un,a as Qi,aa as us,b as Zi,ba as Nr,ca as Rr,da as _r,ea as Lr,fa as ys,ga as ws,h as nr,ha as Mr,i as sr,ia as Ur,j as Ot,k as cn,l as ir,m as rr,n as ar,o as cr,p as lr,q as dr,r as gr,s as mr,t as pr,u as ur,v as fr,w as hr,x as yr,y as wr,z as jt}from"./chunk-FZ3ZDG6T.js";import{i as Dr,j as fs,k as Pr,l as hs}from"./chunk-F6CNF7V3.js";import{a as er,d as or,e as tr}from"./chunk-FAJEBVZE.js";import{J as Xi,m as Mi,o as Yo,q as as,r as Fi,t as po,z as Ki}from"./chunk-DIKZWTL5.js";import{b as Vo,c as rn,d as an,e as Ko,f as qi,g as Co,h as At}from"./chunk-P7LNYB53.js";import{d as ls,f as Yi}from"./chunk-VMDA2SX2.js";import{a as zi}from"./chunk-QLTM3F7M.js";import{a as Ui,e as Gi}from"./chunk-NZ6AQIKJ.js";import{f as Ji,g as Hi,h as cs}from"./chunk-76Z4VHDX.js";import{a as de,b as be,c as To,d as Vi}from"./chunk-B32HVIDN.js";import{h as Li}from"./chunk-DWADWDMU.js";import{b as mo,d as sn,f as rs}from"./chunk-RCVGIKC2.js";import{b as zo,d as Pi}from"./chunk-2GIDVZ4H.js";import{a as is,b as Si,c as wl,d as tn,e as Ei,f as Ci,g as $l,h as Ti,i as kl,m as Go,n as Ri,o as _i,s as Di,v as Xe,w as Et}from"./chunk-H4MIYENA.js";import{a as Ni,b as vl}from"./chunk-AJONZWLT.js";import{a as io,b as Ho,e as Oi,f as St}from"./chunk-F4HZTZHW.js";import{a as so,b as yl}from"./chunk-L2WSPY6S.js";import{f as Ai,g as D,h as nn,j as we}from"./chunk-IAG6FI3Q.js";import{g as ji,k as Ii,l as bl}from"./chunk-BH3GTCZ6.js";import{a as hl}from"./chunk-FIOB3MEX.js";import{Command as xl}from"commander";var Yr=new xl().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 Zi({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()});we();import{Command as Sl}from"commander";import{execFileSync as ro}from"node:child_process";import{cpSync as Vr,existsSync as ks,mkdirSync as bs,mkdtempSync as El,readFileSync as Al,rmSync as Ol,writeFileSync as Kr}from"node:fs";import{dirname as $s,join as Ie,resolve as Xr}from"node:path";import{homedir as yn,release as jl,tmpdir as Il}from"node:os";import{fileURLToPath as Cl}from"node:url";import{setTimeout as Tl}from"node:timers/promises";function wn(){let e=jr(process.platform,process.arch,jl());if(e)throw new Error(e)}function Tt(){return`gui/${process.getuid()}/${ps}`}function et(){return Ie(yn(),"Library/LaunchAgents",`${ps}.plist`)}async function Qr(){try{ro("launchctl",["bootout",Tt()],{stdio:"pipe"})}catch{}for(let e=0;e<30;e++){try{ro("launchctl",["print",Tt()],{stdio:"pipe"})}catch{return}await Tl(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Zr(){if(!ks(et()))throw new Error("Run agentx desktop install first.");let e=!0;try{ro("launchctl",["print",Tt()],{stdio:"pipe"})}catch{e=!1}e||ro("launchctl",["bootstrap",`gui/${process.getuid()}`,et()],{stdio:"pipe"}),ro("launchctl",["kickstart",Tt()],{stdio:"pipe"})}function Nl(){let e=$s(Cl(import.meta.url));for(let o of[Xr(e,".."),Xr(e,"../.."),process.cwd()])try{if(JSON.parse(Al(Ie(o,"package.json"),"utf8")).name==="agentix-cli"&&ks(Ie(o,"apps/mac-voice/build.sh")))return o}catch{}throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var ot=new Sl("desktop").description("install and control the macOS desktop assistant");ot.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","agent to use (defaults to the first configured agent)").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{wn();let o=D(),t=Ir(o.agents,e.agent),n=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,s=Nl(),i=Ie(yn(),"Applications");if(console.log(`Desktop assistant \u2192 ${Ie(i,mn)}
2
- Computer-use helper \u2192 ${Ie(i,pn)}
1
+ import{a as ta,b as xn,g as na}from"./chunk-SJPLXXCI.js";import{b as Xr}from"./chunk-B5HKRYCU.js";import{a as nt,b as Kr,f as vn,j as oa}from"./chunk-REPZID5M.js";import{a as Qr,c as Zr,d as ea}from"./chunk-2TJ5L7CB.js";import{a as et}from"./chunk-GV7S5BAX.js";import{e as er}from"./chunk-GSX4NK2N.js";import{c as or}from"./chunk-SZDACK6O.js";import{$ as Dt,A as ks,B as fn,C as Cr,D as ot,E as ho,F as Nr,G as vs,H as xs,I as Rr,J as Dr,K as Rt,L as hn,M as _r,N as Pr,O as Lr,P as tt,Q as Mr,R as Fr,S as Ss,T as yn,U as wn,V as Ur,W as qr,X as Wr,Y as Br,Z as $e,_ as bn,a as dr,aa as Es,b as gr,ba as Jr,ca as $n,da as kn,ea as zr,fa as Ts,ga as Is,h as fr,ha as Yr,i as hr,ia as Vr,j as Ct,k as un,l as yr,m as wr,n as br,o as $r,p as kr,q as vr,r as xr,s as Sr,t as Er,u as Ar,v as Or,w as Tr,x as Ir,y as jr,z as Nt}from"./chunk-FZ3ZDG6T.js";import{i as Gr,j as As,k as Hr,l as Os}from"./chunk-F6CNF7V3.js";import{a as mr,d as pr,e as ur}from"./chunk-FAJEBVZE.js";import{J as lr,m as Ki,o as Xo,q as ws,r as Qi,t as fo,z as cr}from"./chunk-DIKZWTL5.js";import{b as Qo,c as mn,d as pn,e as Zo,f as Zi,g as No,h as jt}from"./chunk-P7LNYB53.js";import{d as $s,f as rr}from"./chunk-VMDA2SX2.js";import{a as ir}from"./chunk-QLTM3F7M.js";import{a as Xi,e as sr}from"./chunk-NZ6AQIKJ.js";import{f as tr,g as nr,h as bs}from"./chunk-76Z4VHDX.js";import{a as de,b as be,c as Ro,d as ar}from"./chunk-B32HVIDN.js";import{h as Vi}from"./chunk-DWADWDMU.js";import{b as uo,d as gn,f as ys}from"./chunk-RCVGIKC2.js";import{b as Ko,d as Yi}from"./chunk-2GIDVZ4H.js";import{a as hs,b as Pi,c as Ll,d as ln,e as Li,f as Wi,g as Fl,h as Bi,i as Ul,m as Vo,n as Gi,o as Hi,s as zi,v as Qe,w as It}from"./chunk-H4MIYENA.js";import{a as Ji,b as ql}from"./chunk-AJONZWLT.js";import{a as ao,b as Yo,e as Fi,f as Tt}from"./chunk-F4HZTZHW.js";import{a as ro,b as Pl}from"./chunk-L2WSPY6S.js";import{f as Mi,g as _,h as dn,j as pe}from"./chunk-IAG6FI3Q.js";import{g as Ui,k as qi,l as Ml}from"./chunk-BH3GTCZ6.js";import{a as _l}from"./chunk-FIOB3MEX.js";import{Command as Wl}from"commander";var sa=new Wl().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 gr({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()});pe();import{Command as Bl}from"commander";import{execFileSync as co}from"node:child_process";import{cpSync as ia,existsSync as Ns,mkdirSync as js,mkdtempSync as Jl,readFileSync as Gl,rmSync as Hl,writeFileSync as ra}from"node:fs";import{dirname as Cs,join as Ie,resolve as aa}from"node:path";import{homedir as Sn,release as zl,tmpdir as Yl}from"node:os";import{fileURLToPath as Vl}from"node:url";import{setTimeout as Kl}from"node:timers/promises";function En(){let e=Ur(process.platform,process.arch,zl());if(e)throw new Error(e)}function _t(){return`gui/${process.getuid()}/${Ss}`}function st(){return Ie(Sn(),"Library/LaunchAgents",`${Ss}.plist`)}async function ca(){try{co("launchctl",["bootout",_t()],{stdio:"pipe"})}catch{}for(let e=0;e<30;e++){try{co("launchctl",["print",_t()],{stdio:"pipe"})}catch{return}await Kl(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function la(){if(!Ns(st()))throw new Error("Run agentx desktop install first.");let e=!0;try{co("launchctl",["print",_t()],{stdio:"pipe"})}catch{e=!1}e||co("launchctl",["bootstrap",`gui/${process.getuid()}`,st()],{stdio:"pipe"}),co("launchctl",["kickstart",_t()],{stdio:"pipe"})}function Xl(){let e=Cs(Vl(import.meta.url));for(let o of[aa(e,".."),aa(e,"../.."),process.cwd()])try{if(JSON.parse(Gl(Ie(o,"package.json"),"utf8")).name==="agentix-cli"&&Ns(Ie(o,"apps/mac-voice/build.sh")))return o}catch{}throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var it=new Bl("desktop").description("install and control the macOS desktop assistant");it.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","agent to use (defaults to the first configured agent)").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{En();let o=_(),t=qr(o.agents,e.agent),n=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,s=Xl(),i=Ie(Sn(),"Applications");if(console.log(`Desktop assistant \u2192 ${Ie(i,yn)}
2
+ Computer-use helper \u2192 ${Ie(i,wn)}
3
3
  Agent \u2192 ${t}
4
4
  Daemon \u2192 ${n}
5
- Starts at login \u2192 ${et()}`),e.dryRun)return;try{ro("xcrun",["--find","swiftc"],{stdio:"pipe"})}catch{throw new Error("Apple command-line tools are required. Run xcode-select --install, finish installation, then retry.")}let r=El(Ie(Il(),"agentx-desktop-"));try{for(let g of["mac-helper","mac-voice"])Vr(Ie(s,"apps",g),Ie(r,g),{recursive:!0,filter:l=>!l.split("/").includes("build")}),ro("/bin/bash",[Ie(r,g,"build.sh")],{stdio:"inherit"});let a=Ie(yn(),"Library/Logs/agentx-desktop.err.log"),c=Cr({executable:Ie(i,mn,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:t,url:n,helper:Tr(yn()),cli:Ie(s,"dist/cli.js"),node:process.execPath,log:a}),d=Ie(r,"desktop.plist");Kr(d,c,{mode:384}),ro("plutil",["-lint",d],{stdio:"pipe"}),await Qr(),bs(i,{recursive:!0});for(let[g,l,p]of[["mac-voice","AgentX Voice.app",mn],["mac-helper",pn,pn]])Vr(Ie(r,g,"build",l),Ie(i,p),{recursive:!0});bs($s(et()),{recursive:!0}),bs($s(a),{recursive:!0}),Kr(et(),c,{mode:384}),Zr(),console.log(`Desktop assistant is running. Hold Option\u2013Space to speak; Command\u2013Option\u2013V for smart paste.
5
+ Starts at login \u2192 ${st()}`),e.dryRun)return;try{co("xcrun",["--find","swiftc"],{stdio:"pipe"})}catch{throw new Error("Apple command-line tools are required. Run xcode-select --install, finish installation, then retry.")}let r=Jl(Ie(Yl(),"agentx-desktop-"));try{for(let g of["mac-helper","mac-voice"])ia(Ie(s,"apps",g),Ie(r,g),{recursive:!0,filter:l=>!l.split("/").includes("build")}),co("/bin/bash",[Ie(r,g,"build.sh")],{stdio:"inherit"});let a=Ie(Sn(),"Library/Logs/agentx-desktop.err.log"),c=Wr({executable:Ie(i,yn,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:t,url:n,helper:Br(Sn()),cli:Ie(s,"dist/cli.js"),node:process.execPath,log:a}),d=Ie(r,"desktop.plist");ra(d,c,{mode:384}),co("plutil",["-lint",d],{stdio:"pipe"}),await ca(),js(i,{recursive:!0});for(let[g,l,p]of[["mac-voice","AgentX Voice.app",yn],["mac-helper",wn,wn]])ia(Ie(r,g,"build",l),Ie(i,p),{recursive:!0});js(Cs(st()),{recursive:!0}),js(Cs(a),{recursive:!0}),ra(st(),c,{mode:384}),la(),console.log(`Desktop assistant is running. Hold Option\u2013Space to speak; Command\u2013Option\u2013V for smart paste.
6
6
  Allow Microphone for the app and Accessibility / Screen Recording for the helper when macOS asks.
7
- The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{Ol(r,{recursive:!0,force:!0})}});ot.command("start").description("start the installed desktop assistant").action(()=>{wn(),Zr(),console.log("Desktop assistant started.")});ot.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{wn(),await Qr(),console.log("Desktop assistant stopped.")});ot.command("status").description("show the desktop login service status").action(()=>{wn();try{console.log(ro("launchctl",["print",Tt()],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(ks(et())?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as Ml}from"commander";import{open as Ul}from"fs/promises";import{existsSync as kn,mkdirSync as Rl,readFileSync as vn,writeFileSync as ea}from"fs";import{homedir as _l}from"os";import{dirname as Dl,resolve as vs}from"path";var xs="/attach/",oa="/guard/check";function ta(e,o,t=""){return`curl -s --max-time 3 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${o}${e}${t}`}' 2>/dev/null || true`}function bn(e,o,t){let n={hooks:[{type:"command",command:ta(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function Pl(e){return{SessionStart:[bn("/attach/session-start",e,"")],UserPromptSubmit:[bn("/attach/prompt",e)],Stop:[bn("/attach/stop",e)],SessionEnd:[bn("/attach/session-end",e)]}}function Ll(e){let o=ta("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function $n(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function Nt(){return vs(_l(),".claude/settings.json")}function Rt(e=process.cwd()){for(let o of[e,vs(e,"..")]){let t=vs(o,"agentx.json");if(kn(t))try{let n=JSON.parse(vn(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function na(e,o={}){let t=o.path??Nt(),n=o.withGuard!==!1,s={};if(kn(t))try{s=JSON.parse(vn(t,"utf-8"))}catch(g){throw new Error(`${t} is not valid JSON (${g?.message}) \u2014 refusing to overwrite it`)}let i=JSON.stringify(s),r=s.hooks??={},a=[];for(let[g,l]of Object.entries(Pl(e))){let p=Array.isArray(r[g])?r[g].filter(f=>!$n(f,xs)):[];r[g]=[...p,...l],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(l=>!$n(l,oa)):[];r.PreToolUse=[...g,...Ll(e)],c=!0}let d=JSON.stringify(s)!==i;return d&&(Rl(Dl(t),{recursive:!0}),ea(t,`${JSON.stringify(s,null,2)}
8
- `)),{path:t,changed:d,events:a,guardInstalled:c}}function sa(e={}){let o=e.path??Nt();if(!kn(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(vn(o,"utf-8"))}catch(a){throw new Error(`${o} is not valid JSON (${a?.message}) \u2014 refusing to rewrite it`)}let n=JSON.stringify(t),s=t.hooks,i=[];if(s&&typeof s=="object"){for(let a of Object.keys(s)){if(!Array.isArray(s[a]))continue;let c=a==="PreToolUse"?oa:xs;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let d=s[a].filter(g=>!$n(g,c));d.length!==s[a].length&&i.push(a),d.length===0?delete s[a]:s[a]=d}Object.keys(s).length===0&&delete t.hooks}let r=JSON.stringify(t)!==n;return r&&ea(o,`${JSON.stringify(t,null,2)}
9
- `),{path:o,changed:r,events:i,guardInstalled:!1}}function xn(e=Nt()){if(!kn(e))return!1;try{return!!JSON.parse(vn(e,"utf-8"))?.hooks?.Stop?.some?.(t=>$n(t,xs))}catch{return!1}}var Sn=new Ml("monitor").description("Register external CLI sessions and report ended runs to the briefing"),ia=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Rt()}`;async function ra(e,o,t){let n=process.env.MESH_TOKEN,s=await fetch(e.replace(/\/$/,"")+"/monitor/"+o,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify(t),signal:AbortSignal.timeout(8e3)});if(!s.ok)throw new Error(`Monitor HTTP ${s.status}: ${(await s.text()).slice(0,300)}`)}Sn.command("register").requiredOption("--session <id>","Native session ID").requiredOption("--runtime <name>","claude, codex, gemini, opencode, or another CLI").requiredOption("--label <label>","Human-readable task label").option("--url <url>","Daemon URL",ia).action(async e=>{try{await ra(e.url,"register",or.parse({id:e.session,runtime:e.runtime,label:e.label})),console.log("Session registered. Report each stopped run with agentx monitor ended.")}catch(o){console.error(o.message),process.exitCode=1}});Sn.command("ended").requiredOption("--session <id>","Registered session ID").requiredOption("--run <id>","Stable unique turn ID; reuse this ID when retrying delivery").requiredOption("--transcript <file>","Local transcript file; only the last 90 KB is submitted").option("--url <url>","Daemon URL",ia).action(async e=>{try{let o=await Ul(e.transcript,"r"),t;try{let n=await o.stat();if(!n.isFile())throw new Error("Transcript must be a regular file");let s=Math.min(n.size,9e4),i=Buffer.alloc(s),{bytesRead:r}=await o.read(i,0,s,Math.max(0,n.size-s));t=(n.size>s?`[Transcript truncated: last 90 KB only]
10
- `:"")+i.subarray(0,r).toString("utf8")}finally{await o.close()}await ra(e.url,"ended",tr.parse({sessionId:e.session,runId:e.run,transcript:t})),console.log("Run queued for review.")}catch(o){console.error(o.message),process.exitCode=1}});import{Command as Wu}from"commander";import{Command as Fl}from"commander";we();import O from"chalk";import{existsSync as ql,readFileSync as Wl}from"fs";async function Bl(e){try{let{execFileSync:o}=await import("child_process"),t=o("ps",["-p",String(e),"-o","command="],{encoding:"utf-8",timeout:2e3}).trim();return t?/\bnode\b/.test(t)||/agentx|agentix|cli\.js/.test(t):!1}catch{return!0}}var Qe=new Fl().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");Qe.command("start").description("start the daemon (default if no subcommand)").option("-c, --config <path>","path to agentx.json").option("-d, --detach","run in background (detached)").option("--port <port>","override bind port").action(async e=>{if(e.detach){let{spawn:d}=await import("child_process"),{openSync:g,writeFileSync:l,existsSync:p}=await import("fs"),f=process.argv[1];(!f||!p(f))&&(console.error(O.red(` Cannot resolve agentx CLI entrypoint (process.argv[1]=${f||"?"}).`)),console.error(O.dim(" Try running without --detach to see the underlying error.")),process.exit(1));let u=[f,"daemon","start"];e.config&&u.push("-c",e.config),e.port&&u.push("--port",e.port);let w="/tmp/agentx-daemon.log",y;try{y=g(w,"a")}catch(b){console.error(O.red(` Failed to open ${w} for writing: ${b.message}`)),process.exit(1)}let $=d(process.execPath,u,{detached:!0,stdio:["ignore",y,y],cwd:process.cwd()});$.unref(),l("/tmp/agentx-daemon.pid",String($.pid)),console.log(O.green(`Daemon started in background (PID: ${$.pid})`)),console.log(O.dim(` Logs: tail -f ${w}`)),console.log(O.dim(" Stop: agentx daemon stop")),await new Promise(b=>setTimeout(b,1e3));try{process.kill($.pid,0)}catch{console.log(),console.log(O.yellow(` Daemon exited within 1s \u2014 check ${w} for the error:`)),console.log(O.dim(` tail -n 40 ${w}`))}return}let{readFileSync:o,writeFileSync:t,mkdirSync:n,existsSync:s}=await import("fs"),{resolve:i}=await import("path"),r=i(process.cwd(),".agentx");s(r)||n(r,{recursive:!0});let a=i(r,"daemon.pid");if(s(a)){let d=parseInt(o(a,"utf-8").trim(),10);if(d&&d!==process.pid){let g=!1;try{process.kill(d,0),g=!0}catch{}g&&await Bl(d)&&(console.error(`Another agentx daemon is already running (PID ${d}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{Jl(i(process.cwd(),".env"))}catch{}await new ws(e.config).start()});function Jl(e){if(!ql(e))return;let o=Wl(e,"utf-8");for(let t of o.split(`
11
- `)){let n=t.trim();if(!n||n.startsWith("#"))continue;let s=n.indexOf("=");if(s<0)continue;let i=n.slice(0,s).trim();if(!i||process.env[i]!==void 0)continue;let r=n.slice(s+1).trim();(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))&&(r=r.slice(1,-1)),process.env[i]=r}}Qe.command("stop").description("stop the running daemon").action(async()=>{let{readFileSync:e,existsSync:o,unlinkSync:t}=await import("fs"),{resolve:n}=await import("path"),s=[n(process.cwd(),".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"];for(let r of s)if(o(r))try{let a=parseInt(e(r,"utf-8").trim(),10);process.kill(a,"SIGTERM"),await new Promise(c=>setTimeout(c,2e3));try{t(r)}catch{}console.log(O.green(`Daemon stopped (PID: ${a})`));return}catch{try{t(r)}catch{}}let{execSync:i}=await import("child_process");try{i("pkill -f 'node dist/cli.js daemon'",{stdio:"ignore"}),console.log(O.green("Daemon stopped"))}catch{console.log(O.yellow("No daemon process found"))}});Qe.command("status").alias("st").description("show daemon status, agents, crons, and mesh").option("-c, --config <path>","path to agentx.json").option("--json","output as JSON").action(async e=>{try{let o=D(e.config),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}/health`,r=await(await fetch(s,{signal:AbortSignal.timeout(3e3)})).json();if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(O.bold(` ${r.node.name}`)+O.dim(` (${r.node.id})`)),console.log(O.green(" Status: running")+O.dim(` \u2014 uptime ${Hl(r.uptime)}`)),console.log(),console.log(O.bold(" Agents:"));for(let c of r.agents){let d=c.active>0?O.yellow(` [${c.active} active]`):"",g=c.errors>0?O.red(` (${c.errors} errors)`):"";console.log(` ${O.cyan(c.name)} ${O.dim(`(${c.tier})`)}${d}${g}`),console.log(O.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(O.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let d=c.enabled?O.green("\u25CF"):O.dim("\u25CB"),g=c.nextRun?O.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${d} ${c.id}${g}`)}}if(r.mesh?.length){console.log(),console.log(O.bold(" Mesh:"));for(let c of r.mesh){let d=c.healthy?O.green("\u25CF"):O.red("\u25CF"),g=c.skills?.length?O.dim(` (${c.skills.length} agents)`):"";console.log(` ${d} ${c.peer} ${O.dim(c.peerUrl)}${g}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError")console.log(O.red(" Daemon is not running")),console.log(O.dim(" Start with: agentx daemon start"));else try{let t=D(e.config),n=nn(t);if(console.log(),console.log(O.bold(` ${t.node.name}`)+O.dim(` (${t.node.id})`)),console.log(O.yellow(" Status: stopped")),console.log(O.dim(` ${Object.keys(t.agents).length} agents, ${Object.keys(t.crons).length} crons configured`)),n.length){console.log();for(let s of n)console.log(O.yellow(` \u26A0 ${s}`))}console.log()}catch(t){console.log(O.red(` ${t.message}`))}}});Qe.command("logs").description("tail daemon logs").option("-n, --lines <n>","number of lines","50").option("-f, --follow","follow log output",!1).action(async e=>{let{execSync:o,spawn:t}=await import("child_process"),n="/tmp/agentx-daemon.log",{existsSync:s}=await import("fs");if(!s(n)){console.log(O.yellow("No log file found at /tmp/agentx-daemon.log"));return}if(e.follow){let i=t("tail",["-f","-n",e.lines,n],{stdio:"inherit"});process.on("SIGINT",()=>{i.kill(),process.exit(0)})}else o(`tail -n ${e.lines} ${n}`,{stdio:"inherit"})});Qe.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(D(e.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(O.dim(` Connecting to ${n}...`)),console.log(O.dim(` Press Ctrl+C to stop
7
+ The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{Hl(r,{recursive:!0,force:!0})}});it.command("start").description("start the installed desktop assistant").action(()=>{En(),la(),console.log("Desktop assistant started.")});it.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{En(),await ca(),console.log("Desktop assistant stopped.")});it.command("status").description("show the desktop login service status").action(()=>{En();try{console.log(co("launchctl",["print",_t()],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(Ns(st())?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as nd}from"commander";import{open as sd}from"fs/promises";import{existsSync as Tn,mkdirSync as Ql,readFileSync as In,writeFileSync as da}from"fs";import{homedir as Zl}from"os";import{dirname as ed,resolve as Rs}from"path";var Ds="/attach/",ga="/guard/check";function ma(e,o,t=""){return`curl -s --max-time 3 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${o}${e}${t}`}' 2>/dev/null || true`}function An(e,o,t){let n={hooks:[{type:"command",command:ma(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function od(e){return{SessionStart:[An("/attach/session-start",e,"")],UserPromptSubmit:[An("/attach/prompt",e)],Stop:[An("/attach/stop",e)],SessionEnd:[An("/attach/session-end",e)]}}function td(e){let o=ma("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function On(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function Pt(){return Rs(Zl(),".claude/settings.json")}function Lt(e=process.cwd()){for(let o of[e,Rs(e,"..")]){let t=Rs(o,"agentx.json");if(Tn(t))try{let n=JSON.parse(In(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function pa(e,o={}){let t=o.path??Pt(),n=o.withGuard!==!1,s={};if(Tn(t))try{s=JSON.parse(In(t,"utf-8"))}catch(g){throw new Error(`${t} is not valid JSON (${g?.message}) \u2014 refusing to overwrite it`)}let i=JSON.stringify(s),r=s.hooks??={},a=[];for(let[g,l]of Object.entries(od(e))){let p=Array.isArray(r[g])?r[g].filter(f=>!On(f,Ds)):[];r[g]=[...p,...l],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(l=>!On(l,ga)):[];r.PreToolUse=[...g,...td(e)],c=!0}let d=JSON.stringify(s)!==i;return d&&(Ql(ed(t),{recursive:!0}),da(t,`${JSON.stringify(s,null,2)}
8
+ `)),{path:t,changed:d,events:a,guardInstalled:c}}function ua(e={}){let o=e.path??Pt();if(!Tn(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(In(o,"utf-8"))}catch(a){throw new Error(`${o} is not valid JSON (${a?.message}) \u2014 refusing to rewrite it`)}let n=JSON.stringify(t),s=t.hooks,i=[];if(s&&typeof s=="object"){for(let a of Object.keys(s)){if(!Array.isArray(s[a]))continue;let c=a==="PreToolUse"?ga:Ds;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let d=s[a].filter(g=>!On(g,c));d.length!==s[a].length&&i.push(a),d.length===0?delete s[a]:s[a]=d}Object.keys(s).length===0&&delete t.hooks}let r=JSON.stringify(t)!==n;return r&&da(o,`${JSON.stringify(t,null,2)}
9
+ `),{path:o,changed:r,events:i,guardInstalled:!1}}function jn(e=Pt()){if(!Tn(e))return!1;try{return!!JSON.parse(In(e,"utf-8"))?.hooks?.Stop?.some?.(t=>On(t,Ds))}catch{return!1}}var Cn=new nd("monitor").description("Register external CLI sessions and report ended runs to the briefing"),fa=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Lt()}`;async function ha(e,o,t){let n=process.env.MESH_TOKEN,s=await fetch(e.replace(/\/$/,"")+"/monitor/"+o,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify(t),signal:AbortSignal.timeout(8e3)});if(!s.ok)throw new Error(`Monitor HTTP ${s.status}: ${(await s.text()).slice(0,300)}`)}Cn.command("register").requiredOption("--session <id>","Native session ID").requiredOption("--runtime <name>","claude, codex, gemini, opencode, or another CLI").requiredOption("--label <label>","Human-readable task label").option("--url <url>","Daemon URL",fa).action(async e=>{try{await ha(e.url,"register",pr.parse({id:e.session,runtime:e.runtime,label:e.label})),console.log("Session registered. Report each stopped run with agentx monitor ended.")}catch(o){console.error(o.message),process.exitCode=1}});Cn.command("ended").requiredOption("--session <id>","Registered session ID").requiredOption("--run <id>","Stable unique turn ID; reuse this ID when retrying delivery").requiredOption("--transcript <file>","Local transcript file; only the last 90 KB is submitted").option("--url <url>","Daemon URL",fa).action(async e=>{try{let o=await sd(e.transcript,"r"),t;try{let n=await o.stat();if(!n.isFile())throw new Error("Transcript must be a regular file");let s=Math.min(n.size,9e4),i=Buffer.alloc(s),{bytesRead:r}=await o.read(i,0,s,Math.max(0,n.size-s));t=(n.size>s?`[Transcript truncated: last 90 KB only]
10
+ `:"")+i.subarray(0,r).toString("utf8")}finally{await o.close()}await ha(e.url,"ended",ur.parse({sessionId:e.session,runId:e.run,transcript:t})),console.log("Run queued for review.")}catch(o){console.error(o.message),process.exitCode=1}});import{Command as Of}from"commander";import{Command as id}from"commander";pe();import O from"chalk";import{existsSync as rd,readFileSync as ad}from"fs";async function cd(e){try{let{execFileSync:o}=await import("child_process"),t=o("ps",["-p",String(e),"-o","command="],{encoding:"utf-8",timeout:2e3}).trim();return t?/\bnode\b/.test(t)||/agentx|agentix|cli\.js/.test(t):!1}catch{return!0}}var Ze=new id().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");Ze.command("start").description("start the daemon (default if no subcommand)").option("-c, --config <path>","path to agentx.json").option("-d, --detach","run in background (detached)").option("--port <port>","override bind port").action(async e=>{if(e.detach){let{spawn:d}=await import("child_process"),{openSync:g,writeFileSync:l,existsSync:p}=await import("fs"),f=process.argv[1];(!f||!p(f))&&(console.error(O.red(` Cannot resolve agentx CLI entrypoint (process.argv[1]=${f||"?"}).`)),console.error(O.dim(" Try running without --detach to see the underlying error.")),process.exit(1));let u=[f,"daemon","start"];e.config&&u.push("-c",e.config),e.port&&u.push("--port",e.port);let w="/tmp/agentx-daemon.log",y;try{y=g(w,"a")}catch(b){console.error(O.red(` Failed to open ${w} for writing: ${b.message}`)),process.exit(1)}let k=d(process.execPath,u,{detached:!0,stdio:["ignore",y,y],cwd:process.cwd()});k.unref(),l("/tmp/agentx-daemon.pid",String(k.pid)),console.log(O.green(`Daemon started in background (PID: ${k.pid})`)),console.log(O.dim(` Logs: tail -f ${w}`)),console.log(O.dim(" Stop: agentx daemon stop")),await new Promise(b=>setTimeout(b,1e3));try{process.kill(k.pid,0)}catch{console.log(),console.log(O.yellow(` Daemon exited within 1s \u2014 check ${w} for the error:`)),console.log(O.dim(` tail -n 40 ${w}`))}return}let{readFileSync:o,writeFileSync:t,mkdirSync:n,existsSync:s}=await import("fs"),{resolve:i}=await import("path"),r=i(process.cwd(),".agentx");s(r)||n(r,{recursive:!0});let a=i(r,"daemon.pid");if(s(a)){let d=parseInt(o(a,"utf-8").trim(),10);if(d&&d!==process.pid){let g=!1;try{process.kill(d,0),g=!0}catch{}g&&await cd(d)&&(console.error(`Another agentx daemon is already running (PID ${d}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{ld(i(process.cwd(),".env"))}catch{}await new Is(e.config).start()});function ld(e){if(!rd(e))return;let o=ad(e,"utf-8");for(let t of o.split(`
11
+ `)){let n=t.trim();if(!n||n.startsWith("#"))continue;let s=n.indexOf("=");if(s<0)continue;let i=n.slice(0,s).trim();if(!i||process.env[i]!==void 0)continue;let r=n.slice(s+1).trim();(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))&&(r=r.slice(1,-1)),process.env[i]=r}}Ze.command("stop").description("stop the running daemon").action(async()=>{let{readFileSync:e,existsSync:o,unlinkSync:t}=await import("fs"),{resolve:n}=await import("path"),s=[n(process.cwd(),".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"];for(let r of s)if(o(r))try{let a=parseInt(e(r,"utf-8").trim(),10);process.kill(a,"SIGTERM"),await new Promise(c=>setTimeout(c,2e3));try{t(r)}catch{}console.log(O.green(`Daemon stopped (PID: ${a})`));return}catch{try{t(r)}catch{}}let{execSync:i}=await import("child_process");try{i("pkill -f 'node dist/cli.js daemon'",{stdio:"ignore"}),console.log(O.green("Daemon stopped"))}catch{console.log(O.yellow("No daemon process found"))}});Ze.command("status").alias("st").description("show daemon status, agents, crons, and mesh").option("-c, --config <path>","path to agentx.json").option("--json","output as JSON").action(async e=>{try{let o=_(e.config),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}/health`,r=await(await fetch(s,{signal:AbortSignal.timeout(3e3)})).json();if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(O.bold(` ${r.node.name}`)+O.dim(` (${r.node.id})`)),console.log(O.green(" Status: running")+O.dim(` \u2014 uptime ${dd(r.uptime)}`)),console.log(),console.log(O.bold(" Agents:"));for(let c of r.agents){let d=c.active>0?O.yellow(` [${c.active} active]`):"",g=c.errors>0?O.red(` (${c.errors} errors)`):"";console.log(` ${O.cyan(c.name)} ${O.dim(`(${c.tier})`)}${d}${g}`),console.log(O.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(O.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let d=c.enabled?O.green("\u25CF"):O.dim("\u25CB"),g=c.nextRun?O.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${d} ${c.id}${g}`)}}if(r.mesh?.length){console.log(),console.log(O.bold(" Mesh:"));for(let c of r.mesh){let d=c.healthy?O.green("\u25CF"):O.red("\u25CF"),g=c.skills?.length?O.dim(` (${c.skills.length} agents)`):"";console.log(` ${d} ${c.peer} ${O.dim(c.peerUrl)}${g}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError")console.log(O.red(" Daemon is not running")),console.log(O.dim(" Start with: agentx daemon start"));else try{let t=_(e.config),n=dn(t);if(console.log(),console.log(O.bold(` ${t.node.name}`)+O.dim(` (${t.node.id})`)),console.log(O.yellow(" Status: stopped")),console.log(O.dim(` ${Object.keys(t.agents).length} agents, ${Object.keys(t.crons).length} crons configured`)),n.length){console.log();for(let s of n)console.log(O.yellow(` \u26A0 ${s}`))}console.log()}catch(t){console.log(O.red(` ${t.message}`))}}});Ze.command("logs").description("tail daemon logs").option("-n, --lines <n>","number of lines","50").option("-f, --follow","follow log output",!1).action(async e=>{let{execSync:o,spawn:t}=await import("child_process"),n="/tmp/agentx-daemon.log",{existsSync:s}=await import("fs");if(!s(n)){console.log(O.yellow("No log file found at /tmp/agentx-daemon.log"));return}if(e.follow){let i=t("tail",["-f","-n",e.lines,n],{stdio:"inherit"});process.on("SIGINT",()=>{i.kill(),process.exit(0)})}else o(`tail -n ${e.lines} ${n}`,{stdio:"inherit"})});Ze.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(_(e.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(O.dim(` Connecting to ${n}...`)),console.log(O.dim(` Press Ctrl+C to stop
12
12
  `));try{let s=await fetch(n);if(!s.ok||!s.body){console.log(O.red(` Failed: ${s.status}`));return}let i=s.body.getReader(),r=new TextDecoder,a="";for(;;){let{done:c,value:d}=await i.read();if(c)break;a+=r.decode(d,{stream:!0});let g=a.split(`
13
- `);a=g.pop()||"";for(let l of g)if(l.startsWith("data: "))try{let p=JSON.parse(l.slice(6)),f=new Date(p.time).toLocaleTimeString(),u=p.message?.replace(/^\[agentx\]\s*/,"")||"";u.includes("executing")?console.log(`${O.dim(f)} ${O.cyan("\u25B6")} ${u}`):u.includes("completed")?console.log(`${O.dim(f)} ${O.green("\u2713")} ${u}`):u.includes("error")||u.includes("Error")?console.log(`${O.dim(f)} ${O.red("\u2717")} ${u}`):u.includes("Routing")?console.log(`${O.dim(f)} ${O.yellow("\u2192")} ${u}`):u.includes("mention")?console.log(`${O.dim(f)} ${O.magenta("@")} ${u}`):u.includes("Skipping")?console.log(`${O.dim(f)} ${O.dim("\u2298")} ${O.dim(u)}`):console.log(`${O.dim(f)} ${u}`)}catch{}else l.startsWith("event: status")}}catch(s){console.log(O.red(` Connection failed: ${s.message}`)),console.log(O.dim(" Is the daemon running? Diagnostic order:")),console.log(O.dim(" 1) agentx daemon status # is the daemon up?")),console.log(O.dim(" 2) tail -n 60 /tmp/agentx-daemon.log # detach-mode crash log")),console.log(O.dim(" 3) journalctl -u agentx -n 60 # systemd-managed installs")),console.log(O.dim(" If the log file is missing, the daemon never started \u2014 re-run without --detach")),console.log(O.dim(" to see the error in the foreground."))}});Qe.command("send <agent> <message...>").description("send a task to an agent via the daemon API").option("-c, --config <path>","path to agentx.json").option("--peer <peer>","send to a mesh peer's agent").option("--json","output raw JSON response").action(async(e,o,t)=>{let n=o.join(" ");try{let s=D(t.config),[i,r]=s.node.bind.split(":"),a=`http://${i||"127.0.0.1"}:${r}`,c,d;t.peer?(c=`${a}/mesh/task`,d={peer:t.peer,message:n,agent:e}):(c=`${a}/task`,d={agent:e,message:n}),console.log(O.dim(` Sending to ${t.peer?`${t.peer}/${e}`:e}...`));let l=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)})).json();t.json?console.log(JSON.stringify(l,null,2)):l.error?console.log(O.red(` Error: ${l.error}`)):(console.log(),console.log(l.content||l.response||"No response"),l.duration&&console.log(O.dim(`
14
- (${(l.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(O.red(` Failed: ${s.message}`)),console.log(O.dim(" Is the daemon running? Try: agentx daemon status"))}});Qe.command("deploy <host>").description("deploy agentx to a remote server via rsync").option("-i, --identity <key>","SSH identity file").option("-u, --user <user>","SSH user","root").option("-p, --path <path>","remote agentx path","~/agentx").option("--restart","restart remote daemon after deploy",!1).option("--skip-checks","skip build and test before deploy",!1).action(async(e,o)=>{let{execSync:t}=await import("child_process"),n=o.identity?`-e "ssh -i ${o.identity}"`:"",s=`${o.user}@${e}:${o.path}/dist/`;if(!o.skipChecks){try{console.log(O.dim(" Running tests...")),t("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(O.green(" \u2713 Tests passed"))}catch{console.log(O.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(O.dim(" Use --skip-checks to deploy anyway"));return}let{existsSync:i,statSync:r}=await import("fs"),{resolve:a}=await import("path"),c=a(process.cwd(),"dist/cli.js");if(!i(c)){console.log(O.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(c).mtimeMs>3e5&&(console.log(O.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),t("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(O.green(" \u2713 Build complete")))}console.log(O.dim(` Deploying to ${o.user}@${e}:${o.path}...`));try{if(t(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(O.green(" \u2713 Deploy complete")),o.restart){console.log(O.dim(" Restarting remote daemon..."));let i=o.identity?`ssh -i ${o.identity}`:"ssh";t(`${i} ${o.user}@${e} "pkill -f 'node dist/cli.js daemon' 2>/dev/null; sleep 2; cd ${o.path} && nohup node dist/cli.js daemon start > /tmp/agentx-daemon.log 2>&1 &"`,{stdio:"inherit"}),console.log(O.green(" Remote daemon restarted"))}}catch(i){console.log(O.red(` Deploy failed: ${i.message}`))}});Qe.action(async e=>{await new ws(e.config).start()});function Hl(e){return e<60?`${Math.round(e)}s`:e<3600?`${Math.round(e/60)}m`:e<86400?`${Math.round(e/3600)}h ${Math.round(e%3600/60)}m`:`${Math.round(e/86400)}d ${Math.round(e%86400/3600)}h`}import{Command as Gl}from"commander";import He from"chalk";import{existsSync as _t,readFileSync as zl,writeFileSync as aa,mkdirSync as ca}from"fs";import{hostname as la}from"os";import{resolve as tt}from"path";var da=new Gl().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=tt(o,"agentx.json"),n=tt(o,".env"),s=tt(o,".agentx/sessions");if(console.log(),console.log(He.bold(" agentx init")),console.log(),_t(t)&&!e.force){console.log(He.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[tt(o,"agentx.example.json"),tt(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(_t(c)){r=zl(c,"utf-8");break}r||(r=JSON.stringify({node:{id:la().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:la(),bind:"127.0.0.1:18800"},providers:{claude:{apiKey:"${ANTHROPIC_API_KEY}"}},agents:{assistant:{name:"Assistant",workspace:o,tier:"claude-code",model:"claude-sonnet-4-6",mentions:["@assistant","assistant"],maxConcurrent:2,systemPrompt:"You are a helpful assistant.",permissionMode:"default"}},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}}},null,2)),aa(t,r),console.log(He.green(" \u2713 Created agentx.json")),_t(n)||(aa(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
15
- `)),console.log(He.green(" \u2713 Created .env template"))),_t(s)||(ca(s,{recursive:!0}),console.log(He.green(" \u2713 Created .agentx/sessions/")));let a=tt(o,".claude");_t(a)||(ca(a,{recursive:!0}),console.log(He.green(" \u2713 Created .claude/"))),console.log(),console.log(He.bold(" Next steps:")),console.log(` 1. Edit ${He.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${He.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${He.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${He.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as Yl}from"commander";import No from"chalk";import{spawn as ma}from"child_process";import{existsSync as Vl}from"fs";import{dirname as Kl,resolve as Xl}from"path";import{fileURLToPath as Ql}from"url";we();var pa=new Yl().name("setup").description("open the web setup wizard to create or extend your AgentX install").option("--port <n>","dashboard port (default: from agentx.json, else 4202)").option("--no-open","don't try to open the browser").action(async e=>{let o=Fr(),t=e.port?parseInt(e.port,10):Zl(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(No.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(No.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(No.bold(` Opening ${n}`)),console.log(),await od(n).catch(()=>!1))console.log(No.dim(" Dashboard is already running.")),e.open!==!1&&ga(n);else{console.log(No.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=ed(),r=ma(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&ga(n),await new Promise(a=>r.on("exit",()=>a()))}});function Zl(){try{return D().dashboard.port||4202}catch{return 4202}}function ed(){let e=Xl(Kl(Ql(import.meta.url)),"cli.js");return Vl(e)?e:process.argv[1]||e}async function od(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}function ga(e){let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=ma(o,[e],{stdio:"ignore",detached:!0});t.once("error",()=>{console.log(No.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),t.unref()}catch{console.log(No.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as td}from"commander";import xe from"chalk";var Dt=new td().name("token").description("scoped API tokens for external access (mesh peers, integrations)");Dt.command("create").description("mint a new token \u2014 prints the secret once, store it somewhere safe").requiredOption("--name <name>","human-readable label (e.g. 'Slack integration')").option("--scope <scopes>","comma-separated scopes (default: dashboard:read)","dashboard:read").option("--expires <days>","expire after N days (default: no expiry)").action(e=>{try{let o=new fn,t=String(e.scope).split(",").map(r=>r.trim()).filter(Boolean),n=e.expires?parseInt(e.expires,10):void 0;if(e.expires&&(!n||n<1))throw new Error("--expires must be a positive integer (days)");let{token:s,record:i}=o.create({name:e.name,scopes:t,expiresInDays:n});console.log(),console.log(xe.bold(" Token created.")),console.log(),console.log(` id: ${xe.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||xe.dim("never")}`),console.log(),console.log(xe.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${xe.green.bold(s)}`),console.log(),console.log(xe.dim(" Use it via the Authorization header:")),console.log(xe.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});Dt.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new fn().list();if(e.length===0){console.log(xe.dim(`
13
+ `);a=g.pop()||"";for(let l of g)if(l.startsWith("data: "))try{let p=JSON.parse(l.slice(6)),f=new Date(p.time).toLocaleTimeString(),u=p.message?.replace(/^\[agentx\]\s*/,"")||"";u.includes("executing")?console.log(`${O.dim(f)} ${O.cyan("\u25B6")} ${u}`):u.includes("completed")?console.log(`${O.dim(f)} ${O.green("\u2713")} ${u}`):u.includes("error")||u.includes("Error")?console.log(`${O.dim(f)} ${O.red("\u2717")} ${u}`):u.includes("Routing")?console.log(`${O.dim(f)} ${O.yellow("\u2192")} ${u}`):u.includes("mention")?console.log(`${O.dim(f)} ${O.magenta("@")} ${u}`):u.includes("Skipping")?console.log(`${O.dim(f)} ${O.dim("\u2298")} ${O.dim(u)}`):console.log(`${O.dim(f)} ${u}`)}catch{}else l.startsWith("event: status")}}catch(s){console.log(O.red(` Connection failed: ${s.message}`)),console.log(O.dim(" Is the daemon running? Diagnostic order:")),console.log(O.dim(" 1) agentx daemon status # is the daemon up?")),console.log(O.dim(" 2) tail -n 60 /tmp/agentx-daemon.log # detach-mode crash log")),console.log(O.dim(" 3) journalctl -u agentx -n 60 # systemd-managed installs")),console.log(O.dim(" If the log file is missing, the daemon never started \u2014 re-run without --detach")),console.log(O.dim(" to see the error in the foreground."))}});Ze.command("send <agent> <message...>").description("send a task to an agent via the daemon API").option("-c, --config <path>","path to agentx.json").option("--peer <peer>","send to a mesh peer's agent").option("--json","output raw JSON response").action(async(e,o,t)=>{let n=o.join(" ");try{let s=_(t.config),[i,r]=s.node.bind.split(":"),a=`http://${i||"127.0.0.1"}:${r}`,c,d;t.peer?(c=`${a}/mesh/task`,d={peer:t.peer,message:n,agent:e}):(c=`${a}/task`,d={agent:e,message:n}),console.log(O.dim(` Sending to ${t.peer?`${t.peer}/${e}`:e}...`));let l=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)})).json();t.json?console.log(JSON.stringify(l,null,2)):l.error?console.log(O.red(` Error: ${l.error}`)):(console.log(),console.log(l.content||l.response||"No response"),l.duration&&console.log(O.dim(`
14
+ (${(l.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(O.red(` Failed: ${s.message}`)),console.log(O.dim(" Is the daemon running? Try: agentx daemon status"))}});Ze.command("deploy <host>").description("deploy agentx to a remote server via rsync").option("-i, --identity <key>","SSH identity file").option("-u, --user <user>","SSH user","root").option("-p, --path <path>","remote agentx path","~/agentx").option("--restart","restart remote daemon after deploy",!1).option("--skip-checks","skip build and test before deploy",!1).action(async(e,o)=>{let{execSync:t}=await import("child_process"),n=o.identity?`-e "ssh -i ${o.identity}"`:"",s=`${o.user}@${e}:${o.path}/dist/`;if(!o.skipChecks){try{console.log(O.dim(" Running tests...")),t("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(O.green(" \u2713 Tests passed"))}catch{console.log(O.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(O.dim(" Use --skip-checks to deploy anyway"));return}let{existsSync:i,statSync:r}=await import("fs"),{resolve:a}=await import("path"),c=a(process.cwd(),"dist/cli.js");if(!i(c)){console.log(O.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(c).mtimeMs>3e5&&(console.log(O.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),t("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(O.green(" \u2713 Build complete")))}console.log(O.dim(` Deploying to ${o.user}@${e}:${o.path}...`));try{if(t(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(O.green(" \u2713 Deploy complete")),o.restart){console.log(O.dim(" Restarting remote daemon..."));let i=o.identity?`ssh -i ${o.identity}`:"ssh";t(`${i} ${o.user}@${e} "pkill -f 'node dist/cli.js daemon' 2>/dev/null; sleep 2; cd ${o.path} && nohup node dist/cli.js daemon start > /tmp/agentx-daemon.log 2>&1 &"`,{stdio:"inherit"}),console.log(O.green(" Remote daemon restarted"))}}catch(i){console.log(O.red(` Deploy failed: ${i.message}`))}});Ze.action(async e=>{await new Is(e.config).start()});function dd(e){return e<60?`${Math.round(e)}s`:e<3600?`${Math.round(e/60)}m`:e<86400?`${Math.round(e/3600)}h ${Math.round(e%3600/60)}m`:`${Math.round(e/86400)}d ${Math.round(e%86400/3600)}h`}import{Command as gd}from"commander";import He from"chalk";import{existsSync as Mt,readFileSync as md,writeFileSync as ya,mkdirSync as wa}from"fs";import{hostname as ba}from"os";import{resolve as rt}from"path";var $a=new gd().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=rt(o,"agentx.json"),n=rt(o,".env"),s=rt(o,".agentx/sessions");if(console.log(),console.log(He.bold(" agentx init")),console.log(),Mt(t)&&!e.force){console.log(He.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[rt(o,"agentx.example.json"),rt(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(Mt(c)){r=md(c,"utf-8");break}r||(r=JSON.stringify({node:{id:ba().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:ba(),bind:"127.0.0.1:18800"},providers:{claude:{apiKey:"${ANTHROPIC_API_KEY}"}},agents:{assistant:{name:"Assistant",workspace:o,tier:"claude-code",model:"claude-sonnet-4-6",mentions:["@assistant","assistant"],maxConcurrent:2,systemPrompt:"You are a helpful assistant.",permissionMode:"default"}},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}}},null,2)),ya(t,r),console.log(He.green(" \u2713 Created agentx.json")),Mt(n)||(ya(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
15
+ `)),console.log(He.green(" \u2713 Created .env template"))),Mt(s)||(wa(s,{recursive:!0}),console.log(He.green(" \u2713 Created .agentx/sessions/")));let a=rt(o,".claude");Mt(a)||(wa(a,{recursive:!0}),console.log(He.green(" \u2713 Created .claude/"))),console.log(),console.log(He.bold(" Next steps:")),console.log(` 1. Edit ${He.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${He.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${He.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${He.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as pd}from"commander";import Do from"chalk";import{spawn as va}from"child_process";import{existsSync as ud}from"fs";import{dirname as fd,resolve as hd}from"path";import{fileURLToPath as yd}from"url";pe();var xa=new pd().name("setup").description("open the web setup wizard to create or extend your AgentX install").option("--port <n>","dashboard port (default: from agentx.json, else 4202)").option("--no-open","don't try to open the browser").action(async e=>{let o=Kr(),t=e.port?parseInt(e.port,10):wd(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(Do.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(Do.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(Do.bold(` Opening ${n}`)),console.log(),await $d(n).catch(()=>!1))console.log(Do.dim(" Dashboard is already running.")),e.open!==!1&&ka(n);else{console.log(Do.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=bd(),r=va(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&ka(n),await new Promise(a=>r.on("exit",()=>a()))}});function wd(){try{return _().dashboard.port||4202}catch{return 4202}}function bd(){let e=hd(fd(yd(import.meta.url)),"cli.js");return ud(e)?e:process.argv[1]||e}async function $d(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}function ka(e){let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=va(o,[e],{stdio:"ignore",detached:!0});t.once("error",()=>{console.log(Do.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),t.unref()}catch{console.log(Do.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as kd}from"commander";import Se from"chalk";var Ft=new kd().name("token").description("scoped API tokens for external access (mesh peers, integrations)");Ft.command("create").description("mint a new token \u2014 prints the secret once, store it somewhere safe").requiredOption("--name <name>","human-readable label (e.g. 'Slack integration')").option("--scope <scopes>","comma-separated scopes (default: dashboard:read)","dashboard:read").option("--expires <days>","expire after N days (default: no expiry)").action(e=>{try{let o=new vn,t=String(e.scope).split(",").map(r=>r.trim()).filter(Boolean),n=e.expires?parseInt(e.expires,10):void 0;if(e.expires&&(!n||n<1))throw new Error("--expires must be a positive integer (days)");let{token:s,record:i}=o.create({name:e.name,scopes:t,expiresInDays:n});console.log(),console.log(Se.bold(" Token created.")),console.log(),console.log(` id: ${Se.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||Se.dim("never")}`),console.log(),console.log(Se.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${Se.green.bold(s)}`),console.log(),console.log(Se.dim(" Use it via the Authorization header:")),console.log(Se.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(o){console.log(Se.red(` ${o.message}`)),process.exit(1)}});Ft.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new vn().list();if(e.length===0){console.log(Se.dim(`
16
16
  No tokens issued.
17
- `));return}console.log();for(let o of e){let t=o.revokedAt?xe.red("revoked"):o.expiresAt&&Date.parse(o.expiresAt)<Date.now()?xe.red("expired"):xe.green("active");console.log(` ${xe.cyan(o.id)} ${t} ${o.name}`),console.log(xe.dim(` prefix: ${o.prefix}\u2026 scopes: ${o.scopes.join(", ")}`)),console.log(xe.dim(` created: ${o.createdAt}${o.expiresAt?` expires: ${o.expiresAt}`:""}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(xe.red(` ${e.message}`)),process.exit(1)}});Dt.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new fn().revoke(e);o||(console.log(xe.red(` Token ${e} not found.`)),process.exit(1)),console.log(xe.green(`
17
+ `));return}console.log();for(let o of e){let t=o.revokedAt?Se.red("revoked"):o.expiresAt&&Date.parse(o.expiresAt)<Date.now()?Se.red("expired"):Se.green("active");console.log(` ${Se.cyan(o.id)} ${t} ${o.name}`),console.log(Se.dim(` prefix: ${o.prefix}\u2026 scopes: ${o.scopes.join(", ")}`)),console.log(Se.dim(` created: ${o.createdAt}${o.expiresAt?` expires: ${o.expiresAt}`:""}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(Se.red(` ${e.message}`)),process.exit(1)}});Ft.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new vn().revoke(e);o||(console.log(Se.red(` Token ${e} not found.`)),process.exit(1)),console.log(Se.green(`
18
18
  \u2713 Revoked ${e} (${o.name})
19
- `))}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});we();import{Command as eo}from"commander";import h from"chalk";import je from"prompts";import{readFileSync as ho,writeFileSync as nt,existsSync as ge,mkdirSync as Ze,cpSync as Ss,readdirSync as As}from"fs";import{resolve as J,join as fo,dirname as nd}from"path";import{fileURLToPath as sd}from"url";function ne(){let e=J(process.cwd(),"agentx.json");if(!ge(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(ho(e,"utf-8"))}function De(e){return de(o=>{for(let t of Object.keys(o))delete o[t];Object.assign(o,e)}).then(o=>{if(!o.success){console.error(h.red(` Config save failed: ${o.error}`));return}o.reloaded?console.error(h.dim(" (daemon hot-reloaded)")):o.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(o.reloadSkipped)&&console.error(h.dim(` (daemon reload skipped: ${o.reloadSkipped})`))})}var Ro=new eo().name("agent").description("manage agents \u2014 add, list, remove");Ro.command("list").alias("ls").description("list configured agents").action(()=>{let e=ne();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=t.mentions?.join(", ")||"";console.log(` ${h.cyan(o)} \u2014 ${t.name} (${t.tier})`),console.log(h.dim(` workspace: ${t.workspace}`)),n&&console.log(h.dim(` mentions: ${n}`))}console.log()});Ro.command("add").description("add a new agent interactively").action(async()=>{let e=ne(),o=await je([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:d=>/^[a-z0-9-]+$/.test(d)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:J(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!o.id)return;let t=o.workspace.endsWith(o.id)?o.workspace:fo(o.workspace,o.id);Ze(J(t,".claude/skills"),{recursive:!0});let n={name:o.name,workspace:t,tier:o.tier,model:o.model,mentions:o.mentions?.map(d=>d.trim()).filter(Boolean)||[],maxConcurrent:o.maxConcurrent,systemPrompt:o.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-G6KGWPHY.js"),i=s(o.id,n,"19900",(...d)=>{console.log(h.dim(` ${d.join(" ")}`))}),r=J(process.cwd(),"src/wiki/SKILL.md"),a=J(nd(sd(import.meta.url)),"../wiki/SKILL.md"),c=ge(r)?r:a;ge(c)&&(Ze(J(t,".claude/skills/wiki"),{recursive:!0}),Ss(c,J(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await De(e),console.log(h.green(`
20
- Agent "${o.id}" added`)),console.log(h.dim(` Workspace: ${t}`)),console.log(h.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});Ro.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=ne();if(!o.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete o.agents[e],await De(o),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});Ro.command("capability <id>").alias("caps").description("set agent capability flags (intents, maxDelegationDepth, contextReferences, contextStrategy)").option("--intents <csv>","comma-separated intent allow-list (set to '-' to clear)").option("--max-delegation-depth <n>","max distinct upstream agents on the same subject before refusal (0 disables)").option("--context-references <bool>","render the deterministic [Verified References] block (true|false)").option("--context-strategy <name>","per-agent override: layered | planner").option("--max-execution-minutes <n>","wall-clock cap on a single Claude Code call (1\u2013240)").option("--show","just print the current capability fields").action(async(e,o)=>{let t=ne(),n=t.agents?.[e];if(n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1)),o.show){console.log(),console.log(h.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):h.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":h.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||h.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(o.intents!==void 0&&(o.intents==="-"||o.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(o.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),o.maxDelegationDepth!==void 0){let i=parseInt(o.maxDelegationDepth,10);(!Number.isFinite(i)||i<0||i>50)&&(console.log(h.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=i,s.push(`maxDelegationDepth=${i}`)}if(o.contextReferences!==void 0){let i=String(o.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(i)||(console.log(h.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=i==="true"||i==="on"||i==="1",s.push(`contextReferences=${n.contextReferences}`)}if(o.contextStrategy!==void 0&&(o.contextStrategy==="-"||o.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(o.contextStrategy)?(n.contextStrategy=o.contextStrategy,s.push(`contextStrategy=${o.contextStrategy}`)):(console.log(h.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),o.maxExecutionMinutes!==void 0){let i=parseInt(o.maxExecutionMinutes,10);(!Number.isFinite(i)||i<1||i>240)&&(console.log(h.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(h.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await De(t),console.log(h.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(h.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var Pt=new eo().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");Pt.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=ne().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(o.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(h.dim(`
19
+ `))}catch(o){console.log(Se.red(` ${o.message}`)),process.exit(1)}});pe();import{Command as oo}from"commander";import h from"chalk";import Te from"prompts";import{readFileSync as wo,writeFileSync as at,existsSync as ge,mkdirSync as eo,cpSync as _s,readdirSync as Ls}from"fs";import{resolve as J,join as yo,dirname as vd}from"path";import{fileURLToPath as xd}from"url";function ne(){let e=J(process.cwd(),"agentx.json");if(!ge(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(wo(e,"utf-8"))}function _e(e){return de(o=>{for(let t of Object.keys(o))delete o[t];Object.assign(o,e)}).then(o=>{if(!o.success){console.error(h.red(` Config save failed: ${o.error}`));return}o.reloaded?console.error(h.dim(" (daemon hot-reloaded)")):o.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(o.reloadSkipped)&&console.error(h.dim(` (daemon reload skipped: ${o.reloadSkipped})`))})}var _o=new oo().name("agent").description("manage agents \u2014 add, list, remove");_o.command("list").alias("ls").description("list configured agents").action(()=>{let e=ne();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=t.mentions?.join(", ")||"";console.log(` ${h.cyan(o)} \u2014 ${t.name} (${t.tier})`),console.log(h.dim(` workspace: ${t.workspace}`)),n&&console.log(h.dim(` mentions: ${n}`))}console.log()});_o.command("add").description("add a new agent interactively").action(async()=>{let e=ne(),o=await Te([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:d=>/^[a-z0-9-]+$/.test(d)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:J(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!o.id)return;let t=o.workspace.endsWith(o.id)?o.workspace:yo(o.workspace,o.id);eo(J(t,".claude/skills"),{recursive:!0});let n={name:o.name,workspace:t,tier:o.tier,model:o.model,mentions:o.mentions?.map(d=>d.trim()).filter(Boolean)||[],maxConcurrent:o.maxConcurrent,systemPrompt:o.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-G6KGWPHY.js"),i=s(o.id,n,"19900",(...d)=>{console.log(h.dim(` ${d.join(" ")}`))}),r=J(process.cwd(),"src/wiki/SKILL.md"),a=J(vd(xd(import.meta.url)),"../wiki/SKILL.md"),c=ge(r)?r:a;ge(c)&&(eo(J(t,".claude/skills/wiki"),{recursive:!0}),_s(c,J(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await _e(e),console.log(h.green(`
20
+ Agent "${o.id}" added`)),console.log(h.dim(` Workspace: ${t}`)),console.log(h.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});_o.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=ne();if(!o.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete o.agents[e],await _e(o),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});_o.command("capability <id>").alias("caps").description("set agent capability flags (intents, maxDelegationDepth, contextReferences, contextStrategy)").option("--intents <csv>","comma-separated intent allow-list (set to '-' to clear)").option("--max-delegation-depth <n>","max distinct upstream agents on the same subject before refusal (0 disables)").option("--context-references <bool>","render the deterministic [Verified References] block (true|false)").option("--context-strategy <name>","per-agent override: layered | planner").option("--max-execution-minutes <n>","wall-clock cap on a single Claude Code call (1\u2013240)").option("--show","just print the current capability fields").action(async(e,o)=>{let t=ne(),n=t.agents?.[e];if(n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1)),o.show){console.log(),console.log(h.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):h.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":h.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||h.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(o.intents!==void 0&&(o.intents==="-"||o.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(o.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),o.maxDelegationDepth!==void 0){let i=parseInt(o.maxDelegationDepth,10);(!Number.isFinite(i)||i<0||i>50)&&(console.log(h.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=i,s.push(`maxDelegationDepth=${i}`)}if(o.contextReferences!==void 0){let i=String(o.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(i)||(console.log(h.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=i==="true"||i==="on"||i==="1",s.push(`contextReferences=${n.contextReferences}`)}if(o.contextStrategy!==void 0&&(o.contextStrategy==="-"||o.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(o.contextStrategy)?(n.contextStrategy=o.contextStrategy,s.push(`contextStrategy=${o.contextStrategy}`)):(console.log(h.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),o.maxExecutionMinutes!==void 0){let i=parseInt(o.maxExecutionMinutes,10);(!Number.isFinite(i)||i<1||i>240)&&(console.log(h.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(h.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await _e(t),console.log(h.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(h.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var Ut=new oo().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");Ut.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=ne().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(o.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(h.dim(`
21
21
  ${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
22
- `));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,l]of Object.entries(c))typeof l=="string"&&/^[A-Z][A-Z0-9_]*$/.test(l)?a.push(process.env[l]?h.green(`${g}:${l}=set`):h.yellow(`${g}:${l}=UNSET`)):g==="auth"&&l==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof l=="string"&&a.push(h.dim(`sessionDir:${l}`));let d=Object.entries(i.metadata??{}).map(([g,l])=>`${g}=${l}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),d&&console.log(` ${h.dim(d)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});Pt.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=ne();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-SRTXHGSK.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await je({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await je({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),d=String(o.sessionDir||"").trim();if(!a&&!c&&!d&&n){let p=await je({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});p.scheme==="tokenEnv"?a=((await je({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():p.scheme==="keyring"?c="keyring":p.scheme==="sessionDir"&&(d=((await je({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let p of String(o.metadata).split(",")){let[f,...u]=p.split("=");f&&(g[f.trim()]=u.join("=").trim())}else if(n){let p=await je({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(p.metadata)for(let f of String(p.metadata).split(",")){let[u,...w]=f.split("=");u&&(g[u.trim()]=w.join("=").trim())}}let l={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),l.tokenEnv=a),c==="keyring"&&(l.auth="keyring"),d&&(l.sessionDir=d),Object.keys(l).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(p=>p.kind===i&&p.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:l,metadata:g,enabled:!0}),await De(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Pt.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=ne(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(d=>d.kind===i&&(!r||d.label===r)||d.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await De(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Pt.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=ne().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},d=[];for(let[g,l]of Object.entries(c))typeof l=="string"&&/^[A-Z][A-Z0-9_]*$/.test(l)&&!process.env[l]&&d.push(`${g}: env var ${l} is unset`);if(d.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of d)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});Ro.addCommand(Pt);var En=new eo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");En.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ne();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});En.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ne(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await je({type:"select",name:"channelType",message:"Channel type",choices:[{title:"Telegram \u2014 bot via BotFather token",value:"telegram"},{title:"WhatsApp \u2014 link via QR code (self-chat or contacts)",value:"whatsapp"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await je([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await De(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await je([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:t},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let i=[],r=s.addRoute;for(;r;){let a=await je([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await De(e),Ze(J(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await je([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let i=[],r=s.addRoute;for(;r;){let a=await je([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await De(e),console.log(h.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(h.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(h.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(h.dim(` Secret token: ${s.webhookSecret}`)),console.log(h.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(h.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var st=new eo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");st.command("list").alias("ls").description("list cron jobs").action(()=>{let e=ne();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});st.command("add").description("add a cron job").action(async()=>{let e=ne(),o=Object.keys(e.agents||{}),t=await je([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:o.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!t.id||!t.schedule||(e.crons=e.crons||{},e.crons[t.id]={enabled:t.enabled,schedule:t.schedule,timezone:t.timezone,agent:t.agent,prompt:t.prompt,timeout:t.timeout,onError:["log"]},await De(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});st.command("enable <id>").description("enable a cron job").action(async e=>{let o=ne();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!0,await De(o),console.log(h.green(` Cron "${e}" enabled`))});st.command("disable <id>").description("disable a cron job").action(async e=>{let o=ne();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await De(o),console.log(h.green(` Cron "${e}" disabled`))});var it=new eo().name("mesh").description("manage mesh peers \u2014 add, list, remove");it.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=ne();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});it.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=ne(),o=await je([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(h.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:o.url,name:o.name,...o.token?{token:o.token}:{}}),await De(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});it.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=ne();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await De(o),console.log(h.green(` Peer "${e}" removed`)))});it.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let o=ne();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await De(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});var _o=new eo().name("skill").description("manage skills \u2014 add to agent(s), list");_o.command("add <skillPath>").description("add a skill to agent(s)").option("-a, --agent <agents...>","target agent ID(s)").option("--all","add to all agents").action(async(e,o)=>{let t=ne(),n=J(e);if(!ge(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=ge(fo(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(o.all)i=Object.keys(t.agents||{});else if(o.agent)i=o.agent;else{let r=Object.keys(t.agents||{});i=(await je({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=J(a.workspace,".claude/skills",s);Ze(c,{recursive:!0}),ge(fo(n,"SKILL.md"))?Ss(n,c,{recursive:!0}):n.endsWith(".md")&&Ss(n,fo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});_o.command("list").alias("ls").description("list skills per agent").action(()=>{let e=ne();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=J(t.workspace,".claude/skills"),s=ge(n)?As(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});_o.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[J(n,"src",e,"SKILL.md"),J(n,"skills",e,"SKILL.md")],i=s.find($=>ge($));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let $ of s)console.log(h.dim(` ${$}`));return}let r=ho(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),d;try{d=D()}catch($){console.log(h.red(` Can't load agentx.json: ${$.message}`));return}let g=Object.entries(d.agents||{}),l=o.agent?g.filter(([$])=>$===o.agent):g;if(l.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let p=0,f=0,u=0,w=0;for(let[$,b]of l){let v=b.workspace;if(!v||!ge(v)){console.log(` ${h.yellow("\u2717")} ${$.padEnd(22)} ${h.dim("(workspace missing: "+(v||"undefined")+")")}`),w++;continue}let A=J(v,".claude/skills",e),x=J(A,"SKILL.md");if(!ge(x)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${$.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}o.dryRun||(Ze(A,{recursive:!0}),nt(x,r)),console.log(` ${h.green("+")} ${$.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),p++;continue}let E=ho(x,"utf-8");if(t("sha256").update(E).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${$.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),u++;continue}let N=(E.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||nt(x,r),console.log(` ${h.yellow("\u21BB")} ${$.padEnd(22)} ${h.dim(`v${N} \u2192 v${c}`)}`),f++}console.log();let y=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${y} seed ${p}, ${y} update ${f}, ${u} already current, ${w} skipped.`)),o.dryRun&&(p>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});_o.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:o}=await import("./loader-BOKE5M5S.js"),{auditAll:t}=await import("./audit-4245CX6P.js"),{loadReferences:n}=await import("./loader-4ZGTK7LD.js"),{loadRecipes:s}=await import("./recipes-7S4MC5OJ.js"),i=[];if(e.workspace){let f=ne().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(J(f.workspace))}else if(e.allWorkspaces){let p=ne();for(let f of Object.values(p.agents||{}))f?.workspace&&i.push(J(f.workspace))}else i.push(J(e.cwd));let r=J(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(p=>o(p)))).flat(),[d,g]=await Promise.all([n(r),s(r)]),l=t({skills:c,references:d,recipes:g});if(e.json)console.log(JSON.stringify(l.map(p=>({name:p.name,verdict:p.verdict,reasons:p.reasons,path:p.skill?.path})),null,2));else{let p={PASS:0,REVIEW:0,FAILING:0};for(let f of l)p[f.verdict]++;console.log();for(let f of l){let u=f.verdict==="PASS"?h.green("PASS "):f.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${u} ${h.bold(f.name)}${f.skill?.path?h.dim(` (${f.skill.path})`):""}`);for(let w of f.reasons)console.log(` ${h.dim("\xB7")} ${w}`)}console.log(),console.log(` ${h.green(`${p.PASS} PASS`)} ${h.yellow(`${p.REVIEW} REVIEW`)} ${h.red(`${p.FAILING} FAILING`)}`),console.log()}process.exit(l.some(p=>p.verdict==="FAILING")?1:0)});_o.command("suggest").description("rank an agent's skills against a task (suggests, never loads)").argument("<task>","the task, in the words it arrived in").option("--agent <id>","whose skills to rank").option("--min <p>","minimum P(any skill applies)","0.6").option("--json","emit the ranking as JSON").action(async(e,o)=>{let t=ne(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-BOKE5M5S.js"),{pickSkillForTask:a}=await import("./select-L4VIYSFJ.js"),c=await r(i.workspace);if(c.length===0){console.log(h.yellow(` ${s} has no skills`));return}let d=await a(c,e,{agent:s,minRelevant:Number(o.min)||.6});if(o.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:d.skill?.frontmatter.name??null,anyRelevant:d.anyRelevant,confidence:d.confidence,judged:d.judged,reason:d.reason,shortlist:d.shortlist},null,2));return}if(console.log(),d.skill?(console.log(` ${h.green("\u2192")} ${h.bold(d.skill.frontmatter.name)} ${h.dim(`\xB7 ${d.reason}`)}`),console.log(` ${h.dim(d.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${h.yellow("\xB7")} no skill for this ${h.dim(`\u2014 ${d.reason}`)}`),d.shortlist.length>1){console.log(h.dim(`
22
+ `));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,l]of Object.entries(c))typeof l=="string"&&/^[A-Z][A-Z0-9_]*$/.test(l)?a.push(process.env[l]?h.green(`${g}:${l}=set`):h.yellow(`${g}:${l}=UNSET`)):g==="auth"&&l==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof l=="string"&&a.push(h.dim(`sessionDir:${l}`));let d=Object.entries(i.metadata??{}).map(([g,l])=>`${g}=${l}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),d&&console.log(` ${h.dim(d)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});Ut.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=ne();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-SRTXHGSK.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Te({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Te({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),d=String(o.sessionDir||"").trim();if(!a&&!c&&!d&&n){let p=await Te({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});p.scheme==="tokenEnv"?a=((await Te({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():p.scheme==="keyring"?c="keyring":p.scheme==="sessionDir"&&(d=((await Te({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let p of String(o.metadata).split(",")){let[f,...u]=p.split("=");f&&(g[f.trim()]=u.join("=").trim())}else if(n){let p=await Te({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(p.metadata)for(let f of String(p.metadata).split(",")){let[u,...w]=f.split("=");u&&(g[u.trim()]=w.join("=").trim())}}let l={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),l.tokenEnv=a),c==="keyring"&&(l.auth="keyring"),d&&(l.sessionDir=d),Object.keys(l).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(p=>p.kind===i&&p.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:l,metadata:g,enabled:!0}),await _e(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Ut.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=ne(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(d=>d.kind===i&&(!r||d.label===r)||d.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await _e(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Ut.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=ne().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},d=[];for(let[g,l]of Object.entries(c))typeof l=="string"&&/^[A-Z][A-Z0-9_]*$/.test(l)&&!process.env[l]&&d.push(`${g}: env var ${l} is unset`);if(d.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of d)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});_o.addCommand(Ut);var Nn=new oo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Nn.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ne();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});Nn.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ne(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Te({type:"select",name:"channelType",message:"Channel type",choices:[{title:"Telegram \u2014 bot via BotFather token",value:"telegram"},{title:"WhatsApp \u2014 link via QR code (self-chat or contacts)",value:"whatsapp"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await Te([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await _e(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Te([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:t},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let i=[],r=s.addRoute;for(;r;){let a=await Te([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await _e(e),eo(J(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Te([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let i=[],r=s.addRoute;for(;r;){let a=await Te([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await _e(e),console.log(h.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(h.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(h.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(h.dim(` Secret token: ${s.webhookSecret}`)),console.log(h.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(h.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var ct=new oo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");ct.command("list").alias("ls").description("list cron jobs").action(()=>{let e=ne();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});ct.command("add").description("add a cron job").action(async()=>{let e=ne(),o=Object.keys(e.agents||{}),t=await Te([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:o.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!t.id||!t.schedule||(e.crons=e.crons||{},e.crons[t.id]={enabled:t.enabled,schedule:t.schedule,timezone:t.timezone,agent:t.agent,prompt:t.prompt,timeout:t.timeout,onError:["log"]},await _e(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});ct.command("enable <id>").description("enable a cron job").action(async e=>{let o=ne();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!0,await _e(o),console.log(h.green(` Cron "${e}" enabled`))});ct.command("disable <id>").description("disable a cron job").action(async e=>{let o=ne();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await _e(o),console.log(h.green(` Cron "${e}" disabled`))});var lt=new oo().name("mesh").description("manage mesh peers \u2014 add, list, remove");lt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=ne();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});lt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=ne(),o=await Te([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(h.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:o.url,name:o.name,...o.token?{token:o.token}:{}}),await _e(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});lt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=ne();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await _e(o),console.log(h.green(` Peer "${e}" removed`)))});lt.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let o=ne();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await _e(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});var Po=new oo().name("skill").description("manage skills \u2014 add to agent(s), list");Po.command("add <skillPath>").description("add a skill to agent(s)").option("-a, --agent <agents...>","target agent ID(s)").option("--all","add to all agents").action(async(e,o)=>{let t=ne(),n=J(e);if(!ge(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=ge(yo(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(o.all)i=Object.keys(t.agents||{});else if(o.agent)i=o.agent;else{let r=Object.keys(t.agents||{});i=(await Te({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=J(a.workspace,".claude/skills",s);eo(c,{recursive:!0}),ge(yo(n,"SKILL.md"))?_s(n,c,{recursive:!0}):n.endsWith(".md")&&_s(n,yo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Po.command("list").alias("ls").description("list skills per agent").action(()=>{let e=ne();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=J(t.workspace,".claude/skills"),s=ge(n)?Ls(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});Po.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[J(n,"src",e,"SKILL.md"),J(n,"skills",e,"SKILL.md")],i=s.find(k=>ge(k));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(h.dim(` ${k}`));return}let r=wo(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),d;try{d=_()}catch(k){console.log(h.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(d.agents||{}),l=o.agent?g.filter(([k])=>k===o.agent):g;if(l.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let p=0,f=0,u=0,w=0;for(let[k,b]of l){let x=b.workspace;if(!x||!ge(x)){console.log(` ${h.yellow("\u2717")} ${k.padEnd(22)} ${h.dim("(workspace missing: "+(x||"undefined")+")")}`),w++;continue}let A=J(x,".claude/skills",e),S=J(A,"SKILL.md");if(!ge(S)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${k.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}o.dryRun||(eo(A,{recursive:!0}),at(S,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),p++;continue}let v=wo(S,"utf-8");if(t("sha256").update(v).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${k.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),u++;continue}let C=(v.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||at(S,r),console.log(` ${h.yellow("\u21BB")} ${k.padEnd(22)} ${h.dim(`v${C} \u2192 v${c}`)}`),f++}console.log();let y=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${y} seed ${p}, ${y} update ${f}, ${u} already current, ${w} skipped.`)),o.dryRun&&(p>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Po.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:o}=await import("./loader-BOKE5M5S.js"),{auditAll:t}=await import("./audit-4245CX6P.js"),{loadReferences:n}=await import("./loader-4ZGTK7LD.js"),{loadRecipes:s}=await import("./recipes-7S4MC5OJ.js"),i=[];if(e.workspace){let f=ne().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(J(f.workspace))}else if(e.allWorkspaces){let p=ne();for(let f of Object.values(p.agents||{}))f?.workspace&&i.push(J(f.workspace))}else i.push(J(e.cwd));let r=J(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(p=>o(p)))).flat(),[d,g]=await Promise.all([n(r),s(r)]),l=t({skills:c,references:d,recipes:g});if(e.json)console.log(JSON.stringify(l.map(p=>({name:p.name,verdict:p.verdict,reasons:p.reasons,path:p.skill?.path})),null,2));else{let p={PASS:0,REVIEW:0,FAILING:0};for(let f of l)p[f.verdict]++;console.log();for(let f of l){let u=f.verdict==="PASS"?h.green("PASS "):f.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${u} ${h.bold(f.name)}${f.skill?.path?h.dim(` (${f.skill.path})`):""}`);for(let w of f.reasons)console.log(` ${h.dim("\xB7")} ${w}`)}console.log(),console.log(` ${h.green(`${p.PASS} PASS`)} ${h.yellow(`${p.REVIEW} REVIEW`)} ${h.red(`${p.FAILING} FAILING`)}`),console.log()}process.exit(l.some(p=>p.verdict==="FAILING")?1:0)});Po.command("suggest").description("rank an agent's skills against a task (suggests, never loads)").argument("<task>","the task, in the words it arrived in").option("--agent <id>","whose skills to rank").option("--min <p>","minimum P(any skill applies)","0.6").option("--json","emit the ranking as JSON").action(async(e,o)=>{let t=ne(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-BOKE5M5S.js"),{pickSkillForTask:a}=await import("./select-L4VIYSFJ.js"),c=await r(i.workspace);if(c.length===0){console.log(h.yellow(` ${s} has no skills`));return}let d=await a(c,e,{agent:s,minRelevant:Number(o.min)||.6});if(o.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:d.skill?.frontmatter.name??null,anyRelevant:d.anyRelevant,confidence:d.confidence,judged:d.judged,reason:d.reason,shortlist:d.shortlist},null,2));return}if(console.log(),d.skill?(console.log(` ${h.green("\u2192")} ${h.bold(d.skill.frontmatter.name)} ${h.dim(`\xB7 ${d.reason}`)}`),console.log(` ${h.dim(d.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${h.yellow("\xB7")} no skill for this ${h.dim(`\u2014 ${d.reason}`)}`),d.shortlist.length>1){console.log(h.dim(`
23
23
  shortlist (lexical -> judged)`));for(let g of d.shortlist.slice(0,6)){let l=g.p===void 0?" - ":g.p.toFixed(2);console.log(h.dim(` ${g.lexical.toFixed(2)} -> ${l} ${g.name}`))}}d.judged||console.log(h.dim(`
24
- (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var Lt=new eo().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Lt.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=J(o.cwd),n=J(t,"references/example"),s=J(t,"references/recipes/example.yaml");ge(n)||(console.log(h.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=J(t,".agentx/references",e),r=J(t,".agentx/references/recipes");Ze(i,{recursive:!0}),Ze(r,{recursive:!0});let a=As(n).filter(l=>l.endsWith(".yaml")||l.endsWith(".yml")),c=0,d=0;for(let l of a){let p=fo(i,l);if(ge(p)&&!o.force){console.log(h.dim(` skip ${p} (exists; --force to overwrite)`)),d++;continue}let u=ho(fo(n,l),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);nt(p,u),console.log(h.green(` + ${p}`)),c++}let g=fo(r,`${e}.yaml`);if(ge(g)&&!o.force)console.log(h.dim(` skip ${g} (exists; --force to overwrite)`)),d++;else if(ge(s)){let l=ho(s,"utf-8").replaceAll("example.",`${e}.`);nt(g,l),console.log(h.green(` + ${g}`)),c++}console.log(),console.log(h.dim(` ${c} written, ${d} skipped. Edit the placeholders, then:`)),console.log(h.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(h.dim(" 2. agentx skill audit # verify references resolve")),console.log(h.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});Lt.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.example.com)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-BOKE5M5S.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-D4VVRNAI.js"),i=J(o.cwd),r=o.from?String(o.from).split(",").map(w=>w.trim()).filter(Boolean):[e],a=await t(i),c=n(a,{namespace:e,filter:r,gitlabHost:o.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(h.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(h.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(h.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let d=Object.fromEntries(Object.entries(c.byKind).map(([w,y])=>[w,y.length]));console.log(` Discovered: ssh=${d.ssh} gitlab=${d.gitlab} paths=${d.path} contacts=${d.contact}`);let g=s(c,e),l=J(o.referencesCwd||o.cwd),p=J(l,".agentx/references",e);if(!o.write){console.log(),console.log(h.dim(` Dry-run \u2014 would write to ${p}/`));for(let[w,y]of Object.entries(g))console.log(h.cyan(`
24
+ (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var qt=new oo().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");qt.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=J(o.cwd),n=J(t,"references/example"),s=J(t,"references/recipes/example.yaml");ge(n)||(console.log(h.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=J(t,".agentx/references",e),r=J(t,".agentx/references/recipes");eo(i,{recursive:!0}),eo(r,{recursive:!0});let a=Ls(n).filter(l=>l.endsWith(".yaml")||l.endsWith(".yml")),c=0,d=0;for(let l of a){let p=yo(i,l);if(ge(p)&&!o.force){console.log(h.dim(` skip ${p} (exists; --force to overwrite)`)),d++;continue}let u=wo(yo(n,l),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);at(p,u),console.log(h.green(` + ${p}`)),c++}let g=yo(r,`${e}.yaml`);if(ge(g)&&!o.force)console.log(h.dim(` skip ${g} (exists; --force to overwrite)`)),d++;else if(ge(s)){let l=wo(s,"utf-8").replaceAll("example.",`${e}.`);at(g,l),console.log(h.green(` + ${g}`)),c++}console.log(),console.log(h.dim(` ${c} written, ${d} skipped. Edit the placeholders, then:`)),console.log(h.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(h.dim(" 2. agentx skill audit # verify references resolve")),console.log(h.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});qt.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.example.com)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-BOKE5M5S.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-D4VVRNAI.js"),i=J(o.cwd),r=o.from?String(o.from).split(",").map(w=>w.trim()).filter(Boolean):[e],a=await t(i),c=n(a,{namespace:e,filter:r,gitlabHost:o.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(h.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(h.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(h.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let d=Object.fromEntries(Object.entries(c.byKind).map(([w,y])=>[w,y.length]));console.log(` Discovered: ssh=${d.ssh} gitlab=${d.gitlab} paths=${d.path} contacts=${d.contact}`);let g=s(c,e),l=J(o.referencesCwd||o.cwd),p=J(l,".agentx/references",e);if(!o.write){console.log(),console.log(h.dim(` Dry-run \u2014 would write to ${p}/`));for(let[w,y]of Object.entries(g))console.log(h.cyan(`
25
25
  --- ${w} ---`)),console.log(y.split(`
26
- `).slice(0,30).map($=>` ${$}`).join(`
26
+ `).slice(0,30).map(k=>` ${k}`).join(`
27
27
  `)),y.split(`
28
28
  `).length>30&&console.log(h.dim(` \u2026 (${y.split(`
29
- `).length-30} more lines truncated in preview)`));console.log(),console.log(h.dim(` Re-run with --write to commit these to ${p}/`)),console.log();return}Ze(p,{recursive:!0});let f=0,u=0;for(let[w,y]of Object.entries(g)){let $=fo(p,w);if(ge($)&&!o.force){console.log(h.dim(` skip ${$} (exists; --force to overwrite)`)),u++;continue}nt($,y),console.log(h.green(` + ${$}`)),f++}console.log(),console.log(h.dim(` ${f} written, ${u} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(h.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});Lt.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:o}=await import("./loader-4ZGTK7LD.js"),t=await o(J(e.cwd)),n=[...t.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(h.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=t.sourceById.get(s.id);console.log(` ${h.cyan(s.id)} ${h.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(h.dim(` ${i}`))}console.log(),console.log(h.dim(` ${n.length} reference(s) loaded.`)),console.log()});var Os=new eo().name("hook").description("manage hooks \u2014 add to agent workspace");Os.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=ne().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=J(t.workspace,".claude/settings.json"),s=ge(n)?JSON.parse(ho(n,"utf-8")):{},i=await je([{type:"select",name:"event",message:"Hook event",choices:[{title:"PreToolUse \u2014 before any tool runs",value:"PreToolUse"},{title:"PostToolUse \u2014 after any tool runs",value:"PostToolUse"},{title:"SessionStart \u2014 when session begins",value:"SessionStart"},{title:"Notification \u2014 on notifications",value:"Notification"},{title:"Stop \u2014 before session stops",value:"Stop"}]},{type:"select",name:"type",message:"Hook type",choices:[{title:"command \u2014 run a shell command",value:"command"},{title:"http \u2014 POST to a URL",value:"http"}]},{type:"text",name:"value",message:c=>c==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!i.event||!i.value)return;s.hooks=s.hooks||{},s.hooks[i.event]=s.hooks[i.event]||[];let a={hooks:[{type:i.type,...i.type==="command"?{command:i.value}:{url:i.value}}]};i.matcher&&(a.matcher=i.matcher),s.hooks[i.event].push(a),Ze(J(t.workspace,".claude"),{recursive:!0}),nt(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var js=new eo().name("migrate").description("import configuration from OpenClaw or other tools");js.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(e,o)=>{let t=[e,J(process.env.HOME||"",".openclaw/openclaw.json"),J(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of t)if(f&&ge(f)){n=f;break}if(!n){console.log(h.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(h.dim(` Reading: ${n}`));let s=JSON.parse(ho(n,"utf-8")),i=ge(J(process.cwd(),"agentx.json"))?ne():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},r=s.agents?.list||[],a=s.bindings||[],c={};for(let f of a)f.match?.channel==="telegram"&&(c[f.match.accountId]=f.agentId);r.find(f=>f.id==="main"||f.default)&&(c.default="main");let d=0;for(let f of r){if(f.workspace?.startsWith("/data"))continue;let u=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),w=f.groupChat?.mentionPatterns||[];if(w.some(y=>y===u)||w.push(u),i.agents[u]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:w,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},d++,!o.dryRun){Ze(J(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-G6KGWPHY.js");y(u,i.agents[u])}}console.log(` ${h.green(d)} agents imported (workspaces set up with Claude Code best practices)`);let g=s.channels?.telegram?.accounts||{},l=0;for(let[f,u]of Object.entries(g)){if(!u.botToken)continue;let y=c[f]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[f]={token:u.botToken,agentBinding:y},i.channels.telegram.enabled=!0,l++}console.log(` ${h.green(l)} Telegram accounts imported`);let p=J(n,"../cron/jobs.json");if(ge(p)){let f=JSON.parse(ho(p,"utf-8")),u=0;for(let w of f.jobs||[]){let y=w.name||w.id,$=w.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[y]={enabled:w.enabled||!1,schedule:w.schedule?.expr||"0 9 * * *",timezone:w.schedule?.tz||"UTC",agent:$,prompt:w.payload?.message||"",timeout:w.payload?.timeoutSeconds||600,onError:["log"]},u++}console.log(` ${h.green(u)} cron jobs imported`)}o.dryRun?(console.log(h.yellow(`
30
- Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await De(i),console.log(h.green(`
31
- Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var yo=new eo().name("config").description("validate and inspect configuration");yo.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async e=>{console.log();try{let o=D(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=nn(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=ge(J(r,".claude")),c=ge(J(r,"CLAUDE.md")),d=ge(J(r,".claude/settings.json")),g=ge(J(r,".claude/skills"))?As(J(r,".claude/skills")).filter(p=>!p.startsWith(".")).length:0,l=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",d?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${l.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});yo.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=D(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function id(e,o){if(o)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(t=>t.trim()).filter(Boolean):e}function Es(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}yo.command("get <path>").description("read a config value by dot-path (e.g. agents.devops.model)").option("-c, --config <path>","path to agentx.json").option("--raw","show ${VAR} tokens instead of env-expanded values").option("--json","output as JSON (for scripting)").action(async(e,o)=>{let{readFileSync:t,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-KJ5GEMVV.js"),{expandEnvVars:r}=await import("./config-SRTXHGSK.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(h.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(t(a,"utf-8")),d=o.raw?c:r(c),g=i(d,e);o.json?console.log(JSON.stringify(g)):console.log(Es(g))});yo.command("set <path> <value>").description("write a config value by dot-path; validates against schema and hot-reloads the daemon").option("-c, --config <path>","path to agentx.json").option("--string","treat the value as a literal string (skip JSON parsing)").option("--dry-run","validate and diff without writing").action(async(e,o,t)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:i}=await import("./config-mutator-KJ5GEMVV.js"),r=id(o,!!t.string),a=await n(d=>{s(d,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(h.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would become: ${Es(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${Es(c)}`)),a.reloaded?console.log(h.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(h.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});yo.command("unset <path>").description("remove a config value by dot-path (validates + hot-reloads)").option("-c, --config <path>","path to agentx.json").option("--dry-run","validate without writing").action(async(e,o)=>{let{applyConfigMutation:t,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-KJ5GEMVV.js"),i=await t(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:o.config,dryRun:!!o.dryRun});if(i.success||(console.log(h.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(h.dim(` (no-op) ${h.cyan(e)} was not set`));return}o.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would be removed`)):(console.log(h.green(` \u2713 ${h.cyan(e)} removed`)),i.reloaded&&console.log(h.dim(" Daemon hot-reloaded.")))});yo.command("governance").description("show resolved governance flags (read-only; flags read once at startup)").option("-c, --config <path>","path to agentx.json").option("--json","emit JSON").action(e=>{let o=!1,t=0,n;try{let l=D(e.config);o=!!l.business?.enabled,t=(l.business?.projects??[]).length}catch(l){n=l?.message??String(l)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(h.bold(" Governance flags")),console.log(),n&&(console.log(h.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let d=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${d(s)}${c?"":h.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?h.green("active"):r?h.yellow("env=true but business.enabled=false \u2192 inactive"):h.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(h.dim(` business.enabled ${o?h.green("true"):h.dim("false")}`)),console.log(h.dim(` business.projects[] ${t}`)),console.log(),console.log(h.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(h.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as rd}from"commander";import wo from"chalk";import{resolve as bo}from"path";import{existsSync as ad}from"fs";var ao=new rd().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Do(e){let o=bo(e,".agentx/db.sqlite");ad(o)||(console.log(wo.red(` No SQLite at ${o}`)),console.log(wo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=zi({path:o});return t||(console.log(wo.red(` Could not open ${o}`)),console.log(wo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function Po(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(wo.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}ao.command("tasks").description("recent task_history rows (one per agent task)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by start day (UTC)").option("-s, --status <status>","ok | error").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=Do(bo(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(t.push("status = @status"),n.status=e.status);let s=`
29
+ `).length-30} more lines truncated in preview)`));console.log(),console.log(h.dim(` Re-run with --write to commit these to ${p}/`)),console.log();return}eo(p,{recursive:!0});let f=0,u=0;for(let[w,y]of Object.entries(g)){let k=yo(p,w);if(ge(k)&&!o.force){console.log(h.dim(` skip ${k} (exists; --force to overwrite)`)),u++;continue}at(k,y),console.log(h.green(` + ${k}`)),f++}console.log(),console.log(h.dim(` ${f} written, ${u} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(h.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});qt.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:o}=await import("./loader-4ZGTK7LD.js"),t=await o(J(e.cwd)),n=[...t.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(h.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=t.sourceById.get(s.id);console.log(` ${h.cyan(s.id)} ${h.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(h.dim(` ${i}`))}console.log(),console.log(h.dim(` ${n.length} reference(s) loaded.`)),console.log()});var Ms=new oo().name("hook").description("manage hooks \u2014 add to agent workspace");Ms.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=ne().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=J(t.workspace,".claude/settings.json"),s=ge(n)?JSON.parse(wo(n,"utf-8")):{},i=await Te([{type:"select",name:"event",message:"Hook event",choices:[{title:"PreToolUse \u2014 before any tool runs",value:"PreToolUse"},{title:"PostToolUse \u2014 after any tool runs",value:"PostToolUse"},{title:"SessionStart \u2014 when session begins",value:"SessionStart"},{title:"Notification \u2014 on notifications",value:"Notification"},{title:"Stop \u2014 before session stops",value:"Stop"}]},{type:"select",name:"type",message:"Hook type",choices:[{title:"command \u2014 run a shell command",value:"command"},{title:"http \u2014 POST to a URL",value:"http"}]},{type:"text",name:"value",message:c=>c==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!i.event||!i.value)return;s.hooks=s.hooks||{},s.hooks[i.event]=s.hooks[i.event]||[];let a={hooks:[{type:i.type,...i.type==="command"?{command:i.value}:{url:i.value}}]};i.matcher&&(a.matcher=i.matcher),s.hooks[i.event].push(a),eo(J(t.workspace,".claude"),{recursive:!0}),at(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var Fs=new oo().name("migrate").description("import configuration from OpenClaw or other tools");Fs.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(e,o)=>{let t=[e,J(process.env.HOME||"",".openclaw/openclaw.json"),J(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of t)if(f&&ge(f)){n=f;break}if(!n){console.log(h.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(h.dim(` Reading: ${n}`));let s=JSON.parse(wo(n,"utf-8")),i=ge(J(process.cwd(),"agentx.json"))?ne():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},r=s.agents?.list||[],a=s.bindings||[],c={};for(let f of a)f.match?.channel==="telegram"&&(c[f.match.accountId]=f.agentId);r.find(f=>f.id==="main"||f.default)&&(c.default="main");let d=0;for(let f of r){if(f.workspace?.startsWith("/data"))continue;let u=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),w=f.groupChat?.mentionPatterns||[];if(w.some(y=>y===u)||w.push(u),i.agents[u]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:w,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},d++,!o.dryRun){eo(J(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-G6KGWPHY.js");y(u,i.agents[u])}}console.log(` ${h.green(d)} agents imported (workspaces set up with Claude Code best practices)`);let g=s.channels?.telegram?.accounts||{},l=0;for(let[f,u]of Object.entries(g)){if(!u.botToken)continue;let y=c[f]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[f]={token:u.botToken,agentBinding:y},i.channels.telegram.enabled=!0,l++}console.log(` ${h.green(l)} Telegram accounts imported`);let p=J(n,"../cron/jobs.json");if(ge(p)){let f=JSON.parse(wo(p,"utf-8")),u=0;for(let w of f.jobs||[]){let y=w.name||w.id,k=w.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[y]={enabled:w.enabled||!1,schedule:w.schedule?.expr||"0 9 * * *",timezone:w.schedule?.tz||"UTC",agent:k,prompt:w.payload?.message||"",timeout:w.payload?.timeoutSeconds||600,onError:["log"]},u++}console.log(` ${h.green(u)} cron jobs imported`)}o.dryRun?(console.log(h.yellow(`
30
+ Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await _e(i),console.log(h.green(`
31
+ Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var bo=new oo().name("config").description("validate and inspect configuration");bo.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async e=>{console.log();try{let o=_(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=dn(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=ge(J(r,".claude")),c=ge(J(r,"CLAUDE.md")),d=ge(J(r,".claude/settings.json")),g=ge(J(r,".claude/skills"))?Ls(J(r,".claude/skills")).filter(p=>!p.startsWith(".")).length:0,l=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",d?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${l.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});bo.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=_(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function Sd(e,o){if(o)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(t=>t.trim()).filter(Boolean):e}function Ps(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}bo.command("get <path>").description("read a config value by dot-path (e.g. agents.devops.model)").option("-c, --config <path>","path to agentx.json").option("--raw","show ${VAR} tokens instead of env-expanded values").option("--json","output as JSON (for scripting)").action(async(e,o)=>{let{readFileSync:t,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-KJ5GEMVV.js"),{expandEnvVars:r}=await import("./config-SRTXHGSK.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(h.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(t(a,"utf-8")),d=o.raw?c:r(c),g=i(d,e);o.json?console.log(JSON.stringify(g)):console.log(Ps(g))});bo.command("set <path> <value>").description("write a config value by dot-path; validates against schema and hot-reloads the daemon").option("-c, --config <path>","path to agentx.json").option("--string","treat the value as a literal string (skip JSON parsing)").option("--dry-run","validate and diff without writing").action(async(e,o,t)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:i}=await import("./config-mutator-KJ5GEMVV.js"),r=Sd(o,!!t.string),a=await n(d=>{s(d,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(h.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would become: ${Ps(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${Ps(c)}`)),a.reloaded?console.log(h.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(h.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});bo.command("unset <path>").description("remove a config value by dot-path (validates + hot-reloads)").option("-c, --config <path>","path to agentx.json").option("--dry-run","validate without writing").action(async(e,o)=>{let{applyConfigMutation:t,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-KJ5GEMVV.js"),i=await t(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:o.config,dryRun:!!o.dryRun});if(i.success||(console.log(h.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(h.dim(` (no-op) ${h.cyan(e)} was not set`));return}o.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would be removed`)):(console.log(h.green(` \u2713 ${h.cyan(e)} removed`)),i.reloaded&&console.log(h.dim(" Daemon hot-reloaded.")))});bo.command("governance").description("show resolved governance flags (read-only; flags read once at startup)").option("-c, --config <path>","path to agentx.json").option("--json","emit JSON").action(e=>{let o=!1,t=0,n;try{let l=_(e.config);o=!!l.business?.enabled,t=(l.business?.projects??[]).length}catch(l){n=l?.message??String(l)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(h.bold(" Governance flags")),console.log(),n&&(console.log(h.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let d=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${d(s)}${c?"":h.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?h.green("active"):r?h.yellow("env=true but business.enabled=false \u2192 inactive"):h.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(h.dim(` business.enabled ${o?h.green("true"):h.dim("false")}`)),console.log(h.dim(` business.projects[] ${t}`)),console.log(),console.log(h.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(h.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as Ed}from"commander";import $o from"chalk";import{resolve as ko}from"path";import{existsSync as Ad}from"fs";var lo=new Ed().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Lo(e){let o=ko(e,".agentx/db.sqlite");Ad(o)||(console.log($o.red(` No SQLite at ${o}`)),console.log($o.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=ir({path:o});return t||(console.log($o.red(` Could not open ${o}`)),console.log($o.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function Mo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log($o.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}lo.command("tasks").description("recent task_history rows (one per agent task)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by start day (UTC)").option("-s, --status <status>","ok | error").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=Lo(ko(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(t.push("status = @status"),n.status=e.status);let s=`
32
32
  SELECT agent_id, channel, status, duration_ms,
33
33
  input_tokens, output_tokens,
34
34
  substr(message_preview, 1, 60) AS message,
@@ -37,7 +37,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
37
37
  ${t.length?"WHERE "+t.join(" AND "):""}
38
38
  ORDER BY started_at DESC
39
39
  LIMIT @limit
40
- `,i=o.prepare(s).all({...n,limit:Number(e.limit)});Po(i,!!e.json)});ao.command("rotations").description("session rotation events (stale | tier-2 | max-turns)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-r, --reason <r>","stale | tier-2 | max-turns").option("-n, --limit <n>","max rows","20").option("--summary","group by agent + reason").option("--json","emit JSON").action(e=>{let o=Do(bo(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.reason&&(t.push("reason = @reason"),n.reason=e.reason);let s=t.length?"WHERE "+t.join(" AND "):"",i=e.summary?`
40
+ `,i=o.prepare(s).all({...n,limit:Number(e.limit)});Mo(i,!!e.json)});lo.command("rotations").description("session rotation events (stale | tier-2 | max-turns)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-r, --reason <r>","stale | tier-2 | max-turns").option("-n, --limit <n>","max rows","20").option("--summary","group by agent + reason").option("--json","emit JSON").action(e=>{let o=Lo(ko(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.reason&&(t.push("reason = @reason"),n.reason=e.reason);let s=t.length?"WHERE "+t.join(" AND "):"",i=e.summary?`
41
41
  SELECT agent_id, reason, COUNT(*) AS n,
42
42
  ROUND(AVG(last_turn_input_tokens)) AS avg_input_tokens,
43
43
  MAX(last_turn_input_tokens) AS max_input_tokens
@@ -51,14 +51,14 @@ The AgentX daemon and a speech transcription backend must also be available. Run
51
51
  ${s}
52
52
  ORDER BY rotated_at DESC
53
53
  LIMIT @limit
54
- `,r=o.prepare(i).all({...n,limit:Number(e.limit)});Po(r,!!e.json)});ao.command("usage").description("token usage rolled up per (agent, model, day)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by day (UTC)").option("--json","emit JSON").action(e=>{let o=Do(bo(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("day = @day"),n.day=e.day);let s=`
54
+ `,r=o.prepare(i).all({...n,limit:Number(e.limit)});Mo(r,!!e.json)});lo.command("usage").description("token usage rolled up per (agent, model, day)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by day (UTC)").option("--json","emit JSON").action(e=>{let o=Lo(ko(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("day = @day"),n.day=e.day);let s=`
55
55
  SELECT day, agent_id, model, tasks,
56
56
  input_tokens AS in_tok, output_tokens AS out_tok,
57
57
  cache_read_tokens AS cache_read, cache_create_tokens AS cache_create
58
58
  FROM usage_daily
59
59
  ${t.length?"WHERE "+t.join(" AND "):""}
60
60
  ORDER BY day DESC, agent_id
61
- `,i=o.prepare(s).all(n);Po(i,!!e.json)});ao.command("routes").description("inbound routing decisions captured by the pipeline trace").option("--cwd <cwd>","working directory",process.cwd()).option("-c, --channel <ch>","filter by channel (telegram, gitlab, github, ...)").option("-k, --kind <k>","match | drop").option("-n, --limit <n>","max rows","20").option("--summary","group by channel + kind + deciding stage").option("--json","emit JSON").action(e=>{let o=Do(bo(e.cwd)),t=[],n={};e.channel&&(t.push("channel = @channel"),n.channel=e.channel),e.kind&&(t.push("kind = @kind"),n.kind=e.kind);let s=t.length?"WHERE "+t.join(" AND "):"",i=e.summary?`
61
+ `,i=o.prepare(s).all(n);Mo(i,!!e.json)});lo.command("routes").description("inbound routing decisions captured by the pipeline trace").option("--cwd <cwd>","working directory",process.cwd()).option("-c, --channel <ch>","filter by channel (telegram, gitlab, github, ...)").option("-k, --kind <k>","match | drop").option("-n, --limit <n>","max rows","20").option("--summary","group by channel + kind + deciding stage").option("--json","emit JSON").action(e=>{let o=Lo(ko(e.cwd)),t=[],n={};e.channel&&(t.push("channel = @channel"),n.channel=e.channel),e.kind&&(t.push("kind = @kind"),n.kind=e.kind);let s=t.length?"WHERE "+t.join(" AND "):"",i=e.summary?`
62
62
  SELECT channel, kind, deciding_stage, COUNT(*) AS n
63
63
  FROM route_traces
64
64
  ${s}
@@ -71,7 +71,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
71
71
  ${s}
72
72
  ORDER BY at DESC
73
73
  LIMIT @limit
74
- `,r=o.prepare(i).all({...n,limit:Number(e.limit)});Po(r,!!e.json)});ao.command("errors").description("failed tasks (status='error') with their error message").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=Do(bo(e.cwd)),t=["status = 'error'"],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent);let s=`
74
+ `,r=o.prepare(i).all({...n,limit:Number(e.limit)});Mo(r,!!e.json)});lo.command("errors").description("failed tasks (status='error') with their error message").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=Lo(ko(e.cwd)),t=["status = 'error'"],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent);let s=`
75
75
  SELECT agent_id, channel, duration_ms,
76
76
  substr(error, 1, 120) AS error,
77
77
  started_at
@@ -79,12 +79,12 @@ The AgentX daemon and a speech transcription backend must also be available. Run
79
79
  WHERE ${t.join(" AND ")}
80
80
  ORDER BY started_at DESC
81
81
  LIMIT @limit
82
- `,i=o.prepare(s).all({...n,limit:Number(e.limit)});Po(i,!!e.json)});ao.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=Do(bo(e.cwd)),n=o.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map(s=>({table:s.name,rows:o.prepare(`SELECT COUNT(*) AS c FROM ${s.name}`).get().c}));Po(n,!!e.json)});ao.command("query <sql>").description("run an arbitrary read-only SQL query (escape hatch)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action((e,o)=>{let t=Do(bo(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(wo.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(wo.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();Po(n,!!o.json)}catch(n){console.log(wo.red(` ${n.message}`)),process.exit(1)}});import{Command as dd}from"commander";import G from"chalk";import{mkdtempSync as gd}from"fs";import{tmpdir as md}from"os";import{resolve as fa,join as ha}from"path";import{existsSync as pd}from"fs";import ud from"better-sqlite3";function ua(e,o,t,n=[]){let s=new Map;for(let c of o)s.set(c.id,c);let i=[];for(let c of t)i.push({kind:"decision",ts:c.decidedAt,decision:c});for(let c of n)i.push({kind:"resolution",ts:c.resolvedAt,resolution:c});i.sort((c,d)=>c.ts!==d.ts?c.ts-d.ts:c.kind===d.kind?0:c.kind==="decision"?-1:1);let r=[],a=0;for(let c of i){if(c.kind==="resolution"){try{e.recordResolution(c.resolution)}catch(u){r.push({eventId:c.resolution.decisionEventId,decidedBy:c.resolution.decisionDecidedBy,expected:{agentId:null,outcome:"resolved"},actual:{agentId:null,outcome:"resolution-failed"},reason:`recordResolution threw: ${u?.message??u}`})}continue}let d=c.decision,g=s.get(d.eventId);if(!g){r.push({eventId:d.eventId,decidedBy:d.decidedBy,expected:{agentId:d.agentId,outcome:d.outcome},actual:{agentId:null,outcome:"skipped"},reason:"decision references event not in snapshot"});continue}let l=cd(d),p={id:g.id,ts:g.ts,source:g.source,sourceEventId:g.sourceEventId,project:g.project,subject:g.subject,intent:g.intent,rawJson:g.rawJson},f=Gi(e,p,l,()=>d.decidedAt);a+=1,(f.outcome!==d.outcome||f.agentId!==d.agentId)&&r.push({eventId:g.id,decidedBy:d.decidedBy,expected:{agentId:d.agentId,outcome:d.outcome},actual:{agentId:f.agentId,outcome:f.outcome},reason:ld(d,f)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function cd(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function ld(e,o){return e.outcome==="dispatched"&&o.outcome==="deduped"?"active-task-safety-now-fires (slot held by earlier decision)":e.outcome==="deduped"&&o.outcome==="halted"?"policy-returned-null (recorded as deduped means the live system hit active-task safety; playback policy returned null because deduped is illegal at the policy layer \u2014 investigate whether the in-flight decision is present in the snapshot)":e.agentId!==o.agentId?`agent-changed (recorded=${e.agentId} replayed=${o.agentId})`:e.outcome!==o.outcome?`outcome-changed (recorded=${e.outcome} replayed=${o.outcome})`:"unknown"}var $o=new dd().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function rt(e){let o=fa(e.cwd??process.cwd()),t=fa(o,e.path??".agentx/intent/ledger.sqlite");pd(t)||(console.log(G.red(` No ledger at ${t}`)),console.log(G.dim(' Make sure the daemon has run with INTENT_LEDGER_MODE != "off". The file is created on first ledger write.')),process.exit(1));try{return new ud(t,{readonly:!0})}catch(n){console.log(G.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(G.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Lo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(G.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}function fd(e){let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!o)return null;let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function An(e){if(!e)return;let o=fd(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(G.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}$o.command("stats").description("overview: events by source, decisions, divergences, in-flight count").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--since <duration>","limit to events newer than (e.g. 1h, 24h, 7d)").option("--json","emit JSON").action(e=>{let o=rt(e),t=An(e.since),n=t!==void 0?"WHERE ts >= @since":"",s=t!==void 0?"WHERE decided_at >= @since":"",i=n,r=o.prepare(`SELECT source, COUNT(*) as n FROM intent_events ${n} GROUP BY source ORDER BY n DESC`).all({since:t}),a=o.prepare(`SELECT COUNT(*) as n FROM intent_decisions ${s}`).get({since:t}).n,c=o.prepare(`SELECT outcome, COUNT(*) as n FROM intent_decisions ${s} GROUP BY outcome ORDER BY n DESC`).all({since:t}),d=o.prepare(`SELECT COUNT(*) as n FROM intent_divergences ${i}`).get({since:t}).n,g=o.prepare(`SELECT source, COUNT(*) as n FROM intent_divergences ${i} GROUP BY source ORDER BY n DESC`).all({since:t}),l=o.prepare(`
82
+ `,i=o.prepare(s).all({...n,limit:Number(e.limit)});Mo(i,!!e.json)});lo.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=Lo(ko(e.cwd)),n=o.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map(s=>({table:s.name,rows:o.prepare(`SELECT COUNT(*) AS c FROM ${s.name}`).get().c}));Mo(n,!!e.json)});lo.command("query <sql>").description("run an arbitrary read-only SQL query (escape hatch)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action((e,o)=>{let t=Lo(ko(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log($o.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log($o.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();Mo(n,!!o.json)}catch(n){console.log($o.red(` ${n.message}`)),process.exit(1)}});import{Command as Id}from"commander";import H from"chalk";import{mkdtempSync as jd}from"fs";import{tmpdir as Cd}from"os";import{resolve as Ea,join as Aa}from"path";import{existsSync as Nd}from"fs";import Rd from"better-sqlite3";function Sa(e,o,t,n=[]){let s=new Map;for(let c of o)s.set(c.id,c);let i=[];for(let c of t)i.push({kind:"decision",ts:c.decidedAt,decision:c});for(let c of n)i.push({kind:"resolution",ts:c.resolvedAt,resolution:c});i.sort((c,d)=>c.ts!==d.ts?c.ts-d.ts:c.kind===d.kind?0:c.kind==="decision"?-1:1);let r=[],a=0;for(let c of i){if(c.kind==="resolution"){try{e.recordResolution(c.resolution)}catch(u){r.push({eventId:c.resolution.decisionEventId,decidedBy:c.resolution.decisionDecidedBy,expected:{agentId:null,outcome:"resolved"},actual:{agentId:null,outcome:"resolution-failed"},reason:`recordResolution threw: ${u?.message??u}`})}continue}let d=c.decision,g=s.get(d.eventId);if(!g){r.push({eventId:d.eventId,decidedBy:d.decidedBy,expected:{agentId:d.agentId,outcome:d.outcome},actual:{agentId:null,outcome:"skipped"},reason:"decision references event not in snapshot"});continue}let l=Od(d),p={id:g.id,ts:g.ts,source:g.source,sourceEventId:g.sourceEventId,project:g.project,subject:g.subject,intent:g.intent,rawJson:g.rawJson},f=sr(e,p,l,()=>d.decidedAt);a+=1,(f.outcome!==d.outcome||f.agentId!==d.agentId)&&r.push({eventId:g.id,decidedBy:d.decidedBy,expected:{agentId:d.agentId,outcome:d.outcome},actual:{agentId:f.agentId,outcome:f.outcome},reason:Td(d,f)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function Od(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function Td(e,o){return e.outcome==="dispatched"&&o.outcome==="deduped"?"active-task-safety-now-fires (slot held by earlier decision)":e.outcome==="deduped"&&o.outcome==="halted"?"policy-returned-null (recorded as deduped means the live system hit active-task safety; playback policy returned null because deduped is illegal at the policy layer \u2014 investigate whether the in-flight decision is present in the snapshot)":e.agentId!==o.agentId?`agent-changed (recorded=${e.agentId} replayed=${o.agentId})`:e.outcome!==o.outcome?`outcome-changed (recorded=${e.outcome} replayed=${o.outcome})`:"unknown"}var vo=new Id().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function dt(e){let o=Ea(e.cwd??process.cwd()),t=Ea(o,e.path??".agentx/intent/ledger.sqlite");Nd(t)||(console.log(H.red(` No ledger at ${t}`)),console.log(H.dim(' Make sure the daemon has run with INTENT_LEDGER_MODE != "off". The file is created on first ledger write.')),process.exit(1));try{return new Rd(t,{readonly:!0})}catch(n){console.log(H.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(H.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Fo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(H.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}function Dd(e){let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!o)return null;let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function Rn(e){if(!e)return;let o=Dd(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(H.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}vo.command("stats").description("overview: events by source, decisions, divergences, in-flight count").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--since <duration>","limit to events newer than (e.g. 1h, 24h, 7d)").option("--json","emit JSON").action(e=>{let o=dt(e),t=Rn(e.since),n=t!==void 0?"WHERE ts >= @since":"",s=t!==void 0?"WHERE decided_at >= @since":"",i=n,r=o.prepare(`SELECT source, COUNT(*) as n FROM intent_events ${n} GROUP BY source ORDER BY n DESC`).all({since:t}),a=o.prepare(`SELECT COUNT(*) as n FROM intent_decisions ${s}`).get({since:t}).n,c=o.prepare(`SELECT outcome, COUNT(*) as n FROM intent_decisions ${s} GROUP BY outcome ORDER BY n DESC`).all({since:t}),d=o.prepare(`SELECT COUNT(*) as n FROM intent_divergences ${i}`).get({since:t}).n,g=o.prepare(`SELECT source, COUNT(*) as n FROM intent_divergences ${i} GROUP BY source ORDER BY n DESC`).all({since:t}),l=o.prepare(`
83
83
  SELECT COUNT(*) as n FROM intent_decisions d
84
84
  LEFT JOIN intent_resolutions r
85
85
  ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
86
86
  WHERE d.outcome = 'dispatched' AND r.decision_event_id IS NULL
87
- `).get().n;if(e.json){console.log(JSON.stringify({since:t??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:d,divergencesBySource:g,inFlight:l},null,2));return}console.log(G.bold("Events by source")),Lo(r,!1),console.log(),console.log(G.bold(`Decisions: ${a}`)),Lo(c,!1),console.log(),console.log(G.bold(`Divergences: ${d}`)),Lo(g,!1),console.log(),console.log(G.bold(`In-flight (dispatched, no resolution): ${l}`))});$o.command("divergences").description("recent divergence rows (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source (telegram, gitlab, workflow, cron, mesh, github)").option("--since <duration>","limit to divergences newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=rt(e),t=An(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
87
+ `).get().n;if(e.json){console.log(JSON.stringify({since:t??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:d,divergencesBySource:g,inFlight:l},null,2));return}console.log(H.bold("Events by source")),Fo(r,!1),console.log(),console.log(H.bold(`Decisions: ${a}`)),Fo(c,!1),console.log(),console.log(H.bold(`Divergences: ${d}`)),Fo(g,!1),console.log(),console.log(H.bold(`In-flight (dispatched, no resolution): ${l}`))});vo.command("divergences").description("recent divergence rows (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source (telegram, gitlab, workflow, cron, mesh, github)").option("--since <duration>","limit to divergences newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=dt(e),t=Rn(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
88
88
  SELECT
89
89
  datetime(ts/1000, 'unixepoch') AS at,
90
90
  source,
@@ -98,7 +98,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
98
98
  ${i}
99
99
  ORDER BY ts DESC
100
100
  LIMIT @limit
101
- `).all(s);Lo(r,!!e.json)});$o.command("active").description("currently in-flight dispatched decisions (no resolution yet)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=rt(e),t=["d.outcome = 'dispatched'","r.decision_event_id IS NULL"],n={limit:Number(e.limit)};e.source&&(t.push("e.source = @source"),n.source=e.source);let s=o.prepare(`
101
+ `).all(s);Fo(r,!!e.json)});vo.command("active").description("currently in-flight dispatched decisions (no resolution yet)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=dt(e),t=["d.outcome = 'dispatched'","r.decision_event_id IS NULL"],n={limit:Number(e.limit)};e.source&&(t.push("e.source = @source"),n.source=e.source);let s=o.prepare(`
102
102
  SELECT
103
103
  datetime(d.decided_at/1000, 'unixepoch') AS dispatched_at,
104
104
  e.source,
@@ -114,7 +114,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
114
114
  WHERE ${t.join(" AND ")}
115
115
  ORDER BY d.decided_at DESC
116
116
  LIMIT @limit
117
- `).all(n);Lo(s,!!e.json)});$o.command("events").description("recent events (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-p, --project <name>","filter by project").option("--since <duration>","limit to newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let o=rt(e),t=An(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),e.project&&(n.push("project = @project"),s.project=e.project),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
117
+ `).all(n);Fo(s,!!e.json)});vo.command("events").description("recent events (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-p, --project <name>","filter by project").option("--since <duration>","limit to newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let o=dt(e),t=Rn(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),e.project&&(n.push("project = @project"),s.project=e.project),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
118
118
  SELECT
119
119
  datetime(ts/1000, 'unixepoch') AS at,
120
120
  source,
@@ -125,8 +125,8 @@ The AgentX daemon and a speech transcription backend must also be available. Run
125
125
  ${i}
126
126
  ORDER BY ts DESC
127
127
  LIMIT @limit
128
- `).all(s);Lo(r,!!e.json)});$o.command("lineage <eventOrSubject>").description("walk the dispatch chain on the same (project, subject) and print every decision + resolution").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--by-subject","treat the argument as `<project>:<subject>` instead of an event id").option("--json","emit JSON").action((e,o)=>{let t=rt(o),n=null,s=null;if(o.bySubject){let l=e.indexOf(":");l<0&&(console.log(G.red(' --by-subject expects "<project>:<subject>"')),process.exit(1)),n=e.slice(0,l),s=e.slice(l+1)}else{let l=t.prepare("SELECT project, subject FROM intent_events WHERE id = ?").get(e);l||(console.log(G.red(` no event with id ${e}`)),process.exit(1)),n=l.project,s=l.subject,(n===null||s===null)&&(console.log(G.yellow(` event ${e} has no (project, subject) \u2014 lineage requires both`)),n&&console.log(G.dim(` project: ${n}`)),s&&console.log(G.dim(` subject: ${s}`)),process.exit(1))}let i=t.prepare(`SELECT id, ts, source, COALESCE(intent, '-') AS intent, COALESCE(source_event_id, '-') AS source_event_id
129
- FROM intent_events WHERE project = ? AND subject = ? ORDER BY ts ASC`).all(n,s);if(i.length===0){console.log(G.dim(` (no events for ${n}:${s})`));return}let r=i.map(l=>l.id),a=r.map((l,p)=>`@id${p}`).join(", "),c=Object.fromEntries(r.map((l,p)=>[`id${p}`,l])),d=t.prepare(`
128
+ `).all(s);Fo(r,!!e.json)});vo.command("lineage <eventOrSubject>").description("walk the dispatch chain on the same (project, subject) and print every decision + resolution").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--by-subject","treat the argument as `<project>:<subject>` instead of an event id").option("--json","emit JSON").action((e,o)=>{let t=dt(o),n=null,s=null;if(o.bySubject){let l=e.indexOf(":");l<0&&(console.log(H.red(' --by-subject expects "<project>:<subject>"')),process.exit(1)),n=e.slice(0,l),s=e.slice(l+1)}else{let l=t.prepare("SELECT project, subject FROM intent_events WHERE id = ?").get(e);l||(console.log(H.red(` no event with id ${e}`)),process.exit(1)),n=l.project,s=l.subject,(n===null||s===null)&&(console.log(H.yellow(` event ${e} has no (project, subject) \u2014 lineage requires both`)),n&&console.log(H.dim(` project: ${n}`)),s&&console.log(H.dim(` subject: ${s}`)),process.exit(1))}let i=t.prepare(`SELECT id, ts, source, COALESCE(intent, '-') AS intent, COALESCE(source_event_id, '-') AS source_event_id
129
+ FROM intent_events WHERE project = ? AND subject = ? ORDER BY ts ASC`).all(n,s);if(i.length===0){console.log(H.dim(` (no events for ${n}:${s})`));return}let r=i.map(l=>l.id),a=r.map((l,p)=>`@id${p}`).join(", "),c=Object.fromEntries(r.map((l,p)=>[`id${p}`,l])),d=t.prepare(`
130
130
  SELECT d.event_id, d.decided_at, d.decided_by, d.agent_id, d.outcome, d.reason,
131
131
  r.resolved_at, r.status AS resolution_status, r.duration_ms, r.result_summary
132
132
  FROM intent_decisions d
@@ -134,13 +134,13 @@ The AgentX daemon and a speech transcription backend must also be available. Run
134
134
  ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
135
135
  WHERE d.event_id IN (${a})
136
136
  ORDER BY d.decided_at ASC
137
- `).all(c);if(o.json){let l=i.map(p=>({event:p,decisions:d.filter(f=>f.event_id===p.id)}));console.log(JSON.stringify({project:n,subject:s,lineage:l},null,2));return}let g=new Set;for(let l of d)l.outcome==="dispatched"&&l.agent_id&&g.add(l.agent_id);console.log(),console.log(G.bold(` Lineage for ${G.cyan(n+":"+s)}`)),console.log(G.dim(` ${i.length} event(s), ${d.length} decision(s), ${g.size} distinct agent(s) dispatched`)),console.log();for(let l of i){let p=new Date(l.ts).toISOString().slice(0,19).replace("T"," ");console.log(` ${G.dim(p)} ${G.bold(l.id)} ${G.dim(`(${l.source}/${l.intent})`)}`);let f=d.filter(u=>u.event_id===l.id);if(f.length===0){console.log(G.dim(" (no decisions yet)"));continue}for(let u of f){let w=u.outcome==="dispatched"?G.green(u.outcome):u.outcome==="dropped"?G.dim(u.outcome):G.yellow(u.outcome),y=u.agent_id?G.cyan(u.agent_id):G.dim("-"),$=u.reason?G.dim(` \u2014 ${u.reason.slice(0,60)}`):"";if(console.log(` ${G.dim(u.decided_by)} \u2192 ${w} ${y}${$}`),u.resolution_status){let b=u.resolution_status==="ok"?G.green(u.resolution_status):G.red(u.resolution_status),v=u.duration_ms?`${(u.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${G.dim("resolved")} ${b} ${G.dim(v)}`)}else u.outcome==="dispatched"&&console.log(` ${G.yellow("(in-flight, no resolution)")}`)}}console.log()});$o.command("replay").description("replay the source ledger onto a fresh tmp ledger; report divergences").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--since <duration>","limit to events newer than (e.g. 1h, 24h, 7d)").option("-s, --source <name>","filter to one source").option("-n, --limit <n>","max events to replay (defaults to all)").option("--json","emit JSON").action(e=>{let o=rt(e),t=An(e.since),n=[],s={};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=e.limit?`LIMIT ${Number(e.limit)}`:"",r=o.prepare(`
137
+ `).all(c);if(o.json){let l=i.map(p=>({event:p,decisions:d.filter(f=>f.event_id===p.id)}));console.log(JSON.stringify({project:n,subject:s,lineage:l},null,2));return}let g=new Set;for(let l of d)l.outcome==="dispatched"&&l.agent_id&&g.add(l.agent_id);console.log(),console.log(H.bold(` Lineage for ${H.cyan(n+":"+s)}`)),console.log(H.dim(` ${i.length} event(s), ${d.length} decision(s), ${g.size} distinct agent(s) dispatched`)),console.log();for(let l of i){let p=new Date(l.ts).toISOString().slice(0,19).replace("T"," ");console.log(` ${H.dim(p)} ${H.bold(l.id)} ${H.dim(`(${l.source}/${l.intent})`)}`);let f=d.filter(u=>u.event_id===l.id);if(f.length===0){console.log(H.dim(" (no decisions yet)"));continue}for(let u of f){let w=u.outcome==="dispatched"?H.green(u.outcome):u.outcome==="dropped"?H.dim(u.outcome):H.yellow(u.outcome),y=u.agent_id?H.cyan(u.agent_id):H.dim("-"),k=u.reason?H.dim(` \u2014 ${u.reason.slice(0,60)}`):"";if(console.log(` ${H.dim(u.decided_by)} \u2192 ${w} ${y}${k}`),u.resolution_status){let b=u.resolution_status==="ok"?H.green(u.resolution_status):H.red(u.resolution_status),x=u.duration_ms?`${(u.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${H.dim("resolved")} ${b} ${H.dim(x)}`)}else u.outcome==="dispatched"&&console.log(` ${H.yellow("(in-flight, no resolution)")}`)}}console.log()});vo.command("replay").description("replay the source ledger onto a fresh tmp ledger; report divergences").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--since <duration>","limit to events newer than (e.g. 1h, 24h, 7d)").option("-s, --source <name>","filter to one source").option("-n, --limit <n>","max events to replay (defaults to all)").option("--json","emit JSON").action(e=>{let o=dt(e),t=Rn(e.since),n=[],s={};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=e.limit?`LIMIT ${Number(e.limit)}`:"",r=o.prepare(`
138
138
  SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
139
139
  FROM intent_events
140
140
  ${n.length?"WHERE "+n.join(" AND "):""}
141
141
  ORDER BY ts ASC
142
142
  ${i}
143
- `).all(s).map(u=>({id:u.id,ts:u.ts,source:u.source,sourceEventId:u.source_event_id,project:u.project,subject:u.subject,intent:u.intent,rawJson:u.raw_json}));if(r.length===0){console.log(G.dim(" (no events match filter)"));return}let a=new Set(r.map(u=>u.id)),c=r.map((u,w)=>`@id${w}`).join(", "),d=Object.fromEntries(r.map((u,w)=>[`id${w}`,u.id])),g=o.prepare(`
143
+ `).all(s).map(u=>({id:u.id,ts:u.ts,source:u.source,sourceEventId:u.source_event_id,project:u.project,subject:u.subject,intent:u.intent,rawJson:u.raw_json}));if(r.length===0){console.log(H.dim(" (no events match filter)"));return}let a=new Set(r.map(u=>u.id)),c=r.map((u,w)=>`@id${w}`).join(", "),d=Object.fromEntries(r.map((u,w)=>[`id${w}`,u.id])),g=o.prepare(`
144
144
  SELECT event_id, decided_at, decided_by, agent_id, outcome, reason
145
145
  FROM intent_decisions
146
146
  WHERE event_id IN (${c})
@@ -148,7 +148,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
148
148
  SELECT decision_event_id, decision_decided_by, resolved_at, status, duration_ms, result_summary
149
149
  FROM intent_resolutions
150
150
  WHERE decision_event_id IN (${c})
151
- `).all(d).map(u=>({decisionEventId:u.decision_event_id,decisionDecidedBy:u.decision_decided_by,resolvedAt:u.resolved_at,status:u.status,durationMs:u.duration_ms,resultSummary:u.result_summary})),p=gd(ha(md(),"agentx-ledger-replay-")),f=new Ui({path:ha(p,"target.sqlite")});try{let u=ua(f,r,g,l);if(e.json){console.log(JSON.stringify(u,null,2));return}console.log(G.bold(`Replayed ${u.eventsCount} events, ${u.decisionsCount} decisions, ${l.length} resolutions`)),u.divergences.length===0?console.log(G.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(G.red(` \u2717 ${u.divergences.length} divergences`)),Lo(u.divergences.map(w=>({event_id:w.eventId,decided_by:w.decidedBy,recorded:`${w.expected.outcome}/${w.expected.agentId??"-"}`,replayed:`${w.actual.outcome}/${w.actual.agentId??"-"}`,reason:w.reason.slice(0,80)})),!1))}finally{f.close()}});Ei();bl();$l();kl();wl();Ri();St();import{Command as hd}from"commander";import F from"chalk";import{existsSync as ya}from"fs";import{resolve as Is}from"path";import yd from"better-sqlite3";var Pe=new hd().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),Ge=".agentx/decisions/decisions.sqlite";function wd(e){return Is(Is(e.cwd??process.cwd()),e.path??Ge)}function to(e,o=!1){let t=wd(e);ya(t)||(console.log(F.red(` No decision store at ${t}`)),console.log(F.dim(' Set decisions.enabled and give a seat mode "shadow" (or export AGENTX_DECISION_SEAT_<SEAT>=shadow). The file is created on the first recorded call.')),process.exit(1));try{return new tn({path:t,readonly:!o})}catch(n){console.log(F.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(F.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function oo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(F.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(F.bold(s(t)));for(let i of e)console.log(s(t.map(r=>i[r])))}function Cs(e){if(!e)return;let o=e.match(/^(\d+)([dhm])$/);if(o){let n=Number(o[1]),s=o[2]==="d"?864e5:o[2]==="h"?36e5:6e4;return Date.now()-n*s}let t=Date.parse(e);return Number.isNaN(t)?void 0:t}function Ts(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:Cs(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}Pe.command("stats").description("per-seat call counts, failure rate, repair rate and latency").option("--path <file>","store path",Ge).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let o=to(e),t=Cs(e.since)??0,n=o.db.prepare(`SELECT seat, mode, backend, model, structure_mode AS structureMode,
151
+ `).all(d).map(u=>({decisionEventId:u.decision_event_id,decisionDecidedBy:u.decision_decided_by,resolvedAt:u.resolved_at,status:u.status,durationMs:u.duration_ms,resultSummary:u.result_summary})),p=jd(Aa(Cd(),"agentx-ledger-replay-")),f=new Xi({path:Aa(p,"target.sqlite")});try{let u=Sa(f,r,g,l);if(e.json){console.log(JSON.stringify(u,null,2));return}console.log(H.bold(`Replayed ${u.eventsCount} events, ${u.decisionsCount} decisions, ${l.length} resolutions`)),u.divergences.length===0?console.log(H.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(H.red(` \u2717 ${u.divergences.length} divergences`)),Fo(u.divergences.map(w=>({event_id:w.eventId,decided_by:w.decidedBy,recorded:`${w.expected.outcome}/${w.expected.agentId??"-"}`,replayed:`${w.actual.outcome}/${w.actual.agentId??"-"}`,reason:w.reason.slice(0,80)})),!1))}finally{f.close()}});Li();Ml();Fl();Ul();Ll();Gi();Tt();import{Command as _d}from"commander";import U from"chalk";import{existsSync as Oa}from"fs";import{resolve as Us}from"path";import Pd from"better-sqlite3";var Pe=new _d().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),ze=".agentx/decisions/decisions.sqlite";function Ld(e){return Us(Us(e.cwd??process.cwd()),e.path??ze)}function no(e,o=!1){let t=Ld(e);Oa(t)||(console.log(U.red(` No decision store at ${t}`)),console.log(U.dim(' Set decisions.enabled and give a seat mode "shadow" (or export AGENTX_DECISION_SEAT_<SEAT>=shadow). The file is created on the first recorded call.')),process.exit(1));try{return new ln({path:t,readonly:!o})}catch(n){console.log(U.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(U.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function to(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(U.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(U.bold(s(t)));for(let i of e)console.log(s(t.map(r=>i[r])))}function qs(e){if(!e)return;let o=e.match(/^(\d+)([dhm])$/);if(o){let n=Number(o[1]),s=o[2]==="d"?864e5:o[2]==="h"?36e5:6e4;return Date.now()-n*s}let t=Date.parse(e);return Number.isNaN(t)?void 0:t}function Ws(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:qs(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}Pe.command("stats").description("per-seat call counts, failure rate, repair rate and latency").option("--path <file>","store path",ze).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let o=no(e),t=qs(e.since)??0,n=o.db.prepare(`SELECT seat, mode, backend, model, structure_mode AS structureMode,
152
152
  COUNT(*) AS calls,
153
153
  SUM(CASE WHEN error IS NOT NULL THEN 1 ELSE 0 END) AS failed,
154
154
  SUM(retries) AS retries,
@@ -158,38 +158,38 @@ The AgentX daemon and a speech transcription backend must also be available. Run
158
158
  FROM decision_calls
159
159
  WHERE ts >= ?
160
160
  GROUP BY seat, mode, backend, model, structure_mode
161
- ORDER BY calls DESC`).all(t);oo(n,e.json);let s=o.db.prepare(`SELECT seat, mode, COALESCE(action,'(none)') AS action, explored, COUNT(*) AS calls
161
+ ORDER BY calls DESC`).all(t);to(n,e.json);let s=o.db.prepare(`SELECT seat, mode, COALESCE(action,'(none)') AS action, explored, COUNT(*) AS calls
162
162
  FROM decision_calls WHERE ts >= ? GROUP BY seat, mode, action, explored
163
- ORDER BY calls DESC`).all(t);!e.json&&s.length>0&&(console.log(F.bold(`
164
- policy`)),oo(s,!1),console.log(F.dim(`
163
+ ORDER BY calls DESC`).all(t);!e.json&&s.length>0&&(console.log(U.bold(`
164
+ policy`)),to(s,!1),console.log(U.dim(`
165
165
  explored=1 means the policy wanted to skip and the expensive path ran anyway.
166
- Those are the only rows in the skip region that can ever be graded.`))),o.close()});Pe.command("calls").description("recent calls").option("--path <file>","store path",Ge).option("--seat <seat>").option("--since <window>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=to(e),t=["ts >= ?"],n=[Cs(e.since)??0];e.seat&&(t.push("seat = ?"),n.push(e.seat));let s=o.db.prepare(`SELECT id, datetime(ts/1000, 'unixepoch') AS at, seat, mode, backend, model,
166
+ Those are the only rows in the skip region that can ever be graded.`))),o.close()});Pe.command("calls").description("recent calls").option("--path <file>","store path",ze).option("--seat <seat>").option("--since <window>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=no(e),t=["ts >= ?"],n=[qs(e.since)??0];e.seat&&(t.push("seat = ?"),n.push(e.seat));let s=o.db.prepare(`SELECT id, datetime(ts/1000, 'unixepoch') AS at, seat, mode, backend, model,
167
167
  structure_mode AS structure, latency_ms AS ms, retries, truncated, error
168
168
  FROM decision_calls WHERE ${t.join(" AND ")}
169
- ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));oo(s,e.json),o.close()});Pe.command("answers <callId>").description("every answer on one call, with its incumbent and label").option("--path <file>","store path",Ge).option("--json").action((e,o)=>{let t=to(o),n=t.gradedRows({}).filter(s=>s.callId===e);if(n.length===0){console.log(F.dim(` (no answers for ${e} \u2014 check \`decisions calls\`)`)),t.close();return}oo(n.map(s=>({question:s.question,type:s.type,predicted:s.predicted,confidence:s.confidence.toFixed(3),incumbent:s.incumbent??"",truth:s.truth??""})),o.json),t.close()});Pe.command("label <callId> <question> <value>").description("attach ground truth to one answer (append-only; newest wins)").option("--path <file>","store path",Ge).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,o,t,n)=>{let s=to(n,!0);s.label(e,o,t,{kind:n.kind,labeledBy:n.by,note:n.note}),console.log(F.green(` labeled ${e}.${o} = ${t}`)),s.close()});Pe.command("unlabeled").description("lowest-confidence unlabeled answers first \u2014 the most informative to label").option("--path <file>","store path",Ge).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=to(e),t=o.gradedRows({seat:e.seat}).filter(n=>n.truth===void 0).sort((n,s)=>n.confidence-s.confidence).slice(0,Number(e.limit));oo(t.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),o.close()});Pe.command("backfill-labels").description("derive ground truth from what actually happened (monitor-prefilter seat)").option("--path <file>","store path",Ge).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let o=to(e,!0),t=Is(process.cwd(),e.db);ya(t)||(console.log(F.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new yd(t,{readonly:!0});try{let s=er(n,o);console.log(F.green(` wrote ${s} label(s)`)),s===0&&console.log(F.dim(` Rows whose outcome is genuinely ambiguous stay unlabeled on purpose \u2014
170
- label those by hand: agentx decisions unlabeled --seat monitor-prefilter`))}finally{n.close(),o.close()}});Pe.command("calibrate").description("is this seat's confidence worth anything? reliability, ECE, Brier, temperature").option("--path <file>","store path",Ge).requiredOption("--seat <seat>").option("--question <name>").option("--backend <name>","grade one backend in isolation").option("--model <id>").option("--structure-mode <mode>","never pool verbalized and logprob rows").option("--since <window>").option("--explored","only rows the policy wanted to skip \u2014 the unbiased skip-region sample").option("--min-n <n>","refuse to report below this many labeled rows","100").option("--bins <n>","default 10","10").option("--json").action(e=>{let o=to(e),t=o.gradedRows(Ts(e)),n=Ii(t,{minN:Number(e.minN),bins:Number(e.bins)});if(e.json){console.log(JSON.stringify(n,null,2)),o.close();return}if(console.log(F.bold(`
171
- ${e.seat}${e.question?`.${e.question}`:""}`)),console.log(` ${n.n} answers, ${n.nLabeled} labeled`+(n.agreement.n>0?`, ${n.agreement.n} with an incumbent (agree ${(n.agreement.rate*100).toFixed(1)}%, kappa ${n.agreement.kappa.toFixed(3)})`:"")),n.insufficient){console.log(F.yellow(`
172
- Not enough ground truth: ${n.nLabeled} labeled rows, need ${n.minN}.`)),console.log(F.dim(" An ECE on this little data is noise, and a noisy number on a dashboard gets acted on.")),console.log(F.dim(` Label the most informative rows: agentx decisions unlabeled --seat ${e.seat}`)),o.close();return}console.log(`
173
- accuracy ${(n.accuracy*100).toFixed(1)}%`),console.log(` ECE ${n.ece.toFixed(4)} `+F.dim(`[95% CI ${n.eceInterval.lo.toFixed(4)}\u2013${n.eceInterval.hi.toFixed(4)}]`)),console.log(` ECE (mass) ${n.eceEqualMass.toFixed(4)} ${F.dim("equal-mass bins")}`),console.log(` MCE ${n.mce.toFixed(4)} ${F.dim("worst single bin")}`),console.log(` Brier ${n.brier.toFixed(4)} ${F.dim("proper score, lower is better")}`),console.log(` log loss ${n.logLoss.toFixed(4)}`);let s=n.temperature;console.log(`
174
- fitted temperature ${s.temperature} `+F.dim(`(NLL ${s.nllBefore.toFixed(4)} \u2192 ${s.nll.toFixed(4)})`)),s.temperature>1.15&&console.log(F.dim(` T > 1 means the backend is overconfident. Set decisions.seats.${e.seat}.temperature = ${s.temperature}.`));let i=t.filter(a=>a.action==="skip"),r=i.filter(a=>a.explored&&a.truth!==void 0);i.length>0&&(console.log(`
175
- skip region ${i.length} answers (${(i.length/t.length*100).toFixed(1)}% of traffic), ${r.length} gradeable`),r.length===0&&console.log(F.yellow(` Nothing in the skip region has been graded. Everything below describes
169
+ ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));to(s,e.json),o.close()});Pe.command("answers <callId>").description("every answer on one call, with its incumbent and label").option("--path <file>","store path",ze).option("--json").action((e,o)=>{let t=no(o),n=t.gradedRows({}).filter(s=>s.callId===e);if(n.length===0){console.log(U.dim(` (no answers for ${e} \u2014 check \`decisions calls\`)`)),t.close();return}to(n.map(s=>({question:s.question,type:s.type,predicted:s.predicted,confidence:s.confidence.toFixed(3),incumbent:s.incumbent??"",truth:s.truth??""})),o.json),t.close()});Pe.command("label <callId> <question> <value>").description("attach ground truth to one answer (append-only; newest wins)").option("--path <file>","store path",ze).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,o,t,n)=>{let s=no(n,!0);s.label(e,o,t,{kind:n.kind,labeledBy:n.by,note:n.note}),console.log(U.green(` labeled ${e}.${o} = ${t}`)),s.close()});Pe.command("unlabeled").description("lowest-confidence unlabeled answers first \u2014 the most informative to label").option("--path <file>","store path",ze).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=no(e),t=o.gradedRows({seat:e.seat}).filter(n=>n.truth===void 0).sort((n,s)=>n.confidence-s.confidence).slice(0,Number(e.limit));to(t.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),o.close()});Pe.command("backfill-labels").description("derive ground truth from what actually happened (monitor-prefilter seat)").option("--path <file>","store path",ze).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let o=no(e,!0),t=Us(process.cwd(),e.db);Oa(t)||(console.log(U.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new Pd(t,{readonly:!0});try{let s=mr(n,o);console.log(U.green(` wrote ${s} label(s)`)),s===0&&console.log(U.dim(` Rows whose outcome is genuinely ambiguous stay unlabeled on purpose \u2014
170
+ label those by hand: agentx decisions unlabeled --seat monitor-prefilter`))}finally{n.close(),o.close()}});Pe.command("calibrate").description("is this seat's confidence worth anything? reliability, ECE, Brier, temperature").option("--path <file>","store path",ze).requiredOption("--seat <seat>").option("--question <name>").option("--backend <name>","grade one backend in isolation").option("--model <id>").option("--structure-mode <mode>","never pool verbalized and logprob rows").option("--since <window>").option("--explored","only rows the policy wanted to skip \u2014 the unbiased skip-region sample").option("--min-n <n>","refuse to report below this many labeled rows","100").option("--bins <n>","default 10","10").option("--json").action(e=>{let o=no(e),t=o.gradedRows(Ws(e)),n=qi(t,{minN:Number(e.minN),bins:Number(e.bins)});if(e.json){console.log(JSON.stringify(n,null,2)),o.close();return}if(console.log(U.bold(`
171
+ ${e.seat}${e.question?`.${e.question}`:""}`)),console.log(` ${n.n} answers, ${n.nLabeled} labeled`+(n.agreement.n>0?`, ${n.agreement.n} with an incumbent (agree ${(n.agreement.rate*100).toFixed(1)}%, kappa ${n.agreement.kappa.toFixed(3)})`:"")),n.insufficient){console.log(U.yellow(`
172
+ Not enough ground truth: ${n.nLabeled} labeled rows, need ${n.minN}.`)),console.log(U.dim(" An ECE on this little data is noise, and a noisy number on a dashboard gets acted on.")),console.log(U.dim(` Label the most informative rows: agentx decisions unlabeled --seat ${e.seat}`)),o.close();return}console.log(`
173
+ accuracy ${(n.accuracy*100).toFixed(1)}%`),console.log(` ECE ${n.ece.toFixed(4)} `+U.dim(`[95% CI ${n.eceInterval.lo.toFixed(4)}\u2013${n.eceInterval.hi.toFixed(4)}]`)),console.log(` ECE (mass) ${n.eceEqualMass.toFixed(4)} ${U.dim("equal-mass bins")}`),console.log(` MCE ${n.mce.toFixed(4)} ${U.dim("worst single bin")}`),console.log(` Brier ${n.brier.toFixed(4)} ${U.dim("proper score, lower is better")}`),console.log(` log loss ${n.logLoss.toFixed(4)}`);let s=n.temperature;console.log(`
174
+ fitted temperature ${s.temperature} `+U.dim(`(NLL ${s.nllBefore.toFixed(4)} \u2192 ${s.nll.toFixed(4)})`)),s.temperature>1.15&&console.log(U.dim(` T > 1 means the backend is overconfident. Set decisions.seats.${e.seat}.temperature = ${s.temperature}.`));let i=t.filter(a=>a.action==="skip"),r=i.filter(a=>a.explored&&a.truth!==void 0);i.length>0&&(console.log(`
175
+ skip region ${i.length} answers (${(i.length/t.length*100).toFixed(1)}% of traffic), ${r.length} gradeable`),r.length===0&&console.log(U.yellow(` Nothing in the skip region has been graded. Everything below describes
176
176
  only the decisions this policy chose NOT to skip \u2014 it cannot tell you
177
- what skipping would cost. Raise decisions.seats.<seat>.explore.`))),console.log(F.bold(`
178
- reliability (equal-width bins)`)),oo(n.bins.map(a=>({bin:`${a.lo.toFixed(2)}\u2013${a.hi.toFixed(2)}`,n:a.n,claimed:a.meanConfidence.toFixed(3),actual:a.accuracy.toFixed(3),gap:(a.accuracy-a.meanConfidence).toFixed(3)})),!1),o.close()});Pe.command("recalibrate").description("is one global temperature enough, or does calibration differ by group?").option("--path <file>","store path",Ge).requiredOption("--seat <seat>").option("--question <name>").option("--since <window>").option("--by <names>","comma-separated covariates","agent,question").option("--folds <n>","cross-validation folds","5").option("--min-n <n>","default 100","100").option("--json").action(e=>{let o=to(e),t=o.gradedRows(Ts(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=Ci(t,{covariates:n},{folds:Number(e.folds),minN:Number(e.minN)});if(e.json){console.log(JSON.stringify(s,null,2)),o.close();return}if(s.insufficient){console.log(F.yellow(` ${s.n} labeled rows, need ${s.minN}.`)),o.close();return}console.log(F.bold(`
179
- ${e.seat} \u2014 held-out comparison (${s.folds}-fold, n=${s.n})`)),console.log(F.dim(` Cross-validated, because more parameters always fit training data better.
180
- `)),oo(s.scores.map(i=>({model:i.name,logLoss:i.logLoss.toFixed(4),brier:i.brier.toFixed(4),best:i.name===s.best?"<-":""})),!1),s.best==="covariate"?(console.log(F.green(`
181
- Calibration differs by ${n.join("/")} \u2014 a single temperature averages groups`)),console.log(F.dim(" that need different corrections."))):s.best==="temperature"?console.log(F.dim(`
182
- One global temperature is enough. ${n.join("/")} carries no calibration signal here.`)):console.log(F.dim(`
183
- Neither correction beats the raw confidence out of sample. Leave it alone.`)),o.close()});Pe.command("coverage").description("accuracy at each threshold against the traffic it keeps \u2014 read this to pick one").option("--path <file>","store path",Ge).requiredOption("--seat <seat>").option("--question <name>").option("--since <window>").option("--explored","only rows the policy wanted to skip").option("--steps <n>","default 20","20").option("--json").action(e=>{let o=to(e),t=o.gradedRows({...Ts(e),labeledOnly:!0}),n=ji(t,Number(e.steps));if(n.length===0){console.log(F.yellow(` No labeled rows for seat "${e.seat}".`)),o.close();return}oo(n.map(s=>({threshold:s.threshold.toFixed(2),coverage:`${(s.coverage*100).toFixed(1)}%`,accuracy:`${(s.accuracy*100).toFixed(1)}%`,n:s.n})),e.json),o.close()});Pe.command("consistency").description("does the question hold still? resample one recorded state N times").option("--path <file>","store path",Ge).requiredOption("--seat <seat>").option("--backend <name>","default: the backend that recorded the row").option("--model <id>").option("--call <id>","a specific call id; default is the newest with stored state").option("-n, --samples <n>","default 15","15").option("--json").action(async e=>{Go();let o=to(e),t=o.db.prepare(`SELECT id, backend, model, state_json, questions_json FROM decision_calls
177
+ what skipping would cost. Raise decisions.seats.<seat>.explore.`))),console.log(U.bold(`
178
+ reliability (equal-width bins)`)),to(n.bins.map(a=>({bin:`${a.lo.toFixed(2)}\u2013${a.hi.toFixed(2)}`,n:a.n,claimed:a.meanConfidence.toFixed(3),actual:a.accuracy.toFixed(3),gap:(a.accuracy-a.meanConfidence).toFixed(3)})),!1),o.close()});Pe.command("recalibrate").description("is one global temperature enough, or does calibration differ by group?").option("--path <file>","store path",ze).requiredOption("--seat <seat>").option("--question <name>").option("--since <window>").option("--by <names>","comma-separated covariates","agent,question").option("--folds <n>","cross-validation folds","5").option("--min-n <n>","default 100","100").option("--json").action(e=>{let o=no(e),t=o.gradedRows(Ws(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=Wi(t,{covariates:n},{folds:Number(e.folds),minN:Number(e.minN)});if(e.json){console.log(JSON.stringify(s,null,2)),o.close();return}if(s.insufficient){console.log(U.yellow(` ${s.n} labeled rows, need ${s.minN}.`)),o.close();return}console.log(U.bold(`
179
+ ${e.seat} \u2014 held-out comparison (${s.folds}-fold, n=${s.n})`)),console.log(U.dim(` Cross-validated, because more parameters always fit training data better.
180
+ `)),to(s.scores.map(i=>({model:i.name,logLoss:i.logLoss.toFixed(4),brier:i.brier.toFixed(4),best:i.name===s.best?"<-":""})),!1),s.best==="covariate"?(console.log(U.green(`
181
+ Calibration differs by ${n.join("/")} \u2014 a single temperature averages groups`)),console.log(U.dim(" that need different corrections."))):s.best==="temperature"?console.log(U.dim(`
182
+ One global temperature is enough. ${n.join("/")} carries no calibration signal here.`)):console.log(U.dim(`
183
+ Neither correction beats the raw confidence out of sample. Leave it alone.`)),o.close()});Pe.command("coverage").description("accuracy at each threshold against the traffic it keeps \u2014 read this to pick one").option("--path <file>","store path",ze).requiredOption("--seat <seat>").option("--question <name>").option("--since <window>").option("--explored","only rows the policy wanted to skip").option("--steps <n>","default 20","20").option("--json").action(e=>{let o=no(e),t=o.gradedRows({...Ws(e),labeledOnly:!0}),n=Ui(t,Number(e.steps));if(n.length===0){console.log(U.yellow(` No labeled rows for seat "${e.seat}".`)),o.close();return}to(n.map(s=>({threshold:s.threshold.toFixed(2),coverage:`${(s.coverage*100).toFixed(1)}%`,accuracy:`${(s.accuracy*100).toFixed(1)}%`,n:s.n})),e.json),o.close()});Pe.command("consistency").description("does the question hold still? resample one recorded state N times").option("--path <file>","store path",ze).requiredOption("--seat <seat>").option("--backend <name>","default: the backend that recorded the row").option("--model <id>").option("--call <id>","a specific call id; default is the newest with stored state").option("-n, --samples <n>","default 15","15").option("--json").action(async e=>{Vo();let o=no(e),t=o.db.prepare(`SELECT id, backend, model, state_json, questions_json FROM decision_calls
184
184
  WHERE seat = ? AND state_json IS NOT NULL AND error IS NULL
185
185
  ${e.call?"AND id = ?":""}
186
- ORDER BY ts DESC LIMIT 1`).get(...e.call?[e.seat,e.call]:[e.seat]);if(!t){console.log(F.yellow(` No recorded call with stored state for seat "${e.seat}".`)),console.log(F.dim(" State is kept for the first `keepStateRows` per seat; see decisions.redactState.")),o.close();return}let n=e.backend??t.backend,s=e.model??(n===t.backend?t.model:void 0),i=await Ti(n,JSON.parse(t.state_json),JSON.parse(t.questions_json),{samples:Number(e.samples),model:s});if(e.json){console.log(JSON.stringify(i,null,2)),o.close();return}console.log(F.bold(`
187
- ${e.seat} on ${i.backend} (${i.model})`)),console.log(F.dim(` ${i.samples} samples of call ${t.id}, ${i.totalMs}ms, ${i.usage.inputTokens.toLocaleString()} input tokens
188
- `)),oo(i.questions.map(r=>({question:r.question,mean:r.mean.toFixed(4),stdev:r.stdev.toFixed(4),min:r.min.toFixed(3),max:r.max.toFixed(3),answers:r.distinctAnswers.join("/"),band:r.bands.join("/"),stable:r.crossesThreshold?F.red("NO"):"yes"})),!1),console.log(`
189
- mean stdev ${i.meanStdev.toFixed(4)}`),console.log(F.dim(" TypeSafe publish 0.0102 for jev across a 14-question rubric, as a reference.")),i.unstable.length>0?(console.log(F.red(`
190
- Unstable: ${i.unstable.join(", ")} \u2014 identical calls disagree about what to DO,`)),console.log(F.dim(` not merely by how much. Usually a compound question: one name, several questions.
191
- Split it, or narrow it to a single clause in the state's own vocabulary.`))):console.log(F.green(`
192
- Every question held its decision across all samples.`)),console.log(F.dim("\n Stability is not correctness. A question can hold perfectly still and be\n perfectly wrong \u2014 that is what `decisions calibrate` is for.")),o.close()});Pe.command("backends").description("registered decision backends and what they claim").action(()=>{Go();let e=Si().map(o=>{let t=is(o).capabilities;return{backend:o,source:t.probabilitySource,calibrated:t.calibratedProbabilities?"yes":"no",maxOptions:t.maxChoiceOptions,maxStateChars:t.maxStateChars}});oo(e,!1),console.log(F.dim(`
186
+ ORDER BY ts DESC LIMIT 1`).get(...e.call?[e.seat,e.call]:[e.seat]);if(!t){console.log(U.yellow(` No recorded call with stored state for seat "${e.seat}".`)),console.log(U.dim(" State is kept for the first `keepStateRows` per seat; see decisions.redactState.")),o.close();return}let n=e.backend??t.backend,s=e.model??(n===t.backend?t.model:void 0),i=await Bi(n,JSON.parse(t.state_json),JSON.parse(t.questions_json),{samples:Number(e.samples),model:s});if(e.json){console.log(JSON.stringify(i,null,2)),o.close();return}console.log(U.bold(`
187
+ ${e.seat} on ${i.backend} (${i.model})`)),console.log(U.dim(` ${i.samples} samples of call ${t.id}, ${i.totalMs}ms, ${i.usage.inputTokens.toLocaleString()} input tokens
188
+ `)),to(i.questions.map(r=>({question:r.question,mean:r.mean.toFixed(4),stdev:r.stdev.toFixed(4),min:r.min.toFixed(3),max:r.max.toFixed(3),answers:r.distinctAnswers.join("/"),band:r.bands.join("/"),stable:r.crossesThreshold?U.red("NO"):"yes"})),!1),console.log(`
189
+ mean stdev ${i.meanStdev.toFixed(4)}`),console.log(U.dim(" TypeSafe publish 0.0102 for jev across a 14-question rubric, as a reference.")),i.unstable.length>0?(console.log(U.red(`
190
+ Unstable: ${i.unstable.join(", ")} \u2014 identical calls disagree about what to DO,`)),console.log(U.dim(` not merely by how much. Usually a compound question: one name, several questions.
191
+ Split it, or narrow it to a single clause in the state's own vocabulary.`))):console.log(U.green(`
192
+ Every question held its decision across all samples.`)),console.log(U.dim("\n Stability is not correctness. A question can hold perfectly still and be\n perfectly wrong \u2014 that is what `decisions calibrate` is for.")),o.close()});Pe.command("backends").description("registered decision backends and what they claim").action(()=>{Vo();let e=Pi().map(o=>{let t=hs(o).capabilities;return{backend:o,source:t.probabilitySource,calibrated:t.calibratedProbabilities?"yes":"no",maxOptions:t.maxChoiceOptions,maxStateChars:t.maxStateChars}});to(e,!1),console.log(U.dim(`
193
193
  source where the numbers come from. "verbalized" means the model wrote them
194
194
  into its answer; "logits" means they were read off its next-token
195
195
  distribution. Logits are the model's actual posterior \u2014 verbalized
@@ -197,15 +197,15 @@ The AgentX daemon and a speech transcription backend must also be available. Run
197
197
  calibrated whether an answer given 0.8 is right about 80% of the time ON YOUR
198
198
  traffic. Reading real logits does not buy this: a posterior can be
199
199
  confidently wrong. It comes from a recalibrator fitted on your own
200
- labeled rows \u2014 see \`agentx decisions recalibrate\`.`))});Pe.command("ask").description("one-off smoke test against a backend (does not record)").requiredOption("--state <text>","the state to evaluate").option("--backend <name>","default mock","mock").option("--model <id>").option("--choice <labels>","comma-separated options for a choice question").option("--noul <question>","a yes/no question").action(async e=>{Go();let o={};if(e.choice){let s={};for(let i of String(e.choice).split(",").map(r=>r.trim()))i&&(s[i]=null);o.answer=Ho(s,"Which option fits this state?")}e.noul&&(o.verdict=io(String(e.noul))),Object.keys(o).length===0&&(console.log(F.red(" Give at least one of --choice or --noul.")),process.exit(1));let n=await is(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as bd}from"commander";import j from"chalk";import{resolve as wa}from"path";import{existsSync as $d}from"fs";import kd from"better-sqlite3";var Mt=new bd().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function Rs(e){let o=wa(e.cwd??process.cwd()),t=wa(o,e.path??".agentx/db.sqlite");$d(t)||(console.log(j.red(` No db at ${t}`)),console.log(j.dim(" The file is created on first SQLite write \u2014 start the daemon and run a task.")),process.exit(1));try{return new kd(t,{readonly:!0})}catch(n){console.log(j.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(j.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function vd(e){let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!o)return null;let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function xd(e){if(!e)return;let o=vd(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(j.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}function Sd(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s ago`:o<3600?`${Math.round(o/60)}m ago`:o<86400?`${Math.round(o/3600)}h ago`:`${Math.round(o/86400)}d ago`}function Ns(e){return e==="ok"?j.green:e==="error"||e==="timeout"?j.red:e==="in-flight"?j.yellow:j.dim}Mt.command("list").description("list recent traces (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--agent <id>","filter by agentId").option("--channel <name>","filter by channel (telegram|whatsapp|gitlab|...)").option("--chat <id>","filter by chatId").option("--workflow <runId>","filter by workflowRunId").option("--status <s>","filter by status (in-flight|ok|error|timeout)").option("--since <duration>","limit to traces newer than (e.g. 1h, 24h, 7d)").option("--limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=Rs(e),t=Yi(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:xd(e.since),limit:parseInt(e.limit,10)||50});if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(j.dim(" (no traces)"));return}for(let n of t){let s=Ns(n.status)(n.status.padEnd(9)),i=n.durationMs!=null?`${(n.durationMs/1e3).toFixed(2)}s`:"\u2014",r=n.workflowRunId?j.cyan(` wf=${n.workflowRunId}`):"",a=n.inputTokens!=null?j.dim(` ${n.inputTokens}/${n.outputTokens??0} tok`):"";console.log(`${j.dim(n.taskId)} ${s} ${j.bold(n.agentId)}${j.dim(` ${n.channel??"\u2014"}:${n.chatId??"\u2014"}`)}${r} ${j.dim("\xB7")} ${i}${a} ${j.dim(Sd(n.startedAt))}`),n.error&&console.log(` ${j.red("error:")} ${n.error}`)}});Mt.command("show <taskId>").description("show one trace with its full ordered step log").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--json","emit JSON").action((e,o)=>{let t=Rs(o),n=ls(t,e);if(n||(console.log(j.red(` No trace at ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}Ed(n.task,n.steps)});function Ed(e,o){let t=Ns(e.status)(e.status);if(console.log(j.bold(`Trace ${e.taskId}`)),console.log(` ${j.dim("agent")} ${e.agentId}`),console.log(` ${j.dim("channel")} ${e.channel??"\u2014"}:${e.chatId??"\u2014"}`),e.workflowRunId){let n=[e.workflowId,e.workflowNodeId].filter(Boolean).join("/");console.log(` ${j.dim("workflow")} ${j.cyan(e.workflowRunId)}${n?j.dim(` (${n})`):""}`)}if(e.intentEventId&&console.log(` ${j.dim("intent")} ${e.intentEventId} ${j.dim(`(${e.intentDecidedBy??"?"})`)}`),e.model&&console.log(` ${j.dim("model")} ${e.model}`),e.resumeSessionId&&console.log(` ${j.dim("resume")} ${e.resumeSessionId.slice(0,12)}\u2026`),e.finalSessionId&&console.log(` ${j.dim("final")} ${e.finalSessionId.slice(0,12)}\u2026`),console.log(` ${j.dim("status")} ${t}`),e.durationMs!=null&&console.log(` ${j.dim("duration")} ${(e.durationMs/1e3).toFixed(2)}s`),(e.inputTokens!=null||e.outputTokens!=null)&&console.log(` ${j.dim("tokens")} in=${e.inputTokens??0} out=${e.outputTokens??0} cache_read=${e.cacheReadTokens??0} cache_create=${e.cacheCreateTokens??0}`),e.error&&console.log(` ${j.red("error")} ${e.error}`),e.messagePreview&&console.log(` ${j.dim("message")} ${e.messagePreview}`),console.log(),o.length===0){console.log(j.dim(" (no recorded steps \u2014 task may have been on a non-streaming tier or completed before any tool call)"));return}console.log(j.bold(`Steps (${o.length}):`));for(let n of o){let s=n.status?Ns(n.status)(n.status):j.dim("\u2014"),i=n.action?j.cyan(n.action):"";if(console.log(` ${j.dim(`#${n.seq}`)} ${j.bold(n.name)}${i?" "+i:""} ${s}${n.ms!=null?j.dim(` ${n.ms}ms`):""}`),n.inputSummary){let r=n.inputSummary.split(`
201
- `).slice(0,8);console.log(r.map(a=>` ${j.dim("\u2192")} ${a}`).join(`
200
+ labeled rows \u2014 see \`agentx decisions recalibrate\`.`))});Pe.command("ask").description("one-off smoke test against a backend (does not record)").requiredOption("--state <text>","the state to evaluate").option("--backend <name>","default mock","mock").option("--model <id>").option("--choice <labels>","comma-separated options for a choice question").option("--noul <question>","a yes/no question").action(async e=>{Vo();let o={};if(e.choice){let s={};for(let i of String(e.choice).split(",").map(r=>r.trim()))i&&(s[i]=null);o.answer=Yo(s,"Which option fits this state?")}e.noul&&(o.verdict=ao(String(e.noul))),Object.keys(o).length===0&&(console.log(U.red(" Give at least one of --choice or --noul.")),process.exit(1));let n=await hs(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as Md}from"commander";import I from"chalk";import{resolve as Ta}from"path";import{existsSync as Fd}from"fs";import Ud from"better-sqlite3";var Wt=new Md().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function Js(e){let o=Ta(e.cwd??process.cwd()),t=Ta(o,e.path??".agentx/db.sqlite");Fd(t)||(console.log(I.red(` No db at ${t}`)),console.log(I.dim(" The file is created on first SQLite write \u2014 start the daemon and run a task.")),process.exit(1));try{return new Ud(t,{readonly:!0})}catch(n){console.log(I.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(I.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function qd(e){let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!o)return null;let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function Wd(e){if(!e)return;let o=qd(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(I.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}function Bd(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s ago`:o<3600?`${Math.round(o/60)}m ago`:o<86400?`${Math.round(o/3600)}h ago`:`${Math.round(o/86400)}d ago`}function Bs(e){return e==="ok"?I.green:e==="error"||e==="timeout"?I.red:e==="in-flight"?I.yellow:I.dim}Wt.command("list").description("list recent traces (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--agent <id>","filter by agentId").option("--channel <name>","filter by channel (telegram|whatsapp|gitlab|...)").option("--chat <id>","filter by chatId").option("--workflow <runId>","filter by workflowRunId").option("--status <s>","filter by status (in-flight|ok|error|timeout)").option("--since <duration>","limit to traces newer than (e.g. 1h, 24h, 7d)").option("--limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=Js(e),t=rr(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:Wd(e.since),limit:parseInt(e.limit,10)||50});if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(I.dim(" (no traces)"));return}for(let n of t){let s=Bs(n.status)(n.status.padEnd(9)),i=n.durationMs!=null?`${(n.durationMs/1e3).toFixed(2)}s`:"\u2014",r=n.workflowRunId?I.cyan(` wf=${n.workflowRunId}`):"",a=n.inputTokens!=null?I.dim(` ${n.inputTokens}/${n.outputTokens??0} tok`):"";console.log(`${I.dim(n.taskId)} ${s} ${I.bold(n.agentId)}${I.dim(` ${n.channel??"\u2014"}:${n.chatId??"\u2014"}`)}${r} ${I.dim("\xB7")} ${i}${a} ${I.dim(Bd(n.startedAt))}`),n.error&&console.log(` ${I.red("error:")} ${n.error}`)}});Wt.command("show <taskId>").description("show one trace with its full ordered step log").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--json","emit JSON").action((e,o)=>{let t=Js(o),n=$s(t,e);if(n||(console.log(I.red(` No trace at ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}Jd(n.task,n.steps)});function Jd(e,o){let t=Bs(e.status)(e.status);if(console.log(I.bold(`Trace ${e.taskId}`)),console.log(` ${I.dim("agent")} ${e.agentId}`),console.log(` ${I.dim("channel")} ${e.channel??"\u2014"}:${e.chatId??"\u2014"}`),e.workflowRunId){let n=[e.workflowId,e.workflowNodeId].filter(Boolean).join("/");console.log(` ${I.dim("workflow")} ${I.cyan(e.workflowRunId)}${n?I.dim(` (${n})`):""}`)}if(e.intentEventId&&console.log(` ${I.dim("intent")} ${e.intentEventId} ${I.dim(`(${e.intentDecidedBy??"?"})`)}`),e.model&&console.log(` ${I.dim("model")} ${e.model}`),e.resumeSessionId&&console.log(` ${I.dim("resume")} ${e.resumeSessionId.slice(0,12)}\u2026`),e.finalSessionId&&console.log(` ${I.dim("final")} ${e.finalSessionId.slice(0,12)}\u2026`),console.log(` ${I.dim("status")} ${t}`),e.durationMs!=null&&console.log(` ${I.dim("duration")} ${(e.durationMs/1e3).toFixed(2)}s`),(e.inputTokens!=null||e.outputTokens!=null)&&console.log(` ${I.dim("tokens")} in=${e.inputTokens??0} out=${e.outputTokens??0} cache_read=${e.cacheReadTokens??0} cache_create=${e.cacheCreateTokens??0}`),e.error&&console.log(` ${I.red("error")} ${e.error}`),e.messagePreview&&console.log(` ${I.dim("message")} ${e.messagePreview}`),console.log(),o.length===0){console.log(I.dim(" (no recorded steps \u2014 task may have been on a non-streaming tier or completed before any tool call)"));return}console.log(I.bold(`Steps (${o.length}):`));for(let n of o){let s=n.status?Bs(n.status)(n.status):I.dim("\u2014"),i=n.action?I.cyan(n.action):"";if(console.log(` ${I.dim(`#${n.seq}`)} ${I.bold(n.name)}${i?" "+i:""} ${s}${n.ms!=null?I.dim(` ${n.ms}ms`):""}`),n.inputSummary){let r=n.inputSummary.split(`
201
+ `).slice(0,8);console.log(r.map(a=>` ${I.dim("\u2192")} ${a}`).join(`
202
202
  `)),n.inputSummary.split(`
203
- `).length>8&&console.log(` ${j.dim("\u2026")}`)}if(n.outputSummary){let r=n.outputSummary.split(`
204
- `).slice(0,8);console.log(r.map(a=>` ${j.dim("\u2190")} ${a}`).join(`
203
+ `).length>8&&console.log(` ${I.dim("\u2026")}`)}if(n.outputSummary){let r=n.outputSummary.split(`
204
+ `).slice(0,8);console.log(r.map(a=>` ${I.dim("\u2190")} ${a}`).join(`
205
205
  `)),n.outputSummary.split(`
206
- `).length>8&&console.log(` ${j.dim("\u2026")}`)}n.error&&console.log(` ${j.red("error:")} ${n.error}`)}}Mt.command("replay <taskId>").description("re-run a recorded task against the current agent config (handoff item #11)").option("--cwd <dir>","project root",process.cwd()).option("--path <p>","sqlite db path (relative to --cwd)",".agentx/db.sqlite").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--diff","show original input + output vs new output side-by-side").option("--no-fresh","do NOT freshSession (default is fresh \u2014 required for clean replay)").action(async(e,o)=>{let t=Rs(o),n=ls(t,e);n||(console.log(j.red(` task not found: ${e}`)),console.log(j.dim(" agentx trace list \u2014 see what's available")),process.exit(1));let s=n.task,i=s.originalMessage??s.messagePreview;i||(console.log(j.red(` task ${e} has no recorded input message \u2014 cannot replay`)),process.exit(1)),!s.originalMessage&&s.messagePreview!=null&&console.log(j.yellow(" \u26A0 pre-migration-v8 row: input message was capped at 200 chars; replay uses the preview")),console.log(),console.log(j.bold(` replay ${j.cyan(e)}`)),console.log(j.dim(` agent=${s.agentId} channel=${s.channel??"\u2014"} chatId=${s.chatId??"\u2014"}`)),console.log(j.dim(` original status=${s.status} duration=${s.durationMs??"?"}ms tokens=in:${s.inputTokens??0}/out:${s.outputTokens??0}`)),console.log();let a=String(o.daemon).replace(/\/+$/,""),c={agent:s.agentId,message:i,freshSession:o.fresh!==!1,context:{channel:s.channel??"api",chatId:`replay-${e.toLowerCase().slice(-8)}-${Date.now().toString(36)}`}},d=Date.now(),g;try{g=await fetch(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})}catch(f){console.log(j.red(` daemon unreachable at ${a}: ${f.message||f}`)),process.exit(1)}let l=await g.json().catch(()=>({})),p=Date.now()-d;if(g.ok||(console.log(j.red(` replay failed (${g.status}): ${l.error||"unknown error"}`)),process.exit(1)),o.diff){console.log(j.bold(" INPUT (replayed verbatim)")),console.log(),On(i),console.log(),console.log(j.bold(` ORIGINAL OUTPUT ${j.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?On(s.finalResponse):console.log(j.yellow(" (not captured \u2014 pre-migration-v8 row, or response was empty)")),console.log(),console.log(j.bold(` CURRENT OUTPUT ${j.dim(`status=${l.error?"error":"ok"} ${p}ms tokens=in:${l.usage?.inputTokens??0}/out:${l.usage?.outputTokens??0}`)}`)),console.log(),On(l.content??"(empty reply)"),l.error&&console.log(j.red(` error: ${l.error}`)),console.log();let f=(s.finalResponse??"").trim()===(l.content??"").trim();s.finalResponse&&(console.log(f?j.dim(" outputs are identical"):j.yellow(" outputs differ \u2014 read both blocks to see what changed")),console.log())}else console.log(j.green(` \u2713 replayed in ${p}ms`)),console.log(),On(l.content??"(empty reply)"),l.error&&console.log(j.red(`
207
- error: ${l.error}`)),console.log(),console.log(j.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function On(e){let o=e.split(`
208
- `),t=60,n=o.slice(0,t);for(let s of n)console.log(` ${j.dim("\u2502")} ${s}`);o.length>t&&console.log(` ${j.dim("\u2502")} ${j.dim(`\u2026+${o.length-t} more lines`)}`)}import{Command as Id}from"commander";import ce from"chalk";import{existsSync as Cd,mkdirSync as Td,writeFileSync as Nd}from"fs";import{resolve as ka,join as $a,dirname as Rd}from"path";var Ad=`# AgentX destructive-action guardrails \u2014 global policy
206
+ `).length>8&&console.log(` ${I.dim("\u2026")}`)}n.error&&console.log(` ${I.red("error:")} ${n.error}`)}}Wt.command("replay <taskId>").description("re-run a recorded task against the current agent config (handoff item #11)").option("--cwd <dir>","project root",process.cwd()).option("--path <p>","sqlite db path (relative to --cwd)",".agentx/db.sqlite").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--diff","show original input + output vs new output side-by-side").option("--no-fresh","do NOT freshSession (default is fresh \u2014 required for clean replay)").action(async(e,o)=>{let t=Js(o),n=$s(t,e);n||(console.log(I.red(` task not found: ${e}`)),console.log(I.dim(" agentx trace list \u2014 see what's available")),process.exit(1));let s=n.task,i=s.originalMessage??s.messagePreview;i||(console.log(I.red(` task ${e} has no recorded input message \u2014 cannot replay`)),process.exit(1)),!s.originalMessage&&s.messagePreview!=null&&console.log(I.yellow(" \u26A0 pre-migration-v8 row: input message was capped at 200 chars; replay uses the preview")),console.log(),console.log(I.bold(` replay ${I.cyan(e)}`)),console.log(I.dim(` agent=${s.agentId} channel=${s.channel??"\u2014"} chatId=${s.chatId??"\u2014"}`)),console.log(I.dim(` original status=${s.status} duration=${s.durationMs??"?"}ms tokens=in:${s.inputTokens??0}/out:${s.outputTokens??0}`)),console.log();let a=String(o.daemon).replace(/\/+$/,""),c={agent:s.agentId,message:i,freshSession:o.fresh!==!1,context:{channel:s.channel??"api",chatId:`replay-${e.toLowerCase().slice(-8)}-${Date.now().toString(36)}`}},d=Date.now(),g;try{g=await fetch(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})}catch(f){console.log(I.red(` daemon unreachable at ${a}: ${f.message||f}`)),process.exit(1)}let l=await g.json().catch(()=>({})),p=Date.now()-d;if(g.ok||(console.log(I.red(` replay failed (${g.status}): ${l.error||"unknown error"}`)),process.exit(1)),o.diff){console.log(I.bold(" INPUT (replayed verbatim)")),console.log(),Dn(i),console.log(),console.log(I.bold(` ORIGINAL OUTPUT ${I.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?Dn(s.finalResponse):console.log(I.yellow(" (not captured \u2014 pre-migration-v8 row, or response was empty)")),console.log(),console.log(I.bold(` CURRENT OUTPUT ${I.dim(`status=${l.error?"error":"ok"} ${p}ms tokens=in:${l.usage?.inputTokens??0}/out:${l.usage?.outputTokens??0}`)}`)),console.log(),Dn(l.content??"(empty reply)"),l.error&&console.log(I.red(` error: ${l.error}`)),console.log();let f=(s.finalResponse??"").trim()===(l.content??"").trim();s.finalResponse&&(console.log(f?I.dim(" outputs are identical"):I.yellow(" outputs differ \u2014 read both blocks to see what changed")),console.log())}else console.log(I.green(` \u2713 replayed in ${p}ms`)),console.log(),Dn(l.content??"(empty reply)"),l.error&&console.log(I.red(`
207
+ error: ${l.error}`)),console.log(),console.log(I.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function Dn(e){let o=e.split(`
208
+ `),t=60,n=o.slice(0,t);for(let s of n)console.log(` ${I.dim("\u2502")} ${s}`);o.length>t&&console.log(` ${I.dim("\u2502")} ${I.dim(`\u2026+${o.length-t} more lines`)}`)}import{Command as Yd}from"commander";import ce from"chalk";import{existsSync as Vd,mkdirSync as Kd,writeFileSync as Xd}from"fs";import{resolve as Ca,join as ja,dirname as Qd}from"path";var Gd=`# AgentX destructive-action guardrails \u2014 global policy
209
209
  #
210
210
  # This file + environments/*.yaml + agents/<id>.yaml are deep-merged
211
211
  # (most specific wins). The built-in catalog (prisma / rm -rf / docker /
@@ -231,7 +231,7 @@ defaults:
231
231
  # action: escalate
232
232
  # severity: high
233
233
  rules: []
234
- `,Od=`# Production protected resources.
234
+ `,Hd=`# Production protected resources.
235
235
  #
236
236
  # The catalog rules reference \`target_in: production\`, so DECLARING this set is
237
237
  # what arms them. \`resolve_env: true\` expands $VAR / \${VAR} and reads .env* in
@@ -253,7 +253,7 @@ protected_resources:
253
253
 
254
254
  # Production-only rules beyond the catalog:
255
255
  rules: []
256
- `,jd=`# Per-agent override for coder-agent. Top-level rules here are auto-scoped to
256
+ `,zd=`# Per-agent override for coder-agent. Top-level rules here are auto-scoped to
257
257
  # this agent (the filename names it). coder agents never touch production.
258
258
  rules:
259
259
  - id: coder-no-prod
@@ -262,7 +262,7 @@ rules:
262
262
  action: deny
263
263
  severity: critical
264
264
  message: "coder-agent is not permitted to run commands against production."
265
- `,ba=[{relPath:"policy.yaml",content:Ad},{relPath:"environments/production.yaml",content:Od},{relPath:"agents/coder-agent.yaml",content:jd}];var ko=new Id().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function _s(e){return e==="deny"?ce.red:e==="escalate"||e==="ask"?ce.yellow:e==="warn"?ce.magenta:ce.green}function jn(e){return e.root?ka(e.root):wr()}ko.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 yr({root:jn(e),agentId:e.agent,env:e.env}),process.exit(0)});ko.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=jn(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=hr({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}_d(s,i,r)});function _d(e,o,t){let n=_s(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":ce.dim(" (no rule matched)")}`),console.log(` enforced as ${_s(e.effectiveAction)(e.effectiveAction)} ${ce.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${ce.cyan(e.ruleId)}${e.severity?ce.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${ce.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${ce.dim(`evaluated in ${t}ms`)}`),console.log()}ko.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=fr({root:jn(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(ce.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=_s(t.verdict),i=t.effective_action!==t.verdict?ce.dim(`->${t.effective_action}`):"";console.log(` ${ce.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${ce.cyan((t.agent_id??"?").padEnd(16))} ${ce.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(ce.dim(` target: ${t.resolved_target}`))}});ko.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=$a(ka(e.root),pr),t=0;for(let n of ba){let s=$a(o,n.relPath);if(Cd(s)&&!e.force){console.log(ce.dim(` skip (exists) ${n.relPath}`));continue}Td(Rd(s),{recursive:!0}),Nd(s,n.content),console.log(ce.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${ce.cyan(o)}`),console.log(ce.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(ce.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});ko.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(ce.green(` daemon reloaded (${e.url})`)):console.log(ce.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(ce.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});ko.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=ur(jn(e),e.agent);console.log(JSON.stringify(o,null,2))});Et();import{Command as Dd}from"commander";import{execFile as Pd}from"child_process";import{promisify as Ld}from"util";import{existsSync as Md}from"fs";import ze from"chalk";St();var Ft="ui-element";function In(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:Ut(t.tried,80),screenChanged:t.changed,note:t.note?Ut(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:va(t.role),label:Ut(t.label,120),value:t.value?Ut(t.value,80):null,enabled:t.enabled}))}}function Cn(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${va(t.role)}: ${Ut(n,80)}`}return{target:Ho(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:io("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 Tn(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 va(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Ut(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}var xa=Ld(Pd),Sa=new Dd().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").action(async(e,o)=>{Md(Ee)||(console.log(ze.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await un({max:Number(o.max)||40})}catch(l){console.log(ze.red(` could not read the screen: ${l?.message??l}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(ze.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let l=Ct(t,n[0].id);l&&(console.log(ze.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+ze.bold(n[0].label)),await xa(Ee,["point","--x",String(l.x),"--y",String(l.y),"--w",String(l.width),"--h",String(l.height),"--label",n[0].label]));return}let s=await Xe(Ft,In({request:e,app:t.app,window:t.window,candidates:n}),Cn(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(ze.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${Ft}.mode`)),process.exit(1));let i=Tn(s.answers,n),r=Ct(t,i.id),a=n.find(l=>l.id===i.id)?.label??"",c=t.ocrRects.has(i.id),d=Number(o.minPresent)||.5;if((i.present<d||!r)&&(console.log(ze.yellow(` nothing on screen matches "${e}"`)+ze.dim(` (P(exists)=${i.present.toFixed(2)} below ${d})`)),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(l=>({...l,label:n.find(p=>p.id===l.id)?.label}))},null,2));return}let g=a;console.log(` ${ze.green("\u2192")} ${ze.bold(g)} `+ze.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await xa(Ee,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",g])});import{Command as dg}from"commander";import Le from"chalk";import{execFile as Ud}from"child_process";import{promisify as Fd}from"util";import{existsSync as qd,readFileSync as Ds}from"fs";import{homedir as Wd,tmpdir as Bd}from"os";import{join as Ea}from"path";var Jd=Fd(Ud),Aa=12e5,Hd="https://openrouter.ai/api/v1/chat/completions",Gd=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function zd(e={kind:"window"},o=Aa){if(!qd(Ee))throw new Error("helper not built \u2014 run apps/mac-helper/build.sh");let n=["capture","--out",Ea(Bd(),`agentx-look-${Date.now()}.png`),"--max-pixels",String(o)];e.kind==="menubar"&&n.push("--menubar"),e.kind==="screen"&&n.push("--screen-full"),(e.kind==="screen"||e.kind==="menubar")&&e.index!==void 0&&n.push("--screen",String(e.index)),e.kind==="rect"&&n.push("--x",String(e.x),"--y",String(e.y),"--w",String(e.width),"--h",String(e.height));let s=await Jd(Ee,n).then(a=>a.stdout,a=>{if(typeof a?.stdout=="string"&&a.stdout.trim().startsWith("{"))return a.stdout;throw a}),i=JSON.parse(s);if(!i.ok)throw new Error(i.error??"capture failed");let r=Ds(i.path).length;return{path:i.path,region:{x:i.region.x,y:i.region.y,width:i.region.w,height:i.region.h},bytes:r}}var Yd=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
265
+ `,Ia=[{relPath:"policy.yaml",content:Gd},{relPath:"environments/production.yaml",content:Hd},{relPath:"agents/coder-agent.yaml",content:zd}];var xo=new Yd().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function Gs(e){return e==="deny"?ce.red:e==="escalate"||e==="ask"?ce.yellow:e==="warn"?ce.magenta:ce.green}function _n(e){return e.root?Ca(e.root):jr()}xo.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 Ir({root:_n(e),agentId:e.agent,env:e.env}),process.exit(0)});xo.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=_n(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=Tr({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}Zd(s,i,r)});function Zd(e,o,t){let n=Gs(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":ce.dim(" (no rule matched)")}`),console.log(` enforced as ${Gs(e.effectiveAction)(e.effectiveAction)} ${ce.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${ce.cyan(e.ruleId)}${e.severity?ce.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${ce.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${ce.dim(`evaluated in ${t}ms`)}`),console.log()}xo.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=Or({root:_n(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(ce.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=Gs(t.verdict),i=t.effective_action!==t.verdict?ce.dim(`->${t.effective_action}`):"";console.log(` ${ce.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${ce.cyan((t.agent_id??"?").padEnd(16))} ${ce.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(ce.dim(` target: ${t.resolved_target}`))}});xo.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=ja(Ca(e.root),Er),t=0;for(let n of Ia){let s=ja(o,n.relPath);if(Vd(s)&&!e.force){console.log(ce.dim(` skip (exists) ${n.relPath}`));continue}Kd(Qd(s),{recursive:!0}),Xd(s,n.content),console.log(ce.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${ce.cyan(o)}`),console.log(ce.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(ce.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});xo.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(ce.green(` daemon reloaded (${e.url})`)):console.log(ce.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(ce.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});xo.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=Ar(_n(e),e.agent);console.log(JSON.stringify(o,null,2))});It();import{Command as eg}from"commander";import{execFile as og}from"child_process";import{promisify as tg}from"util";import{existsSync as ng}from"fs";import Ye from"chalk";Tt();var Jt="ui-element";function Pn(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:Bt(t.tried,80),screenChanged:t.changed,note:t.note?Bt(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:Na(t.role),label:Bt(t.label,120),value:t.value?Bt(t.value,80):null,enabled:t.enabled}))}}function Ln(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${Na(t.role)}: ${Bt(n,80)}`}return{target:Yo(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:ao("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 Mn(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 Na(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Bt(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}var Ra=tg(og),Da=new eg().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").action(async(e,o)=>{ng($e)||(console.log(Ye.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await bn({max:Number(o.max)||40})}catch(l){console.log(Ye.red(` could not read the screen: ${l?.message??l}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(Ye.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let l=Dt(t,n[0].id);l&&(console.log(Ye.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+Ye.bold(n[0].label)),await Ra($e,["point","--x",String(l.x),"--y",String(l.y),"--w",String(l.width),"--h",String(l.height),"--label",n[0].label]));return}let s=await Qe(Jt,Pn({request:e,app:t.app,window:t.window,candidates:n}),Ln(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(Ye.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${Jt}.mode`)),process.exit(1));let i=Mn(s.answers,n),r=Dt(t,i.id),a=n.find(l=>l.id===i.id)?.label??"",c=t.ocrRects.has(i.id),d=Number(o.minPresent)||.5;if((i.present<d||!r)&&(console.log(Ye.yellow(` nothing on screen matches "${e}"`)+Ye.dim(` (P(exists)=${i.present.toFixed(2)} below ${d})`)),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(l=>({...l,label:n.find(p=>p.id===l.id)?.label}))},null,2));return}let g=a;console.log(` ${Ye.green("\u2192")} ${Ye.bold(g)} `+Ye.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await Ra($e,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",g])});import{Command as Ig}from"commander";import Le from"chalk";import{execFile as sg}from"child_process";import{promisify as ig}from"util";import{existsSync as rg,readFileSync as Hs}from"fs";import{homedir as ag,tmpdir as cg}from"os";import{join as _a}from"path";var lg=ig(sg),Pa=12e5,dg="https://openrouter.ai/api/v1/chat/completions",gg=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function mg(e={kind:"window"},o=Pa){if(!rg($e))throw new Error("helper not built \u2014 run apps/mac-helper/build.sh");let n=["capture","--out",_a(cg(),`agentx-look-${Date.now()}.png`),"--max-pixels",String(o)];e.kind==="menubar"&&n.push("--menubar"),e.kind==="screen"&&n.push("--screen-full"),(e.kind==="screen"||e.kind==="menubar")&&e.index!==void 0&&n.push("--screen",String(e.index)),e.kind==="rect"&&n.push("--x",String(e.x),"--y",String(e.y),"--w",String(e.width),"--h",String(e.height));let s=await lg($e,n).then(a=>a.stdout,a=>{if(typeof a?.stdout=="string"&&a.stdout.trim().startsWith("{"))return a.stdout;throw a}),i=JSON.parse(s);if(!i.ok)throw new Error(i.error??"capture failed");let r=Hs(i.path).length;return{path:i.path,region:{x:i.region.x,y:i.region.y,width:i.region.w,height:i.region.h},bytes:r}}var pg=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
266
266
 
267
267
  Report only what is visible in this image.
268
268
 
@@ -270,10 +270,10 @@ The failure that matters: an application that performs an action is on screen, a
270
270
 
271
271
  State indicators are usually small and specific: a coloured dot, a pill or badge in the menu bar, an elapsed timer, a filled or highlighted toggle, a progress bar, a changed icon. If the question turns on such an indicator, say whether you can see it and what it looks like.
272
272
 
273
- Answer "unclear" when the deciding detail is not in frame, too small to read, or covered. "unclear" is a useful answer. A confident guess is not.`;async function Vd(e,o,t,n){let s=Xd();if(!s)throw new Error("no OPENROUTER_API_KEY \u2014 looking at the screen needs a vision model (set it, or ~/.agentx/openrouter-key.txt)");let i=Ds(o.path).toString("base64"),r={model:t,max_tokens:700,messages:[{role:"user",content:[{type:"text",text:`Question: ${e}
273
+ Answer "unclear" when the deciding detail is not in frame, too small to read, or covered. "unclear" is a useful answer. A confident guess is not.`;async function ug(e,o,t,n){let s=hg();if(!s)throw new Error("no OPENROUTER_API_KEY \u2014 looking at the screen needs a vision model (set it, or ~/.agentx/openrouter-key.txt)");let i=Hs(o.path).toString("base64"),r={model:t,max_tokens:700,messages:[{role:"user",content:[{type:"text",text:`Question: ${e}
274
274
 
275
- The image is the region ${Kd(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:Yd,tools:[{type:"function",function:{name:"report",description:"Report what is visible and how it bears on the question",parameters:{type:"object",properties:{observation:{type:"string",description:"What is visible in the image, factually, in one or two sentences."},evidence:{type:"string",description:"The specific visible detail that decides the question \u2014 where it is and what it looks like. Empty string if no such detail is visible."},reading:{type:"string",enum:["yes","no","unclear"],description:"Answer to the question, or unclear if the pixels do not settle it."}},required:["observation","evidence","reading"]}}}],tool_choice:{type:"function",function:{name:"report"}}},a=new AbortController,c=setTimeout(()=>a.abort(),n),d;try{d=await fetch(Hd,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`,"HTTP-Referer":"https://github.com/acme/agentx","X-Title":"agentx"},body:JSON.stringify(r),signal:a.signal})}finally{clearTimeout(c)}if(!d.ok){let u=await d.text().catch(()=>"");throw new Error(`vision model ${d.status}: ${u.slice(0,300)}`)}let g=await d.json(),l=g?.choices?.[0]?.message?.tool_calls?.[0];if(!l?.function?.arguments)throw new Error("vision model returned no structured report");let p=JSON.parse(l.function.arguments),f=p.reading==="yes"||p.reading==="no"?p.reading:"unclear";return{observation:(p.observation??"").trim(),evidence:(p.evidence??"").trim(),reading:f,model:typeof g.model=="string"?g.model:t,usage:{inputTokens:g?.usage?.prompt_tokens??0,outputTokens:g?.usage?.completion_tokens??0}}}async function Nn(e,o={}){let t=Date.now(),n=await zd(o.region??{kind:"window"},o.maxPixels??Aa),s=await Vd(e,n,o.model??Gd,o.timeoutMs??45e3);return{question:e,observation:s.observation,evidence:s.evidence,reading:s.reading,shot:n,model:s.model,latencyMs:Date.now()-t,usage:s.usage}}function Kd(e){let{x:o,y:t,width:n,height:s}=e.region;return t<=1&&s<=40?"the macOS menu bar at the top of the screen":`x=${Math.round(o)} y=${Math.round(t)} ${Math.round(n)}x${Math.round(s)} points`}var qt;function Xd(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(qt!==void 0)return qt??void 0;try{let e=Ds(Ea(Wd(),".agentx","openrouter-key.txt"),"utf-8").trim();qt=e.length>0?e:null}catch{qt=null}return qt??void 0}import{execFile as Qd}from"child_process";import{promisify as Zd}from"util";var eg=Zd(Qd),og=["screencapture"],tg=["Screen Studio","OBS","QuickTime Player","Zoom"];async function ja(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await ng()),t}async function ng(){let e=await Oa(og);if(e.length)return{checked:"running screen-capture processes (pgrep)",found:`A screen capture is definitely in progress: ${e.join(", ")}. This process only exists while it is recording, so this settles the question on its own.`};let o=await Oa(tg);return o.length?{checked:"running screen-capture processes (pgrep)",found:`No standalone capture process. A recorder application IS open (${o.join(", ")}), but its process exists whether or not it is recording, so this neither confirms nor denies. macOS does not expose in-app recording state to this tool, and the menu bar indicator is about six points \u2014 measured as below what the vision models here resolve reliably. Unless something else settles it, this claim cannot be verified.`}:{checked:"running screen-capture processes (pgrep)",found:"No screen-capture process is running and no recorder application is open. Nothing that records the screen from outside an app is active."}}async function Oa(e){let o=[];for(let t of e)try{let{stdout:n}=await eg("pgrep",["-x",t]),s=n.trim().split(`
276
- `)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}Et();St();var Ia="screen-state",Ca={observable:io("The evidence gathered \u2014 the screenshot and the system checks together \u2014 is enough to settle the claim, either way.",{true:"Something in the evidence decides it. Either the observation names a specific visible detail that bears on the claim and was legible, or a system check directly establishes the claim true or false. A system check alone is sufficient: it does not need the image to agree with it, or the image to have shown anything at all.",false:"Nothing decides it. The deciding detail is not in frame, too small or blurred, or covered; the observation only describes context \u2014 which application is open, what the screen generally shows \u2014 without the detail itself; and no system check settles it either. Absence of evidence in a capture that could not have shown the evidence is not evidence of absence. This is also false when a check says the question is not answerable from a screenshot and the observation nonetheless claims to have seen it: that is a guess, however specific it sounds."}),holds:io("The claim is true of the screen right now.",{true:"The visible evidence shows the claimed state is in effect: the indicator is present, the text is there, the element is visible and unobstructed, the action has plainly already happened.",false:"The visible evidence shows the claimed state is NOT in effect. An application being open, capable of the action, or offering it, is not the action having happened \u2014 a recorder on screen is not a recording, an unpressed button is not a pressed one, an offered dialog is not a chosen one. A system check that directly contradicts the observation outweighs it: the checks are deterministic readings of the machine, the observation is a model's reading of an image."})};function Ta(e){return{claim:e.claim,capturedRegion:e.region,whatWasSeen:e.observation,decidingDetail:e.evidence||null,visionModelReading:e.reading,...e.treeNote?{accessibilityTree:e.treeNote}:{},...e.probes?.length?{systemChecks:e.probes}:{}}}function Na(e){return{observable:e.observable.noul,holds:e.holds.noul}}var sg=.6,ig=.7,rg=.3;async function Wt(e,o={}){let[t,n]=await Promise.all([Nn(e,o),ja(e).catch(()=>[])]),s=o.observableFloor??sg,i=await Xe(Ia,Ta({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:lg(t),treeNote:o.treeNote,probes:n}),Ca,{incumbent:{holds:t.reading==="yes"?1:0},features:{model:t.model,region:t.shot.region.height<=40?"menubar":"window"}});if(!i){let d=t.reading==="yes"?"confirmed":t.reading==="no"?"refuted":"unknown";return{claim:e,outcome:d,ok:d==="confirmed",observable:null,holds:null,calibrated:!1,reason:cg(d,t),sighting:t,probes:n}}let{observable:r,holds:a}=Na(i.answers);if(r<s)return{claim:e,outcome:"unknown",ok:!1,observable:r,holds:a,calibrated:!0,reason:`Could not tell from the screenshot or the system checks (${Rn(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=ig?"confirmed":a<=rg?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:ag(c,a,t),sighting:t,probes:n}}function ag(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${Rn(o)}). ${n}`:e==="refuted"?`Not true (${Rn(1-o)} it is false). ${n}`:`Inconclusive (${Rn(o)}, between the thresholds). ${n}`}function cg(e,o){let t=o.evidence||o.observation||"no specific detail",n=" \u2014 uncalibrated, the screen-state seat is off";return e==="unknown"?`Could not tell${n}. ${t}`:`${e==="confirmed"?"Looks true":"Looks false"}${n}. ${t}`}function lg(e){let o=e.shot.region;return o.y<=1&&o.height<=40?"the macOS menu bar":`a ${Math.round(o.width)}x${Math.round(o.height)} region of the screen`}var Rn=e=>`${Math.round(e*100)}%`;var Ra=new dg().name("look").description("look at the screen with a vision model \u2014 for state the tree and OCR cannot see").argument("<question>",'what you want to know, e.g. "is a dialog covering the page?"').option("--verify","treat the argument as a claim and judge it (exit 3 refuted, 4 unknown)").option("--menubar","capture the menu bar instead of the focused window").option("--screen","capture the whole screen instead of the focused window").option("--rect <x,y,w,h>","capture an explicit region").option("--model <id>","vision model to use").option("--json","emit the result as JSON").action(async(e,o)=>{let t={kind:"window"};if(o.menubar)t={kind:"menubar"};else if(o.screen)t={kind:"screen"};else if(o.rect){let n=String(o.rect).split(",").map(Number);(n.length!==4||n.some(Number.isNaN))&&(console.log(Le.red(" --rect wants x,y,w,h")),process.exit(1)),t={kind:"rect",x:n[0],y:n[1],width:n[2],height:n[3]}}try{if(o.verify){let s=await Wt(e,{region:t,model:o.model});if(o.json)console.log(JSON.stringify({claim:s.claim,outcome:s.outcome,ok:s.ok,observable:s.observable,holds:s.holds,calibrated:s.calibrated,reason:s.reason,evidence:s.sighting.evidence,probes:s.probes,observation:s.sighting.observation,shot:s.sighting.shot.path,model:s.sighting.model,latencyMs:s.sighting.latencyMs},null,2));else{let i=s.outcome==="confirmed"?Le.green("\u2713"):s.outcome==="refuted"?Le.red("\u2717"):Le.yellow("?");console.log(` ${i} ${Le.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(Le.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(Le.dim(` ${s.sighting.model} \xB7 ${s.sighting.latencyMs}ms \xB7 ${s.sighting.shot.path}`))}process.exit(s.outcome==="confirmed"?0:s.outcome==="refuted"?3:4)}let n=await Nn(e,{region:t,model:o.model});if(o.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${Le.bold(n.observation)}`),n.evidence&&console.log(Le.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${gg(n.reading)}`),console.log(Le.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(Le.red(` ${n?.message??n}`)),process.exit(1)}});function gg(e){return e==="yes"?Le.green(e):e==="no"?Le.red(e):Le.yellow(e)}Et();import{Command as ug}from"commander";import{execFile as qa}from"child_process";import{promisify as fg}from"util";import{existsSync as hg,readFileSync as yg,writeFileSync as Wa,mkdirSync as wg}from"fs";import{homedir as bg}from"os";import{join as $g,dirname as kg}from"path";import Ce from"chalk";St();var Ps="paste-transform";function _a(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function Da(e){let o={};for(let t of e)o[t.id]=t.criterion;return{worthChanging:io("The text is in the wrong shape for where it is being pasted, and a mechanical reshaping would fix it.",{true:"The destination renders or stores formatted text, and the clipboard arrived in a shape that will not come out right: lines hard-wrapped mid-sentence going into prose, a link carrying campaign or tracking parameters, JSON collapsed onto one line, separate items going somewhere that renders a list, text padded with stray whitespace from a web page. The fix is mechanical and is what the person would have done by hand after pasting.",false:"The text is already in the right shape for this destination, OR its exact bytes carry meaning that reformatting would destroy \u2014 a credential, a command, a path, code, an identifier, a search query \u2014 OR the destination is a terminal, a password field, a URL bar or a code editor, where introduced formatting would corrupt what is pasted."}),shape:Ho(o,"What shape should this paste arrive in?")}}function Pa(e){let o=e.worthChanging,t=e.shape,n=Object.entries(t.probabilities??{}).map(([s,i])=>({id:s,p:Number(i)||0})).sort((s,i)=>i.p-s.p);return{worthChanging:o.noul,id:t.choice,confidence:t.confidence,ranked:n}}var mg=new Set(["utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id","gclid","fbclid","mc_cid","mc_eid","igshid","ref_src","ref_url","s","si","spm","scid","twclid","yclid","_hsenc","_hsmi"]),pg=e=>/^https?:\/\/\S+$/i.test(e.trim()),Ls=[{id:"asIs",criterion:"Paste it unchanged. The text is already in the right shape for where it is going, or it is something whose exact bytes matter \u2014 a password, a token, a command, code, an identifier.",label:"unchanged",apply:e=>e},{id:"unwrap",criterion:"Join lines that were hard-wrapped back into continuous paragraphs, keeping blank lines as paragraph breaks. For text copied out of a PDF, an email or a terminal, where every line ends at a fixed width mid-sentence.",label:"unwrap lines",apply:e=>{let o=e.split(`
275
+ The image is the region ${fg(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:pg,tools:[{type:"function",function:{name:"report",description:"Report what is visible and how it bears on the question",parameters:{type:"object",properties:{observation:{type:"string",description:"What is visible in the image, factually, in one or two sentences."},evidence:{type:"string",description:"The specific visible detail that decides the question \u2014 where it is and what it looks like. Empty string if no such detail is visible."},reading:{type:"string",enum:["yes","no","unclear"],description:"Answer to the question, or unclear if the pixels do not settle it."}},required:["observation","evidence","reading"]}}}],tool_choice:{type:"function",function:{name:"report"}}},a=new AbortController,c=setTimeout(()=>a.abort(),n),d;try{d=await fetch(dg,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`,"HTTP-Referer":"https://github.com/acme/agentx","X-Title":"agentx"},body:JSON.stringify(r),signal:a.signal})}finally{clearTimeout(c)}if(!d.ok){let u=await d.text().catch(()=>"");throw new Error(`vision model ${d.status}: ${u.slice(0,300)}`)}let g=await d.json(),l=g?.choices?.[0]?.message?.tool_calls?.[0];if(!l?.function?.arguments)throw new Error("vision model returned no structured report");let p=JSON.parse(l.function.arguments),f=p.reading==="yes"||p.reading==="no"?p.reading:"unclear";return{observation:(p.observation??"").trim(),evidence:(p.evidence??"").trim(),reading:f,model:typeof g.model=="string"?g.model:t,usage:{inputTokens:g?.usage?.prompt_tokens??0,outputTokens:g?.usage?.completion_tokens??0}}}async function Fn(e,o={}){let t=Date.now(),n=await mg(o.region??{kind:"window"},o.maxPixels??Pa),s=await ug(e,n,o.model??gg,o.timeoutMs??45e3);return{question:e,observation:s.observation,evidence:s.evidence,reading:s.reading,shot:n,model:s.model,latencyMs:Date.now()-t,usage:s.usage}}function fg(e){let{x:o,y:t,width:n,height:s}=e.region;return t<=1&&s<=40?"the macOS menu bar at the top of the screen":`x=${Math.round(o)} y=${Math.round(t)} ${Math.round(n)}x${Math.round(s)} points`}var Gt;function hg(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(Gt!==void 0)return Gt??void 0;try{let e=Hs(_a(ag(),".agentx","openrouter-key.txt"),"utf-8").trim();Gt=e.length>0?e:null}catch{Gt=null}return Gt??void 0}import{execFile as yg}from"child_process";import{promisify as wg}from"util";var bg=wg(yg),$g=["screencapture"],kg=["Screen Studio","OBS","QuickTime Player","Zoom"];async function Ma(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await vg()),t}async function vg(){let e=await La($g);if(e.length)return{checked:"running screen-capture processes (pgrep)",found:`A screen capture is definitely in progress: ${e.join(", ")}. This process only exists while it is recording, so this settles the question on its own.`};let o=await La(kg);return o.length?{checked:"running screen-capture processes (pgrep)",found:`No standalone capture process. A recorder application IS open (${o.join(", ")}), but its process exists whether or not it is recording, so this neither confirms nor denies. macOS does not expose in-app recording state to this tool, and the menu bar indicator is about six points \u2014 measured as below what the vision models here resolve reliably. Unless something else settles it, this claim cannot be verified.`}:{checked:"running screen-capture processes (pgrep)",found:"No screen-capture process is running and no recorder application is open. Nothing that records the screen from outside an app is active."}}async function La(e){let o=[];for(let t of e)try{let{stdout:n}=await bg("pgrep",["-x",t]),s=n.trim().split(`
276
+ `)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}It();Tt();var Fa="screen-state",Ua={observable:ao("The evidence gathered \u2014 the screenshot and the system checks together \u2014 is enough to settle the claim, either way.",{true:"Something in the evidence decides it. Either the observation names a specific visible detail that bears on the claim and was legible, or a system check directly establishes the claim true or false. A system check alone is sufficient: it does not need the image to agree with it, or the image to have shown anything at all.",false:"Nothing decides it. The deciding detail is not in frame, too small or blurred, or covered; the observation only describes context \u2014 which application is open, what the screen generally shows \u2014 without the detail itself; and no system check settles it either. Absence of evidence in a capture that could not have shown the evidence is not evidence of absence. This is also false when a check says the question is not answerable from a screenshot and the observation nonetheless claims to have seen it: that is a guess, however specific it sounds."}),holds:ao("The claim is true of the screen right now.",{true:"The visible evidence shows the claimed state is in effect: the indicator is present, the text is there, the element is visible and unobstructed, the action has plainly already happened.",false:"The visible evidence shows the claimed state is NOT in effect. An application being open, capable of the action, or offering it, is not the action having happened \u2014 a recorder on screen is not a recording, an unpressed button is not a pressed one, an offered dialog is not a chosen one. A system check that directly contradicts the observation outweighs it: the checks are deterministic readings of the machine, the observation is a model's reading of an image."})};function qa(e){return{claim:e.claim,capturedRegion:e.region,whatWasSeen:e.observation,decidingDetail:e.evidence||null,visionModelReading:e.reading,...e.treeNote?{accessibilityTree:e.treeNote}:{},...e.probes?.length?{systemChecks:e.probes}:{}}}function Wa(e){return{observable:e.observable.noul,holds:e.holds.noul}}var xg=.6,Sg=.7,Eg=.3;async function Ht(e,o={}){let[t,n]=await Promise.all([Fn(e,o),Ma(e).catch(()=>[])]),s=o.observableFloor??xg,i=await Qe(Fa,qa({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:Tg(t),treeNote:o.treeNote,probes:n}),Ua,{incumbent:{holds:t.reading==="yes"?1:0},features:{model:t.model,region:t.shot.region.height<=40?"menubar":"window"}});if(!i){let d=t.reading==="yes"?"confirmed":t.reading==="no"?"refuted":"unknown";return{claim:e,outcome:d,ok:d==="confirmed",observable:null,holds:null,calibrated:!1,reason:Og(d,t),sighting:t,probes:n}}let{observable:r,holds:a}=Wa(i.answers);if(r<s)return{claim:e,outcome:"unknown",ok:!1,observable:r,holds:a,calibrated:!0,reason:`Could not tell from the screenshot or the system checks (${Un(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=Sg?"confirmed":a<=Eg?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:Ag(c,a,t),sighting:t,probes:n}}function Ag(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${Un(o)}). ${n}`:e==="refuted"?`Not true (${Un(1-o)} it is false). ${n}`:`Inconclusive (${Un(o)}, between the thresholds). ${n}`}function Og(e,o){let t=o.evidence||o.observation||"no specific detail",n=" \u2014 uncalibrated, the screen-state seat is off";return e==="unknown"?`Could not tell${n}. ${t}`:`${e==="confirmed"?"Looks true":"Looks false"}${n}. ${t}`}function Tg(e){let o=e.shot.region;return o.y<=1&&o.height<=40?"the macOS menu bar":`a ${Math.round(o.width)}x${Math.round(o.height)} region of the screen`}var Un=e=>`${Math.round(e*100)}%`;var Ba=new Ig().name("look").description("look at the screen with a vision model \u2014 for state the tree and OCR cannot see").argument("<question>",'what you want to know, e.g. "is a dialog covering the page?"').option("--verify","treat the argument as a claim and judge it (exit 3 refuted, 4 unknown)").option("--menubar","capture the menu bar instead of the focused window").option("--screen","capture the whole screen instead of the focused window").option("--rect <x,y,w,h>","capture an explicit region").option("--model <id>","vision model to use").option("--json","emit the result as JSON").action(async(e,o)=>{let t={kind:"window"};if(o.menubar)t={kind:"menubar"};else if(o.screen)t={kind:"screen"};else if(o.rect){let n=String(o.rect).split(",").map(Number);(n.length!==4||n.some(Number.isNaN))&&(console.log(Le.red(" --rect wants x,y,w,h")),process.exit(1)),t={kind:"rect",x:n[0],y:n[1],width:n[2],height:n[3]}}try{if(o.verify){let s=await Ht(e,{region:t,model:o.model});if(o.json)console.log(JSON.stringify({claim:s.claim,outcome:s.outcome,ok:s.ok,observable:s.observable,holds:s.holds,calibrated:s.calibrated,reason:s.reason,evidence:s.sighting.evidence,probes:s.probes,observation:s.sighting.observation,shot:s.sighting.shot.path,model:s.sighting.model,latencyMs:s.sighting.latencyMs},null,2));else{let i=s.outcome==="confirmed"?Le.green("\u2713"):s.outcome==="refuted"?Le.red("\u2717"):Le.yellow("?");console.log(` ${i} ${Le.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(Le.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(Le.dim(` ${s.sighting.model} \xB7 ${s.sighting.latencyMs}ms \xB7 ${s.sighting.shot.path}`))}process.exit(s.outcome==="confirmed"?0:s.outcome==="refuted"?3:4)}let n=await Fn(e,{region:t,model:o.model});if(o.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${Le.bold(n.observation)}`),n.evidence&&console.log(Le.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${jg(n.reading)}`),console.log(Le.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(Le.red(` ${n?.message??n}`)),process.exit(1)}});function jg(e){return e==="yes"?Le.green(e):e==="no"?Le.red(e):Le.yellow(e)}It();import{Command as Rg}from"commander";import{execFile as Xa}from"child_process";import{promisify as Dg}from"util";import{existsSync as _g,readFileSync as Pg,writeFileSync as Qa,mkdirSync as Lg}from"fs";import{homedir as Mg}from"os";import{join as Fg,dirname as Ug}from"path";import je from"chalk";Tt();var zs="paste-transform";function Ja(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function Ga(e){let o={};for(let t of e)o[t.id]=t.criterion;return{worthChanging:ao("The text is in the wrong shape for where it is being pasted, and a mechanical reshaping would fix it.",{true:"The destination renders or stores formatted text, and the clipboard arrived in a shape that will not come out right: lines hard-wrapped mid-sentence going into prose, a link carrying campaign or tracking parameters, JSON collapsed onto one line, separate items going somewhere that renders a list, text padded with stray whitespace from a web page. The fix is mechanical and is what the person would have done by hand after pasting.",false:"The text is already in the right shape for this destination, OR its exact bytes carry meaning that reformatting would destroy \u2014 a credential, a command, a path, code, an identifier, a search query \u2014 OR the destination is a terminal, a password field, a URL bar or a code editor, where introduced formatting would corrupt what is pasted."}),shape:Yo(o,"What shape should this paste arrive in?")}}function Ha(e){let o=e.worthChanging,t=e.shape,n=Object.entries(t.probabilities??{}).map(([s,i])=>({id:s,p:Number(i)||0})).sort((s,i)=>i.p-s.p);return{worthChanging:o.noul,id:t.choice,confidence:t.confidence,ranked:n}}var Cg=new Set(["utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id","gclid","fbclid","mc_cid","mc_eid","igshid","ref_src","ref_url","s","si","spm","scid","twclid","yclid","_hsenc","_hsmi"]),Ng=e=>/^https?:\/\/\S+$/i.test(e.trim()),Ys=[{id:"asIs",criterion:"Paste it unchanged. The text is already in the right shape for where it is going, or it is something whose exact bytes matter \u2014 a password, a token, a command, code, an identifier.",label:"unchanged",apply:e=>e},{id:"unwrap",criterion:"Join lines that were hard-wrapped back into continuous paragraphs, keeping blank lines as paragraph breaks. For text copied out of a PDF, an email or a terminal, where every line ends at a fixed width mid-sentence.",label:"unwrap lines",apply:e=>{let o=e.split(`
277
277
  `);if(o.length<3)return null;let t=0;for(let n=0;n<o.length-1;n++){let s=o[n].trim(),i=o[n+1].trim();s.length>40&&i.length>0&&!/[.!?:;]$/.test(s)&&t++}return t<2?null:e.split(/\n\s*\n/).map(n=>n.split(`
278
278
  `).map(s=>s.trim()).filter(Boolean).join(" ")).filter(Boolean).join(`
279
279
 
@@ -281,78 +281,112 @@ The image is the region ${Kd(o)}.`},{type:"image_url",image_url:{url:`data:image
281
281
  `).map(t=>t.trim()).filter(Boolean);return o.length<2||o.every(t=>/^([-*+]|\d+[.)])\s/.test(t))?null:o.map(t=>`- ${t}`).join(`
282
282
  `)}},{id:"quote",criterion:"Prefix every line with a markdown blockquote marker. For quoting someone else's words into a document, an issue or a message.",label:"blockquote",apply:e=>{let o=e.split(`
283
283
  `);return o.every(t=>t.startsWith(">")||!t.trim())?null:o.map(t=>t.trim()?`> ${t}`:">").join(`
284
- `)}},{id:"codeFence",criterion:"Wrap it in a fenced code block. For code, a command, a log line or structured output going somewhere that renders markdown.",label:"code block",apply:e=>e.trim().startsWith("```")?null:"```\n"+e.replace(/\n+$/,"")+"\n```"},{id:"prettyJson",criterion:"Re-indent it as readable JSON. Only for text that already parses as JSON.",label:"format JSON",apply:e=>{let o=e.trim();if(!/^[[{]/.test(o))return null;try{let t=JSON.parse(o),n=JSON.stringify(t,null,2);return n===o?null:n}catch{return null}}},{id:"cleanUrl",criterion:"Strip campaign and tracking parameters from the link, keeping the rest of it intact. For a URL copied out of a share sheet, a newsletter or a social post.",label:"clean the link",apply:e=>{let o=e.trim();if(!pg(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])mg.has(s.toLowerCase())&&(t.searchParams.delete(s),n++);return n===0?null:t.toString().replace(/\?$/,"")}catch{return null}}},{id:"slug",criterion:"Convert to a lowercase hyphenated slug. For a title or phrase going into a branch name, a filename or a URL path.",label:"slug",apply:e=>{let o=e.trim();if(o.includes(`
284
+ `)}},{id:"codeFence",criterion:"Wrap it in a fenced code block. For code, a command, a log line or structured output going somewhere that renders markdown.",label:"code block",apply:e=>e.trim().startsWith("```")?null:"```\n"+e.replace(/\n+$/,"")+"\n```"},{id:"prettyJson",criterion:"Re-indent it as readable JSON. Only for text that already parses as JSON.",label:"format JSON",apply:e=>{let o=e.trim();if(!/^[[{]/.test(o))return null;try{let t=JSON.parse(o),n=JSON.stringify(t,null,2);return n===o?null:n}catch{return null}}},{id:"cleanUrl",criterion:"Strip campaign and tracking parameters from the link, keeping the rest of it intact. For a URL copied out of a share sheet, a newsletter or a social post.",label:"clean the link",apply:e=>{let o=e.trim();if(!Ng(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])Cg.has(s.toLowerCase())&&(t.searchParams.delete(s),n++);return n===0?null:t.toString().replace(/\?$/,"")}catch{return null}}},{id:"slug",criterion:"Convert to a lowercase hyphenated slug. For a title or phrase going into a branch name, a filename or a URL path.",label:"slug",apply:e=>{let o=e.trim();if(o.includes(`
285
285
  `)||o.length>90||o.length<3)return null;let t=o.normalize("NFKD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t&&t!==o?t:null}},{id:"collapseSpace",criterion:"Collapse runs of whitespace and trim the ends, leaving one clean line. For text copied out of a web page that arrived padded with stray spaces, tabs and newlines.",label:"tidy whitespace",apply:e=>{let o=e.replace(/[ \t]+/g," ").replace(/\s*\n\s*/g,`
286
- `).trim();return o===e?null:o}}];function La(e){let o=[];for(let t of Ls){let n=t.apply(e);n!==null&&(t.id!=="asIs"&&n===e||o.push({transform:t,result:n}))}return o}function Ma(e,o=320){if(e.length<=o)return e;let t=Math.floor(o*.7),n=o-t;return`${e.slice(0,t)}
286
+ `).trim();return o===e?null:o}}];function za(e){let o=[];for(let t of Ys){let n=t.apply(e);n!==null&&(t.id!=="asIs"&&n===e||o.push({transform:t,result:n}))}return o}function Ya(e,o=320){if(e.length<=o)return e;let t=Math.floor(o*.7),n=o-t;return`${e.slice(0,t)}
287
287
  \u2026[${e.length-o} more characters]\u2026
288
- ${e.slice(-n)}`}function Ua(e){let o=e.trim();return o.includes(`
289
- `)||o.length>200?!1:/^(sk|pk|ghp|gho|ghs|glpat|xox[abps])[-_][A-Za-z0-9_-]{16,}$/.test(o)||/^[A-Za-z0-9+/]{40,}={0,2}$/.test(o)||/^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\./.test(o)||o.length>=20&&!/\s/.test(o)&&/[A-Z]/.test(o)&&/[a-z]/.test(o)&&/\d/.test(o)&&!/^https?:\/\//i.test(o)&&!/\.(com|org|net|io|ai|tn)$/i.test(o)}var Ms=fg(qa),Ba=new ug().name("paste").description("reshape the clipboard to fit where it is being pasted").option("--apply","write the result back to the clipboard").option("--paste","apply, then press cmd-V into the focused control").option("--as <id>",`force a transform (${Ls.map(e=>e.id).join(", ")})`).option("--min <p>","minimum P(worth changing) before transforming","0.45").option("--undo","restore the clipboard as it was before the last apply").option("--json","emit the decision as JSON").action(async e=>{if(e.undo){let c=xg();c===null&&(console.log(Ce.yellow(" nothing to undo")),process.exit(2)),await Ha(c),console.log(` ${Ce.green("\u2192")} clipboard restored`);return}let o=await Sg();if(o||(console.log(Ce.yellow(" clipboard is empty")),process.exit(2)),Ua(o)){Ja(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=La(o),n=await Eg();if(e.as){let c=t.find(d=>d.transform.id===e.as);c||(console.log(Ce.red(` "${e.as}" does not apply to this clipboard`)),console.log(Ce.dim(` available: ${t.map(d=>d.transform.id).join(", ")}`)),process.exit(1)),await at(e,c.transform.id,c.result,o,"forced",1);return}if(t.length<2){await at(e,"asIs",o,o,"nothing else applies",0);return}let s=await Xe(Ps,_a({preview:Ma(o),length:o.length,lineCount:o.split(`
290
- `).length,app:n.app,destination:n.role,destinationLabel:n.label}),Da(t.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:t.length,chars:o.length}});if(!s){await at(e,"asIs",o,o,`seat unavailable \u2014 set decisions.seats.${Ps}.mode`,0);return}let i=Pa(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await at(e,"asIs",o,o,`paste as copied (P(worth changing) ${i.worthChanging.toFixed(2)} below ${r})`,i.worthChanging);return}let a=t.find(c=>c.transform.id===i.id);if(!a){await at(e,"asIs",o,o,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await at(e,a.transform.id,a.result,o,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function at(e,o,t,n,s,i){let r=t!==n;r&&(e.apply||e.paste)&&(vg(n),await Ha(t)),Ja(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await Ms(Ee,["key","--name","v","--mod","command"]).catch(a=>{console.log(Ce.red(` could not paste: ${a?.message??a}`))})}function Ja(e,o){if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.changed){console.log(` ${Ce.dim("\u2192")} ${Ce.bold("unchanged")} ${Ce.dim(`\xB7 ${o.reason}`)}`);return}console.log(` ${Ce.green("\u2192")} ${Ce.bold(o.applied)} ${Ce.dim(`\xB7 ${o.reason}`)}`),console.log(Ce.dim(" \u2500\u2500\u2500 before \u2500\u2500\u2500")),console.log(Ce.dim(Fa(o.original))),console.log(Ce.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(Fa(o.result)),!e.apply&&!e.paste&&console.log(Ce.dim(`
291
- (dry run \u2014 pass --apply to write it back)`))}var Fa=(e,o=400)=>(e.length>o?`${e.slice(0,o)}\u2026`:e).split(`
288
+ ${e.slice(-n)}`}function Va(e){let o=e.trim();return o.includes(`
289
+ `)||o.length>200?!1:/^(sk|pk|ghp|gho|ghs|glpat|xox[abps])[-_][A-Za-z0-9_-]{16,}$/.test(o)||/^[A-Za-z0-9+/]{40,}={0,2}$/.test(o)||/^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\./.test(o)||o.length>=20&&!/\s/.test(o)&&/[A-Z]/.test(o)&&/[a-z]/.test(o)&&/\d/.test(o)&&!/^https?:\/\//i.test(o)&&!/\.(com|org|net|io|ai|tn)$/i.test(o)}var Vs=Dg(Xa),Za=new Rg().name("paste").description("reshape the clipboard to fit where it is being pasted").option("--apply","write the result back to the clipboard").option("--paste","apply, then press cmd-V into the focused control").option("--as <id>",`force a transform (${Ys.map(e=>e.id).join(", ")})`).option("--min <p>","minimum P(worth changing) before transforming","0.45").option("--undo","restore the clipboard as it was before the last apply").option("--json","emit the decision as JSON").action(async e=>{if(e.undo){let c=Wg();c===null&&(console.log(je.yellow(" nothing to undo")),process.exit(2)),await oc(c),console.log(` ${je.green("\u2192")} clipboard restored`);return}let o=await Bg();if(o||(console.log(je.yellow(" clipboard is empty")),process.exit(2)),Va(o)){ec(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=za(o),n=await Jg();if(e.as){let c=t.find(d=>d.transform.id===e.as);c||(console.log(je.red(` "${e.as}" does not apply to this clipboard`)),console.log(je.dim(` available: ${t.map(d=>d.transform.id).join(", ")}`)),process.exit(1)),await gt(e,c.transform.id,c.result,o,"forced",1);return}if(t.length<2){await gt(e,"asIs",o,o,"nothing else applies",0);return}let s=await Qe(zs,Ja({preview:Ya(o),length:o.length,lineCount:o.split(`
290
+ `).length,app:n.app,destination:n.role,destinationLabel:n.label}),Ga(t.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:t.length,chars:o.length}});if(!s){await gt(e,"asIs",o,o,`seat unavailable \u2014 set decisions.seats.${zs}.mode`,0);return}let i=Ha(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await gt(e,"asIs",o,o,`paste as copied (P(worth changing) ${i.worthChanging.toFixed(2)} below ${r})`,i.worthChanging);return}let a=t.find(c=>c.transform.id===i.id);if(!a){await gt(e,"asIs",o,o,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await gt(e,a.transform.id,a.result,o,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function gt(e,o,t,n,s,i){let r=t!==n;r&&(e.apply||e.paste)&&(qg(n),await oc(t)),ec(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await Vs($e,["key","--name","v","--mod","command"]).catch(a=>{console.log(je.red(` could not paste: ${a?.message??a}`))})}function ec(e,o){if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.changed){console.log(` ${je.dim("\u2192")} ${je.bold("unchanged")} ${je.dim(`\xB7 ${o.reason}`)}`);return}console.log(` ${je.green("\u2192")} ${je.bold(o.applied)} ${je.dim(`\xB7 ${o.reason}`)}`),console.log(je.dim(" \u2500\u2500\u2500 before \u2500\u2500\u2500")),console.log(je.dim(Ka(o.original))),console.log(je.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(Ka(o.result)),!e.apply&&!e.paste&&console.log(je.dim(`
291
+ (dry run \u2014 pass --apply to write it back)`))}var Ka=(e,o=400)=>(e.length>o?`${e.slice(0,o)}\u2026`:e).split(`
292
292
  `).map(t=>` ${t}`).join(`
293
- `),_n=$g(bg(),".agentx","paste-undo.txt");function vg(e){try{wg(kg(_n),{recursive:!0}),Wa(_n,e,{mode:384})}catch{}}function xg(){try{let e=yg(_n,"utf-8");return Wa(_n,"",{mode:384}),e.length?e:null}catch{return null}}async function Sg(){let{stdout:e}=await Ms("pbpaste",[],{maxBuffer:16777216});return e}async function Ha(e){await new Promise((o,t)=>{qa("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function Eg(){if(!hg(Ee))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await Ms(Ee,["focused"]),o=JSON.parse(e);return o.ok===!1||!o.role?{app:"unknown",role:"an unknown control",label:null}:{app:o.app??"unknown",role:Ag(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function Ag(e,o){return{AXTextField:"a single-line text field",AXTextArea:"a multi-line text area",AXSearchField:"a search field",AXComboBox:"a combo box",AXSecureTextField:"a password field"}[e]??(o?"an editable control":`a ${e||"unknown"} control`)}import{Command as Og}from"commander";import Ye from"chalk";var jg=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function Ig(e,o){return async({title:t,message:n,channel:s,chatId:i})=>{let r=t&&!n.startsWith(t)?`${t}
294
- ${n}`:n,a=await fetch(`${jg}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:s??e,chatId:i??o,text:r})});if(!a.ok)throw new Error(`daemon ${a.status}: ${(await a.text().catch(()=>"")).slice(0,200)}`)}}var Ga=new Og().name("notify").description("tell the operator something, holding it if they are in Focus").argument("[message]","what to say").option("--from <who>","who is speaking","agentx").option("--title <text>","notification title","Secretary").option("--priority <n>","1 (min) to 5 (max)","4").option("--urgent","deliver even during Focus").option("--channel <name>","delivery channel","ntfy").option("--chat-id <id>","channel address","default").option("--no-sound","do not play a sound on this machine").option("--status","show Focus state and anything being held").option("--flush","deliver everything held, as one message").option("--json","emit the result as JSON").action(async(e,o)=>{let t=new cr,n=rr(),s=o.sound===!1?!1:void 0;if(o.status){let r=t.list();if(o.json){console.log(JSON.stringify({focus:n,held:r},null,2));return}console.log(` ${n.active?Ye.yellow("\u25D0"):Ye.green("\u25CB")} ${ar(n)} ${Ye.dim(`\xB7 ${n.reason}`)}`),console.log(` ${r.length} held`);for(let a of r.slice(0,8)){let c=new Date(a.at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(Ye.dim(` ${c} ${a.from}: ${a.message.slice(0,70)}`))}return}let i=Ig(o.channel,o.chatId);if(o.flush){let r=await dr(i,{queue:t,sound:s});console.log(r?Ye.green(` delivered ${r} held notification(s)`):Ye.dim(" nothing was held"));return}e?.trim()||(console.log(Ye.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let r=await lr({message:e.trim(),from:o.from,title:o.title,priority:Number(o.priority)||4,urgent:!!o.urgent,channel:o.channel,chatId:o.chatId},i,{queue:t,sound:s,focus:n});if(o.json){console.log(JSON.stringify(r,null,2));return}let a=r.delivered?Ye.green("\u2192"):Ye.yellow("\u23F8");console.log(` ${a} ${r.reason}`),r.held&&console.log(Ye.dim(" it will arrive with the others when Focus ends"))}catch(r){console.log(Ye.red(` ${r?.message??r}`)),s!==!1&&gr(),process.exit(1)}});Et();Ri();Ei();St();import{Command as Cg}from"commander";import{readFileSync as Tg}from"fs";var za=new Cg().name("decide").description("ask a typed question about some state and get a calibrated answer back").option("--file <path>","spec JSON file (default: stdin)").option("--backend <name>","decision backend","typesafe").option("--seat <name>","seat name the answers are recorded under","adhoc").option("--no-record","answer without writing a row").option("--timeout <ms>","abandon the call after this long","20000").action(async e=>{let o;try{o=e.file?Tg(e.file,"utf8"):await Ng()}catch(r){Mo(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return Mo("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return Mo(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return Mo("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return Mo("spec needs at least one entry in `questions`");try{Oi(t.questions)}catch(r){return Mo(r?.message??String(r))}let n=t.seat||e.seat;Go(),process.env[Di(n)]="active";let s=null;if(e.record!==!1)try{s=new tn({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
295
- `)}_i({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await Xe(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return Mo(`the ${e.backend} backend did not answer \u2014 check the key and that the seat is reachable`);console.log(JSON.stringify({ok:!0,seat:n,callId:i.callId,answers:i.answers},null,2)),s?.close()});function Mo(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function Ng(){if(process.stdin.isTTY)return"";let e=[];for await(let o of process.stdin)e.push(Buffer.from(o));return Buffer.concat(e).toString("utf8")}Et();import{Command as qg}from"commander";import{execFile as Wg,spawn as Ka}from"child_process";import{promisify as Bg}from"util";import{existsSync as Jg,statSync as Hg}from"fs";import{join as Xa}from"path";import{tmpdir as Gg}from"os";import X from"chalk";var Rg={id:"x-advanced-search",title:"X search: find anyone's best posts",appHint:"Opens X in Chrome; sign in before running the lesson.",start:{app:"Google Chrome",url:"https://x.com/home",ready:"Google Chrome is frontmost showing the signed-in x.com home page with its navigation sidebar"},steps:[{say:"Here's something about X search that almost nobody uses. It takes ten seconds and it changes what the site is good for."},{say:"Let's open search. This is it in the sidebar.",find:"the search and explore link in the sidebar",label:"Search",before:"Google Chrome is frontmost showing signed-in x.com with the search and explore sidebar link visible",click:!0,afterClickWaitMs:2600},{say:"Here's the box itself. Most people type a few words here and scroll. But it accepts commands, not just words.",find:"the search query input field where you type",label:"search field",before:"Google Chrome is frontmost showing x.com with the search query input visible",click:!0,afterClickWaitMs:900},{say:"Watch. From colon, then a username, limits it to that person. Then min underscore faves, colon, five hundred \u2014 only posts with at least five hundred likes.",before:"Google Chrome is frontmost on x.com and the empty search query input has keyboard focus",type:"from:naval min_faves:500",holdSeconds:1.8},{say:"And submit.",before:"Google Chrome is frontmost on x.com and the focused search input contains from:naval min_faves:500",key:"return",holdSeconds:3.2,verify:"the x.com page is displaying search results for the query from:naval min_faves:500, with at least one post visible"},{say:"There it is. That person's greatest hits \u2014 everything they wrote that actually landed. No scrolling through years of replies.",holdSeconds:2},{say:"Two more that pair well with it. Until colon, and since colon, with a date, pin it to a time period. Useful when you half remember something from a particular month."},{say:"And filter colon links, or filter colon media, narrows it to posts that shared something, which is usually where the substance is."},{say:"After you search, check the Latest tab. Top is ranked, Latest is chronological, and for research you almost always want chronological.",find:"the Latest tab",label:"Latest"},{say:"That's it. From colon someone, min underscore faves colon five hundred. It works on your own account too, which is a quick way to see what people actually responded to."}]},_g={id:"x-bookmark-folders",title:"X bookmarks: turn the pile into folders",appHint:"Opens X in Chrome; sign in before running the lesson.",start:{app:"Google Chrome",url:"https://x.com/home",ready:"Google Chrome is frontmost showing the signed-in x.com home page with its navigation sidebar"},steps:[{say:"Most people's bookmarks on X are a single pile they never open again. There's a fix that takes a minute."},{say:"Bookmarks live here in the sidebar. By default everything you save lands in one list, in the order you saved it.",find:"the Bookmarks link in the sidebar",label:"Bookmarks",before:"Google Chrome is frontmost showing signed-in x.com with the Bookmarks sidebar link visible",click:!0,verify:"Google Chrome is showing the x.com Bookmarks page"},{say:"But bookmarks support folders. Open bookmarks and look for the add folder control, usually a small plus at the top right.",find:"the add folder button",label:"new folder"},{say:"The trick is what you name them. Not topics like design or tech, which you'll never search for. Name them after decisions you're going to make, like hiring, or pricing.",holdSeconds:2},{say:"Then when you save a post, hold the bookmark button instead of tapping it, and it asks which folder. That one gesture is the whole difference between a pile and a library."}]},Dg={id:"agentx-dashboard-tour",title:"AgentX: a tour of your agent team",appHint:"Start the demo first: docker compose -f docker-compose.demo.yml up -d",start:{app:"Google Chrome",url:"http://127.0.0.1:18931/live",cleanWindow:!0,ready:"The text laptop-paris is visible on the page"},steps:[{say:"This is AgentX: a team of AI agents running on your own machines. Everything here is real, except the model's replies, which are scripted for the demo."},{say:"Up top, three machines, one agent each, all online.",find:"the 3/3 machines count under Agents online",label:"3 machines online"},{say:"This machine is a laptop in Paris. Its agent, CX, talks to customers, and hands technical work to others.",find:"the laptop-paris machine name",label:"CX \xB7 laptop-paris"},{say:"And this is Builder, on a server in New York. When CX gets a code problem, it sends it here, across the mesh.",find:"the @builder Builder agent name in the vps-nyc section",label:"Builder \xB7 vps-nyc"},{say:"Operations shows what the whole team actually did.",find:"the Operations tab in the top navigation bar",label:"Operations",before:"The AgentX Live page is on screen with the Live tab selected",click:!0,verify:"The page shows the heading Mesh operations"},{say:"Machines online, work in progress, failures today, and jobs waiting for a person to review.",find:"the Nodes online summary",label:"The team at a glance"},{say:"Each lane is one kind of work. The demo's run landed here, as direct tasks.",find:"the Direct lane label in the What ran chart",label:"Direct tasks"},{say:"Workflows turn a job you repeat into steps you can review before they run.",find:"the Workflows tab in the top navigation bar",label:"Workflows",before:"The AgentX page with the heading Mesh operations is on screen",click:!0,verify:"The page shows a Workflows list that includes Draft the demo shop report"},{say:"This one drafts a report for the demo shop. It's saved switched off, so nothing runs until you say so.",find:"the Draft the demo shop report workflow title",label:"A saved workflow"},{say:"And on every page, you can ask an agent about what you're looking at.",find:"the Ask an agent about this page input",label:"Ask an agent"},{say:"That's the tour. Your machines, the work they did, and the jobs you can hand them."}]},Us=[Rg,_g,Dg];we();we();import Ve from"chalk";import{execFile as Pg}from"child_process";import{promisify as Lg}from"util";import{createInterface as Mg}from"readline";var Ya=Lg(Pg);function Ug(e){e.type==="step"?console.log(`${Ve.cyan(` ${e.n}. ${e.action}`)}${e.target?Ve.dim(` "${e.target}"`):""} ${e.say}`):e.type==="changed"?console.log(Ve.dim(` ${e.changed?"screen changed":"no change"}`)):e.type==="acted"?console.log(e.error?Ve.red(` failed: ${e.error}`):Ve.dim(" done it")):e.type==="replanned"?console.log(Ve.yellow(` screen changed, looking again: ${e.reason}`)):e.type==="door"?console.log(Ve.cyan(` you: ${e.text}`)):e.type==="error"?console.log(Ve.red(` error: ${e.error}`)):e.type==="end"&&console.log(Ve.dim(` \xB7 ended (${e.reason})`))}async function Fg(e,o){let t=Date.now()+o;for(let n=0;Date.now()<t;n++){n&&n%10===0&&await Ya("open",["-a",e]).catch(()=>{});try{let s=(await us()).app;if(s.toLowerCase()===e.replace(/\.app$/i,"").toLowerCase())return s}catch{}await new Promise(s=>setTimeout(s,500))}return null}async function Va(e,o){let t=D(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=["teach","watch","act"].includes(o.mode??"")?o.mode:"teach",i;if(o.app&&(await Ya("open",["-a",o.app]),i=await Fg(o.app,15e3)??void 0,!i))throw new Error(`${o.app} did not come to the front`);let r=dn(n,t.agents,!1),a=Rr(n,t.agents[n]),c=new Or({goal:e,app:i,mode:s,speaker:r,actionsAllowed:a.allowActions,maxSteps:Number(o.steps)||void 0},{readScreen:us,presence:new _r(a,Ee,n),speech:new Qo,model:gn({system:Ar(r.persona,"Anis")}),act:Nr});c.on(Ug),console.log(Ve.bold(`
296
- ${a.name} teaches: ${e}`)+Ve.dim(` (${s}${s==="act"&&!a.allowActions?", actions not allowed":""}; type to cut in, "stop" to end)
297
- `));let d=Mg({input:process.stdin});d.on("line",g=>{g.trim()&&c.door(g)}),process.once("SIGINT",()=>c.stop("interrupted")),await c.run(),d.close()}var qs=Bg(Wg),Qa=new qg().name("teach").description("walk through something on screen, speaking and pointing as it goes").argument("[lesson]","lesson id (omit to list)").option("--voice <voice>",`system voice name, "${uo}" for the OS default, or ElevenLabs voice id (overrides the agent's)`).option("--agent <id>","speak in this agent's voice (default: AGENTX_VOICE_AGENT or node.defaultAgent)").option("--no-speak","point only, print the narration").option("--no-hud","skip the on-screen callout").option("--record","record the screen (screencapture) around the lesson").option("--record-dir <path>","where to write the recording").option("--live <goal>","no lesson: the agent reads the screen and teaches this, step by step").option("--mode <mode>","with --live: teach (you do each step), watch (you drive, it coaches) or act (it does it, if allowed)").option("--app <name>","with --live: open this app first").option("-c, --config <path>","with --live: agentx.json to read the agent from").option("--steps <n>","with --live: most steps before it stops (default 12)").action(async(e,o)=>{if(o.live)try{await Va(String(o.live),o),process.exit(0)}catch(g){console.log(X.red(` ${g?.message??g}`)),process.exit(1)}if(!e){console.log(X.bold(`
293
+ `),qn=Fg(Mg(),".agentx","paste-undo.txt");function qg(e){try{Lg(Ug(qn),{recursive:!0}),Qa(qn,e,{mode:384})}catch{}}function Wg(){try{let e=Pg(qn,"utf-8");return Qa(qn,"",{mode:384}),e.length?e:null}catch{return null}}async function Bg(){let{stdout:e}=await Vs("pbpaste",[],{maxBuffer:16777216});return e}async function oc(e){await new Promise((o,t)=>{Xa("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function Jg(){if(!_g($e))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await Vs($e,["focused"]),o=JSON.parse(e);return o.ok===!1||!o.role?{app:"unknown",role:"an unknown control",label:null}:{app:o.app??"unknown",role:Gg(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function Gg(e,o){return{AXTextField:"a single-line text field",AXTextArea:"a multi-line text area",AXSearchField:"a search field",AXComboBox:"a combo box",AXSecureTextField:"a password field"}[e]??(o?"an editable control":`a ${e||"unknown"} control`)}import{Command as Hg}from"commander";import Ve from"chalk";var zg=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function Yg(e,o){return async({title:t,message:n,channel:s,chatId:i})=>{let r=t&&!n.startsWith(t)?`${t}
294
+ ${n}`:n,a=await fetch(`${zg}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:s??e,chatId:i??o,text:r})});if(!a.ok)throw new Error(`daemon ${a.status}: ${(await a.text().catch(()=>"")).slice(0,200)}`)}}var tc=new Hg().name("notify").description("tell the operator something, holding it if they are in Focus").argument("[message]","what to say").option("--from <who>","who is speaking","agentx").option("--title <text>","notification title","Secretary").option("--priority <n>","1 (min) to 5 (max)","4").option("--urgent","deliver even during Focus").option("--channel <name>","delivery channel","ntfy").option("--chat-id <id>","channel address","default").option("--no-sound","do not play a sound on this machine").option("--status","show Focus state and anything being held").option("--flush","deliver everything held, as one message").option("--json","emit the result as JSON").action(async(e,o)=>{let t=new $r,n=wr(),s=o.sound===!1?!1:void 0;if(o.status){let r=t.list();if(o.json){console.log(JSON.stringify({focus:n,held:r},null,2));return}console.log(` ${n.active?Ve.yellow("\u25D0"):Ve.green("\u25CB")} ${br(n)} ${Ve.dim(`\xB7 ${n.reason}`)}`),console.log(` ${r.length} held`);for(let a of r.slice(0,8)){let c=new Date(a.at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(Ve.dim(` ${c} ${a.from}: ${a.message.slice(0,70)}`))}return}let i=Yg(o.channel,o.chatId);if(o.flush){let r=await vr(i,{queue:t,sound:s});console.log(r?Ve.green(` delivered ${r} held notification(s)`):Ve.dim(" nothing was held"));return}e?.trim()||(console.log(Ve.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let r=await kr({message:e.trim(),from:o.from,title:o.title,priority:Number(o.priority)||4,urgent:!!o.urgent,channel:o.channel,chatId:o.chatId},i,{queue:t,sound:s,focus:n});if(o.json){console.log(JSON.stringify(r,null,2));return}let a=r.delivered?Ve.green("\u2192"):Ve.yellow("\u23F8");console.log(` ${a} ${r.reason}`),r.held&&console.log(Ve.dim(" it will arrive with the others when Focus ends"))}catch(r){console.log(Ve.red(` ${r?.message??r}`)),s!==!1&&xr(),process.exit(1)}});It();Gi();Li();Tt();import{Command as Vg}from"commander";import{readFileSync as Kg}from"fs";var nc=new Vg().name("decide").description("ask a typed question about some state and get a calibrated answer back").option("--file <path>","spec JSON file (default: stdin)").option("--backend <name>","decision backend","typesafe").option("--seat <name>","seat name the answers are recorded under","adhoc").option("--no-record","answer without writing a row").option("--timeout <ms>","abandon the call after this long","20000").action(async e=>{let o;try{o=e.file?Kg(e.file,"utf8"):await Xg()}catch(r){Uo(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return Uo("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return Uo(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return Uo("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return Uo("spec needs at least one entry in `questions`");try{Fi(t.questions)}catch(r){return Uo(r?.message??String(r))}let n=t.seat||e.seat;Vo(),process.env[zi(n)]="active";let s=null;if(e.record!==!1)try{s=new ln({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
295
+ `)}Hi({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await Qe(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return Uo(`the ${e.backend} backend did not answer \u2014 check the key and that the seat is reachable`);console.log(JSON.stringify({ok:!0,seat:n,callId:i.callId,answers:i.answers},null,2)),s?.close()});function Uo(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function Xg(){if(process.stdin.isTTY)return"";let e=[];for await(let o of process.stdin)e.push(Buffer.from(o));return Buffer.concat(e).toString("utf8")}It();import{Command as Em}from"commander";import{execFile as Am,spawn as fc}from"child_process";import{promisify as Om}from"util";import{existsSync as Tm,statSync as Im}from"fs";import{join as hc}from"path";import{tmpdir as jm}from"os";import X from"chalk";var Qg={id:"x-advanced-search",title:"X search: find anyone's best posts",appHint:"Opens X in Chrome; sign in before running the lesson.",start:{app:"Google Chrome",url:"https://x.com/home",ready:"Google Chrome is frontmost showing the signed-in x.com home page with its navigation sidebar"},steps:[{say:"Here's something about X search that almost nobody uses. It takes ten seconds and it changes what the site is good for."},{say:"Let's open search. This is it in the sidebar.",find:"the search and explore link in the sidebar",label:"Search",before:"Google Chrome is frontmost showing signed-in x.com with the search and explore sidebar link visible",click:!0,afterClickWaitMs:2600},{say:"Here's the box itself. Most people type a few words here and scroll. But it accepts commands, not just words.",find:"the search query input field where you type",label:"search field",before:"Google Chrome is frontmost showing x.com with the search query input visible",click:!0,afterClickWaitMs:900},{say:"Watch. From colon, then a username, limits it to that person. Then min underscore faves, colon, five hundred \u2014 only posts with at least five hundred likes.",before:"Google Chrome is frontmost on x.com and the empty search query input has keyboard focus",type:"from:naval min_faves:500",holdSeconds:1.8},{say:"And submit.",before:"Google Chrome is frontmost on x.com and the focused search input contains from:naval min_faves:500",key:"return",holdSeconds:3.2,verify:"the x.com page is displaying search results for the query from:naval min_faves:500, with at least one post visible"},{say:"There it is. That person's greatest hits \u2014 everything they wrote that actually landed. No scrolling through years of replies.",holdSeconds:2},{say:"Two more that pair well with it. Until colon, and since colon, with a date, pin it to a time period. Useful when you half remember something from a particular month."},{say:"And filter colon links, or filter colon media, narrows it to posts that shared something, which is usually where the substance is."},{say:"After you search, check the Latest tab. Top is ranked, Latest is chronological, and for research you almost always want chronological.",find:"the Latest tab",label:"Latest"},{say:"That's it. From colon someone, min underscore faves colon five hundred. It works on your own account too, which is a quick way to see what people actually responded to."}]},Zg={id:"x-bookmark-folders",title:"X bookmarks: turn the pile into folders",appHint:"Opens X in Chrome; sign in before running the lesson.",start:{app:"Google Chrome",url:"https://x.com/home",ready:"Google Chrome is frontmost showing the signed-in x.com home page with its navigation sidebar"},steps:[{say:"Most people's bookmarks on X are a single pile they never open again. There's a fix that takes a minute."},{say:"Bookmarks live here in the sidebar. By default everything you save lands in one list, in the order you saved it.",find:"the Bookmarks link in the sidebar",label:"Bookmarks",before:"Google Chrome is frontmost showing signed-in x.com with the Bookmarks sidebar link visible",click:!0,verify:"Google Chrome is showing the x.com Bookmarks page"},{say:"But bookmarks support folders. Open bookmarks and look for the add folder control, usually a small plus at the top right.",find:"the add folder button",label:"new folder"},{say:"The trick is what you name them. Not topics like design or tech, which you'll never search for. Name them after decisions you're going to make, like hiring, or pricing.",holdSeconds:2},{say:"Then when you save a post, hold the bookmark button instead of tapping it, and it asks which folder. That one gesture is the whole difference between a pile and a library."}]},em={id:"agentx-dashboard-tour",title:"AgentX: a tour of your agent team",appHint:"Start the demo first: docker compose -f docker-compose.demo.yml up -d",start:{app:"Google Chrome",url:"http://127.0.0.1:18931/live",cleanWindow:!0,ready:"The text laptop-paris is visible on the page"},steps:[{say:"This is AgentX: a team of AI agents running on your own machines. Everything here is real, except the model's replies, which are scripted for the demo."},{say:"Up top, three machines, one agent each, all online.",find:"the 3/3 machines count under Agents online",label:"3 machines online"},{say:"This machine is a laptop in Paris. Its agent, CX, talks to customers, and hands technical work to others.",find:"the laptop-paris machine name",label:"CX \xB7 laptop-paris"},{say:"And this is Builder, on a server in New York. When CX gets a code problem, it sends it here, across the mesh.",find:"the @builder Builder agent name in the vps-nyc section",label:"Builder \xB7 vps-nyc"},{say:"Operations shows what the whole team actually did.",find:"the Operations tab in the top navigation bar",label:"Operations",before:"The AgentX Live page is on screen with the Live tab selected",click:!0,verify:"The page shows the heading Mesh operations"},{say:"Machines online, work in progress, failures today, and jobs waiting for a person to review.",find:"the Nodes online summary",label:"The team at a glance"},{say:"Each lane is one kind of work. The demo's run landed here, as direct tasks.",find:"the Direct lane label in the What ran chart",label:"Direct tasks"},{say:"Workflows turn a job you repeat into steps you can review before they run.",find:"the Workflows tab in the top navigation bar",label:"Workflows",before:"The AgentX page with the heading Mesh operations is on screen",click:!0,verify:"The page shows a Workflows list that includes Draft the demo shop report"},{say:"This one drafts a report for the demo shop. It's saved switched off, so nothing runs until you say so.",find:"the Draft the demo shop report workflow title",label:"A saved workflow"},{say:"And on every page, you can ask an agent about what you're looking at.",find:"the Ask an agent about this page input",label:"Ask an agent"},{say:"That's the tour. Your machines, the work they did, and the jobs you can hand them."}]},Ks=[Qg,Zg,em];pe();pe();import Ke from"chalk";import{execFile as om}from"child_process";import{promisify as tm}from"util";import{createInterface as nm}from"readline";var sc=tm(om);function sm(e){e.type==="step"?console.log(`${Ke.cyan(` ${e.n}. ${e.action}`)}${e.target?Ke.dim(` "${e.target}"`):""} ${e.say}`):e.type==="changed"?console.log(Ke.dim(` ${e.changed?"screen changed":"no change"}`)):e.type==="acted"?console.log(e.error?Ke.red(` failed: ${e.error}`):Ke.dim(" done it")):e.type==="replanned"?console.log(Ke.yellow(` screen changed, looking again: ${e.reason}`)):e.type==="door"?console.log(Ke.cyan(` you: ${e.text}`)):e.type==="error"?console.log(Ke.red(` error: ${e.error}`)):e.type==="end"&&console.log(Ke.dim(` \xB7 ended (${e.reason})`))}async function im(e,o){let t=Date.now()+o;for(let n=0;Date.now()<t;n++){n&&n%10===0&&await sc("open",["-a",e]).catch(()=>{});try{let s=(await Es()).app;if(s.toLowerCase()===e.replace(/\.app$/i,"").toLowerCase())return s}catch{}await new Promise(s=>setTimeout(s,500))}return null}async function ic(e,o){let t=_(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=["teach","watch","act"].includes(o.mode??"")?o.mode:"teach",i;if(o.app&&(await sc("open",["-a",o.app]),i=await im(o.app,15e3)??void 0,!i))throw new Error(`${o.app} did not come to the front`);let r=hn(n,t.agents,!1),a=$n(n,t.agents[n]),c=new Fr({goal:e,app:i,mode:s,speaker:r,actionsAllowed:a.allowActions,maxSteps:Number(o.steps)||void 0},{readScreen:Es,presence:new kn(a,$e,n),speech:new ot,model:tt({system:Mr(r.persona,"Anis")}),act:Jr});c.on(sm),console.log(Ke.bold(`
296
+ ${a.name} teaches: ${e}`)+Ke.dim(` (${s}${s==="act"&&!a.allowActions?", actions not allowed":""}; type to cut in, "stop" to end)
297
+ `));let d=nm({input:process.stdin});d.on("line",g=>{g.trim()&&c.door(g)}),process.once("SIGINT",()=>c.stop("interrupted")),await c.run(),d.close()}pe();import so from"chalk";import{execFile as hm}from"child_process";import{copyFileSync as ym,existsSync as Xs}from"fs";import{homedir as wm}from"os";import{join as pc,resolve as bm}from"path";import{promisify as $m}from"util";var We={w:1e3,h:640},rc=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],ac=["rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","cloud","heart"],rm=["none","semi","solid","fill","pattern"],am=["s","m","l","xl"],cm=["draw","sans","serif","mono"];function cc(){return[`You plan a simple, good-looking illustration for a tldraw canvas ${We.w} wide and ${We.h} tall (x right, y down, origin top-left).`,"Reply with JSON Lines only: one element per line, no prose, no code fences, at most 14 lines. Draw back to front: big background shapes first, details and text last, arrows at the end.",'Shape: {"id":"sea","say":"First, the sea.","geo":"rectangle","x":0,"y":420,"w":1000,"h":220,"color":"blue","fill":"fill","label":""}','Text: {"id":"title","say":"And a title.","text":"Sidi Bou Said","x":330,"y":40,"size":"xl","color":"black","font":"draw"}',`Arrow: {"id":"a1","say":"That's the sun.","arrow":["sun-note","sun"],"label":"","color":"black"}`,"An arrow joins two DIFFERENT earlier elements. To label something, first add a small text element beside it (e.g. id sun-note, a few words), then an arrow from that text to the thing.",`geo is one of: ${ac.join(", ")}.`,`color is one of: ${rc.join(", ")}. fill is fill (strong colour), solid (pale tint), semi, none or pattern; prefer fill for the main shapes. size is s, m, l or xl. font is draw, sans, serif or mono.`,"Keep everything inside the canvas. Use 3 to 5 colours that go together. Give text room: an xl word is about 40 px tall and 28 px wide per letter.","say is a short caption, at most 8 words, in the voice of someone drawing it live. Caption only the steps worth narrating (about one in three) and leave say empty on the rest: captioned steps pause so they can be read, the others draw straight through."].join(`
298
+ `)}function zt(e,o,t){return typeof e=="string"&&o.includes(e)?e:t}function Wn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}var Bn=(e,o,t)=>Math.min(t,Math.max(o,e));function lc(e,o){let t=e.trim().replace(/,$/,"");if(!t.startsWith("{"))return null;let n;try{n=JSON.parse(t)}catch{return null}let s=typeof n.id=="string"&&n.id?n.id.slice(0,40):null;if(!s||o.has(s))return null;let i=typeof n.say=="string"?n.say.slice(0,80):"",r=zt(n.color,rc,"black");if(Array.isArray(n.arrow)){let[d,g]=n.arrow;return typeof d!="string"||typeof g!="string"||!o.has(d)||!o.has(g)||d===g?null:{kind:"arrow",id:s,say:i,from:d,to:g,label:typeof n.label=="string"?n.label.slice(0,40):"",color:r}}let a=Wn(n.x),c=Wn(n.y);if(a===null||c===null)return null;if(typeof n.text=="string"&&n.text)return{kind:"text",id:s,say:i,text:n.text.slice(0,60),x:Bn(a,0,We.w-20),y:Bn(c,0,We.h-20),size:zt(n.size,am,"l"),color:r,font:zt(n.font,cm,"draw")};if(typeof n.geo=="string"){let d=Wn(n.w),g=Wn(n.h);if(d===null||g===null||d<4||g<4)return null;let l=Bn(a,0,We.w-4),p=Bn(c,0,We.h-4);return{kind:"geo",id:s,say:i,geo:zt(n.geo,ac,"rectangle"),x:l,y:p,w:Math.min(d,We.w-l),h:Math.min(g,We.h-p),color:r,fill:zt(n.fill,rm,"solid"),label:typeof n.label=="string"?n.label.slice(0,40):""}}return null}var Jn=class{buf="";push(o){this.buf+=o;let t=this.buf.split(`
299
+ `);return this.buf=t.pop()??"",t}flush(){let o=this.buf;return this.buf="",o.trim()?[o]:[]}};var lm=500,dm=e=>`
300
+ editor.zoomToBounds({ x: 0, y: 0, w: ${We.w}, h: ${We.h} }, { inset: ${e}, immediate: true })
301
+ const o = editor.pageToScreen({ x: 0, y: 0 }), e = editor.pageToScreen({ x: ${We.w}, y: 0 })
302
+ const chrome = window.outerHeight - window.innerHeight
303
+ return { ox: window.screenX + o.x, oy: window.screenY + chrome + o.y, scale: (e.x - o.x) / ${We.w} }`;function dc(e,o,t,n=0,s=0){return{x:e.ox+o*e.scale,y:e.oy+t*e.scale,width:n*e.scale,height:s*e.scale}}function gc(e){let o={s:18,m:24,l:32,xl:44}[e.size]??32;return{x:e.x,y:e.y,w:e.text.length*o*.6,h:o*1.3}}function gm(e,o){let t=s=>JSON.stringify(`${o}-${s}`),n=`const { createShapeId, toRichText } = await import('tldraw')
304
+ const el = ${JSON.stringify(e)}
305
+ const frames = 10, wait = () => new Promise((r) => setTimeout(r, ${Math.round(lm/10)}))
306
+ const ease = (t) => 1 - Math.pow(1 - t, 3)`;return e.kind==="geo"?`${n}
307
+ const id = createShapeId(${t(e.id)})
308
+ editor.createShape({ id, type: 'geo', x: el.x, y: el.y, props: { geo: el.geo, w: 1, h: 1, color: el.color, fill: el.fill } })
309
+ for (let i = 1; i <= frames; i++) {
310
+ const t = ease(i / frames)
311
+ editor.updateShape({ id, type: 'geo', props: { w: Math.max(1, el.w * t), h: Math.max(1, el.h * t) } })
312
+ await wait()
313
+ }
314
+ if (el.label) editor.updateShape({ id, type: 'geo', props: { richText: toRichText(el.label) } })
315
+ return id`:e.kind==="text"?`${n}
316
+ const id = createShapeId(${t(e.id)})
317
+ editor.createShape({ id, type: 'text', x: el.x, y: el.y, props: { richText: toRichText(''), size: el.size, color: el.color, font: el.font } })
318
+ for (let i = 1; i <= frames; i++) {
319
+ editor.updateShape({ id, type: 'text', props: { richText: toRichText(el.text.slice(0, Math.ceil(el.text.length * i / frames))) } })
320
+ await wait()
321
+ }
322
+ return id`:`${n}
323
+ const arrow = helpers.createArrowBetweenShapes(createShapeId(${t(e.from)}), createShapeId(${t(e.to)}), el.label ? { richText: toRichText(el.label) } : {})
324
+ const aid = typeof arrow === 'string' ? arrow : arrow?.id
325
+ if (aid) editor.updateShape({ id: aid, type: 'arrow', props: { color: el.color } })
326
+ return aid ?? null`}function mm(e,o){if(e.kind==="geo")return[qo(e.x,e.y),qo(e.x+e.w,e.y+e.h)];if(e.kind==="text"){let s=gc(e);return[qo(s.x,s.y+s.h/2),qo(s.x+s.w,s.y+s.h/2)]}let t=o.get(e.from),n=o.get(e.to);return[qo(t.x+t.w/2,t.y+t.h/2),qo(n.x+n.w/2,n.y+n.h/2)]}var qo=(e,o)=>({x:e,y:o,w:0,h:0});async function mc(e,o,t,n=()=>{}){let s=o.sleep??(v=>new Promise($=>setTimeout($,v))),i=o.now??Date.now,r=t.stepMs??1500,a=t.runTag??i().toString(36),c=i(),d=await o.api.exec(t.docId,dm(60)),g=new Set,l=new Map,p=[],f=!1,u=0,w=null,y=null,k=null,b=()=>{k?.(),k=null},x=v=>{let $=lc(v,g);if(!$){v.trim()&&n({type:"skipped",line:v.slice(0,120)});return}g.add($.id),w??=i()-c,p.push($),n({type:"planned",n:g.size,el:$,atMs:i()-c}),b()},A=(async()=>{let v=new Jn;try{for await(let $ of o.model.reply(`Draw: ${e}`,t.signal))v.push($).forEach(x);v.flush().forEach(x)}catch($){y=$?.message??String($)}finally{u=i()-c,f=!0,b()}})(),S=0;for(;!t.signal?.aborted;){let v=p.shift();if(!v){if(f)break;await new Promise(D=>{k=D});continue}if(v.kind==="arrow"&&!(l.has(v.from)&&l.has(v.to))){n({type:"error",error:`${v.id}: an end was not drawn`});continue}let $=i(),[C,j]=mm(v,l);v.say&&o.presence.say(v.say),o.presence.moveTo(dc(d,C.x,C.y)),await s(250),o.presence.moveTo(dc(d,j.x,j.y));try{await o.api.exec(t.docId,gm(v,a))}catch(D){n({type:"error",error:`${v.id}: ${D?.message??D}`});continue}l.set(v.id,v.kind==="geo"?v:v.kind==="text"?gc(v):qo(0,0)),S++,n({type:"drawn",n:S,el:v,ms:i()-$});let T=(v.say?r:0)-(i()-$);T>0&&await s(T)}return await A,y&&n({type:"error",error:`plan: ${y}`}),o.presence.park(),{steps:S,totalMs:i()-c,firstLineMs:w,planMs:u}}import{readFileSync as pm}from"fs";import{homedir as um}from"os";import{join as fm}from"path";var Yt=fm(um(),"Library","Application Support","tldraw","server.json"),Gn=class{constructor(o=Yt,t=fetch){this.serverJson=o;this.fetchFn=t}server(){let o;try{o=pm(this.serverJson,"utf8")}catch{throw new Error("tldraw offline is not running (no server.json)")}let{port:t,token:n}=JSON.parse(o);return{port:t,token:n}}async post(o,t){let{port:n,token:s}=this.server(),i=await this.fetchFn(`http://localhost:${n}${o}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${s}`},body:JSON.stringify(t)}),r=await i.json();if(!i.ok||r.success===!1)throw new Error(`tldraw ${o}: ${r.error??i.status}`);return r.result}createDoc(o,t){return this.post("/api/docs/create",{name:o,...t?{directory:t}:{}})}exec(o,t){return this.post(`/api/doc/${o}/exec`,{code:t})}search(o){return this.post("/api/search",{code:o})}};var km=$m(hm),vm="claude-sonnet-5";function xm(e){e.type==="planned"?console.log(so.dim(` planned ${e.n}: ${e.el.kind} ${e.el.id} at ${(e.atMs/1e3).toFixed(1)} s`)):e.type==="drawn"?console.log(`${so.cyan(` ${e.n}. ${e.el.kind} ${e.el.id}`)} ${e.el.say}${so.dim(` (${(e.ms/1e3).toFixed(1)} s)`)}`):e.type==="skipped"?console.log(so.yellow(` skipped: ${e.line}`)):console.log(so.red(` error: ${e.error}`))}async function Sm(){if(!Xs(Yt)){await km("open",["-a","tldraw offline"]);for(let e=0;e<40&&!Xs(Yt);e++)await new Promise(o=>setTimeout(o,500));if(!Xs(Yt))throw new Error("tldraw offline did not start")}}async function uc(e,o){let t=_(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=o.model||vm,i=bm(o.out||pc(wm(),"Documents")),r=$n(n,t.agents[n]),a=tt({system:cc(),model:s}),c=new kn(r,$e,n),d=new Gn;try{await Sm();let g=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),l=await d.createDoc(`agentx-draw-${g}`,i);await new Promise(y=>setTimeout(y,800)),console.log(so.bold(`
327
+ ${r.name} draws: ${e}`)+so.dim(` (${s}, ${l.filePath})
328
+ `));let p=new AbortController;process.once("SIGINT",()=>p.abort());let f=await mc(e,{api:d,presence:c,model:a},{docId:l.id,signal:p.signal},xm);await d.exec(l.id,"await helpers.saveDoc(); return true");let u=await d.search(`return await api.getScreenshot(${JSON.stringify(l.id)}, { size: 'full' })`),w=l.filePath?l.filePath.replace(/\.tldraw$/,".jpg"):pc(i,`agentx-draw-${g}.jpg`);ym(u.filePath,w),console.log(so.bold(`
329
+ ${f.steps} steps in ${(f.totalMs/1e3).toFixed(1)} s`)+so.dim(` (first shape planned at ${f.firstLineMs===null?"\u2013":(f.firstLineMs/1e3).toFixed(1)} s, plan done at ${(f.planMs/1e3).toFixed(1)} s)`)),console.log(so.dim(` ${l.filePath}
330
+ ${w}
331
+ `))}finally{a.close(),c.close()}}var Zs=Om(Am),yc=new Em().name("teach").description("walk through something on screen, speaking and pointing as it goes").argument("[lesson]","lesson id (omit to list)").option("--voice <voice>",`system voice name, "${ho}" for the OS default, or ElevenLabs voice id (overrides the agent's)`).option("--agent <id>","speak in this agent's voice (default: AGENTX_VOICE_AGENT or node.defaultAgent)").option("--no-speak","point only, print the narration").option("--no-hud","skip the on-screen callout").option("--record","record the screen (screencapture) around the lesson").option("--record-dir <path>","where to write the recording").option("--live <goal>","no lesson: the agent reads the screen and teaches this, step by step").option("--mode <mode>","with --live: teach (you do each step), watch (you drive, it coaches) act (it does it, if allowed) or draw (plans a tldraw offline illustration in one model turn and draws it)").option("--app <name>","with --live: open this app first").option("-c, --config <path>","with --live: agentx.json to read the agent from").option("--steps <n>","with --live: most steps before it stops (default 12)").option("--model <id>","with --mode draw: the planning model (default claude-sonnet-5)").option("--out <dir>","with --mode draw: where the .tldraw file and the picture go (default ~/Documents)").action(async(e,o)=>{if(o.live)try{o.mode==="draw"?await uc(String(o.live),o):await ic(String(o.live),o),process.exit(0)}catch(g){console.log(X.red(` ${g?.message??g}`)),process.exit(1)}if(!e){console.log(X.bold(`
298
332
  lessons
299
- `));for(let g of Us)console.log(` ${X.cyan(g.id.padEnd(22))} ${g.title}`),console.log(` ${" ".repeat(22)} ${X.dim(g.appHint)}
300
- `);return}let t=Us.find(g=>g.id===e);t||(console.log(X.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),Jg(Ee)||(console.log(X.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let n=o.speak===!1?void 0:Vg(o.voice,o.agent);console.log(X.bold(`
333
+ `));for(let g of Ks)console.log(` ${X.cyan(g.id.padEnd(22))} ${g.title}`),console.log(` ${" ".repeat(22)} ${X.dim(g.appHint)}
334
+ `);return}let t=Ks.find(g=>g.id===e);t||(console.log(X.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),Tm($e)||(console.log(X.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let n=o.speak===!1?void 0:Rm(o.voice,o.agent);console.log(X.bold(`
301
335
  ${t.title}`)),console.log(X.dim(` ${t.appHint}
302
- `));try{t.start&&(await qs("/usr/bin/open",zg(t.start)),await vo(2e3),await Dn(t.start.ready))}catch(g){console.log(X.red(` setup stopped: ${g?.message??g}`)),process.exitCode=3;return}let s=null,i=null;o.record&&(i=Xa(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(X.dim(` recording \u2192 ${i}`)),s=Ka("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await vo(2e3));let r=o.hud===!1?null:Ka(Ee,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(g,l,p,f)=>{try{r?.stdin?.write(JSON.stringify({title:g,body:l,state:p,avoid:f})+`
303
- `)}catch{}},c=[],d=!1;try{for(let[g,l]of t.steps.entries()){if(console.log(` ${X.dim(String(g+1).padStart(2))} ${l.say}`),a(`Step ${g+1} of ${t.steps.length}`,l.say,"talking"),l.click||l.type||l.key){if(!l.before)throw new Error(`Step ${g+1} needs a before claim`);await Dn(l.before)}let p=o.speak===!1?Promise.resolve():Xg(l.say,n),f=l.find?await Yg(l.find,c):null;if(l.find&&!f)throw c.push({tried:l.find,changed:!1,note:"not found on screen"}),await p,new Error(`Could not find "${l.find}"; stopped before acting`);if(await p,f&&(a(`Step ${g+1} of ${t.steps.length}`,l.say,"pointing",{x:f.x,y:f.y,w:f.width,h:f.height}),await qs(Ee,["point","--x",String(f.x),"--y",String(f.y),"--w",String(f.width),"--h",String(f.height),"--label",l.label??l.find??"","--hold",String(l.click||l.type?.5:l.holdSeconds??2.6)]),l.click)){let{error:u,changed:w}=await Fs(["click"]);if(u)throw new Error(u);c.push({tried:l.label??l.find??"control",changed:w!==!1,note:u??void 0}),w===!1&&console.log(X.yellow(" \xB7 clicked, but the screen did not change")),await vo(l.afterClickWaitMs??1500)}if(l.type){await Dn(l.before),a(`Step ${g+1} of ${t.steps.length}`,l.type,"typing");let{error:u}=await Fs(["type","--text",l.type]);if(u)throw console.log(X.red(` \u2717 ${u}`)),a("Blocked",u,"waiting"),c.push({tried:`type into ${l.label??"the field"}`,changed:!1,note:u}),new Error(u)}if(l.key){await Dn(l.before),a(`Step ${g+1} of ${t.steps.length}`,`\u21B5 ${l.key}`,"typing");let{error:u}=await Fs(["key","--name",l.key]);if(u)throw console.log(X.red(` \u2717 ${u}`)),a("Blocked",u,"waiting"),c.push({tried:`press ${l.key}`,changed:!1,note:u}),new Error(u)}if(!f&&!l.type&&!l.key?await vo((l.holdSeconds??1.2)*1e3):l.holdSeconds&&await vo(l.holdSeconds*1e3),l.verify){a(`Step ${g+1} of ${t.steps.length}`,"Checking that worked\u2026","waiting");let u;try{u=await Wt(l.verify)}catch(w){u=null,console.log(X.yellow(` ? could not check: ${w?.message??w}`))}if(!u&&!l.verifyOptional)throw new Error(`Could not verify: ${l.verify}`);if(u){let w=u.outcome==="confirmed"?X.green("\u2713"):u.outcome==="refuted"?X.red("\u2717"):X.yellow("?");if(console.log(` ${w} ${X.dim(u.reason)}`),!u.ok&&!l.verifyOptional){a("Stopped",`That did not work: ${l.verify}`,"waiting"),console.log(X.red(`
304
- stopping: could not confirm \u2014 ${l.verify}`)),console.log(X.dim(` ${u.reason}`)),console.log(X.dim(` screenshot: ${u.sighting.shot.path}`)),await vo(2500);try{r?.stdin?.end()}catch{}d=!0;break}}}}}catch(g){d=!0,console.log(X.red(` stopping: ${g?.message??g}`)),a("Stopped",String(g?.message??g),"waiting")}finally{if(d)try{r?.stdin?.end()}catch{}}if(!d){a("Done",t.title,"done"),await vo(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await vo(2500);try{let{size:g}=Hg(i);console.log(X.green(` recorded ${(g/1048576).toFixed(1)} MB \u2192 ${i}`))}catch{console.log(X.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(d){console.log(X.red(` lesson stopped before the end.
336
+ `));try{t.start&&(await Zs("/usr/bin/open",Cm(t.start)),await So(2e3),await Hn(t.start.ready))}catch(g){console.log(X.red(` setup stopped: ${g?.message??g}`)),process.exitCode=3;return}let s=null,i=null;o.record&&(i=hc(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(X.dim(` recording \u2192 ${i}`)),s=fc("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await So(2e3));let r=o.hud===!1?null:fc($e,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(g,l,p,f)=>{try{r?.stdin?.write(JSON.stringify({title:g,body:l,state:p,avoid:f})+`
337
+ `)}catch{}},c=[],d=!1;try{for(let[g,l]of t.steps.entries()){if(console.log(` ${X.dim(String(g+1).padStart(2))} ${l.say}`),a(`Step ${g+1} of ${t.steps.length}`,l.say,"talking"),l.click||l.type||l.key){if(!l.before)throw new Error(`Step ${g+1} needs a before claim`);await Hn(l.before)}let p=o.speak===!1?Promise.resolve():_m(l.say,n),f=l.find?await Nm(l.find,c):null;if(l.find&&!f)throw c.push({tried:l.find,changed:!1,note:"not found on screen"}),await p,new Error(`Could not find "${l.find}"; stopped before acting`);if(await p,f&&(a(`Step ${g+1} of ${t.steps.length}`,l.say,"pointing",{x:f.x,y:f.y,w:f.width,h:f.height}),await Zs($e,["point","--x",String(f.x),"--y",String(f.y),"--w",String(f.width),"--h",String(f.height),"--label",l.label??l.find??"","--hold",String(l.click||l.type?.5:l.holdSeconds??2.6)]),l.click)){let{error:u,changed:w}=await Qs(["click"]);if(u)throw new Error(u);c.push({tried:l.label??l.find??"control",changed:w!==!1,note:u??void 0}),w===!1&&console.log(X.yellow(" \xB7 clicked, but the screen did not change")),await So(l.afterClickWaitMs??1500)}if(l.type){await Hn(l.before),a(`Step ${g+1} of ${t.steps.length}`,l.type,"typing");let{error:u}=await Qs(["type","--text",l.type]);if(u)throw console.log(X.red(` \u2717 ${u}`)),a("Blocked",u,"waiting"),c.push({tried:`type into ${l.label??"the field"}`,changed:!1,note:u}),new Error(u)}if(l.key){await Hn(l.before),a(`Step ${g+1} of ${t.steps.length}`,`\u21B5 ${l.key}`,"typing");let{error:u}=await Qs(["key","--name",l.key]);if(u)throw console.log(X.red(` \u2717 ${u}`)),a("Blocked",u,"waiting"),c.push({tried:`press ${l.key}`,changed:!1,note:u}),new Error(u)}if(!f&&!l.type&&!l.key?await So((l.holdSeconds??1.2)*1e3):l.holdSeconds&&await So(l.holdSeconds*1e3),l.verify){a(`Step ${g+1} of ${t.steps.length}`,"Checking that worked\u2026","waiting");let u;try{u=await Ht(l.verify)}catch(w){u=null,console.log(X.yellow(` ? could not check: ${w?.message??w}`))}if(!u&&!l.verifyOptional)throw new Error(`Could not verify: ${l.verify}`);if(u){let w=u.outcome==="confirmed"?X.green("\u2713"):u.outcome==="refuted"?X.red("\u2717"):X.yellow("?");if(console.log(` ${w} ${X.dim(u.reason)}`),!u.ok&&!l.verifyOptional){a("Stopped",`That did not work: ${l.verify}`,"waiting"),console.log(X.red(`
338
+ stopping: could not confirm \u2014 ${l.verify}`)),console.log(X.dim(` ${u.reason}`)),console.log(X.dim(` screenshot: ${u.sighting.shot.path}`)),await So(2500);try{r?.stdin?.end()}catch{}d=!0;break}}}}}catch(g){d=!0,console.log(X.red(` stopping: ${g?.message??g}`)),a("Stopped",String(g?.message??g),"waiting")}finally{if(d)try{r?.stdin?.end()}catch{}}if(!d){a("Done",t.title,"done"),await So(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await So(2500);try{let{size:g}=Im(i);console.log(X.green(` recorded ${(g/1048576).toFixed(1)} MB \u2192 ${i}`))}catch{console.log(X.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(d){console.log(X.red(` lesson stopped before the end.
305
339
  `)),process.exitCode=3;return}console.log(X.green(`
306
340
  done.
307
- `))});function zg(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${Xa(Gg(),"agentx-teach-chrome")}`,"--no-first-run","--no-default-browser-check","--window-position=0,200","--window-size=1440,680",`--app=${e.url}`]:["-a",e.app,e.url]}async function Dn(e){let o=await Wt(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function Fs(e){try{let{stdout:o}=await qs(Ee,e),t=JSON.parse(o||"{}");return t.ok===!1?{error:String(t.error??"refused")}:{error:null,changed:t.changed}}catch(o){try{let t=JSON.parse(o?.stdout||"{}");if(t.error)return{error:String(t.error)}}catch{}return{error:o?.message??"failed"}}}async function Yg(e,o=[]){try{let t=await un({max:45});if(t.candidates.length<2)return null;let n=await Xe(Ft,In({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),Cn(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=Tn(n.answers,t.candidates);return s.present<.5?null:Ct(t,s.id)}catch{return null}}function Vg(e,o){if(e?.trim().toLowerCase()===uo)return{provider:"system",elevenlabs:It(),system:null,fallback:!0};let t=e?ln(e,jt()):null;if(t)return{provider:"system",elevenlabs:It(),system:t.id,fallback:!0};if(e)return{provider:"elevenlabs",elevenlabs:e,system:null,fallback:!0};try{let n=D(),s=o||process.env.AGENTX_VOICE_AGENT||n.node.defaultAgent;return s&&!n.agents[s]&&console.log(X.yellow(` no agent "${s}" in agentx.json \u2014 using the default voice`)),s&&n.agents[s]?vr($r(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:It(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(X.dim(` no agent voice (${String(n?.message??n).split(`
308
- `)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:It(),system:null,fallback:!0}}}var Kg=new Qo;async function Xg(e,o){o&&await Kg.say({voice:o,text:e})}var vo=e=>new Promise(o=>setTimeout(o,e));we();import{Command as Za}from"commander";import Me from"chalk";import{createInterface as ec}from"readline";var Qg=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function ct(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(Qg()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function Zg(e){e.type==="line"?console.log(`${Me.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(Me.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(Me.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(Me.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(Me.dim(" \xB7 hushed")):e.type==="error"?console.log(Me.red(` error: ${e.error}`)):e.type==="end"&&console.log(Me.dim(` \xB7 ended (${e.reason})`))}function oc(e){if(!e.length)return"no hand-overs measured";let o=[...e].sort((n,s)=>n-s);return`gap between speakers: median ${o[Math.floor(o.length/2)]} ms, max ${o.at(-1)} ms over ${e.length} hand-overs`}async function em(e,o,t){let n=D(t.config),s=n.agents,i;if(e.some(l=>!s[l])){let l=await ct("GET","/mesh").then(p=>Array.isArray(p.data)?p.data:[]).catch(()=>[]);i=new Sr(()=>n,()=>l),i.usePool(await xr(br()))}let r=e.map(l=>s[l]?dn(l,s,!0):i?.speaker(l,!0)),a=e.filter((l,p)=>!r[p]);if(a.length)throw new Error(`Unknown agent: ${a.join(", ")}`);let c=Date.now(),d=new Er({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new Qo,model:(l,p)=>gn({system:p})});d.on(Zg),d.on(l=>{l.type==="line"&&l.turn===0&&console.log(Me.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=ec({input:process.stdin});g.on("line",l=>{l.trim()&&d.door(l)}),process.once("SIGINT",()=>d.stop("interrupted")),await d.run(),g.close(),console.log(Me.dim(` ${oc(d.gaps)}`))}async function om(e,o,t){let n=await ct("POST","/talk",{agents:e,topic:o,context:t.context,maxTurns:Number(t.turns)||void 0});if(n.status>=300)throw new Error(n.data.error||`HTTP ${n.status}`);let s=ec({input:process.stdin});s.on("line",a=>{a.trim()&&ct("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void ct("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await ct("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${Me.bold(c[i].name)}: ${c[i].text}`);if(r=a.gaps??r,!a.active)break;await new Promise(d=>setTimeout(d,400))}s.close(),console.log(Me.dim(` ${oc(r)}`))}var tc=new Za().name("talk").description('two agents, local or on a mesh peer, talk a topic through out loud; type to cut in, "stop" to end').argument("<agentA>").argument("<agentB>").argument("<topic...>").option("--context <text>","a few lines of context both agents should know").option("--turns <n>","most lines before they wrap up (default 10)").option("--local","run the talk in this process instead of the daemon").option("-c, --config <path>","agentx.json for --local (default: the usual lookup)").action(async(e,o,t,n)=>{let s=t.join(" ");try{await(n.local?em:om)([e,o],s,n),process.exit(0)}catch(i){console.error(Me.red(` ${i?.message??i}`)),process.exit(1)}}),nc=new Za().name("narrate").description("switch spoken task narration on or off for an agent or one task").argument("<target>","agent id, or task id with --task").argument("<state>","on | off | default").option("--task","the target is a task id").action(async(e,o,t)=>{let n=o==="on"?!0:o==="off"?!1:o==="default"?null:void 0;n===void 0&&(console.error(Me.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await ct("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(Me.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});we();import{Command as tm}from"commander";import Se from"chalk";import{existsSync as nm,readFileSync as sm,writeFileSync as im}from"fs";import{resolve as sc}from"path";var Pn=new tm().name("voice").description("list installed system voices and pick each agent's voice");function rm(e){let o=e?[e]:[sc(process.cwd(),"agentx.json"),sc(process.cwd(),".agentx/config.json")],t=o.find(n=>nm(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function am(e,o,t,n,s){let{provider:i,gender:r}=n,a=n.lang?.toLowerCase().split(/[-_]/)[0],c=e?.agents?.[o];if(!c)throw new Error(`No agent "${o}" in agentx.json`);if(i&&i!=="system"&&i!=="elevenlabs")throw new Error("--provider must be system or elevenlabs");if(r&&!["female","male","neutral"].includes(r))throw new Error("--gender must be female, male or neutral");if(a&&!t)throw new Error("--lang needs a voice");if(!t&&!i&&!r)throw new Error("Give a voice, a --provider, a --gender, or a mix");let d={...c.voice??{}};i&&(d.provider=i),r&&(d.gender=r);let g=d.provider??e?.voice?.provider??"system",l=[i&&`provider ${i}`,r&&`gender ${r}`],p=w=>{if(!a){d.system=w;return}let y=typeof d.system=="string"?{[String(e?.voice?.locale??"en").toLowerCase().split(/[-_]/)[0]]:d.system}:{...d.system??{}};d.system={...y,[a]:w}},f=a?` for ${a}`:"";if(t){let w=t.trim().toLowerCase()===uo,y=w?null:ln(t,s,a??e?.voice?.locale),$=y?`system voice ${gs(y)}`:"the OS default voice";if((y||w)&&g==="system")p(w?uo:t),l.push(`${$}${f}`);else if(g==="elevenlabs"&&!y&&!w&&!a)d.elevenlabsVoiceId=t,l.push(`ElevenLabs voice ${t}`);else if(y||w)p(w?uo:t),l.push(`fallback ${$}${f}`);else throw new Error(`"${t}" is not an installed system voice. Run \`agentx voice list\`, or add --provider elevenlabs for an ElevenLabs voice id.`)}let u=l.filter(Boolean).join(", ");return{raw:{...e,agents:{...e.agents,[o]:{...c,voice:d}}},summary:u}}Pn.command("list").alias("ls").description("installed system voices, best first, and which agent uses which").option("--all","every language, not only the configured one").option("-c, --config <path>","agentx.json to read").action(e=>{let o=jt(),t;try{t=D(e.config)}catch{}let n=t?.voice.locale??"en",s=new Map,i=t?kr(t.agents,t.voice,o):new Map;if(t)for(let[r,a]of Object.entries(t.agents)){let c=i.get(r),d=Object.values(ms(r,a.voice?.system,a.voice?.gender,t.voice,o));for(let g of new Set([c,...d]))g&&s.set(g.id,[...s.get(g.id)??[],r])}if(!o.length)console.log(Se.yellow(`
341
+ `))});function Cm(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${hc(jm(),"agentx-teach-chrome")}`,"--no-first-run","--no-default-browser-check","--window-position=0,200","--window-size=1440,680",`--app=${e.url}`]:["-a",e.app,e.url]}async function Hn(e){let o=await Ht(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function Qs(e){try{let{stdout:o}=await Zs($e,e),t=JSON.parse(o||"{}");return t.ok===!1?{error:String(t.error??"refused")}:{error:null,changed:t.changed}}catch(o){try{let t=JSON.parse(o?.stdout||"{}");if(t.error)return{error:String(t.error)}}catch{}return{error:o?.message??"failed"}}}async function Nm(e,o=[]){try{let t=await bn({max:45});if(t.candidates.length<2)return null;let n=await Qe(Jt,Pn({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),Ln(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=Mn(n.answers,t.candidates);return s.present<.5?null:Dt(t,s.id)}catch{return null}}function Rm(e,o){if(e?.trim().toLowerCase()===ho)return{provider:"system",elevenlabs:Rt(),system:null,fallback:!0};let t=e?fn(e,Nt()):null;if(t)return{provider:"system",elevenlabs:Rt(),system:t.id,fallback:!0};if(e)return{provider:"elevenlabs",elevenlabs:e,system:null,fallback:!0};try{let n=_(),s=o||process.env.AGENTX_VOICE_AGENT||n.node.defaultAgent;return s&&!n.agents[s]&&console.log(X.yellow(` no agent "${s}" in agentx.json \u2014 using the default voice`)),s&&n.agents[s]?Dr(Nr(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:Rt(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(X.dim(` no agent voice (${String(n?.message??n).split(`
342
+ `)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:Rt(),system:null,fallback:!0}}}var Dm=new ot;async function _m(e,o){o&&await Dm.say({voice:o,text:e})}var So=e=>new Promise(o=>setTimeout(o,e));pe();import{Command as wc}from"commander";import Me from"chalk";import{createInterface as bc}from"readline";var Pm=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function mt(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(Pm()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function Lm(e){e.type==="line"?console.log(`${Me.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(Me.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(Me.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(Me.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(Me.dim(" \xB7 hushed")):e.type==="error"?console.log(Me.red(` error: ${e.error}`)):e.type==="end"&&console.log(Me.dim(` \xB7 ended (${e.reason})`))}function $c(e){if(!e.length)return"no hand-overs measured";let o=[...e].sort((n,s)=>n-s);return`gap between speakers: median ${o[Math.floor(o.length/2)]} ms, max ${o.at(-1)} ms over ${e.length} hand-overs`}async function Mm(e,o,t){let n=_(t.config),s=n.agents,i;if(e.some(l=>!s[l])){let l=await mt("GET","/mesh").then(p=>Array.isArray(p.data)?p.data:[]).catch(()=>[]);i=new Pr(()=>n,()=>l),i.usePool(await _r(Cr()))}let r=e.map(l=>s[l]?hn(l,s,!0):i?.speaker(l,!0)),a=e.filter((l,p)=>!r[p]);if(a.length)throw new Error(`Unknown agent: ${a.join(", ")}`);let c=Date.now(),d=new Lr({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new ot,model:(l,p)=>tt({system:p})});d.on(Lm),d.on(l=>{l.type==="line"&&l.turn===0&&console.log(Me.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=bc({input:process.stdin});g.on("line",l=>{l.trim()&&d.door(l)}),process.once("SIGINT",()=>d.stop("interrupted")),await d.run(),g.close(),console.log(Me.dim(` ${$c(d.gaps)}`))}async function Fm(e,o,t){let n=await mt("POST","/talk",{agents:e,topic:o,context:t.context,maxTurns:Number(t.turns)||void 0});if(n.status>=300)throw new Error(n.data.error||`HTTP ${n.status}`);let s=bc({input:process.stdin});s.on("line",a=>{a.trim()&&mt("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void mt("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await mt("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${Me.bold(c[i].name)}: ${c[i].text}`);if(r=a.gaps??r,!a.active)break;await new Promise(d=>setTimeout(d,400))}s.close(),console.log(Me.dim(` ${$c(r)}`))}var kc=new wc().name("talk").description('two agents, local or on a mesh peer, talk a topic through out loud; type to cut in, "stop" to end').argument("<agentA>").argument("<agentB>").argument("<topic...>").option("--context <text>","a few lines of context both agents should know").option("--turns <n>","most lines before they wrap up (default 10)").option("--local","run the talk in this process instead of the daemon").option("-c, --config <path>","agentx.json for --local (default: the usual lookup)").action(async(e,o,t,n)=>{let s=t.join(" ");try{await(n.local?Mm:Fm)([e,o],s,n),process.exit(0)}catch(i){console.error(Me.red(` ${i?.message??i}`)),process.exit(1)}}),vc=new wc().name("narrate").description("switch spoken task narration on or off for an agent or one task").argument("<target>","agent id, or task id with --task").argument("<state>","on | off | default").option("--task","the target is a task id").action(async(e,o,t)=>{let n=o==="on"?!0:o==="off"?!1:o==="default"?null:void 0;n===void 0&&(console.error(Me.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await mt("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(Me.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});pe();import{Command as Um}from"commander";import Ee from"chalk";import{existsSync as qm,readFileSync as Wm,writeFileSync as Bm}from"fs";import{resolve as xc}from"path";var zn=new Um().name("voice").description("list installed system voices and pick each agent's voice");function Jm(e){let o=e?[e]:[xc(process.cwd(),"agentx.json"),xc(process.cwd(),".agentx/config.json")],t=o.find(n=>qm(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function Gm(e,o,t,n,s){let{provider:i,gender:r}=n,a=n.lang?.toLowerCase().split(/[-_]/)[0],c=e?.agents?.[o];if(!c)throw new Error(`No agent "${o}" in agentx.json`);if(i&&i!=="system"&&i!=="elevenlabs")throw new Error("--provider must be system or elevenlabs");if(r&&!["female","male","neutral"].includes(r))throw new Error("--gender must be female, male or neutral");if(a&&!t)throw new Error("--lang needs a voice");if(!t&&!i&&!r)throw new Error("Give a voice, a --provider, a --gender, or a mix");let d={...c.voice??{}};i&&(d.provider=i),r&&(d.gender=r);let g=d.provider??e?.voice?.provider??"system",l=[i&&`provider ${i}`,r&&`gender ${r}`],p=w=>{if(!a){d.system=w;return}let y=typeof d.system=="string"?{[String(e?.voice?.locale??"en").toLowerCase().split(/[-_]/)[0]]:d.system}:{...d.system??{}};d.system={...y,[a]:w}},f=a?` for ${a}`:"";if(t){let w=t.trim().toLowerCase()===ho,y=w?null:fn(t,s,a??e?.voice?.locale),k=y?`system voice ${vs(y)}`:"the OS default voice";if((y||w)&&g==="system")p(w?ho:t),l.push(`${k}${f}`);else if(g==="elevenlabs"&&!y&&!w&&!a)d.elevenlabsVoiceId=t,l.push(`ElevenLabs voice ${t}`);else if(y||w)p(w?ho:t),l.push(`fallback ${k}${f}`);else throw new Error(`"${t}" is not an installed system voice. Run \`agentx voice list\`, or add --provider elevenlabs for an ElevenLabs voice id.`)}let u=l.filter(Boolean).join(", ");return{raw:{...e,agents:{...e.agents,[o]:{...c,voice:d}}},summary:u}}zn.command("list").alias("ls").description("installed system voices, best first, and which agent uses which").option("--all","every language, not only the configured one").option("-c, --config <path>","agentx.json to read").action(e=>{let o=Nt(),t;try{t=_(e.config)}catch{}let n=t?.voice.locale??"en",s=new Map,i=t?Rr(t.agents,t.voice,o):new Map;if(t)for(let[r,a]of Object.entries(t.agents)){let c=i.get(r),d=Object.values(xs(r,a.voice?.system,a.voice?.gender,t.voice,o));for(let g of new Set([c,...d]))g&&s.set(g.id,[...s.get(g.id)??[],r])}if(!o.length)console.log(Ee.yellow(`
309
343
  No system voices found (system voices need macOS).
310
- `));else{let r=e.all?ds(o,""):ds(o,n);console.log(Se.bold(`
344
+ `));else{let r=e.all?ks(o,""):ks(o,n);console.log(Ee.bold(`
311
345
  System voices${e.all?"":` (${n})`}, best first
312
- `));for(let a of r){let c=a.siri?Se.magenta("siri"):a.quality==="standard"?Se.dim("standard"):Se.green(a.quality),d=s.get(a.id)?.join(", ");console.log(` ${(a.siri?`siri:${a.name.toLowerCase()}`:a.name).padEnd(12)} ${a.locale.padEnd(6)} ${c.padEnd(18)} ${Se.dim((a.gender??"").padEnd(7))} ${d?Se.cyan(d):""}`)}o.some(a=>a.quality!=="standard")||(console.log(Se.dim(`
313
- More natural voices are free: System Settings \u2192 Accessibility \u2192 Spoken Content \u2192`)),console.log(Se.dim(" System Voice \u2192 Manage Voices, then download a Premium or Enhanced voice.")))}if(t){console.log(Se.bold(`
346
+ `));for(let a of r){let c=a.siri?Ee.magenta("siri"):a.quality==="standard"?Ee.dim("standard"):Ee.green(a.quality),d=s.get(a.id)?.join(", ");console.log(` ${(a.siri?`siri:${a.name.toLowerCase()}`:a.name).padEnd(12)} ${a.locale.padEnd(6)} ${c.padEnd(18)} ${Ee.dim((a.gender??"").padEnd(7))} ${d?Ee.cyan(d):""}`)}o.some(a=>a.quality!=="standard")||(console.log(Ee.dim(`
347
+ More natural voices are free: System Settings \u2192 Accessibility \u2192 Spoken Content \u2192`)),console.log(Ee.dim(" System Voice \u2192 Manage Voices, then download a Premium or Enhanced voice.")))}if(t){console.log(Ee.bold(`
314
348
  Agents
315
- `));for(let[r,a]of Object.entries(t.agents)){let c=a.voice?.provider??t.voice.provider,d=p=>p?gs(p):Se.dim("system default"),g=Object.entries(ms(r,a.voice?.system,a.voice?.gender,t.voice,o)).filter(([,p])=>(p?.id??null)!==(i.get(r)?.id??null)).map(([p,f])=>`${Se.dim(`${p}:`)} ${d(f)}`).join(Se.dim(" \xB7 ")),l=c==="elevenlabs"?`elevenlabs ${a.voice?.elevenlabsVoiceId??Se.dim("(default voice)")}`:`system ${d(i.get(r))}${g?Se.dim(" \xB7 ")+g:""}`;console.log(` ${r.padEnd(24)} ${l}${a.voice?.gender?Se.dim(` (${a.voice.gender})`):""}`)}}console.log()});Pn.command("set <agent> [voice]").description(`pick an agent's voice: a system voice name, a Siri voice as siri:<name>, "${uo}" for the OS default, or an ElevenLabs id with --provider elevenlabs`).option("--provider <provider>","system or elevenlabs").option("--lang <lang>","use this voice for lines in one language only: en, fr, ar").option("--gender <gender>","female, male or neutral; an assigned voice matches it").option("-c, --config <path>","agentx.json to change").action((e,o,t)=>{try{let n=rm(t.config),{raw:s,summary:i}=am(JSON.parse(sm(n,"utf8")),e,o,t,jt());im(n,JSON.stringify(s,null,2)+`
316
- `),console.log(Se.green(` ${e}: ${i}`)),console.log(Se.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(Se.red(` ${n.message}`)),process.exit(1)}});import{Command as cm}from"commander";import M from"chalk";var Uo=new cm().name("attach").description("wear an agentx agent identity in this Claude Code session"),Ws=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Rt()}`;function Bs(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function Js(e,o,t){let n=await fetch(`${e}${o}`,{method:t?"POST":"GET",headers:{"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0}),s=await n.text(),i=null;try{i=s?JSON.parse(s):null}catch{}if(!n.ok)throw new Error(i?.error||s||`HTTP ${n.status}`);return i}function Hs(e){let o=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(o)?`daemon not reachable \u2014 start it with ${M.cyan("agentx daemon start")}`:o}function ic(e){return e==="auto"?M.yellow:e==="manual"?M.gray:M.green}function lm(e,o=!1){let t=e.agentIds.length?e.agentIds.join(", "):M.gray("(not bound)"),n=e.pending?M.yellow(`${e.pending} pending`):M.gray("empty"),s=o?M.cyan(" \u2190 this session"):"";console.log(` ${M.bold(t)} ${ic(e.mode)(e.mode)} ${n} ${M.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${M.gray(e.cwd)}`)}Uo.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${as.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",Ws).action(async(e,o)=>{let t=Bs(o.session);t||(console.error(M.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${M.cyan("--session <id>")} (list them with ${M.cyan("agentx attach list")}).`),process.exit(1)),Fi(o.mode)||(console.error(M.red(`Invalid mode "${o.mode}". Expected one of: ${as.join(", ")}`)),process.exit(1)),xn()||(console.error(M.yellow("Attach hooks are not installed yet.")),console.error(`Run ${M.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{let n=await Js(o.url,"/attach/bind",{sessionId:t,agentId:e,mode:o.mode,cwd:process.cwd()});console.log(`${M.green("\u2713")} This session is now wearing ${M.bold(e)} (${ic(o.mode)(o.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(M.yellow(` ${s} message(s) already queued for it.`)),console.log(M.gray(o.mode==="auto"?" Queued messages will be answered automatically at the end of each turn.":o.mode==="notify"?" You'll be told when messages arrive; run /inbox to answer them.":" Nothing will interrupt you; run /inbox to check for messages."))}catch(n){console.error(M.red(`Bind failed: ${Hs(n)}`)),process.exit(1)}});Uo.command("detach").description("stop wearing an identity in this session (queued work falls back to spawned agents)").option("--agent <id>","release only this identity (default: all)").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",Ws).action(async e=>{let o=Bs(e.session);o||(console.error(M.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await Js(e.url,"/attach/detach",{sessionId:o,agentId:e.agent}),console.log(`${M.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(t){console.error(M.red(`Detach failed: ${Hs(t)}`)),process.exit(1)}});Uo.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",Ws).option("--json","raw JSON output").action(async e=>{let o=Bs();try{let n=(await Js(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:xn(),sessions:n},null,2));return}console.log(),console.log(xn()?`${M.green("\u2713")} Attach hooks installed ${M.gray(Nt())}`:`${M.yellow("!")} Attach hooks not installed \u2014 run ${M.cyan("agentx attach install")}`),console.log();let s=n.filter(r=>r.agentIds.length>0);if(s.length===0)console.log(M.gray(" No session is wearing an identity right now."));else for(let r of s)lm(r,r.sessionId===o);let i=n.length-s.length;i>0&&console.log(M.gray(`
317
- ${i} registered session(s) with no binding.`)),console.log()}catch(t){console.error(M.red(`Could not read attach state: ${Hs(t)}`)),process.exit(1)}});Uo.command("install").description("wire the attach hooks into ~/.claude/settings.json (one time, all sessions)").option("--port <n>","daemon port the hooks should call (default: node.bind in agentx.json)").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--no-guard","skip the PreToolUse guard hook (not recommended)").action(e=>{try{let o=String(e.port||Rt()),t=na(o,{path:e.path,withGuard:e.guard});console.log(t.changed?`${M.green("\u2713")} Installed attach hooks in ${M.gray(t.path)}`:`${M.green("\u2713")} Attach hooks already up to date in ${M.gray(t.path)}`),console.log(M.gray(` Events: ${t.events.join(", ")} \u2192 127.0.0.1:${o}`)),t.guardInstalled?(console.log(M.gray(" PreToolUse guard installed at user scope.")),console.log(M.gray(` (An attached session runs under your permissions, not the agent's workspace
349
+ `));for(let[r,a]of Object.entries(t.agents)){let c=a.voice?.provider??t.voice.provider,d=p=>p?vs(p):Ee.dim("system default"),g=Object.entries(xs(r,a.voice?.system,a.voice?.gender,t.voice,o)).filter(([,p])=>(p?.id??null)!==(i.get(r)?.id??null)).map(([p,f])=>`${Ee.dim(`${p}:`)} ${d(f)}`).join(Ee.dim(" \xB7 ")),l=c==="elevenlabs"?`elevenlabs ${a.voice?.elevenlabsVoiceId??Ee.dim("(default voice)")}`:`system ${d(i.get(r))}${g?Ee.dim(" \xB7 ")+g:""}`;console.log(` ${r.padEnd(24)} ${l}${a.voice?.gender?Ee.dim(` (${a.voice.gender})`):""}`)}}console.log()});zn.command("set <agent> [voice]").description(`pick an agent's voice: a system voice name, a Siri voice as siri:<name>, "${ho}" for the OS default, or an ElevenLabs id with --provider elevenlabs`).option("--provider <provider>","system or elevenlabs").option("--lang <lang>","use this voice for lines in one language only: en, fr, ar").option("--gender <gender>","female, male or neutral; an assigned voice matches it").option("-c, --config <path>","agentx.json to change").action((e,o,t)=>{try{let n=Jm(t.config),{raw:s,summary:i}=Gm(JSON.parse(Wm(n,"utf8")),e,o,t,Nt());Bm(n,JSON.stringify(s,null,2)+`
350
+ `),console.log(Ee.green(` ${e}: ${i}`)),console.log(Ee.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(Ee.red(` ${n.message}`)),process.exit(1)}});import{Command as Hm}from"commander";import M from"chalk";var Wo=new Hm().name("attach").description("wear an agentx agent identity in this Claude Code session"),ei=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Lt()}`;function oi(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function ti(e,o,t){let n=await fetch(`${e}${o}`,{method:t?"POST":"GET",headers:{"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0}),s=await n.text(),i=null;try{i=s?JSON.parse(s):null}catch{}if(!n.ok)throw new Error(i?.error||s||`HTTP ${n.status}`);return i}function ni(e){let o=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(o)?`daemon not reachable \u2014 start it with ${M.cyan("agentx daemon start")}`:o}function Sc(e){return e==="auto"?M.yellow:e==="manual"?M.gray:M.green}function zm(e,o=!1){let t=e.agentIds.length?e.agentIds.join(", "):M.gray("(not bound)"),n=e.pending?M.yellow(`${e.pending} pending`):M.gray("empty"),s=o?M.cyan(" \u2190 this session"):"";console.log(` ${M.bold(t)} ${Sc(e.mode)(e.mode)} ${n} ${M.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${M.gray(e.cwd)}`)}Wo.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${ws.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",ei).action(async(e,o)=>{let t=oi(o.session);t||(console.error(M.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${M.cyan("--session <id>")} (list them with ${M.cyan("agentx attach list")}).`),process.exit(1)),Qi(o.mode)||(console.error(M.red(`Invalid mode "${o.mode}". Expected one of: ${ws.join(", ")}`)),process.exit(1)),jn()||(console.error(M.yellow("Attach hooks are not installed yet.")),console.error(`Run ${M.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{let n=await ti(o.url,"/attach/bind",{sessionId:t,agentId:e,mode:o.mode,cwd:process.cwd()});console.log(`${M.green("\u2713")} This session is now wearing ${M.bold(e)} (${Sc(o.mode)(o.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(M.yellow(` ${s} message(s) already queued for it.`)),console.log(M.gray(o.mode==="auto"?" Queued messages will be answered automatically at the end of each turn.":o.mode==="notify"?" You'll be told when messages arrive; run /inbox to answer them.":" Nothing will interrupt you; run /inbox to check for messages."))}catch(n){console.error(M.red(`Bind failed: ${ni(n)}`)),process.exit(1)}});Wo.command("detach").description("stop wearing an identity in this session (queued work falls back to spawned agents)").option("--agent <id>","release only this identity (default: all)").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",ei).action(async e=>{let o=oi(e.session);o||(console.error(M.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await ti(e.url,"/attach/detach",{sessionId:o,agentId:e.agent}),console.log(`${M.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(t){console.error(M.red(`Detach failed: ${ni(t)}`)),process.exit(1)}});Wo.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",ei).option("--json","raw JSON output").action(async e=>{let o=oi();try{let n=(await ti(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:jn(),sessions:n},null,2));return}console.log(),console.log(jn()?`${M.green("\u2713")} Attach hooks installed ${M.gray(Pt())}`:`${M.yellow("!")} Attach hooks not installed \u2014 run ${M.cyan("agentx attach install")}`),console.log();let s=n.filter(r=>r.agentIds.length>0);if(s.length===0)console.log(M.gray(" No session is wearing an identity right now."));else for(let r of s)zm(r,r.sessionId===o);let i=n.length-s.length;i>0&&console.log(M.gray(`
351
+ ${i} registered session(s) with no binding.`)),console.log()}catch(t){console.error(M.red(`Could not read attach state: ${ni(t)}`)),process.exit(1)}});Wo.command("install").description("wire the attach hooks into ~/.claude/settings.json (one time, all sessions)").option("--port <n>","daemon port the hooks should call (default: node.bind in agentx.json)").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--no-guard","skip the PreToolUse guard hook (not recommended)").action(e=>{try{let o=String(e.port||Lt()),t=pa(o,{path:e.path,withGuard:e.guard});console.log(t.changed?`${M.green("\u2713")} Installed attach hooks in ${M.gray(t.path)}`:`${M.green("\u2713")} Attach hooks already up to date in ${M.gray(t.path)}`),console.log(M.gray(` Events: ${t.events.join(", ")} \u2192 127.0.0.1:${o}`)),t.guardInstalled?(console.log(M.gray(" PreToolUse guard installed at user scope.")),console.log(M.gray(` (An attached session runs under your permissions, not the agent's workspace
318
352
  settings \u2014 without this an attached production identity would be less
319
- guarded than a spawned one.)`))):console.log(M.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${M.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(M.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Uo.command("uninstall").description("remove the attach hooks from ~/.claude/settings.json").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--remove-guard","also remove the PreToolUse guard hook").action(e=>{try{let o=sa({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${M.green("\u2713")} Removed attach hooks from ${M.gray(o.path)} (${o.events.join(", ")})`:`${M.gray("Nothing to remove.")}`),e.removeGuard||console.log(M.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(M.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});we();import{Command as dm}from"commander";import pe from"chalk";var Ln=new dm().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function ac(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=D(e.config);o||(o=n.dashboard?.daemonUrl||""),t||(t=n.dashboard?.token||"")}catch{}return o||(o="http://localhost:18800"),{baseUrl:o.replace(/\/+$/,""),token:t}}function cc(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function rc(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s`:o<3600?`${Math.round(o/60)}m`:o<86400?`${Math.round(o/3600)}h`:`${Math.round(o/86400)}d`}function gm(e){return e==="busy"?pe.magenta:e==="warm-hot"?pe.green:e==="warm-cold"?pe.cyan:e==="idle"?pe.yellow:e==="dead"?pe.red:pe.dim}Ln.command("list").description("list every live persistent claude process").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("--json","emit JSON").action(async e=>{let{baseUrl:o,token:t}=ac(e),n;try{n=await fetch(`${o}/api/processes`,{headers:cc(t)})}catch(r){console.log(pe.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(pe.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(pe.red(` HTTP ${n.status} from ${o}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(pe.dim(" (no processes)"));return}for(let r of i){let a=gm(r.state)(r.state.padEnd(9)),c=rc(r.spawnedAt),d=r.lastTurnAt?rc(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?pe.dim(`last_in=${r.lastInputTokens} tok`):"",l=r.claudeSessionId?pe.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):pe.dim("sess=\u2014"),p=r.pendingTaskId?pe.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${pe.bold(r.key.agentId)}${pe.dim(":"+r.key.channel+":"+r.key.chatId)} ${pe.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${d} ${l} ${g} ${p}`),r.deadReason&&console.log(` ${pe.red("dead:")} ${r.deadReason}`)}});Ln.command("kill <agentId> <channel> <chatId>").description("force-kill one persistent process (the next dispatch will spawn fresh)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("-r, --reason <reason>","kill reason (recorded on the dead-process snapshot)","operator-cli").action(async(e,o,t,n)=>{let{baseUrl:s,token:i}=ac(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:cc(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(pe.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(pe.dim(" daemon has no persistent-process registry"));return}if(!r.ok){let a=`HTTP ${r.status}`;try{let c=await r.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(pe.red(` ${a}`)),process.exit(1)}console.log(pe.green(` killed ${e}:${o}:${t}`))});import{Command as mm}from"commander";import Te from"chalk";import{existsSync as Gs,rmSync as pm}from"fs";import{resolve as zs}from"path";var lt=new mm().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");lt.command("add <agentId>").description("build or refresh an agent's lexical index from one or more globs").argument("<globs...>","glob patterns relative to cwd (e.g. './docs/**/*.md')").option("-v, --verbose","log each indexed file").action(async(e,o,t)=>{o.length===0&&(console.log(Te.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await Ji(e,o,{verbose:n}),r=Date.now()-s;console.log(Te.green(` \u2713 indexed ${i.docs} doc(s) for ${Te.bold(e)} in ${r}ms`)),console.log(Te.dim(` \u2192 ${i.path}`))});lt.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=zs(e.cwd,".agentx","rag");if(!Gs(o)){console.log(Te.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>Gs(zs(o,s,"index.json")));if(n.length===0){console.log(Te.dim(" (no indexes)"));return}for(let s of n.sort()){let i=cs(s);console.log(` ${Te.bold(s)} ${i.docs} doc(s) ${Te.dim(i.path)}`)}});lt.command("search <agentId> <query>").description("query an agent's index \u2014 useful for debugging recall before the agent calls rag.lexical").option("-k, --k <n>","top-k results","5").option("--json","emit JSON").action((e,o,t)=>{let n=parseInt(t.k,10)||5,s=Hi(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=cs(e);i.exists?console.log(Te.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Te.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Te.bold(i.title)} ${Te.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Te.dim(i.path)}`),console.log(` ${Te.dim(i.snippet.slice(0,200))}`)});lt.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=zs(process.cwd(),".agentx","rag",e);if(!Gs(o)){console.log(Te.dim(` no index for ${e} \u2014 nothing to clear`));return}pm(o,{recursive:!0,force:!0}),console.log(Te.green(` \u2713 cleared index for ${e}`))});we();import{Command as um}from"commander";import K from"chalk";import dt from"prompts";var Fo=new um().name("backlog").description("manage the local backlog used by business workSource=backlog");function Bt(e){let o=D(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new Dr(n)}}function fm(e){return e?K.cyan(`${e.type}:${e.project}#${e.iid}`):K.dim("manual")}function hm(e){return{todo:K.gray("todo"),doing:K.yellow("doing"),blocked:K.red("blocked"),done:K.green("done")}[e]}Fo.command("list",{isDefault:!0}).description("list backlog items").option("--status <status>","filter by status (todo|doing|blocked|done)").option("--assignee <agent>","filter by assignee").option("--source <type>","filter by source.type (gitlab|github|manual)").option("-c, --config <path>","config path").action(async e=>{let{store:o}=Bt(e.config),t=o.list();if(e.status&&(t=t.filter(n=>n.status===e.status)),e.assignee&&(t=t.filter(n=>n.assignee===e.assignee)),e.source&&(t=t.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!t.length){console.log(K.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?K.magenta(`@${n.assignee}`):K.dim("unassigned");console.log(` ${hm(n.status).padEnd(7)} ${fm(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(K.dim(` ${n.source.url}`))}console.log(),console.log(K.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});Fo.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,o,t)=>{let n=Bt(t.config);n.store.findById(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(K.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=Pr([o],i.source,n.config),a=await hs(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(K.dim(" sync:"),...c));console.log(a.ok?K.dim(` synced -> ${a.url??i.source.type}`):K.yellow(` sync failed: ${a.error}`))}});Fo.command("done <id>").description("mark an item as done; closes the upstream issue if linked").option("--note <text>","comment to post upstream").option("--close","also close the upstream issue (default: only labels change)",!1).option("-c, --config <path>","config path").action(async(e,o)=>{let t=Bt(o.config);t.store.findById(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(K.green(` done: ${s.title}`)),s.source){let i=await hs(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(K.dim(" sync:"),...r));console.log(i.ok?K.dim(` synced -> ${i.url??s.source.type}`):K.yellow(` sync failed: ${i.error}`))}});Fo.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,o)=>{let{store:t}=Bt(o.config);t.remove(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1)),console.log(K.green(` removed ${e}`))});Fo.command("import").description("import open issues from gitlab/github into the backlog (interactive)").option("--source <type>","source type (gitlab|github)").option("--project <id>","project id (group/repo for gitlab, owner/repo for github)").option("--assignee <agent>","assign all imported items to this agentId").option("-c, --config <path>","config path").action(async e=>{let o=Bt(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(K.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let y=[t&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await dt({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!t&&(console.error(K.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(K.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?wm(o.config):bm(o.config);y.length?(i=(await dt({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...y.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await dt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await dt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await dt({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(K.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await $m(o.config,i,a):await km(o.config,i,a);if(!c.length){console.log(K.yellow(" no open issues matched"));return}console.log(K.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let d=i,g=new Set(o.store.list().map(y=>y.id)),l=c.map(y=>{let $=fs({type:s,project:d,iid:y.iid,url:y.url}),b=g.has($),v=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${v}${b?K.dim(" (already imported)"):""}`,value:y,disabled:b}}),f=(await dt({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:l,min:1})).selected||[];if(!f.length){console.log(K.dim(" nothing selected"));return}let u=f.map(y=>{let $={type:s,host:s==="gitlab"?ym(o.config):void 0,project:d,iid:y.iid,url:y.url};return{id:fs($),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:$,importedAt:new Date().toISOString()}}),w=o.store.addMany(u);console.log(K.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(K.dim(` ${y.id} \u2014 ${y.title}`))});function ym(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function wm(e){let o=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&o.add(n.project);let t=e.business?.workSource;if(t?.type==="gitlab")for(let n of t.projects??[])o.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&o.add(n.id);return[...o].sort()}function bm(e){let o=new Set;for(let t of e.channels.github?.routes??[])t.repo&&t.repo!=="*"&&o.add(t.repo);return[...o].sort()}async function $m(e,o,t){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});t&&s.set("search",t);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(o)}/issues?${s}`,{headers:{"PRIVATE-TOKEN":n.token}});if(!i.ok)throw new Error(`GitLab ${i.status}: ${await i.text().catch(()=>"")}`);let r=await i.json();return Array.isArray(r)?r.map(a=>({iid:a.iid,title:a.title,description:a.description||void 0,labels:Array.isArray(a.labels)?a.labels.map(c=>typeof c=="string"?c:c.name):[],milestone:a.milestone?.title||void 0,assignee:a.assignee?.username||a.assignees?.[0]?.username||void 0,url:a.web_url})):[]}async function km(e,o,t){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(t){let c=`repo:${o} is:issue is:open ${t}`;i=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let d=await fetch(i,{headers:s});if(!d.ok)throw new Error(`GitHub ${d.status}: ${await d.text().catch(()=>"")}`);return((await d.json()).items??[]).map(lc)}i=`https://api.github.com/repos/${o}/issues?state=open&per_page=100&sort=updated&direction=desc`;let r=await fetch(i,{headers:s});if(!r.ok)throw new Error(`GitHub ${r.status}: ${await r.text().catch(()=>"")}`);let a=await r.json();return Array.isArray(a)?a.filter(c=>!c.pull_request).map(lc):[]}function lc(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(o=>typeof o=="string"?o:o.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as Sm}from"commander";import z from"chalk";import{existsSync as Em,readFileSync as Am}from"fs";import{resolve as Om}from"path";import jm from"prompts";we();import vm from"cronstrue";var Ys={sun:0,sunday:0,mon:1,monday:1,tue:2,tuesday:2,tues:2,wed:3,wednesday:3,thu:4,thursday:4,thurs:4,fri:5,friday:5,sat:6,saturday:6},Mn={morning:{h:9,m:0},afternoon:{h:14,m:0},evening:{h:18,m:0},night:{h:22,m:0},noon:{h:12,m:0},midnight:{h:0,m:0}};function no(e){try{return vm.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function xm(e){if(/\b(noon|midday)\b/.test(e))return Mn.noon;if(/\bmidnight\b/.test(e))return Mn.midnight;let o=e.match(/\b(?:at|by|@)\s*(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/);if(o){let t=parseInt(o[1],10),n=o[2]?parseInt(o[2],10):0,s=o[3];return s==="pm"&&t<12&&(t+=12),s==="am"&&t===12&&(t=0),t>23||n>59?null:{h:t,m:n}}return null}function Vs(e){let o=e.trim().toLowerCase();if(!o)return null;let t;if(t=o.match(/\bevery\s+(\d+)\s*(minutes|mins|m)\b/)){let l=parseInt(t[1],10);return l<1||l>59?null:{cron:`*/${l} * * * *`,human:no(`*/${l} * * * *`),matched:t[0]}}if(/\bevery\s+minute\b/.test(o))return{cron:"* * * * *",human:no("* * * * *"),matched:"every minute"};if(t=o.match(/\bevery\s+(\d+)\s*(hours|hrs|h)\b/)){let l=parseInt(t[1],10);return l<1||l>23?null:{cron:`0 */${l} * * *`,human:no(`0 */${l} * * *`),matched:t[0]}}if(/\b(every hour|hourly)\b/.test(o))return{cron:"0 * * * *",human:no("0 * * * *"),matched:"every hour"};let n=xm(o),s=null;for(let[l,p]of Object.entries(Mn))if(!(l==="noon"||l==="midnight")&&new RegExp(`\\b(every\\s+)?${l}s?\\b`).test(o)){s=p;break}let i=n||s,r=o.match(/\b(first|1st|2nd|3rd|last|(\d+)(?:st|nd|rd|th)?)\s+(day\s+)?of\s+(every|each|the)\s+month\b/);if(r){let l=r[1],p=1;if(l==="last"||(/^\d+(st|nd|rd|th)?$/.test(l)?p=parseInt(l,10):l==="first"||l==="1st"?p=1:l==="2nd"?p=2:l==="3rd"&&(p=3),p<1||p>31))return null;let f=i||{h:9,m:0},u=`${f.m} ${f.h} ${p} * *`;return{cron:u,human:no(u),matched:r[0]}}let a=[],c=Object.keys(Ys).join("|"),d=new RegExp(`\\b(?:every|on|each|by)\\s+((?:${c})s?(?:\\s*(?:,|and|&)\\s*(?:${c})s?)*)\\b`),g=o.match(d);if(g){let l=g[1];for(let p of Object.keys(Ys))if(new RegExp(`\\b${p}s?\\b`).test(l)){let f=Ys[p];a.includes(f)||a.push(f)}}if(a.length){let l=i||{h:9,m:0};a.sort((u,w)=>u-w);let p=a.join(","),f=`${l.m} ${l.h} * * ${p}`;return{cron:f,human:no(f),matched:`on ${p}`}}if(/\b(weekday|workday|business day)s?\b/.test(o)){let l=i||{h:9,m:0},p=`${l.m} ${l.h} * * 1-5`;return{cron:p,human:no(p),matched:"weekdays"}}if(/\bweekends?\b/.test(o)){let l=i||{h:9,m:0},p=`${l.m} ${l.h} * * 0,6`;return{cron:p,human:no(p),matched:"weekends"}}if(/\b(every day|daily|each day)\b/.test(o)||s){let l=i||{h:9,m:0},p=`${l.m} ${l.h} * * *`;return{cron:p,human:no(p),matched:s&&Object.entries(Mn).find(([,f])=>f===s)?.[0]||"daily"}}if(n){let l=`${n.m} ${n.h} * * *`;return{cron:l,human:no(l),matched:`at ${n.h}:${String(n.m).padStart(2,"0")}`}}return null}function dc(e,o){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"job"}-${o}`}function gc(e){let o=e||Om(process.cwd(),"agentx.json");return Em(o)||(console.log(z.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Am(o,"utf-8"))}function Im(e){return e?e.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o==="log"||o==="notify"||o==="disable"):["log"]}async function Cm(e,o){if(!e)return;if(e==="me"){let n=o?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(z.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await jm([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let t=e.split(":");if(t.length>=2)return{channel:t[0],chatId:t[1],accountId:t[2]};console.log(z.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var xo=new Sm().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');xo.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>","IANA timezone (default: Africa/Tunis)","Africa/Tunis").option("--timeout <seconds>","max run time","600").option("--model <model>","override model").option("--disabled","create but leave disabled").option("--dry-run","print what would be written without writing").action(async(e,o)=>{if(!e){xo.help();return}o.agent||(console.log(z.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(z.red(' --do "<prompt>" is required')),process.exit(1));let t=Vs(e);t||(console.log(z.red(` Couldn't parse: "${e}"`)),console.log(z.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(z.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(z.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=gc(o.config),s=Ai(n);n.agents?.[o.agent]||(console.log(z.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(z.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=Im(o.onError),r=await Cm(o.notify,s);r&&!i.includes("notify")&&i.push("notify");let a=o.id||dc(t.matched,o.agent),c={enabled:!o.disabled,schedule:t.cron,timezone:o.timezone,agent:o.agent,prompt:o.do,timeout:parseInt(o.timeout,10),onError:i};o.model&&(c.model=o.model),r&&(c.notify=r);let d=await de(l=>be(l,`crons.${a}`,c),{configPath:o.config,dryRun:!!o.dryRun});d.success||(console.log(z.red(` \u2717 ${d.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(z.green(` \u2713 ${g} cron ${z.cyan(a)}`)),console.log(z.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(z.dim(` Agent: ${o.agent}`)),r&&console.log(z.dim(` Notify: ${r.channel} ${r.chatId}`)),i.length&&console.log(z.dim(` On error: ${i.join(", ")}`)),!o.dryRun&&d.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});xo.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async e=>{let t=gc(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(z.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.enabled?z.green("\u25CF"):z.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}console.log(` ${r} ${z.cyan(s.padEnd(32))} ${z.dim(i.schedule.padEnd(14))} ${z.dim("\u2192")} ${i.agent}`),console.log(z.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(z.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`))}console.log()});for(let[e,o]of[["on",!0],["off",!1]])xo.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await de(s=>{if(!To(s,`crons.${t}`))throw new Error(`cron "${t}" not found`);be(s,`crons.${t}.enabled`,o)});n.success||(console.log(z.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(z.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});xo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await de(t=>{if(!To(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);Vi(t,`crons.${e}`)});o.success||(console.log(z.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(z.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});xo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Vs(o);t||(console.log(z.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(z.green(` "${o}"`)),console.log(z.dim(` \u2192 ${t.cron}`)),console.log(z.dim(` \u2192 ${t.human}`))});import{Command as Zm}from"commander";import gt from"chalk";import Z from"chalk";import Ht from"prompts";import{readFileSync as Tm,writeFileSync as Nm,existsSync as Rm}from"fs";import{resolve as mc}from"path";var _m=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Dm(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function Ks(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function pc(e=".env"){let o=mc(e);if(!Rm(o))return[];let t=Tm(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(_m);i?n.push({kind:"kv",key:i[1],value:Dm(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Pm(e){return e.map(o=>o.kind==="kv"?`${o.key}=${Ks(o.value)}`:o.raw).join(`
353
+ guarded than a spawned one.)`))):console.log(M.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${M.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(M.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Wo.command("uninstall").description("remove the attach hooks from ~/.claude/settings.json").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--remove-guard","also remove the PreToolUse guard hook").action(e=>{try{let o=ua({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${M.green("\u2713")} Removed attach hooks from ${M.gray(o.path)} (${o.events.join(", ")})`:`${M.gray("Nothing to remove.")}`),e.removeGuard||console.log(M.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(M.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});pe();import{Command as Ym}from"commander";import ue from"chalk";var Yn=new Ym().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Ac(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=_(e.config);o||(o=n.dashboard?.daemonUrl||""),t||(t=n.dashboard?.token||"")}catch{}return o||(o="http://localhost:18800"),{baseUrl:o.replace(/\/+$/,""),token:t}}function Oc(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function Ec(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s`:o<3600?`${Math.round(o/60)}m`:o<86400?`${Math.round(o/3600)}h`:`${Math.round(o/86400)}d`}function Vm(e){return e==="busy"?ue.magenta:e==="warm-hot"?ue.green:e==="warm-cold"?ue.cyan:e==="idle"?ue.yellow:e==="dead"?ue.red:ue.dim}Yn.command("list").description("list every live persistent claude process").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("--json","emit JSON").action(async e=>{let{baseUrl:o,token:t}=Ac(e),n;try{n=await fetch(`${o}/api/processes`,{headers:Oc(t)})}catch(r){console.log(ue.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(ue.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(ue.red(` HTTP ${n.status} from ${o}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(ue.dim(" (no processes)"));return}for(let r of i){let a=Vm(r.state)(r.state.padEnd(9)),c=Ec(r.spawnedAt),d=r.lastTurnAt?Ec(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?ue.dim(`last_in=${r.lastInputTokens} tok`):"",l=r.claudeSessionId?ue.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):ue.dim("sess=\u2014"),p=r.pendingTaskId?ue.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${ue.bold(r.key.agentId)}${ue.dim(":"+r.key.channel+":"+r.key.chatId)} ${ue.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${d} ${l} ${g} ${p}`),r.deadReason&&console.log(` ${ue.red("dead:")} ${r.deadReason}`)}});Yn.command("kill <agentId> <channel> <chatId>").description("force-kill one persistent process (the next dispatch will spawn fresh)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("-r, --reason <reason>","kill reason (recorded on the dead-process snapshot)","operator-cli").action(async(e,o,t,n)=>{let{baseUrl:s,token:i}=Ac(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Oc(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(ue.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(ue.dim(" daemon has no persistent-process registry"));return}if(!r.ok){let a=`HTTP ${r.status}`;try{let c=await r.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(ue.red(` ${a}`)),process.exit(1)}console.log(ue.green(` killed ${e}:${o}:${t}`))});import{Command as Km}from"commander";import Ce from"chalk";import{existsSync as si,rmSync as Xm}from"fs";import{resolve as ii}from"path";var pt=new Km().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");pt.command("add <agentId>").description("build or refresh an agent's lexical index from one or more globs").argument("<globs...>","glob patterns relative to cwd (e.g. './docs/**/*.md')").option("-v, --verbose","log each indexed file").action(async(e,o,t)=>{o.length===0&&(console.log(Ce.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await tr(e,o,{verbose:n}),r=Date.now()-s;console.log(Ce.green(` \u2713 indexed ${i.docs} doc(s) for ${Ce.bold(e)} in ${r}ms`)),console.log(Ce.dim(` \u2192 ${i.path}`))});pt.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=ii(e.cwd,".agentx","rag");if(!si(o)){console.log(Ce.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>si(ii(o,s,"index.json")));if(n.length===0){console.log(Ce.dim(" (no indexes)"));return}for(let s of n.sort()){let i=bs(s);console.log(` ${Ce.bold(s)} ${i.docs} doc(s) ${Ce.dim(i.path)}`)}});pt.command("search <agentId> <query>").description("query an agent's index \u2014 useful for debugging recall before the agent calls rag.lexical").option("-k, --k <n>","top-k results","5").option("--json","emit JSON").action((e,o,t)=>{let n=parseInt(t.k,10)||5,s=nr(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=bs(e);i.exists?console.log(Ce.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Ce.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Ce.bold(i.title)} ${Ce.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Ce.dim(i.path)}`),console.log(` ${Ce.dim(i.snippet.slice(0,200))}`)});pt.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=ii(process.cwd(),".agentx","rag",e);if(!si(o)){console.log(Ce.dim(` no index for ${e} \u2014 nothing to clear`));return}Xm(o,{recursive:!0,force:!0}),console.log(Ce.green(` \u2713 cleared index for ${e}`))});pe();import{Command as Qm}from"commander";import K from"chalk";import ut from"prompts";var Bo=new Qm().name("backlog").description("manage the local backlog used by business workSource=backlog");function Vt(e){let o=_(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new Gr(n)}}function Zm(e){return e?K.cyan(`${e.type}:${e.project}#${e.iid}`):K.dim("manual")}function ep(e){return{todo:K.gray("todo"),doing:K.yellow("doing"),blocked:K.red("blocked"),done:K.green("done")}[e]}Bo.command("list",{isDefault:!0}).description("list backlog items").option("--status <status>","filter by status (todo|doing|blocked|done)").option("--assignee <agent>","filter by assignee").option("--source <type>","filter by source.type (gitlab|github|manual)").option("-c, --config <path>","config path").action(async e=>{let{store:o}=Vt(e.config),t=o.list();if(e.status&&(t=t.filter(n=>n.status===e.status)),e.assignee&&(t=t.filter(n=>n.assignee===e.assignee)),e.source&&(t=t.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!t.length){console.log(K.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?K.magenta(`@${n.assignee}`):K.dim("unassigned");console.log(` ${ep(n.status).padEnd(7)} ${Zm(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(K.dim(` ${n.source.url}`))}console.log(),console.log(K.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});Bo.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,o,t)=>{let n=Vt(t.config);n.store.findById(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(K.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=Hr([o],i.source,n.config),a=await Os(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(K.dim(" sync:"),...c));console.log(a.ok?K.dim(` synced -> ${a.url??i.source.type}`):K.yellow(` sync failed: ${a.error}`))}});Bo.command("done <id>").description("mark an item as done; closes the upstream issue if linked").option("--note <text>","comment to post upstream").option("--close","also close the upstream issue (default: only labels change)",!1).option("-c, --config <path>","config path").action(async(e,o)=>{let t=Vt(o.config);t.store.findById(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(K.green(` done: ${s.title}`)),s.source){let i=await Os(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(K.dim(" sync:"),...r));console.log(i.ok?K.dim(` synced -> ${i.url??s.source.type}`):K.yellow(` sync failed: ${i.error}`))}});Bo.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,o)=>{let{store:t}=Vt(o.config);t.remove(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1)),console.log(K.green(` removed ${e}`))});Bo.command("import").description("import open issues from gitlab/github into the backlog (interactive)").option("--source <type>","source type (gitlab|github)").option("--project <id>","project id (group/repo for gitlab, owner/repo for github)").option("--assignee <agent>","assign all imported items to this agentId").option("-c, --config <path>","config path").action(async e=>{let o=Vt(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(K.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let y=[t&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await ut({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!t&&(console.error(K.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(K.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?tp(o.config):np(o.config);y.length?(i=(await ut({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...y.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await ut({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await ut({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await ut({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(K.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await sp(o.config,i,a):await ip(o.config,i,a);if(!c.length){console.log(K.yellow(" no open issues matched"));return}console.log(K.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let d=i,g=new Set(o.store.list().map(y=>y.id)),l=c.map(y=>{let k=As({type:s,project:d,iid:y.iid,url:y.url}),b=g.has(k),x=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${x}${b?K.dim(" (already imported)"):""}`,value:y,disabled:b}}),f=(await ut({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:l,min:1})).selected||[];if(!f.length){console.log(K.dim(" nothing selected"));return}let u=f.map(y=>{let k={type:s,host:s==="gitlab"?op(o.config):void 0,project:d,iid:y.iid,url:y.url};return{id:As(k),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),w=o.store.addMany(u);console.log(K.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(K.dim(` ${y.id} \u2014 ${y.title}`))});function op(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function tp(e){let o=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&o.add(n.project);let t=e.business?.workSource;if(t?.type==="gitlab")for(let n of t.projects??[])o.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&o.add(n.id);return[...o].sort()}function np(e){let o=new Set;for(let t of e.channels.github?.routes??[])t.repo&&t.repo!=="*"&&o.add(t.repo);return[...o].sort()}async function sp(e,o,t){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});t&&s.set("search",t);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(o)}/issues?${s}`,{headers:{"PRIVATE-TOKEN":n.token}});if(!i.ok)throw new Error(`GitLab ${i.status}: ${await i.text().catch(()=>"")}`);let r=await i.json();return Array.isArray(r)?r.map(a=>({iid:a.iid,title:a.title,description:a.description||void 0,labels:Array.isArray(a.labels)?a.labels.map(c=>typeof c=="string"?c:c.name):[],milestone:a.milestone?.title||void 0,assignee:a.assignee?.username||a.assignees?.[0]?.username||void 0,url:a.web_url})):[]}async function ip(e,o,t){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(t){let c=`repo:${o} is:issue is:open ${t}`;i=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let d=await fetch(i,{headers:s});if(!d.ok)throw new Error(`GitHub ${d.status}: ${await d.text().catch(()=>"")}`);return((await d.json()).items??[]).map(Tc)}i=`https://api.github.com/repos/${o}/issues?state=open&per_page=100&sort=updated&direction=desc`;let r=await fetch(i,{headers:s});if(!r.ok)throw new Error(`GitHub ${r.status}: ${await r.text().catch(()=>"")}`);let a=await r.json();return Array.isArray(a)?a.filter(c=>!c.pull_request).map(Tc):[]}function Tc(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(o=>typeof o=="string"?o:o.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as cp}from"commander";import z from"chalk";import{existsSync as lp,readFileSync as dp}from"fs";import{resolve as gp}from"path";import mp from"prompts";pe();import rp from"cronstrue";var ri={sun:0,sunday:0,mon:1,monday:1,tue:2,tuesday:2,tues:2,wed:3,wednesday:3,thu:4,thursday:4,thurs:4,fri:5,friday:5,sat:6,saturday:6},Vn={morning:{h:9,m:0},afternoon:{h:14,m:0},evening:{h:18,m:0},night:{h:22,m:0},noon:{h:12,m:0},midnight:{h:0,m:0}};function io(e){try{return rp.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function ap(e){if(/\b(noon|midday)\b/.test(e))return Vn.noon;if(/\bmidnight\b/.test(e))return Vn.midnight;let o=e.match(/\b(?:at|by|@)\s*(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/);if(o){let t=parseInt(o[1],10),n=o[2]?parseInt(o[2],10):0,s=o[3];return s==="pm"&&t<12&&(t+=12),s==="am"&&t===12&&(t=0),t>23||n>59?null:{h:t,m:n}}return null}function ai(e){let o=e.trim().toLowerCase();if(!o)return null;let t;if(t=o.match(/\bevery\s+(\d+)\s*(minutes|mins|m)\b/)){let l=parseInt(t[1],10);return l<1||l>59?null:{cron:`*/${l} * * * *`,human:io(`*/${l} * * * *`),matched:t[0]}}if(/\bevery\s+minute\b/.test(o))return{cron:"* * * * *",human:io("* * * * *"),matched:"every minute"};if(t=o.match(/\bevery\s+(\d+)\s*(hours|hrs|h)\b/)){let l=parseInt(t[1],10);return l<1||l>23?null:{cron:`0 */${l} * * *`,human:io(`0 */${l} * * *`),matched:t[0]}}if(/\b(every hour|hourly)\b/.test(o))return{cron:"0 * * * *",human:io("0 * * * *"),matched:"every hour"};let n=ap(o),s=null;for(let[l,p]of Object.entries(Vn))if(!(l==="noon"||l==="midnight")&&new RegExp(`\\b(every\\s+)?${l}s?\\b`).test(o)){s=p;break}let i=n||s,r=o.match(/\b(first|1st|2nd|3rd|last|(\d+)(?:st|nd|rd|th)?)\s+(day\s+)?of\s+(every|each|the)\s+month\b/);if(r){let l=r[1],p=1;if(l==="last"||(/^\d+(st|nd|rd|th)?$/.test(l)?p=parseInt(l,10):l==="first"||l==="1st"?p=1:l==="2nd"?p=2:l==="3rd"&&(p=3),p<1||p>31))return null;let f=i||{h:9,m:0},u=`${f.m} ${f.h} ${p} * *`;return{cron:u,human:io(u),matched:r[0]}}let a=[],c=Object.keys(ri).join("|"),d=new RegExp(`\\b(?:every|on|each|by)\\s+((?:${c})s?(?:\\s*(?:,|and|&)\\s*(?:${c})s?)*)\\b`),g=o.match(d);if(g){let l=g[1];for(let p of Object.keys(ri))if(new RegExp(`\\b${p}s?\\b`).test(l)){let f=ri[p];a.includes(f)||a.push(f)}}if(a.length){let l=i||{h:9,m:0};a.sort((u,w)=>u-w);let p=a.join(","),f=`${l.m} ${l.h} * * ${p}`;return{cron:f,human:io(f),matched:`on ${p}`}}if(/\b(weekday|workday|business day)s?\b/.test(o)){let l=i||{h:9,m:0},p=`${l.m} ${l.h} * * 1-5`;return{cron:p,human:io(p),matched:"weekdays"}}if(/\bweekends?\b/.test(o)){let l=i||{h:9,m:0},p=`${l.m} ${l.h} * * 0,6`;return{cron:p,human:io(p),matched:"weekends"}}if(/\b(every day|daily|each day)\b/.test(o)||s){let l=i||{h:9,m:0},p=`${l.m} ${l.h} * * *`;return{cron:p,human:io(p),matched:s&&Object.entries(Vn).find(([,f])=>f===s)?.[0]||"daily"}}if(n){let l=`${n.m} ${n.h} * * *`;return{cron:l,human:io(l),matched:`at ${n.h}:${String(n.m).padStart(2,"0")}`}}return null}function Ic(e,o){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"job"}-${o}`}function jc(e){let o=e||gp(process.cwd(),"agentx.json");return lp(o)||(console.log(z.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(dp(o,"utf-8"))}function pp(e){return e?e.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o==="log"||o==="notify"||o==="disable"):["log"]}async function up(e,o){if(!e)return;if(e==="me"){let n=o?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(z.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await mp([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let t=e.split(":");if(t.length>=2)return{channel:t[0],chatId:t[1],accountId:t[2]};console.log(z.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var Eo=new cp().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');Eo.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>","IANA timezone (default: Africa/Tunis)","Africa/Tunis").option("--timeout <seconds>","max run time","600").option("--model <model>","override model").option("--disabled","create but leave disabled").option("--dry-run","print what would be written without writing").action(async(e,o)=>{if(!e){Eo.help();return}o.agent||(console.log(z.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(z.red(' --do "<prompt>" is required')),process.exit(1));let t=ai(e);t||(console.log(z.red(` Couldn't parse: "${e}"`)),console.log(z.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(z.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(z.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=jc(o.config),s=Mi(n);n.agents?.[o.agent]||(console.log(z.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(z.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=pp(o.onError),r=await up(o.notify,s);r&&!i.includes("notify")&&i.push("notify");let a=o.id||Ic(t.matched,o.agent),c={enabled:!o.disabled,schedule:t.cron,timezone:o.timezone,agent:o.agent,prompt:o.do,timeout:parseInt(o.timeout,10),onError:i};o.model&&(c.model=o.model),r&&(c.notify=r);let d=await de(l=>be(l,`crons.${a}`,c),{configPath:o.config,dryRun:!!o.dryRun});d.success||(console.log(z.red(` \u2717 ${d.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(z.green(` \u2713 ${g} cron ${z.cyan(a)}`)),console.log(z.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(z.dim(` Agent: ${o.agent}`)),r&&console.log(z.dim(` Notify: ${r.channel} ${r.chatId}`)),i.length&&console.log(z.dim(` On error: ${i.join(", ")}`)),!o.dryRun&&d.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});Eo.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async e=>{let t=jc(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(z.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.enabled?z.green("\u25CF"):z.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}console.log(` ${r} ${z.cyan(s.padEnd(32))} ${z.dim(i.schedule.padEnd(14))} ${z.dim("\u2192")} ${i.agent}`),console.log(z.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(z.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`))}console.log()});for(let[e,o]of[["on",!0],["off",!1]])Eo.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await de(s=>{if(!Ro(s,`crons.${t}`))throw new Error(`cron "${t}" not found`);be(s,`crons.${t}.enabled`,o)});n.success||(console.log(z.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(z.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});Eo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await de(t=>{if(!Ro(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);ar(t,`crons.${e}`)});o.success||(console.log(z.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(z.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});Eo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=ai(o);t||(console.log(z.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(z.green(` "${o}"`)),console.log(z.dim(` \u2192 ${t.cron}`)),console.log(z.dim(` \u2192 ${t.human}`))});import{Command as Lp}from"commander";import ft from"chalk";import Z from"chalk";import Xt from"prompts";import{readFileSync as fp,writeFileSync as hp,existsSync as yp}from"fs";import{resolve as Cc}from"path";var wp=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function bp(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function ci(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Nc(e=".env"){let o=Cc(e);if(!yp(o))return[];let t=fp(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(wp);i?n.push({kind:"kv",key:i[1],value:bp(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function $p(e){return e.map(o=>o.kind==="kv"?`${o.key}=${ci(o.value)}`:o.raw).join(`
320
354
  `)+`
321
- `}function Jt(e,o,t=".env"){let n=mc(t),s=pc(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Ks(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Ks(o)}`})),Nm(n,Pm(s))}function Xs(e,o=".env"){return pc(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var uc="https://t.me/BotFather";async function Lm(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 Mm(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 fc(e={}){console.log(),console.log(Z.bold(" Connect Telegram")),console.log(),console.log(Z.dim(` 1. Open ${uc}`)),console.log(Z.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Z.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await Ht({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),v=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(v,[uc],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Ht({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(Z.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Lm(t.trim());n||(console.log(Z.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Z.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(Z.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),d=Object.keys(c.agents||{});d.length===0&&(console.log(Z.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Ht({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:d.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(Z.red(" Aborted")),process.exit(1));let l=c.channels?.telegram?.accounts||{},p=e.account||g;l[p]&&l[p].agentBinding!==g&&(p=(await Ht({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(Z.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Jt(f,t.trim()),process.env[f]=t.trim();let u=await de(b=>{be(b,"channels.telegram.enabled",!0),be(b,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:g});let v=To(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),be(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(u.success||(console.log(Z.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(Z.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(Z.dim(` Token stored in .env as ${f}`)),console.log(Z.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(Z.dim(" Daemon hot-reloaded.")):console.log(Z.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await Ht({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(Z.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Z.dim(" Waiting up to 90s..."));let y=await Mm(t.trim(),9e4);if(!y){console.log(Z.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Z.dim(" agentx config set notifications.destination.channel telegram")),console.log(Z.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Z.dim(` agentx config set notifications.destination.accountId ${p}`));return}let $=await de(b=>{be(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:p})},{configPath:e.configPath});if(!$.success){console.log(Z.red(` \u2717 failed to save destination: ${$.error}`));return}console.log(Z.green(" \u2713 Default --notify target set")),console.log(Z.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Z.dim(" From now on, --notify me resolves to this chat.")),$.reloaded&&console.log(Z.dim(" Daemon hot-reloaded."))}import ue from"chalk";import Qs from"prompts";import{existsSync as ei,mkdirSync as Um,readdirSync as Fm,readFileSync as hc}from"fs";import{resolve as Zs}from"path";var qm=".agentx/whatsapp-sessions";function Wm(){let e=Zs(process.cwd(),".agentx/daemon.pid");if(!ei(e))return!1;try{let o=parseInt(hc(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Bm(e){if(!ei(e))return!1;try{return Fm(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Jm(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ue.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ue.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;Um(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},d=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 d.ev.on("creds.update",r),await new Promise(g=>{let p=setTimeout(()=>{o(ue.yellow(" Timed out waiting for scan (2min)."));try{d.end(void 0)}catch{}g(!1)},12e4);d.ev.on("connection.update",async f=>{if(f.qr){o(ue.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:u}=await import("qrcode-terminal");u.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(p),o(ue.green(" \u2713 Paired"));try{d.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),o(ue.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function yc(e={}){if(console.log(),console.log(ue.bold(" Connect WhatsApp")),console.log(),Wm()){console.log(ue.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ue.dim(" agentx daemon stop")),console.log();let{cont:d}=await Qs({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});d||(console.log(ue.red(" Aborted")),process.exit(1))}let o=e.configPath||Zs(process.cwd(),"agentx.json");ei(o)||(console.log(ue.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(hc(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||qm,s=Zs(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ue.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Qs({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ue.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Bm(s)&&a){let{keep:d}=await Qs({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!d,d&&console.log(ue.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Jm(s,g=>console.log(g))||(console.log(ue.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await de(d=>{be(d,"channels.whatsapp.enabled",!0),be(d,"channels.whatsapp.sessionDir",n),be(d,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ue.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ue.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ue.dim(` Session: ${n}`)),console.log(ue.dim(" Start the daemon to begin receiving:")),console.log(ue.dim(" agentx daemon start")),console.log(ue.dim(" Add routes later with:")),console.log(ue.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Hm}from"crypto";import $e from"chalk";import wc from"prompts";var Un="agentx-mesh:",Fn="//join/";function Gm(e){return Buffer.from(e,"utf-8").toString("base64url")}function zm(e){return Buffer.from(e,"base64url").toString("utf-8")}function Ym(e){return`${Un}${Fn}${Gm(JSON.stringify(e))}`}function Vm(e){if(!e.startsWith(`${Un}${Fn}`))throw new Error(`Not a mesh invite link \u2014 expected ${Un}${Fn}\u2026`);let o=e.slice(Un.length+Fn.length),t=JSON.parse(zm(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 Km(){return Hm(32).toString("hex")}function Xm(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Qm(e){return e?.node?.name||e?.node?.id||"node"}async function bc(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($e.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Xs("MESH_TOKEN");r||(r=Km(),Jt("MESH_TOKEN",r),console.log($e.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Xm(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:l}=await wc({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});l||(console.log($e.red(" Aborted")),process.exit(1)),a=l}let d=await de(l=>{be(l,"mesh.enabled",!0)},{configPath:e.configPath});d.success||(console.log($e.red(` \u2717 ${d.error}`)),process.exit(1));let g=Ym({url:a,token:r,name:Qm(i),version:1});console.log(),console.log($e.bold(" Mesh invite")),console.log(),console.log(` ${$e.cyan(g)}`),console.log(),console.log($e.dim(" Run on the other node:")),console.log($e.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log($e.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function $c(e,o={}){let t;try{t=Vm(e)}catch(i){console.log($e.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Xs("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await wc({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log($e.red(" Aborted (keeping existing .env)")),process.exit(1))}Jt("MESH_TOKEN",t.token);let s=await de(i=>{be(i,"mesh.enabled",!0);let r=To(i,"mesh.peers")||[],a=r.findIndex(d=>d.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),be(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log($e.red(` \u2717 ${s.error}`)),process.exit(1)),console.log($e.green(" \u2713 Joined mesh")),console.log($e.dim(` Peer: ${t.name} @ ${t.url}`)),console.log($e.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log($e.dim(" Daemon hot-reloaded.")):console.log($e.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($e.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log($e.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log($e.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var mt=new Zm().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");mt.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 fc({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});mt.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 yc({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var kc=mt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");kc.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 bc({url:e.url,configPath:e.config})});kc.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 $c(e,{configPath:o.config})});mt.action(()=>{console.log(),console.log(gt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${gt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${gt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${gt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${gt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(gt.dim(" GitLab connect is the next slice.")),console.log()});we();import{Command as ep}from"commander";import le from"chalk";var Gt=new ep().name("usage").description("token usage analysis and reporting");Gt.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=D(),[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(le.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(le.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${le.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: ${le.red(String(s.totalErrors))}`),console.log(),console.log(le.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 d=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${le.cyan(a)}: ${d} tokens (${c.tasks} tasks) ${le.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(le.red(" Daemon not running. Start with: agentx daemon start")):console.log(le.red(` ${e.message}`))}});Gt.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(le.red(` Script not found: ${s}`)),console.log(le.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(le.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(le.red(" Analysis failed. Is Python 3 installed?"))}});Gt.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-UREILT2E.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-FJLMTESZ.js"),r=await i(),a=new Set(n.filter(l=>l.kind==="cli").map(l=>l.name)),c=[],d=(l,p)=>{for(let f of l.commands??[]){let u=p?`${p} ${f.name()}`:f.name();c.push(u),d(f,u)}};d(r,"");let g=c.filter(l=>!a.has(l)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(le.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let l of g)console.log(` ${le.dim("\xB7")} ${l}`);console.log(),console.log(le.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(le.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(le.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(le.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(le.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(le.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=le.dim(`${i.days}d`);console.log(` ${le.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(le.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as op}from"commander";import fe from"chalk";import{resolve as tp}from"path";we();var So=new op().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");So.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{Pi(tp(process.cwd(),".env"))}catch{}let o=np(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-HLTVSSGW.js");t(o)}catch(o){console.log(fe.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(fe.dim(o.stack)),process.exit(1)}});function np(e,o){try{let t=D();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(fe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(fe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
322
- `)),{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}}}}So.command("list").description("list configured boards").action(()=>{try{let e=D();if(!e.boards?.length){console.log(fe.dim(`
355
+ `}function Kt(e,o,t=".env"){let n=Cc(t),s=Nc(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${ci(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${ci(o)}`})),hp(n,$p(s))}function li(e,o=".env"){return Nc(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var Rc="https://t.me/BotFather";async function kp(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 vp(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 Dc(e={}){console.log(),console.log(Z.bold(" Connect Telegram")),console.log(),console.log(Z.dim(` 1. Open ${Rc}`)),console.log(Z.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Z.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await Xt({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),x=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(x,[Rc],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Xt({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(Z.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await kp(t.trim());n||(console.log(Z.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Z.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(Z.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),d=Object.keys(c.agents||{});d.length===0&&(console.log(Z.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Xt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:d.map(x=>({title:x,value:x})),initial:0})).agent),g||(console.log(Z.red(" Aborted")),process.exit(1));let l=c.channels?.telegram?.accounts||{},p=e.account||g;l[p]&&l[p].agentBinding!==g&&(p=(await Xt({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(Z.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Kt(f,t.trim()),process.env[f]=t.trim();let u=await de(b=>{be(b,"channels.telegram.enabled",!0),be(b,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:g});let x=Ro(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;x.includes(A)||(x.push(A),be(b,`agents.${g}.mentions`,x))},{configPath:e.configPath});if(u.success||(console.log(Z.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(Z.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(Z.dim(` Token stored in .env as ${f}`)),console.log(Z.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(Z.dim(" Daemon hot-reloaded.")):console.log(Z.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await Xt({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(Z.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Z.dim(" Waiting up to 90s..."));let y=await vp(t.trim(),9e4);if(!y){console.log(Z.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Z.dim(" agentx config set notifications.destination.channel telegram")),console.log(Z.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Z.dim(` agentx config set notifications.destination.accountId ${p}`));return}let k=await de(b=>{be(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:p})},{configPath:e.configPath});if(!k.success){console.log(Z.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(Z.green(" \u2713 Default --notify target set")),console.log(Z.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Z.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(Z.dim(" Daemon hot-reloaded."))}import fe from"chalk";import di from"prompts";import{existsSync as mi,mkdirSync as xp,readdirSync as Sp,readFileSync as _c}from"fs";import{resolve as gi}from"path";var Ep=".agentx/whatsapp-sessions";function Ap(){let e=gi(process.cwd(),".agentx/daemon.pid");if(!mi(e))return!1;try{let o=parseInt(_c(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Op(e){if(!mi(e))return!1;try{return Sp(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Tp(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(fe.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(fe.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;xp(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},d=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 d.ev.on("creds.update",r),await new Promise(g=>{let p=setTimeout(()=>{o(fe.yellow(" Timed out waiting for scan (2min)."));try{d.end(void 0)}catch{}g(!1)},12e4);d.ev.on("connection.update",async f=>{if(f.qr){o(fe.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:u}=await import("qrcode-terminal");u.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(p),o(fe.green(" \u2713 Paired"));try{d.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),o(fe.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Pc(e={}){if(console.log(),console.log(fe.bold(" Connect WhatsApp")),console.log(),Ap()){console.log(fe.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(fe.dim(" agentx daemon stop")),console.log();let{cont:d}=await di({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});d||(console.log(fe.red(" Aborted")),process.exit(1))}let o=e.configPath||gi(process.cwd(),"agentx.json");mi(o)||(console.log(fe.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(_c(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Ep,s=gi(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(fe.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await di({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(fe.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Op(s)&&a){let{keep:d}=await di({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!d,d&&console.log(fe.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Tp(s,g=>console.log(g))||(console.log(fe.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await de(d=>{be(d,"channels.whatsapp.enabled",!0),be(d,"channels.whatsapp.sessionDir",n),be(d,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(fe.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(fe.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(fe.dim(` Session: ${n}`)),console.log(fe.dim(" Start the daemon to begin receiving:")),console.log(fe.dim(" agentx daemon start")),console.log(fe.dim(" Add routes later with:")),console.log(fe.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Ip}from"crypto";import ke from"chalk";import Lc from"prompts";var Kn="agentx-mesh:",Xn="//join/";function jp(e){return Buffer.from(e,"utf-8").toString("base64url")}function Cp(e){return Buffer.from(e,"base64url").toString("utf-8")}function Np(e){return`${Kn}${Xn}${jp(JSON.stringify(e))}`}function Rp(e){if(!e.startsWith(`${Kn}${Xn}`))throw new Error(`Not a mesh invite link \u2014 expected ${Kn}${Xn}\u2026`);let o=e.slice(Kn.length+Xn.length),t=JSON.parse(Cp(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 Dp(){return Ip(32).toString("hex")}function _p(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Pp(e){return e?.node?.name||e?.node?.id||"node"}async function Mc(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(ke.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=li("MESH_TOKEN");r||(r=Dp(),Kt("MESH_TOKEN",r),console.log(ke.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||_p(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:l}=await Lc({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});l||(console.log(ke.red(" Aborted")),process.exit(1)),a=l}let d=await de(l=>{be(l,"mesh.enabled",!0)},{configPath:e.configPath});d.success||(console.log(ke.red(` \u2717 ${d.error}`)),process.exit(1));let g=Np({url:a,token:r,name:Pp(i),version:1});console.log(),console.log(ke.bold(" Mesh invite")),console.log(),console.log(` ${ke.cyan(g)}`),console.log(),console.log(ke.dim(" Run on the other node:")),console.log(ke.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(ke.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Fc(e,o={}){let t;try{t=Rp(e)}catch(i){console.log(ke.red(` \u2717 ${i.message}`)),process.exit(1)}let n=li("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Lc({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(ke.red(" Aborted (keeping existing .env)")),process.exit(1))}Kt("MESH_TOKEN",t.token);let s=await de(i=>{be(i,"mesh.enabled",!0);let r=Ro(i,"mesh.peers")||[],a=r.findIndex(d=>d.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),be(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(ke.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(ke.green(" \u2713 Joined mesh")),console.log(ke.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(ke.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(ke.dim(" Daemon hot-reloaded.")):console.log(ke.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(ke.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(ke.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(ke.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var ht=new Lp().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");ht.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 Dc({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});ht.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 Pc({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Uc=ht.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Uc.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 Mc({url:e.url,configPath:e.config})});Uc.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 Fc(e,{configPath:o.config})});ht.action(()=>{console.log(),console.log(ft.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${ft.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${ft.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${ft.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${ft.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(ft.dim(" GitLab connect is the next slice.")),console.log()});pe();import{Command as Mp}from"commander";import le from"chalk";var Qt=new Mp().name("usage").description("token usage analysis and reporting");Qt.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=_(),[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(le.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(le.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${le.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: ${le.red(String(s.totalErrors))}`),console.log(),console.log(le.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 d=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${le.cyan(a)}: ${d} tokens (${c.tasks} tasks) ${le.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(le.red(" Daemon not running. Start with: agentx daemon start")):console.log(le.red(` ${e.message}`))}});Qt.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(le.red(` Script not found: ${s}`)),console.log(le.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(le.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(le.red(" Analysis failed. Is Python 3 installed?"))}});Qt.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-UREILT2E.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-LAACUZWW.js"),r=await i(),a=new Set(n.filter(l=>l.kind==="cli").map(l=>l.name)),c=[],d=(l,p)=>{for(let f of l.commands??[]){let u=p?`${p} ${f.name()}`:f.name();c.push(u),d(f,u)}};d(r,"");let g=c.filter(l=>!a.has(l)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(le.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let l of g)console.log(` ${le.dim("\xB7")} ${l}`);console.log(),console.log(le.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(le.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(le.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(le.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(le.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(le.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=le.dim(`${i.days}d`);console.log(` ${le.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(le.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Fp}from"commander";import he from"chalk";import{resolve as Up}from"path";pe();var Ao=new Fp().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Ao.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{Yi(Up(process.cwd(),".env"))}catch{}let o=qp(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-HLTVSSGW.js");t(o)}catch(o){console.log(he.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(he.dim(o.stack)),process.exit(1)}});function qp(e,o){try{let t=_();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(he.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(he.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
356
+ `)),{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}}}}Ao.command("list").description("list configured boards").action(()=>{try{let e=_();if(!e.boards?.length){console.log(he.dim(`
323
357
  No boards configured.
324
- `));return}console.log();for(let o of e.boards){console.log(` ${fe.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(fe.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(fe.dim(` primary label: ${o.primaryToolLabel}`)),console.log(fe.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(fe.red(` ${e.message}`)),process.exit(1)}});So.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{zt(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(fe.red(` ${t.message}`)),process.exit(1)}});So.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{zt(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(fe.red(` ${t.message}`)),process.exit(1)}});var oi=So.command("column").description("manage a board's columns (add / remove / edit / list)");oi.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(hl("fs").readFileSync("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(fe.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(` ${fe.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${fe.dim(i)}`)}}catch(o){console.log(fe.red(` ${o.message}`)),process.exit(1)}});oi.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{zt(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(fe.red(` ${n.message}`)),process.exit(1)}});oi.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{zt(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(fe.red(` ${t.message}`)),process.exit(1)}});So.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{zt(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(fe.red(` ${o.message}`)),process.exit(1)}});function zt(e){let{summary:o,backupPath:t}=Zo(n=>e(n));console.log(fe.green(`
358
+ `));return}console.log();for(let o of e.boards){console.log(` ${he.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(he.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(he.dim(` primary label: ${o.primaryToolLabel}`)),console.log(he.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(he.red(` ${e.message}`)),process.exit(1)}});Ao.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{Zt(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(he.red(` ${t.message}`)),process.exit(1)}});Ao.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{Zt(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(he.red(` ${t.message}`)),process.exit(1)}});var pi=Ao.command("column").description("manage a board's columns (add / remove / edit / list)");pi.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(_l("fs").readFileSync("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(he.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(` ${he.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${he.dim(i)}`)}}catch(o){console.log(he.red(` ${o.message}`)),process.exit(1)}});pi.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{Zt(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(he.red(` ${n.message}`)),process.exit(1)}});pi.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{Zt(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(he.red(` ${t.message}`)),process.exit(1)}});Ao.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Zt(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(he.red(` ${o.message}`)),process.exit(1)}});function Zt(e){let{summary:o,backupPath:t}=nt(n=>e(n));console.log(he.green(`
325
359
  \u2713 ${o}
326
- `)),t&&console.log(fe.dim(` Backup: ${t}`)),console.log(fe.dim(` Restart the dashboard to pick up the change if not auto-reloading.
327
- `))}import{Command as sp}from"commander";import m from"chalk";import{resolve as q,relative as vc,dirname as xc}from"path";import{execSync as qo}from"child_process";import{writeFileSync as Wo,mkdirSync as co,readFileSync as Yt,readdirSync as ip,renameSync as qn,rmSync as rp,existsSync as Be}from"fs";function ke(e,o){return new rs(Vt(e),void 0,o||"graph")}function Vt(e){return e||q(process.cwd(),".agentx/wiki")}function ni(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var ee=new sp().name("wiki").description("wiki knowledge base management");ee.command("status").description("show wiki status per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").action(e=>{let o=e.mode,t=ke(e.dir,o),n=t.summary(),i=t.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${ni(o)}]`)),console.log(),console.log(` Total raw entries: ${i}`),console.log(` Agents: ${n.length}`),console.log();for(let a of n){let c=a.unabsorbed>0?m.yellow(`${a.unabsorbed} unabsorbed`):m.green("up to date");if(console.log(` ${m.cyan(a.agentId)}`),console.log(` Entries: ${a.totalEntries} Articles: ${a.totalArticles} ${c}`),a.articles.length>0){for(let d of a.articles.slice(0,3))console.log(m.dim(` - ${d.title} [${(d.tags||[]).slice(0,3).join(", ")}]`));a.articles.length>3&&console.log(m.dim(` ... and ${a.articles.length-3} more`))}console.log()}let r=n.reduce((a,c)=>a+c.unabsorbed,0);r>0&&(console.log(m.dim(` ${r} raw entries on disk. Absorb is deprecated \u2014 see 'agentx wiki absorb --help'.`)),console.log())});ee.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(e=>{let o=ke(e.dir,e.mode),t=e.agent?[e.agent]:o.listAgents(),n=0;console.log();for(let s of t){let r=o.getAgentWiki(s).lint();if(n+=r.length,r.length===0)console.log(` ${m.cyan(s)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(s)}: ${m.yellow(`${r.length} issues`)}`);for(let a of r){let c=a.type==="broken-link"?"x":a.type==="orphan"?"?":"!";console.log(` [${c}] ${m.dim(a.type)} ${a.article}: ${a.message}`)}}}console.log(),n===0&&console.log(m.green(" All agent wikis are healthy")),console.log()});ee.command("absorb").description("compile unabsorbed entries into typed per-agent wiki articles (Farzapedia-faithful)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","absorb only this agent").option("--dry-run","preview without running").option("--no-facts","skip the system-of-record lookups").option("--max <n>","max entries per agent","10").option("--since <date>","only entries dated on or after YYYY-MM-DD").action(async e=>{let o=e.mode,t=ke(e.dir,o),n=e.agent?[e.agent]:t.listAgents(),s=parseInt(e.max),i=(()=>{try{let p=q(process.cwd(),".agentx/graph");return Be(p)?new mo({baseDir:p}):null}catch{return null}})(),r=new Map;if(i)try{let p=i.loadIndex();for(let[f,u]of Object.entries(p.entries))r.set(f,u.path)}catch{}let a,c=p=>{let f=p.meta?.intentPath;if(Array.isArray(f)&&f.every(y=>typeof y=="string")&&f.length>0)return f;if(!i||r.size===0)return;let u=String(p.meta?.sender??""),w=i.fingerprint({text:p.content,channel:p.source,sender:u});return r.get(w)},d=(p,f)=>{let u=new Map;for(let y of p){let $=f.find(x=>x.id===y);if(!$)continue;let b=c($);if(!b?.length)continue;let v=b.join("/"),A=u.get(v);A?A.n++:u.set(v,{path:b,n:1})}if(u.size===0)return;let w;for(let y of u.values())(!w||y.n>w.n)&&(w=y);return w?.path},g=0,l=0;for(let p of n){let f=typeof e.since=="string"?e.since.trim():"",u=t.getUnabsorbedEntries(p).filter(k=>!f||(k.date??"")>=f).slice(0,s);if(u.length===0){console.log(` ${m.cyan(p)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(p)}: ${u.length} entries to absorb`));for(let k of u.slice(0,3))console.log(m.dim(` [${k.date} via ${k.source}] ${k.content.slice(0,80)}...`));if(u.length>3&&console.log(m.dim(` ... and ${u.length-3} more`)),e.dryRun)continue;let w=t.getAgentWiki(p),y=w.rebuildIndex(),$=w.getWorldview()||t.getSharedStore().getWorldview()||"",b=u.map(k=>`--- ENTRY ${k.id} [${k.date} ${k.agentId} via ${k.source}] ---
328
- ${k.content}
360
+ `)),t&&console.log(he.dim(` Backup: ${t}`)),console.log(he.dim(` Restart the dashboard to pick up the change if not auto-reloading.
361
+ `))}import{Command as Wp}from"commander";import m from"chalk";import{resolve as q,relative as qc,dirname as Wc}from"path";import{execSync as Jo}from"child_process";import{writeFileSync as Go,mkdirSync as go,readFileSync as en,readdirSync as Bp,renameSync as Qn,rmSync as Jp,existsSync as Je}from"fs";function ve(e,o){return new ys(on(e),void 0,o||"graph")}function on(e){return e||q(process.cwd(),".agentx/wiki")}function fi(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var ee=new Wp().name("wiki").description("wiki knowledge base management");ee.command("status").description("show wiki status per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").action(e=>{let o=e.mode,t=ve(e.dir,o),n=t.summary(),i=t.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${fi(o)}]`)),console.log(),console.log(` Total raw entries: ${i}`),console.log(` Agents: ${n.length}`),console.log();for(let a of n){let c=a.unabsorbed>0?m.yellow(`${a.unabsorbed} unabsorbed`):m.green("up to date");if(console.log(` ${m.cyan(a.agentId)}`),console.log(` Entries: ${a.totalEntries} Articles: ${a.totalArticles} ${c}`),a.articles.length>0){for(let d of a.articles.slice(0,3))console.log(m.dim(` - ${d.title} [${(d.tags||[]).slice(0,3).join(", ")}]`));a.articles.length>3&&console.log(m.dim(` ... and ${a.articles.length-3} more`))}console.log()}let r=n.reduce((a,c)=>a+c.unabsorbed,0);r>0&&(console.log(m.dim(` ${r} raw entries on disk. Absorb is deprecated \u2014 see 'agentx wiki absorb --help'.`)),console.log())});ee.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(e=>{let o=ve(e.dir,e.mode),t=e.agent?[e.agent]:o.listAgents(),n=0;console.log();for(let s of t){let r=o.getAgentWiki(s).lint();if(n+=r.length,r.length===0)console.log(` ${m.cyan(s)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(s)}: ${m.yellow(`${r.length} issues`)}`);for(let a of r){let c=a.type==="broken-link"?"x":a.type==="orphan"?"?":"!";console.log(` [${c}] ${m.dim(a.type)} ${a.article}: ${a.message}`)}}}console.log(),n===0&&console.log(m.green(" All agent wikis are healthy")),console.log()});ee.command("absorb").description("compile unabsorbed entries into typed per-agent wiki articles (Farzapedia-faithful)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","absorb only this agent").option("--dry-run","preview without running").option("--no-facts","skip the system-of-record lookups").option("--max <n>","max entries per agent","10").option("--since <date>","only entries dated on or after YYYY-MM-DD").action(async e=>{let o=e.mode,t=ve(e.dir,o),n=e.agent?[e.agent]:t.listAgents(),s=parseInt(e.max),i=(()=>{try{let p=q(process.cwd(),".agentx/graph");return Je(p)?new uo({baseDir:p}):null}catch{return null}})(),r=new Map;if(i)try{let p=i.loadIndex();for(let[f,u]of Object.entries(p.entries))r.set(f,u.path)}catch{}let a,c=p=>{let f=p.meta?.intentPath;if(Array.isArray(f)&&f.every(y=>typeof y=="string")&&f.length>0)return f;if(!i||r.size===0)return;let u=String(p.meta?.sender??""),w=i.fingerprint({text:p.content,channel:p.source,sender:u});return r.get(w)},d=(p,f)=>{let u=new Map;for(let y of p){let k=f.find(S=>S.id===y);if(!k)continue;let b=c(k);if(!b?.length)continue;let x=b.join("/"),A=u.get(x);A?A.n++:u.set(x,{path:b,n:1})}if(u.size===0)return;let w;for(let y of u.values())(!w||y.n>w.n)&&(w=y);return w?.path},g=0,l=0;for(let p of n){let f=typeof e.since=="string"?e.since.trim():"",u=t.getUnabsorbedEntries(p).filter($=>!f||($.date??"")>=f).slice(0,s);if(u.length===0){console.log(` ${m.cyan(p)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(p)}: ${u.length} entries to absorb`));for(let $ of u.slice(0,3))console.log(m.dim(` [${$.date} via ${$.source}] ${$.content.slice(0,80)}...`));if(u.length>3&&console.log(m.dim(` ... and ${u.length-3} more`)),e.dryRun)continue;let w=t.getAgentWiki(p),y=w.rebuildIndex(),k=w.getWorldview()||t.getSharedStore().getWorldview()||"",b=u.map($=>`--- ENTRY ${$.id} [${$.date} ${$.agentId} via ${$.source}] ---
362
+ ${$.content}
329
363
  --- END ENTRY ---`).join(`
330
364
 
331
- `),v="";if(e.facts!==!1){let{extractHints:k,resolveFacts:N,mergeRecords:C,renderFactsBlock:I,installPrompts:P,defaultSources:W,recordsFromEntries:L}=await import("./facts-YVEJOM7O.js");if(!a){let B=new Set;for(let ve of t.listAgents())for(let he of t.getAgentWiki(ve).listArticles(ve))he.meta.type==="person"&&B.add(he.meta.title);a=[...B]}let H=k(u.map(B=>({context:B.sourceContext,content:B.content,sender:typeof B.meta?.sender=="string"?B.meta.sender:void 0})),{known:a}),ae=L(u);if(H.length>0||ae.length>0){let B=W(),{records:ve,results:he}=H.length>0?await N(H,{sources:B}):{records:[],results:[]},_=C([...ae,...ve]);v=I(_);let qe=[...ae.length>0?[`entries:${ae.length}`]:[],...he.filter(ye=>ye.records.length>0).map(ye=>`${ye.source}:${ye.records.length}`)];console.log(m.dim(` Facts: ${H.length} entities \u2192 ${_.length} resolved${qe.length?` (${qe.join(" ")})`:""}`));for(let ye of P(he,B))console.log(m.yellow(` ! ${ye.source} ${ye.kind} \u2014 would supply ${ye.provides.join(", ")}`)),console.log(m.dim(` ${ye.hint}`))}}let A=nr(o,p,$,y.articles,b,u.length,v);console.log(m.dim(` Mode: ${ni(o)}`));let x=q(w.baseDir,"_tmp");co(x,{recursive:!0});let E=q(x,"absorb-prompt.txt");Wo(E,A),console.log(m.dim(" Compiling with Claude..."));try{let k;try{k=qo(`cat '${E}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:zo({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(_){if(k=_.stdout||"",!k)throw _}let N=k;try{let _=JSON.parse(k);N=_.result||_.content||"",N||(console.log(m.dim(` Claude envelope keys: ${Object.keys(_).join(", ")}`)),console.log(m.dim(` is_error: ${_.is_error}, stop_reason: ${_.stop_reason}`)))}catch{}let C,I=[],P=N.indexOf("{"),W=N.indexOf("["),L=P>=0&&(W<0||P<W)?P:W;if(L===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(N.slice(0,500)));continue}let H=N[L],ae=H==="{"?"}":"]",B=0,ve=-1;for(let _=L;_<N.length;_++)if(N[_]===H)B++;else if(N[_]===ae&&(B--,B===0)){ve=_+1;break}if(ve===-1){console.log(m.red(" Unbalanced JSON"));continue}let he=N.slice(L,ve);try{let _=JSON.parse(he);Array.isArray(_)?C=_:(C=_.articles||[],I=_.gaps||[])}catch(_){console.log(m.red(` JSON parse error: ${_.message}`)),console.log(m.dim(` First 300 chars: ${he.slice(0,300)}`));continue}for(let _ of C){let qe=new Date().toISOString().slice(0,10),ye=d(_.sources||[],u);w.writeArticle(_.path,{title:_.title,type:_.type,related:Array.isArray(_.related)?_.related:void 0,tags:_.tags||[],owner:p,access:"public",created:qe,lastUpdated:qe,sources:_.sources||[],graphPath:ye},_.content,p);let Io=_.type?m.magenta(`[${_.type}]`)+" ":"",T=Array.isArray(_.related)&&_.related.length?` \u2192 ${_.related.slice(0,3).join(", ")}${_.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${Io}${_.path}: ${_.title}${m.dim(T)}`);let me=(_.tags||[]).slice(0,4).join(", ");me&&console.log(m.dim(` tags: ${me}`)),ye?.length&&(console.log(m.dim(` graphPath: ${ye.join(" \u203A ")}`)),l++),g++}if(I.length>0){console.log(),console.log(m.yellow(` Gaps detected (${I.length} missing pieces):`));for(let _ of I)console.log(m.yellow(` ? ${_}`));try{let{QuestionStore:_}=await import("./questions-4B4KSPXG.js"),qe=new _(Vt(e.dir)).add(I.map(ye=>({kind:"article",agentId:p,path:"",subject:String(ye).slice(0,120),question:`No article yet for: ${String(ye).slice(0,160)}`})));qe.added>0&&console.log(m.dim(` queued ${qe.added} for follow-up (agentx wiki questions)`))}catch{}}w.rebuildIndex()}catch(k){console.log(m.red(` Absorb failed: ${k.message?.slice(0,200)}`)),k.stderr&&console.log(m.dim(String(k.stderr).slice(0,300))),k.stdout&&console.log(m.dim("stdout: "+String(k.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let p=g>0?Math.round(l/g*100):0;console.log(m.dim(` ${l}/${g} carry graphPath (${p}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});ee.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--commit","write articles and ledger (default: dry-run)",!1).action(async e=>{let o=ap(e.since),t=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=t.find(a=>!n.includes(a));s&&(console.log(m.red(` Invalid memory type "${s}". Valid: ${n.join(", ")}`)),process.exit(1)),e.commit&&!e.via&&!e.model&&(console.log(m.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1)),console.log(),console.log(m.bold(" Memory \u2192 Wiki Promotion")),console.log();let i=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-LEOPEOEG.js"),{default:c}=await import("better-sqlite3"),d=q(process.cwd(),".agentx/db.sqlite");if(!Be(d))console.log(m.yellow(` --reviews: no ${d}`));else{let g=new c(d,{readonly:!0});try{let l=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(o??6048e5));i=a(l,{kinds:String(e.reviewKinds).split(",").map(u=>u.trim()).filter(Boolean)});let p=i.filter(u=>(u.occurrences??1)>1).length;console.log(m.dim(` ${l.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${p} seen in more than one session`));let f=i[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.memory.description.slice(0,84)}`))}finally{g.close()}}}let r=await sr({extraCandidates:i,wikiDir:e.dir?q(e.dir):void 0,memoryRoot:e.memoryDir?q(e.memoryDir):void 0,sinceMs:o,agentFilter:e.agent,types:t,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,log:a=>console.log(m.dim(` ${a}`))});if(r.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.clusters){let c=a.candidates[0],d=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${d} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${c.memory.description}`))}if(console.log(),r.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to promote")),console.log();return}for(let a of r.written){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",d=a.related?.length?` \u2192 ${a.related.slice(0,3).join(", ")}${a.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${c}${a.path}: ${a.title}${m.dim(d)}`),console.log(m.dim(` from: ${a.stamps.join(", ")}`))}for(let a of r.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(m.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(m.dim(` ! ${a}`));for(let a of r.errors)console.log(m.red(` x ${a}`));console.log(),console.log(r.errors.length?m.red(` ${r.written.length} promoted, ${r.errors.length} error(s)`):m.green(` ${r.written.length} promoted, ${r.skipped.length} skipped`)),console.log(),r.errors.length&&process.exit(1)});function ap(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());o||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}ee.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",q(process.cwd(),".agentx/task-history")).option("--n <n>","number of messages to sample (newest first)","10").option("--out <path>","markdown output file (default: stdout)").option("--selector-model <m>","agentic selector model","haiku").option("--synth-model <m>","agentic synthesis model","sonnet").action(async e=>{let{agenticQuery:o}=await import("./query-ZSUBNWOL.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=ke(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let d=a.getAgentWiki(c),g=parseInt(e.n),l=i(e.history,c);if(!s(l)){console.log(m.yellow(` no task-history at ${l}`));return}let p=[],f=t(l).sort().reverse();for(let y of f){let $=r(l,y),b=[];try{b=t($).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of b){if(p.length>=g)break;try{let A=JSON.parse(n(r($,v),"utf-8")),x=A.message||A.task?.message;typeof x=="string"&&x.trim().length>10&&p.push({id:A.id||v.replace(".json",""),message:x.trim(),ts:A.at||A.timestamp||y})}catch{}}if(p.length>=g)break}if(p.length===0){console.log(m.yellow(` no task messages found under ${l}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${p.length} messages from ${c}`)),console.log(m.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(m.dim(` NEW: agenticQuery() catalog+wikilink walk (selector=${e.selectorModel}, synth=${e.synthModel})`)),console.log();let u=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${p.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let y=0;y<p.length;y++){let $=p[y];process.stdout.write(m.dim(` [${y+1}/${p.length}] querying... `));let v=d.findRelevant($.message,c,3).map(x=>`- **${x.meta.title}** [${x.meta.type||"?"}] (${x.path})`).join(`
332
- `)||"_(none returned)_",A;try{let x=await o($.message,d,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(x.status!=="ok")A=`_(status: ${x.status}${x.error?" \u2014 "+x.error:""})_`;else{let E=x.citations.map(k=>`\`${k.title}\` [${k.type||"?"}]`).join(", ");A=`**Answer:**
365
+ `),x="";if(e.facts!==!1){let{extractHints:$,resolveFacts:C,mergeRecords:j,renderFactsBlock:T,installPrompts:D,defaultSources:W,recordsFromEntries:L}=await import("./facts-YVEJOM7O.js");if(!a){let B=new Set;for(let xe of t.listAgents())for(let ye of t.getAgentWiki(xe).listArticles(xe))ye.meta.type==="person"&&B.add(ye.meta.title);a=[...B]}let G=$(u.map(B=>({context:B.sourceContext,content:B.content,sender:typeof B.meta?.sender=="string"?B.meta.sender:void 0})),{known:a}),ae=L(u);if(G.length>0||ae.length>0){let B=W(),{records:xe,results:ye}=G.length>0?await C(G,{sources:B}):{records:[],results:[]},P=j([...ae,...xe]);x=T(P);let qe=[...ae.length>0?[`entries:${ae.length}`]:[],...ye.filter(we=>we.records.length>0).map(we=>`${we.source}:${we.records.length}`)];console.log(m.dim(` Facts: ${G.length} entities \u2192 ${P.length} resolved${qe.length?` (${qe.join(" ")})`:""}`));for(let we of D(ye,B))console.log(m.yellow(` ! ${we.source} ${we.kind} \u2014 would supply ${we.provides.join(", ")}`)),console.log(m.dim(` ${we.hint}`))}}let A=fr(o,p,k,y.articles,b,u.length,x);console.log(m.dim(` Mode: ${fi(o)}`));let S=q(w.baseDir,"_tmp");go(S,{recursive:!0});let v=q(S,"absorb-prompt.txt");Go(v,A),console.log(m.dim(" Compiling with Claude..."));try{let $;try{$=Jo(`cat '${v}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Ko({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(P){if($=P.stdout||"",!$)throw P}let C=$;try{let P=JSON.parse($);C=P.result||P.content||"",C||(console.log(m.dim(` Claude envelope keys: ${Object.keys(P).join(", ")}`)),console.log(m.dim(` is_error: ${P.is_error}, stop_reason: ${P.stop_reason}`)))}catch{}let j,T=[],D=C.indexOf("{"),W=C.indexOf("["),L=D>=0&&(W<0||D<W)?D:W;if(L===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(C.slice(0,500)));continue}let G=C[L],ae=G==="{"?"}":"]",B=0,xe=-1;for(let P=L;P<C.length;P++)if(C[P]===G)B++;else if(C[P]===ae&&(B--,B===0)){xe=P+1;break}if(xe===-1){console.log(m.red(" Unbalanced JSON"));continue}let ye=C.slice(L,xe);try{let P=JSON.parse(ye);Array.isArray(P)?j=P:(j=P.articles||[],T=P.gaps||[])}catch(P){console.log(m.red(` JSON parse error: ${P.message}`)),console.log(m.dim(` First 300 chars: ${ye.slice(0,300)}`));continue}for(let P of j){let qe=new Date().toISOString().slice(0,10),we=d(P.sources||[],u);w.writeArticle(P.path,{title:P.title,type:P.type,related:Array.isArray(P.related)?P.related:void 0,tags:P.tags||[],owner:p,access:"public",created:qe,lastUpdated:qe,sources:P.sources||[],graphPath:we},P.content,p);let Co=P.type?m.magenta(`[${P.type}]`)+" ":"",N=Array.isArray(P.related)&&P.related.length?` \u2192 ${P.related.slice(0,3).join(", ")}${P.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${Co}${P.path}: ${P.title}${m.dim(N)}`);let me=(P.tags||[]).slice(0,4).join(", ");me&&console.log(m.dim(` tags: ${me}`)),we?.length&&(console.log(m.dim(` graphPath: ${we.join(" \u203A ")}`)),l++),g++}if(T.length>0){console.log(),console.log(m.yellow(` Gaps detected (${T.length} missing pieces):`));for(let P of T)console.log(m.yellow(` ? ${P}`));try{let{QuestionStore:P}=await import("./questions-4B4KSPXG.js"),qe=new P(on(e.dir)).add(T.map(we=>({kind:"article",agentId:p,path:"",subject:String(we).slice(0,120),question:`No article yet for: ${String(we).slice(0,160)}`})));qe.added>0&&console.log(m.dim(` queued ${qe.added} for follow-up (agentx wiki questions)`))}catch{}}w.rebuildIndex()}catch($){console.log(m.red(` Absorb failed: ${$.message?.slice(0,200)}`)),$.stderr&&console.log(m.dim(String($.stderr).slice(0,300))),$.stdout&&console.log(m.dim("stdout: "+String($.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let p=g>0?Math.round(l/g*100):0;console.log(m.dim(` ${l}/${g} carry graphPath (${p}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});ee.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--commit","write articles and ledger (default: dry-run)",!1).action(async e=>{let o=Gp(e.since),t=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=t.find(a=>!n.includes(a));s&&(console.log(m.red(` Invalid memory type "${s}". Valid: ${n.join(", ")}`)),process.exit(1)),e.commit&&!e.via&&!e.model&&(console.log(m.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1)),console.log(),console.log(m.bold(" Memory \u2192 Wiki Promotion")),console.log();let i=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-LEOPEOEG.js"),{default:c}=await import("better-sqlite3"),d=q(process.cwd(),".agentx/db.sqlite");if(!Je(d))console.log(m.yellow(` --reviews: no ${d}`));else{let g=new c(d,{readonly:!0});try{let l=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(o??6048e5));i=a(l,{kinds:String(e.reviewKinds).split(",").map(u=>u.trim()).filter(Boolean)});let p=i.filter(u=>(u.occurrences??1)>1).length;console.log(m.dim(` ${l.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${p} seen in more than one session`));let f=i[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.memory.description.slice(0,84)}`))}finally{g.close()}}}let r=await hr({extraCandidates:i,wikiDir:e.dir?q(e.dir):void 0,memoryRoot:e.memoryDir?q(e.memoryDir):void 0,sinceMs:o,agentFilter:e.agent,types:t,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,log:a=>console.log(m.dim(` ${a}`))});if(r.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.clusters){let c=a.candidates[0],d=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${d} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${c.memory.description}`))}if(console.log(),r.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to promote")),console.log();return}for(let a of r.written){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",d=a.related?.length?` \u2192 ${a.related.slice(0,3).join(", ")}${a.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${c}${a.path}: ${a.title}${m.dim(d)}`),console.log(m.dim(` from: ${a.stamps.join(", ")}`))}for(let a of r.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(m.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(m.dim(` ! ${a}`));for(let a of r.errors)console.log(m.red(` x ${a}`));console.log(),console.log(r.errors.length?m.red(` ${r.written.length} promoted, ${r.errors.length} error(s)`):m.green(` ${r.written.length} promoted, ${r.skipped.length} skipped`)),console.log(),r.errors.length&&process.exit(1)});function Gp(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());o||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}ee.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",q(process.cwd(),".agentx/task-history")).option("--n <n>","number of messages to sample (newest first)","10").option("--out <path>","markdown output file (default: stdout)").option("--selector-model <m>","agentic selector model","haiku").option("--synth-model <m>","agentic synthesis model","sonnet").action(async e=>{let{agenticQuery:o}=await import("./query-ZSUBNWOL.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=ve(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let d=a.getAgentWiki(c),g=parseInt(e.n),l=i(e.history,c);if(!s(l)){console.log(m.yellow(` no task-history at ${l}`));return}let p=[],f=t(l).sort().reverse();for(let y of f){let k=r(l,y),b=[];try{b=t(k).filter(x=>x.endsWith(".json")).sort().reverse()}catch{continue}for(let x of b){if(p.length>=g)break;try{let A=JSON.parse(n(r(k,x),"utf-8")),S=A.message||A.task?.message;typeof S=="string"&&S.trim().length>10&&p.push({id:A.id||x.replace(".json",""),message:S.trim(),ts:A.at||A.timestamp||y})}catch{}}if(p.length>=g)break}if(p.length===0){console.log(m.yellow(` no task messages found under ${l}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${p.length} messages from ${c}`)),console.log(m.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(m.dim(` NEW: agenticQuery() catalog+wikilink walk (selector=${e.selectorModel}, synth=${e.synthModel})`)),console.log();let u=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${p.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let y=0;y<p.length;y++){let k=p[y];process.stdout.write(m.dim(` [${y+1}/${p.length}] querying... `));let x=d.findRelevant(k.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
366
+ `)||"_(none returned)_",A;try{let S=await o(k.message,d,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(S.status!=="ok")A=`_(status: ${S.status}${S.error?" \u2014 "+S.error:""})_`;else{let v=S.citations.map($=>`\`${$.title}\` [${$.type||"?"}]`).join(", ");A=`**Answer:**
333
367
 
334
- ${x.answer}
368
+ ${S.answer}
335
369
 
336
- **Citations:** ${E}`}}catch(x){A=`_(error: ${x.message})_`}console.log(m.dim("done")),u.push(`## ${y+1}. ${$.id}`,"",`> ${$.message.replace(/\n/g," ").slice(0,400)}${$.message.length>400?"\u2026":""}`,"","### OLD \u2014 BM25 preload (top 3)","",v,"","### NEW \u2014 agentic query","",A,"","| Path | Rating 0\u20132 | Notes |","|---|---|---|","| OLD | | |","| NEW | | |","")}let w=u.join(`
337
- `);e.out?((await import("fs")).writeFileSync(e.out,w),console.log(),console.log(m.green(` Wrote ${w.length} bytes to ${e.out}`))):(console.log(),console.log(w))});ee.command("interview").description("interactive interview session \u2014 Q&A with an LLM synthesizer, produces one typed wiki article").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to write to (required)").option("--topic <text>","what to interview about (e.g. 'Globex deployment procedure')").option("--type <t>","article type hint (person|project|place|concept|event|decision|pattern)").option("--model <m>","synthesis model","sonnet").option("--no-commit","show the draft but don't write").option("--answers <path>","non-interactive: one answer per line (same order as questions); last line = save|edit|scrap").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{WIKI_ARTICLE_TYPES:n}=await import("./types-OIFU3KSQ.js"),s=e.answers?Yt(e.answers,"utf-8").split(/\r?\n/).filter(T=>T.length>0):null,i=0;if(!e.agent){console.log(m.red(" --agent <id> is required. The article will be owned by this agent."));return}let r=ke(e.dir),a;try{a=r.getAgentWiki(e.agent)}catch(T){console.log(m.red(` can't open wiki for agent "${e.agent}": ${T.message}`));return}let c=s?null:o.createInterface({input:process.stdin,output:process.stdout}),d=async T=>{if(s){let me=s[i++]??"";return process.stdout.write(T+m.dim(`[scripted] ${me.slice(0,80)}${me.length>80?"\u2026":""}`)+`
338
- `),me.trim()}return(await c.question(T)).trim()};console.log(),console.log(m.bold(" Wiki Interview")),console.log(m.dim(" One article per session. Empty answer = skip field. /done = stop & synthesize. /abort = quit.")),console.log();let g=e.topic||"";if(!g&&(g=await d(m.cyan(" Topic? ")+m.dim("(a person, a procedure, a past event, \u2026) ")),!g||g==="/abort")){c?.close();return}let l=(e.type||"").toLowerCase(),p=new Set(n);if(!p.has(l)){console.log(m.dim(` Types: ${n.join(" | ")}`));let T=await d(m.cyan(" Type? "));if(T==="/abort"){c?.close();return}p.has(T)?l=T:(console.log(m.yellow(` "${T}" isn't a valid type. Falling back to "concept".`)),l="concept")}let f={person:["Full name (and any aliases / Telegram handle / GitLab username)?","Role or title?","Which org or team are they part of (use the article title if you have one)?","Key responsibilities in OUR work?","Preferred channel to reach them (Telegram, email, in-person, \u2026)?","Who do they report to? (skip if none)","Notable decisions, events, or patterns they're involved in?","Anything quirky we should remember (timezone, working hours, style)?"],project:["One-line description \u2014 what is this project?","Who owns it? (person article title)","Tech stack or key tools involved?","Current status (active / paused / archived)?","Repo / URL / path on disk?","Two or three key decisions made so far?","Any open blockers, risks, or known issues?","Related projects or patterns?"],place:["Kind \u2014 office / server / environment / domain / URL?","Address \u2014 URL, IP, hostname, or physical location?","Owner (person or team)?","How to access it (SSH host, login, VPN, \u2026)?","What lives there (services, people, data)?","Known quirks (timezone, uptime, access restrictions)?"],concept:["Define it in one sentence \u2014 what does this term mean in OUR work?","Where did we first adopt it (origin story, date)?","Two or three concrete examples from our team?","What does it replace or extend (older concept, related concept)?","Common misunderstandings to avoid?"],event:["Date (YYYY-MM-DD)?","One-line summary \u2014 what happened?","Who was involved?","Timeline \u2014 key moments (start \u2192 resolution)?","Impact \u2014 what broke, what got delivered, who was affected?","Resolution / outcome?","Follow-ups or lessons captured?"],decision:["Context \u2014 what was the situation forcing a choice?","Options that were considered?","Chosen option \u2014 and one-sentence why?","Alternatives rejected \u2014 and one-sentence why not?","Who decided, and when (date)?","Is this reversible, and what would trigger a revisit?"],pattern:["Trigger \u2014 when should someone follow this pattern?","Inputs required (what do you need before starting)?","Steps in order \u2014 keep it tight, one line per step?","Expected output \u2014 how do you know it worked?","Common failure modes?","Related patterns, decisions, or runbooks?"]},u=f[l]||f.concept;console.log(),console.log(m.bold(` Topic: ${m.cyan(g)} \xB7 Type: ${m.magenta(l)}`)),console.log(m.dim(` ${u.length} questions. Skip with empty answer. /done to stop early.`)),console.log();let w=[],y=!1;for(let T=0;T<u.length;T++){let me=u[T],Je=await d(` ${m.dim(`[${T+1}/${u.length}]`)} ${me}
339
- ${m.green(">")} `);if(Je==="/abort"){y=!0;break}if(Je==="/done")break;Je!=="/skip"&&Je&&w.push({q:me,a:Je})}if(!y){let T=await d(`
370
+ **Citations:** ${v}`}}catch(S){A=`_(error: ${S.message})_`}console.log(m.dim("done")),u.push(`## ${y+1}. ${k.id}`,"",`> ${k.message.replace(/\n/g," ").slice(0,400)}${k.message.length>400?"\u2026":""}`,"","### OLD \u2014 BM25 preload (top 3)","",x,"","### NEW \u2014 agentic query","",A,"","| Path | Rating 0\u20132 | Notes |","|---|---|---|","| OLD | | |","| NEW | | |","")}let w=u.join(`
371
+ `);e.out?((await import("fs")).writeFileSync(e.out,w),console.log(),console.log(m.green(` Wrote ${w.length} bytes to ${e.out}`))):(console.log(),console.log(w))});ee.command("interview").description("interactive interview session \u2014 Q&A with an LLM synthesizer, produces one typed wiki article").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to write to (required)").option("--topic <text>","what to interview about (e.g. 'Globex deployment procedure')").option("--type <t>","article type hint (person|project|place|concept|event|decision|pattern)").option("--model <m>","synthesis model","sonnet").option("--no-commit","show the draft but don't write").option("--answers <path>","non-interactive: one answer per line (same order as questions); last line = save|edit|scrap").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{WIKI_ARTICLE_TYPES:n}=await import("./types-OIFU3KSQ.js"),s=e.answers?en(e.answers,"utf-8").split(/\r?\n/).filter(N=>N.length>0):null,i=0;if(!e.agent){console.log(m.red(" --agent <id> is required. The article will be owned by this agent."));return}let r=ve(e.dir),a;try{a=r.getAgentWiki(e.agent)}catch(N){console.log(m.red(` can't open wiki for agent "${e.agent}": ${N.message}`));return}let c=s?null:o.createInterface({input:process.stdin,output:process.stdout}),d=async N=>{if(s){let me=s[i++]??"";return process.stdout.write(N+m.dim(`[scripted] ${me.slice(0,80)}${me.length>80?"\u2026":""}`)+`
372
+ `),me.trim()}return(await c.question(N)).trim()};console.log(),console.log(m.bold(" Wiki Interview")),console.log(m.dim(" One article per session. Empty answer = skip field. /done = stop & synthesize. /abort = quit.")),console.log();let g=e.topic||"";if(!g&&(g=await d(m.cyan(" Topic? ")+m.dim("(a person, a procedure, a past event, \u2026) ")),!g||g==="/abort")){c?.close();return}let l=(e.type||"").toLowerCase(),p=new Set(n);if(!p.has(l)){console.log(m.dim(` Types: ${n.join(" | ")}`));let N=await d(m.cyan(" Type? "));if(N==="/abort"){c?.close();return}p.has(N)?l=N:(console.log(m.yellow(` "${N}" isn't a valid type. Falling back to "concept".`)),l="concept")}let f={person:["Full name (and any aliases / Telegram handle / GitLab username)?","Role or title?","Which org or team are they part of (use the article title if you have one)?","Key responsibilities in OUR work?","Preferred channel to reach them (Telegram, email, in-person, \u2026)?","Who do they report to? (skip if none)","Notable decisions, events, or patterns they're involved in?","Anything quirky we should remember (timezone, working hours, style)?"],project:["One-line description \u2014 what is this project?","Who owns it? (person article title)","Tech stack or key tools involved?","Current status (active / paused / archived)?","Repo / URL / path on disk?","Two or three key decisions made so far?","Any open blockers, risks, or known issues?","Related projects or patterns?"],place:["Kind \u2014 office / server / environment / domain / URL?","Address \u2014 URL, IP, hostname, or physical location?","Owner (person or team)?","How to access it (SSH host, login, VPN, \u2026)?","What lives there (services, people, data)?","Known quirks (timezone, uptime, access restrictions)?"],concept:["Define it in one sentence \u2014 what does this term mean in OUR work?","Where did we first adopt it (origin story, date)?","Two or three concrete examples from our team?","What does it replace or extend (older concept, related concept)?","Common misunderstandings to avoid?"],event:["Date (YYYY-MM-DD)?","One-line summary \u2014 what happened?","Who was involved?","Timeline \u2014 key moments (start \u2192 resolution)?","Impact \u2014 what broke, what got delivered, who was affected?","Resolution / outcome?","Follow-ups or lessons captured?"],decision:["Context \u2014 what was the situation forcing a choice?","Options that were considered?","Chosen option \u2014 and one-sentence why?","Alternatives rejected \u2014 and one-sentence why not?","Who decided, and when (date)?","Is this reversible, and what would trigger a revisit?"],pattern:["Trigger \u2014 when should someone follow this pattern?","Inputs required (what do you need before starting)?","Steps in order \u2014 keep it tight, one line per step?","Expected output \u2014 how do you know it worked?","Common failure modes?","Related patterns, decisions, or runbooks?"]},u=f[l]||f.concept;console.log(),console.log(m.bold(` Topic: ${m.cyan(g)} \xB7 Type: ${m.magenta(l)}`)),console.log(m.dim(` ${u.length} questions. Skip with empty answer. /done to stop early.`)),console.log();let w=[],y=!1;for(let N=0;N<u.length;N++){let me=u[N],Ge=await d(` ${m.dim(`[${N+1}/${u.length}]`)} ${me}
373
+ ${m.green(">")} `);if(Ge==="/abort"){y=!0;break}if(Ge==="/done")break;Ge!=="/skip"&&Ge&&w.push({q:me,a:Ge})}if(!y){let N=await d(`
340
374
  ${m.dim("Anything else worth capturing?")}
341
- ${m.green(">")} `);T&&T!=="/abort"&&T!=="/done"&&w.push({q:"Anything else worth capturing?",a:T})}if(y||w.length===0){console.log(m.yellow(`
342
- Nothing captured. Exiting.`)),c?.close();return}let b=a.listArticles(e.agent).slice(0,40).map(T=>`- ${T.meta.title} [${T.meta.type||"?"}]`).join(`
343
- `),v=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${g}`,`**Type:** ${l}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...w.map(T=>`
344
- Q: ${T.q}
345
- A: ${T.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",b||"(none yet)","","## Output rules","- Output EXACTLY one markdown file: frontmatter (---) + body. No code fences, no preamble.","- Frontmatter fields in this exact order: title, type, related, tags, owner, access, created, last_updated, sources.",' - `title`: "\u2026"',` - \`type\`: ${l}`,' - `related`: ["Article Title", \u2026] (titles that exist in the catalog above; drop if none)'," - `tags`: 2-4 specific tags, lowercase-kebab \u2014 no dates unless type=event",` - \`owner\`: ${e.agent}`," - `access`: public (unless the content is sensitive)",` - \`created\`: ${new Date().toISOString().slice(0,10)}`,` - \`last_updated\`: ${new Date().toISOString().slice(0,10)}`,` - \`sources\`: ["interview-${new Date().toISOString().slice(0,10)}"]`,"- Body: 20-80 lines, Wikipedia-style, organized by theme (not by question), synthesized (not verbatim Q&A).","- Use [[Title]] inline every time you reference something that has an article in the catalog.","- Do NOT invent facts. If the transcript didn't cover something, skip that sub-topic."].join(`
346
- `),A=q(a.baseDir,"_tmp");co(A,{recursive:!0});let x=q(A,`interview-${t().slice(0,8)}.txt`);Wo(x,v),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let E="";try{let T=`cat '${x}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,me=qo(T,{env:zo({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Je=JSON.parse(me);E=String(Je.result||Je.content||"")}catch{E=me}}catch(T){console.log(m.red(` synthesis failed: ${T.message?.slice(0,200)}`)),c?.close();return}E=E.trim();let k=E.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);k&&(E=k[1].trim());let N=E.indexOf("---");N>0&&(E=E.slice(N));let C=E.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!C){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(E.slice(0,600)),c?.close();return}let I={};for(let T of C[1].split(`
347
- `)){let me=T.match(/^(\w+):\s*(.+)$/);me&&(I[me[1]]=me[2].trim().replace(/^"(.*)"$/,"$1"))}let P=C[2],W=I.title||g,L=W.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),ae=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[l]||l+"s"}/${L}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${ae}`)),console.log(),console.log(E),console.log();let B=await d(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),B==="scrap"||B==="/abort"){console.log(m.dim(" Discarded."));return}if(!e.commit){console.log(m.dim(" --no-commit: not writing.")),console.log(m.dim(` Draft kept at ${x} (prompt only; no article file)`));return}let ve=P,he={title:W,type:I.type||l,related:I.related?I.related.replace(/^\[|\]$/g,"").split(",").map(T=>T.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:I.tags?I.tags.replace(/^\[|\]$/g,"").split(",").map(T=>T.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:I.access||"public",created:I.created||new Date().toISOString().slice(0,10),lastUpdated:I.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(B==="edit"){let T=process.env.EDITOR||"vi",me=q(A,`draft-${t().slice(0,8)}.md`);Wo(me,E);try{qo(`${T} '${me}'`,{stdio:"inherit"});let ns=Yt(me,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(ns){let go={};for(let xt of ns[1].split(`
348
- `)){let ss=xt.match(/^(\w+):\s*(.+)$/);ss&&(go[ss[1]]=ss[2].trim().replace(/^"(.*)"$/,"$1"))}ve=ns[2],he={...he,title:go.title||he.title,type:go.type||he.type,access:go.access||he.access,related:go.related?go.related.replace(/^\[|\]$/g,"").split(",").map(xt=>xt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):he.related,tags:go.tags?go.tags.replace(/^\[|\]$/g,"").split(",").map(xt=>xt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):he.tags}}}catch(Je){console.log(m.red(` editor failed: ${Je.message}`));return}}if(!a.writeArticle(ae,he,ve,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${ae} saved.`));let qe=a.extractWikilinks(ve),ye=new Map;for(let T of a.listArticles(e.agent))ye.set(T.meta.title.toLowerCase(),!0);let Io=qe.filter(T=>!ye.has(T.toLowerCase()));if(Io.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let T of Io.slice(0,8))console.log(m.dim(` - ${T}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});ee.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{agenticQuery:n}=await import("./query-ZSUBNWOL.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=ke(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(f){console.log(m.red(` can't open wiki for agent "${e.agent}": ${f.message}`));return}let r=null;if(e.script){let u=Yt(e.script,"utf-8").split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);r=[];for(let w of u){let y=w.split(/\r?\n/).filter(v=>v.trim());if(y.length<2)continue;let $=y[0].replace(/^Q:\s*/i,"").trim(),b=y.slice(1).join(" ").trim();$&&b&&r.push({q:$,verdict:b})}}let a=r?null:o.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",d=Math.min(parseInt(e.rounds)||20,r?.length??999),g=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${d} \xB7 ${g?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let l=[],p=0;for(let f=0;f<d;f++){let u,w;if(r){let H=r[f];if(!H)break;u=H.q,w=H.verdict,console.log(m.cyan(` [${f+1}] Q: `)+u)}else{if(u=await c(m.cyan(` [${f+1}] Q: `)),!u||u==="/done"||u==="/abort")break;w=""}process.stdout.write(m.dim(" querying... "));let y;try{y=await n(u,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(H){console.log(m.red(`failed: ${H.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),y.status!=="ok")console.log(m.yellow(` (status: ${y.status}${y.error?" \u2014 "+y.error:""})`));else{let H=y.citations.map(ae=>`${ae.title} [${ae.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
349
- `)),console.log(m.dim(" citations: "+H))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let $={q:u,answer:y.answer,citations:y.citations,verdict:w},b=w.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!b){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),l.push($);continue}let v=b[1].toLowerCase(),A=(b[2]||"").trim();if(l.push($),v==="/ok"||v==="/skip")continue;if(!A){console.log(m.yellow(` ${v} without note \u2014 skipping.`));continue}let x=y.citations[0];if(!x){console.log(m.yellow(" no cited article to patch."));continue}let E=i.readArticle(x.path);if(!E){console.log(m.red(` can't read ${x.path} to patch.`));continue}console.log(m.dim(` patching ${x.title} (${x.path})...`));let k=lp(E.content,v,A,E.meta.title,E.meta.type),N=q(i.baseDir,"_tmp");co(N,{recursive:!0});let C=q(N,`quiz-patch-${t().slice(0,8)}.txt`);Wo(C,k);let I="";try{let H=`cat '${C}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,ae=qo(H,{env:zo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let ve=JSON.parse(ae);I=String(ve.result||ve.content||"")}catch{I=ae}let B=I.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);B&&(I=B[1].trim()),I=I.trim()}catch(H){console.log(m.red(` patch failed: ${H.message?.slice(0,120)}`));continue}if(!I||I.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let P=E.content.split(`
350
- `).length,W=I.split(`
351
- `).length;if(console.log(m.dim(` diff: ${P} \u2192 ${W} lines (${W-P>=0?"+":""}${W-P})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),$.patched=x.path+" (dry)";continue}if(!i.writeArticle(x.path,{...E.meta,lastUpdated:new Date().toISOString().slice(0,10)},I,e.agent)){console.log(m.red(" write failed (permission?)"));continue}p++,$.patched=x.path,console.log(m.green(` \u2713 patched ${x.path}`))}if(a&&a.close(),p>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${l.length} rounds, ${p} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${l.length} rounds \xB7 ${p} patches_`,""];for(let u=0;u<l.length;u++){let w=l[u];f.push(`## ${u+1}. Q: ${w.q}`,"",`**A:** ${w.answer}`,"",`**Citations:** ${w.citations.map(y=>`\`${y.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${w.verdict}\``+(w.patched?` \u2192 patched \`${w.patched}\``:""),"")}Wo(e.out,f.join(`
352
- `)),console.log(m.dim(` Transcript written to ${e.out}`))}});ee.command("edit <agent> <titleOrPath>").description("open an article in $EDITOR (resolves by title or path), rebuild catalog on exit").option("--dir <path>","wiki directory").option("--editor <cmd>","override $EDITOR for this run").action((e,o,t)=>{let n=ke(t.dir),s;try{s=n.getAgentWiki(e)}catch(d){console.log(m.red(` can't open wiki for agent "${e}": ${d.message}`));return}let i=Ac(s,o,e);if(!i){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`)),console.log(m.dim(` Tip: ${m.green("agentx wiki status")} lists agents; ${m.green(`agentx wiki search "term" --agent ${e}`)} finds by content.`));return}let r=q(s.baseDir,i),a=t.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${i} in ${a}...`));try{qo(`${a} '${r}'`,{stdio:"inherit"})}catch(d){console.log(m.red(` editor exited with error: ${d.message?.slice(0,150)}`));return}let c=s.readArticle(i);if(c){let d=new Set,g=s.extractWikilinks(c.content).filter(f=>d.has(f)?!1:(d.add(f),!0)),l=c.meta.related||[];(g.some(f=>!l.includes(f))||l.some(f=>!g.includes(f)))&&(s.writeArticle(i,{...c.meta,related:g.length?g:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.content,e),console.log(m.dim(` (synced frontmatter.related from body: ${g.length} wikilink${g.length===1?"":"s"})`)))}try{s.rebuildIndex(),console.log(m.green(` \u2713 ${i} saved. Catalog rebuilt.`))}catch(d){console.log(m.yellow(` saved, but catalog rebuild failed: ${d.message?.slice(0,100)}`))}});ee.command("patch <agent> <titleOrPath> <instruction>").description("LLM-patch an article from a free-form instruction; shows diff + confirms before writing").option("--dir <path>","wiki directory").option("--patch-model <m>","patch model","sonnet").option("--yes","skip confirmation and write immediately").option("--no-commit","show the patched body but don't write").action(async(e,o,t,n)=>{let s=await import("node:readline/promises"),{randomUUID:i}=await import("node:crypto"),r=ke(n.dir),a;try{a=r.getAgentWiki(e)}catch(x){console.log(m.red(` can't open wiki for agent "${e}": ${x.message}`));return}let c=Ac(a,o,e);if(!c){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`));return}let d=a.readArticle(c);if(!d){console.log(m.red(` can't read ${c}.`));return}let g=cp(d.content,d.meta.title,d.meta.type,t),l=q(a.baseDir,"_tmp");co(l,{recursive:!0});let p=q(l,`patch-${i().slice(0,8)}.txt`);Wo(p,g),console.log(),console.log(m.dim(` Target: ${d.meta.title} (${c})`)),console.log(m.dim(` Patching with ${n.patchModel}...`));let f="";try{let x=`cat '${p}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,E=qo(x,{env:zo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let N=JSON.parse(E);f=String(N.result||N.content||"")}catch{f=E}let k=f.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);k&&(f=k[1].trim()),f=f.trim()}catch(x){console.log(m.red(` patch failed: ${x.message?.slice(0,150)}`));return}if(!f||f.length<20){console.log(m.yellow(" patch returned nothing usable."));return}let u=d.content.split(`
375
+ ${m.green(">")} `);N&&N!=="/abort"&&N!=="/done"&&w.push({q:"Anything else worth capturing?",a:N})}if(y||w.length===0){console.log(m.yellow(`
376
+ Nothing captured. Exiting.`)),c?.close();return}let b=a.listArticles(e.agent).slice(0,40).map(N=>`- ${N.meta.title} [${N.meta.type||"?"}]`).join(`
377
+ `),x=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${g}`,`**Type:** ${l}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...w.map(N=>`
378
+ Q: ${N.q}
379
+ A: ${N.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",b||"(none yet)","","## Output rules","- Output EXACTLY one markdown file: frontmatter (---) + body. No code fences, no preamble.","- Frontmatter fields in this exact order: title, type, related, tags, owner, access, created, last_updated, sources.",' - `title`: "\u2026"',` - \`type\`: ${l}`,' - `related`: ["Article Title", \u2026] (titles that exist in the catalog above; drop if none)'," - `tags`: 2-4 specific tags, lowercase-kebab \u2014 no dates unless type=event",` - \`owner\`: ${e.agent}`," - `access`: public (unless the content is sensitive)",` - \`created\`: ${new Date().toISOString().slice(0,10)}`,` - \`last_updated\`: ${new Date().toISOString().slice(0,10)}`,` - \`sources\`: ["interview-${new Date().toISOString().slice(0,10)}"]`,"- Body: 20-80 lines, Wikipedia-style, organized by theme (not by question), synthesized (not verbatim Q&A).","- Use [[Title]] inline every time you reference something that has an article in the catalog.","- Do NOT invent facts. If the transcript didn't cover something, skip that sub-topic."].join(`
380
+ `),A=q(a.baseDir,"_tmp");go(A,{recursive:!0});let S=q(A,`interview-${t().slice(0,8)}.txt`);Go(S,x),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let v="";try{let N=`cat '${S}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,me=Jo(N,{env:Ko({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Ge=JSON.parse(me);v=String(Ge.result||Ge.content||"")}catch{v=me}}catch(N){console.log(m.red(` synthesis failed: ${N.message?.slice(0,200)}`)),c?.close();return}v=v.trim();let $=v.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);$&&(v=$[1].trim());let C=v.indexOf("---");C>0&&(v=v.slice(C));let j=v.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!j){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(v.slice(0,600)),c?.close();return}let T={};for(let N of j[1].split(`
381
+ `)){let me=N.match(/^(\w+):\s*(.+)$/);me&&(T[me[1]]=me[2].trim().replace(/^"(.*)"$/,"$1"))}let D=j[2],W=T.title||g,L=W.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),ae=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[l]||l+"s"}/${L}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${ae}`)),console.log(),console.log(v),console.log();let B=await d(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),B==="scrap"||B==="/abort"){console.log(m.dim(" Discarded."));return}if(!e.commit){console.log(m.dim(" --no-commit: not writing.")),console.log(m.dim(` Draft kept at ${S} (prompt only; no article file)`));return}let xe=D,ye={title:W,type:T.type||l,related:T.related?T.related.replace(/^\[|\]$/g,"").split(",").map(N=>N.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:T.tags?T.tags.replace(/^\[|\]$/g,"").split(",").map(N=>N.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:T.access||"public",created:T.created||new Date().toISOString().slice(0,10),lastUpdated:T.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(B==="edit"){let N=process.env.EDITOR||"vi",me=q(A,`draft-${t().slice(0,8)}.md`);Go(me,v);try{Jo(`${N} '${me}'`,{stdio:"inherit"});let us=en(me,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(us){let po={};for(let Ot of us[1].split(`
382
+ `)){let fs=Ot.match(/^(\w+):\s*(.+)$/);fs&&(po[fs[1]]=fs[2].trim().replace(/^"(.*)"$/,"$1"))}xe=us[2],ye={...ye,title:po.title||ye.title,type:po.type||ye.type,access:po.access||ye.access,related:po.related?po.related.replace(/^\[|\]$/g,"").split(",").map(Ot=>Ot.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ye.related,tags:po.tags?po.tags.replace(/^\[|\]$/g,"").split(",").map(Ot=>Ot.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ye.tags}}}catch(Ge){console.log(m.red(` editor failed: ${Ge.message}`));return}}if(!a.writeArticle(ae,ye,xe,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${ae} saved.`));let qe=a.extractWikilinks(xe),we=new Map;for(let N of a.listArticles(e.agent))we.set(N.meta.title.toLowerCase(),!0);let Co=qe.filter(N=>!we.has(N.toLowerCase()));if(Co.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let N of Co.slice(0,8))console.log(m.dim(` - ${N}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});ee.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{agenticQuery:n}=await import("./query-ZSUBNWOL.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=ve(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(f){console.log(m.red(` can't open wiki for agent "${e.agent}": ${f.message}`));return}let r=null;if(e.script){let u=en(e.script,"utf-8").split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);r=[];for(let w of u){let y=w.split(/\r?\n/).filter(x=>x.trim());if(y.length<2)continue;let k=y[0].replace(/^Q:\s*/i,"").trim(),b=y.slice(1).join(" ").trim();k&&b&&r.push({q:k,verdict:b})}}let a=r?null:o.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",d=Math.min(parseInt(e.rounds)||20,r?.length??999),g=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${d} \xB7 ${g?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let l=[],p=0;for(let f=0;f<d;f++){let u,w;if(r){let G=r[f];if(!G)break;u=G.q,w=G.verdict,console.log(m.cyan(` [${f+1}] Q: `)+u)}else{if(u=await c(m.cyan(` [${f+1}] Q: `)),!u||u==="/done"||u==="/abort")break;w=""}process.stdout.write(m.dim(" querying... "));let y;try{y=await n(u,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(G){console.log(m.red(`failed: ${G.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),y.status!=="ok")console.log(m.yellow(` (status: ${y.status}${y.error?" \u2014 "+y.error:""})`));else{let G=y.citations.map(ae=>`${ae.title} [${ae.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
383
+ `)),console.log(m.dim(" citations: "+G))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let k={q:u,answer:y.answer,citations:y.citations,verdict:w},b=w.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!b){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),l.push(k);continue}let x=b[1].toLowerCase(),A=(b[2]||"").trim();if(l.push(k),x==="/ok"||x==="/skip")continue;if(!A){console.log(m.yellow(` ${x} without note \u2014 skipping.`));continue}let S=y.citations[0];if(!S){console.log(m.yellow(" no cited article to patch."));continue}let v=i.readArticle(S.path);if(!v){console.log(m.red(` can't read ${S.path} to patch.`));continue}console.log(m.dim(` patching ${S.title} (${S.path})...`));let $=zp(v.content,x,A,v.meta.title,v.meta.type),C=q(i.baseDir,"_tmp");go(C,{recursive:!0});let j=q(C,`quiz-patch-${t().slice(0,8)}.txt`);Go(j,$);let T="";try{let G=`cat '${j}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,ae=Jo(G,{env:Ko({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let xe=JSON.parse(ae);T=String(xe.result||xe.content||"")}catch{T=ae}let B=T.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);B&&(T=B[1].trim()),T=T.trim()}catch(G){console.log(m.red(` patch failed: ${G.message?.slice(0,120)}`));continue}if(!T||T.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let D=v.content.split(`
384
+ `).length,W=T.split(`
385
+ `).length;if(console.log(m.dim(` diff: ${D} \u2192 ${W} lines (${W-D>=0?"+":""}${W-D})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),k.patched=S.path+" (dry)";continue}if(!i.writeArticle(S.path,{...v.meta,lastUpdated:new Date().toISOString().slice(0,10)},T,e.agent)){console.log(m.red(" write failed (permission?)"));continue}p++,k.patched=S.path,console.log(m.green(` \u2713 patched ${S.path}`))}if(a&&a.close(),p>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${l.length} rounds, ${p} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${l.length} rounds \xB7 ${p} patches_`,""];for(let u=0;u<l.length;u++){let w=l[u];f.push(`## ${u+1}. Q: ${w.q}`,"",`**A:** ${w.answer}`,"",`**Citations:** ${w.citations.map(y=>`\`${y.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${w.verdict}\``+(w.patched?` \u2192 patched \`${w.patched}\``:""),"")}Go(e.out,f.join(`
386
+ `)),console.log(m.dim(` Transcript written to ${e.out}`))}});ee.command("edit <agent> <titleOrPath>").description("open an article in $EDITOR (resolves by title or path), rebuild catalog on exit").option("--dir <path>","wiki directory").option("--editor <cmd>","override $EDITOR for this run").action((e,o,t)=>{let n=ve(t.dir),s;try{s=n.getAgentWiki(e)}catch(d){console.log(m.red(` can't open wiki for agent "${e}": ${d.message}`));return}let i=Gc(s,o,e);if(!i){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`)),console.log(m.dim(` Tip: ${m.green("agentx wiki status")} lists agents; ${m.green(`agentx wiki search "term" --agent ${e}`)} finds by content.`));return}let r=q(s.baseDir,i),a=t.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${i} in ${a}...`));try{Jo(`${a} '${r}'`,{stdio:"inherit"})}catch(d){console.log(m.red(` editor exited with error: ${d.message?.slice(0,150)}`));return}let c=s.readArticle(i);if(c){let d=new Set,g=s.extractWikilinks(c.content).filter(f=>d.has(f)?!1:(d.add(f),!0)),l=c.meta.related||[];(g.some(f=>!l.includes(f))||l.some(f=>!g.includes(f)))&&(s.writeArticle(i,{...c.meta,related:g.length?g:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.content,e),console.log(m.dim(` (synced frontmatter.related from body: ${g.length} wikilink${g.length===1?"":"s"})`)))}try{s.rebuildIndex(),console.log(m.green(` \u2713 ${i} saved. Catalog rebuilt.`))}catch(d){console.log(m.yellow(` saved, but catalog rebuild failed: ${d.message?.slice(0,100)}`))}});ee.command("patch <agent> <titleOrPath> <instruction>").description("LLM-patch an article from a free-form instruction; shows diff + confirms before writing").option("--dir <path>","wiki directory").option("--patch-model <m>","patch model","sonnet").option("--yes","skip confirmation and write immediately").option("--no-commit","show the patched body but don't write").action(async(e,o,t,n)=>{let s=await import("node:readline/promises"),{randomUUID:i}=await import("node:crypto"),r=ve(n.dir),a;try{a=r.getAgentWiki(e)}catch(S){console.log(m.red(` can't open wiki for agent "${e}": ${S.message}`));return}let c=Gc(a,o,e);if(!c){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`));return}let d=a.readArticle(c);if(!d){console.log(m.red(` can't read ${c}.`));return}let g=Hp(d.content,d.meta.title,d.meta.type,t),l=q(a.baseDir,"_tmp");go(l,{recursive:!0});let p=q(l,`patch-${i().slice(0,8)}.txt`);Go(p,g),console.log(),console.log(m.dim(` Target: ${d.meta.title} (${c})`)),console.log(m.dim(` Patching with ${n.patchModel}...`));let f="";try{let S=`cat '${p}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,v=Jo(S,{env:Ko({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let C=JSON.parse(v);f=String(C.result||C.content||"")}catch{f=v}let $=f.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);$&&(f=$[1].trim()),f=f.trim()}catch(S){console.log(m.red(` patch failed: ${S.message?.slice(0,150)}`));return}if(!f||f.length<20){console.log(m.yellow(" patch returned nothing usable."));return}let u=d.content.split(`
353
387
  `).length,w=f.split(`
354
- `).length;if(console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${u} \u2192 ${w} lines (${w-u>=0?"+":""}${w-u})`)),console.log(),console.log(f),console.log(),!n.commit){console.log(m.dim(" --no-commit: preview only, not written."));return}let y=!!n.yes;if(!y){let x=s.createInterface({input:process.stdin,output:process.stdout}),E=(await x.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();x.close(),y=E==="y"||E==="yes"}if(!y){console.log(m.dim(" aborted."));return}let $=new Set,b=a.extractWikilinks(f).filter(x=>$.has(x)?!1:($.add(x),!0));if(!a.writeArticle(c,{...d.meta,related:b.length?b:void 0,lastUpdated:new Date().toISOString().slice(0,10)},f,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex();let A=(d.meta.related||[]).filter(x=>!b.includes(x));A.length&&console.log(m.dim(` (pruned stale related: ${A.slice(0,3).join(", ")}${A.length>3?", \u2026":""})`)),console.log(m.green(` \u2713 ${c} patched.`))});function Ac(e,o,t){let n=o.trim(),s=e.listArticles(t),i=n.toLowerCase(),r=s.find(d=>d.meta.title.toLowerCase()===i);if(r)return r.path;if(n.includes("/")||n.endsWith(".md")){let d=n.endsWith(".md")?n:`${n}.md`,g=s.find(l=>l.path===d||l.path===n);if(g)return g.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(d=>{let g=d.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return g===a||g.includes(a)||d.path.toLowerCase().includes(a)});return c?c.path:null}function cp(e,o,t,n){return["You are editing a single wiki article to incorporate an operator instruction.","",`## Article: "${o}" (type: ${t||"untyped"})`,"","<article-body>",e,"</article-body>","","## Operator instruction",n,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the instruction requires changing them.","- Make the MINIMUM edit that satisfies the instruction \u2014 don't rewrite untouched sections.","- If the instruction is ambiguous or can't be applied, return the original body unchanged."].join(`
355
- `)}function lp(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
388
+ `).length;if(console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${u} \u2192 ${w} lines (${w-u>=0?"+":""}${w-u})`)),console.log(),console.log(f),console.log(),!n.commit){console.log(m.dim(" --no-commit: preview only, not written."));return}let y=!!n.yes;if(!y){let S=s.createInterface({input:process.stdin,output:process.stdout}),v=(await S.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();S.close(),y=v==="y"||v==="yes"}if(!y){console.log(m.dim(" aborted."));return}let k=new Set,b=a.extractWikilinks(f).filter(S=>k.has(S)?!1:(k.add(S),!0));if(!a.writeArticle(c,{...d.meta,related:b.length?b:void 0,lastUpdated:new Date().toISOString().slice(0,10)},f,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex();let A=(d.meta.related||[]).filter(S=>!b.includes(S));A.length&&console.log(m.dim(` (pruned stale related: ${A.slice(0,3).join(", ")}${A.length>3?", \u2026":""})`)),console.log(m.green(` \u2713 ${c} patched.`))});function Gc(e,o,t){let n=o.trim(),s=e.listArticles(t),i=n.toLowerCase(),r=s.find(d=>d.meta.title.toLowerCase()===i);if(r)return r.path;if(n.includes("/")||n.endsWith(".md")){let d=n.endsWith(".md")?n:`${n}.md`,g=s.find(l=>l.path===d||l.path===n);if(g)return g.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(d=>{let g=d.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return g===a||g.includes(a)||d.path.toLowerCase().includes(a)});return c?c.path:null}function Hp(e,o,t,n){return["You are editing a single wiki article to incorporate an operator instruction.","",`## Article: "${o}" (type: ${t||"untyped"})`,"","<article-body>",e,"</article-body>","","## Operator instruction",n,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the instruction requires changing them.","- Make the MINIMUM edit that satisfies the instruction \u2014 don't rewrite untouched sections.","- If the instruction is ambiguous or can't be applied, return the original body unchanged."].join(`
389
+ `)}function zp(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
356
390
 
357
391
  ${t}
358
392
 
@@ -365,8 +399,8 @@ Incorporate it into the most relevant existing section, or create a short new se
365
399
  ${t}
366
400
 
367
401
  Add it as a Markdown link in the most relevant section, or append a "## References" section at the end if none exists. If it looks like a URL, use it as-is; otherwise treat it as a wikilink target and use [[${t}]].`};return["You are editing a single wiki article to incorporate operator feedback.","",`## Article: "${n}" (type: ${s||"untyped"})`,"","<article-body>",e,"</article-body>","","## Edit instruction",i[o]||`Make a minimal edit per: ${t}`,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the edit requires changing them.","- If no meaningful edit can be made from the operator's feedback, return the original body unchanged."].join(`
368
- `)}ee.command("prune").description("collapse legacy flat/unified mode dirs into graph/ (dedup by title; losers archived)").option("--dir <path>","wiki directory").option("--agent <id>","prune only this agent's wiki").option("--commit","execute moves + archives (default: dry-run)").action(async e=>{let o=ke(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=!!e.commit,s=e.dir?q(e.dir):q(process.cwd(),".agentx/wiki"),i="graph",r=["flat","unified"];console.log(),console.log(m.bold(n?" Pruning (commit)":" Pruning (dry-run)")),console.log(m.dim(` Canonical: ${i}/ \xB7 Legacy to collapse: ${r.join("/, ")}/`));let a=0,c=0,d=0,g=0;for(let l of t){let p=q(s,"agents",l);if(!Be(p))continue;let f=q(p,i),u=r.map(b=>({mode:b,dir:q(p,b)})).filter(b=>Be(b.dir));if(u.length===0)continue;let w=new Map;ti(f,b=>{let v=vc(f,b);if(v.startsWith("_")||v.startsWith("raw/")||v.includes("_tmp/"))return;let A=Sc(Yt(b,"utf-8"));A?.meta.title&&w.set(A.meta.title.trim().toLowerCase(),{relPath:v,type:A.meta.type,lastUpdated:A.meta.lastUpdated||""})});let y=[];for(let b of u)ti(b.dir,v=>{let A=vc(b.dir,v);if(A.startsWith("_")||A.startsWith("raw/")||A.includes("_tmp/"))return;let x=Sc(Yt(v,"utf-8"));x?.meta.title&&y.push({mode:b.mode,relPath:A,absPath:v,title:x.meta.title.trim(),type:x.meta.type,lastUpdated:x.meta.lastUpdated||""})});if(a+=y.length,y.length===0)continue;console.log();let $=u.map(b=>b.mode).join("+");console.log(m.bold(` ${m.cyan(l)}: ${y.length} legacy article(s) across ${$}`));for(let b of y){let v=b.title.toLowerCase(),A=w.get(v),x;A?!A.type&&b.type||!!A.type==!!b.type&&b.lastUpdated&&A.lastUpdated&&b.lastUpdated>A.lastUpdated?x="upgrade":x="archive":x="promote";let E=b.type?m.magenta(`[${b.type}]`):m.yellow("[untyped]"),k=x==="promote"?m.green("\u2192 promote "):x==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),N=b.relPath.length>46?b.relPath.slice(0,43)+"...":b.relPath.padEnd(46);if(console.log(` ${k} ${E} ${m.dim(b.mode+"/")}${N}`),x==="upgrade"&&console.log(m.dim(` (replaces ${A.relPath}, old version kept under _versions/)`)),!n){x==="promote"?c++:x==="upgrade"?d++:g++;continue}try{if(x==="promote"){let C=q(f,b.relPath);Be(C)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${b.relPath}`)),Ec(p,b),g++):(co(xc(C),{recursive:!0}),qn(b.absPath,C),w.set(v,{relPath:b.relPath,type:b.type,lastUpdated:b.lastUpdated}),c++)}else if(x==="upgrade"){let C=q(f,A.relPath);if(Be(C)){let I=q(p,"_versions",A.relPath.replace(/\.md$/,""));co(I,{recursive:!0});let P=new Date().toISOString().replace(/[:.]/g,"-");qn(C,q(I,`${P}.md`))}co(xc(C),{recursive:!0}),qn(b.absPath,C),w.set(v,{relPath:A.relPath,type:b.type,lastUpdated:b.lastUpdated}),d++}else Ec(p,b),g++}catch(C){console.log(m.red(` ! ${x} failed: ${C.message?.slice(0,120)}`))}}if(n){for(let b of u)try{rp(b.dir,{recursive:!0,force:!0})}catch{}try{o.getAgentWiki(l).rebuildIndex()}catch(b){console.log(m.dim(` (catalog rebuild skipped: ${b.message?.slice(0,80)})`))}}}console.log(),console.log(m.dim(` Legacy scanned: ${a}`)),n?(console.log(m.green(` Promoted: ${c} \xB7 Upgraded canonical: ${d} \xB7 Archived: ${g}`)),console.log(m.dim(" Archived losers preserved under <agent>/_versions/. Legacy mode dirs deleted."))):(console.log(m.dim(` Would: promote ${c} \xB7 upgrade ${d} \xB7 archive ${g}`)),console.log(m.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function ti(e,o){if(Be(e))for(let t of ip(e,{withFileTypes:!0})){let n=q(e,t.name);t.isDirectory()?ti(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function Sc(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
369
- `)){let s=n.match(/^(\w+):\s*(.+)$/);if(!s)continue;let i=s[1]==="last_updated"?"lastUpdated":s[1];t[i]=s[2].trim().replace(/^"(.*)"$/,"$1")}return{meta:t}}function Ec(e,o){let t=q(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));co(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");qn(o.absPath,q(t,`${n}.md`))}ee.command("migrate").description("backfill type + related on legacy articles (one-shot)").option("--dir <path>","wiki directory").option("--agent <id>","migrate only this agent's articles").option("--commit","write changes (default: dry-run, reports what would change)").option("--batch <n>","articles per LLM call","10").option("--max <n>","cap articles this run (for spot-checks)").option("--model <m>","classifier model","sonnet").action(async e=>{let o=ke(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=Math.max(1,parseInt(e.batch)||10),s=e.max?parseInt(e.max):1/0,i=!!e.commit;console.log(),console.log(m.bold(i?" Migrating (commit)":" Migrating (dry-run)")),console.log(m.dim(` Batch size: ${n} \xB7 Model: ${e.model}`)),console.log();let r=0,a=0,c=0;for(let d of t){let g=o.getAgentWiki(d),l=g.listArticles(d),p=l.filter($=>!$.meta.type);if(r+=l.length,a+=p.length,p.length===0){console.log(` ${m.cyan(d)}: ${m.green("all typed")} (${l.length} articles)`);continue}let f=Math.max(0,s-c),u=Math.min(p.length,f);if(u===0){console.log(m.dim(` ${d}: skipped (--max reached)`));continue}console.log(),console.log(m.bold(` ${m.cyan(d)}: ${u}/${p.length} untyped articles`));let w=g.baseDir,y=q(w,"_tmp");co(y,{recursive:!0});for(let $=0;$<u;$+=n){let b=p.slice($,Math.min($+n,u)),v=gp(b),A=q(y,"migrate-prompt.txt");Wo(A,v);let x;try{let E=`cat '${A}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,k=qo(E,{env:zo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),N=JSON.parse(k),I=String(N.result||N.content||"").match(/\[[\s\S]*\]/);if(!I)throw new Error("no JSON array in classifier response");x=JSON.parse(I[0])}catch(E){console.log(m.red(` LLM classify failed: ${E.message?.slice(0,150)}`));continue}for(let E of b){let k=x.find(L=>L.path===E.path),N=dp(k?.type);if(!k||!N){console.log(m.yellow(` ? ${E.path}: unclassified${k?` (got "${k.type}")`:""}`));continue}let C=g.extractWikilinks(E.content),I={...E.meta,type:N.type,related:C.length?C:void 0,lastUpdated:new Date().toISOString().slice(0,10)},P=C.length?m.dim(` \u2192 ${C.slice(0,3).join(", ")}${C.length>3?", \u2026":""}`):"",W=N.alias?m.dim(` (from "${N.alias}")`):"";console.log(` ${m.green("+")} ${m.magenta("["+N.type+"]")}${W} ${E.path}${P}`),i&&(g.writeArticle(E.path,I,E.content,d),c++)}}i&&g.rebuildIndex()}console.log(),console.log(m.dim(` Scanned ${r} articles; ${a} needed migration`)),console.log(i?m.green(` Applied ${c} patches.`):m.dim(" Dry-run \u2014 add --commit to write changes.")),console.log()});function dp(e){if(!e)return null;let o=String(e).trim().toLowerCase().replace(/^[\s"'`]+|[\s"'`]+$/g,"");if(!o)return null;let n={person:"person",project:"project",place:"place",concept:"concept",event:"event",decision:"decision",pattern:"pattern",people:"person",projects:"project",places:"place",concepts:"concept",events:"event",decisions:"decision",patterns:"pattern",agent:"project",bot:"project",service:"project",product:"project",tool:"project",repo:"project",repository:"project",app:"project",application:"project",team:"project",organization:"project",company:"project",issue:"event",mr:"event","merge-request":"event",merge_request:"event",ticket:"event",incident:"event",deploy:"event",deployment:"event",launch:"event",release:"event",process:"pattern",procedure:"pattern",workflow:"pattern",runbook:"pattern",recipe:"pattern",template:"pattern",sop:"pattern",infrastructure:"place",infra:"place",server:"place",environment:"place",env:"place",location:"place",host:"place",decisionrecord:"decision",adr:"decision","decision-record":"decision"}[o];return n?n===o?{type:n}:{type:n,alias:o}:null}function gp(e){let o=e.map((t,n)=>{let s=t.content.replace(/\s+/g," ").slice(0,400),i=(t.meta.tags||[]).slice(0,8).join(", ");return`${n+1}. path: "${t.path}"
402
+ `)}ee.command("prune").description("collapse legacy flat/unified mode dirs into graph/ (dedup by title; losers archived)").option("--dir <path>","wiki directory").option("--agent <id>","prune only this agent's wiki").option("--commit","execute moves + archives (default: dry-run)").action(async e=>{let o=ve(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=!!e.commit,s=e.dir?q(e.dir):q(process.cwd(),".agentx/wiki"),i="graph",r=["flat","unified"];console.log(),console.log(m.bold(n?" Pruning (commit)":" Pruning (dry-run)")),console.log(m.dim(` Canonical: ${i}/ \xB7 Legacy to collapse: ${r.join("/, ")}/`));let a=0,c=0,d=0,g=0;for(let l of t){let p=q(s,"agents",l);if(!Je(p))continue;let f=q(p,i),u=r.map(b=>({mode:b,dir:q(p,b)})).filter(b=>Je(b.dir));if(u.length===0)continue;let w=new Map;ui(f,b=>{let x=qc(f,b);if(x.startsWith("_")||x.startsWith("raw/")||x.includes("_tmp/"))return;let A=Bc(en(b,"utf-8"));A?.meta.title&&w.set(A.meta.title.trim().toLowerCase(),{relPath:x,type:A.meta.type,lastUpdated:A.meta.lastUpdated||""})});let y=[];for(let b of u)ui(b.dir,x=>{let A=qc(b.dir,x);if(A.startsWith("_")||A.startsWith("raw/")||A.includes("_tmp/"))return;let S=Bc(en(x,"utf-8"));S?.meta.title&&y.push({mode:b.mode,relPath:A,absPath:x,title:S.meta.title.trim(),type:S.meta.type,lastUpdated:S.meta.lastUpdated||""})});if(a+=y.length,y.length===0)continue;console.log();let k=u.map(b=>b.mode).join("+");console.log(m.bold(` ${m.cyan(l)}: ${y.length} legacy article(s) across ${k}`));for(let b of y){let x=b.title.toLowerCase(),A=w.get(x),S;A?!A.type&&b.type||!!A.type==!!b.type&&b.lastUpdated&&A.lastUpdated&&b.lastUpdated>A.lastUpdated?S="upgrade":S="archive":S="promote";let v=b.type?m.magenta(`[${b.type}]`):m.yellow("[untyped]"),$=S==="promote"?m.green("\u2192 promote "):S==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),C=b.relPath.length>46?b.relPath.slice(0,43)+"...":b.relPath.padEnd(46);if(console.log(` ${$} ${v} ${m.dim(b.mode+"/")}${C}`),S==="upgrade"&&console.log(m.dim(` (replaces ${A.relPath}, old version kept under _versions/)`)),!n){S==="promote"?c++:S==="upgrade"?d++:g++;continue}try{if(S==="promote"){let j=q(f,b.relPath);Je(j)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${b.relPath}`)),Jc(p,b),g++):(go(Wc(j),{recursive:!0}),Qn(b.absPath,j),w.set(x,{relPath:b.relPath,type:b.type,lastUpdated:b.lastUpdated}),c++)}else if(S==="upgrade"){let j=q(f,A.relPath);if(Je(j)){let T=q(p,"_versions",A.relPath.replace(/\.md$/,""));go(T,{recursive:!0});let D=new Date().toISOString().replace(/[:.]/g,"-");Qn(j,q(T,`${D}.md`))}go(Wc(j),{recursive:!0}),Qn(b.absPath,j),w.set(x,{relPath:A.relPath,type:b.type,lastUpdated:b.lastUpdated}),d++}else Jc(p,b),g++}catch(j){console.log(m.red(` ! ${S} failed: ${j.message?.slice(0,120)}`))}}if(n){for(let b of u)try{Jp(b.dir,{recursive:!0,force:!0})}catch{}try{o.getAgentWiki(l).rebuildIndex()}catch(b){console.log(m.dim(` (catalog rebuild skipped: ${b.message?.slice(0,80)})`))}}}console.log(),console.log(m.dim(` Legacy scanned: ${a}`)),n?(console.log(m.green(` Promoted: ${c} \xB7 Upgraded canonical: ${d} \xB7 Archived: ${g}`)),console.log(m.dim(" Archived losers preserved under <agent>/_versions/. Legacy mode dirs deleted."))):(console.log(m.dim(` Would: promote ${c} \xB7 upgrade ${d} \xB7 archive ${g}`)),console.log(m.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function ui(e,o){if(Je(e))for(let t of Bp(e,{withFileTypes:!0})){let n=q(e,t.name);t.isDirectory()?ui(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function Bc(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
403
+ `)){let s=n.match(/^(\w+):\s*(.+)$/);if(!s)continue;let i=s[1]==="last_updated"?"lastUpdated":s[1];t[i]=s[2].trim().replace(/^"(.*)"$/,"$1")}return{meta:t}}function Jc(e,o){let t=q(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));go(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");Qn(o.absPath,q(t,`${n}.md`))}ee.command("migrate").description("backfill type + related on legacy articles (one-shot)").option("--dir <path>","wiki directory").option("--agent <id>","migrate only this agent's articles").option("--commit","write changes (default: dry-run, reports what would change)").option("--batch <n>","articles per LLM call","10").option("--max <n>","cap articles this run (for spot-checks)").option("--model <m>","classifier model","sonnet").action(async e=>{let o=ve(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=Math.max(1,parseInt(e.batch)||10),s=e.max?parseInt(e.max):1/0,i=!!e.commit;console.log(),console.log(m.bold(i?" Migrating (commit)":" Migrating (dry-run)")),console.log(m.dim(` Batch size: ${n} \xB7 Model: ${e.model}`)),console.log();let r=0,a=0,c=0;for(let d of t){let g=o.getAgentWiki(d),l=g.listArticles(d),p=l.filter(k=>!k.meta.type);if(r+=l.length,a+=p.length,p.length===0){console.log(` ${m.cyan(d)}: ${m.green("all typed")} (${l.length} articles)`);continue}let f=Math.max(0,s-c),u=Math.min(p.length,f);if(u===0){console.log(m.dim(` ${d}: skipped (--max reached)`));continue}console.log(),console.log(m.bold(` ${m.cyan(d)}: ${u}/${p.length} untyped articles`));let w=g.baseDir,y=q(w,"_tmp");go(y,{recursive:!0});for(let k=0;k<u;k+=n){let b=p.slice(k,Math.min(k+n,u)),x=Vp(b),A=q(y,"migrate-prompt.txt");Go(A,x);let S;try{let v=`cat '${A}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,$=Jo(v,{env:Ko({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),C=JSON.parse($),T=String(C.result||C.content||"").match(/\[[\s\S]*\]/);if(!T)throw new Error("no JSON array in classifier response");S=JSON.parse(T[0])}catch(v){console.log(m.red(` LLM classify failed: ${v.message?.slice(0,150)}`));continue}for(let v of b){let $=S.find(L=>L.path===v.path),C=Yp($?.type);if(!$||!C){console.log(m.yellow(` ? ${v.path}: unclassified${$?` (got "${$.type}")`:""}`));continue}let j=g.extractWikilinks(v.content),T={...v.meta,type:C.type,related:j.length?j:void 0,lastUpdated:new Date().toISOString().slice(0,10)},D=j.length?m.dim(` \u2192 ${j.slice(0,3).join(", ")}${j.length>3?", \u2026":""}`):"",W=C.alias?m.dim(` (from "${C.alias}")`):"";console.log(` ${m.green("+")} ${m.magenta("["+C.type+"]")}${W} ${v.path}${D}`),i&&(g.writeArticle(v.path,T,v.content,d),c++)}}i&&g.rebuildIndex()}console.log(),console.log(m.dim(` Scanned ${r} articles; ${a} needed migration`)),console.log(i?m.green(` Applied ${c} patches.`):m.dim(" Dry-run \u2014 add --commit to write changes.")),console.log()});function Yp(e){if(!e)return null;let o=String(e).trim().toLowerCase().replace(/^[\s"'`]+|[\s"'`]+$/g,"");if(!o)return null;let n={person:"person",project:"project",place:"place",concept:"concept",event:"event",decision:"decision",pattern:"pattern",people:"person",projects:"project",places:"place",concepts:"concept",events:"event",decisions:"decision",patterns:"pattern",agent:"project",bot:"project",service:"project",product:"project",tool:"project",repo:"project",repository:"project",app:"project",application:"project",team:"project",organization:"project",company:"project",issue:"event",mr:"event","merge-request":"event",merge_request:"event",ticket:"event",incident:"event",deploy:"event",deployment:"event",launch:"event",release:"event",process:"pattern",procedure:"pattern",workflow:"pattern",runbook:"pattern",recipe:"pattern",template:"pattern",sop:"pattern",infrastructure:"place",infra:"place",server:"place",environment:"place",env:"place",location:"place",host:"place",decisionrecord:"decision",adr:"decision","decision-record":"decision"}[o];return n?n===o?{type:n}:{type:n,alias:o}:null}function Vp(e){let o=e.map((t,n)=>{let s=t.content.replace(/\s+/g," ").slice(0,400),i=(t.meta.tags||[]).slice(0,8).join(", ");return`${n+1}. path: "${t.path}"
370
404
  title: "${t.meta.title}"
371
405
  tags: [${i}]
372
406
  body: ${s}${t.content.length>400?"\u2026":""}`}).join(`
@@ -406,45 +440,45 @@ Output (JSON array, one entry per input article, same order):
406
440
  [
407
441
  {"path": "path/to/article.md", "type": "project"},
408
442
  ...
409
- ]`}ee.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=ke(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});ee.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let o=e.dir||q(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-SRTXHGSK.js");n=(s().mesh?.peers||[]).map(r=>r.url)}catch{}console.log(),console.log(m.bold(" AgentX Wiki Server")),console.log(),console.log(` ${m.green(">")} http://localhost:${t}`),e.agent?console.log(` Agent: ${m.cyan(e.agent)}`):console.log(` Mode: ${m.cyan("Hub")} (all agents)`),n.length>0&&console.log(` Mesh: ${m.cyan(n.length+" peer(s)")} \u2014 ${n.join(", ")}`),console.log(m.dim(` Wiki: ${o}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),Hr(o,t,e.agent,n,e.mode)});ee.command("grade").description("grade absorbed articles with the article-quality seat").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","grade only this agent's wiki").option("--limit <n>","articles to grade","20").option("--min <n>","only show articles scoring below this","3").option("--fields","also check the required fields for each article's type").option("--type <t>","grade only articles of this type (person, place, project, \u2026)").option("--json").action(async e=>{let{articleQualityQuestionsFor:o,articleQualityState:t,gradeArticle:n,ARTICLE_QUALITY_SEAT:s}=await import("./article-quality-44ONVGLN.js"),{fieldQuestions:i,reportFields:r}=await import("./article-fields-L4D2BOGY.js"),{askSeat:a}=await import("./seat-XB4EGUKJ.js"),c=ke(e.dir,e.mode),d=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),l=parseFloat(e.min),p=[];e:for(let y of d){let $=c.getAgentWiki(y);for(let b of $.listArticles(y)){if(p.length>=g)break e;let v=$.readArticle(b.path);if(!v||e.type&&v.meta.type!==e.type)continue;let A={...o(v.meta.type),...e.fields?i(v.meta.type):{}},x=await a(s,t({path:b.path,title:v.meta.title,type:v.meta.type,tags:v.meta.tags,body:v.content}),A,{links:[{kind:"article",id:b.path}],features:{agent:y,type:v.meta.type??"?"}});if(!x){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let E=n(x.answers),k=e.fields?r(v.meta.type,x.answers):null;E.completeness>=l&&!(k&&!k.fit)||p.push({agent:y,type:v.meta.type??"?",score:E.completeness.toFixed(2),standsAlone:E.standsAlone.toFixed(2),gap:E.biggestGap,...k?{missing:k.missingCritical.join(",")||"-",cov:`${Math.round(k.coverage*100)}%`}:{},title:v.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(" no articles below the threshold"));return}p.sort((y,$)=>parseFloat(y.score)-parseFloat($.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],u=f.map(y=>Math.max(y.length,...p.map($=>String($[y]).length))),w=y=>y.map(($,b)=>String($).padEnd(u[b])).join(" ");console.log(),console.log(m.bold(w(f)));for(let y of p)console.log(w(f.map($=>y[$])));if(e.fields){let y=p.filter($=>$.missing!=="-").length;console.log(m.dim(`
443
+ ]`}ee.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=ve(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});ee.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let o=e.dir||q(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-SRTXHGSK.js");n=(s().mesh?.peers||[]).map(r=>r.url)}catch{}console.log(),console.log(m.bold(" AgentX Wiki Server")),console.log(),console.log(` ${m.green(">")} http://localhost:${t}`),e.agent?console.log(` Agent: ${m.cyan(e.agent)}`):console.log(` Mode: ${m.cyan("Hub")} (all agents)`),n.length>0&&console.log(` Mesh: ${m.cyan(n.length+" peer(s)")} \u2014 ${n.join(", ")}`),console.log(m.dim(` Wiki: ${o}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),oa(o,t,e.agent,n,e.mode)});ee.command("grade").description("grade absorbed articles with the article-quality seat").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","grade only this agent's wiki").option("--limit <n>","articles to grade","20").option("--min <n>","only show articles scoring below this","3").option("--fields","also check the required fields for each article's type").option("--type <t>","grade only articles of this type (person, place, project, \u2026)").option("--json").action(async e=>{let{articleQualityQuestionsFor:o,articleQualityState:t,gradeArticle:n,ARTICLE_QUALITY_SEAT:s}=await import("./article-quality-44ONVGLN.js"),{fieldQuestions:i,reportFields:r}=await import("./article-fields-L4D2BOGY.js"),{askSeat:a}=await import("./seat-XB4EGUKJ.js"),c=ve(e.dir,e.mode),d=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),l=parseFloat(e.min),p=[];e:for(let y of d){let k=c.getAgentWiki(y);for(let b of k.listArticles(y)){if(p.length>=g)break e;let x=k.readArticle(b.path);if(!x||e.type&&x.meta.type!==e.type)continue;let A={...o(x.meta.type),...e.fields?i(x.meta.type):{}},S=await a(s,t({path:b.path,title:x.meta.title,type:x.meta.type,tags:x.meta.tags,body:x.content}),A,{links:[{kind:"article",id:b.path}],features:{agent:y,type:x.meta.type??"?"}});if(!S){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let v=n(S.answers),$=e.fields?r(x.meta.type,S.answers):null;v.completeness>=l&&!($&&!$.fit)||p.push({agent:y,type:x.meta.type??"?",score:v.completeness.toFixed(2),standsAlone:v.standsAlone.toFixed(2),gap:v.biggestGap,...$?{missing:$.missingCritical.join(",")||"-",cov:`${Math.round($.coverage*100)}%`}:{},title:x.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(" no articles below the threshold"));return}p.sort((y,k)=>parseFloat(y.score)-parseFloat(k.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],u=f.map(y=>Math.max(y.length,...p.map(k=>String(k[y]).length))),w=y=>y.map((k,b)=>String(k).padEnd(u[b])).join(" ");console.log(),console.log(m.bold(w(f)));for(let y of p)console.log(w(f.map(k=>y[k])));if(e.fields){let y=p.filter(k=>k.missing!=="-").length;console.log(m.dim(`
410
444
  ${p.length} article(s) flagged; ${y} missing a required field.`)),console.log(m.dim(" 'missing' is the actionable column \u2014 a named field beats a score."))}else console.log(m.dim(`
411
- ${p.length} article(s) below ${l}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});ee.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,o)=>{let{agenticQuery:t}=await import("./query-ZSUBNWOL.js"),n=ke(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let d=n.getAgentWiki(c),g=q(d.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(m.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(m.dim(" Citations:"));for(let c of a.citations){let d=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${d} (${c.path})`))}console.log()}if(o.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(d=>!a.candidates.some(g=>g.path===d.path));console.log(m.dim(` followed: ${c.map(d=>`${d.title}@h${d.hop}`).join(" | ")}`))}console.log()}});ee.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,o)=>{let t=ke(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=await t.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});ee.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let o=ke(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=q(process.cwd(),".agentx/graph");if(!Be(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new mo({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[l,p]of Object.entries(i.entries))r.set(l,p.path);if(r.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,d=0,g=0;for(let l of t){let p=o.getAgentWiki(l),f=p.listArticles(l),u=o.getSharedStore().listEntries(),w=new Map(u.map(v=>[v.id,v])),y=0,$=0,b=0;for(let v of f){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;y++,c++;let A=new Map;for(let E of v.meta.sources){let k=w.get(E);if(!k)continue;let N=String(k.meta?.sender??""),C=s.fingerprint({text:k.content,channel:k.source,sender:N}),I=r.get(C);if(!I?.length)continue;let P=I.join("/"),W=A.get(P);W?W.n++:A.set(P,{path:I,n:1})}if(A.size===0)continue;$++,d++;let x;for(let E of A.values())(!x||E.n>x.n)&&(x=E);x&&(e.dryRun||(p.writeArticle(v.path,{...v.meta,graphPath:x.path},v.content,l),b++,g++))}console.log(` ${m.cyan(l)}: ${m.bold(f.length)} articles \xB7 ${y} eligible \xB7 ${$} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${d} matched (${Math.round(d/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});ee.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let t=ke(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-SRTXHGSK.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(m.red(" No --peer specified and no daemon config found")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(n.length===0){console.log(m.dim(" No mesh peers configured"));return}let s=new Set(t.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(m.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(m.red(` HTTP ${a.status}`));continue}let c=await a.json(),d=c.entries||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${d.length} entries`));let l=0;for(let p of d)s.has(p.id)||(e.dryRun||(t.addEntry({id:p.id,date:p.date,agentId:p.agentId,source:`${p.source}@${g}`,sourceContext:p.sourceContext,content:p.content}),s.add(p.id)),l++);l>0?console.log(m.green(` ${l} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=l;try{let p=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(p.ok){let f=await p.json();for(let u of f.agents||[])u.totalEntries>0&&console.log(m.dim(` ${u.agentId}: ${u.totalEntries} entries, ${u.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});ee.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let o=e.dir||q(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let d=new rs(o,void 0,c),l=d.getAgentWiki(t).rebuildIndex(),p=d.getAgentEntries(t),f=d.getUnabsorbedEntries(t),u=new Set,w=0,y=new Set;for(let b of l.articles){for(let v of b.tags||[])u.add(v);w+=b.tags?.length||0;for(let v of b.sources||[])y.add(v)}let $=new Set(l.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:ni(c),articles:l.articles.length,entries:p.length,unabsorbed:f.length,uniqueTags:u.size,avgTags:l.articles.length>0?(w/l.articles.length).toFixed(1):"0",dirs:$.size,coverage:y.size,articleList:l.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,d]of r){let g=s.map(l=>d(l).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,d)=>{let g=Math.max(...s.map(p=>p[c])),l=s.filter(p=>p[c]===g).map(p=>p.label);g>0&&console.log(m.dim(` Best ${d}: ${l.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});ee.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,o)=>{let t=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");Be(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?q(process.cwd(),e):q(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=q(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),d=c("tar",a,{stdio:"inherit"});d.status!==0&&(console.log(m.red(` tar exited with ${d.status}`)),process.exit(d.status||1));let{statSync:g}=await import("fs"),l=Be(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${mp(l)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});ee.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-L4D2BOGY.js"),{askSeat:a}=await import("./seat-XB4EGUKJ.js"),{QuestionStore:c}=await import("./questions-4B4KSPXG.js"),d=ke(e.dir,e.mode),g=[],l=e.agent?[e.agent]:d.listAgents(),p=parseInt(e.limit),f=0,u=[];e:for(let E of l){let k=d.getAgentWiki(E);for(let N of k.listArticles(E)){if(f>=p)break e;let C=k.readArticle(N.path);if(!C||e.type&&C.meta.type!==e.type)continue;f++;let I=await a(r,n({title:C.meta.title,type:C.meta.type,body:C.content}),o(C.meta.type),{links:[{kind:"article",id:N.path}],features:{agent:E,type:C.meta.type??"?"}});if(!I){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=t(C.meta.type,I.answers);for(let W of s(P,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&W.needsHuman||(e.ask&&W.needsHuman&&g.push({kind:"field",agentId:E,path:N.path,subject:C.meta.title,field:W.field,tier:W.tier,question:`${C.meta.title} (${C.meta.type??"?"}) \u2014 ${W.label}?`}),u.push({tier:W.tier,need:W.field,how:W.needsHuman?m.yellow("ask"):W.sources.join("/"),uncertain:W.uncertain?"?":"",agent:E,article:C.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&g.length>0&&(w=new c(Vt(e.dir)).add(g)),e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],$=E=>String(E).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(E=>Math.max(E.length,...u.map(k=>$(k[E]).length))),v=(E,k)=>String(E)+" ".repeat(Math.max(0,b[k]-$(E).length));console.log(),console.log(m.bold(y.map((E,k)=>v(E,k)).join(" ")));for(let E of u)console.log(y.map((k,N)=>v(E[k],N)).join(" "));let A=u.filter(E=>E.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${u.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${A} can be closed by a lookup; ${u.length-A} need a person.`));let x=u[0]?.tier;if(x&&console.log(m.dim(` Start at ${x} \u2014 ${i[x]}.`)),e.ask&&(console.log(m.cyan(` Queued ${w.added} question(s) for a person (${w.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&w.added>0){let{TIER_RANK:E}=await import("./article-fields-L4D2BOGY.js"),k=E[e.notifyTier]??E.pillar,N=g.filter(C=>(E[C.tier??"furniture"]??9)<=k);if(N.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:C}=await import("./config-SRTXHGSK.js"),I=C(),P=I?.notifications?.destination;if(!P?.channel||!P?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let W=N.slice(0,10).map(B=>`\u2022 ${B.question}`).join(`
412
- `),L=N.length>10?`
413
- \u2026and ${N.length-10} more`:"",H=`${N.length} wiki gap(s) need you (${e.notifyTier}+):
445
+ ${p.length} article(s) below ${l}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});ee.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,o)=>{let{agenticQuery:t}=await import("./query-ZSUBNWOL.js"),n=ve(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let d=n.getAgentWiki(c),g=q(d.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(m.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(m.dim(" Citations:"));for(let c of a.citations){let d=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${d} (${c.path})`))}console.log()}if(o.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(d=>!a.candidates.some(g=>g.path===d.path));console.log(m.dim(` followed: ${c.map(d=>`${d.title}@h${d.hop}`).join(" | ")}`))}console.log()}});ee.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,o)=>{let t=ve(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=await t.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});ee.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let o=ve(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=q(process.cwd(),".agentx/graph");if(!Je(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new uo({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[l,p]of Object.entries(i.entries))r.set(l,p.path);if(r.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,d=0,g=0;for(let l of t){let p=o.getAgentWiki(l),f=p.listArticles(l),u=o.getSharedStore().listEntries(),w=new Map(u.map(x=>[x.id,x])),y=0,k=0,b=0;for(let x of f){if(a++,x.meta.graphPath?.length||!x.meta.sources?.length)continue;y++,c++;let A=new Map;for(let v of x.meta.sources){let $=w.get(v);if(!$)continue;let C=String($.meta?.sender??""),j=s.fingerprint({text:$.content,channel:$.source,sender:C}),T=r.get(j);if(!T?.length)continue;let D=T.join("/"),W=A.get(D);W?W.n++:A.set(D,{path:T,n:1})}if(A.size===0)continue;k++,d++;let S;for(let v of A.values())(!S||v.n>S.n)&&(S=v);S&&(e.dryRun||(p.writeArticle(x.path,{...x.meta,graphPath:S.path},x.content,l),b++,g++))}console.log(` ${m.cyan(l)}: ${m.bold(f.length)} articles \xB7 ${y} eligible \xB7 ${k} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${d} matched (${Math.round(d/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});ee.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let t=ve(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-SRTXHGSK.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(m.red(" No --peer specified and no daemon config found")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(n.length===0){console.log(m.dim(" No mesh peers configured"));return}let s=new Set(t.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(m.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(m.red(` HTTP ${a.status}`));continue}let c=await a.json(),d=c.entries||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${d.length} entries`));let l=0;for(let p of d)s.has(p.id)||(e.dryRun||(t.addEntry({id:p.id,date:p.date,agentId:p.agentId,source:`${p.source}@${g}`,sourceContext:p.sourceContext,content:p.content}),s.add(p.id)),l++);l>0?console.log(m.green(` ${l} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=l;try{let p=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(p.ok){let f=await p.json();for(let u of f.agents||[])u.totalEntries>0&&console.log(m.dim(` ${u.agentId}: ${u.totalEntries} entries, ${u.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});ee.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let o=e.dir||q(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let d=new ys(o,void 0,c),l=d.getAgentWiki(t).rebuildIndex(),p=d.getAgentEntries(t),f=d.getUnabsorbedEntries(t),u=new Set,w=0,y=new Set;for(let b of l.articles){for(let x of b.tags||[])u.add(x);w+=b.tags?.length||0;for(let x of b.sources||[])y.add(x)}let k=new Set(l.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:fi(c),articles:l.articles.length,entries:p.length,unabsorbed:f.length,uniqueTags:u.size,avgTags:l.articles.length>0?(w/l.articles.length).toFixed(1):"0",dirs:k.size,coverage:y.size,articleList:l.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,d]of r){let g=s.map(l=>d(l).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,d)=>{let g=Math.max(...s.map(p=>p[c])),l=s.filter(p=>p[c]===g).map(p=>p.label);g>0&&console.log(m.dim(` Best ${d}: ${l.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});ee.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,o)=>{let t=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");Je(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?q(process.cwd(),e):q(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=q(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),d=c("tar",a,{stdio:"inherit"});d.status!==0&&(console.log(m.red(` tar exited with ${d.status}`)),process.exit(d.status||1));let{statSync:g}=await import("fs"),l=Je(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Kp(l)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});ee.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-L4D2BOGY.js"),{askSeat:a}=await import("./seat-XB4EGUKJ.js"),{QuestionStore:c}=await import("./questions-4B4KSPXG.js"),d=ve(e.dir,e.mode),g=[],l=e.agent?[e.agent]:d.listAgents(),p=parseInt(e.limit),f=0,u=[];e:for(let v of l){let $=d.getAgentWiki(v);for(let C of $.listArticles(v)){if(f>=p)break e;let j=$.readArticle(C.path);if(!j||e.type&&j.meta.type!==e.type)continue;f++;let T=await a(r,n({title:j.meta.title,type:j.meta.type,body:j.content}),o(j.meta.type),{links:[{kind:"article",id:C.path}],features:{agent:v,type:j.meta.type??"?"}});if(!T){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let D=t(j.meta.type,T.answers);for(let W of s(D,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&W.needsHuman||(e.ask&&W.needsHuman&&g.push({kind:"field",agentId:v,path:C.path,subject:j.meta.title,field:W.field,tier:W.tier,question:`${j.meta.title} (${j.meta.type??"?"}) \u2014 ${W.label}?`}),u.push({tier:W.tier,need:W.field,how:W.needsHuman?m.yellow("ask"):W.sources.join("/"),uncertain:W.uncertain?"?":"",agent:v,article:j.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&g.length>0&&(w=new c(on(e.dir)).add(g)),e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],k=v=>String(v).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(v=>Math.max(v.length,...u.map($=>k($[v]).length))),x=(v,$)=>String(v)+" ".repeat(Math.max(0,b[$]-k(v).length));console.log(),console.log(m.bold(y.map((v,$)=>x(v,$)).join(" ")));for(let v of u)console.log(y.map(($,C)=>x(v[$],C)).join(" "));let A=u.filter(v=>v.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${u.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${A} can be closed by a lookup; ${u.length-A} need a person.`));let S=u[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${i[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${w.added} question(s) for a person (${w.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&w.added>0){let{TIER_RANK:v}=await import("./article-fields-L4D2BOGY.js"),$=v[e.notifyTier]??v.pillar,C=g.filter(j=>(v[j.tier??"furniture"]??9)<=$);if(C.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:j}=await import("./config-SRTXHGSK.js"),T=j(),D=T?.notifications?.destination;if(!D?.channel||!D?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let W=C.slice(0,10).map(B=>`\u2022 ${B.question}`).join(`
446
+ `),L=C.length>10?`
447
+ \u2026and ${C.length-10} more`:"",G=`${C.length} wiki gap(s) need you (${e.notifyTier}+):
414
448
  ${W}${L}
415
449
 
416
- agentx wiki questions`,ae=I?.daemon?.port??I?.port??18800;try{let B=await fetch(`http://127.0.0.1:${ae}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:H})});console.log(B.ok?m.cyan(` Pushed ${N.length} question(s) to ${P.channel}.`):m.yellow(` Push failed (${B.status}) \u2014 questions are still queued.`))}catch(B){console.log(m.yellow(` Push failed (${String(B?.message??B).slice(0,80)}) \u2014 questions are still queued.`))}}}}});ee.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-L4D2BOGY.js"),{askSeat:r}=await import("./seat-XB4EGUKJ.js"),{resolveFacts:a,mergeRecords:c,installPrompts:d,defaultSources:g,recordsFromEntries:l}=await import("./facts-YVEJOM7O.js"),{backfillArticle:p}=await import("./backfill-MTD2B62I.js"),f=ke(e.dir,e.mode),u=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=g(),$=c(l(f.getSharedStore().listEntries())),b=new Map($.map(I=>[I.name.toLowerCase().trim(),I])),v=0,A=0,x=[],E=!1;e:for(let I of u){let P=f.getAgentWiki(I);for(let W of P.listArticles(I)){if(v>=w)break e;if(W.meta.type!=="person")continue;let L=P.readArticle(W.path);if(!L)continue;v++;let H=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),o(L.meta.type),{links:[{kind:"article",id:W.path}],features:{agent:I,op:"backfill"}});if(!H){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let B=t(L.meta.type,H.answers).missing.filter(T=>i.includes(T));if(B.length===0)continue;let{records:ve,results:he}=await a([{name:L.meta.title,type:"person"}],{sources:y}),_=b.get(L.meta.title.toLowerCase().trim());if(!E){for(let T of d(he,y))console.log(m.yellow(` ! ${T.source} ${T.kind} \u2014 would supply ${T.provides.join(", ")}`)),console.log(m.dim(` ${T.hint}`));E=!0}let qe=c([..._?[{name:_.name,source:"entries",fields:Object.fromEntries(Object.entries(_.fields).map(([T,me])=>[T,me.value]))}]:[],...ve]);if(qe.length===0)continue;let{content:ye,edits:Io}=p(L.content,qe[0],B);if(Io.length!==0){for(let T of Io)x.push({agent:I,article:L.meta.title.slice(0,32),field:T.field,action:T.replaced?"replace":"add",got:`${T.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(W.path,L.meta,ye,I)?A++:console.log(m.red(` could not write ${W.path}`)))}}}if(e.json){console.log(JSON.stringify(x,null,2));return}if(x.length===0){console.log(m.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let k=["agent","article","field","action","got"],N=k.map(I=>Math.max(I.length,...x.map(P=>String(P[I]).length))),C=I=>I.map((P,W)=>String(P).padEnd(N[W])).join(" ");console.log(),console.log(m.bold(C(k)));for(let I of x)console.log(C(k.map(P=>I[P])));console.log(),e.apply?(console.log(m.green(` ${x.length} field(s) written across ${A} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${x.length} field(s) would be written across ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});ee.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:o}=await import("./questions-4B4KSPXG.js"),{TIER_RANK:t}=await import("./article-fields-L4D2BOGY.js"),n=new o(Vt(e.dir)).list(e.status);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(m.green(` no ${e.status} questions`));return}n.sort((s,i)=>(t[s.tier??"furniture"]??9)-(t[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});ee.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,o,t)=>{let{QuestionStore:n}=await import("./questions-4B4KSPXG.js"),{patchIdentityField:s}=await import("./backfill-MTD2B62I.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-L4D2BOGY.js"),r=new n(Vt(t.dir));if(t.dismiss){let f=r.resolve(e,"dismissed");console.log(f?m.dim(` dismissed: ${f.question}`):m.red(` no question matching "${e}"`));return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let a=r.resolve(e,"answered",o);if(!a){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${a.question}`)),a.kind!=="field"||!a.field||!a.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[a.field]){console.log(m.dim(` recorded against ${a.path}. "${a.field}" has no fixed slot, so nothing was rewritten.`));return}let d=ke(t.dir,t.mode).getAgentWiki(a.agentId),g=d.readArticle(a.path);if(!g){console.log(m.yellow(` article gone: ${a.path}`));return}let l=s(g.content,a.field,`${o} (answered by operator)`);if(!l){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=d.writeArticle(a.path,g.meta,l.content,a.agentId);console.log(p?m.green(` wrote ${a.field} into ${a.path} (prior version kept)`):m.red(` could not write ${a.path}`))});ee.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:o,entryTriageQuestions:t,triageState:n,triage:s}=await import("./entry-triage-LK34TSQD.js"),{askSeat:i}=await import("./seat-XB4EGUKJ.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:d,sweepPolicies:g}=await import("./triage-backtest-JNO7RKX7.js"),{calibrationReport:l}=await import("./calibration-ILS5OI44.js"),f=ke(e.dir,"graph").getSharedStore(),u=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:y,backlog:$}=r(u,w),b=a(y,L=>L.absorbed,parseInt(e.n)),v={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},A=[],x=0,E=Date.now();if(e.load){let{readFileSync:L}=await import("fs");A.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${$} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let H=await i(o,n(L),t,{features:{source:L.source??"",absorbed:L.absorbed}});if(!H){x++;continue}let ae=H.answers;A.push({entry:L,verdict:s(H.answers,v),citeWorthy:ae.citeWorthy?.noul})}if(A.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let k=c(A,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),N=d(A,"seat","seat"),C=l(N,{minN:50}),I=((Date.now()-E)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:k,calibration:C,failures:x,elapsed:I},null,2));return}let P=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${k.n} (${k.positives} kept by absorb, ${k.negatives} passed over)`),console.log(` recall ${P(k.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P(k.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P(k.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${k.lostPositives>0?m.yellow(`lost ${k.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in C)||!C.insufficient)&&console.log(` ECE ${C.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),k.lostPositives>0){let L=k.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let W=k.positiveMeans;if(console.log(m.dim(` positives avg: worth ${W.worth.toFixed(2)} \xB7 durability ${W.durability.toFixed(2)} \xB7 typeConf ${W.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${I}s, ${x} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let L=parseFloat(e.minRecall),{best:H,points:ae}=g(A,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${ae.length} policies, recall floor ${P(L)})`)),H)console.log(` best: ${H.requireTyped?`typed & type>=${H.minType}`:"type gate OFF"} worth>=${H.minWorth} durability>=${H.minDurability}`),console.log(` recall ${P(H.recall)} \xB7 filtered ${P(H.filtered)} \xB7 precision ${P(H.precision)} \xB7 lost ${H.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${P(L)} recall \u2014 not even keeping everything typed.`));let B=ae.slice().sort((ve,he)=>he.recall-ve.recall)[0];B&&console.log(m.dim(` Best recall available: ${P(B.recall)} at ${B.requireTyped?`type>=${B.minType}`:"type gate OFF"} worth>=${B.minWorth} dur>=${B.minDurability}, filtering ${P(B.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});ee.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,o)=>{let t=q(process.cwd(),e);Be(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");Be(n)&&!o.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=q(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function mp(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}vl();import{Command as pp}from"commander";import R from"chalk";import{resolve as Wn}from"path";import{existsSync as up}from"fs";we();var pt=new pp().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");pt.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let o=D();if(!o.graph?.enabled){console.log(R.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(R.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(R.red(` agent "${t}" not in config`));return}let n=(e.daemonUrl||o.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new mo({baseDir:Wn(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(R.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(R.bold(` Graph review \u2014 ${r.length} pending`)),console.log(R.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let d=0,g=0,l=0,p=0;for(let u=0;u<r.length;u++){let w=r[u],y=sn(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${u+1}/${r.length}] ${R.cyan(w.msgHash.slice(0,8))} ${R.dim(y)} ... `);let $=fp(w,a,c),b=null;try{b=await hp(n,t,$,o.dashboard?.token)}catch(x){p++,console.log(R.red(`ERR ${x.message?.slice(0,80)}`));continue}if(!b||!b.decision){p++,console.log(R.red("ERR no decision"));continue}let v=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(R.green("APPROVE")+" "+R.dim(A)),e.dryRun)d++;else try{yp(i,w,a,c,t),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:t,reviewReason:A}),d++}catch(x){console.log(R.yellow(` (commit failed, staying pending: ${x.message?.slice(0,100)})`)),p++}else v==="reject"?(console.log(R.red("REJECT")+" "+R.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:t,reviewReason:A}),g++):(console.log(R.yellow("SKIP")+" "+R.dim(A||v)),l++)}console.log();let f=e.dryRun?"would":"did";console.log(R.dim(` Summary: ${f} approve ${d}, ${f} reject ${g}, ${l} skipped, ${p} errors.`)),e.dryRun&&(d>0||g>0)&&console.log(R.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});pt.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let o=D();if(!o.graph){console.log(R.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=Wn(process.cwd(),o.graph.baseDir);if(!up(t)){console.log(R.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-V4WN2VVM.js"),s=new mo({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(R.dim(" "),...a)});console.log(),console.log(R.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(R.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(R.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(R.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});pt.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let o=D();if(!o.graph?.enabled){console.log(R.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let t=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new mo({baseDir:Wn(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(k=>k.id));console.log(),console.log(R.bold(` graph pull \u2190 ${t}`));let d,g,l;try{let k=await fetch(`${t}/graph/schema`,{headers:s});if(!k.ok)throw new Error(`schema HTTP ${k.status}`);d=(await k.json()).schema;let C=await fetch(`${t}/graph/nodes`,{headers:s});if(!C.ok)throw new Error(`nodes HTTP ${C.status}`);g=(await C.json()).nodes||[];let I=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!I.ok)throw new Error(`classifications HTTP ${I.status}`);l=(await I.json()).classifications||[]}catch(k){console.log(R.red(` fetch failed: ${k.message}`));return}let p=r.levels.map(k=>k.id).join(","),f=d?.levels?.map(k=>k.id).join(","),u=p===f;u?console.log(R.dim(` schema matches (${r.levels.length} levels)`)):(console.log(R.yellow(" \u26A0 schema levels differ:")),console.log(R.dim(` local: ${p}`)),console.log(R.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(R.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(d)):console.log(R.yellow(" keeping local schema; node import may fail if levels disagree")));let w=u?r:d,y=new Map;w.levels.forEach((k,N)=>y.set(k.id,N));let $=[...g].sort((k,N)=>(y.get(k.level)??99)-(y.get(N.level)??99)),b=0,v=0,A=0;for(let k of $){if(c.has(k.id)){v++;continue}if(e.dryRun){b++,c.add(k.id);continue}try{i.addNode({...k,createdBy:k.createdBy?`${k.createdBy} (sync)`:`sync:${t}`}),c.add(k.id),b++}catch(N){A++,console.log(R.yellow(` skip node ${k.id}: ${N.message?.slice(0,100)}`))}}console.log(R.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${A} failed`));let x=0,E=0;for(let k of l)if(!(!k.msgHash||!Array.isArray(k.path))){if(i.getFingerprint(k.msgHash)){E++;continue}if(e.dryRun){x++;continue}i.setFingerprint(k.msgHash,{path:k.path,leaf:k.leaf||{}}),x++}console.log(R.dim(` fingerprints: +${x} cached \xB7 ${E} already-present`)),console.log(),e.dryRun?console.log(R.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(R.green(` \u2713 pulled from ${t}`)),console.log()});function fp(e,o,t){let n={};for(let r of t)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=o.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
450
+ agentx wiki questions`,ae=T?.daemon?.port??T?.port??18800;try{let B=await fetch(`http://127.0.0.1:${ae}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:D.channel,chatId:D.chatId,accountId:D.accountId,text:G})});console.log(B.ok?m.cyan(` Pushed ${C.length} question(s) to ${D.channel}.`):m.yellow(` Push failed (${B.status}) \u2014 questions are still queued.`))}catch(B){console.log(m.yellow(` Push failed (${String(B?.message??B).slice(0,80)}) \u2014 questions are still queued.`))}}}}});ee.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-L4D2BOGY.js"),{askSeat:r}=await import("./seat-XB4EGUKJ.js"),{resolveFacts:a,mergeRecords:c,installPrompts:d,defaultSources:g,recordsFromEntries:l}=await import("./facts-YVEJOM7O.js"),{backfillArticle:p}=await import("./backfill-MTD2B62I.js"),f=ve(e.dir,e.mode),u=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=g(),k=c(l(f.getSharedStore().listEntries())),b=new Map(k.map(T=>[T.name.toLowerCase().trim(),T])),x=0,A=0,S=[],v=!1;e:for(let T of u){let D=f.getAgentWiki(T);for(let W of D.listArticles(T)){if(x>=w)break e;if(W.meta.type!=="person")continue;let L=D.readArticle(W.path);if(!L)continue;x++;let G=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),o(L.meta.type),{links:[{kind:"article",id:W.path}],features:{agent:T,op:"backfill"}});if(!G){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let B=t(L.meta.type,G.answers).missing.filter(N=>i.includes(N));if(B.length===0)continue;let{records:xe,results:ye}=await a([{name:L.meta.title,type:"person"}],{sources:y}),P=b.get(L.meta.title.toLowerCase().trim());if(!v){for(let N of d(ye,y))console.log(m.yellow(` ! ${N.source} ${N.kind} \u2014 would supply ${N.provides.join(", ")}`)),console.log(m.dim(` ${N.hint}`));v=!0}let qe=c([...P?[{name:P.name,source:"entries",fields:Object.fromEntries(Object.entries(P.fields).map(([N,me])=>[N,me.value]))}]:[],...xe]);if(qe.length===0)continue;let{content:we,edits:Co}=p(L.content,qe[0],B);if(Co.length!==0){for(let N of Co)S.push({agent:T,article:L.meta.title.slice(0,32),field:N.field,action:N.replaced?"replace":"add",got:`${N.value.split(";").length} value(s)`});e.apply&&(D.writeArticle(W.path,L.meta,we,T)?A++:console.log(m.red(` could not write ${W.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${x} person article(s) considered \u2014 nothing to backfill`));return}let $=["agent","article","field","action","got"],C=$.map(T=>Math.max(T.length,...S.map(D=>String(D[T]).length))),j=T=>T.map((D,W)=>String(D).padEnd(C[W])).join(" ");console.log(),console.log(m.bold(j($)));for(let T of S)console.log(j($.map(D=>T[D])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${A} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${x} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});ee.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:o}=await import("./questions-4B4KSPXG.js"),{TIER_RANK:t}=await import("./article-fields-L4D2BOGY.js"),n=new o(on(e.dir)).list(e.status);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(m.green(` no ${e.status} questions`));return}n.sort((s,i)=>(t[s.tier??"furniture"]??9)-(t[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});ee.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,o,t)=>{let{QuestionStore:n}=await import("./questions-4B4KSPXG.js"),{patchIdentityField:s}=await import("./backfill-MTD2B62I.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-L4D2BOGY.js"),r=new n(on(t.dir));if(t.dismiss){let f=r.resolve(e,"dismissed");console.log(f?m.dim(` dismissed: ${f.question}`):m.red(` no question matching "${e}"`));return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let a=r.resolve(e,"answered",o);if(!a){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${a.question}`)),a.kind!=="field"||!a.field||!a.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[a.field]){console.log(m.dim(` recorded against ${a.path}. "${a.field}" has no fixed slot, so nothing was rewritten.`));return}let d=ve(t.dir,t.mode).getAgentWiki(a.agentId),g=d.readArticle(a.path);if(!g){console.log(m.yellow(` article gone: ${a.path}`));return}let l=s(g.content,a.field,`${o} (answered by operator)`);if(!l){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=d.writeArticle(a.path,g.meta,l.content,a.agentId);console.log(p?m.green(` wrote ${a.field} into ${a.path} (prior version kept)`):m.red(` could not write ${a.path}`))});ee.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:o,entryTriageQuestions:t,triageState:n,triage:s}=await import("./entry-triage-LK34TSQD.js"),{askSeat:i}=await import("./seat-XB4EGUKJ.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:d,sweepPolicies:g}=await import("./triage-backtest-JNO7RKX7.js"),{calibrationReport:l}=await import("./calibration-ILS5OI44.js"),f=ve(e.dir,"graph").getSharedStore(),u=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:y,backlog:k}=r(u,w),b=a(y,L=>L.absorbed,parseInt(e.n)),x={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},A=[],S=0,v=Date.now();if(e.load){let{readFileSync:L}=await import("fs");A.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${k} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let G=await i(o,n(L),t,{features:{source:L.source??"",absorbed:L.absorbed}});if(!G){S++;continue}let ae=G.answers;A.push({entry:L,verdict:s(G.answers,x),citeWorthy:ae.citeWorthy?.noul})}if(A.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let $=c(A,{minType:x.minTypeConfidence,minWorth:x.minWorth,minDurability:x.minDurability}),C=d(A,"seat","seat"),j=l(C,{minN:50}),T=((Date.now()-v)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:$,calibration:j,failures:S,elapsed:T},null,2));return}let D=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${$.n} (${$.positives} kept by absorb, ${$.negatives} passed over)`),console.log(` recall ${D($.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${D($.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${D($.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${$.lostPositives>0?m.yellow(`lost ${$.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in j)||!j.insufficient)&&console.log(` ECE ${j.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),$.lostPositives>0){let L=$.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let W=$.positiveMeans;if(console.log(m.dim(` positives avg: worth ${W.worth.toFixed(2)} \xB7 durability ${W.durability.toFixed(2)} \xB7 typeConf ${W.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${T}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let L=parseFloat(e.minRecall),{best:G,points:ae}=g(A,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${ae.length} policies, recall floor ${D(L)})`)),G)console.log(` best: ${G.requireTyped?`typed & type>=${G.minType}`:"type gate OFF"} worth>=${G.minWorth} durability>=${G.minDurability}`),console.log(` recall ${D(G.recall)} \xB7 filtered ${D(G.filtered)} \xB7 precision ${D(G.precision)} \xB7 lost ${G.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${D(L)} recall \u2014 not even keeping everything typed.`));let B=ae.slice().sort((xe,ye)=>ye.recall-xe.recall)[0];B&&console.log(m.dim(` Best recall available: ${D(B.recall)} at ${B.requireTyped?`type>=${B.minType}`:"type gate OFF"} worth>=${B.minWorth} dur>=${B.minDurability}, filtering ${D(B.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});ee.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,o)=>{let t=q(process.cwd(),e);Je(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");Je(n)&&!o.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=q(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function Kp(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}ql();import{Command as Xp}from"commander";import R from"chalk";import{resolve as Zn}from"path";import{existsSync as Qp}from"fs";pe();var yt=new Xp().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");yt.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let o=_();if(!o.graph?.enabled){console.log(R.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(R.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(R.red(` agent "${t}" not in config`));return}let n=(e.daemonUrl||o.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new uo({baseDir:Zn(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(R.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(R.bold(` Graph review \u2014 ${r.length} pending`)),console.log(R.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let d=0,g=0,l=0,p=0;for(let u=0;u<r.length;u++){let w=r[u],y=gn(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${u+1}/${r.length}] ${R.cyan(w.msgHash.slice(0,8))} ${R.dim(y)} ... `);let k=Zp(w,a,c),b=null;try{b=await eu(n,t,k,o.dashboard?.token)}catch(S){p++,console.log(R.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){p++,console.log(R.red("ERR no decision"));continue}let x=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(x==="approve")if(console.log(R.green("APPROVE")+" "+R.dim(A)),e.dryRun)d++;else try{ou(i,w,a,c,t),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:t,reviewReason:A}),d++}catch(S){console.log(R.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),p++}else x==="reject"?(console.log(R.red("REJECT")+" "+R.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:t,reviewReason:A}),g++):(console.log(R.yellow("SKIP")+" "+R.dim(A||x)),l++)}console.log();let f=e.dryRun?"would":"did";console.log(R.dim(` Summary: ${f} approve ${d}, ${f} reject ${g}, ${l} skipped, ${p} errors.`)),e.dryRun&&(d>0||g>0)&&console.log(R.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});yt.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let o=_();if(!o.graph){console.log(R.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=Zn(process.cwd(),o.graph.baseDir);if(!Qp(t)){console.log(R.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-V4WN2VVM.js"),s=new uo({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(R.dim(" "),...a)});console.log(),console.log(R.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(R.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(R.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(R.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});yt.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let o=_();if(!o.graph?.enabled){console.log(R.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let t=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new uo({baseDir:Zn(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map($=>$.id));console.log(),console.log(R.bold(` graph pull \u2190 ${t}`));let d,g,l;try{let $=await fetch(`${t}/graph/schema`,{headers:s});if(!$.ok)throw new Error(`schema HTTP ${$.status}`);d=(await $.json()).schema;let j=await fetch(`${t}/graph/nodes`,{headers:s});if(!j.ok)throw new Error(`nodes HTTP ${j.status}`);g=(await j.json()).nodes||[];let T=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!T.ok)throw new Error(`classifications HTTP ${T.status}`);l=(await T.json()).classifications||[]}catch($){console.log(R.red(` fetch failed: ${$.message}`));return}let p=r.levels.map($=>$.id).join(","),f=d?.levels?.map($=>$.id).join(","),u=p===f;u?console.log(R.dim(` schema matches (${r.levels.length} levels)`)):(console.log(R.yellow(" \u26A0 schema levels differ:")),console.log(R.dim(` local: ${p}`)),console.log(R.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(R.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(d)):console.log(R.yellow(" keeping local schema; node import may fail if levels disagree")));let w=u?r:d,y=new Map;w.levels.forEach(($,C)=>y.set($.id,C));let k=[...g].sort(($,C)=>(y.get($.level)??99)-(y.get(C.level)??99)),b=0,x=0,A=0;for(let $ of k){if(c.has($.id)){x++;continue}if(e.dryRun){b++,c.add($.id);continue}try{i.addNode({...$,createdBy:$.createdBy?`${$.createdBy} (sync)`:`sync:${t}`}),c.add($.id),b++}catch(C){A++,console.log(R.yellow(` skip node ${$.id}: ${C.message?.slice(0,100)}`))}}console.log(R.dim(` nodes: +${b} added \xB7 ${x} already-present \xB7 ${A} failed`));let S=0,v=0;for(let $ of l)if(!(!$.msgHash||!Array.isArray($.path))){if(i.getFingerprint($.msgHash)){v++;continue}if(e.dryRun){S++;continue}i.setFingerprint($.msgHash,{path:$.path,leaf:$.leaf||{}}),S++}console.log(R.dim(` fingerprints: +${S} cached \xB7 ${v} already-present`)),console.log(),e.dryRun?console.log(R.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(R.green(` \u2713 pulled from ${t}`)),console.log()});function Zp(e,o,t){let n={};for(let r of t)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=o.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
417
451
  `),i=JSON.stringify(e.proposedAxes||{},null,2);return["You are reviewing a pending intent classification. Decide whether it is reasonable.","","--- MESSAGE (first 500 chars) ---",(e.preview||"").slice(0,500),`channel: ${e.channel||"?"} \xB7 sender: ${e.sender||"?"}`,"","--- PROPOSED PATH ---",e.path.join(" \u203A "),"","--- PROPOSED AXES (per new node) ---",i,"","--- CURRENT NODES BY LEVEL (first 10 per level) ---",s,"","--- YOUR JOB ---","Decide one of:"," approve \u2014 the path is right and the axes make sense for the message"," reject \u2014 the path is wrong (e.g. the message is NOT about the proposed org/topic, or the axes are bogus)"," skip \u2014 you can't confidently decide; leave it for a human","",'BEFORE you decide, you MAY call `agentx wiki query` (via Bash) to check institutional context \u2014 e.g. "is there an article for this project" or "who is this person". This is optional; don\'t call it for obvious cases.',"","Bias toward reject over approve when uncertain. A wrong approval pollutes the graph; a wrong rejection just keeps the entry pending.","","Return EXACTLY one JSON object on one line, no prose, no fences:",' {"decision":"approve"|"reject"|"skip","reason":"one sentence"}'].join(`
418
- `)}async function hp(e,o,t,n){let s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);let i=new AbortController,r=setTimeout(()=>i.abort(),12e4);try{let a=await fetch(`${e}/task`,{method:"POST",headers:s,body:JSON.stringify({agent:o,message:t,context:{channel:"a2a",sender:"graph-review"}}),signal:i.signal});if(!a.ok)throw new Error(`daemon /task HTTP ${a.status}`);let c=await a.json();if(c?.error)throw new Error(String(c.error));return Ni((c?.content||"").toString())}finally{clearTimeout(r)}}function yp(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function si(){let e=D();if(!e.graph?.baseDir)return console.log(R.red(" graph.baseDir is not configured")),null;let o=Wn(process.cwd(),e.graph.baseDir);return{store:new mo({baseDir:o}),baseDir:o}}var ii=pt.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");ii.command("next").alias("list").description("what to check next, spread across the confidence range").option("--n <n>","how many","10").option("--strategy <s>","stratified | uncertain","stratified").option("--json").action(async e=>{let o=si();if(!o)return;let{ReviewStore:t,buildQueue:n}=await import("./review-store-B4YE3EFK.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,new Set(i.keys()),{n:parseInt(e.n),strategy:e.strategy});if(e.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(R.green(" nothing left unreviewed"));return}let a=o.store.loadNodes().nodes;console.log();for(let c of r){let d=typeof c.confidence=="number"?c.confidence.toFixed(2):R.dim("cache");console.log(` ${R.cyan(c.msgHash.slice(0,8))} ${d.padStart(5)} ${R.bold(sn(c.path,a)||c.path.join(" \u203A "))}`),c.preview&&console.log(R.dim(` ${String(c.preview).replace(/\s+/g," ").slice(0,96)}`))}console.log(),console.log(R.dim(` ${r.length} to check (${e.strategy}).`)),console.log(R.dim(" agentx graph label mark <hash> correct|wrong|unsure [--path a/b/c]"))});ii.command("mark <hash> <verdict>").description("record a verdict: correct | wrong | unsure").option("--path <p>","for `wrong`: the path it should have been, slash-separated").option("--note <t>","why, when it is worth remembering").option("--by <who>","reviewer","operator").action(async(e,o,t)=>{if(!["correct","wrong","unsure"].includes(o)){console.log(R.red(" verdict must be correct | wrong | unsure"));return}let n=si();if(!n)return;let{ReviewStore:s}=await import("./review-store-B4YE3EFK.js"),r=n.store.listAllClassifications().filter(d=>d.msgHash===e||d.msgHash.startsWith(e));if(r.length===0){console.log(R.red(` no classification matching "${e}"`));return}if(r.length>1){console.log(R.red(` "${e}" matches ${r.length} rows \u2014 use more characters`));return}new s(n.baseDir).record({msgHash:r[0].msgHash,verdict:o,correctPath:t.path?String(t.path).split("/").filter(Boolean):void 0,note:t.note,reviewer:t.by});let c=n.store.loadNodes().nodes;console.log(R.green(` ${o}: ${sn(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(R.dim(` should have been: ${t.path}`))});ii.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=si();if(!o)return;let{ReviewStore:t,labelStats:n}=await import("./review-store-B4YE3EFK.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,i);if(e.json){console.log(JSON.stringify(r,null,2));return}let a=c=>`${(c*100).toFixed(1)}%`;if(console.log(),console.log(` classifications ${r.classifications}`),console.log(` reviewed ${r.reviewed} (${r.correct} correct \xB7 ${r.wrong} wrong \xB7 ${r.unsure} unsure)`),r.correct+r.wrong>0&&console.log(` accuracy ${a(r.accuracy)}`),console.log(` calibratable ${r.calibratable} ${R.dim("reviewed rows that carry a confidence")}`),r.byBin.length>0){console.log(),console.log(R.bold(" reliability \u2014 confidence vs how often it was right"));for(let c of r.byBin){let d=Math.abs(parseFloat(c.bin.split("-")[0])+.05-c.accuracy),g=c.n>=5&&d>.15?R.yellow(" \u2190 miscalibrated"):"";console.log(` ${c.bin} n=${String(c.n).padStart(3)} right ${a(c.accuracy).padStart(6)}${g}`)}}console.log(),r.calibratable<100?console.log(R.dim(` ${100-r.calibratable} more labelled rows before a calibration report means anything.`)):console.log(R.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as xp}from"commander";import Y from"chalk";import{Command as jc}from"commander";import se from"chalk";import{existsSync as wp}from"fs";import{resolve as bp}from"path";import $p from"better-sqlite3";function kp(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(o){let n=Number(o[1]),s=o[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(se.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function vp(e){let o=bp(process.cwd(),e);return wp(o)||(console.log(se.red(` No db at ${o}`)),process.exit(1)),new $p(o,{readonly:!0})}var Ic=new jc().name("extract").description("mine recurring user activity into procedure drafts (dry-run by default)").option("--path <path>","SQLite db path",".agentx/db.sqlite").option("--since <duration>","activity window, e.g. 24h, 7d, or ms epoch","7d").option("--agent <id>","only mine one agent's activity").option("--min-occurrences <n>","recurrences before a pattern becomes a draft",String(Ot)).option("--max <n>","max clusters distilled per run",String(cn)).option("--via <agentId>","route the LLM call through a running agent \u2014 uses the agent's own session").option("--model <model>","direct Anthropic API model \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--commit","write drafts and persist recurrence counts",!1).action(async e=>{e.commit&&!e.via&&!e.model&&(console.log(se.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=vp(e.path),t=await ir(o,{since:kp(e.since),agentId:e.agent,sessions:new Mi(process.cwd()),minOccurrences:Number(e.minOccurrences)||Ot,max:Number(e.max)||cn,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(se.dim(` ${n}`))});console.log(),console.log(` ${t.episodes} episode(s) \u2192 ${t.clusters} cluster(s), ${t.ready.length} at threshold`);for(let n of t.ready)console.log(` ${se.cyan(n.key)} ${se.bold(`\xD7${n.count}`)} ${se.dim(n.status)}`),n.sampleMessage&&console.log(se.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(se.dim(`
452
+ `)}async function eu(e,o,t,n){let s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);let i=new AbortController,r=setTimeout(()=>i.abort(),12e4);try{let a=await fetch(`${e}/task`,{method:"POST",headers:s,body:JSON.stringify({agent:o,message:t,context:{channel:"a2a",sender:"graph-review"}}),signal:i.signal});if(!a.ok)throw new Error(`daemon /task HTTP ${a.status}`);let c=await a.json();if(c?.error)throw new Error(String(c.error));return Ji((c?.content||"").toString())}finally{clearTimeout(r)}}function ou(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function hi(){let e=_();if(!e.graph?.baseDir)return console.log(R.red(" graph.baseDir is not configured")),null;let o=Zn(process.cwd(),e.graph.baseDir);return{store:new uo({baseDir:o}),baseDir:o}}var yi=yt.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");yi.command("next").alias("list").description("what to check next, spread across the confidence range").option("--n <n>","how many","10").option("--strategy <s>","stratified | uncertain","stratified").option("--json").action(async e=>{let o=hi();if(!o)return;let{ReviewStore:t,buildQueue:n}=await import("./review-store-B4YE3EFK.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,new Set(i.keys()),{n:parseInt(e.n),strategy:e.strategy});if(e.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(R.green(" nothing left unreviewed"));return}let a=o.store.loadNodes().nodes;console.log();for(let c of r){let d=typeof c.confidence=="number"?c.confidence.toFixed(2):R.dim("cache");console.log(` ${R.cyan(c.msgHash.slice(0,8))} ${d.padStart(5)} ${R.bold(gn(c.path,a)||c.path.join(" \u203A "))}`),c.preview&&console.log(R.dim(` ${String(c.preview).replace(/\s+/g," ").slice(0,96)}`))}console.log(),console.log(R.dim(` ${r.length} to check (${e.strategy}).`)),console.log(R.dim(" agentx graph label mark <hash> correct|wrong|unsure [--path a/b/c]"))});yi.command("mark <hash> <verdict>").description("record a verdict: correct | wrong | unsure").option("--path <p>","for `wrong`: the path it should have been, slash-separated").option("--note <t>","why, when it is worth remembering").option("--by <who>","reviewer","operator").action(async(e,o,t)=>{if(!["correct","wrong","unsure"].includes(o)){console.log(R.red(" verdict must be correct | wrong | unsure"));return}let n=hi();if(!n)return;let{ReviewStore:s}=await import("./review-store-B4YE3EFK.js"),r=n.store.listAllClassifications().filter(d=>d.msgHash===e||d.msgHash.startsWith(e));if(r.length===0){console.log(R.red(` no classification matching "${e}"`));return}if(r.length>1){console.log(R.red(` "${e}" matches ${r.length} rows \u2014 use more characters`));return}new s(n.baseDir).record({msgHash:r[0].msgHash,verdict:o,correctPath:t.path?String(t.path).split("/").filter(Boolean):void 0,note:t.note,reviewer:t.by});let c=n.store.loadNodes().nodes;console.log(R.green(` ${o}: ${gn(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(R.dim(` should have been: ${t.path}`))});yi.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=hi();if(!o)return;let{ReviewStore:t,labelStats:n}=await import("./review-store-B4YE3EFK.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,i);if(e.json){console.log(JSON.stringify(r,null,2));return}let a=c=>`${(c*100).toFixed(1)}%`;if(console.log(),console.log(` classifications ${r.classifications}`),console.log(` reviewed ${r.reviewed} (${r.correct} correct \xB7 ${r.wrong} wrong \xB7 ${r.unsure} unsure)`),r.correct+r.wrong>0&&console.log(` accuracy ${a(r.accuracy)}`),console.log(` calibratable ${r.calibratable} ${R.dim("reviewed rows that carry a confidence")}`),r.byBin.length>0){console.log(),console.log(R.bold(" reliability \u2014 confidence vs how often it was right"));for(let c of r.byBin){let d=Math.abs(parseFloat(c.bin.split("-")[0])+.05-c.accuracy),g=c.n>=5&&d>.15?R.yellow(" \u2190 miscalibrated"):"";console.log(` ${c.bin} n=${String(c.n).padStart(3)} right ${a(c.accuracy).padStart(6)}${g}`)}}console.log(),r.calibratable<100?console.log(R.dim(` ${100-r.calibratable} more labelled rows before a calibration report means anything.`)):console.log(R.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as au}from"commander";import Y from"chalk";import{Command as zc}from"commander";import se from"chalk";import{existsSync as tu}from"fs";import{resolve as nu}from"path";import su from"better-sqlite3";function iu(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(o){let n=Number(o[1]),s=o[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(se.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function ru(e){let o=nu(process.cwd(),e);return tu(o)||(console.log(se.red(` No db at ${o}`)),process.exit(1)),new su(o,{readonly:!0})}var Yc=new zc().name("extract").description("mine recurring user activity into procedure drafts (dry-run by default)").option("--path <path>","SQLite db path",".agentx/db.sqlite").option("--since <duration>","activity window, e.g. 24h, 7d, or ms epoch","7d").option("--agent <id>","only mine one agent's activity").option("--min-occurrences <n>","recurrences before a pattern becomes a draft",String(Ct)).option("--max <n>","max clusters distilled per run",String(un)).option("--via <agentId>","route the LLM call through a running agent \u2014 uses the agent's own session").option("--model <model>","direct Anthropic API model \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--commit","write drafts and persist recurrence counts",!1).action(async e=>{e.commit&&!e.via&&!e.model&&(console.log(se.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=ru(e.path),t=await yr(o,{since:iu(e.since),agentId:e.agent,sessions:new Ki(process.cwd()),minOccurrences:Number(e.minOccurrences)||Ct,max:Number(e.max)||un,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(se.dim(` ${n}`))});console.log(),console.log(` ${t.episodes} episode(s) \u2192 ${t.clusters} cluster(s), ${t.ready.length} at threshold`);for(let n of t.ready)console.log(` ${se.cyan(n.key)} ${se.bold(`\xD7${n.count}`)} ${se.dim(n.status)}`),n.sampleMessage&&console.log(se.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(se.dim(`
419
453
  near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(se.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(se.green(` \u2713 draft written: ${n.id}`)+se.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(se.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(se.yellow(` \u26A0 ${n}`));t.dryRun?console.log(se.dim(`
420
454
  dry run only; pass --commit --via <agentId> to write drafts`)):t.drafted.length&&console.log(se.dim(`
421
- review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),Oc={hourly:"0 * * * *",daily:"0 3 * * *"},Cc=new jc().name("watch").description("set the extraction cadence: registers the cron + config the daemon runs on").option("--hourly","extract every hour").option("--daily","extract daily at 03:00").option("--cron <expr>","custom 5-field cron expression").option("--on-task","also count patterns live after each completed task").option("--off","disable scheduled extraction").option("--via <agentId>","agent that runs the extraction (LLM distillation goes through its session)").option("--min-occurrences <n>","recurrences before a pattern becomes a draft",String(Ot)).option("--timezone <tz>","IANA timezone","Africa/Tunis").option("-c, --config <path>","path to agentx.json").option("--dry-run","print what would be written without writing").action(async e=>{let o=e.off?void 0:e.cron??(e.hourly?Oc.hourly:e.daily?Oc.daily:void 0);!e.off&&!o&&!e.onTask&&(console.log(se.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(se.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let t=Number(e.minOccurrences)||Ot,n={enabled:!e.off,onTaskCompletion:!e.off&&!!e.onTask,minOccurrences:t,via:e.off?void 0:e.via},s=["Run this shell command EXACTLY as written. Do NOT substitute, rewrite, shorten, or fall back to alternative commands. If it exits non-zero, report the verbatim exit code and stderr and STOP.","",`1) cd ${process.cwd()} && node dist/cli.js procedure extract --since 7d --max ${cn} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
422
- `),i=await de(a=>{be(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&be(a,"crons.procedure-extract.enabled",!1):o&&be(a,"crons.procedure-extract",{enabled:!0,schedule:o,timezone:e.timezone,agent:e.via,prompt:s,timeout:900,onError:"log"})},{configPath:e.config,dryRun:!!e.dryRun});i.success||(console.log(se.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(se.green(` \u2713 ${r} procedure extraction: off`)):(console.log(se.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(se.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(se.dim(" on-task counting: enabled")),console.log(se.dim(` threshold: ${t} occurrences`))),console.log(se.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var Ke=new xp().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");Ke.addCommand(Ic);Ke.addCommand(Cc);Ke.command("list").description("list procedures with their trigger line").option("--drafts","list unreviewed drafts instead",!1).option("--all","list active procedures and drafts",!1).action(e=>{let o=new po,t=[...e.drafts?[]:o.list(),...e.drafts||e.all?o.listDrafts():[]];if(!t.length){console.log(Y.dim(e.drafts?" no procedure drafts. Mine some with: agentx procedure extract":" no procedures yet. Try: agentx procedure extract \xB7 or: agentx procedure add"));return}console.log();for(let n of t){let s=n.meta.status==="active"?Y.green(n.meta.status):n.meta.status==="draft"?Y.yellow(n.meta.status):Y.dim(n.meta.status);console.log(` ${Y.cyan(n.meta.id)} ${Y.bold(n.meta.title)} ${s}`),console.log(` ${Y.dim("trigger:")} ${n.meta.trigger}`),n.meta.source&&console.log(` ${Y.dim("source:")} ${Y.dim(n.meta.source)}`),n.meta.kpis?.length&&console.log(` ${Y.dim("kpis:")} ${n.meta.kpis.join(", ")}`)}console.log(),console.log(Y.dim(` ${t.length} procedure${t.length===1?"":"s"}.`))});Ke.command("add").description("add a new procedure (non-interactive; pass all fields as flags)").requiredOption("--id <id>","procedure id (lower-kebab, e.g. deploy-peer)").requiredOption("--title <t>","human-readable title").requiredOption("--trigger <t>","when this procedure applies (one sentence)").option("--input <i...>","required input (repeatable)",(e,o=[])=>[...o,e]).option("--expected <t>","expected output / success criterion").option("--kpi <k...>","KPI (repeatable)",(e,o=[])=>[...o,e]).option("--owner <id>","owning agent or person").option("--tag <t...>","tag (repeatable)",(e,o=[])=>[...o,e]).option("--related <r...>","related procedure id or wiki article title (repeatable)",(e,o=[])=>[...o,e]).option("--steps <md>","markdown body \u2014 usually numbered steps").action(e=>{let o=new po,t=e.steps?String(e.steps):`## Steps
455
+ review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),Hc={hourly:"0 * * * *",daily:"0 3 * * *"},Vc=new zc().name("watch").description("set the extraction cadence: registers the cron + config the daemon runs on").option("--hourly","extract every hour").option("--daily","extract daily at 03:00").option("--cron <expr>","custom 5-field cron expression").option("--on-task","also count patterns live after each completed task").option("--off","disable scheduled extraction").option("--via <agentId>","agent that runs the extraction (LLM distillation goes through its session)").option("--min-occurrences <n>","recurrences before a pattern becomes a draft",String(Ct)).option("--timezone <tz>","IANA timezone","Africa/Tunis").option("-c, --config <path>","path to agentx.json").option("--dry-run","print what would be written without writing").action(async e=>{let o=e.off?void 0:e.cron??(e.hourly?Hc.hourly:e.daily?Hc.daily:void 0);!e.off&&!o&&!e.onTask&&(console.log(se.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(se.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let t=Number(e.minOccurrences)||Ct,n={enabled:!e.off,onTaskCompletion:!e.off&&!!e.onTask,minOccurrences:t,via:e.off?void 0:e.via},s=["Run this shell command EXACTLY as written. Do NOT substitute, rewrite, shorten, or fall back to alternative commands. If it exits non-zero, report the verbatim exit code and stderr and STOP.","",`1) cd ${process.cwd()} && node dist/cli.js procedure extract --since 7d --max ${un} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
456
+ `),i=await de(a=>{be(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&be(a,"crons.procedure-extract.enabled",!1):o&&be(a,"crons.procedure-extract",{enabled:!0,schedule:o,timezone:e.timezone,agent:e.via,prompt:s,timeout:900,onError:"log"})},{configPath:e.config,dryRun:!!e.dryRun});i.success||(console.log(se.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(se.green(` \u2713 ${r} procedure extraction: off`)):(console.log(se.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(se.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(se.dim(" on-task counting: enabled")),console.log(se.dim(` threshold: ${t} occurrences`))),console.log(se.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var Xe=new au().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");Xe.addCommand(Yc);Xe.addCommand(Vc);Xe.command("list").description("list procedures with their trigger line").option("--drafts","list unreviewed drafts instead",!1).option("--all","list active procedures and drafts",!1).action(e=>{let o=new fo,t=[...e.drafts?[]:o.list(),...e.drafts||e.all?o.listDrafts():[]];if(!t.length){console.log(Y.dim(e.drafts?" no procedure drafts. Mine some with: agentx procedure extract":" no procedures yet. Try: agentx procedure extract \xB7 or: agentx procedure add"));return}console.log();for(let n of t){let s=n.meta.status==="active"?Y.green(n.meta.status):n.meta.status==="draft"?Y.yellow(n.meta.status):Y.dim(n.meta.status);console.log(` ${Y.cyan(n.meta.id)} ${Y.bold(n.meta.title)} ${s}`),console.log(` ${Y.dim("trigger:")} ${n.meta.trigger}`),n.meta.source&&console.log(` ${Y.dim("source:")} ${Y.dim(n.meta.source)}`),n.meta.kpis?.length&&console.log(` ${Y.dim("kpis:")} ${n.meta.kpis.join(", ")}`)}console.log(),console.log(Y.dim(` ${t.length} procedure${t.length===1?"":"s"}.`))});Xe.command("add").description("add a new procedure (non-interactive; pass all fields as flags)").requiredOption("--id <id>","procedure id (lower-kebab, e.g. deploy-peer)").requiredOption("--title <t>","human-readable title").requiredOption("--trigger <t>","when this procedure applies (one sentence)").option("--input <i...>","required input (repeatable)",(e,o=[])=>[...o,e]).option("--expected <t>","expected output / success criterion").option("--kpi <k...>","KPI (repeatable)",(e,o=[])=>[...o,e]).option("--owner <id>","owning agent or person").option("--tag <t...>","tag (repeatable)",(e,o=[])=>[...o,e]).option("--related <r...>","related procedure id or wiki article title (repeatable)",(e,o=[])=>[...o,e]).option("--steps <md>","markdown body \u2014 usually numbered steps").action(e=>{let o=new fo,t=e.steps?String(e.steps):`## Steps
423
457
 
424
458
  1. (fill in)
425
459
 
426
460
  ## Notes
427
461
 
428
- `;try{let n=o.add({id:e.id,title:e.title,trigger:e.trigger,inputs:e.input||[],expected:e.expected,kpis:e.kpi||[],owner:e.owner,tags:e.tag||[],related:e.related||[]},t);console.log(Y.green(` \u2713 procedure added: ${n.meta.id}`)),console.log(Y.dim(` ${o.baseDir}/${n.path}`))}catch(n){console.log(Y.red(` add failed: ${n.message}`)),process.exit(1)}});Ke.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new po,t=o.get(e)??o.getDraft(e);t||(console.log(Y.yellow(` no procedure matches "${e}". Try: agentx procedure list --all`)),process.exit(1)),console.log(),console.log(Y.bold(` ${t.meta.title}`)+Y.dim(` (${t.meta.id}, ${t.meta.status})`)),console.log(Y.dim(` trigger: ${t.meta.trigger}`)),t.meta.inputs?.length&&console.log(Y.dim(` inputs: ${t.meta.inputs.join(", ")}`)),t.meta.expected&&console.log(Y.dim(` expected: ${t.meta.expected}`)),t.meta.kpis?.length&&console.log(Y.dim(` kpis: ${t.meta.kpis.join(", ")}`)),t.meta.owner&&console.log(Y.dim(` owner: ${t.meta.owner}`)),t.meta.source&&console.log(Y.dim(` source: ${t.meta.source}`)),t.meta.related?.length&&console.log(Y.dim(` related: ${t.meta.related.join(", ")}`)),console.log(),console.log(t.body),console.log()});Ke.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new po;try{let t=o.promoteDraft(e);console.log(Y.green(` \u2713 promoted: ${t.meta.id}`)),console.log(Y.dim(` agents will now follow it when a task matches: "${t.meta.trigger}"`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Ke.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new po;try{o.rejectDraft(e),console.log(Y.green(` \u2713 rejected: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Ke.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new po;try{o.deprecate(e),console.log(Y.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Ke.command("match <text>").description("find active procedures matching a task description").option("--limit <n>","max matches","3").option("--min-score <s>","minimum score 0..1","0.2").action((e,o)=>{let t=new po,n=Ki(e,t.list(),{limit:Number(o.limit)||3,minScore:Number(o.minScore)||.2});if(!n.length){console.log(Y.dim(" no matching procedures"));return}for(let s of n)console.log(` ${Y.cyan(s.procedure.meta.id)} ${Y.bold(s.score.toFixed(2))} ${Y.dim(s.reasons.join(", "))}`),console.log(Y.dim(` ${s.procedure.meta.trigger}`))});import{Command as Ap}from"commander";import S from"chalk";import{resolve as ft,basename as Op}from"path";import{existsSync as ri,readFileSync as ai,writeFileSync as Bn}from"fs";import ek from"better-sqlite3";import{readFileSync as Sp}from"fs";import{resolve as ut,dirname as Tc}from"path";import{fileURLToPath as Ep}from"url";var Kt=[{name:"linear",title:"Linear",description:"Trigger \u2192 Agent \u2192 End. Smallest workflow that runs."},{name:"branching",title:"Branching",description:"Classify, then route on the result via a branch node."},{name:"extract",title:"Structured extraction",description:"Pull typed fields from free-form text via extract.structured."},{name:"retry",title:"Retry + fallback",description:"Per-node retry policy with a branch fallback path."}];function Nc(e){let o=Tc(Ep(import.meta.url)),t=process.argv[1]?Tc(process.argv[1]):"",n=[ut(o,`${e}.yaml`),ut(o,"workflows/templates",`${e}.yaml`),ut(o,"..","workflows/templates",`${e}.yaml`),ut(o,"../..","workflows/templates",`${e}.yaml`),t?ut(t,"workflows/templates",`${e}.yaml`):"",t?ut(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return Sp(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
462
+ `;try{let n=o.add({id:e.id,title:e.title,trigger:e.trigger,inputs:e.input||[],expected:e.expected,kpis:e.kpi||[],owner:e.owner,tags:e.tag||[],related:e.related||[]},t);console.log(Y.green(` \u2713 procedure added: ${n.meta.id}`)),console.log(Y.dim(` ${o.baseDir}/${n.path}`))}catch(n){console.log(Y.red(` add failed: ${n.message}`)),process.exit(1)}});Xe.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new fo,t=o.get(e)??o.getDraft(e);t||(console.log(Y.yellow(` no procedure matches "${e}". Try: agentx procedure list --all`)),process.exit(1)),console.log(),console.log(Y.bold(` ${t.meta.title}`)+Y.dim(` (${t.meta.id}, ${t.meta.status})`)),console.log(Y.dim(` trigger: ${t.meta.trigger}`)),t.meta.inputs?.length&&console.log(Y.dim(` inputs: ${t.meta.inputs.join(", ")}`)),t.meta.expected&&console.log(Y.dim(` expected: ${t.meta.expected}`)),t.meta.kpis?.length&&console.log(Y.dim(` kpis: ${t.meta.kpis.join(", ")}`)),t.meta.owner&&console.log(Y.dim(` owner: ${t.meta.owner}`)),t.meta.source&&console.log(Y.dim(` source: ${t.meta.source}`)),t.meta.related?.length&&console.log(Y.dim(` related: ${t.meta.related.join(", ")}`)),console.log(),console.log(t.body),console.log()});Xe.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new fo;try{let t=o.promoteDraft(e);console.log(Y.green(` \u2713 promoted: ${t.meta.id}`)),console.log(Y.dim(` agents will now follow it when a task matches: "${t.meta.trigger}"`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Xe.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new fo;try{o.rejectDraft(e),console.log(Y.green(` \u2713 rejected: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Xe.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new fo;try{o.deprecate(e),console.log(Y.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Xe.command("match <text>").description("find active procedures matching a task description").option("--limit <n>","max matches","3").option("--min-score <s>","minimum score 0..1","0.2").action((e,o)=>{let t=new fo,n=cr(e,t.list(),{limit:Number(o.limit)||3,minScore:Number(o.minScore)||.2});if(!n.length){console.log(Y.dim(" no matching procedures"));return}for(let s of n)console.log(` ${Y.cyan(s.procedure.meta.id)} ${Y.bold(s.score.toFixed(2))} ${Y.dim(s.reasons.join(", "))}`),console.log(Y.dim(` ${s.procedure.meta.trigger}`))});import{Command as du}from"commander";import E from"chalk";import{resolve as bt,basename as gu}from"path";import{existsSync as wi,readFileSync as bi,writeFileSync as es}from"fs";import rv from"better-sqlite3";import{readFileSync as cu}from"fs";import{resolve as wt,dirname as Kc}from"path";import{fileURLToPath as lu}from"url";var tn=[{name:"linear",title:"Linear",description:"Trigger \u2192 Agent \u2192 End. Smallest workflow that runs."},{name:"branching",title:"Branching",description:"Classify, then route on the result via a branch node."},{name:"extract",title:"Structured extraction",description:"Pull typed fields from free-form text via extract.structured."},{name:"retry",title:"Retry + fallback",description:"Per-node retry policy with a branch fallback path."}];function Xc(e){let o=Kc(lu(import.meta.url)),t=process.argv[1]?Kc(process.argv[1]):"",n=[wt(o,`${e}.yaml`),wt(o,"workflows/templates",`${e}.yaml`),wt(o,"..","workflows/templates",`${e}.yaml`),wt(o,"../..","workflows/templates",`${e}.yaml`),t?wt(t,"workflows/templates",`${e}.yaml`):"",t?wt(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return cu(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
429
463
  ${n.join(`
430
- `)}`)}var Ue=new Ap().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Ue.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new Co().list();if(!o.length){console.log(S.dim(" no workflows yet. Add one by writing .agentx/workflows/<id>.json"));return}console.log();for(let t of o){let s=t.nodes.find(a=>a.type.startsWith("trigger."))?.config??{},i=[s.filter?.project,s.filter?.repo,s.filter?.chat].filter(Boolean).join(" / "),r=t.state==="active"?S.green("dispatch: active"):S.yellow(`dispatch: ${t.state}`);console.log(` ${S.cyan(t.id)} ${S.bold(t.title)} ${S.dim(`v${t.version} \xB7`)} ${r} ${S.dim(`\xB7 review: ${t.status}`)}`),console.log(` ${S.dim("trigger:")} ${s.source??"?"}${i?` ${S.dim(i)}`:""}`),console.log(` ${S.dim("nodes: ")} ${t.nodes.length} (${t.nodes.map(a=>a.type).join(", ")})`)}console.log(),console.log(S.dim(` ${o.length} workflow${o.length===1?"":"s"}.`))});Ue.command("show <id>").description("show a single workflow's full definition").option("--format <fmt>","output format: json (default) or yaml","json").action((e,o)=>{let n=new Co().get(e);n||(console.log(S.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=o.format.toLowerCase();s==="yaml"||s==="yml"?console.log(qi(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(S.red(` unknown format "${o.format}" \u2014 use json or yaml`)),process.exit(1))});Ue.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=ft(process.cwd(),e);ri(i)||(console.log(S.red(` file not found: ${i}`)),process.exit(1));try{let r=ai(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?Ko(r,{filePath:e}):JSON.parse(r),d=Vo.safeParse(c);if(!d.success){console.log(S.red(` \u2717 ${i}`));for(let l of d.error.issues)console.log(` ${l.path.join(".")||"<root>"}: ${l.message}`);process.exit(1)}let g=rn(d.data);if(g.length){console.log(S.yellow(` ! ${i} (lint)`));for(let l of g)console.log(` ${l}`);process.exit(1)}console.log(S.green(` \u2713 ${d.data.id} \u2014 valid`))}catch(r){let a=r instanceof an?r.message:`parse error: ${r?.message??r}`;console.log(S.red(` ${a}`)),process.exit(1)}return}let t=new Co().validateAll(),n=0,s=0;for(let i of t)if(i.isValid)console.log(S.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(S.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(S.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});Ue.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${Kt.map(e=>e.name).join(" | ")})`,"linear").option("--agent <id>","fill the agent placeholder with this agent id","default").option("--reviewer <id>","fill the reviewer placeholder for human-in-the-loop templates","alice").option("--title <text>","workflow title","").option("--json","scaffold as .json instead of .yaml",!1).option("--force","overwrite an existing workflow with the same id",!1).action((e,o)=>{let t=String(o.template||"linear");Kt.some(a=>a.name===t)||(console.log(S.red(` unknown template "${o.template}"`)),console.log(S.dim(` available: ${Kt.map(a=>a.name).join(", ")}`)),process.exit(1)),/^[a-z0-9][a-z0-9_-]*$/.test(e)||(console.log(S.red(` workflow id must be lower-kebab (got "${e}")`)),process.exit(1));let n=new Co;!o.force&&n.get(e)&&(console.log(S.red(` workflow "${e}" already exists. Use --force to overwrite or pick a new id.`)),process.exit(1));let s=Nc(t);s=s.replace(/__ID__/g,e).replace(/__TITLE__/g,o.title?String(o.title):`${t} workflow ${e}`).replace(/__AGENT__/g,String(o.agent)).replace(/__REVIEWER__/g,String(o.reviewer));try{let a=Ko(s,{filePath:`${e}.yaml`}),c=Vo.safeParse(a);if(!c.success){console.log(S.red(` template "${t}" failed schema validation after substitution:`));for(let d of c.error.issues)console.log(` ${d.path.join(".")||"<root>"}: ${d.message}`);process.exit(1)}}catch(a){console.log(S.red(` template parse failed: ${a?.message??a}`)),process.exit(1)}let i=o.json?"json":"yaml",r=ft(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=Ko(s,{filePath:`${e}.yaml`}),c=Vo.parse(a);Bn(r,JSON.stringify(c,null,2)+`
431
- `)}else Bn(r,s);console.log(),console.log(S.green(` \u2713 scaffolded ${r}`)),console.log(S.dim(` template: ${t}`)),console.log(),console.log(S.dim(" Next:")),console.log(S.dim(` 1. edit ${r}`)),console.log(S.dim(` 2. agentx workflow validate ${r}`)),console.log(S.dim(` 3. agentx workflow run ${e} --watch`)),console.log()});Ue.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of Kt)console.log(` ${S.cyan(e.name.padEnd(20))} ${S.bold(e.title)}`),console.log(` ${" ".repeat(20)} ${S.dim(e.description)}`);console.log(),console.log(S.dim(" Use: agentx workflow init <id> --template <name>")),console.log()});Ue.command("add <file>").description("import a YAML/JSON workflow file into .agentx/workflows and hot-reload").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--no-reload","skip the POST /reload after writing").action(async(e,o)=>{let t=ft(process.cwd(),e);ri(t)||(console.log(S.red(` file not found: ${t}`)),process.exit(1));let n=ai(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?Ko(n,{filePath:e}):JSON.parse(n)}catch(p){let f=p instanceof an?p.message:`parse error: ${p?.message??p}`;console.log(S.red(` ${f}`)),process.exit(1)}let r=Vo.safeParse(i);if(!r.success){console.log(S.red(" \u2717 schema:"));for(let p of r.error.issues)console.log(` ${p.path.join(".")||"<root>"}: ${p.message}`);process.exit(1)}let a=rn(r.data);if(a.length){console.log(S.red(" \u2717 lint:"));for(let p of a)console.log(` ${p}`);process.exit(1)}let c=new Co,d=s?Op(e).match(/\.yml$/i)?"yml":"yaml":"json",g=ft(c.baseDir,`${r.data.id}.${d}`);if(Bn(g,s?n:JSON.stringify(r.data,null,2)+`
432
- `),console.log(S.green(` \u2713 ${r.data.id} \u2192 ${g}`)),o.reload===!1){console.log(S.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let l=`${String(o.daemon).replace(/\/$/,"")}/reload`;try{let p=await fetch(l,{method:"POST"});p.ok?console.log(S.dim(" \u2713 daemon reloaded")):console.log(S.dim(` daemon /reload returned ${p.status} \u2014 restart manually if needed`))}catch{console.log(S.dim(` daemon not reachable at ${o.daemon} \u2014 start it or restart to pick up the new workflow`))}});Ue.command("runs [id]").description("list recent runs (optionally filtered to a single workflow)").option("--limit <n>","max runs to show","20").option("--node <id>",'home-node id for this daemon (defaults to WF_NODE_ID env or "local")').action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local",n=new At({nodeId:t}).list({workflowId:e,limit:Number(o.limit)});if(!n.length){console.log(S.dim(` no runs yet${e?` for "${e}"`:""}.`));return}console.log();for(let s of n){let i=s.history.at(-1),r=s.pending[0]??(s.status==="completed"?"\u2205":"\u2014"),a=s.status==="running"?S.cyan:s.status==="failed"?S.red:S.green;console.log(` ${S.dim(s.id.slice(0,8))} ${S.bold(s.workflowId)} ${a(r)} ${S.dim(s.status)}`),console.log(` ${S.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${S.dim("home: ")} ${s.homeNode}`),console.log(` ${S.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${S.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(S.dim(` ${n.length} run${n.length===1?"":"s"}.`))});Ue.command("run <id-or-file>").description("manually trigger a workflow by id, or load + register + run a YAML/JSON file").option("--input <json>","JSON object merged into the trigger event payload").option("--force","fire even if the trigger isn't `trigger.manual` (uses a synthesized event)",!1).option("--watch","tail per-step traces while the run executes",!1).option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").action(async(e,o)=>{let t={};if(o.input)try{t=JSON.parse(o.input)}catch{console.log(S.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=ft(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&ri(s)){let c=ai(s,"utf-8"),d=/\.(ya?ml)$/i.test(e),g;try{g=d?Ko(c,{filePath:e}):JSON.parse(c)}catch(b){let v=b instanceof an?b.message:`parse error: ${b?.message??b}`;console.log(S.red(` ${v}`)),process.exit(1)}let l=Vo.safeParse(g);if(!l.success){console.log(S.red(" \u2717 schema:"));for(let b of l.error.issues)console.log(` ${b.path.join(".")||"<root>"}: ${b.message}`);process.exit(1)}let p=rn(l.data);if(p.length){console.log(S.red(" \u2717 lint:"));for(let b of p)console.log(` ${b}`);process.exit(1)}let f=new Co,u=l.data.id.startsWith("_adhoc-")?l.data.id:`_adhoc-${l.data.id}-${Date.now().toString(36)}`,w=d?"yaml":"json",y=ft(f.baseDir,`${u}.${w}`),$=d?c.replace(new RegExp(`^id:\\s*${l.data.id}\\b`,"m"),`id: ${u}`):JSON.stringify({...l.data,id:u},null,2)+`
433
- `;Bn(y,$),n=u,console.log(S.dim(` ad-hoc registered as "${u}" \u2192 ${y}`));try{await fetch(`${String(o.daemon).replace(/\/$/,"")}/reload`,{method:"POST"})}catch{}}let r=`${String(o.daemon).replace(/\/$/,"")}/workflows/${encodeURIComponent(n)}/run`,a;try{let c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:t,force:!!o.force})});if(!c.ok){let g=await c.text();console.log(S.red(` run failed (${c.status}): ${g.slice(0,300)}`)),c.status===409&&console.log(S.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let d=await c.json();a=d.runId,console.log(S.green(` \u2713 run started: ${a||"(unknown id)"}${d.force?S.dim(` (forced, source=${d.source})`):""}`))}catch(c){console.log(S.red(` request to daemon failed: ${c.message}`)),process.exit(1)}o.watch&&a&&await jp({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function jp(e){let o=new Set,t=new Map,n=Date.now(),s=15*60*1e3;for(;Date.now()-n<s;){let i=[];try{let r=await fetch(`${e.daemonUrl}/traces?workflowRunId=${encodeURIComponent(e.runId)}&limit=200`);r.ok&&(i=(await r.json()).traces||[])}catch{}for(let r of i){if(!r.taskId||o.has(r.taskId)||(o.add(r.taskId),t.set(r.taskId,r),e.quiet))continue;let a=r.status||"running",c=a==="ok"?S.green:a==="error"?S.red:S.cyan,d=r.totalTokens!=null?S.dim(`${r.totalTokens}t`):"",g=r.durationMs!=null?S.dim(`${r.durationMs}ms`):"";console.log(` ${c(a.padEnd(5))} ${S.bold(r.nodeId||r.label||"(node)")} ${d} ${g}`),r.error&&console.log(` ${S.red(String(r.error).slice(0,200))}`)}try{let r=await fetch(`${e.daemonUrl}/api/workflows/runs/${encodeURIComponent(e.runId)}`);if(r.ok){let c=(await r.json()).run;if(c&&c.status&&c.status!=="running")return e.quiet||(console.log(),console.log(` ${S.dim("run finished:")} ${c.status}`),console.log(S.dim(` full traces: ${e.daemonUrl}/traces?workflowRunId=${e.runId}`))),Array.from(t.values())}}catch{}await new Promise(r=>setTimeout(r,500))}return e.quiet||console.log(S.yellow(" watch timed out after 15min. Run is still active \u2014 check /traces")),Array.from(t.values())}Ue.command("trace <id>").description("pretty-print a task's execution trace (taskId or runId)").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output",!1).action(async(e,o)=>{let t=String(o.daemon).replace(/\/$/,"");try{let i=await fetch(`${t}/traces/${encodeURIComponent(e)}`);if(i.ok){let r=await i.json();if(o.json){console.log(JSON.stringify(r,null,2));return}Rc(r);return}}catch{}let n;try{let i=await fetch(`${t}/traces?workflowRunId=${encodeURIComponent(e)}&limit=200`);i.ok||(console.log(S.red(` /traces returned ${i.status}`)),process.exit(1)),n=await i.json()}catch(i){console.log(S.red(` daemon request failed: ${i.message}`)),process.exit(1)}let s=n.traces||[];if(s.length===0){console.log(S.yellow(` no traces for "${e}"`)),console.log(S.dim(" (sqlite must be opened \u2014 check 'agentx doctor' if the daemon logged 'sqlite: not opened')"));return}if(o.json){console.log(JSON.stringify(s,null,2));return}console.log(),console.log(S.bold(` ${s.length} step${s.length===1?"":"s"} for run ${e}:`)),console.log();for(let i of s)Rc(i)});function Rc(e){let o=e.status||"ok",t=o==="ok"?S.green:o==="error"?S.red:S.cyan,n=e.totalTokens!=null?`${e.totalTokens}t`:"\u2014",s=e.durationMs!=null?`${e.durationMs}ms`:"\u2014",i=e.model||"\u2014";console.log(` ${t(o.padEnd(5))} ${S.bold(String(e.nodeId||e.label||"(node)"))}`),console.log(` ${S.dim("taskId:")} ${e.taskId||"\u2014"}`),console.log(` ${S.dim("model:")} ${i}`),console.log(` ${S.dim("tokens:")} ${n} ${S.dim("duration:")} ${s}`),e.error&&console.log(` ${S.dim("error:")} ${S.red(String(e.error).slice(0,300))}`),console.log()}Ue.command("pause <runId>").description("pause an active run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new At({nodeId:t}).setStatus(e,"paused")||(console.log(S.yellow(` no such run: ${e}`)),process.exit(1)),console.log(S.green(` \u2713 paused ${e}`))});Ue.command("resume <runId>").description("resume a paused run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new At({nodeId:t}).setStatus(e,"running")||(console.log(S.yellow(` no such run: ${e}`)),process.exit(1)),console.log(S.green(` \u2713 resumed ${e}`))});Ue.command("cancel <runId>").description("cancel an active run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new At({nodeId:t}).setStatus(e,"canceled")||(console.log(S.yellow(` no such run: ${e}`)),process.exit(1)),console.log(S.green(` \u2713 canceled ${e}`))});import{Command as _c}from"commander";import oe from"chalk";import Bo from"prompts";import{readFileSync as Ip,existsSync as Cp}from"fs";import{resolve as Tp}from"path";var Xt=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],ci=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),Dc={gitlab:"GitLab \u2192 Settings \u2192 Webhooks (tick Push/Issue/Pipeline events)",github:"GitHub \u2192 Repo Settings \u2192 Webhooks",sentry:"Sentry \u2192 Project Settings \u2192 Alerts \u2192 Webhooks",stripe:"Stripe Dashboard \u2192 Developers \u2192 Webhooks",vercel:"Vercel \u2192 Project Settings \u2192 Webhooks",odoo:"Odoo \u2192 Settings \u2192 Technical \u2192 Automation \u2192 Webhooks (or your installed `webhook` module)",hubspot:"HubSpot \u2192 Settings \u2192 Integrations \u2192 Private Apps \u2192 Webhooks subscription",discord:"Discord channel \u2192 Integrations \u2192 Webhooks (inbound-only, no on:* events)",slack:"Slack Outgoing Webhooks / Events API (inbound-only, no on:* events)",custom:"Any service that POSTs JSON \u2014 Linear, Calendly, Notion, etc. (inbound-only)"};function Pc(){let e=Tp(process.cwd(),"agentx.json");if(!Cp(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Ip(e,"utf-8"))}function Np(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?oe.yellow("\u26A0 no signing secret"):oe.green("\u2713 active"):oe.dim("disabled")}function Rp(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=ci.has(e.source)?oe.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${oe.cyan(e.id)} ${Np(e)}`),console.log(` ${oe.dim(e.source)} \u2192 ${oe.bold(e.agentId)}${n}`),console.log(` POST ${oe.dim(t)}`),e.secretEnv&&console.log(` secret: ${oe.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${oe.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${oe.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${oe.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var lo=new _c().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");lo.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=Pc(),t=Array.isArray(o.webhooks)?o.webhooks:[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(oe.dim(`
464
+ `)}`)}var Fe=new du().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Fe.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new No().list();if(!o.length){console.log(E.dim(" no workflows yet. Add one by writing .agentx/workflows/<id>.json"));return}console.log();for(let t of o){let s=t.nodes.find(a=>a.type.startsWith("trigger."))?.config??{},i=[s.filter?.project,s.filter?.repo,s.filter?.chat].filter(Boolean).join(" / "),r=t.state==="active"?E.green("dispatch: active"):E.yellow(`dispatch: ${t.state}`);console.log(` ${E.cyan(t.id)} ${E.bold(t.title)} ${E.dim(`v${t.version} \xB7`)} ${r} ${E.dim(`\xB7 review: ${t.status}`)}`),console.log(` ${E.dim("trigger:")} ${s.source??"?"}${i?` ${E.dim(i)}`:""}`),console.log(` ${E.dim("nodes: ")} ${t.nodes.length} (${t.nodes.map(a=>a.type).join(", ")})`)}console.log(),console.log(E.dim(` ${o.length} workflow${o.length===1?"":"s"}.`))});Fe.command("show <id>").description("show a single workflow's full definition").option("--format <fmt>","output format: json (default) or yaml","json").action((e,o)=>{let n=new No().get(e);n||(console.log(E.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=o.format.toLowerCase();s==="yaml"||s==="yml"?console.log(Zi(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(E.red(` unknown format "${o.format}" \u2014 use json or yaml`)),process.exit(1))});Fe.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=bt(process.cwd(),e);wi(i)||(console.log(E.red(` file not found: ${i}`)),process.exit(1));try{let r=bi(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?Zo(r,{filePath:e}):JSON.parse(r),d=Qo.safeParse(c);if(!d.success){console.log(E.red(` \u2717 ${i}`));for(let l of d.error.issues)console.log(` ${l.path.join(".")||"<root>"}: ${l.message}`);process.exit(1)}let g=mn(d.data);if(g.length){console.log(E.yellow(` ! ${i} (lint)`));for(let l of g)console.log(` ${l}`);process.exit(1)}console.log(E.green(` \u2713 ${d.data.id} \u2014 valid`))}catch(r){let a=r instanceof pn?r.message:`parse error: ${r?.message??r}`;console.log(E.red(` ${a}`)),process.exit(1)}return}let t=new No().validateAll(),n=0,s=0;for(let i of t)if(i.isValid)console.log(E.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(E.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(E.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});Fe.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${tn.map(e=>e.name).join(" | ")})`,"linear").option("--agent <id>","fill the agent placeholder with this agent id","default").option("--reviewer <id>","fill the reviewer placeholder for human-in-the-loop templates","alice").option("--title <text>","workflow title","").option("--json","scaffold as .json instead of .yaml",!1).option("--force","overwrite an existing workflow with the same id",!1).action((e,o)=>{let t=String(o.template||"linear");tn.some(a=>a.name===t)||(console.log(E.red(` unknown template "${o.template}"`)),console.log(E.dim(` available: ${tn.map(a=>a.name).join(", ")}`)),process.exit(1)),/^[a-z0-9][a-z0-9_-]*$/.test(e)||(console.log(E.red(` workflow id must be lower-kebab (got "${e}")`)),process.exit(1));let n=new No;!o.force&&n.get(e)&&(console.log(E.red(` workflow "${e}" already exists. Use --force to overwrite or pick a new id.`)),process.exit(1));let s=Xc(t);s=s.replace(/__ID__/g,e).replace(/__TITLE__/g,o.title?String(o.title):`${t} workflow ${e}`).replace(/__AGENT__/g,String(o.agent)).replace(/__REVIEWER__/g,String(o.reviewer));try{let a=Zo(s,{filePath:`${e}.yaml`}),c=Qo.safeParse(a);if(!c.success){console.log(E.red(` template "${t}" failed schema validation after substitution:`));for(let d of c.error.issues)console.log(` ${d.path.join(".")||"<root>"}: ${d.message}`);process.exit(1)}}catch(a){console.log(E.red(` template parse failed: ${a?.message??a}`)),process.exit(1)}let i=o.json?"json":"yaml",r=bt(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=Zo(s,{filePath:`${e}.yaml`}),c=Qo.parse(a);es(r,JSON.stringify(c,null,2)+`
465
+ `)}else es(r,s);console.log(),console.log(E.green(` \u2713 scaffolded ${r}`)),console.log(E.dim(` template: ${t}`)),console.log(),console.log(E.dim(" Next:")),console.log(E.dim(` 1. edit ${r}`)),console.log(E.dim(` 2. agentx workflow validate ${r}`)),console.log(E.dim(` 3. agentx workflow run ${e} --watch`)),console.log()});Fe.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of tn)console.log(` ${E.cyan(e.name.padEnd(20))} ${E.bold(e.title)}`),console.log(` ${" ".repeat(20)} ${E.dim(e.description)}`);console.log(),console.log(E.dim(" Use: agentx workflow init <id> --template <name>")),console.log()});Fe.command("add <file>").description("import a YAML/JSON workflow file into .agentx/workflows and hot-reload").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--no-reload","skip the POST /reload after writing").action(async(e,o)=>{let t=bt(process.cwd(),e);wi(t)||(console.log(E.red(` file not found: ${t}`)),process.exit(1));let n=bi(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?Zo(n,{filePath:e}):JSON.parse(n)}catch(p){let f=p instanceof pn?p.message:`parse error: ${p?.message??p}`;console.log(E.red(` ${f}`)),process.exit(1)}let r=Qo.safeParse(i);if(!r.success){console.log(E.red(" \u2717 schema:"));for(let p of r.error.issues)console.log(` ${p.path.join(".")||"<root>"}: ${p.message}`);process.exit(1)}let a=mn(r.data);if(a.length){console.log(E.red(" \u2717 lint:"));for(let p of a)console.log(` ${p}`);process.exit(1)}let c=new No,d=s?gu(e).match(/\.yml$/i)?"yml":"yaml":"json",g=bt(c.baseDir,`${r.data.id}.${d}`);if(es(g,s?n:JSON.stringify(r.data,null,2)+`
466
+ `),console.log(E.green(` \u2713 ${r.data.id} \u2192 ${g}`)),o.reload===!1){console.log(E.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let l=`${String(o.daemon).replace(/\/$/,"")}/reload`;try{let p=await fetch(l,{method:"POST"});p.ok?console.log(E.dim(" \u2713 daemon reloaded")):console.log(E.dim(` daemon /reload returned ${p.status} \u2014 restart manually if needed`))}catch{console.log(E.dim(` daemon not reachable at ${o.daemon} \u2014 start it or restart to pick up the new workflow`))}});Fe.command("runs [id]").description("list recent runs (optionally filtered to a single workflow)").option("--limit <n>","max runs to show","20").option("--node <id>",'home-node id for this daemon (defaults to WF_NODE_ID env or "local")').action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local",n=new jt({nodeId:t}).list({workflowId:e,limit:Number(o.limit)});if(!n.length){console.log(E.dim(` no runs yet${e?` for "${e}"`:""}.`));return}console.log();for(let s of n){let i=s.history.at(-1),r=s.pending[0]??(s.status==="completed"?"\u2205":"\u2014"),a=s.status==="running"?E.cyan:s.status==="failed"?E.red:E.green;console.log(` ${E.dim(s.id.slice(0,8))} ${E.bold(s.workflowId)} ${a(r)} ${E.dim(s.status)}`),console.log(` ${E.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${E.dim("home: ")} ${s.homeNode}`),console.log(` ${E.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${E.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(E.dim(` ${n.length} run${n.length===1?"":"s"}.`))});Fe.command("run <id-or-file>").description("manually trigger a workflow by id, or load + register + run a YAML/JSON file").option("--input <json>","JSON object merged into the trigger event payload").option("--force","fire even if the trigger isn't `trigger.manual` (uses a synthesized event)",!1).option("--watch","tail per-step traces while the run executes",!1).option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").action(async(e,o)=>{let t={};if(o.input)try{t=JSON.parse(o.input)}catch{console.log(E.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=bt(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&wi(s)){let c=bi(s,"utf-8"),d=/\.(ya?ml)$/i.test(e),g;try{g=d?Zo(c,{filePath:e}):JSON.parse(c)}catch(b){let x=b instanceof pn?b.message:`parse error: ${b?.message??b}`;console.log(E.red(` ${x}`)),process.exit(1)}let l=Qo.safeParse(g);if(!l.success){console.log(E.red(" \u2717 schema:"));for(let b of l.error.issues)console.log(` ${b.path.join(".")||"<root>"}: ${b.message}`);process.exit(1)}let p=mn(l.data);if(p.length){console.log(E.red(" \u2717 lint:"));for(let b of p)console.log(` ${b}`);process.exit(1)}let f=new No,u=l.data.id.startsWith("_adhoc-")?l.data.id:`_adhoc-${l.data.id}-${Date.now().toString(36)}`,w=d?"yaml":"json",y=bt(f.baseDir,`${u}.${w}`),k=d?c.replace(new RegExp(`^id:\\s*${l.data.id}\\b`,"m"),`id: ${u}`):JSON.stringify({...l.data,id:u},null,2)+`
467
+ `;es(y,k),n=u,console.log(E.dim(` ad-hoc registered as "${u}" \u2192 ${y}`));try{await fetch(`${String(o.daemon).replace(/\/$/,"")}/reload`,{method:"POST"})}catch{}}let r=`${String(o.daemon).replace(/\/$/,"")}/workflows/${encodeURIComponent(n)}/run`,a;try{let c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:t,force:!!o.force})});if(!c.ok){let g=await c.text();console.log(E.red(` run failed (${c.status}): ${g.slice(0,300)}`)),c.status===409&&console.log(E.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let d=await c.json();a=d.runId,console.log(E.green(` \u2713 run started: ${a||"(unknown id)"}${d.force?E.dim(` (forced, source=${d.source})`):""}`))}catch(c){console.log(E.red(` request to daemon failed: ${c.message}`)),process.exit(1)}o.watch&&a&&await mu({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function mu(e){let o=new Set,t=new Map,n=Date.now(),s=15*60*1e3;for(;Date.now()-n<s;){let i=[];try{let r=await fetch(`${e.daemonUrl}/traces?workflowRunId=${encodeURIComponent(e.runId)}&limit=200`);r.ok&&(i=(await r.json()).traces||[])}catch{}for(let r of i){if(!r.taskId||o.has(r.taskId)||(o.add(r.taskId),t.set(r.taskId,r),e.quiet))continue;let a=r.status||"running",c=a==="ok"?E.green:a==="error"?E.red:E.cyan,d=r.totalTokens!=null?E.dim(`${r.totalTokens}t`):"",g=r.durationMs!=null?E.dim(`${r.durationMs}ms`):"";console.log(` ${c(a.padEnd(5))} ${E.bold(r.nodeId||r.label||"(node)")} ${d} ${g}`),r.error&&console.log(` ${E.red(String(r.error).slice(0,200))}`)}try{let r=await fetch(`${e.daemonUrl}/api/workflows/runs/${encodeURIComponent(e.runId)}`);if(r.ok){let c=(await r.json()).run;if(c&&c.status&&c.status!=="running")return e.quiet||(console.log(),console.log(` ${E.dim("run finished:")} ${c.status}`),console.log(E.dim(` full traces: ${e.daemonUrl}/traces?workflowRunId=${e.runId}`))),Array.from(t.values())}}catch{}await new Promise(r=>setTimeout(r,500))}return e.quiet||console.log(E.yellow(" watch timed out after 15min. Run is still active \u2014 check /traces")),Array.from(t.values())}Fe.command("trace <id>").description("pretty-print a task's execution trace (taskId or runId)").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output",!1).action(async(e,o)=>{let t=String(o.daemon).replace(/\/$/,"");try{let i=await fetch(`${t}/traces/${encodeURIComponent(e)}`);if(i.ok){let r=await i.json();if(o.json){console.log(JSON.stringify(r,null,2));return}Qc(r);return}}catch{}let n;try{let i=await fetch(`${t}/traces?workflowRunId=${encodeURIComponent(e)}&limit=200`);i.ok||(console.log(E.red(` /traces returned ${i.status}`)),process.exit(1)),n=await i.json()}catch(i){console.log(E.red(` daemon request failed: ${i.message}`)),process.exit(1)}let s=n.traces||[];if(s.length===0){console.log(E.yellow(` no traces for "${e}"`)),console.log(E.dim(" (sqlite must be opened \u2014 check 'agentx doctor' if the daemon logged 'sqlite: not opened')"));return}if(o.json){console.log(JSON.stringify(s,null,2));return}console.log(),console.log(E.bold(` ${s.length} step${s.length===1?"":"s"} for run ${e}:`)),console.log();for(let i of s)Qc(i)});function Qc(e){let o=e.status||"ok",t=o==="ok"?E.green:o==="error"?E.red:E.cyan,n=e.totalTokens!=null?`${e.totalTokens}t`:"\u2014",s=e.durationMs!=null?`${e.durationMs}ms`:"\u2014",i=e.model||"\u2014";console.log(` ${t(o.padEnd(5))} ${E.bold(String(e.nodeId||e.label||"(node)"))}`),console.log(` ${E.dim("taskId:")} ${e.taskId||"\u2014"}`),console.log(` ${E.dim("model:")} ${i}`),console.log(` ${E.dim("tokens:")} ${n} ${E.dim("duration:")} ${s}`),e.error&&console.log(` ${E.dim("error:")} ${E.red(String(e.error).slice(0,300))}`),console.log()}Fe.command("pause <runId>").description("pause an active run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new jt({nodeId:t}).setStatus(e,"paused")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 paused ${e}`))});Fe.command("resume <runId>").description("resume a paused run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new jt({nodeId:t}).setStatus(e,"running")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 resumed ${e}`))});Fe.command("cancel <runId>").description("cancel an active run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new jt({nodeId:t}).setStatus(e,"canceled")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 canceled ${e}`))});import{Command as Zc}from"commander";import oe from"chalk";import Ho from"prompts";import{readFileSync as pu,existsSync as uu}from"fs";import{resolve as fu}from"path";var nn=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],$i=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),el={gitlab:"GitLab \u2192 Settings \u2192 Webhooks (tick Push/Issue/Pipeline events)",github:"GitHub \u2192 Repo Settings \u2192 Webhooks",sentry:"Sentry \u2192 Project Settings \u2192 Alerts \u2192 Webhooks",stripe:"Stripe Dashboard \u2192 Developers \u2192 Webhooks",vercel:"Vercel \u2192 Project Settings \u2192 Webhooks",odoo:"Odoo \u2192 Settings \u2192 Technical \u2192 Automation \u2192 Webhooks (or your installed `webhook` module)",hubspot:"HubSpot \u2192 Settings \u2192 Integrations \u2192 Private Apps \u2192 Webhooks subscription",discord:"Discord channel \u2192 Integrations \u2192 Webhooks (inbound-only, no on:* events)",slack:"Slack Outgoing Webhooks / Events API (inbound-only, no on:* events)",custom:"Any service that POSTs JSON \u2014 Linear, Calendly, Notion, etc. (inbound-only)"};function ol(){let e=fu(process.cwd(),"agentx.json");if(!uu(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(pu(e,"utf-8"))}function hu(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?oe.yellow("\u26A0 no signing secret"):oe.green("\u2713 active"):oe.dim("disabled")}function yu(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=$i.has(e.source)?oe.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${oe.cyan(e.id)} ${hu(e)}`),console.log(` ${oe.dim(e.source)} \u2192 ${oe.bold(e.agentId)}${n}`),console.log(` POST ${oe.dim(t)}`),e.secretEnv&&console.log(` secret: ${oe.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${oe.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${oe.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${oe.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var mo=new Zc().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");mo.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=ol(),t=Array.isArray(o.webhooks)?o.webhooks:[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(oe.dim(`
434
468
  No webhooks registered. Add one with: agentx webhook add
435
- `));return}console.log();for(let n of t)Rp(n)});lo.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${Xt.join(", ")}`).option("--agent <agentId>","agent that receives the webhook").option("--secret-env <name>","env var holding the signing secret (recommended)").option("--description <text>","free-text description").option("--node <peer>","forward to a mesh peer (skips local agent check; validates against mesh.peers)").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=Pc(),n=Object.keys(t.agents||{}),s=(t.mesh?.peers||[]).map(f=>f.name).filter(Boolean),i=String(o.node||"").trim();if(!n.length&&!i)throw new Error("No local agents configured. Add one with: agentx agent add \u2014 or use --node <peer> to forward to a mesh peer.");let r=(e||"").trim(),a=String(o.source||"").trim(),c=String(o.agent||"").trim(),d=String(o.secretEnv||"").trim(),g=String(o.description||"").trim(),l=o.prompt!==!1;if(!r&&l&&(r=((await Bo({type:"text",name:"id",message:"Webhook id (lowercase, e.g. globex-gitlab)",validate:u=>/^[a-z0-9][a-z0-9_-]*$/.test(u)||"Use lowercase letters, digits, -, _"})).id||"").trim()),!r)throw new Error("Webhook id is required.");if(!/^[a-z0-9][a-z0-9_-]*$/.test(r))throw new Error("Webhook id must be lowercase (letters, digits, -, _).");if(!a&&l&&(a=(await Bo({type:"select",name:"source",message:"Source",choices:Xt.map(u=>({title:`${u}${ci.has(u)?" \u2713 wired":""}`,value:u,description:Dc[u]}))})).source),!Xt.includes(a))throw new Error(`Source must be one of: ${Xt.join(", ")}`);if(!c&&l&&(i?c=((await Bo({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await Bo({type:"select",name:"agentId",message:"Agent",choices:n.map(u=>({title:u,value:u}))})).agentId),!c)throw new Error("Agent is required.");if(i){if(!s.includes(i))throw new Error(`Mesh peer "${i}" not found in mesh.peers. Add the peer first or omit --node.`)}else if(!t.agents?.[c])throw new Error(`Unknown agent "${c}". Add it locally, or use --node <peer> to forward to a mesh peer.`);!d&&l&&a!=="custom"&&(d=((await Bo({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&l&&(g=((await Bo({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let p=await de(f=>{if(f.webhooks=Array.isArray(f.webhooks)?f.webhooks:[],f.webhooks.find(w=>w.id===r))throw new Error(`Webhook "${r}" already exists.`);let u={id:r,source:a,agentId:c,enabled:!0};d&&(u.secretEnv=d),g&&(u.description=g),i&&(u.node=i),f.webhooks.push(u)});if(!p.success)throw new Error(p.error);console.log(oe.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),p.reloaded&&console.log(oe.dim(" daemon hot-reloaded")),!d&&a!=="custom"&&console.log(oe.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});lo.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await Bo({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await de(n=>{let s=(n.webhooks||[]).length;if(n.webhooks=(n.webhooks||[]).filter(i=>i.id!==e),n.webhooks.length===s)throw new Error(`Webhook "${e}" not found.`)});if(!t.success)throw new Error(t.error);console.log(oe.green(`\u2713 removed webhook "${e}"`))});function Lc(e){return async o=>{let t=await de(n=>{let s=(n.webhooks||[]).find(i=>i.id===o);if(!s)throw new Error(`Webhook "${o}" not found.`);s.enabled=e});if(!t.success)throw new Error(t.error);console.log(oe.green(`\u2713 ${e?"enabled":"disabled"} webhook "${o}"`))}}lo.command("enable <id>").description("enable a webhook entry").action(Lc(!0));lo.command("disable <id>").description("disable a webhook entry").action(Lc(!1));var Jn=new _c().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");Jn.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await de(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);i.triggers=i.triggers&&typeof i.triggers=="object"?i.triggers:{},i.triggers[o]=t});if(!n.success)throw new Error(n.error);console.log(oe.green(`\u2713 ${e}: ${o} \u2192 ${t}`))});Jn.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await de(n=>{let s=(n.webhooks||[]).find(i=>i.id===e);if(!s)throw new Error(`Webhook "${e}" not found.`);s.triggers&&typeof s.triggers=="object"&&delete s.triggers[o]});if(!t.success)throw new Error(t.error);console.log(oe.green(`\u2713 removed trigger ${o} from "${e}"`))});Jn.command("default <id> <workflowId>").description("set the default workflow when no event-type matches (use '-' to clear)").action(async(e,o)=>{let t=o==="-"||o==="",n=await de(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);t?delete i.defaultWorkflow:i.defaultWorkflow=o});if(!n.success)throw new Error(n.error);console.log(oe.green(`\u2713 ${e}: defaultWorkflow ${t?"cleared":`\u2192 ${o}`}`))});lo.addCommand(Jn);lo.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=Xt.map(t=>({source:t,wired:ci.has(t),hint:Dc[t]}));if(e.json){console.log(JSON.stringify(o,null,2));return}console.log();for(let t of o){let n=t.wired?oe.green("\u2713 wired"):oe.dim("inbound-only");console.log(` ${oe.cyan(t.source.padEnd(8))} ${n} ${oe.dim(t.hint)}`)}console.log(),console.log(oe.dim(" Wired sources emit on:<source>-* hook events that workflows can subscribe to via trigger.hook.")),console.log(oe.dim(" Use 'custom' for any service not in the list (Odoo, HubSpot, Linear, Calendly, etc.).")),console.log()});import{Command as _p}from"commander";import te from"chalk";we();function ht(e){let{summary:o,backupPath:t}=Zo(n=>e(n));console.log(te.green(`
469
+ `));return}console.log();for(let n of t)yu(n)});mo.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${nn.join(", ")}`).option("--agent <agentId>","agent that receives the webhook").option("--secret-env <name>","env var holding the signing secret (recommended)").option("--description <text>","free-text description").option("--node <peer>","forward to a mesh peer (skips local agent check; validates against mesh.peers)").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=ol(),n=Object.keys(t.agents||{}),s=(t.mesh?.peers||[]).map(f=>f.name).filter(Boolean),i=String(o.node||"").trim();if(!n.length&&!i)throw new Error("No local agents configured. Add one with: agentx agent add \u2014 or use --node <peer> to forward to a mesh peer.");let r=(e||"").trim(),a=String(o.source||"").trim(),c=String(o.agent||"").trim(),d=String(o.secretEnv||"").trim(),g=String(o.description||"").trim(),l=o.prompt!==!1;if(!r&&l&&(r=((await Ho({type:"text",name:"id",message:"Webhook id (lowercase, e.g. globex-gitlab)",validate:u=>/^[a-z0-9][a-z0-9_-]*$/.test(u)||"Use lowercase letters, digits, -, _"})).id||"").trim()),!r)throw new Error("Webhook id is required.");if(!/^[a-z0-9][a-z0-9_-]*$/.test(r))throw new Error("Webhook id must be lowercase (letters, digits, -, _).");if(!a&&l&&(a=(await Ho({type:"select",name:"source",message:"Source",choices:nn.map(u=>({title:`${u}${$i.has(u)?" \u2713 wired":""}`,value:u,description:el[u]}))})).source),!nn.includes(a))throw new Error(`Source must be one of: ${nn.join(", ")}`);if(!c&&l&&(i?c=((await Ho({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await Ho({type:"select",name:"agentId",message:"Agent",choices:n.map(u=>({title:u,value:u}))})).agentId),!c)throw new Error("Agent is required.");if(i){if(!s.includes(i))throw new Error(`Mesh peer "${i}" not found in mesh.peers. Add the peer first or omit --node.`)}else if(!t.agents?.[c])throw new Error(`Unknown agent "${c}". Add it locally, or use --node <peer> to forward to a mesh peer.`);!d&&l&&a!=="custom"&&(d=((await Ho({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&l&&(g=((await Ho({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let p=await de(f=>{if(f.webhooks=Array.isArray(f.webhooks)?f.webhooks:[],f.webhooks.find(w=>w.id===r))throw new Error(`Webhook "${r}" already exists.`);let u={id:r,source:a,agentId:c,enabled:!0};d&&(u.secretEnv=d),g&&(u.description=g),i&&(u.node=i),f.webhooks.push(u)});if(!p.success)throw new Error(p.error);console.log(oe.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),p.reloaded&&console.log(oe.dim(" daemon hot-reloaded")),!d&&a!=="custom"&&console.log(oe.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});mo.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await Ho({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await de(n=>{let s=(n.webhooks||[]).length;if(n.webhooks=(n.webhooks||[]).filter(i=>i.id!==e),n.webhooks.length===s)throw new Error(`Webhook "${e}" not found.`)});if(!t.success)throw new Error(t.error);console.log(oe.green(`\u2713 removed webhook "${e}"`))});function tl(e){return async o=>{let t=await de(n=>{let s=(n.webhooks||[]).find(i=>i.id===o);if(!s)throw new Error(`Webhook "${o}" not found.`);s.enabled=e});if(!t.success)throw new Error(t.error);console.log(oe.green(`\u2713 ${e?"enabled":"disabled"} webhook "${o}"`))}}mo.command("enable <id>").description("enable a webhook entry").action(tl(!0));mo.command("disable <id>").description("disable a webhook entry").action(tl(!1));var os=new Zc().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");os.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await de(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);i.triggers=i.triggers&&typeof i.triggers=="object"?i.triggers:{},i.triggers[o]=t});if(!n.success)throw new Error(n.error);console.log(oe.green(`\u2713 ${e}: ${o} \u2192 ${t}`))});os.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await de(n=>{let s=(n.webhooks||[]).find(i=>i.id===e);if(!s)throw new Error(`Webhook "${e}" not found.`);s.triggers&&typeof s.triggers=="object"&&delete s.triggers[o]});if(!t.success)throw new Error(t.error);console.log(oe.green(`\u2713 removed trigger ${o} from "${e}"`))});os.command("default <id> <workflowId>").description("set the default workflow when no event-type matches (use '-' to clear)").action(async(e,o)=>{let t=o==="-"||o==="",n=await de(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);t?delete i.defaultWorkflow:i.defaultWorkflow=o});if(!n.success)throw new Error(n.error);console.log(oe.green(`\u2713 ${e}: defaultWorkflow ${t?"cleared":`\u2192 ${o}`}`))});mo.addCommand(os);mo.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=nn.map(t=>({source:t,wired:$i.has(t),hint:el[t]}));if(e.json){console.log(JSON.stringify(o,null,2));return}console.log();for(let t of o){let n=t.wired?oe.green("\u2713 wired"):oe.dim("inbound-only");console.log(` ${oe.cyan(t.source.padEnd(8))} ${n} ${oe.dim(t.hint)}`)}console.log(),console.log(oe.dim(" Wired sources emit on:<source>-* hook events that workflows can subscribe to via trigger.hook.")),console.log(oe.dim(" Use 'custom' for any service not in the list (Odoo, HubSpot, Linear, Calendly, etc.).")),console.log()});import{Command as wu}from"commander";import te from"chalk";pe();function $t(e){let{summary:o,backupPath:t}=nt(n=>e(n));console.log(te.green(`
436
470
  \u2713 ${o}`)),t&&console.log(te.dim(` Backup: ${t}`)),console.log(te.dim(` Restart the daemon (or POST /reload) for the change to take effect.
437
- `))}function Hn(){try{return D().business||{}}catch{return{}}}var yt=new _p().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");yt.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=Hn();if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o||!o.enabled){console.log(),console.log(te.yellow(" business block not enabled (or missing).")),console.log(te.dim(" Add a `business` key to agentx.json to opt in.")),console.log();return}let t=o.orgChart||{},n=o.projects||[],s=o.contactMap||[];console.log(),console.log(te.bold(" Org chart"));let i=Object.entries(t);if(i.length===0)console.log(te.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?te.dim(` \u2192 reports to ${a.reportsTo}`):"",d=a.schedule?te.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${te.cyan(r)} ${a.role}${c}${d}`)}if(console.log(),console.log(te.bold(` Projects (${n.length})`)),n.length===0)console.log(te.dim(" (empty)"));else for(let r of n){let a=r.pm?te.dim(` \xB7 pm=${r.pm}`):"",c=r.client?te.dim(` \xB7 client=${r.client}`):"";console.log(` ${te.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(te.bold(` Contact map (${s.length})`)),s.length===0)console.log(te.dim(" (empty)"));else for(let r of s){let a=r.chatId?`chatId=${r.chatId}`:r.username?`username=${r.username}`:r.senderId?`senderId=${r.senderId}`:"?",c=r.channel?`${r.channel}/`:"";console.log(` ${te.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?te.dim(` (${r.displayName})`):""}`)}console.log()});var li=yt.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");li.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=Hn(),t=Object.entries(o.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(t),null,2));return}if(t.length===0){console.log(te.dim(" no entries"));return}for(let[n,s]of t)console.log(` ${te.cyan(n)} ${s.role}${s.reportsTo?te.dim(` \u2192 ${s.reportsTo}`):""}`)});li.command("add <agentId>").description("add or update an orgChart entry for an agent").requiredOption("--role <role>","role title (e.g. 'PM', 'Coder', 'DevOps')").option("--reports-to <agentId>","manager's agentId").option("--start <hh:mm>","schedule start","09:00").option("--end <hh:mm>","schedule end","17:00").option("--days <csv>","working days (mon,tue,wed,thu,fri)","mon,tue,wed,thu,fri").option("--utilization <0..1>","target utilization","0.8").action((e,o)=>{let t=String(o.days).split(",").map(n=>n.trim()).filter(Boolean);ht(n=>(n.business=n.business||{},n.business.orgChart=n.business.orgChart||{},n.business.orgChart[e]={role:o.role,...o.reportsTo?{reportsTo:o.reportsTo}:{},schedule:{days:t,start:o.start,end:o.end},utilizationTarget:parseFloat(o.utilization)||.8},`orgChart entry "${e}" upserted (role=${o.role}${o.reportsTo?`, reports to ${o.reportsTo}`:""})`))});li.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{ht(o=>{if(!o.business?.orgChart||!(e in o.business.orgChart))throw new Error(`no orgChart entry for "${e}"`);return delete o.business.orgChart[e],`orgChart entry "${e}" removed`})});var di=yt.command("project").description("manage business.projects \u2014 id, pm, client");di.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=Hn().projects||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(te.dim(" no projects"));return}for(let n of t)console.log(` ${te.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});di.command("add <id>").description("add or update a project entry").option("--pm <agentId>","PM responsible for this project (drives PM gate)").option("--client <name>","client this project belongs to (drives activity-graph attribution)").action((e,o)=>{ht(t=>{t.business=t.business||{},t.business.projects=t.business.projects||[];let n=t.business.projects.findIndex(i=>i.id===e),s={id:e,...o.pm?{pm:o.pm}:{},...o.client?{client:o.client}:{}};return n>=0?t.business.projects[n]={...t.business.projects[n],...s}:t.business.projects.push(s),n>=0?`project "${e}" updated`:`project "${e}" added`})});di.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{ht(o=>{let t=o.business?.projects||[],n=t.length;if(o.business.projects=t.filter(s=>s.id!==e),o.business.projects.length===n)throw new Error(`no project "${e}"`);return`project "${e}" removed`})});var gi=yt.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");gi.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let t=Hn().contactMap||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(te.dim(" no entries"));return}for(let n of t){let s=n.chatId?`chatId=${n.chatId}`:n.username?`username=${n.username}`:n.senderId?`senderId=${n.senderId}`:"?";console.log(` ${n.channel?n.channel+"/":""}${te.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});gi.command("add").description("add a contactMap entry").requiredOption("--client <name>","client this contact belongs to").option("--channel <name>","telegram | whatsapp | slack | discord").option("--chat-id <id>","native chat id (e.g. -100\u2026, JID)").option("--username <handle>","sender username/handle").option("--sender-id <id>","numeric sender id (when username is unstable)").option("--project <id>","project this traffic should attribute to").option("--display-name <name>","display-name override for the initiator pill").action(e=>{!e.chatId&&!e.username&&!e.senderId&&(console.log(te.red(" one of --chat-id / --username / --sender-id is required")),process.exit(1)),ht(o=>{o.business=o.business||{},o.business.contactMap=o.business.contactMap||[];let t={client:e.client};e.channel&&(t.channel=e.channel),e.chatId&&(t.chatId=e.chatId),e.username&&(t.username=e.username),e.senderId&&(t.senderId=e.senderId),e.project&&(t.project=e.project),e.displayName&&(t.displayName=e.displayName),o.business.contactMap.push(t);let n=e.chatId||e.username||e.senderId;return`contact ${e.channel?e.channel+"/":""}${n} \u2192 ${e.client}${e.project?"/"+e.project:""} added`})});gi.command("remove").alias("rm").description("remove a contactMap entry by matching field(s)").option("--channel <name>").option("--chat-id <id>").option("--username <handle>").option("--sender-id <id>").action(e=>{ht(o=>{let t=o.business?.contactMap||[],n=t.length;if(o.business.contactMap=t.filter(s=>!!(e.channel&&s.channel!==e.channel||e.chatId&&s.chatId!==e.chatId||e.username&&s.username!==e.username||e.senderId&&s.senderId!==e.senderId)),o.business.contactMap.length===n)throw new Error("no matching contact entry");return`${n-o.business.contactMap.length} contact entry/entries removed`})});import{Command as Dp}from"commander";import Ne from"chalk";we();var Pp={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function mi(e){let o=Pp[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function Gn(){let o=D().business?.standup?.plansDir||".agentx/plans";return new Lr(o)}var wt=new Dp().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");wt.command("set <tier>").description("write a plan for today | week | month (priorities-as-bullets)").option("-p, --priority <text...>","bullet line \u2014 repeat for multiple priorities").option("-m, --markdown <md>","raw markdown body (overrides --priority)").option("-f, --file <path>","read markdown from a file").action(async(e,o)=>{let t=mi(e),n=Gn(),s;if(o.file){let{readFileSync:a}=await import("fs");s=a(o.file,"utf-8")}else o.markdown?s=o.markdown:o.priority?.length?s=o.priority.map(a=>`- ${a}`).join(`
438
- `):(console.error(Ne.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(t,s);console.log(Ne.green(` \u2713 ${t} plan saved \u2192 ${i.path}`));let r=ys(s);if(r.length){console.log(Ne.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(Ne.dim(` \u2022 ${a}`))}});wt.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=Gn();if(e){let n=mi(e),s=o.read(n);if(!s){console.log(Ne.dim(` No ${n} plan set.`));return}Mc(s.tier,s.date,s.content);return}let t=o.resolve();if(!t){console.log(Ne.yellow(" No plan set at any tier.")),console.log(Ne.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(Ne.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}Mc(t.tier,t.date,t.content)});wt.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=Gn().list(parseInt(e.limit,10)||20);if(!t.length){console.log(Ne.dim(" No plans yet."));return}for(let n of t)console.log(` ${Ne.cyan(n.tier.padEnd(5))} ${Ne.bold(n.date.padEnd(11))} ${Ne.dim(n.path)}`)});wt.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=mi(e),n=Gn().read(o);if(!n){console.log(Ne.dim(` No ${o} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(Ne.green(` \u2713 ${o} plan cleared (${n.path})`))});function Mc(e,o,t){console.log(Ne.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
439
- `))console.log(` ${s}`);console.log();let n=ys(t);n.length&&console.log(Ne.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as Lp}from"commander";import We from"chalk";we();function Mp(){try{return D().notifications||{}}catch{return{}}}function zn(e){let{summary:o,backupPath:t}=Zo(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(We.green(`
440
- \u2713 ${o}`)),t&&console.log(We.dim(` Backup: ${t}`)),console.log(We.dim(` Restart the daemon (or POST /reload) for the change to take effect.
441
- `))}var bt=new Lp().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");bt.command("show").description("print current notifications config").option("--json","JSON output").action(e=>{let o=Mp();if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.destination){let n=o.destination.accountId?` \xB7 account=${o.destination.accountId}`:"";console.log(` destination ${We.cyan(o.destination.channel+":"+o.destination.chatId)}${We.dim(n)}`)}else console.log(` destination ${We.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${We.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?We.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?We.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":We.dim("off")}`),console.log()});bt.command("route").description("set the destination channel/chatId for notifications").requiredOption("--channel <name>","telegram | whatsapp | slack | discord").requiredOption("--chat-id <id>","native chat id (e.g. -100\u2026, JID, channel id)").option("--account-id <id>","channel account id when the channel is multi-account (telegram with multiple bots)").option("--clear","clear the destination instead of setting it").action(e=>{if(e.clear){zn(o=>(delete o.destination,"notifications destination cleared"));return}zn(o=>(o.destination={channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}},`notifications destination \u2192 ${e.channel}:${e.chatId}${e.accountId?` (account=${e.accountId})`:""}`))});bt.command("event <name> <state>").description("toggle an event: name in {taskComplete, taskError, taskQueued}; state in {on, off}").action((e,o)=>{let t=["taskComplete","taskError","taskQueued"];t.includes(e)||(console.log(We.red(` unknown event "${e}". Pick from: ${t.join(", ")}`)),process.exit(1));let n=o.toLowerCase();["on","off","true","false","1","0"].includes(n)||(console.log(We.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";zn(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});bt.command("threshold <seconds>").description("set the long-task threshold in seconds (0 disables long-task pings)").action(e=>{let o=parseInt(e,10);(!Number.isFinite(o)||o<0)&&(console.log(We.red(" threshold must be a non-negative integer")),process.exit(1)),zn(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});import{Command as Up}from"commander";import Eo from"chalk";import{readdirSync as pi,statSync as Uc,unlinkSync as Fp,rmSync as qp,existsSync as Fc}from"fs";import{resolve as qc,join as Wc}from"path";var Bc=[{dir:".agentx/sessions",label:"Per-day session JSON"},{dir:".agentx/drift",label:"Drift snapshots",recursive:!0},{dir:".agentx/router",label:"Router-decision logs",recursive:!0},{dir:".agentx/patterns",label:"Self-improving pattern store",recursive:!0}];function ui(e,o){if(!Fc(e))return[];let t=[];for(let n of pi(e,{withFileTypes:!0})){let s=Wc(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...ui(s,!0))}return t}var Vn=new Up().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");Vn.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of Bc){let t=qc(process.cwd(),o.dir),n=ui(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=Uc(a);s+=c.size,(i===null||c.mtimeMs<i)&&(i=c.mtimeMs)}catch{}e+=s;let r=i!==null?`${Math.round((Date.now()-i)/864e5)}d`:"\u2014";console.log(` ${Eo.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${Yn(s).padStart(10)} oldest=${r}`)}console.log(Eo.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${Yn(e).padStart(10)} total`)),console.log(),console.log(Eo.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});Vn.command("prune").description("delete files older than --days from each retention target").option("--days <n>","max age in days; everything older is deleted","30").option("--dry-run","list candidates, don't delete").option("--target <name>","limit to one target dir (e.g. .agentx/sessions)").action(e=>{let o=parseInt(e.days,10);(!Number.isFinite(o)||o<1)&&(console.log(Eo.red(" --days must be a positive integer")),process.exit(1));let t=Date.now()-o*864e5,n=e.target,s=0,i=0;console.log(),console.log(Eo.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?Eo.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of Bc){if(n&&r.dir!==n)continue;let a=qc(process.cwd(),r.dir),c=ui(a,!!r.recursive),d=0,g=0;for(let p of c)try{let f=Uc(p);if(f.mtimeMs<t&&(g+=f.size,d++,!e.dryRun))try{Fp(p)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{Jc(a)}catch{}let l=e.dryRun?"would remove":"removed";console.log(` ${Eo.cyan(r.dir.padEnd(22))} ${l} ${String(d).padStart(5)} files (${Yn(g)})`),s+=d,i+=g}console.log(),console.log(Eo.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${Yn(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function Jc(e){if(Fc(e))for(let o of pi(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=Wc(e,o.name);Jc(t);try{pi(t).length===0&&qp(t,{recursive:!1})}catch{}}}function Yn(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}import{Command as Wp}from"commander";import U from"chalk";var Ao=new Wp().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");Ao.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new Xo().list();if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(),console.log(U.dim(" No actions yet. Add one with `agentx actions add` or `agentx actions create`.")),console.log();return}console.log();for(let n of t){let s=n.inputs?.length?U.dim(` (${n.inputs.length} input${n.inputs.length===1?"":"s"})`):"",i=n.kind==="shell"?`shell: ${n.command.slice(0,50)}`:`${n.method} ${n.url.slice(0,50)}`;console.log(` ${U.cyan(n.id.padEnd(24))} ${n.title}${s}`),console.log(` ${" ".repeat(24)} ${U.dim(i)}`)}console.log()});Ao.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new Xo().get(e);if(n||(console.log(U.red(` no action "${e}"`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),console.log(U.bold(` ${n.title}`)),n.description&&console.log(U.dim(` ${n.description}`)),console.log(),console.log(` id ${n.id}`),console.log(` kind ${n.kind}`),console.log(` timeout ${n.timeoutMs}ms`),n.kind==="shell"?(console.log(` command ${n.command}`),n.cwd&&console.log(` cwd ${n.cwd}`),n.env&&console.log(` env ${JSON.stringify(n.env)}`)):(console.log(` ${n.method.padEnd(9)} ${n.url}`),n.headers&&console.log(` headers ${JSON.stringify(n.headers)}`),n.body&&console.log(` body ${n.body.slice(0,200)}`)),n.inputs.length){console.log(),console.log(U.bold(" Inputs:"));for(let s of n.inputs){let i=s.required?U.red("*"):" ",r=s.defaultValue!==void 0?U.dim(` default=${JSON.stringify(s.defaultValue)}`):"",a=s.description?U.dim(` \u2014 ${s.description}`):"";console.log(` ${i} ${U.cyan(s.name)} (${s.type})${r}${a}`)}}console.log()});Ao.command("add <id>").description("add (or replace) an action non-interactively").requiredOption("--title <text>").requiredOption("--kind <kind>","shell | http").option("--description <text>").option("--command <text>","[shell] templated shell command").option("--cwd <path>","[shell] working directory").option("--url <url>","[http] URL").option("--method <m>","[http] GET|POST|PUT|PATCH|DELETE","POST").option("--headers <json>","[http] headers as JSON object").option("--body <text>","[http] body template").option("--inputs <csv>","comma-separated list of name:type[!] (e.g. amount:number!,note:string)").option("--timeout <ms>","timeout in ms (default 30000)","30000").action((e,o)=>{let t=Bp(o.inputs),n={id:e,title:o.title,description:o.description,inputs:t,timeoutMs:parseInt(o.timeout,10)||3e4,kind:o.kind};if(o.kind==="shell")o.command||(console.log(U.red(" --command required for kind=shell")),process.exit(1)),n.command=o.command,o.cwd&&(n.cwd=o.cwd);else if(o.kind==="http"){if(o.url||(console.log(U.red(" --url required for kind=http")),process.exit(1)),n.url=o.url,n.method=o.method,o.headers)try{n.headers=JSON.parse(o.headers)}catch{console.log(U.red(" --headers must be valid JSON")),process.exit(1)}o.body&&(n.body=o.body)}else console.log(U.red(" --kind must be shell|http")),process.exit(1);let s=Wi.safeParse(n);if(!s.success){console.log(U.red(" validation failed:"));for(let a of s.error.issues)console.log(U.red(` ${a.path.join(".")}: ${a.message}`));process.exit(1)}let r=new Xo().save(s.data);console.log(U.green(`
442
- \u2713 action "${r.id}" saved (${r.kind}).`)),console.log(U.dim(` Test: agentx actions run ${r.id}
443
- `))});Ao.command("remove <id>").alias("rm").description("delete an action").action(e=>{new Xo().delete(e)||(console.log(U.red(` no action "${e}"`)),process.exit(1)),console.log(U.green(` \u2713 action "${e}" removed`))});Ao.command("run <id>").description("invoke an action and print its output").option("--input <kv...>","input as key=value (repeat for each)").option("--json","JSON output (full ActionRunResult)").action(async(e,o)=>{let n=new Xo().get(e);n||(console.log(U.red(` no action "${e}"`)),process.exit(1));let s={};for(let i of o.input||[]){let r=i.indexOf("=");r<0&&(console.log(U.red(` --input "${i}" must be key=value`)),process.exit(1)),s[i.slice(0,r)]=i.slice(r+1)}try{let i=await Bi(n,s);if(o.json){console.log(JSON.stringify(i,null,2));return}console.log(),console.log(` ${i.ok?U.green("\u2713 ok"):U.red("\u2717 failed")} status=${i.status} ${i.durationMs}ms`),console.log(),i.output&&(console.log(U.dim(" --- output ---")),console.log(i.output)),i.errors&&(console.log(U.dim(" --- errors ---")),console.log(U.red(i.errors))),console.log(),i.ok||process.exit(1)}catch(i){console.log(U.red(` ${i.message}`)),process.exit(1)}});Ao.command("builtin [name]").description("list registered built-in actions, or run one with --input").option("--input <json>","JSON input matching the action's inputSchema").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output (omit chrome)").option("--schema","show the action's input/output schema instead of running it").action(async(e,o)=>{let t=String(o.daemon).replace(/\/+$/,"");if(!e){try{let s=await fetch(`${t}/api/actions/builtin`);s.ok||(console.log(U.red(` list failed (${s.status}): ${(await s.text()).slice(0,200)}`)),process.exit(1));let r=(await s.json()).actions||[];if(o.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(U.dim(" No built-in actions registered. Daemon may not be running, or registerAllBuiltins() didn't fire at boot."));return}console.log(),console.log(U.bold(" Built-in typed actions")),console.log(U.dim(" Invoke: agentx actions builtin <name> --input '<json>'")),console.log();for(let a of r){let c=a.timeoutMs?U.dim(` (timeout=${Math.round(a.timeoutMs/1e3)}s)`):"";console.log(` ${U.cyan(a.name.padEnd(22))} ${a.description||""}${c}`)}console.log()}catch(s){console.log(U.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}return}if(o.schema){try{let r=((await(await fetch(`${t}/api/actions/builtin`)).json()).actions||[]).find(a=>a.name===e);if(r||(console.log(U.red(` unknown action: ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(U.bold(` ${r.name}`)),r.description&&console.log(U.dim(` ${r.description}`)),console.log(),console.log(U.dim(" --- input schema ---")),console.log(JSON.stringify(r.inputSchema??{},null,2)),r.outputSchema&&(console.log(),console.log(U.dim(" --- output schema ---")),console.log(JSON.stringify(r.outputSchema,null,2))),console.log()}catch(s){console.log(U.red(` schema fetch failed: ${s.message||s}`)),process.exit(1)}return}let n={};if(o.input)try{n=JSON.parse(o.input)}catch(s){console.log(U.red(` --input must be valid JSON: ${s.message}`)),process.exit(1)}try{let s=await fetch(`${t}/api/actions/builtin/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json().catch(()=>({}));if(s.ok||(o.json&&(console.log(JSON.stringify(i,null,2)),process.exit(1)),console.log(U.red(` action failed (${s.status}): ${i.error||JSON.stringify(i).slice(0,300)}`)),process.exit(1)),o.json){console.log(JSON.stringify(i,null,2));return}console.log(JSON.stringify(i,null,2))}catch(s){console.log(U.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}});function Bp(e){if(!e)return[];let o=[];for(let t of e.split(",").map(n=>n.trim()).filter(Boolean)){let n=t.endsWith("!"),s=n?t.slice(0,-1):t,i=s.indexOf(":"),r=i>=0?s.slice(0,i):s,a=i>=0?s.slice(i+1):"string";o.push({name:r,type:a,required:n})}return o}we();import{Command as Jp}from"commander";import Q from"chalk";var Hc=new Jp().name("watch").description("stream live daemon events \u2014 workflow runs, user tasks, signals, mesh health").option("-c, --config <path>","daemon config file").option("-t, --type <kinds>","comma-separated event kinds (run,task,signal,mesh,channel,status)").option("-w, --workflow <id>","only events for this workflow id").option("-a, --actor <id>","only task events involving this actor id").option("-r, --run <id>","only events for this run id").option("--channel <name>","only channel events on this channel (telegram/whatsapp/\u2026)").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let r=D(e.config);o||(o=r.dashboard?.daemonUrl||""),t||(t=r.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n=[];typeof e.type=="string"&&n.push(`type=${encodeURIComponent(e.type)}`),typeof e.workflow=="string"&&n.push(`workflow=${encodeURIComponent(e.workflow)}`),typeof e.actor=="string"&&n.push(`actor=${encodeURIComponent(e.actor)}`),typeof e.run=="string"&&n.push(`run=${encodeURIComponent(e.run)}`),typeof e.channel=="string"&&n.push(`channel=${encodeURIComponent(e.channel)}`);let s=`${o.replace(/\/+$/,"")}/events${n.length?`?${n.join("&")}`:""}`;console.log(Q.dim(` connecting to ${s}`));let i={Accept:"text/event-stream"};t&&(i.Authorization=`Bearer ${t}`);try{let r=await fetch(s,{headers:i});(!r.ok||!r.body)&&(console.error(Q.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(Q.green(" connected \u2014 Ctrl-C to stop")),console.log("");let a=r.body.getReader(),c=new TextDecoder,d="";for(;;){let{done:g,value:l}=await a.read();if(g)break;d+=c.decode(l,{stream:!0});let p;for(;(p=d.indexOf(`
444
-
445
- `))>=0;){let f=d.slice(0,p);d=d.slice(p+2),Hp(f)}}}catch(r){console.error(Q.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function Hp(e){let o="message",t="";for(let i of e.split(`
446
- `))i.startsWith("event: ")?o=i.slice(7):i.startsWith("data: ")&&(t=i.slice(6));if(!t)return;let n={};try{n=JSON.parse(t)}catch{console.log(`${o}: ${t}`);return}let s=n.at?Q.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=Q.cyan(n.phase?.padEnd(9)??"run"),r=Q.bold(n.workflowId??""),a=Q.dim((n.runId??"").slice(0,8)),c=n.nodeId?Q.yellow(n.nodeId):"",d=n.note?Q.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${d}`);break}case"task":{let i=Q.magenta(`task.${n.phase}`.padEnd(14)),r=Q.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?Q.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${Q.cyan(a)} ${c}`);break}case"signal":{let i=Q.green("signal".padEnd(9)),r=Q.bold(n.name),a=Q.dim(`(${n.scope})`),c=n.workflowId?Q.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=Q.blue("mesh".padEnd(9)),r=Q.bold(n.peer),a=n.healthy?Q.green("\u2713 healthy"):Q.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${Q.dim(n.delta??"")}`);break}case"channel":{let i=Q.yellow("channel".padEnd(9)),r=n.direction==="in"?Q.cyan("\u2190"):Q.magenta("\u2192"),a=Q.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?Q.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(Q.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${o} ${JSON.stringify(n)}`)}}import{Command as zp}from"commander";import Kn from"chalk";import{spawn as Yp}from"node:child_process";import{execFileSync as Gp}from"node:child_process";function Gc(e=()=>Gp("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let o;try{o=e().trim()}catch(n){return{ok:!1,reason:n?.code==="ENOENT"?"OpenCode is not installed or is not on PATH.":`Could not run opencode --version: ${n?.message||String(n)}`}}let t=o.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return t?Number(t[1])<2?{ok:!1,reason:`OpenCode ${o} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:o}:{ok:!1,reason:`Could not recognize the OpenCode version: ${o||"empty output"}`}}var zc=new zp().name("tui").description("open the AgentX console in OpenCode").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","daemon mesh bearer token for remote nodes").option("--agent <id>","AgentX agent to use as the OpenCode model").option("--legacy","open the built-in Ink terminal UI").option("--poll <ms>","legacy UI snapshot poll interval in ms","3000").action(async e=>{process.stdout.isTTY||(console.error(Kn.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-6BGTH2TT.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:Gc();if(n?.ok){let{fetchAgents:d}=await import("./client-6BGTH2TT.js"),g=await d(t);if(!g.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let l=e.agent||g[0].id;if(!g.some(y=>y.id===l))throw new Error(`Unknown AgentX agent: ${l}`);let p={};try{p=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(y=>[y.id,{name:`AgentX ${y.name||y.id}`}])),u={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...p,model:`agentx/${l}`,providers:{...p.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:f}}})};console.error(Kn.dim(`Opening ${n.version} with AgentX model ${l}.`));let w=Yp("opencode",["--standalone"],{stdio:"inherit",env:u});await new Promise((y,$)=>{w.once("error",$),w.once("exit",b=>b===0?y():$(new Error(`OpenCode exited with code ${b??"unknown"}`)))});return}n&&!n.ok&&(console.error(Kn.yellow(n.reason)),console.error(Kn.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-HSRGG5VA.js"),{render:i}=await import("ink"),r=(await import("react")).default,a=Math.max(500,Number(e.poll)||3e3);await i(r.createElement(s,{conn:t,pollMs:a})).waitUntilExit()});import{Command as Vp}from"commander";import V from"chalk";import{randomUUID as Kc}from"crypto";import{createInterface as Kp}from"node:readline/promises";import Xp from"ora";import Xn from"chalk";function Yc(e){console.error(),console.error(Xn.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(Xn.dim(` ${e.why}`)),console.error(),console.error(` Use ${Xn.cyan(e.instead)} instead.`),e.note&&console.error(Xn.dim(` ${e.note}`)),console.error()}var Vc={why:"No recorded use on any node since 2026-07-03.",instead:"agentx attach <agent>",note:"Wears the identity in the Claude Code session you already have open \u2014 see docs/reference/attach.md"};var Xc=new Vp().name("chat").description("[deprecated \u2014 see agentx attach] interactive chat with a daemon-registered agent").argument("[agent]","agent id to talk to (with or without leading @)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").option("--channel <name>","logical channel name passed in context","chat-cli").option("--chat-id <id>","resume an existing chatId (otherwise a fresh one is generated)").action(async(e,o)=>{Yc({what:"agentx chat",...Vc});let t=Gr({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${Kc().slice(0,12)}`,r=[];try{r=await hn(t)}catch(g){console.error(V.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(V.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(V.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(V.red(` unknown agent: @${n}`)),console.error(V.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(V.dim(` no agent given \u2014 defaulting to @${n}`))),process.stdout.isTTY&&process.stdin.isTTY){let{render:g}=await import("ink"),{ChatApp:l}=await import("./ChatApp-4FOU6Q3S.js"),p=(await import("react")).default;await g(p.createElement(l,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}Zp(t.baseUrl,n,i,s);let a=Kp({input:process.stdin,output:process.stdout}),c=!1,d=!1;for(a.on("close",()=>{if(c){d=!0;return}console.log(V.dim(`
447
- bye`)),process.exit(0)});;){let g;try{g=(await a.question(V.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(V.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${Kc().slice(0,12)}`,console.log(V.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let u=await hn(t);for(let w of u){let y=w.id===n?V.green("\u25CF"):V.dim("\u25CB");console.log(` ${y} @${w.id} ${V.dim(w.tier)} ${w.model??""}`)}}catch(u){console.error(V.red(` failed to list agents: ${u?.message||u}`))}continue}if(g.startsWith("/agent ")){let u=g.slice(7).replace(/^@/,"").trim();if(!u){console.log(V.red(" usage: /agent <id>"));continue}try{if(!(await hn(t)).find(y=>y.id===u)){console.log(V.red(` unknown agent: @${u}`));continue}n=u,console.log(V.dim(` now talking to @${n}`))}catch(w){console.error(V.red(` failed to switch agent: ${w?.message||w}`))}continue}if(g.startsWith("/")){console.log(V.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(V.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let l=Xp({text:`@${n}\u2026`,color:"cyan"}).start(),p=Date.now(),f=Qp(n);try{let u=await zr(t,n,g,{channel:s,chatId:i,onText:y=>{l.stop(),f.text(y)},onThinking:()=>{},onTool:y=>{l.stop(),f.tool(y)}});l.stop();let w=Math.round((Date.now()-p)/100)/10;u.error?f.finishError(u.error):f.finish(w,u.usage)}catch(u){l.stop(),f.finishError(u?.message||String(u))}finally{c=!1}if(d){console.log(V.dim(" bye"));return}}});function Qp(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${V.green(`@${e}`)}
471
+ `))}function ts(){try{return _().business||{}}catch{return{}}}var kt=new wu().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");kt.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=ts();if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o||!o.enabled){console.log(),console.log(te.yellow(" business block not enabled (or missing).")),console.log(te.dim(" Add a `business` key to agentx.json to opt in.")),console.log();return}let t=o.orgChart||{},n=o.projects||[],s=o.contactMap||[];console.log(),console.log(te.bold(" Org chart"));let i=Object.entries(t);if(i.length===0)console.log(te.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?te.dim(` \u2192 reports to ${a.reportsTo}`):"",d=a.schedule?te.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${te.cyan(r)} ${a.role}${c}${d}`)}if(console.log(),console.log(te.bold(` Projects (${n.length})`)),n.length===0)console.log(te.dim(" (empty)"));else for(let r of n){let a=r.pm?te.dim(` \xB7 pm=${r.pm}`):"",c=r.client?te.dim(` \xB7 client=${r.client}`):"";console.log(` ${te.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(te.bold(` Contact map (${s.length})`)),s.length===0)console.log(te.dim(" (empty)"));else for(let r of s){let a=r.chatId?`chatId=${r.chatId}`:r.username?`username=${r.username}`:r.senderId?`senderId=${r.senderId}`:"?",c=r.channel?`${r.channel}/`:"";console.log(` ${te.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?te.dim(` (${r.displayName})`):""}`)}console.log()});var ki=kt.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");ki.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=ts(),t=Object.entries(o.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(t),null,2));return}if(t.length===0){console.log(te.dim(" no entries"));return}for(let[n,s]of t)console.log(` ${te.cyan(n)} ${s.role}${s.reportsTo?te.dim(` \u2192 ${s.reportsTo}`):""}`)});ki.command("add <agentId>").description("add or update an orgChart entry for an agent").requiredOption("--role <role>","role title (e.g. 'PM', 'Coder', 'DevOps')").option("--reports-to <agentId>","manager's agentId").option("--start <hh:mm>","schedule start","09:00").option("--end <hh:mm>","schedule end","17:00").option("--days <csv>","working days (mon,tue,wed,thu,fri)","mon,tue,wed,thu,fri").option("--utilization <0..1>","target utilization","0.8").action((e,o)=>{let t=String(o.days).split(",").map(n=>n.trim()).filter(Boolean);$t(n=>(n.business=n.business||{},n.business.orgChart=n.business.orgChart||{},n.business.orgChart[e]={role:o.role,...o.reportsTo?{reportsTo:o.reportsTo}:{},schedule:{days:t,start:o.start,end:o.end},utilizationTarget:parseFloat(o.utilization)||.8},`orgChart entry "${e}" upserted (role=${o.role}${o.reportsTo?`, reports to ${o.reportsTo}`:""})`))});ki.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{$t(o=>{if(!o.business?.orgChart||!(e in o.business.orgChart))throw new Error(`no orgChart entry for "${e}"`);return delete o.business.orgChart[e],`orgChart entry "${e}" removed`})});var vi=kt.command("project").description("manage business.projects \u2014 id, pm, client");vi.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=ts().projects||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(te.dim(" no projects"));return}for(let n of t)console.log(` ${te.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});vi.command("add <id>").description("add or update a project entry").option("--pm <agentId>","PM responsible for this project (drives PM gate)").option("--client <name>","client this project belongs to (drives activity-graph attribution)").action((e,o)=>{$t(t=>{t.business=t.business||{},t.business.projects=t.business.projects||[];let n=t.business.projects.findIndex(i=>i.id===e),s={id:e,...o.pm?{pm:o.pm}:{},...o.client?{client:o.client}:{}};return n>=0?t.business.projects[n]={...t.business.projects[n],...s}:t.business.projects.push(s),n>=0?`project "${e}" updated`:`project "${e}" added`})});vi.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{$t(o=>{let t=o.business?.projects||[],n=t.length;if(o.business.projects=t.filter(s=>s.id!==e),o.business.projects.length===n)throw new Error(`no project "${e}"`);return`project "${e}" removed`})});var xi=kt.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");xi.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let t=ts().contactMap||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(te.dim(" no entries"));return}for(let n of t){let s=n.chatId?`chatId=${n.chatId}`:n.username?`username=${n.username}`:n.senderId?`senderId=${n.senderId}`:"?";console.log(` ${n.channel?n.channel+"/":""}${te.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});xi.command("add").description("add a contactMap entry").requiredOption("--client <name>","client this contact belongs to").option("--channel <name>","telegram | whatsapp | slack | discord").option("--chat-id <id>","native chat id (e.g. -100\u2026, JID)").option("--username <handle>","sender username/handle").option("--sender-id <id>","numeric sender id (when username is unstable)").option("--project <id>","project this traffic should attribute to").option("--display-name <name>","display-name override for the initiator pill").action(e=>{!e.chatId&&!e.username&&!e.senderId&&(console.log(te.red(" one of --chat-id / --username / --sender-id is required")),process.exit(1)),$t(o=>{o.business=o.business||{},o.business.contactMap=o.business.contactMap||[];let t={client:e.client};e.channel&&(t.channel=e.channel),e.chatId&&(t.chatId=e.chatId),e.username&&(t.username=e.username),e.senderId&&(t.senderId=e.senderId),e.project&&(t.project=e.project),e.displayName&&(t.displayName=e.displayName),o.business.contactMap.push(t);let n=e.chatId||e.username||e.senderId;return`contact ${e.channel?e.channel+"/":""}${n} \u2192 ${e.client}${e.project?"/"+e.project:""} added`})});xi.command("remove").alias("rm").description("remove a contactMap entry by matching field(s)").option("--channel <name>").option("--chat-id <id>").option("--username <handle>").option("--sender-id <id>").action(e=>{$t(o=>{let t=o.business?.contactMap||[],n=t.length;if(o.business.contactMap=t.filter(s=>!!(e.channel&&s.channel!==e.channel||e.chatId&&s.chatId!==e.chatId||e.username&&s.username!==e.username||e.senderId&&s.senderId!==e.senderId)),o.business.contactMap.length===n)throw new Error("no matching contact entry");return`${n-o.business.contactMap.length} contact entry/entries removed`})});import{Command as bu}from"commander";import Ne from"chalk";pe();var $u={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function Si(e){let o=$u[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function ns(){let o=_().business?.standup?.plansDir||".agentx/plans";return new zr(o)}var vt=new bu().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");vt.command("set <tier>").description("write a plan for today | week | month (priorities-as-bullets)").option("-p, --priority <text...>","bullet line \u2014 repeat for multiple priorities").option("-m, --markdown <md>","raw markdown body (overrides --priority)").option("-f, --file <path>","read markdown from a file").action(async(e,o)=>{let t=Si(e),n=ns(),s;if(o.file){let{readFileSync:a}=await import("fs");s=a(o.file,"utf-8")}else o.markdown?s=o.markdown:o.priority?.length?s=o.priority.map(a=>`- ${a}`).join(`
472
+ `):(console.error(Ne.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(t,s);console.log(Ne.green(` \u2713 ${t} plan saved \u2192 ${i.path}`));let r=Ts(s);if(r.length){console.log(Ne.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(Ne.dim(` \u2022 ${a}`))}});vt.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=ns();if(e){let n=Si(e),s=o.read(n);if(!s){console.log(Ne.dim(` No ${n} plan set.`));return}nl(s.tier,s.date,s.content);return}let t=o.resolve();if(!t){console.log(Ne.yellow(" No plan set at any tier.")),console.log(Ne.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(Ne.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}nl(t.tier,t.date,t.content)});vt.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=ns().list(parseInt(e.limit,10)||20);if(!t.length){console.log(Ne.dim(" No plans yet."));return}for(let n of t)console.log(` ${Ne.cyan(n.tier.padEnd(5))} ${Ne.bold(n.date.padEnd(11))} ${Ne.dim(n.path)}`)});vt.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=Si(e),n=ns().read(o);if(!n){console.log(Ne.dim(` No ${o} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(Ne.green(` \u2713 ${o} plan cleared (${n.path})`))});function nl(e,o,t){console.log(Ne.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
473
+ `))console.log(` ${s}`);console.log();let n=Ts(t);n.length&&console.log(Ne.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as ku}from"commander";import Be from"chalk";pe();function vu(){try{return _().notifications||{}}catch{return{}}}function ss(e){let{summary:o,backupPath:t}=nt(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(Be.green(`
474
+ \u2713 ${o}`)),t&&console.log(Be.dim(` Backup: ${t}`)),console.log(Be.dim(` Restart the daemon (or POST /reload) for the change to take effect.
475
+ `))}var xt=new ku().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");xt.command("show").description("print current notifications config").option("--json","JSON output").action(e=>{let o=vu();if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.destination){let n=o.destination.accountId?` \xB7 account=${o.destination.accountId}`:"";console.log(` destination ${Be.cyan(o.destination.channel+":"+o.destination.chatId)}${Be.dim(n)}`)}else console.log(` destination ${Be.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${Be.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?Be.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?Be.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":Be.dim("off")}`),console.log()});xt.command("route").description("set the destination channel/chatId for notifications").requiredOption("--channel <name>","telegram | whatsapp | slack | discord").requiredOption("--chat-id <id>","native chat id (e.g. -100\u2026, JID, channel id)").option("--account-id <id>","channel account id when the channel is multi-account (telegram with multiple bots)").option("--clear","clear the destination instead of setting it").action(e=>{if(e.clear){ss(o=>(delete o.destination,"notifications destination cleared"));return}ss(o=>(o.destination={channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}},`notifications destination \u2192 ${e.channel}:${e.chatId}${e.accountId?` (account=${e.accountId})`:""}`))});xt.command("event <name> <state>").description("toggle an event: name in {taskComplete, taskError, taskQueued}; state in {on, off}").action((e,o)=>{let t=["taskComplete","taskError","taskQueued"];t.includes(e)||(console.log(Be.red(` unknown event "${e}". Pick from: ${t.join(", ")}`)),process.exit(1));let n=o.toLowerCase();["on","off","true","false","1","0"].includes(n)||(console.log(Be.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";ss(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});xt.command("threshold <seconds>").description("set the long-task threshold in seconds (0 disables long-task pings)").action(e=>{let o=parseInt(e,10);(!Number.isFinite(o)||o<0)&&(console.log(Be.red(" threshold must be a non-negative integer")),process.exit(1)),ss(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});import{Command as xu}from"commander";import Oo from"chalk";import{readdirSync as Ei,statSync as sl,unlinkSync as Su,rmSync as Eu,existsSync as il}from"fs";import{resolve as rl,join as al}from"path";var cl=[{dir:".agentx/sessions",label:"Per-day session JSON"},{dir:".agentx/drift",label:"Drift snapshots",recursive:!0},{dir:".agentx/router",label:"Router-decision logs",recursive:!0},{dir:".agentx/patterns",label:"Self-improving pattern store",recursive:!0}];function Ai(e,o){if(!il(e))return[];let t=[];for(let n of Ei(e,{withFileTypes:!0})){let s=al(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...Ai(s,!0))}return t}var rs=new xu().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");rs.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of cl){let t=rl(process.cwd(),o.dir),n=Ai(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=sl(a);s+=c.size,(i===null||c.mtimeMs<i)&&(i=c.mtimeMs)}catch{}e+=s;let r=i!==null?`${Math.round((Date.now()-i)/864e5)}d`:"\u2014";console.log(` ${Oo.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${is(s).padStart(10)} oldest=${r}`)}console.log(Oo.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${is(e).padStart(10)} total`)),console.log(),console.log(Oo.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});rs.command("prune").description("delete files older than --days from each retention target").option("--days <n>","max age in days; everything older is deleted","30").option("--dry-run","list candidates, don't delete").option("--target <name>","limit to one target dir (e.g. .agentx/sessions)").action(e=>{let o=parseInt(e.days,10);(!Number.isFinite(o)||o<1)&&(console.log(Oo.red(" --days must be a positive integer")),process.exit(1));let t=Date.now()-o*864e5,n=e.target,s=0,i=0;console.log(),console.log(Oo.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?Oo.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of cl){if(n&&r.dir!==n)continue;let a=rl(process.cwd(),r.dir),c=Ai(a,!!r.recursive),d=0,g=0;for(let p of c)try{let f=sl(p);if(f.mtimeMs<t&&(g+=f.size,d++,!e.dryRun))try{Su(p)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{ll(a)}catch{}let l=e.dryRun?"would remove":"removed";console.log(` ${Oo.cyan(r.dir.padEnd(22))} ${l} ${String(d).padStart(5)} files (${is(g)})`),s+=d,i+=g}console.log(),console.log(Oo.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${is(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function ll(e){if(il(e))for(let o of Ei(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=al(e,o.name);ll(t);try{Ei(t).length===0&&Eu(t,{recursive:!1})}catch{}}}function is(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}import{Command as Au}from"commander";import F from"chalk";var To=new Au().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");To.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new et().list();if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(),console.log(F.dim(" No actions yet. Add one with `agentx actions add` or `agentx actions create`.")),console.log();return}console.log();for(let n of t){let s=n.inputs?.length?F.dim(` (${n.inputs.length} input${n.inputs.length===1?"":"s"})`):"",i=n.kind==="shell"?`shell: ${n.command.slice(0,50)}`:`${n.method} ${n.url.slice(0,50)}`;console.log(` ${F.cyan(n.id.padEnd(24))} ${n.title}${s}`),console.log(` ${" ".repeat(24)} ${F.dim(i)}`)}console.log()});To.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new et().get(e);if(n||(console.log(F.red(` no action "${e}"`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),console.log(F.bold(` ${n.title}`)),n.description&&console.log(F.dim(` ${n.description}`)),console.log(),console.log(` id ${n.id}`),console.log(` kind ${n.kind}`),console.log(` timeout ${n.timeoutMs}ms`),n.kind==="shell"?(console.log(` command ${n.command}`),n.cwd&&console.log(` cwd ${n.cwd}`),n.env&&console.log(` env ${JSON.stringify(n.env)}`)):(console.log(` ${n.method.padEnd(9)} ${n.url}`),n.headers&&console.log(` headers ${JSON.stringify(n.headers)}`),n.body&&console.log(` body ${n.body.slice(0,200)}`)),n.inputs.length){console.log(),console.log(F.bold(" Inputs:"));for(let s of n.inputs){let i=s.required?F.red("*"):" ",r=s.defaultValue!==void 0?F.dim(` default=${JSON.stringify(s.defaultValue)}`):"",a=s.description?F.dim(` \u2014 ${s.description}`):"";console.log(` ${i} ${F.cyan(s.name)} (${s.type})${r}${a}`)}}console.log()});To.command("add <id>").description("add (or replace) an action non-interactively").requiredOption("--title <text>").requiredOption("--kind <kind>","shell | http").option("--description <text>").option("--command <text>","[shell] templated shell command").option("--cwd <path>","[shell] working directory").option("--url <url>","[http] URL").option("--method <m>","[http] GET|POST|PUT|PATCH|DELETE","POST").option("--headers <json>","[http] headers as JSON object").option("--body <text>","[http] body template").option("--inputs <csv>","comma-separated list of name:type[!] (e.g. amount:number!,note:string)").option("--timeout <ms>","timeout in ms (default 30000)","30000").action((e,o)=>{let t=Ou(o.inputs),n={id:e,title:o.title,description:o.description,inputs:t,timeoutMs:parseInt(o.timeout,10)||3e4,kind:o.kind};if(o.kind==="shell")o.command||(console.log(F.red(" --command required for kind=shell")),process.exit(1)),n.command=o.command,o.cwd&&(n.cwd=o.cwd);else if(o.kind==="http"){if(o.url||(console.log(F.red(" --url required for kind=http")),process.exit(1)),n.url=o.url,n.method=o.method,o.headers)try{n.headers=JSON.parse(o.headers)}catch{console.log(F.red(" --headers must be valid JSON")),process.exit(1)}o.body&&(n.body=o.body)}else console.log(F.red(" --kind must be shell|http")),process.exit(1);let s=er.safeParse(n);if(!s.success){console.log(F.red(" validation failed:"));for(let a of s.error.issues)console.log(F.red(` ${a.path.join(".")}: ${a.message}`));process.exit(1)}let r=new et().save(s.data);console.log(F.green(`
476
+ \u2713 action "${r.id}" saved (${r.kind}).`)),console.log(F.dim(` Test: agentx actions run ${r.id}
477
+ `))});To.command("remove <id>").alias("rm").description("delete an action").action(e=>{new et().delete(e)||(console.log(F.red(` no action "${e}"`)),process.exit(1)),console.log(F.green(` \u2713 action "${e}" removed`))});To.command("run <id>").description("invoke an action and print its output").option("--input <kv...>","input as key=value (repeat for each)").option("--json","JSON output (full ActionRunResult)").action(async(e,o)=>{let n=new et().get(e);n||(console.log(F.red(` no action "${e}"`)),process.exit(1));let s={};for(let i of o.input||[]){let r=i.indexOf("=");r<0&&(console.log(F.red(` --input "${i}" must be key=value`)),process.exit(1)),s[i.slice(0,r)]=i.slice(r+1)}try{let i=await or(n,s);if(o.json){console.log(JSON.stringify(i,null,2));return}console.log(),console.log(` ${i.ok?F.green("\u2713 ok"):F.red("\u2717 failed")} status=${i.status} ${i.durationMs}ms`),console.log(),i.output&&(console.log(F.dim(" --- output ---")),console.log(i.output)),i.errors&&(console.log(F.dim(" --- errors ---")),console.log(F.red(i.errors))),console.log(),i.ok||process.exit(1)}catch(i){console.log(F.red(` ${i.message}`)),process.exit(1)}});To.command("builtin [name]").description("list registered built-in actions, or run one with --input").option("--input <json>","JSON input matching the action's inputSchema").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output (omit chrome)").option("--schema","show the action's input/output schema instead of running it").action(async(e,o)=>{let t=String(o.daemon).replace(/\/+$/,"");if(!e){try{let s=await fetch(`${t}/api/actions/builtin`);s.ok||(console.log(F.red(` list failed (${s.status}): ${(await s.text()).slice(0,200)}`)),process.exit(1));let r=(await s.json()).actions||[];if(o.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(F.dim(" No built-in actions registered. Daemon may not be running, or registerAllBuiltins() didn't fire at boot."));return}console.log(),console.log(F.bold(" Built-in typed actions")),console.log(F.dim(" Invoke: agentx actions builtin <name> --input '<json>'")),console.log();for(let a of r){let c=a.timeoutMs?F.dim(` (timeout=${Math.round(a.timeoutMs/1e3)}s)`):"";console.log(` ${F.cyan(a.name.padEnd(22))} ${a.description||""}${c}`)}console.log()}catch(s){console.log(F.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}return}if(o.schema){try{let r=((await(await fetch(`${t}/api/actions/builtin`)).json()).actions||[]).find(a=>a.name===e);if(r||(console.log(F.red(` unknown action: ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(F.bold(` ${r.name}`)),r.description&&console.log(F.dim(` ${r.description}`)),console.log(),console.log(F.dim(" --- input schema ---")),console.log(JSON.stringify(r.inputSchema??{},null,2)),r.outputSchema&&(console.log(),console.log(F.dim(" --- output schema ---")),console.log(JSON.stringify(r.outputSchema,null,2))),console.log()}catch(s){console.log(F.red(` schema fetch failed: ${s.message||s}`)),process.exit(1)}return}let n={};if(o.input)try{n=JSON.parse(o.input)}catch(s){console.log(F.red(` --input must be valid JSON: ${s.message}`)),process.exit(1)}try{let s=await fetch(`${t}/api/actions/builtin/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json().catch(()=>({}));if(s.ok||(o.json&&(console.log(JSON.stringify(i,null,2)),process.exit(1)),console.log(F.red(` action failed (${s.status}): ${i.error||JSON.stringify(i).slice(0,300)}`)),process.exit(1)),o.json){console.log(JSON.stringify(i,null,2));return}console.log(JSON.stringify(i,null,2))}catch(s){console.log(F.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}});function Ou(e){if(!e)return[];let o=[];for(let t of e.split(",").map(n=>n.trim()).filter(Boolean)){let n=t.endsWith("!"),s=n?t.slice(0,-1):t,i=s.indexOf(":"),r=i>=0?s.slice(0,i):s,a=i>=0?s.slice(i+1):"string";o.push({name:r,type:a,required:n})}return o}pe();import{Command as Tu}from"commander";import Q from"chalk";var dl=new Tu().name("watch").description("stream live daemon events \u2014 workflow runs, user tasks, signals, mesh health").option("-c, --config <path>","daemon config file").option("-t, --type <kinds>","comma-separated event kinds (run,task,signal,mesh,channel,status)").option("-w, --workflow <id>","only events for this workflow id").option("-a, --actor <id>","only task events involving this actor id").option("-r, --run <id>","only events for this run id").option("--channel <name>","only channel events on this channel (telegram/whatsapp/\u2026)").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let r=_(e.config);o||(o=r.dashboard?.daemonUrl||""),t||(t=r.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n=[];typeof e.type=="string"&&n.push(`type=${encodeURIComponent(e.type)}`),typeof e.workflow=="string"&&n.push(`workflow=${encodeURIComponent(e.workflow)}`),typeof e.actor=="string"&&n.push(`actor=${encodeURIComponent(e.actor)}`),typeof e.run=="string"&&n.push(`run=${encodeURIComponent(e.run)}`),typeof e.channel=="string"&&n.push(`channel=${encodeURIComponent(e.channel)}`);let s=`${o.replace(/\/+$/,"")}/events${n.length?`?${n.join("&")}`:""}`;console.log(Q.dim(` connecting to ${s}`));let i={Accept:"text/event-stream"};t&&(i.Authorization=`Bearer ${t}`);try{let r=await fetch(s,{headers:i});(!r.ok||!r.body)&&(console.error(Q.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(Q.green(" connected \u2014 Ctrl-C to stop")),console.log("");let a=r.body.getReader(),c=new TextDecoder,d="";for(;;){let{done:g,value:l}=await a.read();if(g)break;d+=c.decode(l,{stream:!0});let p;for(;(p=d.indexOf(`
478
+
479
+ `))>=0;){let f=d.slice(0,p);d=d.slice(p+2),Iu(f)}}}catch(r){console.error(Q.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function Iu(e){let o="message",t="";for(let i of e.split(`
480
+ `))i.startsWith("event: ")?o=i.slice(7):i.startsWith("data: ")&&(t=i.slice(6));if(!t)return;let n={};try{n=JSON.parse(t)}catch{console.log(`${o}: ${t}`);return}let s=n.at?Q.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=Q.cyan(n.phase?.padEnd(9)??"run"),r=Q.bold(n.workflowId??""),a=Q.dim((n.runId??"").slice(0,8)),c=n.nodeId?Q.yellow(n.nodeId):"",d=n.note?Q.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${d}`);break}case"task":{let i=Q.magenta(`task.${n.phase}`.padEnd(14)),r=Q.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?Q.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${Q.cyan(a)} ${c}`);break}case"signal":{let i=Q.green("signal".padEnd(9)),r=Q.bold(n.name),a=Q.dim(`(${n.scope})`),c=n.workflowId?Q.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=Q.blue("mesh".padEnd(9)),r=Q.bold(n.peer),a=n.healthy?Q.green("\u2713 healthy"):Q.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${Q.dim(n.delta??"")}`);break}case"channel":{let i=Q.yellow("channel".padEnd(9)),r=n.direction==="in"?Q.cyan("\u2190"):Q.magenta("\u2192"),a=Q.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?Q.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(Q.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${o} ${JSON.stringify(n)}`)}}import{Command as Cu}from"commander";import as from"chalk";import{spawn as Nu}from"node:child_process";import{execFileSync as ju}from"node:child_process";function gl(e=()=>ju("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let o;try{o=e().trim()}catch(n){return{ok:!1,reason:n?.code==="ENOENT"?"OpenCode is not installed or is not on PATH.":`Could not run opencode --version: ${n?.message||String(n)}`}}let t=o.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return t?Number(t[1])<2?{ok:!1,reason:`OpenCode ${o} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:o}:{ok:!1,reason:`Could not recognize the OpenCode version: ${o||"empty output"}`}}var ml=new Cu().name("tui").description("open the AgentX console in OpenCode").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","daemon mesh bearer token for remote nodes").option("--agent <id>","AgentX agent to use as the OpenCode model").option("--legacy","open the built-in Ink terminal UI").option("--poll <ms>","legacy UI snapshot poll interval in ms","3000").action(async e=>{process.stdout.isTTY||(console.error(as.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-6BGTH2TT.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:gl();if(n?.ok){let{fetchAgents:d}=await import("./client-6BGTH2TT.js"),g=await d(t);if(!g.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let l=e.agent||g[0].id;if(!g.some(y=>y.id===l))throw new Error(`Unknown AgentX agent: ${l}`);let p={};try{p=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(y=>[y.id,{name:`AgentX ${y.name||y.id}`}])),u={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...p,model:`agentx/${l}`,providers:{...p.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:f}}})};console.error(as.dim(`Opening ${n.version} with AgentX model ${l}.`));let w=Nu("opencode",["--standalone"],{stdio:"inherit",env:u});await new Promise((y,k)=>{w.once("error",k),w.once("exit",b=>b===0?y():k(new Error(`OpenCode exited with code ${b??"unknown"}`)))});return}n&&!n.ok&&(console.error(as.yellow(n.reason)),console.error(as.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-HSRGG5VA.js"),{render:i}=await import("ink"),r=(await import("react")).default,a=Math.max(500,Number(e.poll)||3e3);await i(r.createElement(s,{conn:t,pollMs:a})).waitUntilExit()});import{Command as Ru}from"commander";import V from"chalk";import{randomUUID as fl}from"crypto";import{createInterface as Du}from"node:readline/promises";import _u from"ora";import cs from"chalk";function pl(e){console.error(),console.error(cs.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(cs.dim(` ${e.why}`)),console.error(),console.error(` Use ${cs.cyan(e.instead)} instead.`),e.note&&console.error(cs.dim(` ${e.note}`)),console.error()}var ul={why:"No recorded use on any node since 2026-07-03.",instead:"agentx attach <agent>",note:"Wears the identity in the Claude Code session you already have open \u2014 see docs/reference/attach.md"};var hl=new Ru().name("chat").description("[deprecated \u2014 see agentx attach] interactive chat with a daemon-registered agent").argument("[agent]","agent id to talk to (with or without leading @)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").option("--channel <name>","logical channel name passed in context","chat-cli").option("--chat-id <id>","resume an existing chatId (otherwise a fresh one is generated)").action(async(e,o)=>{pl({what:"agentx chat",...ul});let t=ta({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${fl().slice(0,12)}`,r=[];try{r=await xn(t)}catch(g){console.error(V.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(V.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(V.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(V.red(` unknown agent: @${n}`)),console.error(V.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(V.dim(` no agent given \u2014 defaulting to @${n}`))),process.stdout.isTTY&&process.stdin.isTTY){let{render:g}=await import("ink"),{ChatApp:l}=await import("./ChatApp-4FOU6Q3S.js"),p=(await import("react")).default;await g(p.createElement(l,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}Lu(t.baseUrl,n,i,s);let a=Du({input:process.stdin,output:process.stdout}),c=!1,d=!1;for(a.on("close",()=>{if(c){d=!0;return}console.log(V.dim(`
481
+ bye`)),process.exit(0)});;){let g;try{g=(await a.question(V.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(V.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${fl().slice(0,12)}`,console.log(V.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let u=await xn(t);for(let w of u){let y=w.id===n?V.green("\u25CF"):V.dim("\u25CB");console.log(` ${y} @${w.id} ${V.dim(w.tier)} ${w.model??""}`)}}catch(u){console.error(V.red(` failed to list agents: ${u?.message||u}`))}continue}if(g.startsWith("/agent ")){let u=g.slice(7).replace(/^@/,"").trim();if(!u){console.log(V.red(" usage: /agent <id>"));continue}try{if(!(await xn(t)).find(y=>y.id===u)){console.log(V.red(` unknown agent: @${u}`));continue}n=u,console.log(V.dim(` now talking to @${n}`))}catch(w){console.error(V.red(` failed to switch agent: ${w?.message||w}`))}continue}if(g.startsWith("/")){console.log(V.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(V.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let l=_u({text:`@${n}\u2026`,color:"cyan"}).start(),p=Date.now(),f=Pu(n);try{let u=await na(t,n,g,{channel:s,chatId:i,onText:y=>{l.stop(),f.text(y)},onThinking:()=>{},onTool:y=>{l.stop(),f.tool(y)}});l.stop();let w=Math.round((Date.now()-p)/100)/10;u.error?f.finishError(u.error):f.finish(w,u.usage)}catch(u){l.stop(),f.finishError(u?.message||String(u))}finally{c=!1}if(d){console.log(V.dim(" bye"));return}}});function Pu(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${V.green(`@${e}`)}
448
482
  `),o=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)t&&a!==`
449
483
  `&&(process.stdout.write(" "),t=!1),process.stdout.write(a),a===`
450
484
  `&&(t=!0)}},tool(r){if(i(),r.status==="start"&&r.name){let a=r.id||`${r.name}:${s.size}`;if(s.has(a))return;s.add(a),t||(process.stdout.write(`
@@ -459,17 +493,17 @@ agentx wiki questions`,ae=I?.daemon?.port??I?.port??18800;try{let B=await fetch(
459
493
  `))},finishError(r){o&&!t&&process.stdout.write(`
460
494
  `),process.stdout.write(V.red(` \u2717 ${r}
461
495
 
462
- `))}}}function Zp(e,o,t,n){console.log(),console.log(V.bold(" agentx chat")),console.log(V.dim(` daemon: ${e} \xB7 channel: ${n} \xB7 chatId: ${t}`)),console.log(V.dim(` agent: @${o} \xB7 /exit to quit \xB7 /agent <id> to switch`)),console.log()}import{Command as eu}from"commander";import Re from"chalk";import{readFileSync as ou}from"fs";var Qn=["user","feedback","project","reference"],Jo=new eu().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");Jo.command("add").description("add a memory for an agent").requiredOption("--agent <id>","agent id").requiredOption("--type <type>","one of: user, feedback, project, reference").requiredOption("--name <slug>","short slug, unique per agent (e.g. deep-backend)").requiredOption("--description <line>","one-line hook shown in MEMORY.md").option("--body <text>","memory body (markdown); repeat --body or use --file").option("--file <path>","read body from a file (use '-' for stdin)").action(async e=>{if(!Qn.includes(e.type)){console.error(Re.red(` --type must be one of: ${Qn.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await tu();else try{o=ou(e.file,"utf-8")}catch(s){console.error(Re.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(Re.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new Yo().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(Re.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});Jo.command("list").description("list memories for an agent").requiredOption("--agent <id>","agent id").option("--type <type>","filter by memory type").action(e=>{let t=new Yo().list(e.agent);if(e.type){if(!Qn.includes(e.type)){console.error(Re.red(` --type must be one of: ${Qn.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.length){console.log(Re.dim(` no memories for agent "${e.agent}"${e.type?` of type "${e.type}"`:""}`));return}console.log();let n=null;for(let s of t)s.type!==n&&(console.log(Re.bold(` ${s.type}`)),n=s.type),console.log(` ${Re.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(Re.dim(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});Jo.command("show").description("print the full body of a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{let n=new Yo().get(o.agent,e);if(!n){console.error(Re.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Re.bold(`${n.type}/${n.name}`)+Re.dim(` (${n.description})`)),console.log(Re.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});Jo.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new Yo().remove(o.agent,e)){console.error(Re.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Re.green(` \u2713 memory "${e}" removed`))});Jo.command("index").description("print the MEMORY.md index content an agent sees in its prompt").requiredOption("--agent <id>","agent id").action(e=>{let t=new Yo().indexMarkdown(e.agent);if(!t){console.log(Re.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});async function tu(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}yl();import fi from"chalk";import{Command as nu}from"commander";import{resolve as su}from"path";var Qc=new nu().name("serve").description("run agentx as an MCP server for AI editors (Claude Code, Cursor, Windsurf, etc.)").option("--stdio","use stdio transport (default)",!0).option("-c, --cwd <cwd>","working directory",process.cwd()).action(async e=>{try{process.chdir(su(e.cwd)),e.stdio!==!1?await Qi():(so.error("Only stdio transport is currently supported."),so.info(`Usage: ${fi.green("agentx serve --stdio")} or configure in your MCP client.`),so.break(),so.info("Add to Claude Code:"),so.info(fi.dim(" claude mcp add agentx -- npx agentx serve --stdio")),so.break(),so.info("Add to Cursor/MCP config:"),so.info(fi.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){Mr(o)}});import{Command as iu}from"commander";import ie from"chalk";import{spawn as hi}from"child_process";import{mkdirSync as ru,writeFileSync as os,readFileSync as au,readdirSync as cu,rmSync as el,openSync as ol,existsSync as Zn}from"fs";import{resolve as lu,join as _e}from"path";import{randomBytes as du}from"crypto";var Zc={id:"demo-report",version:2,title:"Draft the demo shop report",description:"Scripted documentation example. Review and enable before running.",status:"draft",state:"disabled",nodes:[{id:"start",type:"trigger.manual",config:{},position:{x:80,y:180}},{id:"report",type:"agent",config:{agentId:"cx",prompt:"Prepare the demo shop report."},position:{x:380,y:180}},{id:"done",type:"end",config:{status:"completed"},position:{x:680,y:180}}],edges:[{from:"start",to:"report"},{from:"report",to:"done"}]};var tl="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",gu="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function mu(e,o){return[{dir:_e(e,"node-a"),id:"demo-laptop",name:"laptop-paris",port:o,agentId:"cx",agentName:"CX",persona:"You are CX, the customer-facing coordinator. You triage inbound issues and delegate technical work to @builder on the vps node.",script:{steps:[{match:"USER: Build the demo report workflow",reply:"Here is a scripted example: start it manually, ask CX for a report, then finish. It is saved disabled so you can review it before running.\n\n```json\n"+JSON.stringify(Zc,null,2)+"\n```",delayMs:300,chunkMs:2},{match:"Prepare the demo shop report",reply:"Demo shop report: checkout checks passed, MR !47 is ready for review, and CX has drafted the customer update. This is a scripted example.",delayMs:500},{match:"checkout is broken",thinking:"Checkout failure + red CI \u2014 this is a build problem, not a support question. @builder on vps-nyc owns demo/shop.",reply:"Checkout failure traced to the red pipeline on demo/shop. This needs a code fix \u2014 delegating to @builder on the vps-nyc node over the mesh. I'll report back on this thread.",delayMs:900},{match:"Builder reports",thinking:"Fix confirmed and pipeline green \u2014 close the loop with the customer.",reply:"Resolved \u2705 \u2014 builder patched checkout.test.ts (Node 22 crypto import), MR !47 merged, pipeline green. Customer thread updated. Every hop of this run is in the ledger: `agentx ledger`.",delayMs:800}],fallback:{reply:"Demo mode \u2014 I answer from a script. Try the scripted scenario, or run `agentx setup` to connect a real model."}}},{dir:_e(e,"node-b"),id:"demo-vps",name:"vps-nyc",port:o+1,agentId:"builder",agentName:"Builder",persona:"You are Builder, the engineering agent on the vps node. You fix code, open MRs, and report results tersely.",script:{steps:[{match:"checkout\\.test\\.ts|CI is red",thinking:"Reproducing on Node 22\u2026 crypto.webcrypto import moved. Patching the test setup, rerunning the suite.",reply:"Fixed. checkout.test.ts assumed the legacy crypto.webcrypto import \u2014 patched for Node 22, suite green locally. Opened MR !47 on demo/shop; pipeline is green. Handing back to @cx.",delayMs:1400,chunkMs:40}],fallback:{reply:"Builder here (demo script). Send me a failing pipeline."}}},{dir:_e(e,"node-c"),id:"demo-pi",name:"pi-office",port:o+2,agentId:"scout",agentName:"Scout",persona:"You are Scout, the monitoring agent on the office Raspberry Pi. You watch schedules and report status.",script:{fallback:{reply:"Scout here (demo script) \u2014 all monitors green on pi-office."},steps:[]}}]}function pu(e,o,t){let n=_e(e.dir,"workspaces",e.agentId);ru(n,{recursive:!0}),os(_e(n,"CLAUDE.md"),`# ${e.agentName}
496
+ `))}}}function Lu(e,o,t,n){console.log(),console.log(V.bold(" agentx chat")),console.log(V.dim(` daemon: ${e} \xB7 channel: ${n} \xB7 chatId: ${t}`)),console.log(V.dim(` agent: @${o} \xB7 /exit to quit \xB7 /agent <id> to switch`)),console.log()}import{Command as Mu}from"commander";import Re from"chalk";import{readFileSync as Fu}from"fs";var ls=["user","feedback","project","reference"],zo=new Mu().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");zo.command("add").description("add a memory for an agent").requiredOption("--agent <id>","agent id").requiredOption("--type <type>","one of: user, feedback, project, reference").requiredOption("--name <slug>","short slug, unique per agent (e.g. deep-backend)").requiredOption("--description <line>","one-line hook shown in MEMORY.md").option("--body <text>","memory body (markdown); repeat --body or use --file").option("--file <path>","read body from a file (use '-' for stdin)").action(async e=>{if(!ls.includes(e.type)){console.error(Re.red(` --type must be one of: ${ls.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await Uu();else try{o=Fu(e.file,"utf-8")}catch(s){console.error(Re.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(Re.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new Xo().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(Re.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});zo.command("list").description("list memories for an agent").requiredOption("--agent <id>","agent id").option("--type <type>","filter by memory type").action(e=>{let t=new Xo().list(e.agent);if(e.type){if(!ls.includes(e.type)){console.error(Re.red(` --type must be one of: ${ls.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.length){console.log(Re.dim(` no memories for agent "${e.agent}"${e.type?` of type "${e.type}"`:""}`));return}console.log();let n=null;for(let s of t)s.type!==n&&(console.log(Re.bold(` ${s.type}`)),n=s.type),console.log(` ${Re.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(Re.dim(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});zo.command("show").description("print the full body of a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{let n=new Xo().get(o.agent,e);if(!n){console.error(Re.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Re.bold(`${n.type}/${n.name}`)+Re.dim(` (${n.description})`)),console.log(Re.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});zo.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new Xo().remove(o.agent,e)){console.error(Re.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Re.green(` \u2713 memory "${e}" removed`))});zo.command("index").description("print the MEMORY.md index content an agent sees in its prompt").requiredOption("--agent <id>","agent id").action(e=>{let t=new Xo().indexMarkdown(e.agent);if(!t){console.log(Re.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});async function Uu(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}Pl();import Oi from"chalk";import{Command as qu}from"commander";import{resolve as Wu}from"path";var yl=new qu().name("serve").description("run agentx as an MCP server for AI editors (Claude Code, Cursor, Windsurf, etc.)").option("--stdio","use stdio transport (default)",!0).option("-c, --cwd <cwd>","working directory",process.cwd()).action(async e=>{try{process.chdir(Wu(e.cwd)),e.stdio!==!1?await dr():(ro.error("Only stdio transport is currently supported."),ro.info(`Usage: ${Oi.green("agentx serve --stdio")} or configure in your MCP client.`),ro.break(),ro.info("Add to Claude Code:"),ro.info(Oi.dim(" claude mcp add agentx -- npx agentx serve --stdio")),ro.break(),ro.info("Add to Cursor/MCP config:"),ro.info(Oi.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){Yr(o)}});import{Command as Bu}from"commander";import ie from"chalk";import{spawn as Ti}from"child_process";import{mkdirSync as Ju,writeFileSync as ms,readFileSync as Gu,readdirSync as Hu,rmSync as bl,openSync as $l,existsSync as ds}from"fs";import{resolve as zu,join as De}from"path";import{randomBytes as Yu}from"crypto";var wl={id:"demo-report",version:2,title:"Draft the demo shop report",description:"Scripted documentation example. Review and enable before running.",status:"draft",state:"disabled",nodes:[{id:"start",type:"trigger.manual",config:{},position:{x:80,y:180}},{id:"report",type:"agent",config:{agentId:"cx",prompt:"Prepare the demo shop report."},position:{x:380,y:180}},{id:"done",type:"end",config:{status:"completed"},position:{x:680,y:180}}],edges:[{from:"start",to:"report"},{from:"report",to:"done"}]};var kl="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",Vu="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function Ku(e,o){return[{dir:De(e,"node-a"),id:"demo-laptop",name:"laptop-paris",port:o,agentId:"cx",agentName:"CX",persona:"You are CX, the customer-facing coordinator. You triage inbound issues and delegate technical work to @builder on the vps node.",script:{steps:[{match:"USER: Build the demo report workflow",reply:"Here is a scripted example: start it manually, ask CX for a report, then finish. It is saved disabled so you can review it before running.\n\n```json\n"+JSON.stringify(wl,null,2)+"\n```",delayMs:300,chunkMs:2},{match:"Prepare the demo shop report",reply:"Demo shop report: checkout checks passed, MR !47 is ready for review, and CX has drafted the customer update. This is a scripted example.",delayMs:500},{match:"checkout is broken",thinking:"Checkout failure + red CI \u2014 this is a build problem, not a support question. @builder on vps-nyc owns demo/shop.",reply:"Checkout failure traced to the red pipeline on demo/shop. This needs a code fix \u2014 delegating to @builder on the vps-nyc node over the mesh. I'll report back on this thread.",delayMs:900},{match:"Builder reports",thinking:"Fix confirmed and pipeline green \u2014 close the loop with the customer.",reply:"Resolved \u2705 \u2014 builder patched checkout.test.ts (Node 22 crypto import), MR !47 merged, pipeline green. Customer thread updated. Every hop of this run is in the ledger: `agentx ledger`.",delayMs:800}],fallback:{reply:"Demo mode \u2014 I answer from a script. Try the scripted scenario, or run `agentx setup` to connect a real model."}}},{dir:De(e,"node-b"),id:"demo-vps",name:"vps-nyc",port:o+1,agentId:"builder",agentName:"Builder",persona:"You are Builder, the engineering agent on the vps node. You fix code, open MRs, and report results tersely.",script:{steps:[{match:"checkout\\.test\\.ts|CI is red",thinking:"Reproducing on Node 22\u2026 crypto.webcrypto import moved. Patching the test setup, rerunning the suite.",reply:"Fixed. checkout.test.ts assumed the legacy crypto.webcrypto import \u2014 patched for Node 22, suite green locally. Opened MR !47 on demo/shop; pipeline is green. Handing back to @cx.",delayMs:1400,chunkMs:40}],fallback:{reply:"Builder here (demo script). Send me a failing pipeline."}}},{dir:De(e,"node-c"),id:"demo-pi",name:"pi-office",port:o+2,agentId:"scout",agentName:"Scout",persona:"You are Scout, the monitoring agent on the office Raspberry Pi. You watch schedules and report status.",script:{fallback:{reply:"Scout here (demo script) \u2014 all monitors green on pi-office."},steps:[]}}]}function Xu(e,o,t){let n=De(e.dir,"workspaces",e.agentId);Ju(n,{recursive:!0}),ms(De(n,"CLAUDE.md"),`# ${e.agentName}
463
497
 
464
498
  ${e.persona}
465
- `),os(_e(e.dir,"demo-script.json"),JSON.stringify(e.script,null,2));let s=o.filter(r=>r.id!==e.id).map(r=>({name:r.name,url:`http://127.0.0.1:${r.port}`,token:t})),i={node:{id:e.id,name:e.name,bind:`127.0.0.1:${e.port}`,defaultAgent:e.agentId},dashboard:{enabled:!0,port:e.port+10,bind:"127.0.0.1",daemonUrl:`http://127.0.0.1:${e.port}`},providers:{demo:{apiKey:"demo-mode"}},agents:{[e.agentId]:{name:e.agentName,description:e.persona,workspace:"./workspaces/"+e.agentId,tier:"orchestrator",provider:"demo",mentions:[`@${e.agentId}`,e.agentId],maxConcurrent:2,systemPrompt:e.persona}},mesh:{enabled:!0,peers:s,discovery:"static",healthCheck:{interval:3,timeout:5}},workflows:{enabled:!0}};os(_e(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function yi(e,o,t){let n=Date.now();for(;Date.now()-n<t;){try{if(await o())return}catch{}await new Promise(s=>setTimeout(s,500))}throw new Error(`Timed out waiting for ${e} (${Math.round(t/1e3)}s)`)}async function wi(e,o,t){let n=await fetch(`http://127.0.0.1:${e}${o}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),s=await n.json().catch(()=>({}));if(!n.ok||s.error)throw new Error(s.error||`${o} HTTP ${n.status}`);return s}function es(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
499
+ `),ms(De(e.dir,"demo-script.json"),JSON.stringify(e.script,null,2));let s=o.filter(r=>r.id!==e.id).map(r=>({name:r.name,url:`http://127.0.0.1:${r.port}`,token:t})),i={node:{id:e.id,name:e.name,bind:`127.0.0.1:${e.port}`,defaultAgent:e.agentId},dashboard:{enabled:!0,port:e.port+10,bind:"127.0.0.1",daemonUrl:`http://127.0.0.1:${e.port}`},providers:{demo:{apiKey:"demo-mode"}},agents:{[e.agentId]:{name:e.agentName,description:e.persona,workspace:"./workspaces/"+e.agentId,tier:"orchestrator",provider:"demo",mentions:[`@${e.agentId}`,e.agentId],maxConcurrent:2,systemPrompt:e.persona}},mesh:{enabled:!0,peers:s,discovery:"static",healthCheck:{interval:3,timeout:5}},workflows:{enabled:!0}};ms(De(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function Ii(e,o,t){let n=Date.now();for(;Date.now()-n<t;){try{if(await o())return}catch{}await new Promise(s=>setTimeout(s,500))}throw new Error(`Timed out waiting for ${e} (${Math.round(t/1e3)}s)`)}async function ji(e,o,t){let n=await fetch(`http://127.0.0.1:${e}${o}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),s=await n.json().catch(()=>({}));if(!n.ok||s.error)throw new Error(s.error||`${o} HTTP ${n.status}`);return s}function gs(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
466
500
  `).join(`
467
- `)}`)}var nl=new iu().name("demo").description("zero-key demo: three daemons, a real A2A mesh, a scripted scenario").option("--base-port <port>","first of three consecutive loopback ports","18921").option("--once","play the scenario once and exit (default: keep daemons up until Ctrl-C)").option("--keep","keep the .agentx-demo directory on exit").option("--no-open","don't open the dashboard in a browser").option("--reuse","resume an existing .agentx-demo instead of starting fresh (implies --keep)").option("--bind <host>","dashboard bind address","127.0.0.1").action(async e=>{let o=parseInt(e.basePort,10),t=lu(process.cwd(),".agentx-demo"),n=mu(t,o),s=_e(t,"mesh-token"),i=!!e.reuse&&Zn(s)&&Zn(_e(n[0].dir,"agentx.json")),r=i?au(s,"utf8").trim():du(24).toString("hex"),a=e.keep||e.reuse,c=[],d=process.argv[1];if((!d||!Zn(d))&&(console.error(ie.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!i){if(Zn(t))for(let f of cu(t))el(_e(t,f),{recursive:!0,force:!0});for(let f of n)pu(f,n,r);os(s,r+`
468
- `,{mode:384})}console.log(),console.log(ie.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(ie.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(ie.dim(" Run `agentx setup` to wire real agents.\n"));let g=!1,l=f=>{if(!g){g=!0;for(let u of c)try{u.kill("SIGTERM")}catch{}setTimeout(()=>{if(!a)try{el(t,{recursive:!0,force:!0})}catch{}process.exit(f)},800)}};process.on("SIGINT",()=>l(0)),process.on("SIGTERM",()=>l(0));let p={...process.env};delete p.ANTHROPIC_API_KEY,delete p.ANTHROPIC_API_KEY_OLD,delete p.OPENAI_API_KEY,delete p.DEEPSEEK_API_KEY;try{for(let y of n){let $=ol(_e(y.dir,"daemon.log"),"a"),b=hi(process.execPath,[d,"daemon","start","-c",_e(y.dir,"agentx.json")],{cwd:y.dir,env:{...p,MESH_TOKEN:r,AGENTX_DEMO_SCRIPT:_e(y.dir,"demo-script.json")},stdio:["ignore",$,$]});c.push(b),console.log(ie.dim(` \u25B8 ${y.name} starting on 127.0.0.1:${y.port} (log: ${_e(y.dir,"daemon.log")})`))}for(let y of n)await yi(`${y.name} /health`,async()=>(await fetch(`http://127.0.0.1:${y.port}/health`)).ok,3e4);console.log(ie.green(" \u2713 three daemons up"));let f=n[0].port+10;{let y=ol(_e(n[0].dir,"board.log"),"a"),$=hi(process.execPath,[d,"board","serve","--bind",e.bind],{cwd:n[0].dir,env:{...p,MESH_TOKEN:r},stdio:["ignore",y,y]});c.push($)}await yi("dashboard /live",async()=>(await fetch(`http://127.0.0.1:${f}/live`)).ok,3e4),console.log(ie.green(" \u2713 dashboard up")),await yi("mesh discovery (laptop sees both peers)",async()=>((await(await fetch(`http://127.0.0.1:${n[0].port}/health`)).json()).mesh||[]).filter(v=>v.healthy&&v.skills?.length).length>=2,3e4),console.log(ie.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let u=`http://127.0.0.1:${f}/live`;if(console.log(),console.log(` Dashboard: ${ie.cyan(u)} (all three nodes via the mesh)`),console.log(ie.dim(` Daemon APIs: ${n.map(y=>`127.0.0.1:${y.port}`).join(" \xB7 ")}`)),e.open!==!1){let y=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{hi(y,[u],{stdio:"ignore",detached:!0}).unref()}catch{}}let w=async()=>{console.log(),console.log(ie.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),es("You \u2192 @cx (laptop-paris)",tl,ie.cyan);let y=await wi(n[0].port,"/task",{agent:"cx",message:tl});es("@cx (laptop-paris)",y.content||"(no content)",ie.green),console.log(),console.log(ie.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let $=await wi(n[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:gu}),b=typeof $.messageId=="string"?$.messageId:$.content||"(no reply)";es("@builder (vps-nyc)",b,ie.yellow);let v=await wi(n[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${b}`});es("@cx (laptop-paris)",v.content||"(no content)",ie.green),console.log(),console.log(ie.dim(` Inspect the run: ${u} \xB7 ledger rows on each node record every dispatch`)),console.log(ie.dim(` Worth your time? A star helps others find it: ${ie.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(i?console.log(ie.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await w(),e.once){console.log(),console.log(ie.dim(" --once: shutting down.")),l(0);return}console.log(),console.log(ie.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{w().catch(y=>console.error(ie.red(` Replay failed: ${y.message}`)))}),process.stdin.resume()}catch(f){console.error(),console.error(ie.red(` Demo failed: ${f.message}`)),console.error(ie.dim(` Node logs: ${n.map(u=>_e(u.dir,"daemon.log")).join(", ")}`)),l(1)}});import{Command as uu}from"commander";import{randomUUID as fu}from"crypto";import{readFileSync as hu}from"fs";import{resolve as yu}from"path";we();var il=new uu().name("exec").description("run one task through an agent and exit \u2014 for scripts and benchmarks").argument("[message]","the task (default: read from stdin)").requiredOption("-a, --agent <id>","agent id from the config").option("-c, --config <path>","config file (default: ./agentx.json)").option("-m, --model <model>","override the agent's model for this task").option("--timeout <minutes>","upper bound on the task's run time").option("--setup-workspace","write the managed workspace files first, as daemon boot does").option("--json","print one JSON result object instead of the reply text").action(async(e,o)=>{let t=(e??hu(0,"utf8")).trim();t||sl("no task given (pass it as an argument or on stdin)");let n=D(o.config?yu(o.config):void 0),s=n.agents[o.agent];s||sl(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`);let i=(...d)=>console.error("[agentx exec]",...d);if(o.setupWorkspace){let d=n.node.bind.split(":")[1]||"19900";Li(o.agent,s,d,i)}let r=new Xi(n,i),a=Date.now(),c=await r.execute({agentId:o.agent,message:t,model:o.model,timeoutMinutes:o.timeout?Number(o.timeout):void 0,context:{channel:"exec",chatId:`exec-${fu()}`,sender:"cli"}});o.json?process.stdout.write(JSON.stringify({content:c.content,error:c.error,errorKind:c.errorKind,usage:c.usage,numTurns:c.numTurns,billedModel:c.billedModel,durationMs:Date.now()-a})+`
501
+ `)}`)}var vl=new Bu().name("demo").description("zero-key demo: three daemons, a real A2A mesh, a scripted scenario").option("--base-port <port>","first of three consecutive loopback ports","18921").option("--once","play the scenario once and exit (default: keep daemons up until Ctrl-C)").option("--keep","keep the .agentx-demo directory on exit").option("--no-open","don't open the dashboard in a browser").option("--reuse","resume an existing .agentx-demo instead of starting fresh (implies --keep)").option("--bind <host>","dashboard bind address","127.0.0.1").action(async e=>{let o=parseInt(e.basePort,10),t=zu(process.cwd(),".agentx-demo"),n=Ku(t,o),s=De(t,"mesh-token"),i=!!e.reuse&&ds(s)&&ds(De(n[0].dir,"agentx.json")),r=i?Gu(s,"utf8").trim():Yu(24).toString("hex"),a=e.keep||e.reuse,c=[],d=process.argv[1];if((!d||!ds(d))&&(console.error(ie.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!i){if(ds(t))for(let f of Hu(t))bl(De(t,f),{recursive:!0,force:!0});for(let f of n)Xu(f,n,r);ms(s,r+`
502
+ `,{mode:384})}console.log(),console.log(ie.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(ie.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(ie.dim(" Run `agentx setup` to wire real agents.\n"));let g=!1,l=f=>{if(!g){g=!0;for(let u of c)try{u.kill("SIGTERM")}catch{}setTimeout(()=>{if(!a)try{bl(t,{recursive:!0,force:!0})}catch{}process.exit(f)},800)}};process.on("SIGINT",()=>l(0)),process.on("SIGTERM",()=>l(0));let p={...process.env};delete p.ANTHROPIC_API_KEY,delete p.ANTHROPIC_API_KEY_OLD,delete p.OPENAI_API_KEY,delete p.DEEPSEEK_API_KEY;try{for(let y of n){let k=$l(De(y.dir,"daemon.log"),"a"),b=Ti(process.execPath,[d,"daemon","start","-c",De(y.dir,"agentx.json")],{cwd:y.dir,env:{...p,MESH_TOKEN:r,AGENTX_DEMO_SCRIPT:De(y.dir,"demo-script.json")},stdio:["ignore",k,k]});c.push(b),console.log(ie.dim(` \u25B8 ${y.name} starting on 127.0.0.1:${y.port} (log: ${De(y.dir,"daemon.log")})`))}for(let y of n)await Ii(`${y.name} /health`,async()=>(await fetch(`http://127.0.0.1:${y.port}/health`)).ok,3e4);console.log(ie.green(" \u2713 three daemons up"));let f=n[0].port+10;{let y=$l(De(n[0].dir,"board.log"),"a"),k=Ti(process.execPath,[d,"board","serve","--bind",e.bind],{cwd:n[0].dir,env:{...p,MESH_TOKEN:r},stdio:["ignore",y,y]});c.push(k)}await Ii("dashboard /live",async()=>(await fetch(`http://127.0.0.1:${f}/live`)).ok,3e4),console.log(ie.green(" \u2713 dashboard up")),await Ii("mesh discovery (laptop sees both peers)",async()=>((await(await fetch(`http://127.0.0.1:${n[0].port}/health`)).json()).mesh||[]).filter(x=>x.healthy&&x.skills?.length).length>=2,3e4),console.log(ie.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let u=`http://127.0.0.1:${f}/live`;if(console.log(),console.log(` Dashboard: ${ie.cyan(u)} (all three nodes via the mesh)`),console.log(ie.dim(` Daemon APIs: ${n.map(y=>`127.0.0.1:${y.port}`).join(" \xB7 ")}`)),e.open!==!1){let y=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{Ti(y,[u],{stdio:"ignore",detached:!0}).unref()}catch{}}let w=async()=>{console.log(),console.log(ie.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),gs("You \u2192 @cx (laptop-paris)",kl,ie.cyan);let y=await ji(n[0].port,"/task",{agent:"cx",message:kl});gs("@cx (laptop-paris)",y.content||"(no content)",ie.green),console.log(),console.log(ie.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let k=await ji(n[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:Vu}),b=typeof k.messageId=="string"?k.messageId:k.content||"(no reply)";gs("@builder (vps-nyc)",b,ie.yellow);let x=await ji(n[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${b}`});gs("@cx (laptop-paris)",x.content||"(no content)",ie.green),console.log(),console.log(ie.dim(` Inspect the run: ${u} \xB7 ledger rows on each node record every dispatch`)),console.log(ie.dim(` Worth your time? A star helps others find it: ${ie.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(i?console.log(ie.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await w(),e.once){console.log(),console.log(ie.dim(" --once: shutting down.")),l(0);return}console.log(),console.log(ie.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{w().catch(y=>console.error(ie.red(` Replay failed: ${y.message}`)))}),process.stdin.resume()}catch(f){console.error(),console.error(ie.red(` Demo failed: ${f.message}`)),console.error(ie.dim(` Node logs: ${n.map(u=>De(u.dir,"daemon.log")).join(", ")}`)),l(1)}});import{Command as Qu}from"commander";import{randomUUID as Zu}from"crypto";import{readFileSync as ef}from"fs";import{resolve as of}from"path";pe();var Sl=new Qu().name("exec").description("run one task through an agent and exit \u2014 for scripts and benchmarks").argument("[message]","the task (default: read from stdin)").requiredOption("-a, --agent <id>","agent id from the config").option("-c, --config <path>","config file (default: ./agentx.json)").option("-m, --model <model>","override the agent's model for this task").option("--timeout <minutes>","upper bound on the task's run time").option("--setup-workspace","write the managed workspace files first, as daemon boot does").option("--json","print one JSON result object instead of the reply text").action(async(e,o)=>{let t=(e??ef(0,"utf8")).trim();t||xl("no task given (pass it as an argument or on stdin)");let n=_(o.config?of(o.config):void 0),s=n.agents[o.agent];s||xl(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`);let i=(...d)=>console.error("[agentx exec]",...d);if(o.setupWorkspace){let d=n.node.bind.split(":")[1]||"19900";Vi(o.agent,s,d,i)}let r=new lr(n,i),a=Date.now(),c=await r.execute({agentId:o.agent,message:t,model:o.model,timeoutMinutes:o.timeout?Number(o.timeout):void 0,context:{channel:"exec",chatId:`exec-${Zu()}`,sender:"cli"}});o.json?process.stdout.write(JSON.stringify({content:c.content,error:c.error,errorKind:c.errorKind,usage:c.usage,numTurns:c.numTurns,billedModel:c.billedModel,durationMs:Date.now()-a})+`
469
503
  `):c.error?console.error(c.error):process.stdout.write(c.content+`
470
- `),process.exit(c.error?1:0)});function sl(e){console.error(`agentx exec: ${e}`),process.exit(1)}we();import{Command as wu}from"commander";import Ae from"chalk";var Oo=new wu().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Oo.command("list-chats").description("list chats observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").option("--group","groups only").option("--dm","DMs only").action(async e=>{try{let t=(await Qt("/whatsapp/chats")).chats??[];if(e.group&&(t=t.filter(n=>n.isGroup)),e.dm&&(t=t.filter(n=>!n.isGroup)),e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Ae.dim(" no chats cached yet"));return}console.log(),console.log(Ae.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?Ae.cyan("group"):Ae.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Ae.dim(n.jid.padEnd(40))} ${Ae.dim(i)}`)}console.log()}catch(o){$t(o)}});Oo.command("list-contacts").description("list contacts observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").action(async e=>{try{let t=(await Qt("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Ae.dim(" no contacts cached yet"));return}console.log(),console.log(Ae.bold(` ${t.length} contact${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=(n.name||n.pushName||n.phone||n.jid).padEnd(30),i=n.phone?`+${n.phone}`.padEnd(16):"\u2014".padEnd(16);console.log(` ${s} ${Ae.dim(i)} ${Ae.dim(n.jid)}`)}console.log()}catch(o){$t(o)}});Oo.command("ingest-all").description("run a full ingest sweep against the configured allowlist (writes raw wiki entries)").option("--dry-run","compute entries without writing them \u2014 review before enabling").option("--agent <id>","owner agent for the entries (defaults to channels.whatsapp.defaultAgent)").option("--force","bypass the channels.whatsapp.ingest.enabled guard").action(async e=>{try{let o={dryRun:!!e.dryRun,force:!!e.force};e.agent&&(o.agent=e.agent);let t=await $i("/whatsapp/ingest",o);bi(t,!!e.dryRun)}catch(o){$t(o)}});Oo.command("ingest-contact <jid>").description("ingest one contact (skips scope allowlist for this JID only)").option("--dry-run","compute entries without writing them").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e,onlyKind:"contact"};o.agent&&(t.agent=o.agent);let n=await $i("/whatsapp/ingest",t);bi(n,!!o.dryRun)}catch(t){$t(t)}});Oo.command("ingest-chat <jid>").description("ingest one chat (DM or group) including message window if `--messages` is set").option("--dry-run","compute entries without writing them").option("--messages","include the bounded message window for this chat (overrides config mode)").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e};o.agent&&(t.agent=o.agent),o.messages&&(t.forceMode="messages");let n=await $i("/whatsapp/ingest",t);bi(n,!!o.dryRun)}catch(t){$t(t)}});Oo.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await Qt("/whatsapp/state"),o=await Qt("/whatsapp/chats"),t=await Qt("/whatsapp/contacts");console.log(),console.log(Ae.bold(" WhatsApp status")),console.log(),console.log(` connection: ${e.connection||"\u2014"}`),console.log(` cached chats: ${o.chats?.length??0}`),console.log(` cached contacts: ${t.contacts?.length??0}`),console.log()}catch(e){$t(e)}});function bi(e,o){if(console.log(),console.log(Ae.bold(o?" Ingest (dry-run)":" Ingest report")),console.log(),console.log(` scanned: contacts=${e.scannedContacts}, groups=${e.scannedGroups}`),console.log(` wrote: contacts=${e.wroteContacts}, groups=${e.wroteGroups}, dm-windows=${e.wroteDmWindows}, group-windows=${e.wroteGroupWindows}`),e.skippedUnchanged&&console.log(` skipped: ${e.skippedUnchanged} unchanged`),e.errors?.length){console.log(Ae.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(Ae.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(Ae.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(Ae.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Ae.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function rl(){try{let e=D(),[o,t]=e.node.bind.split(":");return`http://${o||"127.0.0.1"}:${t||"19900"}`}catch{return"http://127.0.0.1:19900"}}async function Qt(e){let o=await fetch(`${rl()}${e}`,{signal:AbortSignal.timeout(1e4)}),t=await o.json().catch(()=>({}));if(!o.ok)throw new Error(t.error||`HTTP ${o.status}`);return t}async function $i(e,o){let t=await fetch(`${rl()}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(6e5)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error(n.error||`HTTP ${t.status}`);return n}function $t(e){console.error(Ae.red(` ${e.message||e}`)),process.exit(1)}we();import{Command as bu}from"commander";import re from"chalk";import{existsSync as $u,mkdirSync as al,writeFileSync as Zt}from"fs";import{join as kt,resolve as ku}from"path";var en=new bu().name("plugin").description("manage agentx plugins (Move B)");en.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=D().plugins??[];if(console.log(),o.length===0){console.log(re.dim(" No plugins configured.")),console.log(re.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(re.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${re.cyan(t)}`);console.log(),console.log(re.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(re.red(` ${e.message}`)),process.exitCode=1}});en.command("init <name>").description("scaffold a new plugin package (npm-publishable, with manifest + setup hook)").option("--cwd <cwd>","directory to create the package under",process.cwd()).option("--description <text>","short package description").option("--force","overwrite an existing directory").action((e,o)=>{/^(@[a-z0-9-]+\/)?[a-z0-9][a-z0-9._-]*$/i.test(e)||(console.log(re.red(` invalid package name "${e}". Use lowercase letters, digits, hyphens; optional @scope/ prefix.`)),process.exit(1));let t=e.startsWith("@")?e.split("/")[1]:e,n=ku(o.cwd,t);$u(n)&&!o.force&&(console.log(re.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),al(n,{recursive:!0}),al(kt(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;Zt(kt(n,"package.json"),Eu(e,s)),Zt(kt(n,"tsconfig.json"),Au()),Zt(kt(n,"src/index.ts"),Ou(e)),Zt(kt(n,"README.md"),ju(e,s)),Zt(kt(n,".gitignore"),Iu()),console.log(),console.log(re.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(re.bold(" Next steps:")),console.log(re.dim(` cd ${t}`)),console.log(re.dim(" pnpm install")),console.log(re.dim(" pnpm build")),console.log(re.dim(" pnpm link --global # for local testing")),console.log(re.dim(" # then in your agentx project:")),console.log(re.dim(` pnpm link --global ${e}`)),console.log(re.dim(` agentx config set plugins[0] "${e}"`)),console.log(re.dim(" agentx plugin doctor")),console.log()});en.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let o=D().plugins??[];if(console.log(),o.length===0){console.log(re.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await vu(n);s.kind==="ok"?console.log(` ${re.green("\u2713")} ${re.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${re.red("\u2717")} ${re.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(re.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(re.red(` ${e.message}`)),process.exitCode=1}});async function vu(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=xu(o);if(!Su(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=mr.safeParse(t.manifest);return n.success?{kind:"ok",manifestName:n.data.name,manifestVersion:n.data.version}:{kind:"fail",reason:`manifest invalid: ${n.error.issues.map(i=>i.message).join("; ")}`}}function xu(e){if(e==null||typeof e!="object")return e;let o=e;if(o.default&&typeof o.default=="object"){let t=o.default;if(t.manifest&&typeof t.setup=="function")return t;if(t.default&&typeof t.default=="object"){let n=t.default;if(n.manifest&&typeof n.setup=="function")return n}}return o.manifest&&typeof o.setup=="function"?o:o.default??o}function Su(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function Eu(e,o){return JSON.stringify({name:e,version:"0.1.0",description:o,main:"dist/index.js",types:"dist/index.d.ts",files:["dist"],scripts:{build:"tsc",prepublishOnly:"pnpm build"},keywords:["agentx","agentx-plugin"],license:"MIT",devDependencies:{typescript:"^5.4.0","@types/node":"^20.0.0"}},null,2)+`
471
- `}function Au(){return JSON.stringify({compilerOptions:{target:"es2020",module:"commonjs",lib:["es2020"],declaration:!0,outDir:"dist",strict:!0,esModuleInterop:!0,skipLibCheck:!0,moduleResolution:"node"},include:["src/**/*.ts"]},null,2)+`
472
- `}function Ou(e){return`// ${e} \u2014 AgentX plugin
504
+ `),process.exit(c.error?1:0)});function xl(e){console.error(`agentx exec: ${e}`),process.exit(1)}pe();import{Command as tf}from"commander";import Ae from"chalk";var Io=new tf().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Io.command("list-chats").description("list chats observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").option("--group","groups only").option("--dm","DMs only").action(async e=>{try{let t=(await sn("/whatsapp/chats")).chats??[];if(e.group&&(t=t.filter(n=>n.isGroup)),e.dm&&(t=t.filter(n=>!n.isGroup)),e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Ae.dim(" no chats cached yet"));return}console.log(),console.log(Ae.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?Ae.cyan("group"):Ae.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Ae.dim(n.jid.padEnd(40))} ${Ae.dim(i)}`)}console.log()}catch(o){St(o)}});Io.command("list-contacts").description("list contacts observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").action(async e=>{try{let t=(await sn("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Ae.dim(" no contacts cached yet"));return}console.log(),console.log(Ae.bold(` ${t.length} contact${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=(n.name||n.pushName||n.phone||n.jid).padEnd(30),i=n.phone?`+${n.phone}`.padEnd(16):"\u2014".padEnd(16);console.log(` ${s} ${Ae.dim(i)} ${Ae.dim(n.jid)}`)}console.log()}catch(o){St(o)}});Io.command("ingest-all").description("run a full ingest sweep against the configured allowlist (writes raw wiki entries)").option("--dry-run","compute entries without writing them \u2014 review before enabling").option("--agent <id>","owner agent for the entries (defaults to channels.whatsapp.defaultAgent)").option("--force","bypass the channels.whatsapp.ingest.enabled guard").action(async e=>{try{let o={dryRun:!!e.dryRun,force:!!e.force};e.agent&&(o.agent=e.agent);let t=await Ni("/whatsapp/ingest",o);Ci(t,!!e.dryRun)}catch(o){St(o)}});Io.command("ingest-contact <jid>").description("ingest one contact (skips scope allowlist for this JID only)").option("--dry-run","compute entries without writing them").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e,onlyKind:"contact"};o.agent&&(t.agent=o.agent);let n=await Ni("/whatsapp/ingest",t);Ci(n,!!o.dryRun)}catch(t){St(t)}});Io.command("ingest-chat <jid>").description("ingest one chat (DM or group) including message window if `--messages` is set").option("--dry-run","compute entries without writing them").option("--messages","include the bounded message window for this chat (overrides config mode)").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e};o.agent&&(t.agent=o.agent),o.messages&&(t.forceMode="messages");let n=await Ni("/whatsapp/ingest",t);Ci(n,!!o.dryRun)}catch(t){St(t)}});Io.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await sn("/whatsapp/state"),o=await sn("/whatsapp/chats"),t=await sn("/whatsapp/contacts");console.log(),console.log(Ae.bold(" WhatsApp status")),console.log(),console.log(` connection: ${e.connection||"\u2014"}`),console.log(` cached chats: ${o.chats?.length??0}`),console.log(` cached contacts: ${t.contacts?.length??0}`),console.log()}catch(e){St(e)}});function Ci(e,o){if(console.log(),console.log(Ae.bold(o?" Ingest (dry-run)":" Ingest report")),console.log(),console.log(` scanned: contacts=${e.scannedContacts}, groups=${e.scannedGroups}`),console.log(` wrote: contacts=${e.wroteContacts}, groups=${e.wroteGroups}, dm-windows=${e.wroteDmWindows}, group-windows=${e.wroteGroupWindows}`),e.skippedUnchanged&&console.log(` skipped: ${e.skippedUnchanged} unchanged`),e.errors?.length){console.log(Ae.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(Ae.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(Ae.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(Ae.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Ae.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function El(){try{let e=_(),[o,t]=e.node.bind.split(":");return`http://${o||"127.0.0.1"}:${t||"19900"}`}catch{return"http://127.0.0.1:19900"}}async function sn(e){let o=await fetch(`${El()}${e}`,{signal:AbortSignal.timeout(1e4)}),t=await o.json().catch(()=>({}));if(!o.ok)throw new Error(t.error||`HTTP ${o.status}`);return t}async function Ni(e,o){let t=await fetch(`${El()}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(6e5)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error(n.error||`HTTP ${t.status}`);return n}function St(e){console.error(Ae.red(` ${e.message||e}`)),process.exit(1)}pe();import{Command as nf}from"commander";import re from"chalk";import{existsSync as sf,mkdirSync as Al,writeFileSync as rn}from"fs";import{join as Et,resolve as rf}from"path";var an=new nf().name("plugin").description("manage agentx plugins (Move B)");an.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=_().plugins??[];if(console.log(),o.length===0){console.log(re.dim(" No plugins configured.")),console.log(re.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(re.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${re.cyan(t)}`);console.log(),console.log(re.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(re.red(` ${e.message}`)),process.exitCode=1}});an.command("init <name>").description("scaffold a new plugin package (npm-publishable, with manifest + setup hook)").option("--cwd <cwd>","directory to create the package under",process.cwd()).option("--description <text>","short package description").option("--force","overwrite an existing directory").action((e,o)=>{/^(@[a-z0-9-]+\/)?[a-z0-9][a-z0-9._-]*$/i.test(e)||(console.log(re.red(` invalid package name "${e}". Use lowercase letters, digits, hyphens; optional @scope/ prefix.`)),process.exit(1));let t=e.startsWith("@")?e.split("/")[1]:e,n=rf(o.cwd,t);sf(n)&&!o.force&&(console.log(re.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),Al(n,{recursive:!0}),Al(Et(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;rn(Et(n,"package.json"),df(e,s)),rn(Et(n,"tsconfig.json"),gf()),rn(Et(n,"src/index.ts"),mf(e)),rn(Et(n,"README.md"),pf(e,s)),rn(Et(n,".gitignore"),uf()),console.log(),console.log(re.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(re.bold(" Next steps:")),console.log(re.dim(` cd ${t}`)),console.log(re.dim(" pnpm install")),console.log(re.dim(" pnpm build")),console.log(re.dim(" pnpm link --global # for local testing")),console.log(re.dim(" # then in your agentx project:")),console.log(re.dim(` pnpm link --global ${e}`)),console.log(re.dim(` agentx config set plugins[0] "${e}"`)),console.log(re.dim(" agentx plugin doctor")),console.log()});an.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let o=_().plugins??[];if(console.log(),o.length===0){console.log(re.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await af(n);s.kind==="ok"?console.log(` ${re.green("\u2713")} ${re.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${re.red("\u2717")} ${re.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(re.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(re.red(` ${e.message}`)),process.exitCode=1}});async function af(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=cf(o);if(!lf(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=Sr.safeParse(t.manifest);return n.success?{kind:"ok",manifestName:n.data.name,manifestVersion:n.data.version}:{kind:"fail",reason:`manifest invalid: ${n.error.issues.map(i=>i.message).join("; ")}`}}function cf(e){if(e==null||typeof e!="object")return e;let o=e;if(o.default&&typeof o.default=="object"){let t=o.default;if(t.manifest&&typeof t.setup=="function")return t;if(t.default&&typeof t.default=="object"){let n=t.default;if(n.manifest&&typeof n.setup=="function")return n}}return o.manifest&&typeof o.setup=="function"?o:o.default??o}function lf(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function df(e,o){return JSON.stringify({name:e,version:"0.1.0",description:o,main:"dist/index.js",types:"dist/index.d.ts",files:["dist"],scripts:{build:"tsc",prepublishOnly:"pnpm build"},keywords:["agentx","agentx-plugin"],license:"MIT",devDependencies:{typescript:"^5.4.0","@types/node":"^20.0.0"}},null,2)+`
505
+ `}function gf(){return JSON.stringify({compilerOptions:{target:"es2020",module:"commonjs",lib:["es2020"],declaration:!0,outDir:"dist",strict:!0,esModuleInterop:!0,skipLibCheck:!0,moduleResolution:"node"},include:["src/**/*.ts"]},null,2)+`
506
+ `}function mf(e){return`// ${e} \u2014 AgentX plugin
473
507
  //
474
508
  // A plugin's default export is { manifest, setup }. The daemon calls
475
509
  // setup(ctx) once at boot. ctx.on() subscribes to the bus; ctx.addChannel()
@@ -505,7 +539,7 @@ const plugin = {
505
539
  }
506
540
 
507
541
  export default plugin
508
- `}function ju(e,o){return`# ${e}
542
+ `}function pf(e,o){return`# ${e}
509
543
 
510
544
  ${o}
511
545
 
@@ -532,19 +566,19 @@ agentx plugin doctor
532
566
  \`\`\`
533
567
 
534
568
  Restart the daemon to activate.
535
- `}function Iu(){return`node_modules/
569
+ `}function uf(){return`node_modules/
536
570
  dist/
537
571
  *.log
538
572
  .env
539
- `}import{Command as Cu}from"commander";import Oe from"chalk";import{writeFileSync as Tu,mkdirSync as Nu,existsSync as ts,readFileSync as cl,appendFileSync as ll}from"fs";import{resolve as vt,dirname as ml}from"path";import{homedir as vi}from"os";var pl=new Cu().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-FJLMTESZ.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Du(t);break;case"bash":s=Fu(t);break;case"fish":s=qu(t);break;default:console.error(Oe.red(`unsupported shell: ${n}`)),console.error(Oe.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?vt(String(e.output)):Ru(n);Nu(ml(i),{recursive:!0}),Tu(i,s),console.log(Oe.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),_u(n,i,!!e.yes)});function Ru(e){let o=vi();switch(e){case"zsh":return vt(o,".zsh","completions","_agentx");case"bash":return vt(o,".bash_completion.d","agentx.bash");case"fish":return vt(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function _u(e,o,t){if(e==="zsh"){let n=vt(vi(),".zshrc"),s=ml(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=ts(n)?cl(n,"utf-8"):"",c=!a.includes(s),d=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!d){console.log(Oe.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&ts(n)){let g=["","# agentx completion"];c&&g.push(i),d&&g.push(r),ll(n,g.join(`
573
+ `}import{Command as ff}from"commander";import Oe from"chalk";import{writeFileSync as hf,mkdirSync as yf,existsSync as ps,readFileSync as Ol,appendFileSync as Tl}from"fs";import{resolve as At,dirname as Cl}from"path";import{homedir as Di}from"os";var Nl=new ff().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-LAACUZWW.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=$f(t);break;case"bash":s=Ef(t);break;case"fish":s=Af(t);break;default:console.error(Oe.red(`unsupported shell: ${n}`)),console.error(Oe.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?At(String(e.output)):wf(n);yf(Cl(i),{recursive:!0}),hf(i,s),console.log(Oe.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),bf(n,i,!!e.yes)});function wf(e){let o=Di();switch(e){case"zsh":return At(o,".zsh","completions","_agentx");case"bash":return At(o,".bash_completion.d","agentx.bash");case"fish":return At(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function bf(e,o,t){if(e==="zsh"){let n=At(Di(),".zshrc"),s=Cl(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=ps(n)?Ol(n,"utf-8"):"",c=!a.includes(s),d=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!d){console.log(Oe.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&ps(n)){let g=["","# agentx completion"];c&&g.push(i),d&&g.push(r),Tl(n,g.join(`
540
574
  `)+`
541
- `),console.log(Oe.green("\u2713 Patched ~/.zshrc")),console.log(Oe.dim("Reload your shell: exec zsh"));return}console.log(Oe.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Oe.cyan(` ${i}`)),d&&console.log(Oe.cyan(` ${r}`)),console.log(),console.log(Oe.dim("Then reload: exec zsh")),console.log(Oe.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=vt(vi(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((ts(n)?cl(n,"utf-8"):"").includes(o)){console.log(Oe.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&ts(n)){ll(n,`
575
+ `),console.log(Oe.green("\u2713 Patched ~/.zshrc")),console.log(Oe.dim("Reload your shell: exec zsh"));return}console.log(Oe.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Oe.cyan(` ${i}`)),d&&console.log(Oe.cyan(` ${r}`)),console.log(),console.log(Oe.dim("Then reload: exec zsh")),console.log(Oe.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=At(Di(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((ps(n)?Ol(n,"utf-8"):"").includes(o)){console.log(Oe.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&ps(n)){Tl(n,`
542
576
  # agentx completion
543
577
  ${s}
544
- `),console.log(Oe.green("\u2713 Patched ~/.bashrc")),console.log(Oe.dim("Reload your shell: exec bash"));return}console.log(Oe.dim("Add this to ~/.bashrc:")),console.log(Oe.cyan(` ${s}`)),console.log(),console.log(Oe.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(Oe.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function Fe(e){return e._name||e.name()||""}function jo(e){return e.commands.filter(o=>{let t=Fe(o);return!(!t||t==="help")})}function on(e){return e.options.filter(o=>!o.hidden)}function Du(e){let o=[];return o.push("#compdef agentx"),o.push(""),ul(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
545
- `)}function dl(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function ul(e,o,t){let n=jo(e),i=on(e).map(Mu).filter(c=>!!c),r=dl(o);if(t.push(`${r}() {`),t.push(" local -a commands"),t.push(" local -a options"),t.push(" "),i.length===0&&n.length===0){t.push(" return 0"),t.push("}"),t.push("");return}let a=[];for(let c of i)a.push(c);if(n.length>0){let c=n.map(Uu).join(" ");a.push(` "1: :_values 'command' ${c}"`),a.push(' "*::arg:->args"')}t.push(" _arguments -C \\");for(let c=0;c<a.length;c++){let d=c===a.length-1;t.push(`${a[c]}${d?"":" \\"}`)}if(n.length>0){t.push(""),t.push(" case $state in"),t.push(" (args)"),t.push(" case $line[1] in");for(let c of n){let d=dl([...o,Fe(c)]);t.push(` (${Fe(c)}) ${d} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)ul(c,[...o,Fe(c)],t)}function Pu(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Lu(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Mu(e){let o=e.short||void 0,t=e.long||void 0;if(!o&&!t)return null;let n=Pu(e.description||"");return o&&t?` "(${t} ${o})"{${t},${o}}"[${n}]"`:` "${t||o}[${n}]"`}function Uu(e){let o=Lu(e.description()||"");return`'${Fe(e)}[${o}]'`}function Fu(e){let o=jo(e),t=[];t.push("# bash completion for agentx"),t.push("_agentx_complete() {"),t.push(" local cur prev words cword"),t.push(" COMPREPLY=()"),t.push(' cur="${COMP_WORDS[COMP_CWORD]}"'),t.push(' prev="${COMP_WORDS[COMP_CWORD-1]}"'),t.push(""),t.push(` local top="${o.map(Fe).join(" ")}"`),t.push(""),t.push(" if [[ $COMP_CWORD -eq 1 ]]; then"),t.push(' COMPREPLY=( $(compgen -W "$top" -- "$cur") )'),t.push(" return 0"),t.push(" fi"),t.push(""),t.push(' local cmd="${COMP_WORDS[1]}"'),t.push(' local sub2="${COMP_WORDS[2]:-}"'),t.push(' case "$cmd" in');for(let n of o){let s=jo(n).map(Fe),i=gl(n);if(t.push(` ${Fe(n)})`),s.length>0){t.push(" if [[ $COMP_CWORD -eq 2 ]]; then"),t.push(` COMPREPLY=( $(compgen -W "${s.join(" ")} ${i}" -- "$cur") )`),t.push(" return 0"),t.push(" fi"),t.push(' case "$sub2" in');for(let r of jo(n)){let a=gl(r);t.push(` ${Fe(r)})`),t.push(` COMPREPLY=( $(compgen -W "${a}" -- "$cur") )`),t.push(" return 0"),t.push(" ;;")}t.push(" esac")}else t.push(` COMPREPLY=( $(compgen -W "${i}" -- "$cur") )`);t.push(" ;;")}return t.push(" esac"),t.push("}"),t.push(""),t.push("complete -F _agentx_complete agentx"),t.push(""),t.join(`
546
- `)}function gl(e){let o=[];for(let t of on(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function qu(e){let o=[];o.push("# fish completion for agentx"),o.push(""),o.push("complete -c agentx -f"),o.push(""),o.push("# top-level commands");for(let t of jo(e)){let n=xi(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${Fe(t)}" -d "${n}"`)}o.push("");for(let t of on(e)){let n=ki(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of jo(e)){let n=Fe(t);o.push(`# ${n}`);for(let s of on(t)){let i=ki(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of jo(t)){let i=xi(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${jo(t).map(Fe).join(" ")}" -a "${Fe(s)}" -d "${i}"`);for(let r of on(s)){let a=ki(r,[`__fish_seen_subcommand_from ${Fe(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
547
- `)}function xi(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function ki(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=xi(e.description||""),r=["complete -c agentx",o.map(a=>`-n "${a}"`).join(" ")];return t&&r.push(`-s ${t}`),n&&r.push(`-l ${n}`),r.push(`-d "${s}"`),r.join(" ")}async function Kx(){let e=await Ur(),o=new Wu().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=Br(n);Jr(s)&&Wr("cli",s)});for(let t of[pa,da,mt,ot,Qe,qr,Ro,En,xo,Uo,Sn,zc,ko,Sa,Ra,Ba,Ga,za,Qa,tc,nc,Pn,Gt,Qc,Dt,yo,pl])o.addCommand(t);for(let t of fl)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=fl.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Bu(t,74," "),""].join(`
548
- `)}),o}var fl=[ee,pt,Jo,Ke,Lt,lt,Ue,lo,So,Fo,yt,wt,$o,Pe,Mt,Ln,Hc,ao,it,Yr,_o,en,Os,Ao,st,js,Vn,bt,Oo,nl,il,Xc];function Bu(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(`
549
- `)}export{Kx as a};
550
- //# sourceMappingURL=chunk-ITIMNSFR.js.map
578
+ `),console.log(Oe.green("\u2713 Patched ~/.bashrc")),console.log(Oe.dim("Reload your shell: exec bash"));return}console.log(Oe.dim("Add this to ~/.bashrc:")),console.log(Oe.cyan(` ${s}`)),console.log(),console.log(Oe.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(Oe.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function Ue(e){return e._name||e.name()||""}function jo(e){return e.commands.filter(o=>{let t=Ue(o);return!(!t||t==="help")})}function cn(e){return e.options.filter(o=>!o.hidden)}function $f(e){let o=[];return o.push("#compdef agentx"),o.push(""),Rl(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
579
+ `)}function Il(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function Rl(e,o,t){let n=jo(e),i=cn(e).map(xf).filter(c=>!!c),r=Il(o);if(t.push(`${r}() {`),t.push(" local -a commands"),t.push(" local -a options"),t.push(" "),i.length===0&&n.length===0){t.push(" return 0"),t.push("}"),t.push("");return}let a=[];for(let c of i)a.push(c);if(n.length>0){let c=n.map(Sf).join(" ");a.push(` "1: :_values 'command' ${c}"`),a.push(' "*::arg:->args"')}t.push(" _arguments -C \\");for(let c=0;c<a.length;c++){let d=c===a.length-1;t.push(`${a[c]}${d?"":" \\"}`)}if(n.length>0){t.push(""),t.push(" case $state in"),t.push(" (args)"),t.push(" case $line[1] in");for(let c of n){let d=Il([...o,Ue(c)]);t.push(` (${Ue(c)}) ${d} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)Rl(c,[...o,Ue(c)],t)}function kf(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function vf(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function xf(e){let o=e.short||void 0,t=e.long||void 0;if(!o&&!t)return null;let n=kf(e.description||"");return o&&t?` "(${t} ${o})"{${t},${o}}"[${n}]"`:` "${t||o}[${n}]"`}function Sf(e){let o=vf(e.description()||"");return`'${Ue(e)}[${o}]'`}function Ef(e){let o=jo(e),t=[];t.push("# bash completion for agentx"),t.push("_agentx_complete() {"),t.push(" local cur prev words cword"),t.push(" COMPREPLY=()"),t.push(' cur="${COMP_WORDS[COMP_CWORD]}"'),t.push(' prev="${COMP_WORDS[COMP_CWORD-1]}"'),t.push(""),t.push(` local top="${o.map(Ue).join(" ")}"`),t.push(""),t.push(" if [[ $COMP_CWORD -eq 1 ]]; then"),t.push(' COMPREPLY=( $(compgen -W "$top" -- "$cur") )'),t.push(" return 0"),t.push(" fi"),t.push(""),t.push(' local cmd="${COMP_WORDS[1]}"'),t.push(' local sub2="${COMP_WORDS[2]:-}"'),t.push(' case "$cmd" in');for(let n of o){let s=jo(n).map(Ue),i=jl(n);if(t.push(` ${Ue(n)})`),s.length>0){t.push(" if [[ $COMP_CWORD -eq 2 ]]; then"),t.push(` COMPREPLY=( $(compgen -W "${s.join(" ")} ${i}" -- "$cur") )`),t.push(" return 0"),t.push(" fi"),t.push(' case "$sub2" in');for(let r of jo(n)){let a=jl(r);t.push(` ${Ue(r)})`),t.push(` COMPREPLY=( $(compgen -W "${a}" -- "$cur") )`),t.push(" return 0"),t.push(" ;;")}t.push(" esac")}else t.push(` COMPREPLY=( $(compgen -W "${i}" -- "$cur") )`);t.push(" ;;")}return t.push(" esac"),t.push("}"),t.push(""),t.push("complete -F _agentx_complete agentx"),t.push(""),t.join(`
580
+ `)}function jl(e){let o=[];for(let t of cn(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function Af(e){let o=[];o.push("# fish completion for agentx"),o.push(""),o.push("complete -c agentx -f"),o.push(""),o.push("# top-level commands");for(let t of jo(e)){let n=_i(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${Ue(t)}" -d "${n}"`)}o.push("");for(let t of cn(e)){let n=Ri(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of jo(e)){let n=Ue(t);o.push(`# ${n}`);for(let s of cn(t)){let i=Ri(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of jo(t)){let i=_i(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${jo(t).map(Ue).join(" ")}" -a "${Ue(s)}" -d "${i}"`);for(let r of cn(s)){let a=Ri(r,[`__fish_seen_subcommand_from ${Ue(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
581
+ `)}function _i(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Ri(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=_i(e.description||""),r=["complete -c agentx",o.map(a=>`-n "${a}"`).join(" ")];return t&&r.push(`-s ${t}`),n&&r.push(`-l ${n}`),r.push(`-d "${s}"`),r.join(" ")}async function tS(){let e=await Vr(),o=new Of().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=Zr(n);ea(s)&&Qr("cli",s)});for(let t of[xa,$a,ht,it,Ze,Xr,_o,Nn,Eo,Wo,Cn,ml,xo,Da,Ba,Za,tc,nc,yc,kc,vc,zn,Qt,yl,Ft,bo,Nl])o.addCommand(t);for(let t of Dl)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Dl.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Tf(t,74," "),""].join(`
582
+ `)}),o}var Dl=[ee,yt,zo,Xe,qt,pt,Fe,mo,Ao,Bo,kt,vt,vo,Pe,Wt,Yn,dl,lo,lt,sa,Po,an,Ms,To,ct,Fs,rs,xt,Io,vl,Sl,hl];function Tf(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(`
583
+ `)}export{tS as a};
584
+ //# sourceMappingURL=chunk-2IYOKDVI.js.map