agentix-cli 0.44.0 → 0.45.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.
Files changed (40) hide show
  1. package/apps/mac-helper/Resources/AppIcon.png +0 -0
  2. package/dist/{agent-3XDPLWMX.js → agent-BCZRXLZ6.js} +2 -2
  3. package/dist/{board-dashboard-OYGL7Z7X.js → board-dashboard-U5YP4HWE.js} +110 -114
  4. package/dist/board-dashboard-U5YP4HWE.js.map +1 -0
  5. package/dist/{chunk-7HHVZJO4.js → chunk-3RCFDI52.js} +202 -173
  6. package/dist/chunk-3RCFDI52.js.map +1 -0
  7. package/dist/chunk-CQR6C5FU.js +23 -0
  8. package/dist/chunk-CQR6C5FU.js.map +1 -0
  9. package/dist/{chunk-BTGPZ6B7.js → chunk-CQRSSVWG.js} +2 -2
  10. package/dist/{chunk-Q3Q6FTFY.js → chunk-DYSVG6T3.js} +141 -141
  11. package/dist/{chunk-Q3Q6FTFY.js.map → chunk-DYSVG6T3.js.map} +1 -1
  12. package/dist/chunk-MX5GCR7Y.js +36 -0
  13. package/dist/chunk-MX5GCR7Y.js.map +1 -0
  14. package/dist/chunk-Z7LNSHG3.js +182 -0
  15. package/dist/chunk-Z7LNSHG3.js.map +1 -0
  16. package/dist/cli.js +1 -1
  17. package/dist/compaction-QXU3A4LQ.js +28 -0
  18. package/dist/compaction-QXU3A4LQ.js.map +1 -0
  19. package/dist/index.d.ts +99 -14
  20. package/dist/index.js +1 -1
  21. package/dist/memory-extract-3TO7UC5B.js +2 -0
  22. package/dist/{program-HGI5C2MP.js → program-4RO4NCBU.js} +2 -2
  23. package/dist/{registry-5QOY65FS.js → registry-OUJ6HT5D.js} +2 -2
  24. package/package.json +1 -1
  25. package/dist/board-dashboard-OYGL7Z7X.js.map +0 -1
  26. package/dist/chunk-77OV7346.js +0 -23
  27. package/dist/chunk-77OV7346.js.map +0 -1
  28. package/dist/chunk-7HHVZJO4.js.map +0 -1
  29. package/dist/chunk-P2Y7DFFP.js +0 -36
  30. package/dist/chunk-P2Y7DFFP.js.map +0 -1
  31. package/dist/chunk-T76YTN34.js +0 -178
  32. package/dist/chunk-T76YTN34.js.map +0 -1
  33. package/dist/compaction-FD4R23HZ.js +0 -28
  34. package/dist/compaction-FD4R23HZ.js.map +0 -1
  35. package/dist/memory-extract-F5ZHWY5E.js +0 -2
  36. /package/dist/{agent-3XDPLWMX.js.map → agent-BCZRXLZ6.js.map} +0 -0
  37. /package/dist/{chunk-BTGPZ6B7.js.map → chunk-CQRSSVWG.js.map} +0 -0
  38. /package/dist/{memory-extract-F5ZHWY5E.js.map → memory-extract-3TO7UC5B.js.map} +0 -0
  39. /package/dist/{program-HGI5C2MP.js.map → program-4RO4NCBU.js.map} +0 -0
  40. /package/dist/{registry-5QOY65FS.js.map → registry-OUJ6HT5D.js.map} +0 -0
@@ -1,34 +1,34 @@
1
- import{a as ha,b as An,g as ya}from"./chunk-7A7RC3R4.js";import{b as da}from"./chunk-YQVR2HQS.js";import{a as Do,b as la,f as En,i as Cs,j as ua,l as fa}from"./chunk-SAFAI4AV.js";import{a as ga,c as ma,d as pa}from"./chunk-2TJ5L7CB.js";import{a as $s,b as pr,c as ks,g as ur,h as fr,j as hr,k as yr,m as wr,n as br,o as $r}from"./chunk-WLVQDEOT.js";import{a as tt}from"./chunk-GV7S5BAX.js";import{e as sr}from"./chunk-GSX4NK2N.js";import{c as ir}from"./chunk-SZDACK6O.js";import{$ as aa,A as zr,B as st,C as yo,D as Yr,E as Ss,F as Es,G as Vr,H as Kr,I as _t,J as kn,K as Xr,L as Qr,M as Zr,N as ea,O as it,P as oa,Q as ta,R as $e,S as vn,T as Pt,U as As,V as na,W as xn,X as Sn,Y as ra,Z as Is,_ as js,a as kr,aa as ca,b as vr,h as Ar,i as Or,j as Rt,k as hn,l as Tr,m as Ir,n as jr,o as Cr,p as Fr,q as Ur,r as qr,s as Wr,t as Br,u as Jr,v as Gr,w as Hr,x as Dt,y as xs,z as $n}from"./chunk-7HHVZJO4.js";import{A as Ts,k as vs,l as yn,m as wn,n as Nr,o as Rr,p as Dr,q as _r,r as Pr,u as bn,v as Mr,w as Lr,x as sa,y as Os,z as ia}from"./chunk-P2Y7DFFP.js";import{a as xr,d as Sr,e as Er}from"./chunk-V5FZJUK4.js";import{D as gr,N as mr,h as Zi,q as er,s as Zo,u as ys,v as tr,x as ho}from"./chunk-T76YTN34.js";import{b as et,c as un,d as fn,e as ot,f as nr,g as Ro,h as Nt}from"./chunk-TCJ3SMOF.js";import{d as bs,f as lr}from"./chunk-VMDA2SX2.js";import{a as Qi}from"./chunk-QLTM3F7M.js";import{a as or,e as cr}from"./chunk-BIFJSQB5.js";import{f as rr,g as ar,h as ws}from"./chunk-76Z4VHDX.js";import{b as ue,c as Se,d as nt,e as dr}from"./chunk-NSYY5NCR.js";import{h as Xi}from"./chunk-DWADWDMU.js";import{b as fo,d as pn,f as hs}from"./chunk-MTVRYTLL.js";import{b as Qo,d as Ki}from"./chunk-2GIDVZ4H.js";import{a as fs,b as Li,c as Zl,d as gn,e as Fi,f as Ji,g as od,h as Gi,i as td,m as Xo,n as zi,o as Yi,s as Vi,v as Ze,w as Ct}from"./chunk-6HMZ5TTM.js";import{a as ro,b as Ko,e as qi,f as jt}from"./chunk-F4HZTZHW.js";import{a as Hi,b as nd}from"./chunk-AJONZWLT.js";import{a as io,b as Ql}from"./chunk-L2WSPY6S.js";import{k as Ui,l as _,m as mn,o as ge}from"./chunk-QJANPP4C.js";import{g as Wi,k as Bi,l as ed}from"./chunk-BH3GTCZ6.js";import{a as Xl}from"./chunk-FIOB3MEX.js";import{Command as sd}from"commander";var wa=new sd().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 vr({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()});ge();import{Command as id}from"commander";import{execFileSync as ao}from"node:child_process";import{cpSync as ba,existsSync as Ds,mkdirSync as Ns,mkdtempSync as rd,readFileSync as ad,rmSync as cd,writeFileSync as $a}from"node:fs";import{dirname as Rs,join as je,resolve as ka}from"node:path";import{homedir as On,release as ld,tmpdir as dd}from"node:os";import{fileURLToPath as gd}from"node:url";import{setTimeout as md}from"node:timers/promises";function Tn(){let e=Nr(process.platform,process.arch,ld());if(e)throw new Error(e)}function Mt(){return`gui/${process.getuid()}/${vs}`}function rt(){return je(On(),"Library/LaunchAgents",`${vs}.plist`)}async function va(){try{ao("launchctl",["bootout",Mt()],{stdio:"pipe"})}catch{}for(let e=0;e<30;e++){try{ao("launchctl",["print",Mt()],{stdio:"pipe"})}catch{return}await md(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function xa(){if(!Ds(rt()))throw new Error("Run agentx desktop install first.");let e=!0;try{ao("launchctl",["print",Mt()],{stdio:"pipe"})}catch{e=!1}e||ao("launchctl",["bootstrap",`gui/${process.getuid()}`,rt()],{stdio:"pipe"}),ao("launchctl",["kickstart",Mt()],{stdio:"pipe"})}function pd(){let e=Rs(gd(import.meta.url));for(let o of[ka(e,".."),ka(e,"../.."),process.cwd()])try{if(JSON.parse(ad(je(o,"package.json"),"utf8")).name==="agentix-cli"&&Ds(je(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 at=new id("desktop").description("install and control the macOS desktop assistant");at.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=>{Tn();let o=_(),t=Rr(o.agents,e.agent),n=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,s=pd(),i=je(On(),"Applications");if(console.log(`Desktop assistant \u2192 ${je(i,yn)}
2
- Computer-use helper \u2192 ${je(i,wn)}
1
+ import{a as ba,b as On,g as $a}from"./chunk-7A7RC3R4.js";import{b as pa}from"./chunk-YQVR2HQS.js";import{a as _o,b as ma,f as An,i as Rs,j as ya,l as wa}from"./chunk-SAFAI4AV.js";import{a as ua,c as fa,d as ha}from"./chunk-2TJ5L7CB.js";import{a as vs,b as hr,c as xs,g as yr,h as wr,j as br,k as $r,m as kr,n as vr,o as xr}from"./chunk-WLVQDEOT.js";import{a as tt}from"./chunk-GV7S5BAX.js";import{e as ar}from"./chunk-GSX4NK2N.js";import{c as cr}from"./chunk-SZDACK6O.js";import{$ as da,A as Kr,B as st,C as yo,D as Xr,E as As,F as Os,G as Qr,H as Zr,I as Pt,J as vn,K as ea,L as oa,M as ta,N as na,O as it,P as sa,Q as ia,R as ke,S as xn,T as Mt,U as Ts,V as ra,W as Sn,X as En,Y as la,Z as Cs,_ as Ns,a as Sr,aa as ga,b as Er,h as jr,i as Ir,j as Dt,k as yn,l as Cr,m as Nr,n as Rr,o as Dr,p as Wr,q as Br,r as Jr,s as Gr,t as Hr,u as zr,v as Yr,w as Vr,x as _t,y as Es,z as kn}from"./chunk-3RCFDI52.js";import{A as js,B as ca,C as Is,k as Ss,l as wn,m as bn,n as _r,o as Pr,p as Mr,q as Lr,r as Fr,u as $n,v as Ur,w as qr,z as aa}from"./chunk-MX5GCR7Y.js";import{a as Ar,d as Or,e as Tr}from"./chunk-V5FZJUK4.js";import{F as ur,P as fr,h as tr,q as nr,s as Nt,u as Zo,w as bs,x as ir,z as ho}from"./chunk-Z7LNSHG3.js";import{b as et,c as fn,d as hn,e as ot,f as rr,g as Do,h as Rt}from"./chunk-TCJ3SMOF.js";import{d as ks,f as mr}from"./chunk-VMDA2SX2.js";import{a as or}from"./chunk-QLTM3F7M.js";import{a as sr,e as gr}from"./chunk-BIFJSQB5.js";import{f as lr,g as dr,h as $s}from"./chunk-76Z4VHDX.js";import{b as fe,c as Ee,d as nt,e as pr}from"./chunk-NSYY5NCR.js";import{h as er}from"./chunk-DWADWDMU.js";import{b as fo,d as un,f as ws}from"./chunk-MTVRYTLL.js";import{b as Qo,d as Zi}from"./chunk-2GIDVZ4H.js";import{a as ys,b as qi,c as td,d as mn,e as Wi,f as zi,g as sd,h as Yi,i as id,m as Xo,n as Ki,o as Xi,s as Qi,v as Ze,w as Ct}from"./chunk-6HMZ5TTM.js";import{a as ro,b as Ko,e as Ji,f as It}from"./chunk-F4HZTZHW.js";import{a as Vi,b as rd}from"./chunk-AJONZWLT.js";import{a as io,b as od}from"./chunk-L2WSPY6S.js";import{k as Bi,l as _,m as pn,o as me}from"./chunk-QJANPP4C.js";import{g as Gi,k as Hi,l as nd}from"./chunk-BH3GTCZ6.js";import{a as ed}from"./chunk-FIOB3MEX.js";import{Command as ad}from"commander";var ka=new ad().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 Er({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()});me();import{Command as cd}from"commander";import{execFileSync as ao}from"node:child_process";import{cpSync as va,existsSync as Ps,mkdirSync as Ds,mkdtempSync as ld,readFileSync as dd,rmSync as gd,writeFileSync as xa}from"node:fs";import{dirname as _s,join as Ce,resolve as Sa}from"node:path";import{homedir as Tn,release as md,tmpdir as pd}from"node:os";import{fileURLToPath as ud}from"node:url";import{setTimeout as fd}from"node:timers/promises";function jn(){let e=_r(process.platform,process.arch,md());if(e)throw new Error(e)}function Lt(){return`gui/${process.getuid()}/${Ss}`}function rt(){return Ce(Tn(),"Library/LaunchAgents",`${Ss}.plist`)}async function Ea(){try{ao("launchctl",["bootout",Lt()],{stdio:"pipe"})}catch{}for(let e=0;e<30;e++){try{ao("launchctl",["print",Lt()],{stdio:"pipe"})}catch{return}await fd(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Aa(){if(!Ps(rt()))throw new Error("Run agentx desktop install first.");let e=!0;try{ao("launchctl",["print",Lt()],{stdio:"pipe"})}catch{e=!1}e||ao("launchctl",["bootstrap",`gui/${process.getuid()}`,rt()],{stdio:"pipe"}),ao("launchctl",["kickstart",Lt()],{stdio:"pipe"})}function hd(){let e=_s(ud(import.meta.url));for(let o of[Sa(e,".."),Sa(e,"../.."),process.cwd()])try{if(JSON.parse(dd(Ce(o,"package.json"),"utf8")).name==="agentix-cli"&&Ps(Ce(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 at=new cd("desktop").description("install and control the macOS desktop assistant");at.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=>{jn();let o=_(),t=Pr(o.agents,e.agent),n=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,s=hd(),i=Ce(Tn(),"Applications");if(console.log(`Desktop assistant \u2192 ${Ce(i,wn)}
2
+ Computer-use helper \u2192 ${Ce(i,bn)}
3
3
  Agent \u2192 ${t}
4
4
  Daemon \u2192 ${n}
5
- Starts at login \u2192 ${rt()}`),e.dryRun)return;try{ao("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=rd(je(dd(),"agentx-desktop-"));try{for(let g of["mac-helper","mac-voice"]){ba(je(s,"apps",g),je(r,g),{recursive:!0,filter:u=>!u.split("/").includes("build")});let d=g==="mac-helper"?_r(o.notifications.local.icon):[];ao("/bin/bash",[je(r,g,"build.sh"),...d],{stdio:"inherit"})}let a=je(On(),"Library/Logs/agentx-desktop.err.log"),c=Dr({executable:je(i,yn,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:t,url:n,helper:Pr(On()),cli:je(s,"dist/cli.js"),node:process.execPath,log:a}),l=je(r,"desktop.plist");$a(l,c,{mode:384}),ao("plutil",["-lint",l],{stdio:"pipe"}),await va(),Ns(i,{recursive:!0});for(let[g,d,u]of[["mac-voice","AgentX Voice.app",yn],["mac-helper",wn,wn]])ba(je(r,g,"build",d),je(i,u),{recursive:!0});Ns(Rs(rt()),{recursive:!0}),Ns(Rs(a),{recursive:!0}),$a(rt(),c,{mode:384}),xa(),console.log(`Desktop assistant is running. Hold Option\u2013Space to speak; Command\u2013Option\u2013V for smart paste.
5
+ Starts at login \u2192 ${rt()}`),e.dryRun)return;try{ao("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=ld(Ce(pd(),"agentx-desktop-"));try{for(let g of["mac-helper","mac-voice"]){va(Ce(s,"apps",g),Ce(r,g),{recursive:!0,filter:u=>!u.split("/").includes("build")});let d=g==="mac-helper"?Lr(o.notifications.local.icon):[];ao("/bin/bash",[Ce(r,g,"build.sh"),...d],{stdio:"inherit"})}let a=Ce(Tn(),"Library/Logs/agentx-desktop.err.log"),c=Mr({executable:Ce(i,wn,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:t,url:n,helper:Fr(Tn()),cli:Ce(s,"dist/cli.js"),node:process.execPath,log:a}),l=Ce(r,"desktop.plist");xa(l,c,{mode:384}),ao("plutil",["-lint",l],{stdio:"pipe"}),await Ea(),Ds(i,{recursive:!0});for(let[g,d,u]of[["mac-voice","AgentX Voice.app",wn],["mac-helper",bn,bn]])va(Ce(r,g,"build",d),Ce(i,u),{recursive:!0});Ds(_s(rt()),{recursive:!0}),Ds(_s(a),{recursive:!0}),xa(rt(),c,{mode:384}),Aa(),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{cd(r,{recursive:!0,force:!0})}});at.command("start").description("start the installed desktop assistant").action(()=>{Tn(),xa(),console.log("Desktop assistant started.")});at.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{Tn(),await va(),console.log("Desktop assistant stopped.")});at.command("status").description("show the desktop login service status").action(()=>{Tn();try{console.log(ao("launchctl",["print",Mt()],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(Ds(rt())?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as bd}from"commander";import{open as $d}from"fs/promises";import{existsSync as Cn,mkdirSync as ud,readFileSync as Nn,writeFileSync as Sa}from"fs";import{homedir as fd}from"os";import{dirname as hd,resolve as _s}from"path";var Ps="/attach/",Ea="/guard/check";function Aa(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 In(e,o,t){let n={hooks:[{type:"command",command:Aa(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function yd(e){return{SessionStart:[In("/attach/session-start",e,"")],UserPromptSubmit:[In("/attach/prompt",e)],Stop:[In("/attach/stop",e)],SessionEnd:[In("/attach/session-end",e)]}}function wd(e){let o=Aa("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function jn(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function Lt(){return _s(fd(),".claude/settings.json")}function Ft(e=process.cwd()){for(let o of[e,_s(e,"..")]){let t=_s(o,"agentx.json");if(Cn(t))try{let n=JSON.parse(Nn(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function Oa(e,o={}){let t=o.path??Lt(),n=o.withGuard!==!1,s={};if(Cn(t))try{s=JSON.parse(Nn(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,d]of Object.entries(yd(e))){let u=Array.isArray(r[g])?r[g].filter(f=>!jn(f,Ps)):[];r[g]=[...u,...d],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(d=>!jn(d,Ea)):[];r.PreToolUse=[...g,...wd(e)],c=!0}let l=JSON.stringify(s)!==i;return l&&(ud(hd(t),{recursive:!0}),Sa(t,`${JSON.stringify(s,null,2)}
8
- `)),{path:t,changed:l,events:a,guardInstalled:c}}function Ta(e={}){let o=e.path??Lt();if(!Cn(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(Nn(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"?Ea:Ps;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let l=s[a].filter(g=>!jn(g,c));l.length!==s[a].length&&i.push(a),l.length===0?delete s[a]:s[a]=l}Object.keys(s).length===0&&delete t.hooks}let r=JSON.stringify(t)!==n;return r&&Sa(o,`${JSON.stringify(t,null,2)}
9
- `),{path:o,changed:r,events:i,guardInstalled:!1}}function Rn(e=Lt()){if(!Cn(e))return!1;try{return!!JSON.parse(Nn(e,"utf-8"))?.hooks?.Stop?.some?.(t=>jn(t,Ps))}catch{return!1}}var Dn=new bd("monitor").description("Register external CLI sessions and report ended runs to the briefing"),Ia=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Ft()}`;async function ja(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)}`)}Dn.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 ja(e.url,"register",Sr.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}});Dn.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 $d(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 ja(e.url,"ended",Er.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 Gf}from"commander";import{Command as kd}from"commander";ge();import O from"chalk";import{existsSync as vd,readFileSync as xd}from"fs";async function Sd(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 eo=new kd().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");eo.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:l}=await import("child_process"),{openSync:g,writeFileSync:d,existsSync:u}=await import("fs"),f=process.argv[1];(!f||!u(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 p=[f,"daemon","start"];e.config&&p.push("-c",e.config),e.port&&p.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=l(process.execPath,p,{detached:!0,stdio:["ignore",y,y],cwd:process.cwd()});k.unref(),d("/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 l=parseInt(o(a,"utf-8").trim(),10);if(l&&l!==process.pid){let g=!1;try{process.kill(l,0),g=!0}catch{}g&&await Sd(l)&&(console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{Ed(i(process.cwd(),".env"))}catch{}await new js(e.config).start()});function Ed(e){if(!vd(e))return;let o=xd(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}}eo.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"))}});eo.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 ${Ad(r.uptime)}`)),console.log(),console.log(O.bold(" Agents:"));for(let c of r.agents){let l=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})`)}${l}${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 l=c.enabled?O.green("\u25CF"):O.dim("\u25CB"),g=c.nextRun?O.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${l} ${c.id}${g}`)}}if(r.mesh?.length){console.log(),console.log(O.bold(" Mesh:"));for(let c of r.mesh){let l=c.healthy?O.green("\u25CF"):O.red("\u25CF"),g=c.skills?.length?O.dim(` (${c.skills.length} agents)`):"";console.log(` ${l} ${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=mn(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}`))}}});eo.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"})});eo.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
7
+ The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{gd(r,{recursive:!0,force:!0})}});at.command("start").description("start the installed desktop assistant").action(()=>{jn(),Aa(),console.log("Desktop assistant started.")});at.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{jn(),await Ea(),console.log("Desktop assistant stopped.")});at.command("status").description("show the desktop login service status").action(()=>{jn();try{console.log(ao("launchctl",["print",Lt()],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(Ps(rt())?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as vd}from"commander";import{open as xd}from"fs/promises";import{existsSync as Nn,mkdirSync as yd,readFileSync as Rn,writeFileSync as Oa}from"fs";import{homedir as wd}from"os";import{dirname as bd,resolve as Ms}from"path";var Ls="/attach/",Ta="/guard/check";function ja(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 In(e,o,t){let n={hooks:[{type:"command",command:ja(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function $d(e){return{SessionStart:[In("/attach/session-start",e,"")],UserPromptSubmit:[In("/attach/prompt",e)],Stop:[In("/attach/stop",e)],SessionEnd:[In("/attach/session-end",e)]}}function kd(e){let o=ja("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function Cn(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function Ft(){return Ms(wd(),".claude/settings.json")}function Ut(e=process.cwd()){for(let o of[e,Ms(e,"..")]){let t=Ms(o,"agentx.json");if(Nn(t))try{let n=JSON.parse(Rn(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function Ia(e,o={}){let t=o.path??Ft(),n=o.withGuard!==!1,s={};if(Nn(t))try{s=JSON.parse(Rn(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,d]of Object.entries($d(e))){let u=Array.isArray(r[g])?r[g].filter(f=>!Cn(f,Ls)):[];r[g]=[...u,...d],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(d=>!Cn(d,Ta)):[];r.PreToolUse=[...g,...kd(e)],c=!0}let l=JSON.stringify(s)!==i;return l&&(yd(bd(t),{recursive:!0}),Oa(t,`${JSON.stringify(s,null,2)}
8
+ `)),{path:t,changed:l,events:a,guardInstalled:c}}function Ca(e={}){let o=e.path??Ft();if(!Nn(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(Rn(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"?Ta:Ls;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let l=s[a].filter(g=>!Cn(g,c));l.length!==s[a].length&&i.push(a),l.length===0?delete s[a]:s[a]=l}Object.keys(s).length===0&&delete t.hooks}let r=JSON.stringify(t)!==n;return r&&Oa(o,`${JSON.stringify(t,null,2)}
9
+ `),{path:o,changed:r,events:i,guardInstalled:!1}}function Dn(e=Ft()){if(!Nn(e))return!1;try{return!!JSON.parse(Rn(e,"utf-8"))?.hooks?.Stop?.some?.(t=>Cn(t,Ls))}catch{return!1}}var _n=new vd("monitor").description("Register external CLI sessions and report ended runs to the briefing"),Na=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Ut()}`;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)}`)}_n.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",Na).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}});_n.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",Na).action(async e=>{try{let o=await xd(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 Xf}from"commander";import{Command as Sd}from"commander";me();import O from"chalk";import{existsSync as Ed,readFileSync as Ad}from"fs";async function Od(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 eo=new Sd().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");eo.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:l}=await import("child_process"),{openSync:g,writeFileSync:d,existsSync:u}=await import("fs"),f=process.argv[1];(!f||!u(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 p=[f,"daemon","start"];e.config&&p.push("-c",e.config),e.port&&p.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=l(process.execPath,p,{detached:!0,stdio:["ignore",y,y],cwd:process.cwd()});k.unref(),d("/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 l=parseInt(o(a,"utf-8").trim(),10);if(l&&l!==process.pid){let g=!1;try{process.kill(l,0),g=!0}catch{}g&&await Od(l)&&(console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{Td(i(process.cwd(),".env"))}catch{}await new Ns(e.config).start()});function Td(e){if(!Ed(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}}eo.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"))}});eo.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 ${jd(r.uptime)}`)),console.log(),console.log(O.bold(" Agents:"));for(let c of r.agents){let l=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})`)}${l}${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 l=c.enabled?O.green("\u25CF"):O.dim("\u25CB"),g=c.nextRun?O.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${l} ${c.id}${g}`)}}if(r.mesh?.length){console.log(),console.log(O.bold(" Mesh:"));for(let c of r.mesh){let l=c.healthy?O.green("\u25CF"):O.red("\u25CF"),g=c.skills?.length?O.dim(` (${c.skills.length} agents)`):"";console.log(` ${l} ${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=pn(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}`))}}});eo.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"})});eo.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:l}=await i.read();if(c)break;a+=r.decode(l,{stream:!0});let g=a.split(`
13
13
  `);a=g.pop()||"";for(let d of g)if(d.startsWith("data: "))try{let u=JSON.parse(d.slice(6)),f=new Date(u.time).toLocaleTimeString(),p=u.message?.replace(/^\[agentx\]\s*/,"")||"";p.includes("executing")?console.log(`${O.dim(f)} ${O.cyan("\u25B6")} ${p}`):p.includes("completed")?console.log(`${O.dim(f)} ${O.green("\u2713")} ${p}`):p.includes("error")||p.includes("Error")?console.log(`${O.dim(f)} ${O.red("\u2717")} ${p}`):p.includes("Routing")?console.log(`${O.dim(f)} ${O.yellow("\u2192")} ${p}`):p.includes("mention")?console.log(`${O.dim(f)} ${O.magenta("@")} ${p}`):p.includes("Skipping")?console.log(`${O.dim(f)} ${O.dim("\u2298")} ${O.dim(p)}`):console.log(`${O.dim(f)} ${p}`)}catch{}else d.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."))}});eo.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,l;t.peer?(c=`${a}/mesh/task`,l={peer:t.peer,message:n,agent:e}):(c=`${a}/task`,l={agent:e,message:n}),console.log(O.dim(` Sending to ${t.peer?`${t.peer}/${e}`:e}...`));let d=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();t.json?console.log(JSON.stringify(d,null,2)):d.error?console.log(O.red(` Error: ${d.error}`)):(console.log(),console.log(d.content||d.response||"No response"),d.duration&&console.log(O.dim(`
14
- (${(d.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"))}});eo.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}`))}});eo.action(async e=>{await new js(e.config).start()});function Ad(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 Od}from"commander";import He from"chalk";import{existsSync as Ut,readFileSync as Td,writeFileSync as Ca,mkdirSync as Na}from"fs";import{hostname as Ra}from"os";import{resolve as ct}from"path";var Da=new Od().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=ct(o,"agentx.json"),n=ct(o,".env"),s=ct(o,".agentx/sessions");if(console.log(),console.log(He.bold(" agentx init")),console.log(),Ut(t)&&!e.force){console.log(He.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[ct(o,"agentx.example.json"),ct(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(Ut(c)){r=Td(c,"utf-8");break}r||(r=JSON.stringify({node:{id:Ra().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:Ra(),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)),Ca(t,r),console.log(He.green(" \u2713 Created agentx.json")),Ut(n)||(Ca(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"))),Ut(s)||(Na(s,{recursive:!0}),console.log(He.green(" \u2713 Created .agentx/sessions/")));let a=ct(o,".claude");Ut(a)||(Na(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 Id}from"commander";import _o from"chalk";import{spawn as Pa}from"child_process";import{existsSync as jd}from"fs";import{dirname as Cd,resolve as Nd}from"path";import{fileURLToPath as Rd}from"url";ge();var Ma=new Id().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=la(),t=e.port?parseInt(e.port,10):Dd(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(_o.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(_o.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(_o.bold(` Opening ${n}`)),console.log(),await Pd(n).catch(()=>!1))console.log(_o.dim(" Dashboard is already running.")),e.open!==!1&&_a(n);else{console.log(_o.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=_d(),r=Pa(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&_a(n),await new Promise(a=>r.on("exit",()=>a()))}});function Dd(){try{return _().dashboard.port||4202}catch{return 4202}}function _d(){let e=Nd(Cd(Rd(import.meta.url)),"cli.js");return jd(e)?e:process.argv[1]||e}async function Pd(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}function _a(e){let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=Pa(o,[e],{stdio:"ignore",detached:!0});t.once("error",()=>{console.log(_o.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),t.unref()}catch{console.log(_o.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as Md}from"commander";import Ee from"chalk";var qt=new Md().name("token").description("scoped API tokens for external access (mesh peers, integrations)");qt.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 En,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(Ee.bold(" Token created.")),console.log(),console.log(` id: ${Ee.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||Ee.dim("never")}`),console.log(),console.log(Ee.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${Ee.green.bold(s)}`),console.log(),console.log(Ee.dim(" Use it via the Authorization header:")),console.log(Ee.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(o){console.log(Ee.red(` ${o.message}`)),process.exit(1)}});qt.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new En().list();if(e.length===0){console.log(Ee.dim(`
14
+ (${(d.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"))}});eo.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}`))}});eo.action(async e=>{await new Ns(e.config).start()});function jd(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 Id}from"commander";import He from"chalk";import{existsSync as qt,readFileSync as Cd,writeFileSync as Da,mkdirSync as _a}from"fs";import{hostname as Pa}from"os";import{resolve as ct}from"path";var Ma=new Id().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=ct(o,"agentx.json"),n=ct(o,".env"),s=ct(o,".agentx/sessions");if(console.log(),console.log(He.bold(" agentx init")),console.log(),qt(t)&&!e.force){console.log(He.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[ct(o,"agentx.example.json"),ct(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(qt(c)){r=Cd(c,"utf-8");break}r||(r=JSON.stringify({node:{id:Pa().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:Pa(),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)),Da(t,r),console.log(He.green(" \u2713 Created agentx.json")),qt(n)||(Da(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"))),qt(s)||(_a(s,{recursive:!0}),console.log(He.green(" \u2713 Created .agentx/sessions/")));let a=ct(o,".claude");qt(a)||(_a(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 Nd}from"commander";import Po from"chalk";import{spawn as Fa}from"child_process";import{existsSync as Rd}from"fs";import{dirname as Dd,resolve as _d}from"path";import{fileURLToPath as Pd}from"url";me();var Ua=new Nd().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=ma(),t=e.port?parseInt(e.port,10):Md(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(Po.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(Po.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(Po.bold(` Opening ${n}`)),console.log(),await Fd(n).catch(()=>!1))console.log(Po.dim(" Dashboard is already running.")),e.open!==!1&&La(n);else{console.log(Po.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=Ld(),r=Fa(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&La(n),await new Promise(a=>r.on("exit",()=>a()))}});function Md(){try{return _().dashboard.port||4202}catch{return 4202}}function Ld(){let e=_d(Dd(Pd(import.meta.url)),"cli.js");return Rd(e)?e:process.argv[1]||e}async function Fd(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}function La(e){let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=Fa(o,[e],{stdio:"ignore",detached:!0});t.once("error",()=>{console.log(Po.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),t.unref()}catch{console.log(Po.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as Ud}from"commander";import Ae from"chalk";var Wt=new Ud().name("token").description("scoped API tokens for external access (mesh peers, integrations)");Wt.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 An,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(Ae.bold(" Token created.")),console.log(),console.log(` id: ${Ae.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||Ae.dim("never")}`),console.log(),console.log(Ae.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${Ae.green.bold(s)}`),console.log(),console.log(Ae.dim(" Use it via the Authorization header:")),console.log(Ae.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(o){console.log(Ae.red(` ${o.message}`)),process.exit(1)}});Wt.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new An().list();if(e.length===0){console.log(Ae.dim(`
16
16
  No tokens issued.
17
- `));return}console.log();for(let o of e){let t=o.revokedAt?Ee.red("revoked"):o.expiresAt&&Date.parse(o.expiresAt)<Date.now()?Ee.red("expired"):Ee.green("active");console.log(` ${Ee.cyan(o.id)} ${t} ${o.name}`),console.log(Ee.dim(` prefix: ${o.prefix}\u2026 scopes: ${o.scopes.join(", ")}`)),console.log(Ee.dim(` created: ${o.createdAt}${o.expiresAt?` expires: ${o.expiresAt}`:""}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(Ee.red(` ${e.message}`)),process.exit(1)}});qt.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new En().revoke(e);o||(console.log(Ee.red(` Token ${e} not found.`)),process.exit(1)),console.log(Ee.green(`
17
+ `));return}console.log();for(let o of e){let t=o.revokedAt?Ae.red("revoked"):o.expiresAt&&Date.parse(o.expiresAt)<Date.now()?Ae.red("expired"):Ae.green("active");console.log(` ${Ae.cyan(o.id)} ${t} ${o.name}`),console.log(Ae.dim(` prefix: ${o.prefix}\u2026 scopes: ${o.scopes.join(", ")}`)),console.log(Ae.dim(` created: ${o.createdAt}${o.expiresAt?` expires: ${o.expiresAt}`:""}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(Ae.red(` ${e.message}`)),process.exit(1)}});Wt.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new An().revoke(e);o||(console.log(Ae.red(` Token ${e} not found.`)),process.exit(1)),console.log(Ae.green(`
18
18
  \u2713 Revoked ${e} (${o.name})
19
- `))}catch(o){console.log(Ee.red(` ${o.message}`)),process.exit(1)}});ge();import{Command as to}from"commander";import h from"chalk";import Ie from"prompts";import{readFileSync as bo,writeFileSync as lt,existsSync as me,mkdirSync as oo,cpSync as Ms,readdirSync as Fs}from"fs";import{resolve as G,join as wo,dirname as Ld}from"path";import{fileURLToPath as Fd}from"url";function se(){let e=G(process.cwd(),"agentx.json");if(!me(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(bo(e,"utf-8"))}function Pe(e){return ue(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 Po=new to().name("agent").description("manage agents \u2014 add, list, remove");Po.command("list").alias("ls").description("list configured agents").action(()=>{let e=se();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()});Po.command("add").description("add a new agent interactively").action(async()=>{let e=se(),o=await Ie([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:l=>/^[a-z0-9-]+$/.test(l)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:G(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:wo(o.workspace,o.id);oo(G(t,".claude/skills"),{recursive:!0});let n={name:o.name,workspace:t,tier:o.tier,model:o.model,mentions:o.mentions?.map(l=>l.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",(...l)=>{console.log(h.dim(` ${l.join(" ")}`))}),r=G(process.cwd(),"src/wiki/SKILL.md"),a=G(Ld(Fd(import.meta.url)),"../wiki/SKILL.md"),c=me(r)?r:a;me(c)&&(oo(G(t,".claude/skills/wiki"),{recursive:!0}),Ms(c,G(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await Pe(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()});Po.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=se();if(!o.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete o.agents[e],await Pe(o),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});Po.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=se(),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 Pe(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 Wt=new to().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");Wt.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=se().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(Ae.red(` ${o.message}`)),process.exit(1)}});me();import{Command as to}from"commander";import h from"chalk";import Ie from"prompts";import{readFileSync as bo,writeFileSync as lt,existsSync as pe,mkdirSync as oo,cpSync as Fs,readdirSync as qs}from"fs";import{resolve as G,join as wo,dirname as qd}from"path";import{fileURLToPath as Wd}from"url";function ie(){let e=G(process.cwd(),"agentx.json");if(!pe(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(bo(e,"utf-8"))}function Pe(e){return fe(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 Mo=new to().name("agent").description("manage agents \u2014 add, list, remove");Mo.command("list").alias("ls").description("list configured agents").action(()=>{let e=ie();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()});Mo.command("add").description("add a new agent interactively").action(async()=>{let e=ie(),o=await Ie([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:l=>/^[a-z0-9-]+$/.test(l)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:G(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:wo(o.workspace,o.id);oo(G(t,".claude/skills"),{recursive:!0});let n={name:o.name,workspace:t,tier:o.tier,model:o.model,mentions:o.mentions?.map(l=>l.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",(...l)=>{console.log(h.dim(` ${l.join(" ")}`))}),r=G(process.cwd(),"src/wiki/SKILL.md"),a=G(qd(Wd(import.meta.url)),"../wiki/SKILL.md"),c=pe(r)?r:a;pe(c)&&(oo(G(t,".claude/skills/wiki"),{recursive:!0}),Fs(c,G(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await Pe(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()});Mo.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=ie();if(!o.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete o.agents[e],await Pe(o),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});Mo.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=ie(),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 Pe(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 Bt=new to().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");Bt.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=ie().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,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?h.green(`${g}:${d}=set`):h.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(h.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).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(" ")}`),l&&console.log(` ${h.dim(l)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});Wt.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=se();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-5V444ZFW.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Ie({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 Ie({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(),l=String(o.sessionDir||"").trim();if(!a&&!c&&!l&&n){let u=await Ie({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"}]});u.scheme==="tokenEnv"?a=((await Ie({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():u.scheme==="keyring"?c="keyring":u.scheme==="sessionDir"&&(l=((await Ie({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let u of String(o.metadata).split(",")){let[f,...p]=u.split("=");f&&(g[f.trim()]=p.join("=").trim())}else if(n){let u=await Ie({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(u.metadata)for(let f of String(u.metadata).split(",")){let[p,...w]=f.split("=");p&&(g[p.trim()]=w.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).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(u=>u.kind===i&&u.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:d,metadata:g,enabled:!0}),await Pe(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`))});Wt.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=se(),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(l=>l.kind===i&&(!r||l.label===r)||l.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await Pe(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Wt.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=se().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??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});Po.addCommand(Wt);var _n=new to().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");_n.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=se();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()});_n.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=se(),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 Ie({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 Ie([{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 Pe(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Ie([{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 Ie([{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 Pe(e),oo(G(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 Ie([{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 Ie([{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 Pe(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 dt=new to().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");dt.command("list").alias("ls").description("list cron jobs").action(()=>{let e=se();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()});dt.command("add").description("add a cron job").action(async()=>{let e=se(),o=Object.keys(e.agents||{}),t=await Ie([{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 Pe(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});dt.command("enable <id>").description("enable a cron job").action(async e=>{let o=se();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}if(o.crons[e].approval?.action==="create"){console.log(h.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}o.crons[e].enabled=!0,await Pe(o),console.log(h.green(` Cron "${e}" enabled`))});dt.command("disable <id>").description("disable a cron job").action(async e=>{let o=se();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Pe(o),console.log(h.green(` Cron "${e}" disabled`))});var gt=new to().name("mesh").description("manage mesh peers \u2014 add, list, remove");gt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=se();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()});gt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=se(),o=await Ie([{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 Pe(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});gt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=se();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Pe(o),console.log(h.green(` Peer "${e}" removed`)))});gt.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=se();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 Pe(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 Mo=new to().name("skill").description("manage skills \u2014 add to agent(s), list");Mo.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=se(),n=G(e);if(!me(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=me(wo(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 Ie({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=G(a.workspace,".claude/skills",s);oo(c,{recursive:!0}),me(wo(n,"SKILL.md"))?Ms(n,c,{recursive:!0}):n.endsWith(".md")&&Ms(n,wo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Mo.command("list").alias("ls").description("list skills per agent").action(()=>{let e=se();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=G(t.workspace,".claude/skills"),s=me(n)?Fs(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});Mo.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]:[G(n,"src",e,"SKILL.md"),G(n,"skills",e,"SKILL.md")],i=s.find(k=>me(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=bo(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=_()}catch(k){console.log(h.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([k])=>k===o.agent):g;if(d.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 u=0,f=0,p=0,w=0;for(let[k,b]of d){let S=b.workspace;if(!S||!me(S)){console.log(` ${h.yellow("\u2717")} ${k.padEnd(22)} ${h.dim("(workspace missing: "+(S||"undefined")+")")}`),w++;continue}let A=G(S,".claude/skills",e),x=G(A,"SKILL.md");if(!me(x)){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||(oo(A,{recursive:!0}),lt(x,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let v=bo(x,"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+")")}`),p++;continue}let C=(v.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||lt(x,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 ${u}, ${y} update ${f}, ${p} already current, ${w} skipped.`)),o.dryRun&&(u>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Mo.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=se().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(G(f.workspace))}else if(e.allWorkspaces){let u=se();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(G(f.workspace))}else i.push(G(e.cwd));let r=G(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>o(u)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=t({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(u=>({name:u.name,verdict:u.verdict,reasons:u.reasons,path:u.skill?.path})),null,2));else{let u={PASS:0,REVIEW:0,FAILING:0};for(let f of d)u[f.verdict]++;console.log();for(let f of d){let p=f.verdict==="PASS"?h.green("PASS "):f.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${p} ${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(`${u.PASS} PASS`)} ${h.yellow(`${u.REVIEW} REVIEW`)} ${h.red(`${u.FAILING} FAILING`)}`),console.log()}process.exit(d.some(u=>u.verdict==="FAILING")?1:0)});Mo.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=se(),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-KPQWIC22.js"),c=await r(i.workspace);if(c.length===0){console.log(h.yellow(` ${s} has no skills`));return}let l=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:l.skill?.frontmatter.name??null,anyRelevant:l.anyRelevant,confidence:l.confidence,judged:l.judged,reason:l.reason,shortlist:l.shortlist},null,2));return}if(console.log(),l.skill?(console.log(` ${h.green("\u2192")} ${h.bold(l.skill.frontmatter.name)} ${h.dim(`\xB7 ${l.reason}`)}`),console.log(` ${h.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${h.yellow("\xB7")} no skill for this ${h.dim(`\u2014 ${l.reason}`)}`),l.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,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?h.green(`${g}:${d}=set`):h.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(h.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).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(" ")}`),l&&console.log(` ${h.dim(l)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});Bt.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=ie();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-5V444ZFW.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Ie({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 Ie({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(),l=String(o.sessionDir||"").trim();if(!a&&!c&&!l&&n){let u=await Ie({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"}]});u.scheme==="tokenEnv"?a=((await Ie({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():u.scheme==="keyring"?c="keyring":u.scheme==="sessionDir"&&(l=((await Ie({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let u of String(o.metadata).split(",")){let[f,...p]=u.split("=");f&&(g[f.trim()]=p.join("=").trim())}else if(n){let u=await Ie({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(u.metadata)for(let f of String(u.metadata).split(",")){let[p,...w]=f.split("=");p&&(g[p.trim()]=w.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).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(u=>u.kind===i&&u.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:d,metadata:g,enabled:!0}),await Pe(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`))});Bt.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=ie(),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(l=>l.kind===i&&(!r||l.label===r)||l.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await Pe(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Bt.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=ie().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??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});Mo.addCommand(Bt);var Pn=new to().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Pn.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ie();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()});Pn.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ie(),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 Ie({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 Ie([{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 Pe(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Ie([{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 Ie([{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 Pe(e),oo(G(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 Ie([{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 Ie([{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 Pe(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 dt=new to().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");dt.command("list").alias("ls").description("list cron jobs").action(()=>{let e=ie();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()});dt.command("add").description("add a cron job").action(async()=>{let e=ie(),o=Object.keys(e.agents||{}),t=await Ie([{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 Pe(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});dt.command("enable <id>").description("enable a cron job").action(async e=>{let o=ie();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}if(o.crons[e].approval?.action==="create"){console.log(h.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}o.crons[e].enabled=!0,await Pe(o),console.log(h.green(` Cron "${e}" enabled`))});dt.command("disable <id>").description("disable a cron job").action(async e=>{let o=ie();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Pe(o),console.log(h.green(` Cron "${e}" disabled`))});var gt=new to().name("mesh").description("manage mesh peers \u2014 add, list, remove");gt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=ie();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()});gt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=ie(),o=await Ie([{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 Pe(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});gt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=ie();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Pe(o),console.log(h.green(` Peer "${e}" removed`)))});gt.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=ie();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 Pe(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 Lo=new to().name("skill").description("manage skills \u2014 add to agent(s), list");Lo.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=ie(),n=G(e);if(!pe(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=pe(wo(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 Ie({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=G(a.workspace,".claude/skills",s);oo(c,{recursive:!0}),pe(wo(n,"SKILL.md"))?Fs(n,c,{recursive:!0}):n.endsWith(".md")&&Fs(n,wo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Lo.command("list").alias("ls").description("list skills per agent").action(()=>{let e=ie();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=G(t.workspace,".claude/skills"),s=pe(n)?qs(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});Lo.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]:[G(n,"src",e,"SKILL.md"),G(n,"skills",e,"SKILL.md")],i=s.find(k=>pe(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=bo(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=_()}catch(k){console.log(h.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([k])=>k===o.agent):g;if(d.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 u=0,f=0,p=0,w=0;for(let[k,b]of d){let S=b.workspace;if(!S||!pe(S)){console.log(` ${h.yellow("\u2717")} ${k.padEnd(22)} ${h.dim("(workspace missing: "+(S||"undefined")+")")}`),w++;continue}let A=G(S,".claude/skills",e),x=G(A,"SKILL.md");if(!pe(x)){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||(oo(A,{recursive:!0}),lt(x,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let v=bo(x,"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+")")}`),p++;continue}let C=(v.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||lt(x,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 ${u}, ${y} update ${f}, ${p} already current, ${w} skipped.`)),o.dryRun&&(u>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Lo.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=ie().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(G(f.workspace))}else if(e.allWorkspaces){let u=ie();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(G(f.workspace))}else i.push(G(e.cwd));let r=G(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>o(u)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=t({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(u=>({name:u.name,verdict:u.verdict,reasons:u.reasons,path:u.skill?.path})),null,2));else{let u={PASS:0,REVIEW:0,FAILING:0};for(let f of d)u[f.verdict]++;console.log();for(let f of d){let p=f.verdict==="PASS"?h.green("PASS "):f.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${p} ${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(`${u.PASS} PASS`)} ${h.yellow(`${u.REVIEW} REVIEW`)} ${h.red(`${u.FAILING} FAILING`)}`),console.log()}process.exit(d.some(u=>u.verdict==="FAILING")?1:0)});Lo.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=ie(),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-KPQWIC22.js"),c=await r(i.workspace);if(c.length===0){console.log(h.yellow(` ${s} has no skills`));return}let l=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:l.skill?.frontmatter.name??null,anyRelevant:l.anyRelevant,confidence:l.confidence,judged:l.judged,reason:l.reason,shortlist:l.shortlist},null,2));return}if(console.log(),l.skill?(console.log(` ${h.green("\u2192")} ${h.bold(l.skill.frontmatter.name)} ${h.dim(`\xB7 ${l.reason}`)}`),console.log(` ${h.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${h.yellow("\xB7")} no skill for this ${h.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(h.dim(`
23
23
  shortlist (lexical -> judged)`));for(let g of l.shortlist.slice(0,6)){let d=g.p===void 0?" - ":g.p.toFixed(2);console.log(h.dim(` ${g.lexical.toFixed(2)} -> ${d} ${g.name}`))}}l.judged||console.log(h.dim(`
24
- (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var Bt=new to().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Bt.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=G(o.cwd),n=G(t,"references/example"),s=G(t,"references/recipes/example.yaml");me(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=G(t,".agentx/references",e),r=G(t,".agentx/references/recipes");oo(i,{recursive:!0}),oo(r,{recursive:!0});let a=Fs(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let u=wo(i,d);if(me(u)&&!o.force){console.log(h.dim(` skip ${u} (exists; --force to overwrite)`)),l++;continue}let p=bo(wo(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);lt(u,p),console.log(h.green(` + ${u}`)),c++}let g=wo(r,`${e}.yaml`);if(me(g)&&!o.force)console.log(h.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(me(s)){let d=bo(s,"utf-8").replaceAll("example.",`${e}.`);lt(g,d),console.log(h.green(` + ${g}`)),c++}console.log(),console.log(h.dim(` ${c} written, ${l} 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()});Bt.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=G(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 l=Object.fromEntries(Object.entries(c.byKind).map(([w,y])=>[w,y.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let g=s(c,e),d=G(o.referencesCwd||o.cwd),u=G(d,".agentx/references",e);if(!o.write){console.log(),console.log(h.dim(` Dry-run \u2014 would write to ${u}/`));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 Jt=new to().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Jt.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=G(o.cwd),n=G(t,"references/example"),s=G(t,"references/recipes/example.yaml");pe(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=G(t,".agentx/references",e),r=G(t,".agentx/references/recipes");oo(i,{recursive:!0}),oo(r,{recursive:!0});let a=qs(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let u=wo(i,d);if(pe(u)&&!o.force){console.log(h.dim(` skip ${u} (exists; --force to overwrite)`)),l++;continue}let p=bo(wo(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);lt(u,p),console.log(h.green(` + ${u}`)),c++}let g=wo(r,`${e}.yaml`);if(pe(g)&&!o.force)console.log(h.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(pe(s)){let d=bo(s,"utf-8").replaceAll("example.",`${e}.`);lt(g,d),console.log(h.green(` + ${g}`)),c++}console.log(),console.log(h.dim(` ${c} written, ${l} 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()});Jt.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=G(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 l=Object.fromEntries(Object.entries(c.byKind).map(([w,y])=>[w,y.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let g=s(c,e),d=G(o.referencesCwd||o.cwd),u=G(d,".agentx/references",e);if(!o.write){console.log(),console.log(h.dim(` Dry-run \u2014 would write to ${u}/`));for(let[w,y]of Object.entries(g))console.log(h.cyan(`
25
25
  --- ${w} ---`)),console.log(y.split(`
26
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 ${u}/`)),console.log();return}oo(u,{recursive:!0});let f=0,p=0;for(let[w,y]of Object.entries(g)){let k=wo(u,w);if(me(k)&&!o.force){console.log(h.dim(` skip ${k} (exists; --force to overwrite)`)),p++;continue}lt(k,y),console.log(h.green(` + ${k}`)),f++}console.log(),console.log(h.dim(` ${f} written, ${p} 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()});Bt.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(G(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 Us=new to().name("hook").description("manage hooks \u2014 add to agent workspace");Us.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=se().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=G(t.workspace,".claude/settings.json"),s=me(n)?JSON.parse(bo(n,"utf-8")):{},i=await Ie([{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),oo(G(t.workspace,".claude"),{recursive:!0}),lt(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var qs=new to().name("migrate").description("import configuration from OpenClaw or other tools");qs.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,G(process.env.HOME||"",".openclaw/openclaw.json"),G(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of t)if(f&&me(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(bo(n,"utf-8")),i=me(G(process.cwd(),"agentx.json"))?se():{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 l=0;for(let f of r){if(f.workspace?.startsWith("/data"))continue;let p=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),w=f.groupChat?.mentionPatterns||[];if(w.some(y=>y===p)||w.push(p),i.agents[p]={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"},l++,!o.dryRun){oo(G(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-G6KGWPHY.js");y(p,i.agents[p])}}console.log(` ${h.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let g=s.channels?.telegram?.accounts||{},d=0;for(let[f,p]of Object.entries(g)){if(!p.botToken)continue;let y=c[f]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[f]={token:p.botToken,agentBinding:y},i.channels.telegram.enabled=!0,d++}console.log(` ${h.green(d)} Telegram accounts imported`);let u=G(n,"../cron/jobs.json");if(me(u)){let f=JSON.parse(bo(u,"utf-8")),p=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"]},p++}console.log(` ${h.green(p)} cron jobs imported`)}o.dryRun?(console.log(h.yellow(`
29
+ `).length-30} more lines truncated in preview)`));console.log(),console.log(h.dim(` Re-run with --write to commit these to ${u}/`)),console.log();return}oo(u,{recursive:!0});let f=0,p=0;for(let[w,y]of Object.entries(g)){let k=wo(u,w);if(pe(k)&&!o.force){console.log(h.dim(` skip ${k} (exists; --force to overwrite)`)),p++;continue}lt(k,y),console.log(h.green(` + ${k}`)),f++}console.log(),console.log(h.dim(` ${f} written, ${p} 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()});Jt.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(G(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 Ws=new to().name("hook").description("manage hooks \u2014 add to agent workspace");Ws.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=ie().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=G(t.workspace,".claude/settings.json"),s=pe(n)?JSON.parse(bo(n,"utf-8")):{},i=await Ie([{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),oo(G(t.workspace,".claude"),{recursive:!0}),lt(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var Bs=new to().name("migrate").description("import configuration from OpenClaw or other tools");Bs.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,G(process.env.HOME||"",".openclaw/openclaw.json"),G(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of t)if(f&&pe(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(bo(n,"utf-8")),i=pe(G(process.cwd(),"agentx.json"))?ie():{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 l=0;for(let f of r){if(f.workspace?.startsWith("/data"))continue;let p=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),w=f.groupChat?.mentionPatterns||[];if(w.some(y=>y===p)||w.push(p),i.agents[p]={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"},l++,!o.dryRun){oo(G(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-G6KGWPHY.js");y(p,i.agents[p])}}console.log(` ${h.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let g=s.channels?.telegram?.accounts||{},d=0;for(let[f,p]of Object.entries(g)){if(!p.botToken)continue;let y=c[f]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[f]={token:p.botToken,agentBinding:y},i.channels.telegram.enabled=!0,d++}console.log(` ${h.green(d)} Telegram accounts imported`);let u=G(n,"../cron/jobs.json");if(pe(u)){let f=JSON.parse(bo(u,"utf-8")),p=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"]},p++}console.log(` ${h.green(p)} cron jobs imported`)}o.dryRun?(console.log(h.yellow(`
30
30
  Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await Pe(i),console.log(h.green(`
31
- Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var $o=new to().name("config").description("validate and inspect configuration");$o.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=mn(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=me(G(r,".claude")),c=me(G(r,"CLAUDE.md")),l=me(G(r,".claude/settings.json")),g=me(G(r,".claude/skills"))?Fs(G(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,d=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",l?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});$o.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 Ud(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 Ls(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}$o.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-E6NQLFWR.js"),{expandEnvVars:r}=await import("./config-5V444ZFW.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")),l=o.raw?c:r(c),g=i(l,e);o.json?console.log(JSON.stringify(g)):console.log(Ls(g))});$o.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-E6NQLFWR.js"),r=Ud(o,!!t.string),a=await n(l=>{s(l,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: ${Ls(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${Ls(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})`)))});$o.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-E6NQLFWR.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.")))});$o.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 d=_(e.config);o=!!d.business?.enabled,t=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}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 l=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${l(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 qd}from"commander";import ko from"chalk";import{resolve as vo}from"path";import{existsSync as Wd}from"fs";var co=new qd().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Lo(e){let o=vo(e,".agentx/db.sqlite");Wd(o)||(console.log(ko.red(` No SQLite at ${o}`)),console.log(ko.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=Qi({path:o});return t||(console.log(ko.red(` Could not open ${o}`)),console.log(ko.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function Fo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(ko.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])))}co.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(vo(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=`
31
+ Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var $o=new to().name("config").description("validate and inspect configuration");$o.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=pn(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=pe(G(r,".claude")),c=pe(G(r,"CLAUDE.md")),l=pe(G(r,".claude/settings.json")),g=pe(G(r,".claude/skills"))?qs(G(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,d=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",l?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});$o.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 Bd(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 Us(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}$o.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-E6NQLFWR.js"),{expandEnvVars:r}=await import("./config-5V444ZFW.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")),l=o.raw?c:r(c),g=i(l,e);o.json?console.log(JSON.stringify(g)):console.log(Us(g))});$o.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-E6NQLFWR.js"),r=Bd(o,!!t.string),a=await n(l=>{s(l,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: ${Us(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${Us(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})`)))});$o.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-E6NQLFWR.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.")))});$o.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 d=_(e.config);o=!!d.business?.enabled,t=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}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 l=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${l(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 Jd}from"commander";import ko from"chalk";import{resolve as vo}from"path";import{existsSync as Gd}from"fs";var co=new Jd().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Fo(e){let o=vo(e,".agentx/db.sqlite");Gd(o)||(console.log(ko.red(` No SQLite at ${o}`)),console.log(ko.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=or({path:o});return t||(console.log(ko.red(` Could not open ${o}`)),console.log(ko.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function Uo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(ko.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])))}co.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=Fo(vo(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)});Fo(i,!!e.json)});co.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(vo(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)});Uo(i,!!e.json)});co.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=Fo(vo(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)});Fo(r,!!e.json)});co.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(vo(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)});Uo(r,!!e.json)});co.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=Fo(vo(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);Fo(i,!!e.json)});co.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(vo(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);Uo(i,!!e.json)});co.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=Fo(vo(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)});Fo(r,!!e.json)});co.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(vo(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)});Uo(r,!!e.json)});co.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=Fo(vo(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)});Fo(i,!!e.json)});co.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=Lo(vo(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}));Fo(n,!!e.json)});co.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(vo(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(ko.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(ko.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();Fo(n,!!o.json)}catch(n){console.log(ko.red(` ${n.message}`)),process.exit(1)}});import{Command as Gd}from"commander";import z from"chalk";import{mkdtempSync as Hd}from"fs";import{tmpdir as zd}from"os";import{resolve as Fa,join as Ua}from"path";import{existsSync as Yd}from"fs";import Vd from"better-sqlite3";function La(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,l)=>c.ts!==l.ts?c.ts-l.ts:c.kind===l.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(p){r.push({eventId:c.resolution.decisionEventId,decidedBy:c.resolution.decisionDecidedBy,expected:{agentId:null,outcome:"resolved"},actual:{agentId:null,outcome:"resolution-failed"},reason:`recordResolution threw: ${p?.message??p}`})}continue}let l=c.decision,g=s.get(l.eventId);if(!g){r.push({eventId:l.eventId,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:null,outcome:"skipped"},reason:"decision references event not in snapshot"});continue}let d=Bd(l),u={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=cr(e,u,d,()=>l.decidedAt);a+=1,(f.outcome!==l.outcome||f.agentId!==l.agentId)&&r.push({eventId:g.id,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:f.agentId,outcome:f.outcome},reason:Jd(l,f)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function Bd(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function Jd(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 xo=new Gd().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function mt(e){let o=Fa(e.cwd??process.cwd()),t=Fa(o,e.path??".agentx/intent/ledger.sqlite");Yd(t)||(console.log(z.red(` No ledger at ${t}`)),console.log(z.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 Vd(t,{readonly:!0})}catch(n){console.log(z.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(z.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Uo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(z.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 Kd(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 Pn(e){if(!e)return;let o=Kd(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(z.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}xo.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=mt(e),t=Pn(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}),l=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}),d=o.prepare(`
82
+ `,i=o.prepare(s).all({...n,limit:Number(e.limit)});Uo(i,!!e.json)});co.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=Fo(vo(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}));Uo(n,!!e.json)});co.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=Fo(vo(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(ko.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(ko.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();Uo(n,!!o.json)}catch(n){console.log(ko.red(` ${n.message}`)),process.exit(1)}});import{Command as Yd}from"commander";import z from"chalk";import{mkdtempSync as Vd}from"fs";import{tmpdir as Kd}from"os";import{resolve as Wa,join as Ba}from"path";import{existsSync as Xd}from"fs";import Qd from"better-sqlite3";function qa(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,l)=>c.ts!==l.ts?c.ts-l.ts:c.kind===l.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(p){r.push({eventId:c.resolution.decisionEventId,decidedBy:c.resolution.decisionDecidedBy,expected:{agentId:null,outcome:"resolved"},actual:{agentId:null,outcome:"resolution-failed"},reason:`recordResolution threw: ${p?.message??p}`})}continue}let l=c.decision,g=s.get(l.eventId);if(!g){r.push({eventId:l.eventId,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:null,outcome:"skipped"},reason:"decision references event not in snapshot"});continue}let d=Hd(l),u={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=gr(e,u,d,()=>l.decidedAt);a+=1,(f.outcome!==l.outcome||f.agentId!==l.agentId)&&r.push({eventId:g.id,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:f.agentId,outcome:f.outcome},reason:zd(l,f)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function Hd(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function zd(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 xo=new Yd().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function mt(e){let o=Wa(e.cwd??process.cwd()),t=Wa(o,e.path??".agentx/intent/ledger.sqlite");Xd(t)||(console.log(z.red(` No ledger at ${t}`)),console.log(z.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 Qd(t,{readonly:!0})}catch(n){console.log(z.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(z.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function qo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(z.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 Zd(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 Mn(e){if(!e)return;let o=Zd(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(z.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}xo.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=mt(e),t=Mn(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}),l=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}),d=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:l,divergencesBySource:g,inFlight:d},null,2));return}console.log(z.bold("Events by source")),Uo(r,!1),console.log(),console.log(z.bold(`Decisions: ${a}`)),Uo(c,!1),console.log(),console.log(z.bold(`Divergences: ${l}`)),Uo(g,!1),console.log(),console.log(z.bold(`In-flight (dispatched, no resolution): ${d}`))});xo.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=mt(e),t=Pn(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:l,divergencesBySource:g,inFlight:d},null,2));return}console.log(z.bold("Events by source")),qo(r,!1),console.log(),console.log(z.bold(`Decisions: ${a}`)),qo(c,!1),console.log(),console.log(z.bold(`Divergences: ${l}`)),qo(g,!1),console.log(),console.log(z.bold(`In-flight (dispatched, no resolution): ${d}`))});xo.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=mt(e),t=Mn(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);Uo(r,!!e.json)});xo.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=mt(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);qo(r,!!e.json)});xo.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=mt(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);Uo(s,!!e.json)});xo.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=mt(e),t=Pn(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);qo(s,!!e.json)});xo.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=mt(e),t=Mn(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,7 +125,7 @@ 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);Uo(r,!!e.json)});xo.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=mt(o),n=null,s=null;if(o.bySubject){let d=e.indexOf(":");d<0&&(console.log(z.red(' --by-subject expects "<project>:<subject>"')),process.exit(1)),n=e.slice(0,d),s=e.slice(d+1)}else{let d=t.prepare("SELECT project, subject FROM intent_events WHERE id = ?").get(e);d||(console.log(z.red(` no event with id ${e}`)),process.exit(1)),n=d.project,s=d.subject,(n===null||s===null)&&(console.log(z.yellow(` event ${e} has no (project, subject) \u2014 lineage requires both`)),n&&console.log(z.dim(` project: ${n}`)),s&&console.log(z.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
128
+ `).all(s);qo(r,!!e.json)});xo.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=mt(o),n=null,s=null;if(o.bySubject){let d=e.indexOf(":");d<0&&(console.log(z.red(' --by-subject expects "<project>:<subject>"')),process.exit(1)),n=e.slice(0,d),s=e.slice(d+1)}else{let d=t.prepare("SELECT project, subject FROM intent_events WHERE id = ?").get(e);d||(console.log(z.red(` no event with id ${e}`)),process.exit(1)),n=d.project,s=d.subject,(n===null||s===null)&&(console.log(z.yellow(` event ${e} has no (project, subject) \u2014 lineage requires both`)),n&&console.log(z.dim(` project: ${n}`)),s&&console.log(z.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
129
  FROM intent_events WHERE project = ? AND subject = ? ORDER BY ts ASC`).all(n,s);if(i.length===0){console.log(z.dim(` (no events for ${n}:${s})`));return}let r=i.map(d=>d.id),a=r.map((d,u)=>`@id${u}`).join(", "),c=Object.fromEntries(r.map((d,u)=>[`id${u}`,d])),l=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
@@ -134,7 +134,7 @@ 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 d=i.map(u=>({event:u,decisions:l.filter(f=>f.event_id===u.id)}));console.log(JSON.stringify({project:n,subject:s,lineage:d},null,2));return}let g=new Set;for(let d of l)d.outcome==="dispatched"&&d.agent_id&&g.add(d.agent_id);console.log(),console.log(z.bold(` Lineage for ${z.cyan(n+":"+s)}`)),console.log(z.dim(` ${i.length} event(s), ${l.length} decision(s), ${g.size} distinct agent(s) dispatched`)),console.log();for(let d of i){let u=new Date(d.ts).toISOString().slice(0,19).replace("T"," ");console.log(` ${z.dim(u)} ${z.bold(d.id)} ${z.dim(`(${d.source}/${d.intent})`)}`);let f=l.filter(p=>p.event_id===d.id);if(f.length===0){console.log(z.dim(" (no decisions yet)"));continue}for(let p of f){let w=p.outcome==="dispatched"?z.green(p.outcome):p.outcome==="dropped"?z.dim(p.outcome):z.yellow(p.outcome),y=p.agent_id?z.cyan(p.agent_id):z.dim("-"),k=p.reason?z.dim(` \u2014 ${p.reason.slice(0,60)}`):"";if(console.log(` ${z.dim(p.decided_by)} \u2192 ${w} ${y}${k}`),p.resolution_status){let b=p.resolution_status==="ok"?z.green(p.resolution_status):z.red(p.resolution_status),S=p.duration_ms?`${(p.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${z.dim("resolved")} ${b} ${z.dim(S)}`)}else p.outcome==="dispatched"&&console.log(` ${z.yellow("(in-flight, no resolution)")}`)}}console.log()});xo.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=mt(e),t=Pn(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 d=i.map(u=>({event:u,decisions:l.filter(f=>f.event_id===u.id)}));console.log(JSON.stringify({project:n,subject:s,lineage:d},null,2));return}let g=new Set;for(let d of l)d.outcome==="dispatched"&&d.agent_id&&g.add(d.agent_id);console.log(),console.log(z.bold(` Lineage for ${z.cyan(n+":"+s)}`)),console.log(z.dim(` ${i.length} event(s), ${l.length} decision(s), ${g.size} distinct agent(s) dispatched`)),console.log();for(let d of i){let u=new Date(d.ts).toISOString().slice(0,19).replace("T"," ");console.log(` ${z.dim(u)} ${z.bold(d.id)} ${z.dim(`(${d.source}/${d.intent})`)}`);let f=l.filter(p=>p.event_id===d.id);if(f.length===0){console.log(z.dim(" (no decisions yet)"));continue}for(let p of f){let w=p.outcome==="dispatched"?z.green(p.outcome):p.outcome==="dropped"?z.dim(p.outcome):z.yellow(p.outcome),y=p.agent_id?z.cyan(p.agent_id):z.dim("-"),k=p.reason?z.dim(` \u2014 ${p.reason.slice(0,60)}`):"";if(console.log(` ${z.dim(p.decided_by)} \u2192 ${w} ${y}${k}`),p.resolution_status){let b=p.resolution_status==="ok"?z.green(p.resolution_status):z.red(p.resolution_status),S=p.duration_ms?`${(p.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${z.dim("resolved")} ${b} ${z.dim(S)}`)}else p.outcome==="dispatched"&&console.log(` ${z.yellow("(in-flight, no resolution)")}`)}}console.log()});xo.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=mt(e),t=Mn(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 "):""}
@@ -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(l).map(p=>({decisionEventId:p.decision_event_id,decisionDecidedBy:p.decision_decided_by,resolvedAt:p.resolved_at,status:p.status,durationMs:p.duration_ms,resultSummary:p.result_summary})),u=Hd(Ua(zd(),"agentx-ledger-replay-")),f=new or({path:Ua(u,"target.sqlite")});try{let p=La(f,r,g,d);if(e.json){console.log(JSON.stringify(p,null,2));return}console.log(z.bold(`Replayed ${p.eventsCount} events, ${p.decisionsCount} decisions, ${d.length} resolutions`)),p.divergences.length===0?console.log(z.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(z.red(` \u2717 ${p.divergences.length} divergences`)),Uo(p.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()}});Fi();ed();od();td();Zl();zi();jt();import{Command as Xd}from"commander";import U from"chalk";import{existsSync as qa}from"fs";import{resolve as Ws}from"path";import Qd from"better-sqlite3";var Le=new Xd().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),ze=".agentx/decisions/decisions.sqlite";function Zd(e){return Ws(Ws(e.cwd??process.cwd()),e.path??ze)}function so(e,o=!1){let t=Zd(e);qa(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 gn({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 no(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 Bs(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 Js(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:Bs(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}Le.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=so(e),t=Bs(e.since)??0,n=o.db.prepare(`SELECT seat, mode, backend, model, structure_mode AS structureMode,
151
+ `).all(l).map(p=>({decisionEventId:p.decision_event_id,decisionDecidedBy:p.decision_decided_by,resolvedAt:p.resolved_at,status:p.status,durationMs:p.duration_ms,resultSummary:p.result_summary})),u=Vd(Ba(Kd(),"agentx-ledger-replay-")),f=new sr({path:Ba(u,"target.sqlite")});try{let p=qa(f,r,g,d);if(e.json){console.log(JSON.stringify(p,null,2));return}console.log(z.bold(`Replayed ${p.eventsCount} events, ${p.decisionsCount} decisions, ${d.length} resolutions`)),p.divergences.length===0?console.log(z.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(z.red(` \u2717 ${p.divergences.length} divergences`)),qo(p.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()}});Wi();nd();sd();id();td();Ki();It();import{Command as eg}from"commander";import U from"chalk";import{existsSync as Ja}from"fs";import{resolve as Js}from"path";import og from"better-sqlite3";var Le=new eg().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),ze=".agentx/decisions/decisions.sqlite";function tg(e){return Js(Js(e.cwd??process.cwd()),e.path??ze)}function so(e,o=!1){let t=tg(e);Ja(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 mn({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 no(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 Gs(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 Hs(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:Gs(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}Le.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=so(e),t=Gs(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,
@@ -163,11 +163,11 @@ The AgentX daemon and a speech transcription backend must also be available. Run
163
163
  ORDER BY calls DESC`).all(t);!e.json&&s.length>0&&(console.log(U.bold(`
164
164
  policy`)),no(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()});Le.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=so(e),t=["ts >= ?"],n=[Bs(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()});Le.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=so(e),t=["ts >= ?"],n=[Gs(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));no(s,e.json),o.close()});Le.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=so(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}no(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()});Le.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=so(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()});Le.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=so(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));no(t.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),o.close()});Le.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=so(e,!0),t=Ws(process.cwd(),e.db);qa(t)||(console.log(U.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new Qd(t,{readonly:!0});try{let s=xr(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()}});Le.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=so(e),t=o.gradedRows(Js(e)),n=Bi(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(`
169
+ ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));no(s,e.json),o.close()});Le.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=so(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}no(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()});Le.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=so(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()});Le.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=so(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));no(t.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),o.close()});Le.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=so(e,!0),t=Js(process.cwd(),e.db);Ja(t)||(console.log(U.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new og(t,{readonly:!0});try{let s=Ar(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()}});Le.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=so(e),t=o.gradedRows(Hs(e)),n=Hi(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
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
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
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(`
@@ -175,21 +175,21 @@ The AgentX daemon and a speech transcription backend must also be available. Run
175
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
177
  what skipping would cost. Raise decisions.seats.<seat>.explore.`))),console.log(U.bold(`
178
- reliability (equal-width bins)`)),no(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()});Le.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=so(e),t=o.gradedRows(Js(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=Ji(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(`
178
+ reliability (equal-width bins)`)),no(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()});Le.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=so(e),t=o.gradedRows(Hs(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=zi(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
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
180
  `)),no(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
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
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()});Le.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=so(e),t=o.gradedRows({...Js(e),labeledOnly:!0}),n=Wi(t,Number(e.steps));if(n.length===0){console.log(U.yellow(` No labeled rows for seat "${e.seat}".`)),o.close();return}no(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()});Le.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=>{Xo();let o=so(e),t=o.db.prepare(`SELECT id, backend, model, state_json, questions_json FROM decision_calls
183
+ Neither correction beats the raw confidence out of sample. Leave it alone.`)),o.close()});Le.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=so(e),t=o.gradedRows({...Hs(e),labeledOnly:!0}),n=Gi(t,Number(e.steps));if(n.length===0){console.log(U.yellow(` No labeled rows for seat "${e.seat}".`)),o.close();return}no(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()});Le.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=>{Xo();let o=so(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(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 Gi(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(`
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 Yi(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
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
188
  `)),no(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
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
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
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()});Le.command("backends").description("registered decision backends and what they claim").action(()=>{Xo();let e=Li().map(o=>{let t=fs(o).capabilities;return{backend:o,source:t.probabilitySource,calibrated:t.calibratedProbabilities?"yes":"no",maxOptions:t.maxChoiceOptions,maxStateChars:t.maxStateChars}});no(e,!1),console.log(U.dim(`
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()});Le.command("backends").description("registered decision backends and what they claim").action(()=>{Xo();let e=qi().map(o=>{let t=ys(o).capabilities;return{backend:o,source:t.probabilitySource,calibrated:t.calibratedProbabilities?"yes":"no",maxOptions:t.maxChoiceOptions,maxStateChars:t.maxStateChars}});no(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\`.`))});Le.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=>{Xo();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=Ko(s,"Which option fits this state?")}e.noul&&(o.verdict=ro(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 fs(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as eg}from"commander";import I from"chalk";import{resolve as Wa}from"path";import{existsSync as og}from"fs";import tg from"better-sqlite3";var Jt=new eg().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function Hs(e){let o=Wa(e.cwd??process.cwd()),t=Wa(o,e.path??".agentx/db.sqlite");og(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 tg(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 ng(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 sg(e){if(!e)return;let o=ng(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 ig(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 Gs(e){return e==="ok"?I.green:e==="error"||e==="timeout"?I.red:e==="in-flight"?I.yellow:I.dim}Jt.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=Hs(e),t=lr(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:sg(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=Gs(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(ig(n.startedAt))}`),n.error&&console.log(` ${I.red("error:")} ${n.error}`)}});Jt.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=Hs(o),n=bs(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}rg(n.task,n.steps)});function rg(e,o){let t=Gs(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?Gs(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(`
200
+ labeled rows \u2014 see \`agentx decisions recalibrate\`.`))});Le.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=>{Xo();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=Ko(s,"Which option fits this state?")}e.noul&&(o.verdict=ro(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 ys(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as ng}from"commander";import j from"chalk";import{resolve as Ga}from"path";import{existsSync as sg}from"fs";import ig from"better-sqlite3";var Gt=new ng().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function Ys(e){let o=Ga(e.cwd??process.cwd()),t=Ga(o,e.path??".agentx/db.sqlite");sg(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 ig(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 rg(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 ag(e){if(!e)return;let o=rg(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 cg(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 zs(e){return e==="ok"?j.green:e==="error"||e==="timeout"?j.red:e==="in-flight"?j.yellow:j.dim}Gt.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=Ys(e),t=mr(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:ag(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=zs(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(cg(n.startedAt))}`),n.error&&console.log(` ${j.red("error:")} ${n.error}`)}});Gt.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=Ys(o),n=ks(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}lg(n.task,n.steps)});function lg(e,o){let t=zs(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?zs(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(`
202
202
  `)),n.inputSummary.split(`
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(`
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(`
205
205
  `)),n.outputSummary.split(`
206
- `).length>8&&console.log(` ${I.dim("\u2026")}`)}n.error&&console.log(` ${I.red("error:")} ${n.error}`)}}Jt.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=Hs(o),n=bs(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)}`}},l=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 d=await g.json().catch(()=>({})),u=Date.now()-l;if(g.ok||(console.log(I.red(` replay failed (${g.status}): ${d.error||"unknown error"}`)),process.exit(1)),o.diff){console.log(I.bold(" INPUT (replayed verbatim)")),console.log(),Mn(i),console.log(),console.log(I.bold(` ORIGINAL OUTPUT ${I.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?Mn(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=${d.error?"error":"ok"} ${u}ms tokens=in:${d.usage?.inputTokens??0}/out:${d.usage?.outputTokens??0}`)}`)),console.log(),Mn(d.content??"(empty reply)"),d.error&&console.log(I.red(` error: ${d.error}`)),console.log();let f=(s.finalResponse??"").trim()===(d.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 ${u}ms`)),console.log(),Mn(d.content??"(empty reply)"),d.error&&console.log(I.red(`
207
- error: ${d.error}`)),console.log(),console.log(I.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function Mn(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 dg}from"commander";import le from"chalk";import{existsSync as gg,mkdirSync as mg,writeFileSync as pg}from"fs";import{resolve as Ga,join as Ja,dirname as ug}from"path";var ag=`# AgentX destructive-action guardrails \u2014 global policy
206
+ `).length>8&&console.log(` ${j.dim("\u2026")}`)}n.error&&console.log(` ${j.red("error:")} ${n.error}`)}}Gt.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=Ys(o),n=ks(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)}`}},l=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 d=await g.json().catch(()=>({})),u=Date.now()-l;if(g.ok||(console.log(j.red(` replay failed (${g.status}): ${d.error||"unknown error"}`)),process.exit(1)),o.diff){console.log(j.bold(" INPUT (replayed verbatim)")),console.log(),Ln(i),console.log(),console.log(j.bold(` ORIGINAL OUTPUT ${j.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?Ln(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=${d.error?"error":"ok"} ${u}ms tokens=in:${d.usage?.inputTokens??0}/out:${d.usage?.outputTokens??0}`)}`)),console.log(),Ln(d.content??"(empty reply)"),d.error&&console.log(j.red(` error: ${d.error}`)),console.log();let f=(s.finalResponse??"").trim()===(d.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 ${u}ms`)),console.log(),Ln(d.content??"(empty reply)"),d.error&&console.log(j.red(`
207
+ error: ${d.error}`)),console.log(),console.log(j.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function Ln(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 pg}from"commander";import de from"chalk";import{existsSync as ug,mkdirSync as fg,writeFileSync as hg}from"fs";import{resolve as Ya,join as za,dirname as yg}from"path";var dg=`# 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
- `,cg=`# Production protected resources.
234
+ `,gg=`# 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
- `,lg=`# Per-agent override for coder-agent. Top-level rules here are auto-scoped to
256
+ `,mg=`# 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:ag},{relPath:"environments/production.yaml",content:cg},{relPath:"agents/coder-agent.yaml",content:lg}];var So=new dg().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function zs(e){return e==="deny"?le.red:e==="escalate"||e==="ask"?le.yellow:e==="warn"?le.magenta:le.green}function Ln(e){return e.root?Ga(e.root):Hr()}So.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 Gr({root:Ln(e),agentId:e.agent,env:e.env}),process.exit(0)});So.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=Ln(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=Jr({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}fg(s,i,r)});function fg(e,o,t){let n=zs(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":le.dim(" (no rule matched)")}`),console.log(` enforced as ${zs(e.effectiveAction)(e.effectiveAction)} ${le.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${le.cyan(e.ruleId)}${e.severity?le.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${le.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${le.dim(`evaluated in ${t}ms`)}`),console.log()}So.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=Zi({root:Ln(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(le.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=zs(t.verdict),i=t.effective_action!==t.verdict?le.dim(`->${t.effective_action}`):"";console.log(` ${le.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${le.cyan((t.agent_id??"?").padEnd(16))} ${le.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(le.dim(` target: ${t.resolved_target}`))}});So.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(Ga(e.root),Wr),t=0;for(let n of Ba){let s=Ja(o,n.relPath);if(gg(s)&&!e.force){console.log(le.dim(` skip (exists) ${n.relPath}`));continue}mg(ug(s),{recursive:!0}),pg(s,n.content),console.log(le.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${le.cyan(o)}`),console.log(le.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(le.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});So.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(le.green(` daemon reloaded (${e.url})`)):console.log(le.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(le.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});So.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=Br(Ln(e),e.agent);console.log(JSON.stringify(o,null,2))});Ct();import{Command as hg}from"commander";import{execFile as yg}from"child_process";import{promisify as wg}from"util";import{existsSync as bg}from"fs";import Ye from"chalk";jt();var Ht="ui-element";function Fn(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:Gt(t.tried,80),screenChanged:t.changed,note:t.note?Gt(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:Ha(t.role),label:Gt(t.label,120),value:t.value?Gt(t.value,80):null,enabled:t.enabled}))}}function Un(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${Ha(t.role)}: ${Gt(n,80)}`}return{target:Ko(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:ro("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 qn(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 Ha(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Gt(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}var za=wg(yg),Ya=new hg().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)=>{bg($e)||(console.log(Ye.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await vn({max:Number(o.max)||40})}catch(d){console.log(Ye.red(` could not read the screen: ${d?.message??d}`)),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 d=Pt(t,n[0].id);d&&(console.log(Ye.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+Ye.bold(n[0].label)),await za($e,["point","--x",String(d.x),"--y",String(d.y),"--w",String(d.width),"--h",String(d.height),"--label",n[0].label]));return}let s=await Ze(Ht,Fn({request:e,app:t.app,window:t.window,candidates:n}),Un(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.${Ht}.mode`)),process.exit(1));let i=qn(s.answers,n),r=Pt(t,i.id),a=n.find(d=>d.id===i.id)?.label??"",c=t.ocrRects.has(i.id),l=Number(o.minPresent)||.5;if((i.present<l||!r)&&(console.log(Ye.yellow(` nothing on screen matches "${e}"`)+Ye.dim(` (P(exists)=${i.present.toFixed(2)} below ${l})`)),process.exit(2)),o.json){console.log(JSON.stringify({app:t.app,request:e,chosen:{...r,label:a,fromOCR:c},present:i.present,confidence:i.confidence,ranked:i.ranked.slice(0,5).map(d=>({...d,label:n.find(u=>u.id===d.id)?.label}))},null,2));return}let g=a;console.log(` ${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 za($e,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",g])});import{Command as Gg}from"commander";import Fe from"chalk";import{execFile as $g}from"child_process";import{promisify as kg}from"util";import{existsSync as vg,readFileSync as Ys}from"fs";import{homedir as xg,tmpdir as Sg}from"os";import{join as Va}from"path";var Eg=kg($g),Ka=12e5,Ag="https://openrouter.ai/api/v1/chat/completions",Og=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function Tg(e={kind:"window"},o=Ka){if(!vg($e))throw new Error("helper not built \u2014 run apps/mac-helper/build.sh");let n=["capture","--out",Va(Sg(),`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 Eg($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=Ys(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 Ig=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
265
+ `,Ha=[{relPath:"policy.yaml",content:dg},{relPath:"environments/production.yaml",content:gg},{relPath:"agents/coder-agent.yaml",content:mg}];var So=new pg().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function Vs(e){return e==="deny"?de.red:e==="escalate"||e==="ask"?de.yellow:e==="warn"?de.magenta:de.green}function Fn(e){return e.root?Ya(e.root):Vr()}So.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:Fn(e),agentId:e.agent,env:e.env}),process.exit(0)});So.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=Fn(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=zr({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}wg(s,i,r)});function wg(e,o,t){let n=Vs(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":de.dim(" (no rule matched)")}`),console.log(` enforced as ${Vs(e.effectiveAction)(e.effectiveAction)} ${de.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${de.cyan(e.ruleId)}${e.severity?de.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${de.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${de.dim(`evaluated in ${t}ms`)}`),console.log()}So.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=tr({root:Fn(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(de.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=Vs(t.verdict),i=t.effective_action!==t.verdict?de.dim(`->${t.effective_action}`):"";console.log(` ${de.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${de.cyan((t.agent_id??"?").padEnd(16))} ${de.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(de.dim(` target: ${t.resolved_target}`))}});So.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=za(Ya(e.root),Gr),t=0;for(let n of Ha){let s=za(o,n.relPath);if(ug(s)&&!e.force){console.log(de.dim(` skip (exists) ${n.relPath}`));continue}fg(yg(s),{recursive:!0}),hg(s,n.content),console.log(de.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${de.cyan(o)}`),console.log(de.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(de.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});So.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(de.green(` daemon reloaded (${e.url})`)):console.log(de.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(de.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});So.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=Hr(Fn(e),e.agent);console.log(JSON.stringify(o,null,2))});Ct();import{Command as bg}from"commander";import{execFile as $g}from"child_process";import{promisify as kg}from"util";import{existsSync as vg}from"fs";import Ye from"chalk";It();var zt="ui-element";function Un(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:Ht(t.tried,80),screenChanged:t.changed,note:t.note?Ht(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:Va(t.role),label:Ht(t.label,120),value:t.value?Ht(t.value,80):null,enabled:t.enabled}))}}function qn(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${Va(t.role)}: ${Ht(n,80)}`}return{target:Ko(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:ro("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 Wn(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 Ht(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}var Ka=kg($g),Xa=new bg().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)=>{vg(ke)||(console.log(Ye.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await xn({max:Number(o.max)||40})}catch(d){console.log(Ye.red(` could not read the screen: ${d?.message??d}`)),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 d=Mt(t,n[0].id);d&&(console.log(Ye.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+Ye.bold(n[0].label)),await Ka(ke,["point","--x",String(d.x),"--y",String(d.y),"--w",String(d.width),"--h",String(d.height),"--label",n[0].label]));return}let s=await Ze(zt,Un({request:e,app:t.app,window:t.window,candidates:n}),qn(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.${zt}.mode`)),process.exit(1));let i=Wn(s.answers,n),r=Mt(t,i.id),a=n.find(d=>d.id===i.id)?.label??"",c=t.ocrRects.has(i.id),l=Number(o.minPresent)||.5;if((i.present<l||!r)&&(console.log(Ye.yellow(` nothing on screen matches "${e}"`)+Ye.dim(` (P(exists)=${i.present.toFixed(2)} below ${l})`)),process.exit(2)),o.json){console.log(JSON.stringify({app:t.app,request:e,chosen:{...r,label:a,fromOCR:c},present:i.present,confidence:i.confidence,ranked:i.ranked.slice(0,5).map(d=>({...d,label:n.find(u=>u.id===d.id)?.label}))},null,2));return}let g=a;console.log(` ${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 Ka(ke,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",g])});import{Command as Yg}from"commander";import Fe from"chalk";import{execFile as xg}from"child_process";import{promisify as Sg}from"util";import{existsSync as Eg,readFileSync as Ks}from"fs";import{homedir as Ag,tmpdir as Og}from"os";import{join as Qa}from"path";var Tg=Sg(xg),Za=12e5,jg="https://openrouter.ai/api/v1/chat/completions",Ig=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function Cg(e={kind:"window"},o=Za){if(!Eg(ke))throw new Error("helper not built \u2014 run apps/mac-helper/build.sh");let n=["capture","--out",Qa(Og(),`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 Tg(ke,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=Ks(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 Ng=`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 jg(e,o,t,n){let s=Ng();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=Ys(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 Rg(e,o,t,n){let s=_g();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=Ks(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 ${Cg(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:Ig,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),l;try{l=await fetch(Ag,{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(!l.ok){let p=await l.text().catch(()=>"");throw new Error(`vision model ${l.status}: ${p.slice(0,300)}`)}let g=await l.json(),d=g?.choices?.[0]?.message?.tool_calls?.[0];if(!d?.function?.arguments)throw new Error("vision model returned no structured report");let u=JSON.parse(d.function.arguments),f=u.reading==="yes"||u.reading==="no"?u.reading:"unclear";return{observation:(u.observation??"").trim(),evidence:(u.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 Wn(e,o={}){let t=Date.now(),n=await Tg(o.region??{kind:"window"},o.maxPixels??Ka),s=await jg(e,n,o.model??Og,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 Cg(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 zt;function Ng(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(zt!==void 0)return zt??void 0;try{let e=Ys(Va(xg(),".agentx","openrouter-key.txt"),"utf-8").trim();zt=e.length>0?e:null}catch{zt=null}return zt??void 0}import{execFile as Rg}from"child_process";import{promisify as Dg}from"util";var _g=Dg(Rg),Pg=["screencapture"],Mg=["Screen Studio","OBS","QuickTime Player","Zoom"];async function Qa(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await Lg()),t}async function Lg(){let e=await Xa(Pg);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 Xa(Mg);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 Xa(e){let o=[];for(let t of e)try{let{stdout:n}=await _g("pgrep",["-x",t]),s=n.trim().split(`
276
- `)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}Ct();jt();var Za="screen-state",ec={observable:ro("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:ro("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 oc(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 tc(e){return{observable:e.observable.noul,holds:e.holds.noul}}var Fg=.6,Ug=.7,qg=.3;async function Yt(e,o={}){let[t,n]=await Promise.all([Wn(e,o),Qa(e).catch(()=>[])]),s=o.observableFloor??Fg,i=await Ze(Za,oc({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:Jg(t),treeNote:o.treeNote,probes:n}),ec,{incumbent:{holds:t.reading==="yes"?1:0},features:{model:t.model,region:t.shot.region.height<=40?"menubar":"window"}});if(!i){let l=t.reading==="yes"?"confirmed":t.reading==="no"?"refuted":"unknown";return{claim:e,outcome:l,ok:l==="confirmed",observable:null,holds:null,calibrated:!1,reason:Bg(l,t),sighting:t,probes:n}}let{observable:r,holds:a}=tc(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 (${Bn(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=Ug?"confirmed":a<=qg?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:Wg(c,a,t),sighting:t,probes:n}}function Wg(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${Bn(o)}). ${n}`:e==="refuted"?`Not true (${Bn(1-o)} it is false). ${n}`:`Inconclusive (${Bn(o)}, between the thresholds). ${n}`}function Bg(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 Jg(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 Bn=e=>`${Math.round(e*100)}%`;var nc=new Gg().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(Fe.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 Yt(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"?Fe.green("\u2713"):s.outcome==="refuted"?Fe.red("\u2717"):Fe.yellow("?");console.log(` ${i} ${Fe.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(Fe.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(Fe.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 Wn(e,{region:t,model:o.model});if(o.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${Fe.bold(n.observation)}`),n.evidence&&console.log(Fe.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${Hg(n.reading)}`),console.log(Fe.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(Fe.red(` ${n?.message??n}`)),process.exit(1)}});function Hg(e){return e==="yes"?Fe.green(e):e==="no"?Fe.red(e):Fe.yellow(e)}Ct();import{Command as Vg}from"commander";import{execFile as gc}from"child_process";import{promisify as Kg}from"util";import{existsSync as Xg,readFileSync as Qg,writeFileSync as mc,mkdirSync as Zg}from"fs";import{homedir as em}from"os";import{join as om,dirname as tm}from"path";import Ce from"chalk";jt();var Vs="paste-transform";function sc(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function ic(e){let o={};for(let t of e)o[t.id]=t.criterion;return{worthChanging:ro("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:Ko(o,"What shape should this paste arrive in?")}}function rc(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 zg=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"]),Yg=e=>/^https?:\/\/\S+$/i.test(e.trim()),Ks=[{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 ${Dg(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:Ng,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),l;try{l=await fetch(jg,{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(!l.ok){let p=await l.text().catch(()=>"");throw new Error(`vision model ${l.status}: ${p.slice(0,300)}`)}let g=await l.json(),d=g?.choices?.[0]?.message?.tool_calls?.[0];if(!d?.function?.arguments)throw new Error("vision model returned no structured report");let u=JSON.parse(d.function.arguments),f=u.reading==="yes"||u.reading==="no"?u.reading:"unclear";return{observation:(u.observation??"").trim(),evidence:(u.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 Bn(e,o={}){let t=Date.now(),n=await Cg(o.region??{kind:"window"},o.maxPixels??Za),s=await Rg(e,n,o.model??Ig,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 Dg(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 Yt;function _g(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(Yt!==void 0)return Yt??void 0;try{let e=Ks(Qa(Ag(),".agentx","openrouter-key.txt"),"utf-8").trim();Yt=e.length>0?e:null}catch{Yt=null}return Yt??void 0}import{execFile as Pg}from"child_process";import{promisify as Mg}from"util";var Lg=Mg(Pg),Fg=["screencapture"],Ug=["Screen Studio","OBS","QuickTime Player","Zoom"];async function oc(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await qg()),t}async function qg(){let e=await ec(Fg);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 ec(Ug);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 ec(e){let o=[];for(let t of e)try{let{stdout:n}=await Lg("pgrep",["-x",t]),s=n.trim().split(`
276
+ `)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}Ct();It();var tc="screen-state",nc={observable:ro("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:ro("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 sc(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 ic(e){return{observable:e.observable.noul,holds:e.holds.noul}}var Wg=.6,Bg=.7,Jg=.3;async function Vt(e,o={}){let[t,n]=await Promise.all([Bn(e,o),oc(e).catch(()=>[])]),s=o.observableFloor??Wg,i=await Ze(tc,sc({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:zg(t),treeNote:o.treeNote,probes:n}),nc,{incumbent:{holds:t.reading==="yes"?1:0},features:{model:t.model,region:t.shot.region.height<=40?"menubar":"window"}});if(!i){let l=t.reading==="yes"?"confirmed":t.reading==="no"?"refuted":"unknown";return{claim:e,outcome:l,ok:l==="confirmed",observable:null,holds:null,calibrated:!1,reason:Hg(l,t),sighting:t,probes:n}}let{observable:r,holds:a}=ic(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 (${Jn(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=Bg?"confirmed":a<=Jg?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:Gg(c,a,t),sighting:t,probes:n}}function Gg(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${Jn(o)}). ${n}`:e==="refuted"?`Not true (${Jn(1-o)} it is false). ${n}`:`Inconclusive (${Jn(o)}, between the thresholds). ${n}`}function Hg(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 zg(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 Jn=e=>`${Math.round(e*100)}%`;var rc=new Yg().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(Fe.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 Vt(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"?Fe.green("\u2713"):s.outcome==="refuted"?Fe.red("\u2717"):Fe.yellow("?");console.log(` ${i} ${Fe.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(Fe.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(Fe.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 Bn(e,{region:t,model:o.model});if(o.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${Fe.bold(n.observation)}`),n.evidence&&console.log(Fe.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${Vg(n.reading)}`),console.log(Fe.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(Fe.red(` ${n?.message??n}`)),process.exit(1)}});function Vg(e){return e==="yes"?Fe.green(e):e==="no"?Fe.red(e):Fe.yellow(e)}Ct();import{Command as Qg}from"commander";import{execFile as uc}from"child_process";import{promisify as Zg}from"util";import{existsSync as em,readFileSync as om,writeFileSync as fc,mkdirSync as tm}from"fs";import{homedir as nm}from"os";import{join as sm,dirname as im}from"path";import Ne from"chalk";It();var Xs="paste-transform";function ac(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function cc(e){let o={};for(let t of e)o[t.id]=t.criterion;return{worthChanging:ro("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:Ko(o,"What shape should this paste arrive in?")}}function lc(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 Kg=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"]),Xg=e=>/^https?:\/\/\S+$/i.test(e.trim()),Qs=[{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,26 +281,26 @@ The image is the region ${Cg(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(!Yg(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])zg.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(!Xg(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])Kg.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 ac(e){let o=[];for(let t of Ks){let n=t.apply(e);n!==null&&(t.id!=="asIs"&&n===e||o.push({transform:t,result:n}))}return o}function cc(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 dc(e){let o=[];for(let t of Qs){let n=t.apply(e);n!==null&&(t.id!=="asIs"&&n===e||o.push({transform:t,result:n}))}return o}function gc(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 lc(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 Xs=Kg(gc),pc=new Vg().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 (${Ks.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=sm();c===null&&(console.log(Ce.yellow(" nothing to undo")),process.exit(2)),await fc(c),console.log(` ${Ce.green("\u2192")} clipboard restored`);return}let o=await im();if(o||(console.log(Ce.yellow(" clipboard is empty")),process.exit(2)),lc(o)){uc(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=ac(o),n=await rm();if(e.as){let c=t.find(l=>l.transform.id===e.as);c||(console.log(Ce.red(` "${e.as}" does not apply to this clipboard`)),console.log(Ce.dim(` available: ${t.map(l=>l.transform.id).join(", ")}`)),process.exit(1)),await pt(e,c.transform.id,c.result,o,"forced",1);return}if(t.length<2){await pt(e,"asIs",o,o,"nothing else applies",0);return}let s=await Ze(Vs,sc({preview:cc(o),length:o.length,lineCount:o.split(`
290
- `).length,app:n.app,destination:n.role,destinationLabel:n.label}),ic(t.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:t.length,chars:o.length}});if(!s){await pt(e,"asIs",o,o,`seat unavailable \u2014 set decisions.seats.${Vs}.mode`,0);return}let i=rc(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await pt(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 pt(e,"asIs",o,o,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await pt(e,a.transform.id,a.result,o,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function pt(e,o,t,n,s,i){let r=t!==n;r&&(e.apply||e.paste)&&(nm(n),await fc(t)),uc(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await Xs($e,["key","--name","v","--mod","command"]).catch(a=>{console.log(Ce.red(` could not paste: ${a?.message??a}`))})}function uc(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(dc(o.original))),console.log(Ce.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(dc(o.result)),!e.apply&&!e.paste&&console.log(Ce.dim(`
291
- (dry run \u2014 pass --apply to write it back)`))}var dc=(e,o=400)=>(e.length>o?`${e.slice(0,o)}\u2026`:e).split(`
288
+ ${e.slice(-n)}`}function mc(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 Zs=Zg(uc),hc=new Qg().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 (${Qs.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=am();c===null&&(console.log(Ne.yellow(" nothing to undo")),process.exit(2)),await wc(c),console.log(` ${Ne.green("\u2192")} clipboard restored`);return}let o=await cm();if(o||(console.log(Ne.yellow(" clipboard is empty")),process.exit(2)),mc(o)){yc(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=dc(o),n=await lm();if(e.as){let c=t.find(l=>l.transform.id===e.as);c||(console.log(Ne.red(` "${e.as}" does not apply to this clipboard`)),console.log(Ne.dim(` available: ${t.map(l=>l.transform.id).join(", ")}`)),process.exit(1)),await pt(e,c.transform.id,c.result,o,"forced",1);return}if(t.length<2){await pt(e,"asIs",o,o,"nothing else applies",0);return}let s=await Ze(Xs,ac({preview:gc(o),length:o.length,lineCount:o.split(`
290
+ `).length,app:n.app,destination:n.role,destinationLabel:n.label}),cc(t.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:t.length,chars:o.length}});if(!s){await pt(e,"asIs",o,o,`seat unavailable \u2014 set decisions.seats.${Xs}.mode`,0);return}let i=lc(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await pt(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 pt(e,"asIs",o,o,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await pt(e,a.transform.id,a.result,o,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function pt(e,o,t,n,s,i){let r=t!==n;r&&(e.apply||e.paste)&&(rm(n),await wc(t)),yc(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await Zs(ke,["key","--name","v","--mod","command"]).catch(a=>{console.log(Ne.red(` could not paste: ${a?.message??a}`))})}function yc(e,o){if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.changed){console.log(` ${Ne.dim("\u2192")} ${Ne.bold("unchanged")} ${Ne.dim(`\xB7 ${o.reason}`)}`);return}console.log(` ${Ne.green("\u2192")} ${Ne.bold(o.applied)} ${Ne.dim(`\xB7 ${o.reason}`)}`),console.log(Ne.dim(" \u2500\u2500\u2500 before \u2500\u2500\u2500")),console.log(Ne.dim(pc(o.original))),console.log(Ne.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(pc(o.result)),!e.apply&&!e.paste&&console.log(Ne.dim(`
291
+ (dry run \u2014 pass --apply to write it back)`))}var pc=(e,o=400)=>(e.length>o?`${e.slice(0,o)}\u2026`:e).split(`
292
292
  `).map(t=>` ${t}`).join(`
293
- `),Jn=om(em(),".agentx","paste-undo.txt");function nm(e){try{Zg(tm(Jn),{recursive:!0}),mc(Jn,e,{mode:384})}catch{}}function sm(){try{let e=Qg(Jn,"utf-8");return mc(Jn,"",{mode:384}),e.length?e:null}catch{return null}}async function im(){let{stdout:e}=await Xs("pbpaste",[],{maxBuffer:16777216});return e}async function fc(e){await new Promise((o,t)=>{gc("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function rm(){if(!Xg($e))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await Xs($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:am(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function am(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 cm}from"commander";import Ve from"chalk";ge();var lm=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function dm(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(`${lm}/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)}`)}}function gm(e){let o;try{o=_(e.config).notifications.local}catch{o=void 0}let t=bn(o);return e.sound||(t.sound=!1),e.banner||(t.banner=!1),Mr(t)}var hc=new cm().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","AgentX").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("--no-banner","do not show a banner on this machine").option("-c, --config <path>","agentx.json to read local settings from (default: ./agentx.json)").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=Ir(),s=gm(o);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")} ${jr(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=dm(o.channel,o.chatId);if(o.flush){let r=await Ur(i,{queue:t,alert: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 Fr({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,alert: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}`)),await s(o.title,e.trim()),process.exit(1)}});Ct();zi();Fi();jt();import{Command as mm}from"commander";import{readFileSync as pm}from"fs";var yc=new mm().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?pm(e.file,"utf8"):await um()}catch(r){qo(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return qo("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return qo(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return qo("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return qo("spec needs at least one entry in `questions`");try{qi(t.questions)}catch(r){return qo(r?.message??String(r))}let n=t.seat||e.seat;Xo(),process.env[Vi(n)]="active";let s=null;if(e.record!==!1)try{s=new gn({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
295
- `)}Yi({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await Ze(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return qo(`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 qo(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function um(){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")}Ct();import{Command as Gm}from"commander";import{execFile as Hm,spawn as Nc}from"child_process";import{promisify as zm}from"util";import{existsSync as Ym,statSync as Vm}from"fs";import{join as Rc}from"path";import{tmpdir as Km}from"os";import X from"chalk";var fm={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."}]},hm={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."}]},ym={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."}]},Qs=[fm,hm,ym];ge();ge();import Ke from"chalk";import{execFile as wm}from"child_process";import{promisify as bm}from"util";import{createInterface as $m}from"readline";var wc=bm(wm);function km(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 vm(e,o){let t=Date.now()+o;for(let n=0;Date.now()<t;n++){n&&n%10===0&&await wc("open",["-a",e]).catch(()=>{});try{let s=(await As()).app;if(s.toLowerCase()===e.replace(/\.app$/i,"").toLowerCase())return s}catch{}await new Promise(s=>setTimeout(s,500))}return null}async function bc(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 wc("open",["-a",o.app]),i=await vm(o.app,15e3)??void 0,!i))throw new Error(`${o.app} did not come to the front`);let r=kn(n,t.agents,!1),a=t.voice.listener??Zr,c=xn(n,t.agents[n]),l=new ta({goal:e,app:i,mode:s,speaker:r,actionsAllowed:c.allowActions,maxSteps:Number(o.steps)||void 0,listener:a},{readScreen:As,presence:new Sn(c,$e,n),speech:new st,model:it({system:oa(r.persona,a)}),act:na});l.on(km),console.log(Ke.bold(`
293
+ `),Gn=sm(nm(),".agentx","paste-undo.txt");function rm(e){try{tm(im(Gn),{recursive:!0}),fc(Gn,e,{mode:384})}catch{}}function am(){try{let e=om(Gn,"utf-8");return fc(Gn,"",{mode:384}),e.length?e:null}catch{return null}}async function cm(){let{stdout:e}=await Zs("pbpaste",[],{maxBuffer:16777216});return e}async function wc(e){await new Promise((o,t)=>{uc("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function lm(){if(!em(ke))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await Zs(ke,["focused"]),o=JSON.parse(e);return o.ok===!1||!o.role?{app:"unknown",role:"an unknown control",label:null}:{app:o.app??"unknown",role:dm(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function dm(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 gm}from"commander";import Ve from"chalk";me();var mm=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function pm(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(`${mm}/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)}`)}}function um(e){let o;try{o=_(e.config).notifications.local}catch{o=void 0}let t=$n(o);return e.sound||(t.sound=!1),e.banner||(t.banner=!1),Ur(t)}var bc=new gm().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","AgentX").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("--no-banner","do not show a banner on this machine").option("-c, --config <path>","agentx.json to read local settings from (default: ./agentx.json)").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 Dr,n=Nr(),s=um(o);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")} ${Rr(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=pm(o.channel,o.chatId);if(o.flush){let r=await Br(i,{queue:t,alert: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 Wr({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,alert: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}`)),await s(o.title,e.trim()),process.exit(1)}});Ct();Ki();Wi();It();import{Command as fm}from"commander";import{readFileSync as hm}from"fs";var $c=new fm().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?hm(e.file,"utf8"):await ym()}catch(r){Wo(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return Wo("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return Wo(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return Wo("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return Wo("spec needs at least one entry in `questions`");try{Ji(t.questions)}catch(r){return Wo(r?.message??String(r))}let n=t.seat||e.seat;Xo(),process.env[Qi(n)]="active";let s=null;if(e.record!==!1)try{s=new mn({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
295
+ `)}Xi({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await Ze(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return Wo(`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 Wo(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function ym(){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")}Ct();import{Command as Ym}from"commander";import{execFile as Vm,spawn as _c}from"child_process";import{promisify as Km}from"util";import{existsSync as Xm,statSync as Qm}from"fs";import{join as Pc}from"path";import{tmpdir as Zm}from"os";import X from"chalk";var wm={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."}]},bm={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."}]},$m={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."}]},ei=[wm,bm,$m];me();me();import Ke from"chalk";import{execFile as km}from"child_process";import{promisify as vm}from"util";import{createInterface as xm}from"readline";var kc=vm(km);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 Em(e,o){let t=Date.now()+o;for(let n=0;Date.now()<t;n++){n&&n%10===0&&await kc("open",["-a",e]).catch(()=>{});try{let s=(await Ts()).app;if(s.toLowerCase()===e.replace(/\.app$/i,"").toLowerCase())return s}catch{}await new Promise(s=>setTimeout(s,500))}return null}async function vc(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 kc("open",["-a",o.app]),i=await Em(o.app,15e3)??void 0,!i))throw new Error(`${o.app} did not come to the front`);let r=vn(n,t.agents,!1),a=t.voice.listener??ta,c=Sn(n,t.agents[n]),l=new ia({goal:e,app:i,mode:s,speaker:r,actionsAllowed:c.allowActions,maxSteps:Number(o.steps)||void 0,listener:a},{readScreen:Ts,presence:new En(c,ke,n),speech:new st,model:it({system:sa(r.persona,a)}),act:ra});l.on(Sm),console.log(Ke.bold(`
296
296
  ${c.name} teaches: ${e}`)+Ke.dim(` (${s}${s==="act"&&!c.allowActions?", actions not allowed":""}; type to cut in, "stop" to end)
297
- `));let g=$m({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close()}ge();import Xe from"chalk";import{execFile as Pm}from"child_process";import{existsSync as oi,writeFileSync as Mm}from"fs";import{homedir as Lm}from"os";import{join as jc,resolve as Fm}from"path";import{promisify as Um}from"util";var Me={w:1e3,h:640},Zs=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],vc=["rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","cloud","heart"],$c=["none","semi","solid","fill","pattern"],ei=180,xc=48,xm=["s","m","l","xl"],Sm=["draw","sans","serif","mono"];function Sc(){return[`You are an illustrator drawing on a tldraw canvas ${Me.w} wide and ${Me.h} tall (x right, y down, origin top-left).`,`Reply with JSON Lines only: one element per line, no prose, no code fences. Scale the number of elements to the brief: a quick sketch needs 10 to 20, a finished, ambitious piece up to ${ei}. Draw back to front: background first, then midground, foreground, details, text last, arrows at the very end.`,'Palette (optional, first line): {"palette":{"blue":"#1f5fa6","white":"#f7f3ea"},"say":"Choosing a palette."} remaps any of the colour names to a hex value for this drawing; every later element uses the names.','Shape: {"id":"sea","say":"First, the sea.","geo":"rectangle","x":0,"y":420,"w":1000,"h":220,"color":"blue","fill":"fill","label":"","opacity":1}',`Path: {"id":"dome","say":"","path":[[400,200],[410,170],[440,150],[470,170],[480,200],[400,200]],"color":"white","fill":"fill","opacity":1} is a free outline of 3 to ${xc} points, closed and filled, for any silhouette a box can't make: domes, arches, hills, foliage, stairs, shadows, reflections. Straight edges stay straight; give curves enough points. With fill none it is an open stroke: a railing, a grille bar, a crack, a horizon line.`,'Text: {"id":"title","say":"And a title.","text":"Sidi Bou Said","x":330,"y":40,"size":"xl","color":"black","font":"serif"}',`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, then an arrow from that text to the thing.",`geo is one of: ${vc.join(", ")}.`,`color is one of: ${Zs.join(", ")}. fill is fill (strong colour), solid (pale tint), semi, none or pattern. opacity is 0.1 to 1: use it for shadows, haze and atmospheric depth. size is s, m, l or xl. font is draw (hand-lettered), sans, serif or mono.`,"Keep everything inside the canvas. 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 five) and leave say empty on the rest: captioned steps pause so they can be read, the others draw straight through."].join(`
298
- `)}function ut(e,o,t){return typeof e=="string"&&o.includes(e)?e:t}function Wo(e){return typeof e=="number"&&Number.isFinite(e)?e:null}var Bo=(e,o,t)=>Math.min(t,Math.max(o,e)),kc=e=>Bo(Wo(e)??1,.1,1),Em=/^#[0-9a-f]{6}$/i;function Am(e){if(!e||typeof e!="object")return null;let o={};for(let[t,n]of Object.entries(e))Zs.includes(t)&&typeof n=="string"&&Em.test(n)&&(o[t]=n);return Object.keys(o).length?o:null}function Om(e){if(!Array.isArray(e))return null;let o=[];for(let t of e.slice(0,xc)){if(!Array.isArray(t))return null;let n=Wo(t[0]),s=Wo(t[1]);if(n===null||s===null)return null;o.push([Bo(n,0,Me.w),Bo(s,0,Me.h)])}return o.length>=2?o:null}function Ec(e,o){let t=e.trim().replace(/,$/,"");if(!t.startsWith("{"))return null;let n;try{n=JSON.parse(t)}catch{return null}if("palette"in n){let l=Am(n.palette);return!l||o.has("palette")?null:{kind:"palette",id:"palette",say:typeof n.say=="string"?n.say.slice(0,80):"",colors:l}}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=ut(n.color,Zs,"black");if(Array.isArray(n.arrow)){let[l,g]=n.arrow;return typeof l!="string"||typeof g!="string"||!o.has(l)||!o.has(g)||l===g?null:{kind:"arrow",id:s,say:i,from:l,to:g,label:typeof n.label=="string"?n.label.slice(0,40):"",color:r}}if("path"in n){let l=Om(n.path),g=ut(n.fill,$c,"fill");return!l||g!=="none"&&l.length<3?null:{kind:"path",id:s,say:i,pts:l,color:r,fill:g,opacity:kc(n.opacity)}}let a=Wo(n.x),c=Wo(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:Bo(a,0,Me.w-20),y:Bo(c,0,Me.h-20),size:ut(n.size,xm,"l"),color:r,font:ut(n.font,Sm,"draw")};if(typeof n.geo=="string"){let l=Wo(n.w),g=Wo(n.h);if(l===null||g===null||l<4||g<4)return null;let d=Bo(a,0,Me.w-4),u=Bo(c,0,Me.h-4);return{kind:"geo",id:s,say:i,geo:ut(n.geo,vc,"rectangle"),x:d,y:u,w:Math.min(l,Me.w-d),h:Math.min(g,Me.h-u),color:r,fill:ut(n.fill,$c,"solid"),label:typeof n.label=="string"?n.label.slice(0,40):"",opacity:kc(n.opacity)}}return null}var Gn=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 Tm=500,Im=e=>`
297
+ `));let g=xm({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close()}me();import Xe from"chalk";import{execFile as Fm}from"child_process";import{existsSync as ni,writeFileSync as Um}from"fs";import{homedir as qm}from"os";import{join as Rc,resolve as Wm}from"path";import{promisify as Bm}from"util";var Me={w:1e3,h:640},oi=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],Ec=["rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","cloud","heart"],xc=["none","semi","solid","fill","pattern"],ti=180,Ac=48,Am=["s","m","l","xl"],Om=["draw","sans","serif","mono"];function Oc(){return[`You are an illustrator drawing on a tldraw canvas ${Me.w} wide and ${Me.h} tall (x right, y down, origin top-left).`,`Reply with JSON Lines only: one element per line, no prose, no code fences. Scale the number of elements to the brief: a quick sketch needs 10 to 20, a finished, ambitious piece up to ${ti}. Draw back to front: background first, then midground, foreground, details, text last, arrows at the very end.`,'Palette (optional, first line): {"palette":{"blue":"#1f5fa6","white":"#f7f3ea"},"say":"Choosing a palette."} remaps any of the colour names to a hex value for this drawing; every later element uses the names.','Shape: {"id":"sea","say":"First, the sea.","geo":"rectangle","x":0,"y":420,"w":1000,"h":220,"color":"blue","fill":"fill","label":"","opacity":1}',`Path: {"id":"dome","say":"","path":[[400,200],[410,170],[440,150],[470,170],[480,200],[400,200]],"color":"white","fill":"fill","opacity":1} is a free outline of 3 to ${Ac} points, closed and filled, for any silhouette a box can't make: domes, arches, hills, foliage, stairs, shadows, reflections. Straight edges stay straight; give curves enough points. With fill none it is an open stroke: a railing, a grille bar, a crack, a horizon line.`,'Text: {"id":"title","say":"And a title.","text":"Sidi Bou Said","x":330,"y":40,"size":"xl","color":"black","font":"serif"}',`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, then an arrow from that text to the thing.",`geo is one of: ${Ec.join(", ")}.`,`color is one of: ${oi.join(", ")}. fill is fill (strong colour), solid (pale tint), semi, none or pattern. opacity is 0.1 to 1: use it for shadows, haze and atmospheric depth. size is s, m, l or xl. font is draw (hand-lettered), sans, serif or mono.`,"Keep everything inside the canvas. 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 five) and leave say empty on the rest: captioned steps pause so they can be read, the others draw straight through."].join(`
298
+ `)}function ut(e,o,t){return typeof e=="string"&&o.includes(e)?e:t}function Bo(e){return typeof e=="number"&&Number.isFinite(e)?e:null}var Jo=(e,o,t)=>Math.min(t,Math.max(o,e)),Sc=e=>Jo(Bo(e)??1,.1,1),Tm=/^#[0-9a-f]{6}$/i;function jm(e){if(!e||typeof e!="object")return null;let o={};for(let[t,n]of Object.entries(e))oi.includes(t)&&typeof n=="string"&&Tm.test(n)&&(o[t]=n);return Object.keys(o).length?o:null}function Im(e){if(!Array.isArray(e))return null;let o=[];for(let t of e.slice(0,Ac)){if(!Array.isArray(t))return null;let n=Bo(t[0]),s=Bo(t[1]);if(n===null||s===null)return null;o.push([Jo(n,0,Me.w),Jo(s,0,Me.h)])}return o.length>=2?o:null}function Tc(e,o){let t=e.trim().replace(/,$/,"");if(!t.startsWith("{"))return null;let n;try{n=JSON.parse(t)}catch{return null}if("palette"in n){let l=jm(n.palette);return!l||o.has("palette")?null:{kind:"palette",id:"palette",say:typeof n.say=="string"?n.say.slice(0,80):"",colors:l}}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=ut(n.color,oi,"black");if(Array.isArray(n.arrow)){let[l,g]=n.arrow;return typeof l!="string"||typeof g!="string"||!o.has(l)||!o.has(g)||l===g?null:{kind:"arrow",id:s,say:i,from:l,to:g,label:typeof n.label=="string"?n.label.slice(0,40):"",color:r}}if("path"in n){let l=Im(n.path),g=ut(n.fill,xc,"fill");return!l||g!=="none"&&l.length<3?null:{kind:"path",id:s,say:i,pts:l,color:r,fill:g,opacity:Sc(n.opacity)}}let a=Bo(n.x),c=Bo(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:Jo(a,0,Me.w-20),y:Jo(c,0,Me.h-20),size:ut(n.size,Am,"l"),color:r,font:ut(n.font,Om,"draw")};if(typeof n.geo=="string"){let l=Bo(n.w),g=Bo(n.h);if(l===null||g===null||l<4||g<4)return null;let d=Jo(a,0,Me.w-4),u=Jo(c,0,Me.h-4);return{kind:"geo",id:s,say:i,geo:ut(n.geo,Ec,"rectangle"),x:d,y:u,w:Math.min(l,Me.w-d),h:Math.min(g,Me.h-u),color:r,fill:ut(n.fill,xc,"solid"),label:typeof n.label=="string"?n.label.slice(0,40):"",opacity:Sc(n.opacity)}}return null}var Hn=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 Cm=500,Nm=e=>`
300
300
  editor.zoomToBounds({ x: 0, y: 0, w: ${Me.w}, h: ${Me.h} }, { inset: ${e}, immediate: true })
301
301
  const o = editor.pageToScreen({ x: 0, y: 0 }), e = editor.pageToScreen({ x: ${Me.w}, y: 0 })
302
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) / ${Me.w} }`;function Ac(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 Oc(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 jm(e){let o=e.map(i=>i[0]),t=e.map(i=>i[1]),n=Math.min(...o),s=Math.min(...t);return{x:n,y:s,w:Math.max(...o)-n,h:Math.max(...t)-s}}function Tc(e){return`const hex = ${JSON.stringify(e.colors)}
303
+ return { ox: window.screenX + o.x, oy: window.screenY + chrome + o.y, scale: (e.x - o.x) / ${Me.w} }`;function jc(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 Ic(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 Rm(e){let o=e.map(i=>i[0]),t=e.map(i=>i[1]),n=Math.min(...o),s=Math.min(...t);return{x:n,y:s,w:Math.max(...o)-n,h:Math.max(...t)-s}}function Cc(e){return`const hex = ${JSON.stringify(e.colors)}
304
304
  const tint = (h, t) => '#' + [1, 3, 5].map((i) => Math.round(parseInt(h.slice(i, i + 2), 16) * (1 - t) + 255 * t).toString(16).padStart(2, '0')).join('')
305
305
  const th = editor.getTheme('default')
306
306
  const colors = structuredClone(th.colors)
@@ -308,9 +308,9 @@ for (const mode of Object.keys(colors)) for (const [name, v] of Object.entries(h
308
308
  if (colors[mode][name]) Object.assign(colors[mode][name], { solid: v, fill: v, pattern: v, linedFill: tint(v, 0.25), semi: tint(v, 0.75), noteFill: v })
309
309
  }
310
310
  editor.updateTheme({ ...th, colors })
311
- return true`}function Cm(e,o){if(e.kind==="palette")return Tc(e);let t=s=>JSON.stringify(`${o}-${s}`),n=`const { createShapeId, toRichText } = await import('tldraw')
311
+ return true`}function Dm(e,o){if(e.kind==="palette")return Cc(e);let t=s=>JSON.stringify(`${o}-${s}`),n=`const { createShapeId, toRichText } = await import('tldraw')
312
312
  const el = ${JSON.stringify(e)}
313
- const frames = 10, wait = () => new Promise((r) => setTimeout(r, ${Math.round(Tm/10)}))
313
+ const frames = 10, wait = () => new Promise((r) => setTimeout(r, ${Math.round(Cm/10)}))
314
314
  const ease = (t) => 1 - Math.pow(1 - t, 3)`;return e.kind==="geo"?`${n}
315
315
  const id = createShapeId(${t(e.id)})
316
316
  editor.createShape({ id, type: 'geo', x: el.x, y: el.y, opacity: el.opacity, props: { geo: el.geo, w: 1, h: 1, color: el.color, fill: el.fill, dash: 'solid', size: 's' } })
@@ -350,70 +350,70 @@ return id`:`${n}
350
350
  const arrow = helpers.createArrowBetweenShapes(createShapeId(${t(e.from)}), createShapeId(${t(e.to)}), el.label ? { richText: toRichText(el.label) } : {})
351
351
  const aid = typeof arrow === 'string' ? arrow : arrow?.id
352
352
  if (aid) editor.updateShape({ id: aid, type: 'arrow', props: { color: el.color } })
353
- return aid ?? null`}function Nm(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.floor(s.length/2)];return[lo(s[0][0],s[0][1]),lo(i[0],i[1])]}if(e.kind==="geo")return[lo(e.x,e.y),lo(e.x+e.w,e.y+e.h)];if(e.kind==="text"){let s=Oc(e);return[lo(s.x,s.y+s.h/2),lo(s.x+s.w,s.y+s.h/2)]}let t=o.get(e.from),n=o.get(e.to);return[lo(t.x+t.w/2,t.y+t.h/2),lo(n.x+n.w/2,n.y+n.h/2)]}var lo=(e,o)=>({x:e,y:o,w:0,h:0});async function Ic(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(),l=await o.api.exec(t.docId,Im(60)),g=new Set,d=new Map,u=[],f=!1,p=0,w=null,y=null,k=null,b=()=>{k?.(),k=null},S=v=>{if(g.size>=ei)return;let $=Ec(v,g);if(!$){v.trim()&&n({type:"skipped",line:v.slice(0,120)});return}g.add($.id),w??=i()-c,u.push($),n({type:"planned",n:g.size,el:$,atMs:i()-c}),b()},A=(async()=>{let v=new Gn;try{for await(let $ of o.model.reply(`Draw: ${e}`,t.signal))v.push($).forEach(S);v.flush().forEach(S)}catch($){y=$?.message??String($)}finally{p=i()-c,f=!0,b()}})(),x=0;for(;!t.signal?.aborted;){let v=u.shift();if(!v){if(f)break;await new Promise(D=>{k=D});continue}if(v.kind==="arrow"&&!(d.has(v.from)&&d.has(v.to))){n({type:"error",error:`${v.id}: an end was not drawn`});continue}let $=i();if(v.kind==="palette"){v.say&&o.presence.say(v.say);try{await o.api.exec(t.docId,Tc(v))}catch(D){n({type:"error",error:`palette: ${D?.message??D}`});continue}x++,n({type:"drawn",n:x,el:v,ms:i()-$});continue}let[C,j]=Nm(v,d);v.say&&o.presence.say(v.say),o.presence.moveTo(Ac(l,C.x,C.y)),await s(250),o.presence.moveTo(Ac(l,j.x,j.y));try{await o.api.exec(t.docId,Cm(v,a))}catch(D){n({type:"error",error:`${v.id}: ${D?.message??D}`});continue}d.set(v.id,v.kind==="geo"?v:v.kind==="text"?Oc(v):v.kind==="path"?jm(v.pts):lo(0,0)),x++,n({type:"drawn",n:x,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:x,totalMs:i()-c,firstLineMs:w,planMs:p}}import{readFileSync as Rm}from"fs";import{homedir as Dm}from"os";import{join as _m}from"path";var Vt=_m(Dm(),"Library","Application Support","tldraw","server.json"),Hn=class{constructor(o=Vt,t=fetch){this.serverJson=o;this.fetchFn=t}server(){let o;try{o=Rm(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 qm=Um(Pm),Wm="claude-sonnet-5";function Bm(e){e.type==="planned"?console.log(Xe.dim(` planned ${e.n}: ${e.el.kind} ${e.el.id} at ${(e.atMs/1e3).toFixed(1)} s`)):e.type==="drawn"?console.log(`${Xe.cyan(` ${e.n}. ${e.el.kind} ${e.el.id}`)} ${e.el.say}${Xe.dim(` (${(e.ms/1e3).toFixed(1)} s)`)}`):e.type==="skipped"?console.log(Xe.yellow(` skipped: ${e.line}`)):console.log(Xe.red(` error: ${e.error}`))}async function Jm(){if(!oi(Vt)){await qm("open",["-a","tldraw offline"]);for(let e=0;e<40&&!oi(Vt);e++)await new Promise(o=>setTimeout(o,500));if(!oi(Vt))throw new Error("tldraw offline did not start")}}async function Cc(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||Wm,i=Fm(o.out||jc(Lm(),"Documents")),r=xn(n,t.agents[n]),a=it({system:Sc(),model:s}),c=new Sn(r,$e,n),l=new Hn;try{await Jm();let g=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),d=await l.createDoc(`agentx-draw-${g}`,i);await new Promise(k=>setTimeout(k,800)),console.log(Xe.bold(`
353
+ return aid ?? null`}function _m(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.floor(s.length/2)];return[lo(s[0][0],s[0][1]),lo(i[0],i[1])]}if(e.kind==="geo")return[lo(e.x,e.y),lo(e.x+e.w,e.y+e.h)];if(e.kind==="text"){let s=Ic(e);return[lo(s.x,s.y+s.h/2),lo(s.x+s.w,s.y+s.h/2)]}let t=o.get(e.from),n=o.get(e.to);return[lo(t.x+t.w/2,t.y+t.h/2),lo(n.x+n.w/2,n.y+n.h/2)]}var lo=(e,o)=>({x:e,y:o,w:0,h:0});async function Nc(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(),l=await o.api.exec(t.docId,Nm(60)),g=new Set,d=new Map,u=[],f=!1,p=0,w=null,y=null,k=null,b=()=>{k?.(),k=null},S=v=>{if(g.size>=ti)return;let $=Tc(v,g);if(!$){v.trim()&&n({type:"skipped",line:v.slice(0,120)});return}g.add($.id),w??=i()-c,u.push($),n({type:"planned",n:g.size,el:$,atMs:i()-c}),b()},A=(async()=>{let v=new Hn;try{for await(let $ of o.model.reply(`Draw: ${e}`,t.signal))v.push($).forEach(S);v.flush().forEach(S)}catch($){y=$?.message??String($)}finally{p=i()-c,f=!0,b()}})(),x=0;for(;!t.signal?.aborted;){let v=u.shift();if(!v){if(f)break;await new Promise(D=>{k=D});continue}if(v.kind==="arrow"&&!(d.has(v.from)&&d.has(v.to))){n({type:"error",error:`${v.id}: an end was not drawn`});continue}let $=i();if(v.kind==="palette"){v.say&&o.presence.say(v.say);try{await o.api.exec(t.docId,Cc(v))}catch(D){n({type:"error",error:`palette: ${D?.message??D}`});continue}x++,n({type:"drawn",n:x,el:v,ms:i()-$});continue}let[C,I]=_m(v,d);v.say&&o.presence.say(v.say),o.presence.moveTo(jc(l,C.x,C.y)),await s(250),o.presence.moveTo(jc(l,I.x,I.y));try{await o.api.exec(t.docId,Dm(v,a))}catch(D){n({type:"error",error:`${v.id}: ${D?.message??D}`});continue}d.set(v.id,v.kind==="geo"?v:v.kind==="text"?Ic(v):v.kind==="path"?Rm(v.pts):lo(0,0)),x++,n({type:"drawn",n:x,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:x,totalMs:i()-c,firstLineMs:w,planMs:p}}import{readFileSync as Pm}from"fs";import{homedir as Mm}from"os";import{join as Lm}from"path";var Kt=Lm(Mm(),"Library","Application Support","tldraw","server.json"),zn=class{constructor(o=Kt,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 Jm=Bm(Fm),Gm="claude-sonnet-5";function Hm(e){e.type==="planned"?console.log(Xe.dim(` planned ${e.n}: ${e.el.kind} ${e.el.id} at ${(e.atMs/1e3).toFixed(1)} s`)):e.type==="drawn"?console.log(`${Xe.cyan(` ${e.n}. ${e.el.kind} ${e.el.id}`)} ${e.el.say}${Xe.dim(` (${(e.ms/1e3).toFixed(1)} s)`)}`):e.type==="skipped"?console.log(Xe.yellow(` skipped: ${e.line}`)):console.log(Xe.red(` error: ${e.error}`))}async function zm(){if(!ni(Kt)){await Jm("open",["-a","tldraw offline"]);for(let e=0;e<40&&!ni(Kt);e++)await new Promise(o=>setTimeout(o,500));if(!ni(Kt))throw new Error("tldraw offline did not start")}}async function Dc(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||Gm,i=Wm(o.out||Rc(qm(),"Documents")),r=Sn(n,t.agents[n]),a=it({system:Oc(),model:s}),c=new En(r,ke,n),l=new zn;try{await zm();let g=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),d=await l.createDoc(`agentx-draw-${g}`,i);await new Promise(k=>setTimeout(k,800)),console.log(Xe.bold(`
354
354
  ${r.name} draws: ${e}`)+Xe.dim(` (${s}, ${d.filePath})
355
- `));let u=new AbortController;process.once("SIGINT",()=>u.abort());let f=await Ic(e,{api:l,presence:c,model:a},{docId:d.id,signal:u.signal},Bm);await l.exec(d.id,"await helpers.saveDoc(); return true");let p=await l.exec(d.id,"const r = await editor.toImageDataUrl([...editor.getCurrentPageShapeIds()], { format: 'png', scale: 2, background: true }); return r.url"),w=d.filePath?d.filePath.replace(/\.tldraw$/,".png"):jc(i,`agentx-draw-${g}.png`);Mm(w,Buffer.from(p.slice(p.indexOf(",")+1),"base64")),console.log(Xe.bold(`
355
+ `));let u=new AbortController;process.once("SIGINT",()=>u.abort());let f=await Nc(e,{api:l,presence:c,model:a},{docId:d.id,signal:u.signal},Hm);await l.exec(d.id,"await helpers.saveDoc(); return true");let p=await l.exec(d.id,"const r = await editor.toImageDataUrl([...editor.getCurrentPageShapeIds()], { format: 'png', scale: 2, background: true }); return r.url"),w=d.filePath?d.filePath.replace(/\.tldraw$/,".png"):Rc(i,`agentx-draw-${g}.png`);Um(w,Buffer.from(p.slice(p.indexOf(",")+1),"base64")),console.log(Xe.bold(`
356
356
  ${f.steps} steps in ${(f.totalMs/1e3).toFixed(1)} s`)+Xe.dim(` (first shape planned at ${f.firstLineMs===null?"\u2013":(f.firstLineMs/1e3).toFixed(1)} s, plan done at ${(f.planMs/1e3).toFixed(1)} s)`));let y=a.lastUsage;y&&console.log(Xe.dim(` tokens: ${y.inputTokens} in, ${y.outputTokens} out, ${y.cacheReadTokens} cache read, ${y.cacheWriteTokens} cache write; cost ${y.costUsd===null?"not reported":`$${y.costUsd.toFixed(4)}`}`)),console.log(Xe.dim(` ${d.filePath}
357
357
  ${w}
358
- `))}finally{a.close(),c.close()}}var ni=zm(Hm),Dc=new Gm().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, "${yo}" 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 Cc(String(o.live),o):await bc(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(`
358
+ `))}finally{a.close(),c.close()}}var ii=Km(Vm),Mc=new Ym().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, "${yo}" 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 Dc(String(o.live),o):await vc(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(`
359
359
  lessons
360
- `));for(let g of Qs)console.log(` ${X.cyan(g.id.padEnd(22))} ${g.title}`),console.log(` ${" ".repeat(22)} ${X.dim(g.appHint)}
361
- `);return}let t=Qs.find(g=>g.id===e);t||(console.log(X.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),Ym($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:Zm(o.voice,o.agent);console.log(X.bold(`
360
+ `));for(let g of ei)console.log(` ${X.cyan(g.id.padEnd(22))} ${g.title}`),console.log(` ${" ".repeat(22)} ${X.dim(g.appHint)}
361
+ `);return}let t=ei.find(g=>g.id===e);t||(console.log(X.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),Xm(ke)||(console.log(X.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let n=o.speak===!1?void 0:tp(o.voice,o.agent);console.log(X.bold(`
362
362
  ${t.title}`)),console.log(X.dim(` ${t.appHint}
363
- `));try{t.start&&(await ni("/usr/bin/open",Xm(t.start)),await Eo(2e3),await zn(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=Rc(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(X.dim(` recording \u2192 ${i}`)),s=Nc("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await Eo(2e3));let r=o.hud===!1?null:Nc($e,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(g,d,u,f)=>{try{r?.stdin?.write(JSON.stringify({title:g,body:d,state:u,avoid:f})+`
364
- `)}catch{}},c=[],l=!1;try{for(let[g,d]of t.steps.entries()){if(console.log(` ${X.dim(String(g+1).padStart(2))} ${d.say}`),a(`Step ${g+1} of ${t.steps.length}`,d.say,"talking"),d.click||d.type||d.key){if(!d.before)throw new Error(`Step ${g+1} needs a before claim`);await zn(d.before)}let u=o.speak===!1?Promise.resolve():op(d.say,n),f=d.find?await Qm(d.find,c):null;if(d.find&&!f)throw c.push({tried:d.find,changed:!1,note:"not found on screen"}),await u,new Error(`Could not find "${d.find}"; stopped before acting`);if(await u,f&&(a(`Step ${g+1} of ${t.steps.length}`,d.say,"pointing",{x:f.x,y:f.y,w:f.width,h:f.height}),await ni($e,["point","--x",String(f.x),"--y",String(f.y),"--w",String(f.width),"--h",String(f.height),"--label",d.label??d.find??"","--hold",String(d.click||d.type?.5:d.holdSeconds??2.6)]),d.click)){let{error:p,changed:w}=await ti(["click"]);if(p)throw new Error(p);c.push({tried:d.label??d.find??"control",changed:w!==!1,note:p??void 0}),w===!1&&console.log(X.yellow(" \xB7 clicked, but the screen did not change")),await Eo(d.afterClickWaitMs??1500)}if(d.type){await zn(d.before),a(`Step ${g+1} of ${t.steps.length}`,d.type,"typing");let{error:p}=await ti(["type","--text",d.type]);if(p)throw console.log(X.red(` \u2717 ${p}`)),a("Blocked",p,"waiting"),c.push({tried:`type into ${d.label??"the field"}`,changed:!1,note:p}),new Error(p)}if(d.key){await zn(d.before),a(`Step ${g+1} of ${t.steps.length}`,`\u21B5 ${d.key}`,"typing");let{error:p}=await ti(["key","--name",d.key]);if(p)throw console.log(X.red(` \u2717 ${p}`)),a("Blocked",p,"waiting"),c.push({tried:`press ${d.key}`,changed:!1,note:p}),new Error(p)}if(!f&&!d.type&&!d.key?await Eo((d.holdSeconds??1.2)*1e3):d.holdSeconds&&await Eo(d.holdSeconds*1e3),d.verify){a(`Step ${g+1} of ${t.steps.length}`,"Checking that worked\u2026","waiting");let p;try{p=await Yt(d.verify)}catch(w){p=null,console.log(X.yellow(` ? could not check: ${w?.message??w}`))}if(!p&&!d.verifyOptional)throw new Error(`Could not verify: ${d.verify}`);if(p){let w=p.outcome==="confirmed"?X.green("\u2713"):p.outcome==="refuted"?X.red("\u2717"):X.yellow("?");if(console.log(` ${w} ${X.dim(p.reason)}`),!p.ok&&!d.verifyOptional){a("Stopped",`That did not work: ${d.verify}`,"waiting"),console.log(X.red(`
365
- stopping: could not confirm \u2014 ${d.verify}`)),console.log(X.dim(` ${p.reason}`)),console.log(X.dim(` screenshot: ${p.sighting.shot.path}`)),await Eo(2500);try{r?.stdin?.end()}catch{}l=!0;break}}}}}catch(g){l=!0,console.log(X.red(` stopping: ${g?.message??g}`)),a("Stopped",String(g?.message??g),"waiting")}finally{if(l)try{r?.stdin?.end()}catch{}}if(!l){a("Done",t.title,"done"),await Eo(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await Eo(2500);try{let{size:g}=Vm(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(l){console.log(X.red(` lesson stopped before the end.
363
+ `));try{t.start&&(await ii("/usr/bin/open",ep(t.start)),await Eo(2e3),await Yn(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=Pc(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(X.dim(` recording \u2192 ${i}`)),s=_c("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await Eo(2e3));let r=o.hud===!1?null:_c(ke,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(g,d,u,f)=>{try{r?.stdin?.write(JSON.stringify({title:g,body:d,state:u,avoid:f})+`
364
+ `)}catch{}},c=[],l=!1;try{for(let[g,d]of t.steps.entries()){if(console.log(` ${X.dim(String(g+1).padStart(2))} ${d.say}`),a(`Step ${g+1} of ${t.steps.length}`,d.say,"talking"),d.click||d.type||d.key){if(!d.before)throw new Error(`Step ${g+1} needs a before claim`);await Yn(d.before)}let u=o.speak===!1?Promise.resolve():sp(d.say,n),f=d.find?await op(d.find,c):null;if(d.find&&!f)throw c.push({tried:d.find,changed:!1,note:"not found on screen"}),await u,new Error(`Could not find "${d.find}"; stopped before acting`);if(await u,f&&(a(`Step ${g+1} of ${t.steps.length}`,d.say,"pointing",{x:f.x,y:f.y,w:f.width,h:f.height}),await ii(ke,["point","--x",String(f.x),"--y",String(f.y),"--w",String(f.width),"--h",String(f.height),"--label",d.label??d.find??"","--hold",String(d.click||d.type?.5:d.holdSeconds??2.6)]),d.click)){let{error:p,changed:w}=await si(["click"]);if(p)throw new Error(p);c.push({tried:d.label??d.find??"control",changed:w!==!1,note:p??void 0}),w===!1&&console.log(X.yellow(" \xB7 clicked, but the screen did not change")),await Eo(d.afterClickWaitMs??1500)}if(d.type){await Yn(d.before),a(`Step ${g+1} of ${t.steps.length}`,d.type,"typing");let{error:p}=await si(["type","--text",d.type]);if(p)throw console.log(X.red(` \u2717 ${p}`)),a("Blocked",p,"waiting"),c.push({tried:`type into ${d.label??"the field"}`,changed:!1,note:p}),new Error(p)}if(d.key){await Yn(d.before),a(`Step ${g+1} of ${t.steps.length}`,`\u21B5 ${d.key}`,"typing");let{error:p}=await si(["key","--name",d.key]);if(p)throw console.log(X.red(` \u2717 ${p}`)),a("Blocked",p,"waiting"),c.push({tried:`press ${d.key}`,changed:!1,note:p}),new Error(p)}if(!f&&!d.type&&!d.key?await Eo((d.holdSeconds??1.2)*1e3):d.holdSeconds&&await Eo(d.holdSeconds*1e3),d.verify){a(`Step ${g+1} of ${t.steps.length}`,"Checking that worked\u2026","waiting");let p;try{p=await Vt(d.verify)}catch(w){p=null,console.log(X.yellow(` ? could not check: ${w?.message??w}`))}if(!p&&!d.verifyOptional)throw new Error(`Could not verify: ${d.verify}`);if(p){let w=p.outcome==="confirmed"?X.green("\u2713"):p.outcome==="refuted"?X.red("\u2717"):X.yellow("?");if(console.log(` ${w} ${X.dim(p.reason)}`),!p.ok&&!d.verifyOptional){a("Stopped",`That did not work: ${d.verify}`,"waiting"),console.log(X.red(`
365
+ stopping: could not confirm \u2014 ${d.verify}`)),console.log(X.dim(` ${p.reason}`)),console.log(X.dim(` screenshot: ${p.sighting.shot.path}`)),await Eo(2500);try{r?.stdin?.end()}catch{}l=!0;break}}}}}catch(g){l=!0,console.log(X.red(` stopping: ${g?.message??g}`)),a("Stopped",String(g?.message??g),"waiting")}finally{if(l)try{r?.stdin?.end()}catch{}}if(!l){a("Done",t.title,"done"),await Eo(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await Eo(2500);try{let{size:g}=Qm(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(l){console.log(X.red(` lesson stopped before the end.
366
366
  `)),process.exitCode=3;return}console.log(X.green(`
367
367
  done.
368
- `))});function Xm(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${Rc(Km(),"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 zn(e){let o=await Yt(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function ti(e){try{let{stdout:o}=await ni($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 Qm(e,o=[]){try{let t=await vn({max:45});if(t.candidates.length<2)return null;let n=await Ze(Ht,Fn({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),Un(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=qn(n.answers,t.candidates);return s.present<.5?null:Pt(t,s.id)}catch{return null}}function Zm(e,o){if(e?.trim().toLowerCase()===yo)return{provider:"system",elevenlabs:_t(),system:null,fallback:!0};let t=e?$n(e,Dt()):null;if(t)return{provider:"system",elevenlabs:_t(),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]?Kr(Yr(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:_t(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(X.dim(` no agent voice (${String(n?.message??n).split(`
369
- `)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:_t(),system:null,fallback:!0}}}var ep=new st;async function op(e,o){o&&await ep.say({voice:o,text:e})}var Eo=e=>new Promise(o=>setTimeout(o,e));ge();import{Command as _c}from"commander";import Ue from"chalk";import{createInterface as Pc}from"readline";var tp=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function ft(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(tp()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function np(e){e.type==="line"?console.log(`${Ue.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(Ue.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(Ue.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(Ue.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(Ue.dim(" \xB7 hushed")):e.type==="error"?console.log(Ue.red(` error: ${e.error}`)):e.type==="end"&&console.log(Ue.dim(` \xB7 ended (${e.reason})`))}function Mc(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 sp(e,o,t){let n=_(t.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await ft("GET","/mesh").then(u=>Array.isArray(u.data)?u.data:[]).catch(()=>[]);i=new Qr(()=>n,()=>d),i.usePool(await Xr(zr()))}let r=e.map(d=>s[d]?kn(d,s,!0):i?.speaker(d,!0)),a=e.filter((d,u)=>!r[u]);if(a.length)throw new Error(`Unknown agent: ${a.join(", ")}`);let c=Date.now(),l=new ea({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new st,listener:n.voice.listener,model:(d,u)=>it({system:u})});l.on(np),l.on(d=>{d.type==="line"&&d.turn===0&&console.log(Ue.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=Pc({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close(),console.log(Ue.dim(` ${Mc(l.gaps)}`))}async function ip(e,o,t){let n=await ft("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=Pc({input:process.stdin});s.on("line",a=>{a.trim()&&ft("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void ft("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await ft("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${Ue.bold(c[i].name)}: ${c[i].text}`);if(r=a.gaps??r,!a.active)break;await new Promise(l=>setTimeout(l,400))}s.close(),console.log(Ue.dim(` ${Mc(r)}`))}var Lc=new _c().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?sp:ip)([e,o],s,n),process.exit(0)}catch(i){console.error(Ue.red(` ${i?.message??i}`)),process.exit(1)}}),Fc=new _c().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(Ue.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await ft("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(Ue.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});ge();import{Command as rp}from"commander";import Ae from"chalk";import{existsSync as ap,readFileSync as cp,writeFileSync as lp}from"fs";import{resolve as Uc}from"path";var Yn=new rp().name("voice").description("list installed system voices and pick each agent's voice");function dp(e){let o=e?[e]:[Uc(process.cwd(),"agentx.json"),Uc(process.cwd(),".agentx/config.json")],t=o.find(n=>ap(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function gp(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 l={...c.voice??{}};i&&(l.provider=i),r&&(l.gender=r);let g=l.provider??e?.voice?.provider??"system",d=[i&&`provider ${i}`,r&&`gender ${r}`],u=w=>{if(!a){l.system=w;return}let y=typeof l.system=="string"?{[String(e?.voice?.locale??"en").toLowerCase().split(/[-_]/)[0]]:l.system}:{...l.system??{}};l.system={...y,[a]:w}},f=a?` for ${a}`:"";if(t){let w=t.trim().toLowerCase()===yo,y=w?null:$n(t,s,a??e?.voice?.locale),k=y?`system voice ${Ss(y)}`:"the OS default voice";if((y||w)&&g==="system")u(w?yo:t),d.push(`${k}${f}`);else if(g==="elevenlabs"&&!y&&!w&&!a)l.elevenlabsVoiceId=t,d.push(`ElevenLabs voice ${t}`);else if(y||w)u(w?yo:t),d.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 p=d.filter(Boolean).join(", ");return{raw:{...e,agents:{...e.agents,[o]:{...c,voice:l}}},summary:p}}Yn.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=Dt(),t;try{t=_(e.config)}catch{}let n=t?.voice.locale??"en",s=new Map,i=t?Vr(t.agents,t.voice,o):new Map;if(t)for(let[r,a]of Object.entries(t.agents)){let c=i.get(r),l=Object.values(Es(r,a.voice?.system,a.voice?.gender,t.voice,o));for(let g of new Set([c,...l]))g&&s.set(g.id,[...s.get(g.id)??[],r])}if(!o.length)console.log(Ae.yellow(`
368
+ `))});function ep(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${Pc(Zm(),"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 Yn(e){let o=await Vt(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function si(e){try{let{stdout:o}=await ii(ke,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 op(e,o=[]){try{let t=await xn({max:45});if(t.candidates.length<2)return null;let n=await Ze(zt,Un({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),qn(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=Wn(n.answers,t.candidates);return s.present<.5?null:Mt(t,s.id)}catch{return null}}function tp(e,o){if(e?.trim().toLowerCase()===yo)return{provider:"system",elevenlabs:Pt(),system:null,fallback:!0};let t=e?kn(e,_t()):null;if(t)return{provider:"system",elevenlabs:Pt(),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]?Zr(Xr(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:Pt(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(X.dim(` no agent voice (${String(n?.message??n).split(`
369
+ `)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:Pt(),system:null,fallback:!0}}}var np=new st;async function sp(e,o){o&&await np.say({voice:o,text:e})}var Eo=e=>new Promise(o=>setTimeout(o,e));me();import{Command as Lc}from"commander";import Ue from"chalk";import{createInterface as Fc}from"readline";var ip=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function ft(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(ip()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function rp(e){e.type==="line"?console.log(`${Ue.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(Ue.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(Ue.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(Ue.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(Ue.dim(" \xB7 hushed")):e.type==="error"?console.log(Ue.red(` error: ${e.error}`)):e.type==="end"&&console.log(Ue.dim(` \xB7 ended (${e.reason})`))}function Uc(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 ap(e,o,t){let n=_(t.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await ft("GET","/mesh").then(u=>Array.isArray(u.data)?u.data:[]).catch(()=>[]);i=new oa(()=>n,()=>d),i.usePool(await ea(Kr()))}let r=e.map(d=>s[d]?vn(d,s,!0):i?.speaker(d,!0)),a=e.filter((d,u)=>!r[u]);if(a.length)throw new Error(`Unknown agent: ${a.join(", ")}`);let c=Date.now(),l=new na({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new st,listener:n.voice.listener,model:(d,u)=>it({system:u})});l.on(rp),l.on(d=>{d.type==="line"&&d.turn===0&&console.log(Ue.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=Fc({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close(),console.log(Ue.dim(` ${Uc(l.gaps)}`))}async function cp(e,o,t){let n=await ft("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=Fc({input:process.stdin});s.on("line",a=>{a.trim()&&ft("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void ft("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await ft("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${Ue.bold(c[i].name)}: ${c[i].text}`);if(r=a.gaps??r,!a.active)break;await new Promise(l=>setTimeout(l,400))}s.close(),console.log(Ue.dim(` ${Uc(r)}`))}var qc=new Lc().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?ap:cp)([e,o],s,n),process.exit(0)}catch(i){console.error(Ue.red(` ${i?.message??i}`)),process.exit(1)}}),Wc=new Lc().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(Ue.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await ft("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(Ue.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});me();import{Command as lp}from"commander";import Oe from"chalk";import{existsSync as dp,readFileSync as gp,writeFileSync as mp}from"fs";import{resolve as Bc}from"path";var Vn=new lp().name("voice").description("list installed system voices and pick each agent's voice");function pp(e){let o=e?[e]:[Bc(process.cwd(),"agentx.json"),Bc(process.cwd(),".agentx/config.json")],t=o.find(n=>dp(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function up(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 l={...c.voice??{}};i&&(l.provider=i),r&&(l.gender=r);let g=l.provider??e?.voice?.provider??"system",d=[i&&`provider ${i}`,r&&`gender ${r}`],u=w=>{if(!a){l.system=w;return}let y=typeof l.system=="string"?{[String(e?.voice?.locale??"en").toLowerCase().split(/[-_]/)[0]]:l.system}:{...l.system??{}};l.system={...y,[a]:w}},f=a?` for ${a}`:"";if(t){let w=t.trim().toLowerCase()===yo,y=w?null:kn(t,s,a??e?.voice?.locale),k=y?`system voice ${As(y)}`:"the OS default voice";if((y||w)&&g==="system")u(w?yo:t),d.push(`${k}${f}`);else if(g==="elevenlabs"&&!y&&!w&&!a)l.elevenlabsVoiceId=t,d.push(`ElevenLabs voice ${t}`);else if(y||w)u(w?yo:t),d.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 p=d.filter(Boolean).join(", ");return{raw:{...e,agents:{...e.agents,[o]:{...c,voice:l}}},summary:p}}Vn.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=_t(),t;try{t=_(e.config)}catch{}let n=t?.voice.locale??"en",s=new Map,i=t?Qr(t.agents,t.voice,o):new Map;if(t)for(let[r,a]of Object.entries(t.agents)){let c=i.get(r),l=Object.values(Os(r,a.voice?.system,a.voice?.gender,t.voice,o));for(let g of new Set([c,...l]))g&&s.set(g.id,[...s.get(g.id)??[],r])}if(!o.length)console.log(Oe.yellow(`
370
370
  No system voices found (system voices need macOS).
371
- `));else{let r=e.all?xs(o,""):xs(o,n);console.log(Ae.bold(`
371
+ `));else{let r=e.all?Es(o,""):Es(o,n);console.log(Oe.bold(`
372
372
  System voices${e.all?"":` (${n})`}, best first
373
- `));for(let a of r){let c=a.siri?Ae.magenta("siri"):a.quality==="standard"?Ae.dim("standard"):Ae.green(a.quality),l=s.get(a.id)?.join(", ");console.log(` ${(a.siri?`siri:${a.name.toLowerCase()}`:a.name).padEnd(12)} ${a.locale.padEnd(6)} ${c.padEnd(18)} ${Ae.dim((a.gender??"").padEnd(7))} ${l?Ae.cyan(l):""}`)}o.some(a=>a.quality!=="standard")||(console.log(Ae.dim(`
374
- More natural voices are free: System Settings \u2192 Accessibility \u2192 Spoken Content \u2192`)),console.log(Ae.dim(" System Voice \u2192 Manage Voices, then download a Premium or Enhanced voice.")))}if(t){console.log(Ae.bold(`
373
+ `));for(let a of r){let c=a.siri?Oe.magenta("siri"):a.quality==="standard"?Oe.dim("standard"):Oe.green(a.quality),l=s.get(a.id)?.join(", ");console.log(` ${(a.siri?`siri:${a.name.toLowerCase()}`:a.name).padEnd(12)} ${a.locale.padEnd(6)} ${c.padEnd(18)} ${Oe.dim((a.gender??"").padEnd(7))} ${l?Oe.cyan(l):""}`)}o.some(a=>a.quality!=="standard")||(console.log(Oe.dim(`
374
+ More natural voices are free: System Settings \u2192 Accessibility \u2192 Spoken Content \u2192`)),console.log(Oe.dim(" System Voice \u2192 Manage Voices, then download a Premium or Enhanced voice.")))}if(t){console.log(Oe.bold(`
375
375
  Agents
376
- `));for(let[r,a]of Object.entries(t.agents)){let c=a.voice?.provider??t.voice.provider,l=u=>u?Ss(u):Ae.dim("system default"),g=Object.entries(Es(r,a.voice?.system,a.voice?.gender,t.voice,o)).filter(([,u])=>(u?.id??null)!==(i.get(r)?.id??null)).map(([u,f])=>`${Ae.dim(`${u}:`)} ${l(f)}`).join(Ae.dim(" \xB7 ")),d=c==="elevenlabs"?`elevenlabs ${a.voice?.elevenlabsVoiceId??Ae.dim("(default voice)")}`:`system ${l(i.get(r))}${g?Ae.dim(" \xB7 ")+g:""}`;console.log(` ${r.padEnd(24)} ${d}${a.voice?.gender?Ae.dim(` (${a.voice.gender})`):""}`)}}console.log()});Yn.command("set <agent> [voice]").description(`pick an agent's voice: a system voice name, a Siri voice as siri:<name>, "${yo}" 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=dp(t.config),{raw:s,summary:i}=gp(JSON.parse(cp(n,"utf8")),e,o,t,Dt());lp(n,JSON.stringify(s,null,2)+`
377
- `),console.log(Ae.green(` ${e}: ${i}`)),console.log(Ae.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(Ae.red(` ${n.message}`)),process.exit(1)}});import{Command as mp}from"commander";import L from"chalk";var Jo=new mp().name("attach").description("wear an agentx agent identity in this Claude Code session"),si=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Ft()}`;function ii(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function ri(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 ai(e){let o=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(o)?`daemon not reachable \u2014 start it with ${L.cyan("agentx daemon start")}`:o}function qc(e){return e==="auto"?L.yellow:e==="manual"?L.gray:L.green}function pp(e,o=!1){let t=e.agentIds.length?e.agentIds.join(", "):L.gray("(not bound)"),n=e.pending?L.yellow(`${e.pending} pending`):L.gray("empty"),s=o?L.cyan(" \u2190 this session"):"";console.log(` ${L.bold(t)} ${qc(e.mode)(e.mode)} ${n} ${L.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${L.gray(e.cwd)}`)}Jo.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${ys.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",si).action(async(e,o)=>{let t=ii(o.session);t||(console.error(L.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${L.cyan("--session <id>")} (list them with ${L.cyan("agentx attach list")}).`),process.exit(1)),tr(o.mode)||(console.error(L.red(`Invalid mode "${o.mode}". Expected one of: ${ys.join(", ")}`)),process.exit(1)),Rn()||(console.error(L.yellow("Attach hooks are not installed yet.")),console.error(`Run ${L.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{let n=await ri(o.url,"/attach/bind",{sessionId:t,agentId:e,mode:o.mode,cwd:process.cwd()});console.log(`${L.green("\u2713")} This session is now wearing ${L.bold(e)} (${qc(o.mode)(o.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(L.yellow(` ${s} message(s) already queued for it.`)),console.log(L.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(L.red(`Bind failed: ${ai(n)}`)),process.exit(1)}});Jo.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",si).action(async e=>{let o=ii(e.session);o||(console.error(L.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await ri(e.url,"/attach/detach",{sessionId:o,agentId:e.agent}),console.log(`${L.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(t){console.error(L.red(`Detach failed: ${ai(t)}`)),process.exit(1)}});Jo.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",si).option("--json","raw JSON output").action(async e=>{let o=ii();try{let n=(await ri(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:Rn(),sessions:n},null,2));return}console.log(),console.log(Rn()?`${L.green("\u2713")} Attach hooks installed ${L.gray(Lt())}`:`${L.yellow("!")} Attach hooks not installed \u2014 run ${L.cyan("agentx attach install")}`),console.log();let s=n.filter(r=>r.agentIds.length>0);if(s.length===0)console.log(L.gray(" No session is wearing an identity right now."));else for(let r of s)pp(r,r.sessionId===o);let i=n.length-s.length;i>0&&console.log(L.gray(`
378
- ${i} registered session(s) with no binding.`)),console.log()}catch(t){console.error(L.red(`Could not read attach state: ${ai(t)}`)),process.exit(1)}});Jo.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||Ft()),t=Oa(o,{path:e.path,withGuard:e.guard});console.log(t.changed?`${L.green("\u2713")} Installed attach hooks in ${L.gray(t.path)}`:`${L.green("\u2713")} Attach hooks already up to date in ${L.gray(t.path)}`),console.log(L.gray(` Events: ${t.events.join(", ")} \u2192 127.0.0.1:${o}`)),t.guardInstalled?(console.log(L.gray(" PreToolUse guard installed at user scope.")),console.log(L.gray(` (An attached session runs under your permissions, not the agent's workspace
376
+ `));for(let[r,a]of Object.entries(t.agents)){let c=a.voice?.provider??t.voice.provider,l=u=>u?As(u):Oe.dim("system default"),g=Object.entries(Os(r,a.voice?.system,a.voice?.gender,t.voice,o)).filter(([,u])=>(u?.id??null)!==(i.get(r)?.id??null)).map(([u,f])=>`${Oe.dim(`${u}:`)} ${l(f)}`).join(Oe.dim(" \xB7 ")),d=c==="elevenlabs"?`elevenlabs ${a.voice?.elevenlabsVoiceId??Oe.dim("(default voice)")}`:`system ${l(i.get(r))}${g?Oe.dim(" \xB7 ")+g:""}`;console.log(` ${r.padEnd(24)} ${d}${a.voice?.gender?Oe.dim(` (${a.voice.gender})`):""}`)}}console.log()});Vn.command("set <agent> [voice]").description(`pick an agent's voice: a system voice name, a Siri voice as siri:<name>, "${yo}" 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=pp(t.config),{raw:s,summary:i}=up(JSON.parse(gp(n,"utf8")),e,o,t,_t());mp(n,JSON.stringify(s,null,2)+`
377
+ `),console.log(Oe.green(` ${e}: ${i}`)),console.log(Oe.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(Oe.red(` ${n.message}`)),process.exit(1)}});import{Command as fp}from"commander";import L from"chalk";var Go=new fp().name("attach").description("wear an agentx agent identity in this Claude Code session"),ri=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Ut()}`;function ai(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function ci(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 li(e){let o=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(o)?`daemon not reachable \u2014 start it with ${L.cyan("agentx daemon start")}`:o}function Jc(e){return e==="auto"?L.yellow:e==="manual"?L.gray:L.green}function hp(e,o=!1){let t=e.agentIds.length?e.agentIds.join(", "):L.gray("(not bound)"),n=e.pending?L.yellow(`${e.pending} pending`):L.gray("empty"),s=o?L.cyan(" \u2190 this session"):"";console.log(` ${L.bold(t)} ${Jc(e.mode)(e.mode)} ${n} ${L.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${L.gray(e.cwd)}`)}Go.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${bs.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",ri).action(async(e,o)=>{let t=ai(o.session);t||(console.error(L.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${L.cyan("--session <id>")} (list them with ${L.cyan("agentx attach list")}).`),process.exit(1)),ir(o.mode)||(console.error(L.red(`Invalid mode "${o.mode}". Expected one of: ${bs.join(", ")}`)),process.exit(1)),Dn()||(console.error(L.yellow("Attach hooks are not installed yet.")),console.error(`Run ${L.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{let n=await ci(o.url,"/attach/bind",{sessionId:t,agentId:e,mode:o.mode,cwd:process.cwd()});console.log(`${L.green("\u2713")} This session is now wearing ${L.bold(e)} (${Jc(o.mode)(o.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(L.yellow(` ${s} message(s) already queued for it.`)),console.log(L.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(L.red(`Bind failed: ${li(n)}`)),process.exit(1)}});Go.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",ri).action(async e=>{let o=ai(e.session);o||(console.error(L.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await ci(e.url,"/attach/detach",{sessionId:o,agentId:e.agent}),console.log(`${L.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(t){console.error(L.red(`Detach failed: ${li(t)}`)),process.exit(1)}});Go.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",ri).option("--json","raw JSON output").action(async e=>{let o=ai();try{let n=(await ci(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:Dn(),sessions:n},null,2));return}console.log(),console.log(Dn()?`${L.green("\u2713")} Attach hooks installed ${L.gray(Ft())}`:`${L.yellow("!")} Attach hooks not installed \u2014 run ${L.cyan("agentx attach install")}`),console.log();let s=n.filter(r=>r.agentIds.length>0);if(s.length===0)console.log(L.gray(" No session is wearing an identity right now."));else for(let r of s)hp(r,r.sessionId===o);let i=n.length-s.length;i>0&&console.log(L.gray(`
378
+ ${i} registered session(s) with no binding.`)),console.log()}catch(t){console.error(L.red(`Could not read attach state: ${li(t)}`)),process.exit(1)}});Go.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||Ut()),t=Ia(o,{path:e.path,withGuard:e.guard});console.log(t.changed?`${L.green("\u2713")} Installed attach hooks in ${L.gray(t.path)}`:`${L.green("\u2713")} Attach hooks already up to date in ${L.gray(t.path)}`),console.log(L.gray(` Events: ${t.events.join(", ")} \u2192 127.0.0.1:${o}`)),t.guardInstalled?(console.log(L.gray(" PreToolUse guard installed at user scope.")),console.log(L.gray(` (An attached session runs under your permissions, not the agent's workspace
379
379
  settings \u2014 without this an attached production identity would be less
380
- guarded than a spawned one.)`))):console.log(L.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${L.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(L.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Jo.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=Ta({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${L.green("\u2713")} Removed attach hooks from ${L.gray(o.path)} (${o.events.join(", ")})`:`${L.gray("Nothing to remove.")}`),e.removeGuard||console.log(L.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(L.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});ge();import{Command as up}from"commander";import fe from"chalk";var Vn=new up().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Bc(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 Jc(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function Wc(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 fp(e){return e==="busy"?fe.magenta:e==="warm-hot"?fe.green:e==="warm-cold"?fe.cyan:e==="idle"?fe.yellow:e==="dead"?fe.red:fe.dim}Vn.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}=Bc(e),n;try{n=await fetch(`${o}/api/processes`,{headers:Jc(t)})}catch(r){console.log(fe.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(fe.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(fe.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(fe.dim(" (no processes)"));return}for(let r of i){let a=fp(r.state)(r.state.padEnd(9)),c=Wc(r.spawnedAt),l=r.lastTurnAt?Wc(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?fe.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?fe.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):fe.dim("sess=\u2014"),u=r.pendingTaskId?fe.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${fe.bold(r.key.agentId)}${fe.dim(":"+r.key.channel+":"+r.key.chatId)} ${fe.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${u}`),r.deadReason&&console.log(` ${fe.red("dead:")} ${r.deadReason}`)}});Vn.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}=Bc(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Jc(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(fe.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(fe.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(fe.red(` ${a}`)),process.exit(1)}console.log(fe.green(` killed ${e}:${o}:${t}`))});import{Command as hp}from"commander";import Ne from"chalk";import{existsSync as ci,rmSync as yp}from"fs";import{resolve as li}from"path";var ht=new hp().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");ht.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(Ne.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await rr(e,o,{verbose:n}),r=Date.now()-s;console.log(Ne.green(` \u2713 indexed ${i.docs} doc(s) for ${Ne.bold(e)} in ${r}ms`)),console.log(Ne.dim(` \u2192 ${i.path}`))});ht.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=li(e.cwd,".agentx","rag");if(!ci(o)){console.log(Ne.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>ci(li(o,s,"index.json")));if(n.length===0){console.log(Ne.dim(" (no indexes)"));return}for(let s of n.sort()){let i=ws(s);console.log(` ${Ne.bold(s)} ${i.docs} doc(s) ${Ne.dim(i.path)}`)}});ht.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=ar(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=ws(e);i.exists?console.log(Ne.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Ne.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Ne.bold(i.title)} ${Ne.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Ne.dim(i.path)}`),console.log(` ${Ne.dim(i.snippet.slice(0,200))}`)});ht.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=li(process.cwd(),".agentx","rag",e);if(!ci(o)){console.log(Ne.dim(` no index for ${e} \u2014 nothing to clear`));return}yp(o,{recursive:!0,force:!0}),console.log(Ne.green(` \u2713 cleared index for ${e}`))});ge();import{Command as wp}from"commander";import K from"chalk";import yt from"prompts";var Go=new wp().name("backlog").description("manage the local backlog used by business workSource=backlog");function Kt(e){let o=_(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new sa(n)}}function bp(e){return e?K.cyan(`${e.type}:${e.project}#${e.iid}`):K.dim("manual")}function $p(e){return{todo:K.gray("todo"),doing:K.yellow("doing"),blocked:K.red("blocked"),done:K.green("done")}[e]}Go.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}=Kt(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(` ${$p(n.status).padEnd(7)} ${bp(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()}`))});Go.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=Kt(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=ia([o],i.source,n.config),a=await Ts(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}`))}});Go.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=Kt(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 Ts(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}`))}});Go.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}=Kt(o.config);t.remove(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1)),console.log(K.green(` removed ${e}`))});Go.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=Kt(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 yt({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"?vp(o.config):xp(o.config);y.length?(i=(await yt({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 yt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await yt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await yt({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 Ep(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 l=i,g=new Set(o.store.list().map(y=>y.id)),d=c.map(y=>{let k=Os({type:s,project:l,iid:y.iid,url:y.url}),b=g.has(k),S=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${S}${b?K.dim(" (already imported)"):""}`,value:y,disabled:b}}),f=(await yt({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!f.length){console.log(K.dim(" nothing selected"));return}let p=f.map(y=>{let k={type:s,host:s==="gitlab"?kp(o.config):void 0,project:l,iid:y.iid,url:y.url};return{id:Os(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(p);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 kp(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function vp(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 xp(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 Ep(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 l=await fetch(i,{headers:s});if(!l.ok)throw new Error(`GitHub ${l.status}: ${await l.text().catch(()=>"")}`);return((await l.json()).items??[]).map(Gc)}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(Gc):[]}function Gc(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 Ap}from"commander";import q from"chalk";import{existsSync as Op,readFileSync as Tp}from"fs";import{resolve as Ip}from"path";import jp from"prompts";ge();function Hc(e){let o=e||Ip(process.cwd(),"agentx.json");return Op(o)||(console.log(q.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Tp(o,"utf-8"))}async function Cp(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(q.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await jp([{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(q.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var go=new Ap().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');go.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: ${ks})`,ks).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){go.help();return}o.agent||(console.log(q.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(q.red(' --do "<prompt>" is required')),process.exit(1));let t=$s(e);t||(console.log(q.red(` Couldn't parse: "${e}"`)),console.log(q.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(q.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(q.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=Hc(o.config),s=Ui(n);n.agents?.[o.agent]||(console.log(q.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(q.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await Cp(o.notify,s),r=o.id||pr(t.matched,o.agent),a=fr({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:ur(o.onError),enabled:!o.disabled}),c=a.onError,l=await ue(d=>Se(d,`crons.${r}`,a),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(q.red(` \u2717 ${l.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(q.green(` \u2713 ${g} cron ${q.cyan(r)}`)),console.log(q.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(q.dim(` Agent: ${o.agent}`)),i&&console.log(q.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(q.dim(` On error: ${c.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(q.dim(" Daemon hot-reloaded."))});go.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=Hc(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(q.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?q.yellow("\u25D0"):i.enabled?q.green("\u25CF"):q.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${q.cyan(s.padEnd(32))} ${q.dim(i.schedule.padEnd(14))} ${q.dim("\u2192")} ${i.agent}`),console.log(q.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(q.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(q.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=yr(hr(i.schedule,c),c);console.log(q.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(q.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,o]of[["on",!0],["off",!1]])go.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await $r(t,o);n.success||(console.log(q.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(q.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(q.dim(" Daemon hot-reloaded."))});go.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await ue(t=>{if(!nt(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);dr(t,`crons.${e}`)});o.success||(console.log(q.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(q.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(q.dim(" Daemon hot-reloaded."))});for(let[e,o,t]of[["approve",wr,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",br,"reject an agent's pending create/delete request (drops the request)"]])go.command(`${e} <id>`).description(t).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await o(n,{configPath:s.config});i.success||(console.log(q.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(q.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(q.dim(" Daemon hot-reloaded."))});go.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=$s(o);t||(console.log(q.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(q.green(` "${o}"`)),console.log(q.dim(` \u2192 ${t.cron}`)),console.log(q.dim(` \u2192 ${t.human}`))});import{Command as eu}from"commander";import wt from"chalk";import Z from"chalk";import Qt from"prompts";import{readFileSync as Np,writeFileSync as Rp,existsSync as Dp}from"fs";import{resolve as zc}from"path";var _p=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Pp(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function di(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Yc(e=".env"){let o=zc(e);if(!Dp(o))return[];let t=Np(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(_p);i?n.push({kind:"kv",key:i[1],value:Pp(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Mp(e){return e.map(o=>o.kind==="kv"?`${o.key}=${di(o.value)}`:o.raw).join(`
380
+ guarded than a spawned one.)`))):console.log(L.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${L.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(L.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Go.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=Ca({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${L.green("\u2713")} Removed attach hooks from ${L.gray(o.path)} (${o.events.join(", ")})`:`${L.gray("Nothing to remove.")}`),e.removeGuard||console.log(L.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(L.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});me();import{Command as yp}from"commander";import he from"chalk";var Kn=new yp().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Hc(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 zc(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function Gc(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 wp(e){return e==="busy"?he.magenta:e==="warm-hot"?he.green:e==="warm-cold"?he.cyan:e==="idle"?he.yellow:e==="dead"?he.red:he.dim}Kn.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}=Hc(e),n;try{n=await fetch(`${o}/api/processes`,{headers:zc(t)})}catch(r){console.log(he.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(he.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(he.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(he.dim(" (no processes)"));return}for(let r of i){let a=wp(r.state)(r.state.padEnd(9)),c=Gc(r.spawnedAt),l=r.lastTurnAt?Gc(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?he.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?he.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):he.dim("sess=\u2014"),u=r.pendingTaskId?he.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${he.bold(r.key.agentId)}${he.dim(":"+r.key.channel+":"+r.key.chatId)} ${he.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${u}`),r.deadReason&&console.log(` ${he.red("dead:")} ${r.deadReason}`)}});Kn.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}=Hc(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:zc(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(he.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(he.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(he.red(` ${a}`)),process.exit(1)}console.log(he.green(` killed ${e}:${o}:${t}`))});import{Command as bp}from"commander";import Re from"chalk";import{existsSync as di,rmSync as $p}from"fs";import{resolve as gi}from"path";var ht=new bp().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");ht.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(Re.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await lr(e,o,{verbose:n}),r=Date.now()-s;console.log(Re.green(` \u2713 indexed ${i.docs} doc(s) for ${Re.bold(e)} in ${r}ms`)),console.log(Re.dim(` \u2192 ${i.path}`))});ht.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=gi(e.cwd,".agentx","rag");if(!di(o)){console.log(Re.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>di(gi(o,s,"index.json")));if(n.length===0){console.log(Re.dim(" (no indexes)"));return}for(let s of n.sort()){let i=$s(s);console.log(` ${Re.bold(s)} ${i.docs} doc(s) ${Re.dim(i.path)}`)}});ht.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=dr(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=$s(e);i.exists?console.log(Re.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Re.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Re.bold(i.title)} ${Re.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Re.dim(i.path)}`),console.log(` ${Re.dim(i.snippet.slice(0,200))}`)});ht.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=gi(process.cwd(),".agentx","rag",e);if(!di(o)){console.log(Re.dim(` no index for ${e} \u2014 nothing to clear`));return}$p(o,{recursive:!0,force:!0}),console.log(Re.green(` \u2713 cleared index for ${e}`))});me();import{Command as kp}from"commander";import K from"chalk";import yt from"prompts";var Ho=new kp().name("backlog").description("manage the local backlog used by business workSource=backlog");function Xt(e){let o=_(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new aa(n)}}function vp(e){return e?K.cyan(`${e.type}:${e.project}#${e.iid}`):K.dim("manual")}function xp(e){return{todo:K.gray("todo"),doing:K.yellow("doing"),blocked:K.red("blocked"),done:K.green("done")}[e]}Ho.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}=Xt(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(` ${xp(n.status).padEnd(7)} ${vp(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()}`))});Ho.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=Xt(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=ca([o],i.source,n.config),a=await Is(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}`))}});Ho.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=Xt(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 Is(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}`))}});Ho.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}=Xt(o.config);t.remove(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1)),console.log(K.green(` removed ${e}`))});Ho.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=Xt(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 yt({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"?Ep(o.config):Ap(o.config);y.length?(i=(await yt({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 yt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await yt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await yt({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 Op(o.config,i,a):await Tp(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 l=i,g=new Set(o.store.list().map(y=>y.id)),d=c.map(y=>{let k=js({type:s,project:l,iid:y.iid,url:y.url}),b=g.has(k),S=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${S}${b?K.dim(" (already imported)"):""}`,value:y,disabled:b}}),f=(await yt({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!f.length){console.log(K.dim(" nothing selected"));return}let p=f.map(y=>{let k={type:s,host:s==="gitlab"?Sp(o.config):void 0,project:l,iid:y.iid,url:y.url};return{id:js(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(p);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 Sp(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Ep(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 Ap(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 Op(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 Tp(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 l=await fetch(i,{headers:s});if(!l.ok)throw new Error(`GitHub ${l.status}: ${await l.text().catch(()=>"")}`);return((await l.json()).items??[]).map(Yc)}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(Yc):[]}function Yc(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 jp}from"commander";import q from"chalk";import{existsSync as Ip,readFileSync as Cp}from"fs";import{resolve as Np}from"path";import Rp from"prompts";me();function Vc(e){let o=e||Np(process.cwd(),"agentx.json");return Ip(o)||(console.log(q.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Cp(o,"utf-8"))}async function Dp(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(q.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await Rp([{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(q.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var go=new jp().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');go.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: ${xs})`,xs).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){go.help();return}o.agent||(console.log(q.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(q.red(' --do "<prompt>" is required')),process.exit(1));let t=vs(e);t||(console.log(q.red(` Couldn't parse: "${e}"`)),console.log(q.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(q.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(q.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=Vc(o.config),s=Bi(n);n.agents?.[o.agent]||(console.log(q.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(q.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await Dp(o.notify,s),r=o.id||hr(t.matched,o.agent),a=wr({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:yr(o.onError),enabled:!o.disabled}),c=a.onError,l=await fe(d=>Ee(d,`crons.${r}`,a),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(q.red(` \u2717 ${l.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(q.green(` \u2713 ${g} cron ${q.cyan(r)}`)),console.log(q.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(q.dim(` Agent: ${o.agent}`)),i&&console.log(q.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(q.dim(` On error: ${c.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(q.dim(" Daemon hot-reloaded."))});go.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=Vc(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(q.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?q.yellow("\u25D0"):i.enabled?q.green("\u25CF"):q.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${q.cyan(s.padEnd(32))} ${q.dim(i.schedule.padEnd(14))} ${q.dim("\u2192")} ${i.agent}`),console.log(q.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(q.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(q.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=$r(br(i.schedule,c),c);console.log(q.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(q.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,o]of[["on",!0],["off",!1]])go.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await xr(t,o);n.success||(console.log(q.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(q.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(q.dim(" Daemon hot-reloaded."))});go.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await fe(t=>{if(!nt(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);pr(t,`crons.${e}`)});o.success||(console.log(q.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(q.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(q.dim(" Daemon hot-reloaded."))});for(let[e,o,t]of[["approve",kr,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",vr,"reject an agent's pending create/delete request (drops the request)"]])go.command(`${e} <id>`).description(t).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await o(n,{configPath:s.config});i.success||(console.log(q.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(q.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(q.dim(" Daemon hot-reloaded."))});go.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=vs(o);t||(console.log(q.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(q.green(` "${o}"`)),console.log(q.dim(` \u2192 ${t.cron}`)),console.log(q.dim(` \u2192 ${t.human}`))});import{Command as nu}from"commander";import wt from"chalk";import Z from"chalk";import Zt from"prompts";import{readFileSync as _p,writeFileSync as Pp,existsSync as Mp}from"fs";import{resolve as Kc}from"path";var Lp=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Fp(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function mi(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Xc(e=".env"){let o=Kc(e);if(!Mp(o))return[];let t=_p(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(Lp);i?n.push({kind:"kv",key:i[1],value:Fp(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Up(e){return e.map(o=>o.kind==="kv"?`${o.key}=${mi(o.value)}`:o.raw).join(`
381
381
  `)+`
382
- `}function Xt(e,o,t=".env"){let n=zc(t),s=Yc(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${di(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${di(o)}`})),Rp(n,Mp(s))}function gi(e,o=".env"){return Yc(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var Vc="https://t.me/BotFather";async function Lp(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 Fp(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 Kc(e={}){console.log(),console.log(Z.bold(" Connect Telegram")),console.log(),console.log(Z.dim(` 1. Open ${Vc}`)),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 Qt({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),S=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(S,[Vc],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Qt({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 Lp(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")),l=Object.keys(c.agents||{});l.length===0&&(console.log(Z.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Qt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(S=>({title:S,value:S})),initial:0})).agent),g||(console.log(Z.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Qt({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(Z.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Xt(f,t.trim()),process.env[f]=t.trim();let p=await ue(b=>{Se(b,"channels.telegram.enabled",!0),Se(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let S=nt(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;S.includes(A)||(S.push(A),Se(b,`agents.${g}.mentions`,S))},{configPath:e.configPath});if(p.success||(console.log(Z.red(` \u2717 ${p.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}`)),p.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 Qt({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 Fp(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 ${u}`));return}let k=await ue(b=>{Se(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{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 he from"chalk";import mi from"prompts";import{existsSync as ui,mkdirSync as Up,readdirSync as qp,readFileSync as Xc}from"fs";import{resolve as pi}from"path";var Wp=".agentx/whatsapp-sessions";function Bp(){let e=pi(process.cwd(),".agentx/daemon.pid");if(!ui(e))return!1;try{let o=parseInt(Xc(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Jp(e){if(!ui(e))return!1;try{return qp(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Gp(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(he.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(he.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;Up(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(he.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(he.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(he.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(he.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Qc(e={}){if(console.log(),console.log(he.bold(" Connect WhatsApp")),console.log(),Bp()){console.log(he.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(he.dim(" agentx daemon stop")),console.log();let{cont:l}=await mi({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(he.red(" Aborted")),process.exit(1))}let o=e.configPath||pi(process.cwd(),"agentx.json");ui(o)||(console.log(he.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Xc(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Wp,s=pi(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(he.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await mi({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(he.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Jp(s)&&a){let{keep:l}=await mi({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(he.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Gp(s,g=>console.log(g))||(console.log(he.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ue(l=>{Se(l,"channels.whatsapp.enabled",!0),Se(l,"channels.whatsapp.sessionDir",n),Se(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(he.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(he.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(he.dim(` Session: ${n}`)),console.log(he.dim(" Start the daemon to begin receiving:")),console.log(he.dim(" agentx daemon start")),console.log(he.dim(" Add routes later with:")),console.log(he.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Hp}from"crypto";import ke from"chalk";import Zc from"prompts";var Kn="agentx-mesh:",Xn="//join/";function zp(e){return Buffer.from(e,"utf-8").toString("base64url")}function Yp(e){return Buffer.from(e,"base64url").toString("utf-8")}function Vp(e){return`${Kn}${Xn}${zp(JSON.stringify(e))}`}function Kp(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(Yp(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 Xp(){return Hp(32).toString("hex")}function Qp(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Zp(e){return e?.node?.name||e?.node?.id||"node"}async function el(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=gi("MESH_TOKEN");r||(r=Xp(),Xt("MESH_TOKEN",r),console.log(ke.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Qp(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Zc({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(ke.red(" Aborted")),process.exit(1)),a=d}let l=await ue(d=>{Se(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(ke.red(` \u2717 ${l.error}`)),process.exit(1));let g=Vp({url:a,token:r,name:Zp(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 ol(e,o={}){let t;try{t=Kp(e)}catch(i){console.log(ke.red(` \u2717 ${i.message}`)),process.exit(1)}let n=gi("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Zc({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))}Xt("MESH_TOKEN",t.token);let s=await ue(i=>{Se(i,"mesh.enabled",!0);let r=nt(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Se(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 bt=new eu().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");bt.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 Kc({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});bt.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 Qc({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var tl=bt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");tl.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 el({url:e.url,configPath:e.config})});tl.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 ol(e,{configPath:o.config})});bt.action(()=>{console.log(),console.log(wt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${wt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${wt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${wt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${wt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(wt.dim(" GitLab connect is the next slice.")),console.log()});ge();import{Command as ou}from"commander";import de from"chalk";var Zt=new ou().name("usage").description("token usage analysis and reporting");Zt.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(de.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(de.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${de.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: ${de.red(String(s.totalErrors))}`),console.log(),console.log(de.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${de.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${de.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(de.red(" Daemon not running. Start with: agentx daemon start")):console.log(de.red(` ${e.message}`))}});Zt.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(de.red(` Script not found: ${s}`)),console.log(de.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(de.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(de.red(" Analysis failed. Is Python 3 installed?"))}});Zt.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-HGI5C2MP.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(de.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${de.dim("\xB7")} ${d}`);console.log(),console.log(de.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(de.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(de.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(de.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(de.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(de.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=de.dim(`${i.days}d`);console.log(` ${de.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(de.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as tu}from"commander";import ye from"chalk";import{resolve as nu}from"path";ge();var Ao=new tu().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{Ki(nu(process.cwd(),".env"))}catch{}let o=su(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-OYGL7Z7X.js");t(o)}catch(o){console.log(ye.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(ye.dim(o.stack)),process.exit(1)}});function su(e,o){try{let t=_();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(ye.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(ye.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
383
- `)),{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(ye.dim(`
382
+ `}function Qt(e,o,t=".env"){let n=Kc(t),s=Xc(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${mi(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${mi(o)}`})),Pp(n,Up(s))}function pi(e,o=".env"){return Xc(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var Qc="https://t.me/BotFather";async function qp(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 Wp(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 Zc(e={}){console.log(),console.log(Z.bold(" Connect Telegram")),console.log(),console.log(Z.dim(` 1. Open ${Qc}`)),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 Zt({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),S=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(S,[Qc],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Zt({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 qp(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")),l=Object.keys(c.agents||{});l.length===0&&(console.log(Z.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Zt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(S=>({title:S,value:S})),initial:0})).agent),g||(console.log(Z.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Zt({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(Z.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Qt(f,t.trim()),process.env[f]=t.trim();let p=await fe(b=>{Ee(b,"channels.telegram.enabled",!0),Ee(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let S=nt(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;S.includes(A)||(S.push(A),Ee(b,`agents.${g}.mentions`,S))},{configPath:e.configPath});if(p.success||(console.log(Z.red(` \u2717 ${p.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}`)),p.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 Zt({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 Wp(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 ${u}`));return}let k=await fe(b=>{Ee(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{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 ye from"chalk";import ui from"prompts";import{existsSync as hi,mkdirSync as Bp,readdirSync as Jp,readFileSync as el}from"fs";import{resolve as fi}from"path";var Gp=".agentx/whatsapp-sessions";function Hp(){let e=fi(process.cwd(),".agentx/daemon.pid");if(!hi(e))return!1;try{let o=parseInt(el(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function zp(e){if(!hi(e))return!1;try{return Jp(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Yp(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ye.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ye.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;Bp(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(ye.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(ye.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(ye.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(ye.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function ol(e={}){if(console.log(),console.log(ye.bold(" Connect WhatsApp")),console.log(),Hp()){console.log(ye.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ye.dim(" agentx daemon stop")),console.log();let{cont:l}=await ui({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ye.red(" Aborted")),process.exit(1))}let o=e.configPath||fi(process.cwd(),"agentx.json");hi(o)||(console.log(ye.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(el(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Gp,s=fi(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ye.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await ui({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ye.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(zp(s)&&a){let{keep:l}=await ui({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(ye.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Yp(s,g=>console.log(g))||(console.log(ye.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await fe(l=>{Ee(l,"channels.whatsapp.enabled",!0),Ee(l,"channels.whatsapp.sessionDir",n),Ee(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ye.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ye.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ye.dim(` Session: ${n}`)),console.log(ye.dim(" Start the daemon to begin receiving:")),console.log(ye.dim(" agentx daemon start")),console.log(ye.dim(" Add routes later with:")),console.log(ye.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Vp}from"crypto";import ve from"chalk";import tl from"prompts";var Xn="agentx-mesh:",Qn="//join/";function Kp(e){return Buffer.from(e,"utf-8").toString("base64url")}function Xp(e){return Buffer.from(e,"base64url").toString("utf-8")}function Qp(e){return`${Xn}${Qn}${Kp(JSON.stringify(e))}`}function Zp(e){if(!e.startsWith(`${Xn}${Qn}`))throw new Error(`Not a mesh invite link \u2014 expected ${Xn}${Qn}\u2026`);let o=e.slice(Xn.length+Qn.length),t=JSON.parse(Xp(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 eu(){return Vp(32).toString("hex")}function ou(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function tu(e){return e?.node?.name||e?.node?.id||"node"}async function nl(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(ve.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=pi("MESH_TOKEN");r||(r=eu(),Qt("MESH_TOKEN",r),console.log(ve.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||ou(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await tl({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(ve.red(" Aborted")),process.exit(1)),a=d}let l=await fe(d=>{Ee(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(ve.red(` \u2717 ${l.error}`)),process.exit(1));let g=Qp({url:a,token:r,name:tu(i),version:1});console.log(),console.log(ve.bold(" Mesh invite")),console.log(),console.log(` ${ve.cyan(g)}`),console.log(),console.log(ve.dim(" Run on the other node:")),console.log(ve.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(ve.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function sl(e,o={}){let t;try{t=Zp(e)}catch(i){console.log(ve.red(` \u2717 ${i.message}`)),process.exit(1)}let n=pi("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await tl({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(ve.red(" Aborted (keeping existing .env)")),process.exit(1))}Qt("MESH_TOKEN",t.token);let s=await fe(i=>{Ee(i,"mesh.enabled",!0);let r=nt(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Ee(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(ve.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(ve.green(" \u2713 Joined mesh")),console.log(ve.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(ve.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(ve.dim(" Daemon hot-reloaded.")):console.log(ve.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(ve.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(ve.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(ve.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var bt=new nu().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");bt.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 Zc({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});bt.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 ol({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var il=bt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");il.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 nl({url:e.url,configPath:e.config})});il.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 sl(e,{configPath:o.config})});bt.action(()=>{console.log(),console.log(wt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${wt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${wt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${wt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${wt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(wt.dim(" GitLab connect is the next slice.")),console.log()});me();import{Command as su}from"commander";import ge from"chalk";var en=new su().name("usage").description("token usage analysis and reporting");en.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(ge.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ge.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${ge.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: ${ge.red(String(s.totalErrors))}`),console.log(),console.log(ge.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ge.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ge.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ge.red(" Daemon not running. Start with: agentx daemon start")):console.log(ge.red(` ${e.message}`))}});en.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(ge.red(` Script not found: ${s}`)),console.log(ge.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ge.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ge.red(" Analysis failed. Is Python 3 installed?"))}});en.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-4RO4NCBU.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(ge.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${ge.dim("\xB7")} ${d}`);console.log(),console.log(ge.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ge.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(ge.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ge.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ge.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(ge.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=ge.dim(`${i.days}d`);console.log(` ${ge.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(ge.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as iu}from"commander";import we from"chalk";import{resolve as ru}from"path";me();var Ao=new iu().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{Zi(ru(process.cwd(),".env"))}catch{}let o=au(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-U5YP4HWE.js");t(o)}catch(o){console.log(we.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(we.dim(o.stack)),process.exit(1)}});function au(e,o){try{let t=_();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(we.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(we.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
383
+ `)),{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(we.dim(`
384
384
  No boards configured.
385
- `));return}console.log();for(let o of e.boards){console.log(` ${ye.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(ye.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(ye.dim(` primary label: ${o.primaryToolLabel}`)),console.log(ye.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(ye.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{en(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(ye.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{en(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(ye.red(` ${t.message}`)),process.exit(1)}});var fi=Ao.command("column").description("manage a board's columns (add / remove / edit / list)");fi.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(Xl("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(ye.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(` ${ye.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${ye.dim(i)}`)}}catch(o){console.log(ye.red(` ${o.message}`)),process.exit(1)}});fi.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{en(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(ye.red(` ${n.message}`)),process.exit(1)}});fi.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{en(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(ye.red(` ${t.message}`)),process.exit(1)}});Ao.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{en(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(ye.red(` ${o.message}`)),process.exit(1)}});function en(e){let{summary:o,backupPath:t}=Do(n=>e(n));console.log(ye.green(`
385
+ `));return}console.log();for(let o of e.boards){console.log(` ${we.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(we.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(we.dim(` primary label: ${o.primaryToolLabel}`)),console.log(we.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(we.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{on(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(we.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{on(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(we.red(` ${t.message}`)),process.exit(1)}});var yi=Ao.command("column").description("manage a board's columns (add / remove / edit / list)");yi.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(ed("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(we.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(` ${we.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${we.dim(i)}`)}}catch(o){console.log(we.red(` ${o.message}`)),process.exit(1)}});yi.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{on(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(we.red(` ${n.message}`)),process.exit(1)}});yi.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{on(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(we.red(` ${t.message}`)),process.exit(1)}});Ao.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{on(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(we.red(` ${o.message}`)),process.exit(1)}});function on(e){let{summary:o,backupPath:t}=_o(n=>e(n));console.log(we.green(`
386
386
  \u2713 ${o}
387
- `)),t&&console.log(ye.dim(` Backup: ${t}`)),console.log(ye.dim(` Restart the dashboard to pick up the change if not auto-reloading.
388
- `))}import{Command as iu}from"commander";import m from"chalk";import{resolve as W,relative as nl,dirname as sl}from"path";import{execSync as Ho}from"child_process";import{writeFileSync as zo,mkdirSync as mo,readFileSync as on,readdirSync as ru,renameSync as Qn,rmSync as au,existsSync as Je}from"fs";function ve(e,o){return new hs(tn(e),void 0,o||"graph")}function tn(e){return e||W(process.cwd(),".agentx/wiki")}function yi(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var ee=new iu().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 [${yi(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 l of a.articles.slice(0,3))console.log(m.dim(` - ${l.title} [${(l.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 u=W(process.cwd(),".agentx/graph");return Je(u)?new fo({baseDir:u}):null}catch{return null}})(),r=new Map;if(i)try{let u=i.loadIndex();for(let[f,p]of Object.entries(u.entries))r.set(f,p.path)}catch{}let a,c=u=>{let f=u.meta?.intentPath;if(Array.isArray(f)&&f.every(y=>typeof y=="string")&&f.length>0)return f;if(!i||r.size===0)return;let p=String(u.meta?.sender??""),w=i.fingerprint({text:u.content,channel:u.source,sender:p});return r.get(w)},l=(u,f)=>{let p=new Map;for(let y of u){let k=f.find(x=>x.id===y);if(!k)continue;let b=c(k);if(!b?.length)continue;let S=b.join("/"),A=p.get(S);A?A.n++:p.set(S,{path:b,n:1})}if(p.size===0)return;let w;for(let y of p.values())(!w||y.n>w.n)&&(w=y);return w?.path},g=0,d=0;for(let u of n){let f=typeof e.since=="string"?e.since.trim():"",p=t.getUnabsorbedEntries(u).filter($=>!f||($.date??"")>=f).slice(0,s);if(p.length===0){console.log(` ${m.cyan(u)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(u)}: ${p.length} entries to absorb`));for(let $ of p.slice(0,3))console.log(m.dim(` [${$.date} via ${$.source}] ${$.content.slice(0,80)}...`));if(p.length>3&&console.log(m.dim(` ... and ${p.length-3} more`)),e.dryRun)continue;let w=t.getAgentWiki(u),y=w.rebuildIndex(),k=w.getWorldview()||t.getSharedStore().getWorldview()||"",b=p.map($=>`--- ENTRY ${$.id} [${$.date} ${$.agentId} via ${$.source}] ---
387
+ `)),t&&console.log(we.dim(` Backup: ${t}`)),console.log(we.dim(` Restart the dashboard to pick up the change if not auto-reloading.
388
+ `))}import{Command as cu}from"commander";import m from"chalk";import{resolve as W,relative as rl,dirname as al}from"path";import{execSync as zo}from"child_process";import{writeFileSync as Yo,mkdirSync as mo,readFileSync as tn,readdirSync as lu,renameSync as Zn,rmSync as du,existsSync as Je}from"fs";function xe(e,o){return new ws(nn(e),void 0,o||"graph")}function nn(e){return e||W(process.cwd(),".agentx/wiki")}function bi(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var ee=new cu().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=xe(e.dir,o),n=t.summary(),i=t.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${bi(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 l of a.articles.slice(0,3))console.log(m.dim(` - ${l.title} [${(l.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=xe(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=xe(e.dir,o),n=e.agent?[e.agent]:t.listAgents(),s=parseInt(e.max),i=(()=>{try{let u=W(process.cwd(),".agentx/graph");return Je(u)?new fo({baseDir:u}):null}catch{return null}})(),r=new Map;if(i)try{let u=i.loadIndex();for(let[f,p]of Object.entries(u.entries))r.set(f,p.path)}catch{}let a,c=u=>{let f=u.meta?.intentPath;if(Array.isArray(f)&&f.every(y=>typeof y=="string")&&f.length>0)return f;if(!i||r.size===0)return;let p=String(u.meta?.sender??""),w=i.fingerprint({text:u.content,channel:u.source,sender:p});return r.get(w)},l=(u,f)=>{let p=new Map;for(let y of u){let k=f.find(x=>x.id===y);if(!k)continue;let b=c(k);if(!b?.length)continue;let S=b.join("/"),A=p.get(S);A?A.n++:p.set(S,{path:b,n:1})}if(p.size===0)return;let w;for(let y of p.values())(!w||y.n>w.n)&&(w=y);return w?.path},g=0,d=0;for(let u of n){let f=typeof e.since=="string"?e.since.trim():"",p=t.getUnabsorbedEntries(u).filter($=>!f||($.date??"")>=f).slice(0,s);if(p.length===0){console.log(` ${m.cyan(u)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(u)}: ${p.length} entries to absorb`));for(let $ of p.slice(0,3))console.log(m.dim(` [${$.date} via ${$.source}] ${$.content.slice(0,80)}...`));if(p.length>3&&console.log(m.dim(` ... and ${p.length-3} more`)),e.dryRun)continue;let w=t.getAgentWiki(u),y=w.rebuildIndex(),k=w.getWorldview()||t.getSharedStore().getWorldview()||"",b=p.map($=>`--- ENTRY ${$.id} [${$.date} ${$.agentId} via ${$.source}] ---
389
389
  ${$.content}
390
390
  --- END ENTRY ---`).join(`
391
391
 
392
- `),S="";if(e.facts!==!1){let{extractHints:$,resolveFacts:C,mergeRecords:j,renderFactsBlock:T,installPrompts:D,defaultSources:B,recordsFromEntries:M}=await import("./facts-YVEJOM7O.js");if(!a){let J=new Set;for(let xe of t.listAgents())for(let we of t.getAgentWiki(xe).listArticles(xe))we.meta.type==="person"&&J.add(we.meta.title);a=[...J]}let H=$(p.map(J=>({context:J.sourceContext,content:J.content,sender:typeof J.meta?.sender=="string"?J.meta.sender:void 0})),{known:a}),ce=M(p);if(H.length>0||ce.length>0){let J=B(),{records:xe,results:we}=H.length>0?await C(H,{sources:J}):{records:[],results:[]},P=j([...ce,...xe]);S=T(P);let Be=[...ce.length>0?[`entries:${ce.length}`]:[],...we.filter(be=>be.records.length>0).map(be=>`${be.source}:${be.records.length}`)];console.log(m.dim(` Facts: ${H.length} entities \u2192 ${P.length} resolved${Be.length?` (${Be.join(" ")})`:""}`));for(let be of D(we,J))console.log(m.yellow(` ! ${be.source} ${be.kind} \u2014 would supply ${be.provides.join(", ")}`)),console.log(m.dim(` ${be.hint}`))}}let A=Ar(o,u,k,y.articles,b,p.length,S);console.log(m.dim(` Mode: ${yi(o)}`));let x=W(w.baseDir,"_tmp");mo(x,{recursive:!0});let v=W(x,"absorb-prompt.txt");zo(v,A),console.log(m.dim(" Compiling with Claude..."));try{let $;try{$=Ho(`cat '${v}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Qo({...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("{"),B=C.indexOf("["),M=D>=0&&(B<0||D<B)?D:B;if(M===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(C.slice(0,500)));continue}let H=C[M],ce=H==="{"?"}":"]",J=0,xe=-1;for(let P=M;P<C.length;P++)if(C[P]===H)J++;else if(C[P]===ce&&(J--,J===0)){xe=P+1;break}if(xe===-1){console.log(m.red(" Unbalanced JSON"));continue}let we=C.slice(M,xe);try{let P=JSON.parse(we);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: ${we.slice(0,300)}`));continue}for(let P of j){let Be=new Date().toISOString().slice(0,10),be=l(P.sources||[],p);w.writeArticle(P.path,{title:P.title,type:P.type,related:Array.isArray(P.related)?P.related:void 0,tags:P.tags||[],owner:u,access:"public",created:Be,lastUpdated:Be,sources:P.sources||[],graphPath:be},P.content,u);let No=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("+")} ${No}${P.path}: ${P.title}${m.dim(N)}`);let pe=(P.tags||[]).slice(0,4).join(", ");pe&&console.log(m.dim(` tags: ${pe}`)),be?.length&&(console.log(m.dim(` graphPath: ${be.join(" \u203A ")}`)),d++),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"),Be=new P(tn(e.dir)).add(T.map(be=>({kind:"article",agentId:u,path:"",subject:String(be).slice(0,120),question:`No article yet for: ${String(be).slice(0,160)}`})));Be.added>0&&console.log(m.dim(` queued ${Be.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 u=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${u}%) \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=cu(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-BFAWNDOR.js"),{default:c}=await import("better-sqlite3"),l=W(process.cwd(),".agentx/db.sqlite");if(!Je(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=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(d,{kinds:String(e.reviewKinds).split(",").map(p=>p.trim()).filter(Boolean)});let u=i.filter(p=>(p.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${u} 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 Or({extraCandidates:i,wikiDir:e.dir?W(e.dir):void 0,memoryRoot:e.memoryDir?W(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],l=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${l} ${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}]`)+" ":"",l=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(l)}`),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 cu(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",W(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-6EMTLCHQ.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 l=a.getAgentWiki(c),g=parseInt(e.n),d=i(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let u=[],f=t(d).sort().reverse();for(let y of f){let k=r(d,y),b=[];try{b=t(k).filter(S=>S.endsWith(".json")).sort().reverse()}catch{continue}for(let S of b){if(u.length>=g)break;try{let A=JSON.parse(n(r(k,S),"utf-8")),x=A.message||A.task?.message;typeof x=="string"&&x.trim().length>10&&u.push({id:A.id||S.replace(".json",""),message:x.trim(),ts:A.at||A.timestamp||y})}catch{}}if(u.length>=g)break}if(u.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${u.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 p=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${u.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<u.length;y++){let k=u[y];process.stdout.write(m.dim(` [${y+1}/${u.length}] querying... `));let S=l.findRelevant(k.message,c,3).map(x=>`- **${x.meta.title}** [${x.meta.type||"?"}] (${x.path})`).join(`
392
+ `),S="";if(e.facts!==!1){let{extractHints:$,resolveFacts:C,mergeRecords:I,renderFactsBlock:T,installPrompts:D,defaultSources:B,recordsFromEntries:M}=await import("./facts-YVEJOM7O.js");if(!a){let J=new Set;for(let Se of t.listAgents())for(let be of t.getAgentWiki(Se).listArticles(Se))be.meta.type==="person"&&J.add(be.meta.title);a=[...J]}let H=$(p.map(J=>({context:J.sourceContext,content:J.content,sender:typeof J.meta?.sender=="string"?J.meta.sender:void 0})),{known:a}),le=M(p);if(H.length>0||le.length>0){let J=B(),{records:Se,results:be}=H.length>0?await C(H,{sources:J}):{records:[],results:[]},P=I([...le,...Se]);S=T(P);let Be=[...le.length>0?[`entries:${le.length}`]:[],...be.filter($e=>$e.records.length>0).map($e=>`${$e.source}:${$e.records.length}`)];console.log(m.dim(` Facts: ${H.length} entities \u2192 ${P.length} resolved${Be.length?` (${Be.join(" ")})`:""}`));for(let $e of D(be,J))console.log(m.yellow(` ! ${$e.source} ${$e.kind} \u2014 would supply ${$e.provides.join(", ")}`)),console.log(m.dim(` ${$e.hint}`))}}let A=jr(o,u,k,y.articles,b,p.length,S);console.log(m.dim(` Mode: ${bi(o)}`));let x=W(w.baseDir,"_tmp");mo(x,{recursive:!0});let v=W(x,"absorb-prompt.txt");Yo(v,A),console.log(m.dim(" Compiling with Claude..."));try{let $;try{$=zo(`cat '${v}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Qo({...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 I,T=[],D=C.indexOf("{"),B=C.indexOf("["),M=D>=0&&(B<0||D<B)?D:B;if(M===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(C.slice(0,500)));continue}let H=C[M],le=H==="{"?"}":"]",J=0,Se=-1;for(let P=M;P<C.length;P++)if(C[P]===H)J++;else if(C[P]===le&&(J--,J===0)){Se=P+1;break}if(Se===-1){console.log(m.red(" Unbalanced JSON"));continue}let be=C.slice(M,Se);try{let P=JSON.parse(be);Array.isArray(P)?I=P:(I=P.articles||[],T=P.gaps||[])}catch(P){console.log(m.red(` JSON parse error: ${P.message}`)),console.log(m.dim(` First 300 chars: ${be.slice(0,300)}`));continue}for(let P of I){let Be=new Date().toISOString().slice(0,10),$e=l(P.sources||[],p);w.writeArticle(P.path,{title:P.title,type:P.type,related:Array.isArray(P.related)?P.related:void 0,tags:P.tags||[],owner:u,access:"public",created:Be,lastUpdated:Be,sources:P.sources||[],graphPath:$e},P.content,u);let Ro=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("+")} ${Ro}${P.path}: ${P.title}${m.dim(N)}`);let ue=(P.tags||[]).slice(0,4).join(", ");ue&&console.log(m.dim(` tags: ${ue}`)),$e?.length&&(console.log(m.dim(` graphPath: ${$e.join(" \u203A ")}`)),d++),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"),Be=new P(nn(e.dir)).add(T.map($e=>({kind:"article",agentId:u,path:"",subject:String($e).slice(0,120),question:`No article yet for: ${String($e).slice(0,160)}`})));Be.added>0&&console.log(m.dim(` queued ${Be.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 u=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${u}%) \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=gu(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-BFAWNDOR.js"),{default:c}=await import("better-sqlite3"),l=W(process.cwd(),".agentx/db.sqlite");if(!Je(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=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(d,{kinds:String(e.reviewKinds).split(",").map(p=>p.trim()).filter(Boolean)});let u=i.filter(p=>(p.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${u} 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 Ir({extraCandidates:i,wikiDir:e.dir?W(e.dir):void 0,memoryRoot:e.memoryDir?W(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],l=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${l} ${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}]`)+" ":"",l=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(l)}`),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 gu(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",W(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-6EMTLCHQ.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=xe(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),g=parseInt(e.n),d=i(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let u=[],f=t(d).sort().reverse();for(let y of f){let k=r(d,y),b=[];try{b=t(k).filter(S=>S.endsWith(".json")).sort().reverse()}catch{continue}for(let S of b){if(u.length>=g)break;try{let A=JSON.parse(n(r(k,S),"utf-8")),x=A.message||A.task?.message;typeof x=="string"&&x.trim().length>10&&u.push({id:A.id||S.replace(".json",""),message:x.trim(),ts:A.at||A.timestamp||y})}catch{}}if(u.length>=g)break}if(u.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${u.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 p=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${u.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<u.length;y++){let k=u[y];process.stdout.write(m.dim(` [${y+1}/${u.length}] querying... `));let S=l.findRelevant(k.message,c,3).map(x=>`- **${x.meta.title}** [${x.meta.type||"?"}] (${x.path})`).join(`
393
393
  `)||"_(none returned)_",A;try{let x=await o(k.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(x.status!=="ok")A=`_(status: ${x.status}${x.error?" \u2014 "+x.error:""})_`;else{let v=x.citations.map($=>`\`${$.title}\` [${$.type||"?"}]`).join(", ");A=`**Answer:**
394
394
 
395
395
  ${x.answer}
396
396
 
397
397
  **Citations:** ${v}`}}catch(x){A=`_(error: ${x.message})_`}console.log(m.dim("done")),p.push(`## ${y+1}. ${k.id}`,"",`> ${k.message.replace(/\n/g," ").slice(0,400)}${k.message.length>400?"\u2026":""}`,"","### OLD \u2014 BM25 preload (top 3)","",S,"","### NEW \u2014 agentic query","",A,"","| Path | Rating 0\u20132 | Notes |","|---|---|---|","| OLD | | |","| NEW | | |","")}let w=p.join(`
398
- `);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?on(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}),l=async N=>{if(s){let pe=s[i++]??"";return process.stdout.write(N+m.dim(`[scripted] ${pe.slice(0,80)}${pe.length>80?"\u2026":""}`)+`
399
- `),pe.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 l(m.cyan(" Topic? ")+m.dim("(a person, a procedure, a past event, \u2026) ")),!g||g==="/abort")){c?.close();return}let d=(e.type||"").toLowerCase(),u=new Set(n);if(!u.has(d)){console.log(m.dim(` Types: ${n.join(" | ")}`));let N=await l(m.cyan(" Type? "));if(N==="/abort"){c?.close();return}u.has(N)?d=N:(console.log(m.yellow(` "${N}" isn't a valid type. Falling back to "concept".`)),d="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?"]},p=f[d]||f.concept;console.log(),console.log(m.bold(` Topic: ${m.cyan(g)} \xB7 Type: ${m.magenta(d)}`)),console.log(m.dim(` ${p.length} questions. Skip with empty answer. /done to stop early.`)),console.log();let w=[],y=!1;for(let N=0;N<p.length;N++){let pe=p[N],Ge=await l(` ${m.dim(`[${N+1}/${p.length}]`)} ${pe}
400
- ${m.green(">")} `);if(Ge==="/abort"){y=!0;break}if(Ge==="/done")break;Ge!=="/skip"&&Ge&&w.push({q:pe,a:Ge})}if(!y){let N=await l(`
398
+ `);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?tn(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=xe(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}),l=async N=>{if(s){let ue=s[i++]??"";return process.stdout.write(N+m.dim(`[scripted] ${ue.slice(0,80)}${ue.length>80?"\u2026":""}`)+`
399
+ `),ue.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 l(m.cyan(" Topic? ")+m.dim("(a person, a procedure, a past event, \u2026) ")),!g||g==="/abort")){c?.close();return}let d=(e.type||"").toLowerCase(),u=new Set(n);if(!u.has(d)){console.log(m.dim(` Types: ${n.join(" | ")}`));let N=await l(m.cyan(" Type? "));if(N==="/abort"){c?.close();return}u.has(N)?d=N:(console.log(m.yellow(` "${N}" isn't a valid type. Falling back to "concept".`)),d="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?"]},p=f[d]||f.concept;console.log(),console.log(m.bold(` Topic: ${m.cyan(g)} \xB7 Type: ${m.magenta(d)}`)),console.log(m.dim(` ${p.length} questions. Skip with empty answer. /done to stop early.`)),console.log();let w=[],y=!1;for(let N=0;N<p.length;N++){let ue=p[N],Ge=await l(` ${m.dim(`[${N+1}/${p.length}]`)} ${ue}
400
+ ${m.green(">")} `);if(Ge==="/abort"){y=!0;break}if(Ge==="/done")break;Ge!=="/skip"&&Ge&&w.push({q:ue,a:Ge})}if(!y){let N=await l(`
401
401
  ${m.dim("Anything else worth capturing?")}
402
402
  ${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(`
403
403
  Nothing captured. Exiting.`)),c?.close();return}let b=a.listArticles(e.agent).slice(0,40).map(N=>`- ${N.meta.title} [${N.meta.type||"?"}]`).join(`
404
404
  `),S=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${g}`,`**Type:** ${d}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...w.map(N=>`
405
405
  Q: ${N.q}
406
406
  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\`: ${d}`,' - `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(`
407
- `),A=W(a.baseDir,"_tmp");mo(A,{recursive:!0});let x=W(A,`interview-${t().slice(0,8)}.txt`);zo(x,S),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let v="";try{let N=`cat '${x}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,pe=Ho(N,{env:Qo({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Ge=JSON.parse(pe);v=String(Ge.result||Ge.content||"")}catch{v=pe}}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(`
408
- `)){let pe=N.match(/^(\w+):\s*(.+)$/);pe&&(T[pe[1]]=pe[2].trim().replace(/^"(.*)"$/,"$1"))}let D=j[2],B=T.title||g,M=B.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),ce=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${M}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${ce}`)),console.log(),console.log(v),console.log();let J=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),J==="scrap"||J==="/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 xe=D,we={title:B,type:T.type||d,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(J==="edit"){let N=process.env.EDITOR||"vi",pe=W(A,`draft-${t().slice(0,8)}.md`);zo(pe,v);try{Ho(`${N} '${pe}'`,{stdio:"inherit"});let ps=on(pe,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(ps){let uo={};for(let It of ps[1].split(`
409
- `)){let us=It.match(/^(\w+):\s*(.+)$/);us&&(uo[us[1]]=us[2].trim().replace(/^"(.*)"$/,"$1"))}xe=ps[2],we={...we,title:uo.title||we.title,type:uo.type||we.type,access:uo.access||we.access,related:uo.related?uo.related.replace(/^\[|\]$/g,"").split(",").map(It=>It.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):we.related,tags:uo.tags?uo.tags.replace(/^\[|\]$/g,"").split(",").map(It=>It.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):we.tags}}}catch(Ge){console.log(m.red(` editor failed: ${Ge.message}`));return}}if(!a.writeArticle(ce,we,xe,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${ce} saved.`));let Be=a.extractWikilinks(xe),be=new Map;for(let N of a.listArticles(e.agent))be.set(N.meta.title.toLowerCase(),!0);let No=Be.filter(N=>!be.has(N.toLowerCase()));if(No.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let N of No.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-6EMTLCHQ.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 p=on(e.script,"utf-8").split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);r=[];for(let w of p){let y=w.split(/\r?\n/).filter(S=>S.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():"",l=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: ${l} \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 d=[],u=0;for(let f=0;f<l;f++){let p,w;if(r){let H=r[f];if(!H)break;p=H.q,w=H.verdict,console.log(m.cyan(` [${f+1}] Q: `)+p)}else{if(p=await c(m.cyan(` [${f+1}] Q: `)),!p||p==="/done"||p==="/abort")break;w=""}process.stdout.write(m.dim(" querying... "));let y;try{y=await n(p,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(ce=>`${ce.title} [${ce.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
410
- `)),console.log(m.dim(" citations: "+H))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let k={q:p,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)")),d.push(k);continue}let S=b[1].toLowerCase(),A=(b[2]||"").trim();if(d.push(k),S==="/ok"||S==="/skip")continue;if(!A){console.log(m.yellow(` ${S} without note \u2014 skipping.`));continue}let x=y.citations[0];if(!x){console.log(m.yellow(" no cited article to patch."));continue}let v=i.readArticle(x.path);if(!v){console.log(m.red(` can't read ${x.path} to patch.`));continue}console.log(m.dim(` patching ${x.title} (${x.path})...`));let $=du(v.content,S,A,v.meta.title,v.meta.type),C=W(i.baseDir,"_tmp");mo(C,{recursive:!0});let j=W(C,`quiz-patch-${t().slice(0,8)}.txt`);zo(j,$);let T="";try{let H=`cat '${j}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,ce=Ho(H,{env:Qo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let xe=JSON.parse(ce);T=String(xe.result||xe.content||"")}catch{T=ce}let J=T.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);J&&(T=J[1].trim()),T=T.trim()}catch(H){console.log(m.red(` patch failed: ${H.message?.slice(0,120)}`));continue}if(!T||T.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let D=v.content.split(`
407
+ `),A=W(a.baseDir,"_tmp");mo(A,{recursive:!0});let x=W(A,`interview-${t().slice(0,8)}.txt`);Yo(x,S),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let v="";try{let N=`cat '${x}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,ue=zo(N,{env:Qo({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Ge=JSON.parse(ue);v=String(Ge.result||Ge.content||"")}catch{v=ue}}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 I=v.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!I){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 I[1].split(`
408
+ `)){let ue=N.match(/^(\w+):\s*(.+)$/);ue&&(T[ue[1]]=ue[2].trim().replace(/^"(.*)"$/,"$1"))}let D=I[2],B=T.title||g,M=B.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),le=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${M}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${le}`)),console.log(),console.log(v),console.log();let J=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),J==="scrap"||J==="/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 Se=D,be={title:B,type:T.type||d,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(J==="edit"){let N=process.env.EDITOR||"vi",ue=W(A,`draft-${t().slice(0,8)}.md`);Yo(ue,v);try{zo(`${N} '${ue}'`,{stdio:"inherit"});let fs=tn(ue,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(fs){let uo={};for(let jt of fs[1].split(`
409
+ `)){let hs=jt.match(/^(\w+):\s*(.+)$/);hs&&(uo[hs[1]]=hs[2].trim().replace(/^"(.*)"$/,"$1"))}Se=fs[2],be={...be,title:uo.title||be.title,type:uo.type||be.type,access:uo.access||be.access,related:uo.related?uo.related.replace(/^\[|\]$/g,"").split(",").map(jt=>jt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):be.related,tags:uo.tags?uo.tags.replace(/^\[|\]$/g,"").split(",").map(jt=>jt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):be.tags}}}catch(Ge){console.log(m.red(` editor failed: ${Ge.message}`));return}}if(!a.writeArticle(le,be,Se,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${le} saved.`));let Be=a.extractWikilinks(Se),$e=new Map;for(let N of a.listArticles(e.agent))$e.set(N.meta.title.toLowerCase(),!0);let Ro=Be.filter(N=>!$e.has(N.toLowerCase()));if(Ro.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let N of Ro.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-6EMTLCHQ.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=xe(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 p=tn(e.script,"utf-8").split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);r=[];for(let w of p){let y=w.split(/\r?\n/).filter(S=>S.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():"",l=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: ${l} \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 d=[],u=0;for(let f=0;f<l;f++){let p,w;if(r){let H=r[f];if(!H)break;p=H.q,w=H.verdict,console.log(m.cyan(` [${f+1}] Q: `)+p)}else{if(p=await c(m.cyan(` [${f+1}] Q: `)),!p||p==="/done"||p==="/abort")break;w=""}process.stdout.write(m.dim(" querying... "));let y;try{y=await n(p,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(le=>`${le.title} [${le.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
410
+ `)),console.log(m.dim(" citations: "+H))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let k={q:p,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)")),d.push(k);continue}let S=b[1].toLowerCase(),A=(b[2]||"").trim();if(d.push(k),S==="/ok"||S==="/skip")continue;if(!A){console.log(m.yellow(` ${S} without note \u2014 skipping.`));continue}let x=y.citations[0];if(!x){console.log(m.yellow(" no cited article to patch."));continue}let v=i.readArticle(x.path);if(!v){console.log(m.red(` can't read ${x.path} to patch.`));continue}console.log(m.dim(` patching ${x.title} (${x.path})...`));let $=pu(v.content,S,A,v.meta.title,v.meta.type),C=W(i.baseDir,"_tmp");mo(C,{recursive:!0});let I=W(C,`quiz-patch-${t().slice(0,8)}.txt`);Yo(I,$);let T="";try{let H=`cat '${I}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,le=zo(H,{env:Qo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Se=JSON.parse(le);T=String(Se.result||Se.content||"")}catch{T=le}let J=T.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);J&&(T=J[1].trim()),T=T.trim()}catch(H){console.log(m.red(` patch failed: ${H.message?.slice(0,120)}`));continue}if(!T||T.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let D=v.content.split(`
411
411
  `).length,B=T.split(`
412
- `).length;if(console.log(m.dim(` diff: ${D} \u2192 ${B} lines (${B-D>=0?"+":""}${B-D})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),k.patched=x.path+" (dry)";continue}if(!i.writeArticle(x.path,{...v.meta,lastUpdated:new Date().toISOString().slice(0,10)},T,e.agent)){console.log(m.red(" write failed (permission?)"));continue}u++,k.patched=x.path,console.log(m.green(` \u2713 patched ${x.path}`))}if(a&&a.close(),u>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${d.length} rounds, ${u} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${u} patches_`,""];for(let p=0;p<d.length;p++){let w=d[p];f.push(`## ${p+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}\``:""),"")}zo(e.out,f.join(`
413
- `)),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(l){console.log(m.red(` can't open wiki for agent "${e}": ${l.message}`));return}let i=al(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=W(s.baseDir,i),a=t.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${i} in ${a}...`));try{Ho(`${a} '${r}'`,{stdio:"inherit"})}catch(l){console.log(m.red(` editor exited with error: ${l.message?.slice(0,150)}`));return}let c=s.readArticle(i);if(c){let l=new Set,g=s.extractWikilinks(c.content).filter(f=>l.has(f)?!1:(l.add(f),!0)),d=c.meta.related||[];(g.some(f=>!d.includes(f))||d.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(l){console.log(m.yellow(` saved, but catalog rebuild failed: ${l.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(x){console.log(m.red(` can't open wiki for agent "${e}": ${x.message}`));return}let c=al(a,o,e);if(!c){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`));return}let l=a.readArticle(c);if(!l){console.log(m.red(` can't read ${c}.`));return}let g=lu(l.content,l.meta.title,l.meta.type,t),d=W(a.baseDir,"_tmp");mo(d,{recursive:!0});let u=W(d,`patch-${i().slice(0,8)}.txt`);zo(u,g),console.log(),console.log(m.dim(` Target: ${l.meta.title} (${c})`)),console.log(m.dim(` Patching with ${n.patchModel}...`));let f="";try{let x=`cat '${u}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,v=Ho(x,{env:Qo({...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(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 p=l.content.split(`
412
+ `).length;if(console.log(m.dim(` diff: ${D} \u2192 ${B} lines (${B-D>=0?"+":""}${B-D})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),k.patched=x.path+" (dry)";continue}if(!i.writeArticle(x.path,{...v.meta,lastUpdated:new Date().toISOString().slice(0,10)},T,e.agent)){console.log(m.red(" write failed (permission?)"));continue}u++,k.patched=x.path,console.log(m.green(` \u2713 patched ${x.path}`))}if(a&&a.close(),u>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${d.length} rounds, ${u} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${u} patches_`,""];for(let p=0;p<d.length;p++){let w=d[p];f.push(`## ${p+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}\``:""),"")}Yo(e.out,f.join(`
413
+ `)),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=xe(t.dir),s;try{s=n.getAgentWiki(e)}catch(l){console.log(m.red(` can't open wiki for agent "${e}": ${l.message}`));return}let i=dl(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=W(s.baseDir,i),a=t.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${i} in ${a}...`));try{zo(`${a} '${r}'`,{stdio:"inherit"})}catch(l){console.log(m.red(` editor exited with error: ${l.message?.slice(0,150)}`));return}let c=s.readArticle(i);if(c){let l=new Set,g=s.extractWikilinks(c.content).filter(f=>l.has(f)?!1:(l.add(f),!0)),d=c.meta.related||[];(g.some(f=>!d.includes(f))||d.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(l){console.log(m.yellow(` saved, but catalog rebuild failed: ${l.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=xe(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=dl(a,o,e);if(!c){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`));return}let l=a.readArticle(c);if(!l){console.log(m.red(` can't read ${c}.`));return}let g=mu(l.content,l.meta.title,l.meta.type,t),d=W(a.baseDir,"_tmp");mo(d,{recursive:!0});let u=W(d,`patch-${i().slice(0,8)}.txt`);Yo(u,g),console.log(),console.log(m.dim(` Target: ${l.meta.title} (${c})`)),console.log(m.dim(` Patching with ${n.patchModel}...`));let f="";try{let x=`cat '${u}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,v=zo(x,{env:Qo({...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(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 p=l.content.split(`
414
414
  `).length,w=f.split(`
415
- `).length;if(console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${p} \u2192 ${w} lines (${w-p>=0?"+":""}${w-p})`)),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}),v=(await x.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();x.close(),y=v==="y"||v==="yes"}if(!y){console.log(m.dim(" aborted."));return}let k=new Set,b=a.extractWikilinks(f).filter(x=>k.has(x)?!1:(k.add(x),!0));if(!a.writeArticle(c,{...l.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=(l.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 al(e,o,t){let n=o.trim(),s=e.listArticles(t),i=n.toLowerCase(),r=s.find(l=>l.meta.title.toLowerCase()===i);if(r)return r.path;if(n.includes("/")||n.endsWith(".md")){let l=n.endsWith(".md")?n:`${n}.md`,g=s.find(d=>d.path===l||d.path===n);if(g)return g.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(l=>{let g=l.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return g===a||g.includes(a)||l.path.toLowerCase().includes(a)});return c?c.path:null}function lu(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(`
416
- `)}function du(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
415
+ `).length;if(console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${p} \u2192 ${w} lines (${w-p>=0?"+":""}${w-p})`)),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}),v=(await x.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();x.close(),y=v==="y"||v==="yes"}if(!y){console.log(m.dim(" aborted."));return}let k=new Set,b=a.extractWikilinks(f).filter(x=>k.has(x)?!1:(k.add(x),!0));if(!a.writeArticle(c,{...l.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=(l.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 dl(e,o,t){let n=o.trim(),s=e.listArticles(t),i=n.toLowerCase(),r=s.find(l=>l.meta.title.toLowerCase()===i);if(r)return r.path;if(n.includes("/")||n.endsWith(".md")){let l=n.endsWith(".md")?n:`${n}.md`,g=s.find(d=>d.path===l||d.path===n);if(g)return g.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(l=>{let g=l.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return g===a||g.includes(a)||l.path.toLowerCase().includes(a)});return c?c.path:null}function mu(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(`
416
+ `)}function pu(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
417
417
 
418
418
  ${t}
419
419
 
@@ -426,8 +426,8 @@ Incorporate it into the most relevant existing section, or create a short new se
426
426
  ${t}
427
427
 
428
428
  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(`
429
- `)}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?W(e.dir):W(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,l=0,g=0;for(let d of t){let u=W(s,"agents",d);if(!Je(u))continue;let f=W(u,i),p=r.map(b=>({mode:b,dir:W(u,b)})).filter(b=>Je(b.dir));if(p.length===0)continue;let w=new Map;hi(f,b=>{let S=nl(f,b);if(S.startsWith("_")||S.startsWith("raw/")||S.includes("_tmp/"))return;let A=il(on(b,"utf-8"));A?.meta.title&&w.set(A.meta.title.trim().toLowerCase(),{relPath:S,type:A.meta.type,lastUpdated:A.meta.lastUpdated||""})});let y=[];for(let b of p)hi(b.dir,S=>{let A=nl(b.dir,S);if(A.startsWith("_")||A.startsWith("raw/")||A.includes("_tmp/"))return;let x=il(on(S,"utf-8"));x?.meta.title&&y.push({mode:b.mode,relPath:A,absPath:S,title:x.meta.title.trim(),type:x.meta.type,lastUpdated:x.meta.lastUpdated||""})});if(a+=y.length,y.length===0)continue;console.log();let k=p.map(b=>b.mode).join("+");console.log(m.bold(` ${m.cyan(d)}: ${y.length} legacy article(s) across ${k}`));for(let b of y){let S=b.title.toLowerCase(),A=w.get(S),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 v=b.type?m.magenta(`[${b.type}]`):m.yellow("[untyped]"),$=x==="promote"?m.green("\u2192 promote "):x==="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}`),x==="upgrade"&&console.log(m.dim(` (replaces ${A.relPath}, old version kept under _versions/)`)),!n){x==="promote"?c++:x==="upgrade"?l++:g++;continue}try{if(x==="promote"){let j=W(f,b.relPath);Je(j)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${b.relPath}`)),rl(u,b),g++):(mo(sl(j),{recursive:!0}),Qn(b.absPath,j),w.set(S,{relPath:b.relPath,type:b.type,lastUpdated:b.lastUpdated}),c++)}else if(x==="upgrade"){let j=W(f,A.relPath);if(Je(j)){let T=W(u,"_versions",A.relPath.replace(/\.md$/,""));mo(T,{recursive:!0});let D=new Date().toISOString().replace(/[:.]/g,"-");Qn(j,W(T,`${D}.md`))}mo(sl(j),{recursive:!0}),Qn(b.absPath,j),w.set(S,{relPath:A.relPath,type:b.type,lastUpdated:b.lastUpdated}),l++}else rl(u,b),g++}catch(j){console.log(m.red(` ! ${x} failed: ${j.message?.slice(0,120)}`))}}if(n){for(let b of p)try{au(b.dir,{recursive:!0,force:!0})}catch{}try{o.getAgentWiki(d).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: ${l} \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 ${l} \xB7 archive ${g}`)),console.log(m.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function hi(e,o){if(Je(e))for(let t of ru(e,{withFileTypes:!0})){let n=W(e,t.name);t.isDirectory()?hi(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function il(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
430
- `)){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 rl(e,o){let t=W(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));mo(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");Qn(o.absPath,W(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 l of t){let g=o.getAgentWiki(l),d=g.listArticles(l),u=d.filter(k=>!k.meta.type);if(r+=d.length,a+=u.length,u.length===0){console.log(` ${m.cyan(l)}: ${m.green("all typed")} (${d.length} articles)`);continue}let f=Math.max(0,s-c),p=Math.min(u.length,f);if(p===0){console.log(m.dim(` ${l}: skipped (--max reached)`));continue}console.log(),console.log(m.bold(` ${m.cyan(l)}: ${p}/${u.length} untyped articles`));let w=g.baseDir,y=W(w,"_tmp");mo(y,{recursive:!0});for(let k=0;k<p;k+=n){let b=u.slice(k,Math.min(k+n,p)),S=mu(b),A=W(y,"migrate-prompt.txt");zo(A,S);let x;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"`,$=Ho(v,{env:Qo({...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");x=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 $=x.find(M=>M.path===v.path),C=gu($?.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":""}`):"",B=C.alias?m.dim(` (from "${C.alias}")`):"";console.log(` ${m.green("+")} ${m.magenta("["+C.type+"]")}${B} ${v.path}${D}`),i&&(g.writeArticle(v.path,T,v.content,l),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 gu(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 mu(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}"
429
+ `)}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=xe(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=!!e.commit,s=e.dir?W(e.dir):W(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,l=0,g=0;for(let d of t){let u=W(s,"agents",d);if(!Je(u))continue;let f=W(u,i),p=r.map(b=>({mode:b,dir:W(u,b)})).filter(b=>Je(b.dir));if(p.length===0)continue;let w=new Map;wi(f,b=>{let S=rl(f,b);if(S.startsWith("_")||S.startsWith("raw/")||S.includes("_tmp/"))return;let A=cl(tn(b,"utf-8"));A?.meta.title&&w.set(A.meta.title.trim().toLowerCase(),{relPath:S,type:A.meta.type,lastUpdated:A.meta.lastUpdated||""})});let y=[];for(let b of p)wi(b.dir,S=>{let A=rl(b.dir,S);if(A.startsWith("_")||A.startsWith("raw/")||A.includes("_tmp/"))return;let x=cl(tn(S,"utf-8"));x?.meta.title&&y.push({mode:b.mode,relPath:A,absPath:S,title:x.meta.title.trim(),type:x.meta.type,lastUpdated:x.meta.lastUpdated||""})});if(a+=y.length,y.length===0)continue;console.log();let k=p.map(b=>b.mode).join("+");console.log(m.bold(` ${m.cyan(d)}: ${y.length} legacy article(s) across ${k}`));for(let b of y){let S=b.title.toLowerCase(),A=w.get(S),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 v=b.type?m.magenta(`[${b.type}]`):m.yellow("[untyped]"),$=x==="promote"?m.green("\u2192 promote "):x==="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}`),x==="upgrade"&&console.log(m.dim(` (replaces ${A.relPath}, old version kept under _versions/)`)),!n){x==="promote"?c++:x==="upgrade"?l++:g++;continue}try{if(x==="promote"){let I=W(f,b.relPath);Je(I)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${b.relPath}`)),ll(u,b),g++):(mo(al(I),{recursive:!0}),Zn(b.absPath,I),w.set(S,{relPath:b.relPath,type:b.type,lastUpdated:b.lastUpdated}),c++)}else if(x==="upgrade"){let I=W(f,A.relPath);if(Je(I)){let T=W(u,"_versions",A.relPath.replace(/\.md$/,""));mo(T,{recursive:!0});let D=new Date().toISOString().replace(/[:.]/g,"-");Zn(I,W(T,`${D}.md`))}mo(al(I),{recursive:!0}),Zn(b.absPath,I),w.set(S,{relPath:A.relPath,type:b.type,lastUpdated:b.lastUpdated}),l++}else ll(u,b),g++}catch(I){console.log(m.red(` ! ${x} failed: ${I.message?.slice(0,120)}`))}}if(n){for(let b of p)try{du(b.dir,{recursive:!0,force:!0})}catch{}try{o.getAgentWiki(d).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: ${l} \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 ${l} \xB7 archive ${g}`)),console.log(m.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function wi(e,o){if(Je(e))for(let t of lu(e,{withFileTypes:!0})){let n=W(e,t.name);t.isDirectory()?wi(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function cl(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
430
+ `)){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 ll(e,o){let t=W(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));mo(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");Zn(o.absPath,W(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=xe(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 l of t){let g=o.getAgentWiki(l),d=g.listArticles(l),u=d.filter(k=>!k.meta.type);if(r+=d.length,a+=u.length,u.length===0){console.log(` ${m.cyan(l)}: ${m.green("all typed")} (${d.length} articles)`);continue}let f=Math.max(0,s-c),p=Math.min(u.length,f);if(p===0){console.log(m.dim(` ${l}: skipped (--max reached)`));continue}console.log(),console.log(m.bold(` ${m.cyan(l)}: ${p}/${u.length} untyped articles`));let w=g.baseDir,y=W(w,"_tmp");mo(y,{recursive:!0});for(let k=0;k<p;k+=n){let b=u.slice(k,Math.min(k+n,p)),S=fu(b),A=W(y,"migrate-prompt.txt");Yo(A,S);let x;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"`,$=zo(v,{env:Qo({...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");x=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 $=x.find(M=>M.path===v.path),C=uu($?.type);if(!$||!C){console.log(m.yellow(` ? ${v.path}: unclassified${$?` (got "${$.type}")`:""}`));continue}let I=g.extractWikilinks(v.content),T={...v.meta,type:C.type,related:I.length?I:void 0,lastUpdated:new Date().toISOString().slice(0,10)},D=I.length?m.dim(` \u2192 ${I.slice(0,3).join(", ")}${I.length>3?", \u2026":""}`):"",B=C.alias?m.dim(` (from "${C.alias}")`):"";console.log(` ${m.green("+")} ${m.magenta("["+C.type+"]")}${B} ${v.path}${D}`),i&&(g.writeArticle(v.path,T,v.content,l),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 uu(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 fu(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}"
431
431
  title: "${t.meta.title}"
432
432
  tags: [${i}]
433
433
  body: ${s}${t.content.length>400?"\u2026":""}`}).join(`
@@ -467,48 +467,48 @@ Output (JSON array, one entry per input article, same order):
467
467
  [
468
468
  {"path": "path/to/article.md", "type": "project"},
469
469
  ...
470
- ]`}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||W(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-5V444ZFW.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(),fa(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-3WT3VJC2.js"),c=ve(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),u=[];e:for(let y of l){let k=c.getAgentWiki(y);for(let b of k.listArticles(y)){if(u.length>=g)break e;let S=k.readArticle(b.path);if(!S||e.type&&S.meta.type!==e.type)continue;let A={...o(S.meta.type),...e.fields?i(S.meta.type):{}},x=await a(s,t({path:b.path,title:S.meta.title,type:S.meta.type,tags:S.meta.tags,body:S.content}),A,{links:[{kind:"article",id:b.path}],features:{agent:y,type:S.meta.type??"?"}});if(!x){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let v=n(x.answers),$=e.fields?r(S.meta.type,x.answers):null;v.completeness>=d&&!($&&!$.fit)||u.push({agent:y,type:S.meta.type??"?",score:v.completeness.toFixed(2),standsAlone:v.standsAlone.toFixed(2),gap:v.biggestGap,...$?{missing:$.missingCritical.join(",")||"-",cov:`${Math.round($.coverage*100)}%`}:{},title:S.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(" no articles below the threshold"));return}u.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"],p=f.map(y=>Math.max(y.length,...u.map(k=>String(k[y]).length))),w=y=>y.map((k,b)=>String(k).padEnd(p[b])).join(" ");console.log(),console.log(m.bold(w(f)));for(let y of u)console.log(w(f.map(k=>y[k])));if(e.fields){let y=u.filter(k=>k.missing!=="-").length;console.log(m.dim(`
470
+ ]`}ee.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=xe(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||W(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-5V444ZFW.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(),wa(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-3WT3VJC2.js"),c=xe(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),u=[];e:for(let y of l){let k=c.getAgentWiki(y);for(let b of k.listArticles(y)){if(u.length>=g)break e;let S=k.readArticle(b.path);if(!S||e.type&&S.meta.type!==e.type)continue;let A={...o(S.meta.type),...e.fields?i(S.meta.type):{}},x=await a(s,t({path:b.path,title:S.meta.title,type:S.meta.type,tags:S.meta.tags,body:S.content}),A,{links:[{kind:"article",id:b.path}],features:{agent:y,type:S.meta.type??"?"}});if(!x){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let v=n(x.answers),$=e.fields?r(S.meta.type,x.answers):null;v.completeness>=d&&!($&&!$.fit)||u.push({agent:y,type:S.meta.type??"?",score:v.completeness.toFixed(2),standsAlone:v.standsAlone.toFixed(2),gap:v.biggestGap,...$?{missing:$.missingCritical.join(",")||"-",cov:`${Math.round($.coverage*100)}%`}:{},title:S.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(" no articles below the threshold"));return}u.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"],p=f.map(y=>Math.max(y.length,...u.map(k=>String(k[y]).length))),w=y=>y.map((k,b)=>String(k).padEnd(p[b])).join(" ");console.log(),console.log(m.bold(w(f)));for(let y of u)console.log(w(f.map(k=>y[k])));if(e.fields){let y=u.filter(k=>k.missing!=="-").length;console.log(m.dim(`
471
471
  ${u.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(`
472
- ${u.length} article(s) below ${d}. 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-6EMTLCHQ.js"),n=ve(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=W(l.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 l=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${l} (${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(l=>!a.candidates.some(g=>g.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.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=W(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 fo({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,u]of Object.entries(i.entries))r.set(d,u.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,l=0,g=0;for(let d of t){let u=o.getAgentWiki(d),f=u.listArticles(d),p=o.getSharedStore().listEntries(),w=new Map(p.map(S=>[S.id,S])),y=0,k=0,b=0;for(let S of f){if(a++,S.meta.graphPath?.length||!S.meta.sources?.length)continue;y++,c++;let A=new Map;for(let v of S.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("/"),B=A.get(D);B?B.n++:A.set(D,{path:T,n:1})}if(A.size===0)continue;k++,l++;let x;for(let v of A.values())(!x||v.n>x.n)&&(x=v);x&&(e.dryRun||(u.writeArticle(S.path,{...S.meta,graphPath:x.path},S.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${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, ${l} matched (${Math.round(l/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-5V444ZFW.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(),l=c.entries||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${l.length} entries`));let d=0;for(let u of l)s.has(u.id)||(e.dryRun||(t.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${g}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),d++);d>0?console.log(m.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=d;try{let u=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(u.ok){let f=await u.json();for(let p of f.agents||[])p.totalEntries>0&&console.log(m.dim(` ${p.agentId}: ${p.totalEntries} entries, ${p.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||W(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let l=new hs(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),u=l.getAgentEntries(t),f=l.getUnabsorbedEntries(t),p=new Set,w=0,y=new Set;for(let b of d.articles){for(let S of b.tags||[])p.add(S);w+=b.tags?.length||0;for(let S of b.sources||[])y.add(S)}let k=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:yi(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(w/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:y.size,articleList:d.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,l]of r){let g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(u=>u[c])),d=s.filter(u=>u[c]===g).map(u=>u.label);g>0&&console.log(m.dim(` Best ${l}: ${d.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?W(process.cwd(),o.dir):W(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?W(process.cwd(),e):W(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=W(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"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:g}=await import("fs"),d=Je(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${pu(d)})`)),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-3WT3VJC2.js"),{QuestionStore:c}=await import("./questions-4B4KSPXG.js"),l=ve(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let v of d){let $=l.getAgentWiki(v);for(let C of $.listArticles(v)){if(f>=u)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 B of s(D,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:v,path:C.path,subject:j.meta.title,field:B.field,tier:B.tier,question:`${j.meta.title} (${j.meta.type??"?"}) \u2014 ${B.label}?`}),p.push({tier:B.tier,need:B.field,how:B.needsHuman?m.yellow("ask"):B.sources.join("/"),uncertain:B.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(tn(e.dir)).add(g)),e.json){console.log(JSON.stringify(p,null,2));return}if(p.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,...p.map($=>k($[v]).length))),S=(v,$)=>String(v)+" ".repeat(Math.max(0,b[$]-k(v).length));console.log(),console.log(m.bold(y.map((v,$)=>S(v,$)).join(" ")));for(let v of p)console.log(y.map(($,C)=>S(v[$],C)).join(" "));let A=p.filter(v=>v.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${p.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${A} can be closed by a lookup; ${p.length-A} need a person.`));let x=p[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: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-5V444ZFW.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 B=C.slice(0,10).map(J=>`\u2022 ${J.question}`).join(`
472
+ ${u.length} article(s) below ${d}. 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-6EMTLCHQ.js"),n=xe(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=W(l.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 l=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${l} (${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(l=>!a.candidates.some(g=>g.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.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=xe(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=xe(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=W(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 fo({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,u]of Object.entries(i.entries))r.set(d,u.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,l=0,g=0;for(let d of t){let u=o.getAgentWiki(d),f=u.listArticles(d),p=o.getSharedStore().listEntries(),w=new Map(p.map(S=>[S.id,S])),y=0,k=0,b=0;for(let S of f){if(a++,S.meta.graphPath?.length||!S.meta.sources?.length)continue;y++,c++;let A=new Map;for(let v of S.meta.sources){let $=w.get(v);if(!$)continue;let C=String($.meta?.sender??""),I=s.fingerprint({text:$.content,channel:$.source,sender:C}),T=r.get(I);if(!T?.length)continue;let D=T.join("/"),B=A.get(D);B?B.n++:A.set(D,{path:T,n:1})}if(A.size===0)continue;k++,l++;let x;for(let v of A.values())(!x||v.n>x.n)&&(x=v);x&&(e.dryRun||(u.writeArticle(S.path,{...S.meta,graphPath:x.path},S.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${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, ${l} matched (${Math.round(l/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=xe(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-5V444ZFW.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(),l=c.entries||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${l.length} entries`));let d=0;for(let u of l)s.has(u.id)||(e.dryRun||(t.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${g}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),d++);d>0?console.log(m.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=d;try{let u=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(u.ok){let f=await u.json();for(let p of f.agents||[])p.totalEntries>0&&console.log(m.dim(` ${p.agentId}: ${p.totalEntries} entries, ${p.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||W(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let l=new ws(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),u=l.getAgentEntries(t),f=l.getUnabsorbedEntries(t),p=new Set,w=0,y=new Set;for(let b of d.articles){for(let S of b.tags||[])p.add(S);w+=b.tags?.length||0;for(let S of b.sources||[])y.add(S)}let k=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:bi(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(w/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:y.size,articleList:d.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,l]of r){let g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(u=>u[c])),d=s.filter(u=>u[c]===g).map(u=>u.label);g>0&&console.log(m.dim(` Best ${l}: ${d.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?W(process.cwd(),o.dir):W(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?W(process.cwd(),e):W(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=W(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"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:g}=await import("fs"),d=Je(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${hu(d)})`)),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-3WT3VJC2.js"),{QuestionStore:c}=await import("./questions-4B4KSPXG.js"),l=xe(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let v of d){let $=l.getAgentWiki(v);for(let C of $.listArticles(v)){if(f>=u)break e;let I=$.readArticle(C.path);if(!I||e.type&&I.meta.type!==e.type)continue;f++;let T=await a(r,n({title:I.meta.title,type:I.meta.type,body:I.content}),o(I.meta.type),{links:[{kind:"article",id:C.path}],features:{agent:v,type:I.meta.type??"?"}});if(!T){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let D=t(I.meta.type,T.answers);for(let B of s(D,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:v,path:C.path,subject:I.meta.title,field:B.field,tier:B.tier,question:`${I.meta.title} (${I.meta.type??"?"}) \u2014 ${B.label}?`}),p.push({tier:B.tier,need:B.field,how:B.needsHuman?m.yellow("ask"):B.sources.join("/"),uncertain:B.uncertain?"?":"",agent:v,article:I.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&g.length>0&&(w=new c(nn(e.dir)).add(g)),e.json){console.log(JSON.stringify(p,null,2));return}if(p.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,...p.map($=>k($[v]).length))),S=(v,$)=>String(v)+" ".repeat(Math.max(0,b[$]-k(v).length));console.log(),console.log(m.bold(y.map((v,$)=>S(v,$)).join(" ")));for(let v of p)console.log(y.map(($,C)=>S(v[$],C)).join(" "));let A=p.filter(v=>v.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${p.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${A} can be closed by a lookup; ${p.length-A} need a person.`));let x=p[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:v}=await import("./article-fields-L4D2BOGY.js"),$=v[e.notifyTier]??v.pillar,C=g.filter(I=>(v[I.tier??"furniture"]??9)<=$);if(C.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:I}=await import("./config-5V444ZFW.js"),T=I(),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 B=C.slice(0,10).map(J=>`\u2022 ${J.question}`).join(`
473
473
  `),M=C.length>10?`
474
474
  \u2026and ${C.length-10} more`:"",H=`${C.length} wiki gap(s) need you (${e.notifyTier}+):
475
475
  ${B}${M}
476
476
 
477
- agentx wiki questions`,ce=T?.daemon?.port??T?.port??18800;try{let J=await fetch(`http://127.0.0.1:${ce}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:D.channel,chatId:D.chatId,accountId:D.accountId,text:H})});console.log(J.ok?m.cyan(` Pushed ${C.length} question(s) to ${D.channel}.`):m.yellow(` Push failed (${J.status}) \u2014 questions are still queued.`))}catch(J){console.log(m.yellow(` Push failed (${String(J?.message??J).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-3WT3VJC2.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-YVEJOM7O.js"),{backfillArticle:u}=await import("./backfill-MTD2B62I.js"),f=ve(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(T=>[T.name.toLowerCase().trim(),T])),S=0,A=0,x=[],v=!1;e:for(let T of p){let D=f.getAgentWiki(T);for(let B of D.listArticles(T)){if(S>=w)break e;if(B.meta.type!=="person")continue;let M=D.readArticle(B.path);if(!M)continue;S++;let H=await r(s,n({title:M.meta.title,type:M.meta.type,body:M.content}),o(M.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:T,op:"backfill"}});if(!H){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=t(M.meta.type,H.answers).missing.filter(N=>i.includes(N));if(J.length===0)continue;let{records:xe,results:we}=await a([{name:M.meta.title,type:"person"}],{sources:y}),P=b.get(M.meta.title.toLowerCase().trim());if(!v){for(let N of l(we,y))console.log(m.yellow(` ! ${N.source} ${N.kind} \u2014 would supply ${N.provides.join(", ")}`)),console.log(m.dim(` ${N.hint}`));v=!0}let Be=c([...P?[{name:P.name,source:"entries",fields:Object.fromEntries(Object.entries(P.fields).map(([N,pe])=>[N,pe.value]))}]:[],...xe]);if(Be.length===0)continue;let{content:be,edits:No}=u(M.content,Be[0],J);if(No.length!==0){for(let N of No)x.push({agent:T,article:M.meta.title.slice(0,32),field:N.field,action:N.replaced?"replace":"add",got:`${N.value.split(";").length} value(s)`});e.apply&&(D.writeArticle(B.path,M.meta,be,T)?A++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(x,null,2));return}if(x.length===0){console.log(m.green(` ${S} person article(s) considered \u2014 nothing to backfill`));return}let $=["agent","article","field","action","got"],C=$.map(T=>Math.max(T.length,...x.map(D=>String(D[T]).length))),j=T=>T.map((D,B)=>String(D).padEnd(C[B])).join(" ");console.log(),console.log(m.bold(j($)));for(let T of x)console.log(j($.map(D=>T[D])));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 ${S} 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(tn(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(tn(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 l=ve(t.dir,t.mode).getAgentWiki(a.agentId),g=l.readArticle(a.path);if(!g){console.log(m.yellow(` article gone: ${a.path}`));return}let d=s(g.content,a.field,`${o} (answered by operator)`);if(!d){console.log(m.dim(" already present \u2014 nothing to write."));return}let u=l.writeArticle(a.path,g.meta,d.content,a.agentId);console.log(u?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-3WT3VJC2.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-JNO7RKX7.js"),{calibrationReport:d}=await import("./calibration-ILS5OI44.js"),f=ve(e.dir,"graph").getSharedStore(),p=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(M=>M.id)),{labeled:y,backlog:k}=r(p,w),b=a(y,M=>M.absorbed,parseInt(e.n)),S={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,v=Date.now();if(e.load){let{readFileSync:M}=await import("fs");A.push(...JSON.parse(M(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 M of e.load?[]:b){let H=await i(o,n(M),t,{features:{source:M.source??"",absorbed:M.absorbed}});if(!H){x++;continue}let ce=H.answers;A.push({entry:M,verdict:s(H.answers,S),citeWorthy:ce.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:M}=await import("fs");M(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let $=c(A,{minType:S.minTypeConfidence,minWorth:S.minWorth,minDurability:S.minDurability}),C=l(A,"seat","seat"),j=d(C,{minN:50}),T=((Date.now()-v)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:$,calibration:j,failures:x,elapsed:T},null,2));return}let D=M=>`${(M*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 M=$.droppedBy;console.log(m.dim(` dropped by: type ${M.type} \xB7 worth ${M.worth} \xB7 durability ${M.durability} (a positive can fail several)`))}let B=$.positiveMeans;if(console.log(m.dim(` positives avg: worth ${B.worth.toFixed(2)} \xB7 durability ${B.durability.toFixed(2)} \xB7 typeConf ${B.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${T}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 M=parseFloat(e.minRecall),{best:H,points:ce}=g(A,{minRecall:M});if(console.log(),console.log(m.bold(` threshold sweep (${ce.length} policies, recall floor ${D(M)})`)),H)console.log(` best: ${H.requireTyped?`typed & type>=${H.minType}`:"type gate OFF"} worth>=${H.minWorth} durability>=${H.minDurability}`),console.log(` recall ${D(H.recall)} \xB7 filtered ${D(H.filtered)} \xB7 precision ${D(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 ${D(M)} recall \u2014 not even keeping everything typed.`));let J=ce.slice().sort((xe,we)=>we.recall-xe.recall)[0];J&&console.log(m.dim(` Best recall available: ${D(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${D(J.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=W(process.cwd(),e);Je(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?W(process.cwd(),o.dir):W(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=W(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 pu(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"}nd();import{Command as uu}from"commander";import R from"chalk";import{resolve as Zn}from"path";import{existsSync as fu}from"fs";ge();var $t=new uu().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");$t.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 fo({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 l=0,g=0,d=0,u=0;for(let p=0;p<r.length;p++){let w=r[p],y=pn(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${R.cyan(w.msgHash.slice(0,8))} ${R.dim(y)} ... `);let k=hu(w,a,c),b=null;try{b=await yu(n,t,k,o.dashboard?.token)}catch(x){u++,console.log(R.red(`ERR ${x.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(R.red("ERR no decision"));continue}let S=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(S==="approve")if(console.log(R.green("APPROVE")+" "+R.dim(A)),e.dryRun)l++;else try{wu(i,w,a,c,t),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:t,reviewReason:A}),l++}catch(x){console.log(R.yellow(` (commit failed, staying pending: ${x.message?.slice(0,100)})`)),u++}else S==="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||S)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(R.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${u} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(R.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});$t.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(!fu(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 fo({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()});$t.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 fo({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 l,g,d;try{let $=await fetch(`${t}/graph/schema`,{headers:s});if(!$.ok)throw new Error(`schema HTTP ${$.status}`);l=(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}`);d=(await T.json()).classifications||[]}catch($){console.log(R.red(` fetch failed: ${$.message}`));return}let u=r.levels.map($=>$.id).join(","),f=l?.levels?.map($=>$.id).join(","),p=u===f;p?console.log(R.dim(` schema matches (${r.levels.length} levels)`)):(console.log(R.yellow(" \u26A0 schema levels differ:")),console.log(R.dim(` local: ${u}`)),console.log(R.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(R.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(R.yellow(" keeping local schema; node import may fail if levels disagree")));let w=p?r:l,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,S=0,A=0;for(let $ of k){if(c.has($.id)){S++;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 ${S} already-present \xB7 ${A} failed`));let x=0,v=0;for(let $ of d)if(!(!$.msgHash||!Array.isArray($.path))){if(i.getFingerprint($.msgHash)){v++;continue}if(e.dryRun){x++;continue}i.setFingerprint($.msgHash,{path:$.path,leaf:$.leaf||{}}),x++}console.log(R.dim(` fingerprints: +${x} 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 hu(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(`
477
+ agentx wiki questions`,le=T?.daemon?.port??T?.port??18800;try{let J=await fetch(`http://127.0.0.1:${le}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:D.channel,chatId:D.chatId,accountId:D.accountId,text:H})});console.log(J.ok?m.cyan(` Pushed ${C.length} question(s) to ${D.channel}.`):m.yellow(` Push failed (${J.status}) \u2014 questions are still queued.`))}catch(J){console.log(m.yellow(` Push failed (${String(J?.message??J).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-3WT3VJC2.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-YVEJOM7O.js"),{backfillArticle:u}=await import("./backfill-MTD2B62I.js"),f=xe(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(T=>[T.name.toLowerCase().trim(),T])),S=0,A=0,x=[],v=!1;e:for(let T of p){let D=f.getAgentWiki(T);for(let B of D.listArticles(T)){if(S>=w)break e;if(B.meta.type!=="person")continue;let M=D.readArticle(B.path);if(!M)continue;S++;let H=await r(s,n({title:M.meta.title,type:M.meta.type,body:M.content}),o(M.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:T,op:"backfill"}});if(!H){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=t(M.meta.type,H.answers).missing.filter(N=>i.includes(N));if(J.length===0)continue;let{records:Se,results:be}=await a([{name:M.meta.title,type:"person"}],{sources:y}),P=b.get(M.meta.title.toLowerCase().trim());if(!v){for(let N of l(be,y))console.log(m.yellow(` ! ${N.source} ${N.kind} \u2014 would supply ${N.provides.join(", ")}`)),console.log(m.dim(` ${N.hint}`));v=!0}let Be=c([...P?[{name:P.name,source:"entries",fields:Object.fromEntries(Object.entries(P.fields).map(([N,ue])=>[N,ue.value]))}]:[],...Se]);if(Be.length===0)continue;let{content:$e,edits:Ro}=u(M.content,Be[0],J);if(Ro.length!==0){for(let N of Ro)x.push({agent:T,article:M.meta.title.slice(0,32),field:N.field,action:N.replaced?"replace":"add",got:`${N.value.split(";").length} value(s)`});e.apply&&(D.writeArticle(B.path,M.meta,$e,T)?A++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(x,null,2));return}if(x.length===0){console.log(m.green(` ${S} person article(s) considered \u2014 nothing to backfill`));return}let $=["agent","article","field","action","got"],C=$.map(T=>Math.max(T.length,...x.map(D=>String(D[T]).length))),I=T=>T.map((D,B)=>String(D).padEnd(C[B])).join(" ");console.log(),console.log(m.bold(I($)));for(let T of x)console.log(I($.map(D=>T[D])));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 ${S} 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(nn(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(nn(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 l=xe(t.dir,t.mode).getAgentWiki(a.agentId),g=l.readArticle(a.path);if(!g){console.log(m.yellow(` article gone: ${a.path}`));return}let d=s(g.content,a.field,`${o} (answered by operator)`);if(!d){console.log(m.dim(" already present \u2014 nothing to write."));return}let u=l.writeArticle(a.path,g.meta,d.content,a.agentId);console.log(u?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-3WT3VJC2.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-JNO7RKX7.js"),{calibrationReport:d}=await import("./calibration-ILS5OI44.js"),f=xe(e.dir,"graph").getSharedStore(),p=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(M=>M.id)),{labeled:y,backlog:k}=r(p,w),b=a(y,M=>M.absorbed,parseInt(e.n)),S={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,v=Date.now();if(e.load){let{readFileSync:M}=await import("fs");A.push(...JSON.parse(M(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 M of e.load?[]:b){let H=await i(o,n(M),t,{features:{source:M.source??"",absorbed:M.absorbed}});if(!H){x++;continue}let le=H.answers;A.push({entry:M,verdict:s(H.answers,S),citeWorthy:le.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:M}=await import("fs");M(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let $=c(A,{minType:S.minTypeConfidence,minWorth:S.minWorth,minDurability:S.minDurability}),C=l(A,"seat","seat"),I=d(C,{minN:50}),T=((Date.now()-v)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:$,calibration:I,failures:x,elapsed:T},null,2));return}let D=M=>`${(M*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 I)||!I.insufficient)&&console.log(` ECE ${I.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),$.lostPositives>0){let M=$.droppedBy;console.log(m.dim(` dropped by: type ${M.type} \xB7 worth ${M.worth} \xB7 durability ${M.durability} (a positive can fail several)`))}let B=$.positiveMeans;if(console.log(m.dim(` positives avg: worth ${B.worth.toFixed(2)} \xB7 durability ${B.durability.toFixed(2)} \xB7 typeConf ${B.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${T}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 M=parseFloat(e.minRecall),{best:H,points:le}=g(A,{minRecall:M});if(console.log(),console.log(m.bold(` threshold sweep (${le.length} policies, recall floor ${D(M)})`)),H)console.log(` best: ${H.requireTyped?`typed & type>=${H.minType}`:"type gate OFF"} worth>=${H.minWorth} durability>=${H.minDurability}`),console.log(` recall ${D(H.recall)} \xB7 filtered ${D(H.filtered)} \xB7 precision ${D(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 ${D(M)} recall \u2014 not even keeping everything typed.`));let J=le.slice().sort((Se,be)=>be.recall-Se.recall)[0];J&&console.log(m.dim(` Best recall available: ${D(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${D(J.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=W(process.cwd(),e);Je(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?W(process.cwd(),o.dir):W(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=W(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 hu(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"}rd();import{Command as yu}from"commander";import R from"chalk";import{resolve as es}from"path";import{existsSync as wu}from"fs";me();var $t=new yu().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");$t.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 fo({baseDir:es(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 l=0,g=0,d=0,u=0;for(let p=0;p<r.length;p++){let w=r[p],y=un(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${R.cyan(w.msgHash.slice(0,8))} ${R.dim(y)} ... `);let k=bu(w,a,c),b=null;try{b=await $u(n,t,k,o.dashboard?.token)}catch(x){u++,console.log(R.red(`ERR ${x.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(R.red("ERR no decision"));continue}let S=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(S==="approve")if(console.log(R.green("APPROVE")+" "+R.dim(A)),e.dryRun)l++;else try{ku(i,w,a,c,t),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:t,reviewReason:A}),l++}catch(x){console.log(R.yellow(` (commit failed, staying pending: ${x.message?.slice(0,100)})`)),u++}else S==="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||S)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(R.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${u} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(R.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});$t.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=es(process.cwd(),o.graph.baseDir);if(!wu(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 fo({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()});$t.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 fo({baseDir:es(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 l,g,d;try{let $=await fetch(`${t}/graph/schema`,{headers:s});if(!$.ok)throw new Error(`schema HTTP ${$.status}`);l=(await $.json()).schema;let I=await fetch(`${t}/graph/nodes`,{headers:s});if(!I.ok)throw new Error(`nodes HTTP ${I.status}`);g=(await I.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}`);d=(await T.json()).classifications||[]}catch($){console.log(R.red(` fetch failed: ${$.message}`));return}let u=r.levels.map($=>$.id).join(","),f=l?.levels?.map($=>$.id).join(","),p=u===f;p?console.log(R.dim(` schema matches (${r.levels.length} levels)`)):(console.log(R.yellow(" \u26A0 schema levels differ:")),console.log(R.dim(` local: ${u}`)),console.log(R.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(R.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(R.yellow(" keeping local schema; node import may fail if levels disagree")));let w=p?r:l,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,S=0,A=0;for(let $ of k){if(c.has($.id)){S++;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 ${S} already-present \xB7 ${A} failed`));let x=0,v=0;for(let $ of d)if(!(!$.msgHash||!Array.isArray($.path))){if(i.getFingerprint($.msgHash)){v++;continue}if(e.dryRun){x++;continue}i.setFingerprint($.msgHash,{path:$.path,leaf:$.leaf||{}}),x++}console.log(R.dim(` fingerprints: +${x} 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 bu(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(`
478
478
  `),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(`
479
- `)}async function yu(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 Hi((c?.content||"").toString())}finally{clearTimeout(r)}}function wu(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function wi(){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 fo({baseDir:o}),baseDir:o}}var bi=$t.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");bi.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=wi();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 l=typeof c.confidence=="number"?c.confidence.toFixed(2):R.dim("cache");console.log(` ${R.cyan(c.msgHash.slice(0,8))} ${l.padStart(5)} ${R.bold(pn(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]"))});bi.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=wi();if(!n)return;let{ReviewStore:s}=await import("./review-store-B4YE3EFK.js"),r=n.store.listAllClassifications().filter(l=>l.msgHash===e||l.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}: ${pn(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(R.dim(` should have been: ${t.path}`))});bi.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=wi();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 l=Math.abs(parseFloat(c.bin.split("-")[0])+.05-c.accuracy),g=c.n>=5&&l>.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 Su}from"commander";import Y from"chalk";import{Command as ll}from"commander";import ie from"chalk";import{existsSync as bu}from"fs";import{resolve as $u}from"path";import ku from"better-sqlite3";function vu(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(ie.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function xu(e){let o=$u(process.cwd(),e);return bu(o)||(console.log(ie.red(` No db at ${o}`)),process.exit(1)),new ku(o,{readonly:!0})}var dl=new ll().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(Rt)).option("--max <n>","max clusters distilled per run",String(hn)).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(ie.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=xu(e.path),t=await Tr(o,{since:vu(e.since),agentId:e.agent,sessions:new er(process.cwd()),minOccurrences:Number(e.minOccurrences)||Rt,max:Number(e.max)||hn,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(ie.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(` ${ie.cyan(n.key)} ${ie.bold(`\xD7${n.count}`)} ${ie.dim(n.status)}`),n.sampleMessage&&console.log(ie.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(ie.dim(`
480
- near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(ie.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(ie.green(` \u2713 draft written: ${n.id}`)+ie.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(ie.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(ie.yellow(` \u26A0 ${n}`));t.dryRun?console.log(ie.dim(`
481
- dry run only; pass --commit --via <agentId> to write drafts`)):t.drafted.length&&console.log(ie.dim(`
482
- review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),cl={hourly:"0 * * * *",daily:"0 3 * * *"},gl=new ll().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(Rt)).option("--timezone <tz>","IANA timezone (default: this machine's)",Intl.DateTimeFormat().resolvedOptions().timeZone).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?cl.hourly:e.daily?cl.daily:void 0);!e.off&&!o&&!e.onTask&&(console.log(ie.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(ie.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let t=Number(e.minOccurrences)||Rt,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 ${hn} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
483
- `),i=await ue(a=>{Se(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&Se(a,"crons.procedure-extract.enabled",!1):o&&Se(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(ie.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(ie.green(` \u2713 ${r} procedure extraction: off`)):(console.log(ie.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(ie.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(ie.dim(" on-task counting: enabled")),console.log(ie.dim(` threshold: ${t} occurrences`))),console.log(ie.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var Qe=new Su().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");Qe.addCommand(dl);Qe.addCommand(gl);Qe.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 ho,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"}.`))});Qe.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 ho,t=e.steps?String(e.steps):`## Steps
479
+ `)}async function $u(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 Vi((c?.content||"").toString())}finally{clearTimeout(r)}}function ku(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function $i(){let e=_();if(!e.graph?.baseDir)return console.log(R.red(" graph.baseDir is not configured")),null;let o=es(process.cwd(),e.graph.baseDir);return{store:new fo({baseDir:o}),baseDir:o}}var ki=$t.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");ki.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=$i();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 l=typeof c.confidence=="number"?c.confidence.toFixed(2):R.dim("cache");console.log(` ${R.cyan(c.msgHash.slice(0,8))} ${l.padStart(5)} ${R.bold(un(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]"))});ki.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=$i();if(!n)return;let{ReviewStore:s}=await import("./review-store-B4YE3EFK.js"),r=n.store.listAllClassifications().filter(l=>l.msgHash===e||l.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}: ${un(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(R.dim(` should have been: ${t.path}`))});ki.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=$i();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 l=Math.abs(parseFloat(c.bin.split("-")[0])+.05-c.accuracy),g=c.n>=5&&l>.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 Ou}from"commander";import Y from"chalk";import{Command as ml}from"commander";import re from"chalk";import{existsSync as vu}from"fs";import{resolve as xu}from"path";import Su from"better-sqlite3";function Eu(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(re.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function Au(e){let o=xu(process.cwd(),e);return vu(o)||(console.log(re.red(` No db at ${o}`)),process.exit(1)),new Su(o,{readonly:!0})}var pl=new ml().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(Dt)).option("--max <n>","max clusters distilled per run",String(yn)).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(re.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=Au(e.path),t=await Cr(o,{since:Eu(e.since),agentId:e.agent,sessions:new nr(process.cwd()),minOccurrences:Number(e.minOccurrences)||Dt,max:Number(e.max)||yn,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(re.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(` ${re.cyan(n.key)} ${re.bold(`\xD7${n.count}`)} ${re.dim(n.status)}`),n.sampleMessage&&console.log(re.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(re.dim(`
480
+ near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(re.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(re.green(` \u2713 draft written: ${n.id}`)+re.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(re.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(re.yellow(` \u26A0 ${n}`));t.dryRun?console.log(re.dim(`
481
+ dry run only; pass --commit --via <agentId> to write drafts`)):t.drafted.length&&console.log(re.dim(`
482
+ review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),gl={hourly:"0 * * * *",daily:"0 3 * * *"},ul=new ml().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(Dt)).option("--timezone <tz>","IANA timezone (default: this machine's)",Intl.DateTimeFormat().resolvedOptions().timeZone).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?gl.hourly:e.daily?gl.daily:void 0);!e.off&&!o&&!e.onTask&&(console.log(re.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(re.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let t=Number(e.minOccurrences)||Dt,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 ${yn} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
483
+ `),i=await fe(a=>{Ee(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&Ee(a,"crons.procedure-extract.enabled",!1):o&&Ee(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(re.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(re.green(` \u2713 ${r} procedure extraction: off`)):(console.log(re.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(re.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(re.dim(" on-task counting: enabled")),console.log(re.dim(` threshold: ${t} occurrences`))),console.log(re.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var Qe=new Ou().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");Qe.addCommand(pl);Qe.addCommand(ul);Qe.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 ho,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"}.`))});Qe.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 ho,t=e.steps?String(e.steps):`## Steps
484
484
 
485
485
  1. (fill in)
486
486
 
487
487
  ## Notes
488
488
 
489
- `;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)}});Qe.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new ho,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()});Qe.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new ho;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)}});Qe.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new ho;try{o.rejectDraft(e),console.log(Y.green(` \u2713 rejected: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Qe.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new ho;try{o.deprecate(e),console.log(Y.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Qe.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 ho,n=gr(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 Ou}from"commander";import E from"chalk";import{resolve as vt,basename as Tu}from"path";import{existsSync as $i,readFileSync as ki,writeFileSync as es}from"fs";import Ev from"better-sqlite3";import{readFileSync as Eu}from"fs";import{resolve as kt,dirname as ml}from"path";import{fileURLToPath as Au}from"url";var nn=[{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 pl(e){let o=ml(Au(import.meta.url)),t=process.argv[1]?ml(process.argv[1]):"",n=[kt(o,`${e}.yaml`),kt(o,"workflows/templates",`${e}.yaml`),kt(o,"..","workflows/templates",`${e}.yaml`),kt(o,"../..","workflows/templates",`${e}.yaml`),t?kt(t,"workflows/templates",`${e}.yaml`):"",t?kt(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return Eu(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
489
+ `;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)}});Qe.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new ho,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()});Qe.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new ho;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)}});Qe.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new ho;try{o.rejectDraft(e),console.log(Y.green(` \u2713 rejected: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Qe.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new ho;try{o.deprecate(e),console.log(Y.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Qe.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 ho,n=ur(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 Iu}from"commander";import E from"chalk";import{resolve as vt,basename as Cu}from"path";import{existsSync as vi,readFileSync as xi,writeFileSync as os}from"fs";import Cv from"better-sqlite3";import{readFileSync as Tu}from"fs";import{resolve as kt,dirname as fl}from"path";import{fileURLToPath as ju}from"url";var sn=[{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 hl(e){let o=fl(ju(import.meta.url)),t=process.argv[1]?fl(process.argv[1]):"",n=[kt(o,`${e}.yaml`),kt(o,"workflows/templates",`${e}.yaml`),kt(o,"..","workflows/templates",`${e}.yaml`),kt(o,"../..","workflows/templates",`${e}.yaml`),t?kt(t,"workflows/templates",`${e}.yaml`):"",t?kt(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return Tu(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
490
490
  ${n.join(`
491
- `)}`)}var qe=new Ou().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");qe.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new Ro().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"}.`))});qe.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 Ro().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(nr(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))});qe.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=vt(process.cwd(),e);$i(i)||(console.log(E.red(` file not found: ${i}`)),process.exit(1));try{let r=ki(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?ot(r,{filePath:e}):JSON.parse(r),l=et.safeParse(c);if(!l.success){console.log(E.red(` \u2717 ${i}`));for(let d of l.error.issues)console.log(` ${d.path.join(".")||"<root>"}: ${d.message}`);process.exit(1)}let g=un(l.data);if(g.length){console.log(E.yellow(` ! ${i} (lint)`));for(let d of g)console.log(` ${d}`);process.exit(1)}console.log(E.green(` \u2713 ${l.data.id} \u2014 valid`))}catch(r){let a=r instanceof fn?r.message:`parse error: ${r?.message??r}`;console.log(E.red(` ${a}`)),process.exit(1)}return}let t=new Ro().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)});qe.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${nn.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");nn.some(a=>a.name===t)||(console.log(E.red(` unknown template "${o.template}"`)),console.log(E.dim(` available: ${nn.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 Ro;!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=pl(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=ot(s,{filePath:`${e}.yaml`}),c=et.safeParse(a);if(!c.success){console.log(E.red(` template "${t}" failed schema validation after substitution:`));for(let l of c.error.issues)console.log(` ${l.path.join(".")||"<root>"}: ${l.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=vt(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=ot(s,{filePath:`${e}.yaml`}),c=et.parse(a);es(r,JSON.stringify(c,null,2)+`
492
- `)}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()});qe.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of nn)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()});qe.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=vt(process.cwd(),e);$i(t)||(console.log(E.red(` file not found: ${t}`)),process.exit(1));let n=ki(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?ot(n,{filePath:e}):JSON.parse(n)}catch(u){let f=u instanceof fn?u.message:`parse error: ${u?.message??u}`;console.log(E.red(` ${f}`)),process.exit(1)}let r=et.safeParse(i);if(!r.success){console.log(E.red(" \u2717 schema:"));for(let u of r.error.issues)console.log(` ${u.path.join(".")||"<root>"}: ${u.message}`);process.exit(1)}let a=un(r.data);if(a.length){console.log(E.red(" \u2717 lint:"));for(let u of a)console.log(` ${u}`);process.exit(1)}let c=new Ro,l=s?Tu(e).match(/\.yml$/i)?"yml":"yaml":"json",g=vt(c.baseDir,`${r.data.id}.${l}`);if(es(g,s?n:JSON.stringify(r.data,null,2)+`
493
- `),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 d=`${String(o.daemon).replace(/\/$/,"")}/reload`;try{let u=await fetch(d,{method:"POST"});u.ok?console.log(E.dim(" \u2713 daemon reloaded")):console.log(E.dim(` daemon /reload returned ${u.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`))}});qe.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 Nt({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"}.`))});qe.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=vt(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&$i(s)){let c=ki(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),g;try{g=l?ot(c,{filePath:e}):JSON.parse(c)}catch(b){let S=b instanceof fn?b.message:`parse error: ${b?.message??b}`;console.log(E.red(` ${S}`)),process.exit(1)}let d=et.safeParse(g);if(!d.success){console.log(E.red(" \u2717 schema:"));for(let b of d.error.issues)console.log(` ${b.path.join(".")||"<root>"}: ${b.message}`);process.exit(1)}let u=un(d.data);if(u.length){console.log(E.red(" \u2717 lint:"));for(let b of u)console.log(` ${b}`);process.exit(1)}let f=new Ro,p=d.data.id.startsWith("_adhoc-")?d.data.id:`_adhoc-${d.data.id}-${Date.now().toString(36)}`,w=l?"yaml":"json",y=vt(f.baseDir,`${p}.${w}`),k=l?c.replace(new RegExp(`^id:\\s*${d.data.id}\\b`,"m"),`id: ${p}`):JSON.stringify({...d.data,id:p},null,2)+`
494
- `;es(y,k),n=p,console.log(E.dim(` ad-hoc registered as "${p}" \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 l=await c.json();a=l.runId,console.log(E.green(` \u2713 run started: ${a||"(unknown id)"}${l.force?E.dim(` (forced, source=${l.source})`):""}`))}catch(c){console.log(E.red(` request to daemon failed: ${c.message}`)),process.exit(1)}o.watch&&a&&await Iu({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function Iu(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,l=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)")} ${l} ${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())}qe.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}ul(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)ul(i)});function ul(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()}qe.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 Nt({nodeId:t}).setStatus(e,"paused")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 paused ${e}`))});qe.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 Nt({nodeId:t}).setStatus(e,"running")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 resumed ${e}`))});qe.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 Nt({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 fl}from"commander";import oe from"chalk";import Yo from"prompts";import{readFileSync as ju,existsSync as Cu}from"fs";import{resolve as Nu}from"path";var sn=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],vi=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),hl={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 yl(){let e=Nu(process.cwd(),"agentx.json");if(!Cu(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(ju(e,"utf-8"))}function Ru(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?oe.yellow("\u26A0 no signing secret"):oe.green("\u2713 active"):oe.dim("disabled")}function Du(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=vi.has(e.source)?oe.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${oe.cyan(e.id)} ${Ru(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 po=new fl().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");po.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=yl(),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(`
491
+ `)}`)}var qe=new Iu().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");qe.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new Do().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"}.`))});qe.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 Do().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(rr(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))});qe.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=vt(process.cwd(),e);vi(i)||(console.log(E.red(` file not found: ${i}`)),process.exit(1));try{let r=xi(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?ot(r,{filePath:e}):JSON.parse(r),l=et.safeParse(c);if(!l.success){console.log(E.red(` \u2717 ${i}`));for(let d of l.error.issues)console.log(` ${d.path.join(".")||"<root>"}: ${d.message}`);process.exit(1)}let g=fn(l.data);if(g.length){console.log(E.yellow(` ! ${i} (lint)`));for(let d of g)console.log(` ${d}`);process.exit(1)}console.log(E.green(` \u2713 ${l.data.id} \u2014 valid`))}catch(r){let a=r instanceof hn?r.message:`parse error: ${r?.message??r}`;console.log(E.red(` ${a}`)),process.exit(1)}return}let t=new Do().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)});qe.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${sn.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");sn.some(a=>a.name===t)||(console.log(E.red(` unknown template "${o.template}"`)),console.log(E.dim(` available: ${sn.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 Do;!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=hl(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=ot(s,{filePath:`${e}.yaml`}),c=et.safeParse(a);if(!c.success){console.log(E.red(` template "${t}" failed schema validation after substitution:`));for(let l of c.error.issues)console.log(` ${l.path.join(".")||"<root>"}: ${l.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=vt(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=ot(s,{filePath:`${e}.yaml`}),c=et.parse(a);os(r,JSON.stringify(c,null,2)+`
492
+ `)}else os(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()});qe.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of sn)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()});qe.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=vt(process.cwd(),e);vi(t)||(console.log(E.red(` file not found: ${t}`)),process.exit(1));let n=xi(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?ot(n,{filePath:e}):JSON.parse(n)}catch(u){let f=u instanceof hn?u.message:`parse error: ${u?.message??u}`;console.log(E.red(` ${f}`)),process.exit(1)}let r=et.safeParse(i);if(!r.success){console.log(E.red(" \u2717 schema:"));for(let u of r.error.issues)console.log(` ${u.path.join(".")||"<root>"}: ${u.message}`);process.exit(1)}let a=fn(r.data);if(a.length){console.log(E.red(" \u2717 lint:"));for(let u of a)console.log(` ${u}`);process.exit(1)}let c=new Do,l=s?Cu(e).match(/\.yml$/i)?"yml":"yaml":"json",g=vt(c.baseDir,`${r.data.id}.${l}`);if(os(g,s?n:JSON.stringify(r.data,null,2)+`
493
+ `),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 d=`${String(o.daemon).replace(/\/$/,"")}/reload`;try{let u=await fetch(d,{method:"POST"});u.ok?console.log(E.dim(" \u2713 daemon reloaded")):console.log(E.dim(` daemon /reload returned ${u.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`))}});qe.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 Rt({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"}.`))});qe.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=vt(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&vi(s)){let c=xi(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),g;try{g=l?ot(c,{filePath:e}):JSON.parse(c)}catch(b){let S=b instanceof hn?b.message:`parse error: ${b?.message??b}`;console.log(E.red(` ${S}`)),process.exit(1)}let d=et.safeParse(g);if(!d.success){console.log(E.red(" \u2717 schema:"));for(let b of d.error.issues)console.log(` ${b.path.join(".")||"<root>"}: ${b.message}`);process.exit(1)}let u=fn(d.data);if(u.length){console.log(E.red(" \u2717 lint:"));for(let b of u)console.log(` ${b}`);process.exit(1)}let f=new Do,p=d.data.id.startsWith("_adhoc-")?d.data.id:`_adhoc-${d.data.id}-${Date.now().toString(36)}`,w=l?"yaml":"json",y=vt(f.baseDir,`${p}.${w}`),k=l?c.replace(new RegExp(`^id:\\s*${d.data.id}\\b`,"m"),`id: ${p}`):JSON.stringify({...d.data,id:p},null,2)+`
494
+ `;os(y,k),n=p,console.log(E.dim(` ad-hoc registered as "${p}" \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 l=await c.json();a=l.runId,console.log(E.green(` \u2713 run started: ${a||"(unknown id)"}${l.force?E.dim(` (forced, source=${l.source})`):""}`))}catch(c){console.log(E.red(` request to daemon failed: ${c.message}`)),process.exit(1)}o.watch&&a&&await Nu({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function Nu(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,l=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)")} ${l} ${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())}qe.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}yl(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)yl(i)});function yl(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()}qe.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 Rt({nodeId:t}).setStatus(e,"paused")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 paused ${e}`))});qe.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 Rt({nodeId:t}).setStatus(e,"running")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 resumed ${e}`))});qe.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 Rt({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 wl}from"commander";import oe from"chalk";import Vo from"prompts";import{readFileSync as Ru,existsSync as Du}from"fs";import{resolve as _u}from"path";var rn=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],Si=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),bl={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 $l(){let e=_u(process.cwd(),"agentx.json");if(!Du(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Ru(e,"utf-8"))}function Pu(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?oe.yellow("\u26A0 no signing secret"):oe.green("\u2713 active"):oe.dim("disabled")}function Mu(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=Si.has(e.source)?oe.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${oe.cyan(e.id)} ${Pu(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 po=new wl().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");po.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=$l(),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(`
495
495
  No webhooks registered. Add one with: agentx webhook add
496
- `));return}console.log();for(let n of t)Du(n)});po.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${sn.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=yl(),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(),l=String(o.secretEnv||"").trim(),g=String(o.description||"").trim(),d=o.prompt!==!1;if(!r&&d&&(r=((await Yo({type:"text",name:"id",message:"Webhook id (lowercase, e.g. globex-gitlab)",validate:p=>/^[a-z0-9][a-z0-9_-]*$/.test(p)||"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&&d&&(a=(await Yo({type:"select",name:"source",message:"Source",choices:sn.map(p=>({title:`${p}${vi.has(p)?" \u2713 wired":""}`,value:p,description:hl[p]}))})).source),!sn.includes(a))throw new Error(`Source must be one of: ${sn.join(", ")}`);if(!c&&d&&(i?c=((await Yo({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await Yo({type:"select",name:"agentId",message:"Agent",choices:n.map(p=>({title:p,value:p}))})).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.`);!l&&d&&a!=="custom"&&(l=((await Yo({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&d&&(g=((await Yo({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let u=await ue(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 p={id:r,source:a,agentId:c,enabled:!0};l&&(p.secretEnv=l),g&&(p.description=g),i&&(p.node=i),f.webhooks.push(p)});if(!u.success)throw new Error(u.error);console.log(oe.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),u.reloaded&&console.log(oe.dim(" daemon hot-reloaded")),!l&&a!=="custom"&&console.log(oe.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});po.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await Yo({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await ue(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 wl(e){return async o=>{let t=await ue(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}"`))}}po.command("enable <id>").description("enable a webhook entry").action(wl(!0));po.command("disable <id>").description("disable a webhook entry").action(wl(!1));var os=new fl().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 ue(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 ue(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 ue(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}`}`))});po.addCommand(os);po.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=sn.map(t=>({source:t,wired:vi.has(t),hint:hl[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 _u}from"commander";import te from"chalk";ge();function xt(e){let{summary:o,backupPath:t}=Do(n=>e(n));console.log(te.green(`
496
+ `));return}console.log();for(let n of t)Mu(n)});po.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${rn.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=$l(),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(),l=String(o.secretEnv||"").trim(),g=String(o.description||"").trim(),d=o.prompt!==!1;if(!r&&d&&(r=((await Vo({type:"text",name:"id",message:"Webhook id (lowercase, e.g. globex-gitlab)",validate:p=>/^[a-z0-9][a-z0-9_-]*$/.test(p)||"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&&d&&(a=(await Vo({type:"select",name:"source",message:"Source",choices:rn.map(p=>({title:`${p}${Si.has(p)?" \u2713 wired":""}`,value:p,description:bl[p]}))})).source),!rn.includes(a))throw new Error(`Source must be one of: ${rn.join(", ")}`);if(!c&&d&&(i?c=((await Vo({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await Vo({type:"select",name:"agentId",message:"Agent",choices:n.map(p=>({title:p,value:p}))})).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.`);!l&&d&&a!=="custom"&&(l=((await Vo({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&d&&(g=((await Vo({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let u=await fe(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 p={id:r,source:a,agentId:c,enabled:!0};l&&(p.secretEnv=l),g&&(p.description=g),i&&(p.node=i),f.webhooks.push(p)});if(!u.success)throw new Error(u.error);console.log(oe.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),u.reloaded&&console.log(oe.dim(" daemon hot-reloaded")),!l&&a!=="custom"&&console.log(oe.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});po.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await Vo({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await fe(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 kl(e){return async o=>{let t=await fe(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}"`))}}po.command("enable <id>").description("enable a webhook entry").action(kl(!0));po.command("disable <id>").description("disable a webhook entry").action(kl(!1));var ts=new wl().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");ts.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await fe(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}`))});ts.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await fe(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}"`))});ts.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 fe(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}`}`))});po.addCommand(ts);po.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=rn.map(t=>({source:t,wired:Si.has(t),hint:bl[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 Lu}from"commander";import te from"chalk";me();function xt(e){let{summary:o,backupPath:t}=_o(n=>e(n));console.log(te.green(`
497
497
  \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.
498
- `))}function ts(){try{return _().business||{}}catch{return{}}}var St=new _u().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");St.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}`):"",l=a.schedule?te.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${te.cyan(r)} ${a.role}${c}${l}`)}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 xi=St.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");xi.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}`):""}`)});xi.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);xt(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}`:""})`))});xi.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{xt(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 Si=St.command("project").description("manage business.projects \u2014 id, pm, client");Si.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())});Si.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)=>{xt(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`})});Si.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{xt(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 Ei=St.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");Ei.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:""}`)}});Ei.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)),xt(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`})});Ei.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=>{xt(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 Pu}from"commander";import Re from"chalk";ge();var Mu={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function Ai(e){let o=Mu[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 ra(o)}var Et=new Pu().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");Et.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=Ai(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(`
499
- `):(console.error(Re.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(t,s);console.log(Re.green(` \u2713 ${t} plan saved \u2192 ${i.path}`));let r=Is(s);if(r.length){console.log(Re.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(Re.dim(` \u2022 ${a}`))}});Et.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=Ai(e),s=o.read(n);if(!s){console.log(Re.dim(` No ${n} plan set.`));return}bl(s.tier,s.date,s.content);return}let t=o.resolve();if(!t){console.log(Re.yellow(" No plan set at any tier.")),console.log(Re.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(Re.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}bl(t.tier,t.date,t.content)});Et.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(Re.dim(" No plans yet."));return}for(let n of t)console.log(` ${Re.cyan(n.tier.padEnd(5))} ${Re.bold(n.date.padEnd(11))} ${Re.dim(n.path)}`)});Et.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=Ai(e),n=ns().read(o);if(!n){console.log(Re.dim(` No ${o} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(Re.green(` \u2713 ${o} plan cleared (${n.path})`))});function bl(e,o,t){console.log(Re.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
500
- `))console.log(` ${s}`);console.log();let n=Is(t);n.length&&console.log(Re.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as Lu}from"commander";import ne from"chalk";ge();function Fu(){try{return _().notifications||{}}catch{return{}}}function Uu(){try{return _().channels?.ntfy}catch{return}}function rn(e){let{summary:o,backupPath:t}=Do(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(ne.green(`
498
+ `))}function ns(){try{return _().business||{}}catch{return{}}}var St=new Lu().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");St.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=ns();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}`):"",l=a.schedule?te.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${te.cyan(r)} ${a.role}${c}${l}`)}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 Ei=St.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");Ei.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=ns(),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}`):""}`)});Ei.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);xt(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}`:""})`))});Ei.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{xt(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 Ai=St.command("project").description("manage business.projects \u2014 id, pm, client");Ai.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=ns().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())});Ai.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)=>{xt(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`})});Ai.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{xt(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 Oi=St.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");Oi.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let t=ns().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:""}`)}});Oi.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)),xt(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`})});Oi.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=>{xt(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 Fu}from"commander";import De from"chalk";me();var Uu={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function Ti(e){let o=Uu[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function ss(){let o=_().business?.standup?.plansDir||".agentx/plans";return new la(o)}var Et=new Fu().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");Et.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=Ti(e),n=ss(),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(`
499
+ `):(console.error(De.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(t,s);console.log(De.green(` \u2713 ${t} plan saved \u2192 ${i.path}`));let r=Cs(s);if(r.length){console.log(De.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(De.dim(` \u2022 ${a}`))}});Et.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=ss();if(e){let n=Ti(e),s=o.read(n);if(!s){console.log(De.dim(` No ${n} plan set.`));return}vl(s.tier,s.date,s.content);return}let t=o.resolve();if(!t){console.log(De.yellow(" No plan set at any tier.")),console.log(De.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(De.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}vl(t.tier,t.date,t.content)});Et.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=ss().list(parseInt(e.limit,10)||20);if(!t.length){console.log(De.dim(" No plans yet."));return}for(let n of t)console.log(` ${De.cyan(n.tier.padEnd(5))} ${De.bold(n.date.padEnd(11))} ${De.dim(n.path)}`)});Et.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=Ti(e),n=ss().read(o);if(!n){console.log(De.dim(` No ${o} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(De.green(` \u2713 ${o} plan cleared (${n.path})`))});function vl(e,o,t){console.log(De.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
500
+ `))console.log(` ${s}`);console.log();let n=Cs(t);n.length&&console.log(De.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as qu}from"commander";import ne from"chalk";me();function Wu(){try{return _().notifications||{}}catch{return{}}}function Bu(){try{return _().channels?.ntfy}catch{return}}function an(e){let{summary:o,backupPath:t}=_o(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(ne.green(`
501
501
  \u2713 ${o}`)),t&&console.log(ne.dim(` Backup: ${t}`)),console.log(ne.dim(` Restart the daemon (or POST /reload) for the change to take effect.
502
- `))}var Oo=new Lu().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");Oo.command("show").description("print current notifications config").option("--json","JSON output").action(e=>{let o=Fu();if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.destination){let i=o.destination.accountId?` \xB7 account=${o.destination.accountId}`:"";console.log(` destination ${ne.cyan(o.destination.channel+":"+o.destination.chatId)}${ne.dim(i)}`)}else console.log(` destination ${ne.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${ne.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?ne.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?ne.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":ne.dim("off")}`);let n=bn(o.local);console.log(` local.banner ${n.banner?"on":ne.dim("off")}`),console.log(` local.sound ${n.sound?`${n.soundName} at ${n.volume}`:ne.dim("off")}`),console.log(` local.icon ${n.icon??ne.dim("AgentX logo")}`);let s=Cs(Uu());console.log(` ntfy ${s.enabled?"on":ne.dim("off")} ${ne.dim(`${s.server} \xB7 topic ${s.topicSet?"set":"unset"} \xB7 token ${s.tokenSet?"set":"unset"}`)}`),console.log()});Oo.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){rn(o=>(delete o.destination,"notifications destination cleared"));return}rn(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})`:""}`))});Oo.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(ne.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(ne.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";rn(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});Oo.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(ne.red(" threshold must be a non-negative integer")),process.exit(1)),rn(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});Oo.command("local").description("set what `agentx notify` does on this Mac: banner, sound, sound name, volume, banner icon").option("--banner <state>","on | off").option("--sound <state>","on | off").option("--sound-name <name>","a macOS system sound, e.g. Glass, Ping, Tink").option("--volume <n>","0 to 1").option("--icon <path>",'image for the banner icon (.png, .jpg, .icns); "" for the AgentX logo').action(e=>{let o=(n,s)=>{let i=s.toLowerCase();if(["on","true","1"].includes(i))return!0;if(["off","false","0"].includes(i))return!1;console.log(ne.red(` ${n} must be on|off`)),process.exit(1)},t={};e.banner!==void 0&&(t.banner=o("--banner",e.banner)),e.sound!==void 0&&(t.sound=o("--sound",e.sound)),e.soundName!==void 0&&(t.soundName=e.soundName),e.volume!==void 0&&(t.volume=e.volume),e.icon!==void 0&&(t.icon=e.icon),Object.keys(t).length===0&&(console.log(ne.red(" nothing to change \u2014 pass --banner, --sound, --sound-name, --volume or --icon")),process.exit(1));try{rn(n=>(n.local=Lr(n.local,t),`notifications.local = ${JSON.stringify(n.local)}`)),e.icon!==void 0&&console.log(ne.dim(` Run agentx desktop install to put the new icon on the helper.
503
- `))}catch(n){console.log(ne.red(` ${n?.message??n}`)),process.exit(1)}});Oo.command("ntfy").description("set up phone push through ntfy: server, topic, token, on/off").option("--server <url>","ntfy server (default https://ntfy.sh)").option("--topic <topic>",'topic to publish to; a secret on ntfy.sh \u2014 "${NTFY_TOPIC}" reads it from .env').option("--token <token>",'access token for a protected topic; "${NTFY_TOKEN}" reads it from .env; "" removes it').option("--enable","turn the channel on").option("--disable","turn the channel off").action(e=>{let o={};e.server!==void 0&&(o.server=e.server),e.topic!==void 0&&(o.topic=e.topic),e.token!==void 0&&(o.token=e.token),e.enable&&(o.enabled=!0),e.disable&&(o.enabled=!1),Object.keys(o).length===0&&(console.log(ne.red(" nothing to change \u2014 pass --server, --topic, --token, --enable or --disable")),process.exit(1));try{let{summary:t,backupPath:n}=Do(s=>{s.channels=s.channels||{},s.channels.ntfy=ua(s.channels.ntfy,o);let i=Cs(s.channels.ntfy);return`channels.ntfy ${i.enabled?"on":"off"} \xB7 ${i.server} \xB7 topic ${i.topicSet?"set":"unset"} \xB7 token ${i.tokenSet?"set":"unset"}`});console.log(ne.green(`
502
+ `))}var Oo=new qu().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");Oo.command("show").description("print current notifications config").option("--json","JSON output").action(e=>{let o=Wu();if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.destination){let i=o.destination.accountId?` \xB7 account=${o.destination.accountId}`:"";console.log(` destination ${ne.cyan(o.destination.channel+":"+o.destination.chatId)}${ne.dim(i)}`)}else console.log(` destination ${ne.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${ne.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?ne.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?ne.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":ne.dim("off")}`);let n=$n(o.local);console.log(` local.banner ${n.banner?"on":ne.dim("off")}`),console.log(` local.sound ${n.sound?`${n.soundName} at ${n.volume}`:ne.dim("off")}`),console.log(` local.icon ${n.icon??ne.dim("AgentX logo")}`);let s=Rs(Bu());console.log(` ntfy ${s.enabled?"on":ne.dim("off")} ${ne.dim(`${s.server} \xB7 topic ${s.topicSet?"set":"unset"} \xB7 token ${s.tokenSet?"set":"unset"}`)}`),console.log()});Oo.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){an(o=>(delete o.destination,"notifications destination cleared"));return}an(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})`:""}`))});Oo.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(ne.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(ne.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";an(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});Oo.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(ne.red(" threshold must be a non-negative integer")),process.exit(1)),an(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});Oo.command("local").description("set what `agentx notify` does on this Mac: banner, sound, sound name, volume, banner icon").option("--banner <state>","on | off").option("--sound <state>","on | off").option("--sound-name <name>","a macOS system sound, e.g. Glass, Ping, Tink").option("--volume <n>","0 to 1").option("--icon <path>",'image for the banner icon (.png, .jpg, .icns); "" for the AgentX logo').action(e=>{let o=(n,s)=>{let i=s.toLowerCase();if(["on","true","1"].includes(i))return!0;if(["off","false","0"].includes(i))return!1;console.log(ne.red(` ${n} must be on|off`)),process.exit(1)},t={};e.banner!==void 0&&(t.banner=o("--banner",e.banner)),e.sound!==void 0&&(t.sound=o("--sound",e.sound)),e.soundName!==void 0&&(t.soundName=e.soundName),e.volume!==void 0&&(t.volume=e.volume),e.icon!==void 0&&(t.icon=e.icon),Object.keys(t).length===0&&(console.log(ne.red(" nothing to change \u2014 pass --banner, --sound, --sound-name, --volume or --icon")),process.exit(1));try{an(n=>(n.local=qr(n.local,t),`notifications.local = ${JSON.stringify(n.local)}`)),e.icon!==void 0&&console.log(ne.dim(` Run agentx desktop install to put the new icon on the helper.
503
+ `))}catch(n){console.log(ne.red(` ${n?.message??n}`)),process.exit(1)}});Oo.command("ntfy").description("set up phone push through ntfy: server, topic, token, on/off").option("--server <url>","ntfy server (default https://ntfy.sh)").option("--topic <topic>",'topic to publish to; a secret on ntfy.sh \u2014 "${NTFY_TOPIC}" reads it from .env').option("--token <token>",'access token for a protected topic; "${NTFY_TOKEN}" reads it from .env; "" removes it').option("--enable","turn the channel on").option("--disable","turn the channel off").action(e=>{let o={};e.server!==void 0&&(o.server=e.server),e.topic!==void 0&&(o.topic=e.topic),e.token!==void 0&&(o.token=e.token),e.enable&&(o.enabled=!0),e.disable&&(o.enabled=!1),Object.keys(o).length===0&&(console.log(ne.red(" nothing to change \u2014 pass --server, --topic, --token, --enable or --disable")),process.exit(1));try{let{summary:t,backupPath:n}=_o(s=>{s.channels=s.channels||{},s.channels.ntfy=ya(s.channels.ntfy,o);let i=Rs(s.channels.ntfy);return`channels.ntfy ${i.enabled?"on":"off"} \xB7 ${i.server} \xB7 topic ${i.topicSet?"set":"unset"} \xB7 token ${i.tokenSet?"set":"unset"}`});console.log(ne.green(`
504
504
  \u2713 ${t}`)),n&&console.log(ne.dim(` Backup: ${n}`)),console.log(ne.dim(` Restart the daemon for a channel change to take effect.
505
- `))}catch(t){console.log(ne.red(` ${t?.message??t}`)),process.exit(1)}});import{Command as qu}from"commander";import To from"chalk";import{readdirSync as Oi,statSync as $l,unlinkSync as Wu,rmSync as Bu,existsSync as kl}from"fs";import{resolve as vl,join as xl}from"path";var Sl=[{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 Ti(e,o){if(!kl(e))return[];let t=[];for(let n of Oi(e,{withFileTypes:!0})){let s=xl(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...Ti(s,!0))}return t}var is=new qu().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");is.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of Sl){let t=vl(process.cwd(),o.dir),n=Ti(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=$l(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(` ${To.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${ss(s).padStart(10)} oldest=${r}`)}console.log(To.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${ss(e).padStart(10)} total`)),console.log(),console.log(To.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});is.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(To.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(To.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?To.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of Sl){if(n&&r.dir!==n)continue;let a=vl(process.cwd(),r.dir),c=Ti(a,!!r.recursive),l=0,g=0;for(let u of c)try{let f=$l(u);if(f.mtimeMs<t&&(g+=f.size,l++,!e.dryRun))try{Wu(u)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{El(a)}catch{}let d=e.dryRun?"would remove":"removed";console.log(` ${To.cyan(r.dir.padEnd(22))} ${d} ${String(l).padStart(5)} files (${ss(g)})`),s+=l,i+=g}console.log(),console.log(To.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${ss(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function El(e){if(kl(e))for(let o of Oi(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=xl(e,o.name);El(t);try{Oi(t).length===0&&Bu(t,{recursive:!1})}catch{}}}function ss(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 Ju}from"commander";import F from"chalk";var Io=new Ju().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");Io.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new tt().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()});Io.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new tt().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()});Io.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=Gu(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=sr.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 tt().save(s.data);console.log(F.green(`
505
+ `))}catch(t){console.log(ne.red(` ${t?.message??t}`)),process.exit(1)}});import{Command as Ju}from"commander";import To from"chalk";import{readdirSync as ji,statSync as xl,unlinkSync as Gu,rmSync as Hu,existsSync as Sl}from"fs";import{resolve as El,join as Al}from"path";var Ol=[{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 Ii(e,o){if(!Sl(e))return[];let t=[];for(let n of ji(e,{withFileTypes:!0})){let s=Al(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...Ii(s,!0))}return t}var rs=new Ju().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 Ol){let t=El(process.cwd(),o.dir),n=Ii(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=xl(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(` ${To.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${is(s).padStart(10)} oldest=${r}`)}console.log(To.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${is(e).padStart(10)} total`)),console.log(),console.log(To.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(To.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(To.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?To.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of Ol){if(n&&r.dir!==n)continue;let a=El(process.cwd(),r.dir),c=Ii(a,!!r.recursive),l=0,g=0;for(let u of c)try{let f=xl(u);if(f.mtimeMs<t&&(g+=f.size,l++,!e.dryRun))try{Gu(u)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{Tl(a)}catch{}let d=e.dryRun?"would remove":"removed";console.log(` ${To.cyan(r.dir.padEnd(22))} ${d} ${String(l).padStart(5)} files (${is(g)})`),s+=l,i+=g}console.log(),console.log(To.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${is(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function Tl(e){if(Sl(e))for(let o of ji(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=Al(e,o.name);Tl(t);try{ji(t).length===0&&Hu(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 zu}from"commander";import F from"chalk";var jo=new zu().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");jo.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new tt().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()});jo.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new tt().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()});jo.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=Yu(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=ar.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 tt().save(s.data);console.log(F.green(`
506
506
  \u2713 action "${r.id}" saved (${r.kind}).`)),console.log(F.dim(` Test: agentx actions run ${r.id}
507
- `))});Io.command("remove <id>").alias("rm").description("delete an action").action(e=>{new tt().delete(e)||(console.log(F.red(` no action "${e}"`)),process.exit(1)),console.log(F.green(` \u2713 action "${e}" removed`))});Io.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 tt().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 ir(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)}});Io.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 Gu(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}ge();import{Command as Hu}from"commander";import Q from"chalk";var Al=new Hu().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,l="";for(;;){let{done:g,value:d}=await a.read();if(g)break;l+=c.decode(d,{stream:!0});let u;for(;(u=l.indexOf(`
507
+ `))});jo.command("remove <id>").alias("rm").description("delete an action").action(e=>{new tt().delete(e)||(console.log(F.red(` no action "${e}"`)),process.exit(1)),console.log(F.green(` \u2713 action "${e}" removed`))});jo.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 tt().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 cr(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)}});jo.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 Yu(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}me();import{Command as Vu}from"commander";import Q from"chalk";var jl=new Vu().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,l="";for(;;){let{done:g,value:d}=await a.read();if(g)break;l+=c.decode(d,{stream:!0});let u;for(;(u=l.indexOf(`
508
508
 
509
- `))>=0;){let f=l.slice(0,u);l=l.slice(u+2),zu(f)}}}catch(r){console.error(Q.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function zu(e){let o="message",t="";for(let i of e.split(`
510
- `))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):"",l=n.note?Q.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);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 Vu}from"commander";import rs from"chalk";import{spawn as Ku}from"node:child_process";import{execFileSync as Yu}from"node:child_process";function Ol(e=()=>Yu("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 Tl=new Vu().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(rs.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-NTC667CA.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:Ol();if(n?.ok){let{fetchAgents:l}=await import("./client-NTC667CA.js"),g=await l(t);if(!g.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let d=e.agent||g[0].id;if(!g.some(y=>y.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let u={};try{u=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(y=>[y.id,{name:`AgentX ${y.name||y.id}`}])),p={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...u,model:`agentx/${d}`,providers:{...u.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:f}}})};console.error(rs.dim(`Opening ${n.version} with AgentX model ${d}.`));let w=Ku("opencode",["--standalone"],{stdio:"inherit",env:p});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(rs.yellow(n.reason)),console.error(rs.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-QTUGMHG7.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 Xu}from"commander";import V from"chalk";import{randomUUID as Cl}from"crypto";import{createInterface as Qu}from"node:readline/promises";import Zu from"ora";import as from"chalk";function Il(e){console.error(),console.error(as.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(as.dim(` ${e.why}`)),console.error(),console.error(` Use ${as.cyan(e.instead)} instead.`),e.note&&console.error(as.dim(` ${e.note}`)),console.error()}var jl={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 Nl=new Xu().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)=>{Il({what:"agentx chat",...jl});let t=ha({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${Cl().slice(0,12)}`,r=[];try{r=await An(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:d}=await import("./ChatApp-634FDG3W.js"),u=(await import("react")).default;await g(u.createElement(d,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}of(t.baseUrl,n,i,s);let a=Qu({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(V.dim(`
511
- 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:${Cl().slice(0,12)}`,console.log(V.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let p=await An(t);for(let w of p){let y=w.id===n?V.green("\u25CF"):V.dim("\u25CB");console.log(` ${y} @${w.id} ${V.dim(w.tier)} ${w.model??""}`)}}catch(p){console.error(V.red(` failed to list agents: ${p?.message||p}`))}continue}if(g.startsWith("/agent ")){let p=g.slice(7).replace(/^@/,"").trim();if(!p){console.log(V.red(" usage: /agent <id>"));continue}try{if(!(await An(t)).find(y=>y.id===p)){console.log(V.red(` unknown agent: @${p}`));continue}n=p,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 d=Zu({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),f=ef(n);try{let p=await ya(t,n,g,{channel:s,chatId:i,onText:y=>{d.stop(),f.text(y)},onThinking:()=>{},onTool:y=>{d.stop(),f.tool(y)}});d.stop();let w=Math.round((Date.now()-u)/100)/10;p.error?f.finishError(p.error):f.finish(w,p.usage)}catch(p){d.stop(),f.finishError(p?.message||String(p))}finally{c=!1}if(l){console.log(V.dim(" bye"));return}}});function ef(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${V.green(`@${e}`)}
509
+ `))>=0;){let f=l.slice(0,u);l=l.slice(u+2),Ku(f)}}}catch(r){console.error(Q.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function Ku(e){let o="message",t="";for(let i of e.split(`
510
+ `))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):"",l=n.note?Q.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);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 Qu}from"commander";import as from"chalk";import{spawn as Zu}from"node:child_process";import{execFileSync as Xu}from"node:child_process";function Il(e=()=>Xu("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 Cl=new Qu().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-NTC667CA.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:Il();if(n?.ok){let{fetchAgents:l}=await import("./client-NTC667CA.js"),g=await l(t);if(!g.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let d=e.agent||g[0].id;if(!g.some(y=>y.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let u={};try{u=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(y=>[y.id,{name:`AgentX ${y.name||y.id}`}])),p={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...u,model:`agentx/${d}`,providers:{...u.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 ${d}.`));let w=Zu("opencode",["--standalone"],{stdio:"inherit",env:p});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-QTUGMHG7.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 ef}from"commander";import V from"chalk";import{randomUUID as Dl}from"crypto";import{createInterface as of}from"node:readline/promises";import tf from"ora";import cs from"chalk";function Nl(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 Rl={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 _l=new ef().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)=>{Nl({what:"agentx chat",...Rl});let t=ba({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${Dl().slice(0,12)}`,r=[];try{r=await On(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:d}=await import("./ChatApp-634FDG3W.js"),u=(await import("react")).default;await g(u.createElement(d,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}sf(t.baseUrl,n,i,s);let a=of({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(V.dim(`
511
+ 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:${Dl().slice(0,12)}`,console.log(V.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let p=await On(t);for(let w of p){let y=w.id===n?V.green("\u25CF"):V.dim("\u25CB");console.log(` ${y} @${w.id} ${V.dim(w.tier)} ${w.model??""}`)}}catch(p){console.error(V.red(` failed to list agents: ${p?.message||p}`))}continue}if(g.startsWith("/agent ")){let p=g.slice(7).replace(/^@/,"").trim();if(!p){console.log(V.red(" usage: /agent <id>"));continue}try{if(!(await On(t)).find(y=>y.id===p)){console.log(V.red(` unknown agent: @${p}`));continue}n=p,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 d=tf({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),f=nf(n);try{let p=await $a(t,n,g,{channel:s,chatId:i,onText:y=>{d.stop(),f.text(y)},onThinking:()=>{},onTool:y=>{d.stop(),f.tool(y)}});d.stop();let w=Math.round((Date.now()-u)/100)/10;p.error?f.finishError(p.error):f.finish(w,p.usage)}catch(p){d.stop(),f.finishError(p?.message||String(p))}finally{c=!1}if(l){console.log(V.dim(" bye"));return}}});function nf(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${V.green(`@${e}`)}
512
512
  `),o=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)t&&a!==`
513
513
  `&&(process.stdout.write(" "),t=!1),process.stdout.write(a),a===`
514
514
  `&&(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(`
@@ -523,17 +523,17 @@ agentx wiki questions`,ce=T?.daemon?.port??T?.port??18800;try{let J=await fetch(
523
523
  `))},finishError(r){o&&!t&&process.stdout.write(`
524
524
  `),process.stdout.write(V.red(` \u2717 ${r}
525
525
 
526
- `))}}}function of(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 tf}from"commander";import De from"chalk";import{readFileSync as nf}from"fs";var cs=["user","feedback","project","reference"],Vo=new tf().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");Vo.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(!cs.includes(e.type)){console.error(De.red(` --type must be one of: ${cs.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await sf();else try{o=nf(e.file,"utf-8")}catch(s){console.error(De.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(De.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new Zo().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(De.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});Vo.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 Zo().list(e.agent);if(e.type){if(!cs.includes(e.type)){console.error(De.red(` --type must be one of: ${cs.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.length){console.log(De.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(De.bold(` ${s.type}`)),n=s.type),console.log(` ${De.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(De.dim(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});Vo.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 Zo().get(o.agent,e);if(!n){console.error(De.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(De.bold(`${n.type}/${n.name}`)+De.dim(` (${n.description})`)),console.log(De.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});Vo.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new Zo().remove(o.agent,e)){console.error(De.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(De.green(` \u2713 memory "${e}" removed`))});Vo.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 Zo().indexMarkdown(e.agent);if(!t){console.log(De.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});async function sf(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}Ql();import Ii from"chalk";import{Command as rf}from"commander";import{resolve as af}from"path";var Rl=new rf().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(af(e.cwd)),e.stdio!==!1?await kr():(io.error("Only stdio transport is currently supported."),io.info(`Usage: ${Ii.green("agentx serve --stdio")} or configure in your MCP client.`),io.break(),io.info("Add to Claude Code:"),io.info(Ii.dim(" claude mcp add agentx -- npx agentx serve --stdio")),io.break(),io.info("Add to Cursor/MCP config:"),io.info(Ii.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){aa(o)}});import{Command as cf}from"commander";import re from"chalk";import{spawn as ji}from"child_process";import{mkdirSync as lf,writeFileSync as gs,readFileSync as df,readdirSync as gf,rmSync as _l,openSync as Pl,existsSync as ls}from"fs";import{resolve as mf,join as _e}from"path";import{randomBytes as pf}from"crypto";var Dl={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 Ml="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",uf="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function ff(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(Dl,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 hf(e,o,t){let n=_e(e.dir,"workspaces",e.agentId);lf(n,{recursive:!0}),gs(_e(n,"CLAUDE.md"),`# ${e.agentName}
526
+ `))}}}function sf(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 rf}from"commander";import se from"chalk";import{readFileSync as af}from"fs";import{existsSync as cf,readdirSync as lf}from"fs";import{resolve as df}from"path";var ls=["user","feedback","project","reference"],Io=new rf().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");Io.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(se.red(` --type must be one of: ${ls.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await gf();else try{o=af(e.file,"utf-8")}catch(s){console.error(se.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(se.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new Zo().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(se.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});Io.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 Zo().list(e.agent);if(e.type){if(!ls.includes(e.type)){console.error(se.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(se.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(se.bold(` ${s.type}`)),n=s.type),console.log(` ${se.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(se.dim(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});Io.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 Zo().get(o.agent,e);if(!n){console.error(se.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(se.bold(`${n.type}/${n.name}`)+se.dim(` (${n.description})`)),console.log(se.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});Io.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new Zo().remove(o.agent,e)){console.error(se.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(se.green(` \u2713 memory "${e}" removed`))});Io.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 Zo().indexMarkdown(e.agent);if(!t){console.log(se.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});var ds=Io.command("facts").description("review facts extracted from conversations (held, approve, reject, scrub)");function Ci(e){if(e)return[e];let o=df(process.cwd(),".agentx/memory");return cf(o)?lf(o).filter(t=>t.endsWith(".jsonl")).map(t=>t.slice(0,-6)).sort():[]}ds.command("summary").description("count facts per agent by source trust and review state").option("--agent <id>","one agent (default: all)").action(e=>{let o=new Nt;for(let t of Ci(e.agent)){let n=Object.entries(o.trustSummary(t)).map(([s,i])=>`${s}: ${i}`).join(", ");console.log(` ${se.bold(t)} ${n||se.dim("(none)")}`)}});ds.command("held").description("list facts waiting for review before they are used").option("--agent <id>","one agent (default: all)").action(e=>{let o=new Nt,t=0;for(let n of Ci(e.agent))for(let s of o.held(n))t++,console.log(` ${se.bold(n)} ${se.cyan(s.id)} ${se.dim(`${s.source.channel} \xB7 ${s.source.date}`)}`),console.log(` ${s.content}`);t===0&&console.log(se.dim(" nothing held"))});for(let e of["approve","reject"])ds.command(e).description(e==="approve"?"let a held fact be used in prompts":"keep a held fact out of prompts for good").requiredOption("--agent <id>","agent id").argument("<id>","fact id (from `agentx memory facts held`)").action((o,t)=>{if(!new Nt().review(t.agent,o,e==="approve"?"approved":"rejected")){console.error(se.red(` no fact "${o}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(se.green(` \u2713 ${o} ${e==="approve"?"approved":"rejected"}`))});ds.command("scrub").description("find stored facts that contain credentials; --apply deletes them").option("--agent <id>","one agent (default: all)").option("--apply","delete them (default: count only)").action(e=>{let o=new Nt,t=0;for(let n of Ci(e.agent)){let s=o.scrubSecrets(n,!!e.apply);s&&console.log(` ${se.bold(n)} ${s}`),t+=s}console.log(e.apply?se.green(` \u2713 deleted ${t} fact(s) containing credentials`):se.dim(` ${t} fact(s) contain credentials (never injected). Run with --apply to delete them.`))});async function gf(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}od();import Ni from"chalk";import{Command as mf}from"commander";import{resolve as pf}from"path";var Pl=new mf().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(pf(e.cwd)),e.stdio!==!1?await Sr():(io.error("Only stdio transport is currently supported."),io.info(`Usage: ${Ni.green("agentx serve --stdio")} or configure in your MCP client.`),io.break(),io.info("Add to Claude Code:"),io.info(Ni.dim(" claude mcp add agentx -- npx agentx serve --stdio")),io.break(),io.info("Add to Cursor/MCP config:"),io.info(Ni.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){da(o)}});import{Command as uf}from"commander";import ae from"chalk";import{spawn as Ri}from"child_process";import{mkdirSync as ff,writeFileSync as ps,readFileSync as hf,readdirSync as yf,rmSync as Ll,openSync as Fl,existsSync as gs}from"fs";import{resolve as wf,join as _e}from"path";import{randomBytes as bf}from"crypto";var Ml={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 Ul="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",$f="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function kf(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(Ml,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 vf(e,o,t){let n=_e(e.dir,"workspaces",e.agentId);ff(n,{recursive:!0}),ps(_e(n,"CLAUDE.md"),`# ${e.agentName}
527
527
 
528
528
  ${e.persona}
529
- `),gs(_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}};gs(_e(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function Ci(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 Ni(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 ds(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
529
+ `),ps(_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}};ps(_e(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function Di(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 _i(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 ms(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
530
530
  `).join(`
531
- `)}`)}var Ll=new cf().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=mf(process.cwd(),".agentx-demo"),n=ff(t,o),s=_e(t,"mesh-token"),i=!!e.reuse&&ls(s)&&ls(_e(n[0].dir,"agentx.json")),r=i?df(s,"utf8").trim():pf(24).toString("hex"),a=e.keep||e.reuse,c=[],l=process.argv[1];if((!l||!ls(l))&&(console.error(re.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!i){if(ls(t))for(let f of gf(t))_l(_e(t,f),{recursive:!0,force:!0});for(let f of n)hf(f,n,r);gs(s,r+`
532
- `,{mode:384})}console.log(),console.log(re.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(re.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(re.dim(" Run `agentx setup` to wire real agents.\n"));let g=!1,d=f=>{if(!g){g=!0;for(let p of c)try{p.kill("SIGTERM")}catch{}setTimeout(()=>{if(!a)try{_l(t,{recursive:!0,force:!0})}catch{}process.exit(f)},800)}};process.on("SIGINT",()=>d(0)),process.on("SIGTERM",()=>d(0));let u={...process.env};delete u.ANTHROPIC_API_KEY,delete u.ANTHROPIC_API_KEY_OLD,delete u.OPENAI_API_KEY,delete u.DEEPSEEK_API_KEY;try{for(let y of n){let k=Pl(_e(y.dir,"daemon.log"),"a"),b=ji(process.execPath,[l,"daemon","start","-c",_e(y.dir,"agentx.json")],{cwd:y.dir,env:{...u,MESH_TOKEN:r,AGENTX_DEMO_SCRIPT:_e(y.dir,"demo-script.json")},stdio:["ignore",k,k]});c.push(b),console.log(re.dim(` \u25B8 ${y.name} starting on 127.0.0.1:${y.port} (log: ${_e(y.dir,"daemon.log")})`))}for(let y of n)await Ci(`${y.name} /health`,async()=>(await fetch(`http://127.0.0.1:${y.port}/health`)).ok,3e4);console.log(re.green(" \u2713 three daemons up"));let f=n[0].port+10;{let y=Pl(_e(n[0].dir,"board.log"),"a"),k=ji(process.execPath,[l,"board","serve","--bind",e.bind],{cwd:n[0].dir,env:{...u,MESH_TOKEN:r},stdio:["ignore",y,y]});c.push(k)}await Ci("dashboard /live",async()=>(await fetch(`http://127.0.0.1:${f}/live`)).ok,3e4),console.log(re.green(" \u2713 dashboard up")),await Ci("mesh discovery (laptop sees both peers)",async()=>((await(await fetch(`http://127.0.0.1:${n[0].port}/health`)).json()).mesh||[]).filter(S=>S.healthy&&S.skills?.length).length>=2,3e4),console.log(re.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let p=`http://127.0.0.1:${f}/live`;if(console.log(),console.log(` Dashboard: ${re.cyan(p)} (all three nodes via the mesh)`),console.log(re.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{ji(y,[p],{stdio:"ignore",detached:!0}).unref()}catch{}}let w=async()=>{console.log(),console.log(re.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),ds("You \u2192 @cx (laptop-paris)",Ml,re.cyan);let y=await Ni(n[0].port,"/task",{agent:"cx",message:Ml});ds("@cx (laptop-paris)",y.content||"(no content)",re.green),console.log(),console.log(re.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let k=await Ni(n[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:uf}),b=typeof k.messageId=="string"?k.messageId:k.content||"(no reply)";ds("@builder (vps-nyc)",b,re.yellow);let S=await Ni(n[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${b}`});ds("@cx (laptop-paris)",S.content||"(no content)",re.green),console.log(),console.log(re.dim(` Inspect the run: ${p} \xB7 ledger rows on each node record every dispatch`)),console.log(re.dim(` Worth your time? A star helps others find it: ${re.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(i?console.log(re.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await w(),e.once){console.log(),console.log(re.dim(" --once: shutting down.")),d(0);return}console.log(),console.log(re.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(re.red(` Replay failed: ${y.message}`)))}),process.stdin.resume()}catch(f){console.error(),console.error(re.red(` Demo failed: ${f.message}`)),console.error(re.dim(` Node logs: ${n.map(p=>_e(p.dir,"daemon.log")).join(", ")}`)),d(1)}});import{Command as yf}from"commander";import{randomUUID as wf}from"crypto";import{readFileSync as bf}from"fs";import{resolve as $f}from"path";ge();var Ul=new yf().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??bf(0,"utf8")).trim();t||Fl("no task given (pass it as an argument or on stdin)");let n=_(o.config?$f(o.config):void 0),s=n.agents[o.agent];s||Fl(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`);let i=(...l)=>console.error("[agentx exec]",...l);if(o.setupWorkspace){let l=n.node.bind.split(":")[1]||"19900";Xi(o.agent,s,l,i)}let r=new mr(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-${wf()}`,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})+`
531
+ `)}`)}var ql=new uf().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=wf(process.cwd(),".agentx-demo"),n=kf(t,o),s=_e(t,"mesh-token"),i=!!e.reuse&&gs(s)&&gs(_e(n[0].dir,"agentx.json")),r=i?hf(s,"utf8").trim():bf(24).toString("hex"),a=e.keep||e.reuse,c=[],l=process.argv[1];if((!l||!gs(l))&&(console.error(ae.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!i){if(gs(t))for(let f of yf(t))Ll(_e(t,f),{recursive:!0,force:!0});for(let f of n)vf(f,n,r);ps(s,r+`
532
+ `,{mode:384})}console.log(),console.log(ae.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(ae.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(ae.dim(" Run `agentx setup` to wire real agents.\n"));let g=!1,d=f=>{if(!g){g=!0;for(let p of c)try{p.kill("SIGTERM")}catch{}setTimeout(()=>{if(!a)try{Ll(t,{recursive:!0,force:!0})}catch{}process.exit(f)},800)}};process.on("SIGINT",()=>d(0)),process.on("SIGTERM",()=>d(0));let u={...process.env};delete u.ANTHROPIC_API_KEY,delete u.ANTHROPIC_API_KEY_OLD,delete u.OPENAI_API_KEY,delete u.DEEPSEEK_API_KEY;try{for(let y of n){let k=Fl(_e(y.dir,"daemon.log"),"a"),b=Ri(process.execPath,[l,"daemon","start","-c",_e(y.dir,"agentx.json")],{cwd:y.dir,env:{...u,MESH_TOKEN:r,AGENTX_DEMO_SCRIPT:_e(y.dir,"demo-script.json")},stdio:["ignore",k,k]});c.push(b),console.log(ae.dim(` \u25B8 ${y.name} starting on 127.0.0.1:${y.port} (log: ${_e(y.dir,"daemon.log")})`))}for(let y of n)await Di(`${y.name} /health`,async()=>(await fetch(`http://127.0.0.1:${y.port}/health`)).ok,3e4);console.log(ae.green(" \u2713 three daemons up"));let f=n[0].port+10;{let y=Fl(_e(n[0].dir,"board.log"),"a"),k=Ri(process.execPath,[l,"board","serve","--bind",e.bind],{cwd:n[0].dir,env:{...u,MESH_TOKEN:r},stdio:["ignore",y,y]});c.push(k)}await Di("dashboard /live",async()=>(await fetch(`http://127.0.0.1:${f}/live`)).ok,3e4),console.log(ae.green(" \u2713 dashboard up")),await Di("mesh discovery (laptop sees both peers)",async()=>((await(await fetch(`http://127.0.0.1:${n[0].port}/health`)).json()).mesh||[]).filter(S=>S.healthy&&S.skills?.length).length>=2,3e4),console.log(ae.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let p=`http://127.0.0.1:${f}/live`;if(console.log(),console.log(` Dashboard: ${ae.cyan(p)} (all three nodes via the mesh)`),console.log(ae.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{Ri(y,[p],{stdio:"ignore",detached:!0}).unref()}catch{}}let w=async()=>{console.log(),console.log(ae.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),ms("You \u2192 @cx (laptop-paris)",Ul,ae.cyan);let y=await _i(n[0].port,"/task",{agent:"cx",message:Ul});ms("@cx (laptop-paris)",y.content||"(no content)",ae.green),console.log(),console.log(ae.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let k=await _i(n[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:$f}),b=typeof k.messageId=="string"?k.messageId:k.content||"(no reply)";ms("@builder (vps-nyc)",b,ae.yellow);let S=await _i(n[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${b}`});ms("@cx (laptop-paris)",S.content||"(no content)",ae.green),console.log(),console.log(ae.dim(` Inspect the run: ${p} \xB7 ledger rows on each node record every dispatch`)),console.log(ae.dim(` Worth your time? A star helps others find it: ${ae.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(i?console.log(ae.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await w(),e.once){console.log(),console.log(ae.dim(" --once: shutting down.")),d(0);return}console.log(),console.log(ae.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(ae.red(` Replay failed: ${y.message}`)))}),process.stdin.resume()}catch(f){console.error(),console.error(ae.red(` Demo failed: ${f.message}`)),console.error(ae.dim(` Node logs: ${n.map(p=>_e(p.dir,"daemon.log")).join(", ")}`)),d(1)}});import{Command as xf}from"commander";import{randomUUID as Sf}from"crypto";import{readFileSync as Ef}from"fs";import{resolve as Af}from"path";me();var Bl=new xf().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||Wl("no task given (pass it as an argument or on stdin)");let n=_(o.config?Af(o.config):void 0),s=n.agents[o.agent];s||Wl(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`);let i=(...l)=>console.error("[agentx exec]",...l);if(o.setupWorkspace){let l=n.node.bind.split(":")[1]||"19900";er(o.agent,s,l,i)}let r=new fr(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-${Sf()}`,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})+`
533
533
  `):c.error?console.error(c.error):process.stdout.write(c.content+`
534
- `),process.exit(c.error?1:0)});function Fl(e){console.error(`agentx exec: ${e}`),process.exit(1)}ge();import{Command as kf}from"commander";import Oe from"chalk";var jo=new kf().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");jo.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 an("/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(Oe.dim(" no chats cached yet"));return}console.log(),console.log(Oe.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?Oe.cyan("group"):Oe.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Oe.dim(n.jid.padEnd(40))} ${Oe.dim(i)}`)}console.log()}catch(o){At(o)}});jo.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 an("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Oe.dim(" no contacts cached yet"));return}console.log(),console.log(Oe.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} ${Oe.dim(i)} ${Oe.dim(n.jid)}`)}console.log()}catch(o){At(o)}});jo.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 Di("/whatsapp/ingest",o);Ri(t,!!e.dryRun)}catch(o){At(o)}});jo.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 Di("/whatsapp/ingest",t);Ri(n,!!o.dryRun)}catch(t){At(t)}});jo.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 Di("/whatsapp/ingest",t);Ri(n,!!o.dryRun)}catch(t){At(t)}});jo.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await an("/whatsapp/state"),o=await an("/whatsapp/chats"),t=await an("/whatsapp/contacts");console.log(),console.log(Oe.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){At(e)}});function Ri(e,o){if(console.log(),console.log(Oe.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(Oe.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(Oe.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(Oe.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(Oe.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Oe.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function ql(){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 an(e){let o=await fetch(`${ql()}${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 Di(e,o){let t=await fetch(`${ql()}${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 At(e){console.error(Oe.red(` ${e.message||e}`)),process.exit(1)}ge();import{Command as vf}from"commander";import ae from"chalk";import{existsSync as xf,mkdirSync as Wl,writeFileSync as cn}from"fs";import{join as Ot,resolve as Sf}from"path";var ln=new vf().name("plugin").description("manage agentx plugins (Move B)");ln.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=_().plugins??[];if(console.log(),o.length===0){console.log(ae.dim(" No plugins configured.")),console.log(ae.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(ae.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${ae.cyan(t)}`);console.log(),console.log(ae.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(ae.red(` ${e.message}`)),process.exitCode=1}});ln.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(ae.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=Sf(o.cwd,t);xf(n)&&!o.force&&(console.log(ae.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),Wl(n,{recursive:!0}),Wl(Ot(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;cn(Ot(n,"package.json"),Tf(e,s)),cn(Ot(n,"tsconfig.json"),If()),cn(Ot(n,"src/index.ts"),jf(e)),cn(Ot(n,"README.md"),Cf(e,s)),cn(Ot(n,".gitignore"),Nf()),console.log(),console.log(ae.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(ae.bold(" Next steps:")),console.log(ae.dim(` cd ${t}`)),console.log(ae.dim(" pnpm install")),console.log(ae.dim(" pnpm build")),console.log(ae.dim(" pnpm link --global # for local testing")),console.log(ae.dim(" # then in your agentx project:")),console.log(ae.dim(` pnpm link --global ${e}`)),console.log(ae.dim(` agentx config set plugins[0] "${e}"`)),console.log(ae.dim(" agentx plugin doctor")),console.log()});ln.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(ae.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await Ef(n);s.kind==="ok"?console.log(` ${ae.green("\u2713")} ${ae.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${ae.red("\u2717")} ${ae.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(ae.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(ae.red(` ${e.message}`)),process.exitCode=1}});async function Ef(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=Af(o);if(!Of(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=qr.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 Af(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 Of(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function Tf(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)+`
535
- `}function If(){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)+`
536
- `}function jf(e){return`// ${e} \u2014 AgentX plugin
534
+ `),process.exit(c.error?1:0)});function Wl(e){console.error(`agentx exec: ${e}`),process.exit(1)}me();import{Command as Of}from"commander";import Te from"chalk";var Co=new Of().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Co.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 cn("/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(Te.dim(" no chats cached yet"));return}console.log(),console.log(Te.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?Te.cyan("group"):Te.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Te.dim(n.jid.padEnd(40))} ${Te.dim(i)}`)}console.log()}catch(o){At(o)}});Co.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 cn("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Te.dim(" no contacts cached yet"));return}console.log(),console.log(Te.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} ${Te.dim(i)} ${Te.dim(n.jid)}`)}console.log()}catch(o){At(o)}});Co.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 Mi("/whatsapp/ingest",o);Pi(t,!!e.dryRun)}catch(o){At(o)}});Co.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 Mi("/whatsapp/ingest",t);Pi(n,!!o.dryRun)}catch(t){At(t)}});Co.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 Mi("/whatsapp/ingest",t);Pi(n,!!o.dryRun)}catch(t){At(t)}});Co.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await cn("/whatsapp/state"),o=await cn("/whatsapp/chats"),t=await cn("/whatsapp/contacts");console.log(),console.log(Te.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){At(e)}});function Pi(e,o){if(console.log(),console.log(Te.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(Te.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(Te.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(Te.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(Te.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Te.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function Jl(){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 cn(e){let o=await fetch(`${Jl()}${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 Mi(e,o){let t=await fetch(`${Jl()}${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 At(e){console.error(Te.red(` ${e.message||e}`)),process.exit(1)}me();import{Command as Tf}from"commander";import ce from"chalk";import{existsSync as jf,mkdirSync as Gl,writeFileSync as ln}from"fs";import{join as Ot,resolve as If}from"path";var dn=new Tf().name("plugin").description("manage agentx plugins (Move B)");dn.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=_().plugins??[];if(console.log(),o.length===0){console.log(ce.dim(" No plugins configured.")),console.log(ce.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(ce.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${ce.cyan(t)}`);console.log(),console.log(ce.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(ce.red(` ${e.message}`)),process.exitCode=1}});dn.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(ce.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=If(o.cwd,t);jf(n)&&!o.force&&(console.log(ce.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),Gl(n,{recursive:!0}),Gl(Ot(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;ln(Ot(n,"package.json"),Df(e,s)),ln(Ot(n,"tsconfig.json"),_f()),ln(Ot(n,"src/index.ts"),Pf(e)),ln(Ot(n,"README.md"),Mf(e,s)),ln(Ot(n,".gitignore"),Lf()),console.log(),console.log(ce.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(ce.bold(" Next steps:")),console.log(ce.dim(` cd ${t}`)),console.log(ce.dim(" pnpm install")),console.log(ce.dim(" pnpm build")),console.log(ce.dim(" pnpm link --global # for local testing")),console.log(ce.dim(" # then in your agentx project:")),console.log(ce.dim(` pnpm link --global ${e}`)),console.log(ce.dim(` agentx config set plugins[0] "${e}"`)),console.log(ce.dim(" agentx plugin doctor")),console.log()});dn.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(ce.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await Cf(n);s.kind==="ok"?console.log(` ${ce.green("\u2713")} ${ce.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${ce.red("\u2717")} ${ce.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(ce.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(ce.red(` ${e.message}`)),process.exitCode=1}});async function Cf(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=Nf(o);if(!Rf(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=Jr.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 Nf(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 Rf(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)+`
535
+ `}function _f(){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)+`
536
+ `}function Pf(e){return`// ${e} \u2014 AgentX plugin
537
537
  //
538
538
  // A plugin's default export is { manifest, setup }. The daemon calls
539
539
  // setup(ctx) once at boot. ctx.on() subscribes to the bus; ctx.addChannel()
@@ -569,7 +569,7 @@ const plugin = {
569
569
  }
570
570
 
571
571
  export default plugin
572
- `}function Cf(e,o){return`# ${e}
572
+ `}function Mf(e,o){return`# ${e}
573
573
 
574
574
  ${o}
575
575
 
@@ -596,19 +596,19 @@ agentx plugin doctor
596
596
  \`\`\`
597
597
 
598
598
  Restart the daemon to activate.
599
- `}function Nf(){return`node_modules/
599
+ `}function Lf(){return`node_modules/
600
600
  dist/
601
601
  *.log
602
602
  .env
603
- `}import{Command as Rf}from"commander";import Te from"chalk";import{writeFileSync as Df,mkdirSync as _f,existsSync as ms,readFileSync as Bl,appendFileSync as Jl}from"fs";import{resolve as Tt,dirname as zl}from"path";import{homedir as Pi}from"os";var Yl=new Rf().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-HGI5C2MP.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Lf(t);break;case"bash":s=Bf(t);break;case"fish":s=Jf(t);break;default:console.error(Te.red(`unsupported shell: ${n}`)),console.error(Te.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?Tt(String(e.output)):Pf(n);_f(zl(i),{recursive:!0}),Df(i,s),console.log(Te.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Mf(n,i,!!e.yes)});function Pf(e){let o=Pi();switch(e){case"zsh":return Tt(o,".zsh","completions","_agentx");case"bash":return Tt(o,".bash_completion.d","agentx.bash");case"fish":return Tt(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Mf(e,o,t){if(e==="zsh"){let n=Tt(Pi(),".zshrc"),s=zl(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=ms(n)?Bl(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Te.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&ms(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Jl(n,g.join(`
603
+ `}import{Command as Ff}from"commander";import je from"chalk";import{writeFileSync as Uf,mkdirSync as qf,existsSync as us,readFileSync as Hl,appendFileSync as zl}from"fs";import{resolve as Tt,dirname as Kl}from"path";import{homedir as Fi}from"os";var Xl=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-4RO4NCBU.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Jf(t);break;case"bash":s=Vf(t);break;case"fish":s=Kf(t);break;default:console.error(je.red(`unsupported shell: ${n}`)),console.error(je.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?Tt(String(e.output)):Wf(n);qf(Kl(i),{recursive:!0}),Uf(i,s),console.log(je.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Bf(n,i,!!e.yes)});function Wf(e){let o=Fi();switch(e){case"zsh":return Tt(o,".zsh","completions","_agentx");case"bash":return Tt(o,".bash_completion.d","agentx.bash");case"fish":return Tt(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Bf(e,o,t){if(e==="zsh"){let n=Tt(Fi(),".zshrc"),s=Kl(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=us(n)?Hl(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(je.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&us(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),zl(n,g.join(`
604
604
  `)+`
605
- `),console.log(Te.green("\u2713 Patched ~/.zshrc")),console.log(Te.dim("Reload your shell: exec zsh"));return}console.log(Te.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Te.cyan(` ${i}`)),l&&console.log(Te.cyan(` ${r}`)),console.log(),console.log(Te.dim("Then reload: exec zsh")),console.log(Te.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Tt(Pi(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((ms(n)?Bl(n,"utf-8"):"").includes(o)){console.log(Te.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&ms(n)){Jl(n,`
605
+ `),console.log(je.green("\u2713 Patched ~/.zshrc")),console.log(je.dim("Reload your shell: exec zsh"));return}console.log(je.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(je.cyan(` ${i}`)),l&&console.log(je.cyan(` ${r}`)),console.log(),console.log(je.dim("Then reload: exec zsh")),console.log(je.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Tt(Fi(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((us(n)?Hl(n,"utf-8"):"").includes(o)){console.log(je.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&us(n)){zl(n,`
606
606
  # agentx completion
607
607
  ${s}
608
- `),console.log(Te.green("\u2713 Patched ~/.bashrc")),console.log(Te.dim("Reload your shell: exec bash"));return}console.log(Te.dim("Add this to ~/.bashrc:")),console.log(Te.cyan(` ${s}`)),console.log(),console.log(Te.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(Te.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function We(e){return e._name||e.name()||""}function Co(e){return e.commands.filter(o=>{let t=We(o);return!(!t||t==="help")})}function dn(e){return e.options.filter(o=>!o.hidden)}function Lf(e){let o=[];return o.push("#compdef agentx"),o.push(""),Vl(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
609
- `)}function Gl(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function Vl(e,o,t){let n=Co(e),i=dn(e).map(qf).filter(c=>!!c),r=Gl(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(Wf).join(" ");a.push(` "1: :_values 'command' ${c}"`),a.push(' "*::arg:->args"')}t.push(" _arguments -C \\");for(let c=0;c<a.length;c++){let l=c===a.length-1;t.push(`${a[c]}${l?"":" \\"}`)}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 l=Gl([...o,We(c)]);t.push(` (${We(c)}) ${l} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)Vl(c,[...o,We(c)],t)}function Ff(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Uf(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function qf(e){let o=e.short||void 0,t=e.long||void 0;if(!o&&!t)return null;let n=Ff(e.description||"");return o&&t?` "(${t} ${o})"{${t},${o}}"[${n}]"`:` "${t||o}[${n}]"`}function Wf(e){let o=Uf(e.description()||"");return`'${We(e)}[${o}]'`}function Bf(e){let o=Co(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(We).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=Co(n).map(We),i=Hl(n);if(t.push(` ${We(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 Co(n)){let a=Hl(r);t.push(` ${We(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(`
610
- `)}function Hl(e){let o=[];for(let t of dn(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function Jf(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 Co(e)){let n=Mi(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${We(t)}" -d "${n}"`)}o.push("");for(let t of dn(e)){let n=_i(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of Co(e)){let n=We(t);o.push(`# ${n}`);for(let s of dn(t)){let i=_i(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of Co(t)){let i=Mi(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${Co(t).map(We).join(" ")}" -a "${We(s)}" -d "${i}"`);for(let r of dn(s)){let a=_i(r,[`__fish_seen_subcommand_from ${We(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
611
- `)}function Mi(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function _i(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=Mi(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 xS(){let e=await ca(),o=new Gf().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=ma(n);pa(s)&&ga("cli",s)});for(let t of[Ma,Da,bt,at,eo,da,Po,_n,go,Jo,Dn,Tl,So,Ya,nc,pc,hc,yc,Dc,Lc,Fc,Yn,Zt,Rl,qt,$o,Yl])o.addCommand(t);for(let t of Kl)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Kl.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Hf(t,74," "),""].join(`
612
- `)}),o}var Kl=[ee,$t,Vo,Qe,Bt,ht,qe,po,Ao,Go,St,Et,xo,Le,Jt,Vn,Al,co,gt,wa,Mo,ln,Us,Io,dt,qs,is,Oo,jo,Ll,Ul,Nl];function Hf(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(`
613
- `)}export{xS as a};
614
- //# sourceMappingURL=chunk-Q3Q6FTFY.js.map
608
+ `),console.log(je.green("\u2713 Patched ~/.bashrc")),console.log(je.dim("Reload your shell: exec bash"));return}console.log(je.dim("Add this to ~/.bashrc:")),console.log(je.cyan(` ${s}`)),console.log(),console.log(je.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(je.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function We(e){return e._name||e.name()||""}function No(e){return e.commands.filter(o=>{let t=We(o);return!(!t||t==="help")})}function gn(e){return e.options.filter(o=>!o.hidden)}function Jf(e){let o=[];return o.push("#compdef agentx"),o.push(""),Ql(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
609
+ `)}function Yl(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function Ql(e,o,t){let n=No(e),i=gn(e).map(zf).filter(c=>!!c),r=Yl(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(Yf).join(" ");a.push(` "1: :_values 'command' ${c}"`),a.push(' "*::arg:->args"')}t.push(" _arguments -C \\");for(let c=0;c<a.length;c++){let l=c===a.length-1;t.push(`${a[c]}${l?"":" \\"}`)}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 l=Yl([...o,We(c)]);t.push(` (${We(c)}) ${l} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)Ql(c,[...o,We(c)],t)}function Gf(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Hf(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function zf(e){let o=e.short||void 0,t=e.long||void 0;if(!o&&!t)return null;let n=Gf(e.description||"");return o&&t?` "(${t} ${o})"{${t},${o}}"[${n}]"`:` "${t||o}[${n}]"`}function Yf(e){let o=Hf(e.description()||"");return`'${We(e)}[${o}]'`}function Vf(e){let o=No(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(We).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=No(n).map(We),i=Vl(n);if(t.push(` ${We(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 No(n)){let a=Vl(r);t.push(` ${We(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(`
610
+ `)}function Vl(e){let o=[];for(let t of gn(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function Kf(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 No(e)){let n=Ui(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${We(t)}" -d "${n}"`)}o.push("");for(let t of gn(e)){let n=Li(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of No(e)){let n=We(t);o.push(`# ${n}`);for(let s of gn(t)){let i=Li(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of No(t)){let i=Ui(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${No(t).map(We).join(" ")}" -a "${We(s)}" -d "${i}"`);for(let r of gn(s)){let a=Li(r,[`__fish_seen_subcommand_from ${We(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
611
+ `)}function Ui(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Li(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=Ui(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 NS(){let e=await ga(),o=new Xf().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=fa(n);ha(s)&&ua("cli",s)});for(let t of[Ua,Ma,bt,at,eo,pa,Mo,Pn,go,Go,_n,Cl,So,Xa,rc,hc,bc,$c,Mc,qc,Wc,Vn,en,Pl,Wt,$o,Xl])o.addCommand(t);for(let t of Zl)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Zl.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Qf(t,74," "),""].join(`
612
+ `)}),o}var Zl=[ee,$t,Io,Qe,Jt,ht,qe,po,Ao,Ho,St,Et,xo,Le,Gt,Kn,jl,co,gt,ka,Lo,dn,Ws,jo,dt,Bs,rs,Oo,Co,ql,Bl,_l];function Qf(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(`
613
+ `)}export{NS as a};
614
+ //# sourceMappingURL=chunk-DYSVG6T3.js.map