agentix-cli 0.34.0 → 0.35.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 (88) hide show
  1. package/apps/mac-helper/Sources/AgentXHelper/Presence.swift +266 -0
  2. package/apps/mac-helper/Sources/AgentXHelper/main.swift +7 -1
  3. package/apps/mac-voice/Sources/AgentXVoice/AgentClient.swift +6 -1
  4. package/apps/mac-voice/Sources/AgentXVoice/main.swift +3 -0
  5. package/dist/{App-QHPZXA42.js → App-K5J52F7O.js} +2 -2
  6. package/dist/{ChatApp-EAHHH365.js → ChatApp-LRRAPZH7.js} +2 -2
  7. package/dist/{agent-KBBO7OZS.js → agent-XEXAYH5J.js} +2 -2
  8. package/dist/{board-dashboard-74OLMLAD.js → board-dashboard-CBOESBMD.js} +4 -4
  9. package/dist/{chunk-X6HLI6XB.js → chunk-3PL3WLIR.js} +2 -2
  10. package/dist/{chunk-JDC35PWM.js → chunk-3TNK7VGH.js} +2 -2
  11. package/dist/{chunk-ZMFUBIEQ.js → chunk-4QNZI4WE.js} +5 -5
  12. package/dist/{chunk-33G4TIZT.js → chunk-DXXWYYZI.js} +204 -187
  13. package/dist/chunk-DXXWYYZI.js.map +1 -0
  14. package/dist/{chunk-5H5L75RN.js → chunk-FLNN3KSX.js} +2 -2
  15. package/dist/{chunk-PG7BAZIZ.js → chunk-GYBYKREN.js} +2 -2
  16. package/dist/{chunk-6WGTLDME.js → chunk-HPY6OOFO.js} +137 -146
  17. package/dist/chunk-HPY6OOFO.js.map +1 -0
  18. package/dist/{chunk-IUNCX6BG.js → chunk-JSZRGMSA.js} +2 -2
  19. package/dist/chunk-LA6AKS4N.js +13 -0
  20. package/dist/chunk-LA6AKS4N.js.map +1 -0
  21. package/dist/{chunk-UJF5JUFJ.js → chunk-LLKILWWO.js} +2 -2
  22. package/dist/{chunk-QXAUKNMW.js → chunk-LQFEH3SA.js} +2 -2
  23. package/dist/{chunk-MJYE5ADH.js → chunk-PBVEYPZB.js} +2 -2
  24. package/dist/{chunk-U5P7XGCB.js → chunk-SYJUZ3F2.js} +2 -2
  25. package/dist/{chunk-QKNAGTJK.js → chunk-WEN2P4RS.js} +2 -2
  26. package/dist/{chunk-CY24RXE4.js → chunk-WRBW4A2U.js} +2 -2
  27. package/dist/{chunk-IVAGDL5M.js → chunk-ZSNTLADV.js} +2 -2
  28. package/dist/cli.js +1 -1
  29. package/dist/client-APAWETTA.js +2 -0
  30. package/dist/config-S3VHHVYW.js +2 -0
  31. package/dist/config-mutator-5B2YWZMK.js +2 -0
  32. package/dist/doctor-SCECRUJ7.js +2 -0
  33. package/dist/index.d.ts +84 -0
  34. package/dist/index.js +1 -1
  35. package/dist/program-XJEQAWN3.js +2 -0
  36. package/dist/query-EDW72Q4O.js +2 -0
  37. package/dist/{registry-3RN7I6YW.js → registry-GWN34G4J.js} +2 -2
  38. package/dist/{request-planner-JX7M3PTD.js → request-planner-V7T6BQU7.js} +2 -2
  39. package/dist/{review-candidates-UTS4RX4U.js → review-candidates-7QKNMRGU.js} +2 -2
  40. package/dist/{routing-D7APOAP6.js → routing-BHQXFUSH.js} +2 -2
  41. package/dist/scheduler-LY4RBPB6.js +2 -0
  42. package/dist/{seat-UA2ROH3V.js → seat-U57NWHKC.js} +2 -2
  43. package/dist/{select-WQXHYEPD.js → select-JL3JJJP4.js} +2 -2
  44. package/dist/wiki-AQ4K3F7V.js +2 -0
  45. package/package.json +1 -1
  46. package/dist/chunk-33G4TIZT.js.map +0 -1
  47. package/dist/chunk-6WGTLDME.js.map +0 -1
  48. package/dist/chunk-SPJWXIAV.js +0 -13
  49. package/dist/chunk-SPJWXIAV.js.map +0 -1
  50. package/dist/client-CAGQYJML.js +0 -2
  51. package/dist/config-NPLE42XY.js +0 -2
  52. package/dist/config-mutator-FFTODESU.js +0 -2
  53. package/dist/doctor-X4KHQFRF.js +0 -2
  54. package/dist/program-ISXECD4J.js +0 -2
  55. package/dist/query-XLJ6I34S.js +0 -2
  56. package/dist/scheduler-EGR5AJAQ.js +0 -2
  57. package/dist/wiki-RNANPNUX.js +0 -2
  58. /package/dist/{App-QHPZXA42.js.map → App-K5J52F7O.js.map} +0 -0
  59. /package/dist/{ChatApp-EAHHH365.js.map → ChatApp-LRRAPZH7.js.map} +0 -0
  60. /package/dist/{agent-KBBO7OZS.js.map → agent-XEXAYH5J.js.map} +0 -0
  61. /package/dist/{board-dashboard-74OLMLAD.js.map → board-dashboard-CBOESBMD.js.map} +0 -0
  62. /package/dist/{chunk-X6HLI6XB.js.map → chunk-3PL3WLIR.js.map} +0 -0
  63. /package/dist/{chunk-JDC35PWM.js.map → chunk-3TNK7VGH.js.map} +0 -0
  64. /package/dist/{chunk-ZMFUBIEQ.js.map → chunk-4QNZI4WE.js.map} +0 -0
  65. /package/dist/{chunk-5H5L75RN.js.map → chunk-FLNN3KSX.js.map} +0 -0
  66. /package/dist/{chunk-PG7BAZIZ.js.map → chunk-GYBYKREN.js.map} +0 -0
  67. /package/dist/{chunk-IUNCX6BG.js.map → chunk-JSZRGMSA.js.map} +0 -0
  68. /package/dist/{chunk-UJF5JUFJ.js.map → chunk-LLKILWWO.js.map} +0 -0
  69. /package/dist/{chunk-QXAUKNMW.js.map → chunk-LQFEH3SA.js.map} +0 -0
  70. /package/dist/{chunk-MJYE5ADH.js.map → chunk-PBVEYPZB.js.map} +0 -0
  71. /package/dist/{chunk-U5P7XGCB.js.map → chunk-SYJUZ3F2.js.map} +0 -0
  72. /package/dist/{chunk-QKNAGTJK.js.map → chunk-WEN2P4RS.js.map} +0 -0
  73. /package/dist/{chunk-CY24RXE4.js.map → chunk-WRBW4A2U.js.map} +0 -0
  74. /package/dist/{chunk-IVAGDL5M.js.map → chunk-ZSNTLADV.js.map} +0 -0
  75. /package/dist/{client-CAGQYJML.js.map → client-APAWETTA.js.map} +0 -0
  76. /package/dist/{config-NPLE42XY.js.map → config-S3VHHVYW.js.map} +0 -0
  77. /package/dist/{config-mutator-FFTODESU.js.map → config-mutator-5B2YWZMK.js.map} +0 -0
  78. /package/dist/{doctor-X4KHQFRF.js.map → doctor-SCECRUJ7.js.map} +0 -0
  79. /package/dist/{program-ISXECD4J.js.map → program-XJEQAWN3.js.map} +0 -0
  80. /package/dist/{query-XLJ6I34S.js.map → query-EDW72Q4O.js.map} +0 -0
  81. /package/dist/{registry-3RN7I6YW.js.map → registry-GWN34G4J.js.map} +0 -0
  82. /package/dist/{request-planner-JX7M3PTD.js.map → request-planner-V7T6BQU7.js.map} +0 -0
  83. /package/dist/{review-candidates-UTS4RX4U.js.map → review-candidates-7QKNMRGU.js.map} +0 -0
  84. /package/dist/{routing-D7APOAP6.js.map → routing-BHQXFUSH.js.map} +0 -0
  85. /package/dist/{scheduler-EGR5AJAQ.js.map → scheduler-LY4RBPB6.js.map} +0 -0
  86. /package/dist/{seat-UA2ROH3V.js.map → seat-U57NWHKC.js.map} +0 -0
  87. /package/dist/{select-WQXHYEPD.js.map → select-JL3JJJP4.js.map} +0 -0
  88. /package/dist/{wiki-RNANPNUX.js.map → wiki-AQ4K3F7V.js.map} +0 -0
@@ -1,45 +1,34 @@
1
- import{a as Ar,b as an,g as Or}from"./chunk-IVAGDL5M.js";import{b as kr}from"./chunk-CY24RXE4.js";import{a as Ko,b as $r,f as rn,j as Er}from"./chunk-U5P7XGCB.js";import{a as vr,c as xr,d as Sr}from"./chunk-2TJ5L7CB.js";import{a as Yo}from"./chunk-GV7S5BAX.js";import{e as Ri}from"./chunk-GSX4NK2N.js";import{c as Ni}from"./chunk-SZDACK6O.js";import{A as xt,B as dr,C as gr,D as mr,E as pr,F as ur,G as yr,H as is,I as rs,J as wr,K as br,a as Wi,b as Bi,h as zi,i as Yi,j as vt,k as sn,l as Ki,m as Vi,n as Xi,o as Qi,p as Zi,q as er,r as or,s as tr,t as nr,u as sr,v as ir,w as rr,x as ar,y as cr,z as lr}from"./chunk-33G4TIZT.js";import{i as fr,j as ns,k as hr,l as ss}from"./chunk-F6CNF7V3.js";import{a as Ji,d as Hi,e as Gi}from"./chunk-X6HLI6XB.js";import{J as qi,m as Ii,o as Ho,q as es,r as ji,t as go,z as Fi}from"./chunk-ZMFUBIEQ.js";import{b as Go,c as tn,d as nn,e as zo,f as Ti,g as Oo,h as kt}from"./chunk-5H5L75RN.js";import{d as ts,f as Mi}from"./chunk-VMDA2SX2.js";import{a as Li}from"./chunk-QLTM3F7M.js";import{a as Ci,e as Pi}from"./chunk-UJF5JUFJ.js";import{f as _i,g as Di,h as os}from"./chunk-76Z4VHDX.js";import{a as de,b as we,c as Io,d as Ui}from"./chunk-MJYE5ADH.js";import{h as Oi}from"./chunk-DWADWDMU.js";import{b as lo,d as on,f as Zn}from"./chunk-PG7BAZIZ.js";import{b as Jo,d as Ai}from"./chunk-2GIDVZ4H.js";import{a as Qn,b as ui,c as tl,d as Zt,e as fi,f as $i,g as sl,h as ki,i as il,m as Bo,n as xi,o as Si,s as Ei,v as Ke,w as $t}from"./chunk-QXAUKNMW.js";import{a as vi,b as rl}from"./chunk-AJONZWLT.js";import{a as no,b as Wo,e as yi,f as bt}from"./chunk-F4HZTZHW.js";import{a as to,b as ol}from"./chunk-L2WSPY6S.js";import{f as hi,g as L,h as en,j as ve}from"./chunk-SPJWXIAV.js";import{g as wi,k as bi,l as nl}from"./chunk-BH3GTCZ6.js";import{a as el}from"./chunk-FIOB3MEX.js";import{Command as al}from"commander";var Ir=new al().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 Bi({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()});ve();import{Command as ll}from"commander";import{execFileSync as so}from"node:child_process";import{cpSync as _r,existsSync as gs,mkdirSync as ls,mkdtempSync as dl,readFileSync as gl,rmSync as ml,writeFileSync as Dr}from"node:fs";import{dirname as ds,join as Ie,resolve as Pr}from"node:path";import{homedir as dn,release as pl,tmpdir as ul}from"node:os";import{fileURLToPath as fl}from"node:url";import{setTimeout as hl}from"node:timers/promises";import{existsSync as cl}from"node:fs";import{join as Cr}from"node:path";var cn="tn.acme.agentx.voice",ln="AgentX Desktop.app",St="AgentX Helper.app";function jr(e,o,t){return e!=="darwin"||o!=="arm64"||Number(t.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function Tr(e,o){if(o&&!Object.hasOwn(e,o))throw new Error(`Unknown agent: ${o}. Run agentx agent list.`);let t=o||Object.keys(e)[0];if(!t)throw new Error("No agents configured. Run agentx setup first.");return t}function as(e){return`'${e.replace(/'/g,"'\\''")}'`}function Rr(e){let o=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),t={AGENTX_VOICE_AGENT:e.agent,AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${as(e.cwd)} && ${as(e.node)} ${as(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
2
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
- <plist version="1.0"><dict>
4
- <key>Label</key><string>${cn}</string>
5
- <key>ProgramArguments</key><array><string>${o(e.executable)}</string></array>
6
- <key>WorkingDirectory</key><string>${o(e.cwd)}</string>
7
- <key>EnvironmentVariables</key><dict>${Object.entries(t).map(([n,s])=>`<key>${n}</key><string>${o(s)}</string>`).join("")}</dict>
8
- <key>RunAtLoad</key><true/><key>KeepAlive</key><true/>
9
- <key>ProcessType</key><string>Interactive</string>
10
- <key>StandardErrorPath</key><string>${o(e.log)}</string>
11
- </dict></plist>
12
- `}function cs(e){return Cr(e,"Applications",St,"Contents/MacOS/agentx-mac-helper")}function Nr(e,o,t){if(t)return t;let n=cs(o);return cl(n)?n:Cr(e,"apps/mac-helper/build/AgentX Helper.app/Contents/MacOS/agentx-mac-helper")}function gn(){let e=jr(process.platform,process.arch,pl());if(e)throw new Error(e)}function Et(){return`gui/${process.getuid()}/${cn}`}function Vo(){return Ie(dn(),"Library/LaunchAgents",`${cn}.plist`)}async function Lr(){try{so("launchctl",["bootout",Et()],{stdio:"pipe"})}catch{}for(let e=0;e<30;e++){try{so("launchctl",["print",Et()],{stdio:"pipe"})}catch{return}await hl(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Mr(){if(!gs(Vo()))throw new Error("Run agentx desktop install first.");let e=!0;try{so("launchctl",["print",Et()],{stdio:"pipe"})}catch{e=!1}e||so("launchctl",["bootstrap",`gui/${process.getuid()}`,Vo()],{stdio:"pipe"}),so("launchctl",["kickstart",Et()],{stdio:"pipe"})}function yl(){let e=ds(fl(import.meta.url));for(let o of[Pr(e,".."),Pr(e,"../.."),process.cwd()])try{if(JSON.parse(gl(Ie(o,"package.json"),"utf8")).name==="agentix-cli"&&gs(Ie(o,"apps/mac-voice/build.sh")))return o}catch{}throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var Xo=new ll("desktop").description("install and control the macOS desktop assistant");Xo.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=>{gn();let o=L(),t=Tr(o.agents,e.agent),n=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,s=yl(),i=Ie(dn(),"Applications");if(console.log(`Desktop assistant \u2192 ${Ie(i,ln)}
13
- Computer-use helper \u2192 ${Ie(i,St)}
1
+ import{a as Dr,b as pn,g as Pr}from"./chunk-ZSNTLADV.js";import{b as Cr}from"./chunk-WRBW4A2U.js";import{a as Vo,b as jr,f as mn,j as _r}from"./chunk-SYJUZ3F2.js";import{a as Tr,c as Nr,d as Rr}from"./chunk-2TJ5L7CB.js";import{a as Ko}from"./chunk-GV7S5BAX.js";import{e as Di}from"./chunk-GSX4NK2N.js";import{c as Pi}from"./chunk-SZDACK6O.js";import{A as St,B as rn,C as pr,D as ur,E as an,F as cn,G as fr,H as hr,I as rs,J as ln,K as dn,L as yr,M as wr,N as br,O as $r,P as Se,Q as gn,R as Et,S as as,T as kr,U as vr,V as xr,W as Ar,X as ds,Y as gs,Z as Or,_ as Ir,a as Hi,b as Gi,h as Vi,i as Xi,j as xt,k as sn,l as Qi,m as Zi,n as er,o as or,p as tr,q as nr,r as sr,s as ir,t as rr,u as ar,v as cr,w as lr,x as dr,y as gr,z as mr}from"./chunk-DXXWYYZI.js";import{i as Sr,j as cs,k as Er,l as ls}from"./chunk-F6CNF7V3.js";import{a as zi,d as Yi,e as Ki}from"./chunk-3PL3WLIR.js";import{J as Ji,m as Ti,o as Go,q as ns,r as Ri,t as mo,z as Bi}from"./chunk-4QNZI4WE.js";import{b as zo,c as tn,d as nn,e as Yo,f as _i,g as Io,h as vt}from"./chunk-FLNN3KSX.js";import{d as is,f as qi}from"./chunk-VMDA2SX2.js";import{a as Fi}from"./chunk-QLTM3F7M.js";import{a as Ni,e as Ui}from"./chunk-LLKILWWO.js";import{f as Li,g as Mi,h as ss}from"./chunk-76Z4VHDX.js";import{a as de,b as be,c as jo,d as Wi}from"./chunk-PBVEYPZB.js";import{h as Ci}from"./chunk-DWADWDMU.js";import{b as go,d as on,f as ts}from"./chunk-GYBYKREN.js";import{b as Ho,d as ji}from"./chunk-2GIDVZ4H.js";import{a as os,b as yi,c as rl,d as Zt,e as wi,f as xi,g as cl,h as Si,i as ll,m as Jo,n as Ai,o as Oi,s as Ii,v as Ke,w as kt}from"./chunk-LQFEH3SA.js";import{a as Ei,b as dl}from"./chunk-AJONZWLT.js";import{a as so,b as Bo,e as $i,f as $t}from"./chunk-F4HZTZHW.js";import{a as no,b as il}from"./chunk-L2WSPY6S.js";import{f as bi,g as D,h as en,j as we}from"./chunk-LA6AKS4N.js";import{g as ki,k as vi,l as al}from"./chunk-BH3GTCZ6.js";import{a as sl}from"./chunk-FIOB3MEX.js";import{Command as gl}from"commander";var Lr=new gl().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 Gi({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});we();import{Command as ml}from"commander";import{execFileSync as io}from"node:child_process";import{cpSync as Mr,existsSync as us,mkdirSync as ms,mkdtempSync as pl,readFileSync as ul,rmSync as fl,writeFileSync as Ur}from"node:fs";import{dirname as ps,join as Ie,resolve as Fr}from"node:path";import{homedir as un,release as hl,tmpdir as yl}from"node:os";import{fileURLToPath as wl}from"node:url";import{setTimeout as bl}from"node:timers/promises";function fn(){let e=yr(process.platform,process.arch,hl());if(e)throw new Error(e)}function At(){return`gui/${process.getuid()}/${rs}`}function Xo(){return Ie(un(),"Library/LaunchAgents",`${rs}.plist`)}async function qr(){try{io("launchctl",["bootout",At()],{stdio:"pipe"})}catch{}for(let e=0;e<30;e++){try{io("launchctl",["print",At()],{stdio:"pipe"})}catch{return}await bl(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Wr(){if(!us(Xo()))throw new Error("Run agentx desktop install first.");let e=!0;try{io("launchctl",["print",At()],{stdio:"pipe"})}catch{e=!1}e||io("launchctl",["bootstrap",`gui/${process.getuid()}`,Xo()],{stdio:"pipe"}),io("launchctl",["kickstart",At()],{stdio:"pipe"})}function $l(){let e=ps(wl(import.meta.url));for(let o of[Fr(e,".."),Fr(e,"../.."),process.cwd()])try{if(JSON.parse(ul(Ie(o,"package.json"),"utf8")).name==="agentix-cli"&&us(Ie(o,"apps/mac-voice/build.sh")))return o}catch{}throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var Qo=new ml("desktop").description("install and control the macOS desktop assistant");Qo.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=>{fn();let o=D(),t=wr(o.agents,e.agent),n=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,s=$l(),i=Ie(un(),"Applications");if(console.log(`Desktop assistant \u2192 ${Ie(i,ln)}
2
+ Computer-use helper \u2192 ${Ie(i,dn)}
14
3
  Agent \u2192 ${t}
15
4
  Daemon \u2192 ${n}
16
- Starts at login \u2192 ${Vo()}`),e.dryRun)return;try{so("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=dl(Ie(ul(),"agentx-desktop-"));try{for(let g of["mac-helper","mac-voice"])_r(Ie(s,"apps",g),Ie(r,g),{recursive:!0,filter:l=>!l.split("/").includes("build")}),so("/bin/bash",[Ie(r,g,"build.sh")],{stdio:"inherit"});let a=Ie(dn(),"Library/Logs/agentx-desktop.err.log"),c=Rr({executable:Ie(i,ln,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:t,url:n,helper:cs(dn()),cli:Ie(s,"dist/cli.js"),node:process.execPath,log:a}),d=Ie(r,"desktop.plist");Dr(d,c,{mode:384}),so("plutil",["-lint",d],{stdio:"pipe"}),await Lr(),ls(i,{recursive:!0});for(let[g,l,u]of[["mac-voice","AgentX Voice.app",ln],["mac-helper",St,St]])_r(Ie(r,g,"build",l),Ie(i,u),{recursive:!0});ls(ds(Vo()),{recursive:!0}),ls(ds(a),{recursive:!0}),Dr(Vo(),c,{mode:384}),Mr(),console.log(`Desktop assistant is running. Hold Option\u2013Space to speak; Command\u2013Option\u2013V for smart paste.
5
+ Starts at login \u2192 ${Xo()}`),e.dryRun)return;try{io("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=pl(Ie(yl(),"agentx-desktop-"));try{for(let m of["mac-helper","mac-voice"])Mr(Ie(s,"apps",m),Ie(r,m),{recursive:!0,filter:l=>!l.split("/").includes("build")}),io("/bin/bash",[Ie(r,m,"build.sh")],{stdio:"inherit"});let a=Ie(un(),"Library/Logs/agentx-desktop.err.log"),c=br({executable:Ie(i,ln,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:t,url:n,helper:$r(un()),cli:Ie(s,"dist/cli.js"),node:process.execPath,log:a}),d=Ie(r,"desktop.plist");Ur(d,c,{mode:384}),io("plutil",["-lint",d],{stdio:"pipe"}),await qr(),ms(i,{recursive:!0});for(let[m,l,u]of[["mac-voice","AgentX Voice.app",ln],["mac-helper",dn,dn]])Mr(Ie(r,m,"build",l),Ie(i,u),{recursive:!0});ms(ps(Xo()),{recursive:!0}),ms(ps(a),{recursive:!0}),Ur(Xo(),c,{mode:384}),Wr(),console.log(`Desktop assistant is running. Hold Option\u2013Space to speak; Command\u2013Option\u2013V for smart paste.
17
6
  Allow Microphone for the app and Accessibility / Screen Recording for the helper when macOS asks.
18
- The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{ml(r,{recursive:!0,force:!0})}});Xo.command("start").description("start the installed desktop assistant").action(()=>{gn(),Mr(),console.log("Desktop assistant started.")});Xo.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{gn(),await Lr(),console.log("Desktop assistant stopped.")});Xo.command("status").description("show the desktop login service status").action(()=>{gn();try{console.log(so("launchctl",["print",Et()],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(gs(Vo())?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as xl}from"commander";import{open as Sl}from"fs/promises";import{existsSync as un,mkdirSync as wl,readFileSync as fn,writeFileSync as Ur}from"fs";import{homedir as bl}from"os";import{dirname as $l,resolve as ms}from"path";var ps="/attach/",Fr="/guard/check";function qr(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 mn(e,o,t){let n={hooks:[{type:"command",command:qr(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function kl(e){return{SessionStart:[mn("/attach/session-start",e,"")],UserPromptSubmit:[mn("/attach/prompt",e)],Stop:[mn("/attach/stop",e)],SessionEnd:[mn("/attach/session-end",e)]}}function vl(e){let o=qr("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function pn(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function At(){return ms(bl(),".claude/settings.json")}function Ot(e=process.cwd()){for(let o of[e,ms(e,"..")]){let t=ms(o,"agentx.json");if(un(t))try{let n=JSON.parse(fn(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function Wr(e,o={}){let t=o.path??At(),n=o.withGuard!==!1,s={};if(un(t))try{s=JSON.parse(fn(t,"utf-8"))}catch(g){throw new Error(`${t} is not valid JSON (${g?.message}) \u2014 refusing to overwrite it`)}let i=JSON.stringify(s),r=s.hooks??={},a=[];for(let[g,l]of Object.entries(kl(e))){let u=Array.isArray(r[g])?r[g].filter(f=>!pn(f,ps)):[];r[g]=[...u,...l],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(l=>!pn(l,Fr)):[];r.PreToolUse=[...g,...vl(e)],c=!0}let d=JSON.stringify(s)!==i;return d&&(wl($l(t),{recursive:!0}),Ur(t,`${JSON.stringify(s,null,2)}
19
- `)),{path:t,changed:d,events:a,guardInstalled:c}}function Br(e={}){let o=e.path??At();if(!un(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(fn(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"?Fr:ps;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let d=s[a].filter(g=>!pn(g,c));d.length!==s[a].length&&i.push(a),d.length===0?delete s[a]:s[a]=d}Object.keys(s).length===0&&delete t.hooks}let r=JSON.stringify(t)!==n;return r&&Ur(o,`${JSON.stringify(t,null,2)}
20
- `),{path:o,changed:r,events:i,guardInstalled:!1}}function hn(e=At()){if(!un(e))return!1;try{return!!JSON.parse(fn(e,"utf-8"))?.hooks?.Stop?.some?.(t=>pn(t,ps))}catch{return!1}}var yn=new xl("monitor").description("Register external CLI sessions and report ended runs to the briefing"),Jr=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Ot()}`;async function Hr(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)}`)}yn.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",Jr).action(async e=>{try{await Hr(e.url,"register",Hi.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}});yn.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",Jr).action(async e=>{try{let o=await Sl(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]
21
- `:"")+i.subarray(0,r).toString("utf8")}finally{await o.close()}await Hr(e.url,"ended",Gi.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 xu}from"commander";import{Command as El}from"commander";ve();import O from"chalk";import{existsSync as Al,readFileSync as Ol}from"fs";async function Il(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 Ve=new El().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");Ve.command("start").description("start the daemon (default if no subcommand)").option("-c, --config <path>","path to agentx.json").option("-d, --detach","run in background (detached)").option("--port <port>","override bind port").action(async e=>{if(e.detach){let{spawn:d}=await import("child_process"),{openSync:g,writeFileSync:l,existsSync: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 $=d(process.execPath,p,{detached:!0,stdio:["ignore",y,y],cwd:process.cwd()});$.unref(),l("/tmp/agentx-daemon.pid",String($.pid)),console.log(O.green(`Daemon started in background (PID: ${$.pid})`)),console.log(O.dim(` Logs: tail -f ${w}`)),console.log(O.dim(" Stop: agentx daemon stop")),await new Promise(b=>setTimeout(b,1e3));try{process.kill($.pid,0)}catch{console.log(),console.log(O.yellow(` Daemon exited within 1s \u2014 check ${w} for the error:`)),console.log(O.dim(` tail -n 40 ${w}`))}return}let{readFileSync:o,writeFileSync:t,mkdirSync:n,existsSync:s}=await import("fs"),{resolve:i}=await import("path"),r=i(process.cwd(),".agentx");s(r)||n(r,{recursive:!0});let a=i(r,"daemon.pid");if(s(a)){let d=parseInt(o(a,"utf-8").trim(),10);if(d&&d!==process.pid){let g=!1;try{process.kill(d,0),g=!0}catch{}g&&await Il(d)&&(console.error(`Another agentx daemon is already running (PID ${d}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{Cl(i(process.cwd(),".env"))}catch{}await new rs(e.config).start()});function Cl(e){if(!Al(e))return;let o=Ol(e,"utf-8");for(let t of o.split(`
22
- `)){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}}Ve.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"))}});Ve.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=L(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 ${jl(r.uptime)}`)),console.log(),console.log(O.bold(" Agents:"));for(let c of r.agents){let d=c.active>0?O.yellow(` [${c.active} active]`):"",g=c.errors>0?O.red(` (${c.errors} errors)`):"";console.log(` ${O.cyan(c.name)} ${O.dim(`(${c.tier})`)}${d}${g}`),console.log(O.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(O.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let d=c.enabled?O.green("\u25CF"):O.dim("\u25CB"),g=c.nextRun?O.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${d} ${c.id}${g}`)}}if(r.mesh?.length){console.log(),console.log(O.bold(" Mesh:"));for(let c of r.mesh){let d=c.healthy?O.green("\u25CF"):O.red("\u25CF"),g=c.skills?.length?O.dim(` (${c.skills.length} agents)`):"";console.log(` ${d} ${c.peer} ${O.dim(c.peerUrl)}${g}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError")console.log(O.red(" Daemon is not running")),console.log(O.dim(" Start with: agentx daemon start"));else try{let t=L(e.config),n=en(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}`))}}});Ve.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"})});Ve.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(L(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
23
- `));try{let s=await fetch(n);if(!s.ok||!s.body){console.log(O.red(` Failed: ${s.status}`));return}let i=s.body.getReader(),r=new TextDecoder,a="";for(;;){let{done:c,value:d}=await i.read();if(c)break;a+=r.decode(d,{stream:!0});let g=a.split(`
24
- `);a=g.pop()||"";for(let l of g)if(l.startsWith("data: "))try{let u=JSON.parse(l.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 l.startsWith("event: status")}}catch(s){console.log(O.red(` Connection failed: ${s.message}`)),console.log(O.dim(" Is the daemon running? Diagnostic order:")),console.log(O.dim(" 1) agentx daemon status # is the daemon up?")),console.log(O.dim(" 2) tail -n 60 /tmp/agentx-daemon.log # detach-mode crash log")),console.log(O.dim(" 3) journalctl -u agentx -n 60 # systemd-managed installs")),console.log(O.dim(" If the log file is missing, the daemon never started \u2014 re-run without --detach")),console.log(O.dim(" to see the error in the foreground."))}});Ve.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=L(t.config),[i,r]=s.node.bind.split(":"),a=`http://${i||"127.0.0.1"}:${r}`,c,d;t.peer?(c=`${a}/mesh/task`,d={peer:t.peer,message:n,agent:e}):(c=`${a}/task`,d={agent:e,message:n}),console.log(O.dim(` Sending to ${t.peer?`${t.peer}/${e}`:e}...`));let l=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)})).json();t.json?console.log(JSON.stringify(l,null,2)):l.error?console.log(O.red(` Error: ${l.error}`)):(console.log(),console.log(l.content||l.response||"No response"),l.duration&&console.log(O.dim(`
25
- (${(l.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(O.red(` Failed: ${s.message}`)),console.log(O.dim(" Is the daemon running? Try: agentx daemon status"))}});Ve.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}`))}});Ve.action(async e=>{await new rs(e.config).start()});function jl(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 Tl}from"commander";import Je from"chalk";import{existsSync as It,readFileSync as Rl,writeFileSync as Gr,mkdirSync as zr}from"fs";import{hostname as Yr}from"os";import{resolve as Qo}from"path";var Kr=new Tl().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=Qo(o,"agentx.json"),n=Qo(o,".env"),s=Qo(o,".agentx/sessions");if(console.log(),console.log(Je.bold(" agentx init")),console.log(),It(t)&&!e.force){console.log(Je.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[Qo(o,"agentx.example.json"),Qo(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(It(c)){r=Rl(c,"utf-8");break}r||(r=JSON.stringify({node:{id:Yr().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:Yr(),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)),Gr(t,r),console.log(Je.green(" \u2713 Created agentx.json")),It(n)||(Gr(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
26
- `)),console.log(Je.green(" \u2713 Created .env template"))),It(s)||(zr(s,{recursive:!0}),console.log(Je.green(" \u2713 Created .agentx/sessions/")));let a=Qo(o,".claude");It(a)||(zr(a,{recursive:!0}),console.log(Je.green(" \u2713 Created .claude/"))),console.log(),console.log(Je.bold(" Next steps:")),console.log(` 1. Edit ${Je.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${Je.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${Je.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${Je.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as Nl}from"commander";import Co from"chalk";import{spawn as Xr}from"child_process";import{existsSync as _l}from"fs";import{dirname as Dl,resolve as Pl}from"path";import{fileURLToPath as Ll}from"url";ve();var Qr=new Nl().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=$r(),t=e.port?parseInt(e.port,10):Ml(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(Co.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(Co.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(Co.bold(` Opening ${n}`)),console.log(),await Fl(n).catch(()=>!1))console.log(Co.dim(" Dashboard is already running.")),e.open!==!1&&Vr(n);else{console.log(Co.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=Ul(),r=Xr(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&Vr(n),await new Promise(a=>r.on("exit",()=>a()))}});function Ml(){try{return L().dashboard.port||4202}catch{return 4202}}function Ul(){let e=Pl(Dl(Ll(import.meta.url)),"cli.js");return _l(e)?e:process.argv[1]||e}async function Fl(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}function Vr(e){let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=Xr(o,[e],{stdio:"ignore",detached:!0});t.once("error",()=>{console.log(Co.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),t.unref()}catch{console.log(Co.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as ql}from"commander";import xe from"chalk";var Ct=new ql().name("token").description("scoped API tokens for external access (mesh peers, integrations)");Ct.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 rn,t=String(e.scope).split(",").map(r=>r.trim()).filter(Boolean),n=e.expires?parseInt(e.expires,10):void 0;if(e.expires&&(!n||n<1))throw new Error("--expires must be a positive integer (days)");let{token:s,record:i}=o.create({name:e.name,scopes:t,expiresInDays:n});console.log(),console.log(xe.bold(" Token created.")),console.log(),console.log(` id: ${xe.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||xe.dim("never")}`),console.log(),console.log(xe.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${xe.green.bold(s)}`),console.log(),console.log(xe.dim(" Use it via the Authorization header:")),console.log(xe.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});Ct.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new rn().list();if(e.length===0){console.log(xe.dim(`
7
+ The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{fl(r,{recursive:!0,force:!0})}});Qo.command("start").description("start the installed desktop assistant").action(()=>{fn(),Wr(),console.log("Desktop assistant started.")});Qo.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{fn(),await qr(),console.log("Desktop assistant stopped.")});Qo.command("status").description("show the desktop login service status").action(()=>{fn();try{console.log(io("launchctl",["print",At()],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(us(Xo())?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as Al}from"commander";import{open as Ol}from"fs/promises";import{existsSync as wn,mkdirSync as kl,readFileSync as bn,writeFileSync as Br}from"fs";import{homedir as vl}from"os";import{dirname as xl,resolve as fs}from"path";var hs="/attach/",Jr="/guard/check";function Hr(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 hn(e,o,t){let n={hooks:[{type:"command",command:Hr(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function Sl(e){return{SessionStart:[hn("/attach/session-start",e,"")],UserPromptSubmit:[hn("/attach/prompt",e)],Stop:[hn("/attach/stop",e)],SessionEnd:[hn("/attach/session-end",e)]}}function El(e){let o=Hr("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function yn(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function Ot(){return fs(vl(),".claude/settings.json")}function It(e=process.cwd()){for(let o of[e,fs(e,"..")]){let t=fs(o,"agentx.json");if(wn(t))try{let n=JSON.parse(bn(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function Gr(e,o={}){let t=o.path??Ot(),n=o.withGuard!==!1,s={};if(wn(t))try{s=JSON.parse(bn(t,"utf-8"))}catch(m){throw new Error(`${t} is not valid JSON (${m?.message}) \u2014 refusing to overwrite it`)}let i=JSON.stringify(s),r=s.hooks??={},a=[];for(let[m,l]of Object.entries(Sl(e))){let u=Array.isArray(r[m])?r[m].filter(f=>!yn(f,hs)):[];r[m]=[...u,...l],a.push(m)}let c=!1;if(n){let m=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(l=>!yn(l,Jr)):[];r.PreToolUse=[...m,...El(e)],c=!0}let d=JSON.stringify(s)!==i;return d&&(kl(xl(t),{recursive:!0}),Br(t,`${JSON.stringify(s,null,2)}
8
+ `)),{path:t,changed:d,events:a,guardInstalled:c}}function zr(e={}){let o=e.path??Ot();if(!wn(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(bn(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"?Jr:hs;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let d=s[a].filter(m=>!yn(m,c));d.length!==s[a].length&&i.push(a),d.length===0?delete s[a]:s[a]=d}Object.keys(s).length===0&&delete t.hooks}let r=JSON.stringify(t)!==n;return r&&Br(o,`${JSON.stringify(t,null,2)}
9
+ `),{path:o,changed:r,events:i,guardInstalled:!1}}function $n(e=Ot()){if(!wn(e))return!1;try{return!!JSON.parse(bn(e,"utf-8"))?.hooks?.Stop?.some?.(t=>yn(t,hs))}catch{return!1}}var kn=new Al("monitor").description("Register external CLI sessions and report ended runs to the briefing"),Yr=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${It()}`;async function Kr(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)}`)}kn.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",Yr).action(async e=>{try{await Kr(e.url,"register",Yi.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}});kn.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",Yr).action(async e=>{try{let o=await Ol(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 Kr(e.url,"ended",Ki.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 Su}from"commander";import{Command as Il}from"commander";we();import O from"chalk";import{existsSync as jl,readFileSync as Cl}from"fs";async function Tl(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 Ve=new Il().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");Ve.command("start").description("start the daemon (default if no subcommand)").option("-c, --config <path>","path to agentx.json").option("-d, --detach","run in background (detached)").option("--port <port>","override bind port").action(async e=>{if(e.detach){let{spawn:d}=await import("child_process"),{openSync:m,writeFileSync:l,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=m(w,"a")}catch(b){console.error(O.red(` Failed to open ${w} for writing: ${b.message}`)),process.exit(1)}let $=d(process.execPath,p,{detached:!0,stdio:["ignore",y,y],cwd:process.cwd()});$.unref(),l("/tmp/agentx-daemon.pid",String($.pid)),console.log(O.green(`Daemon started in background (PID: ${$.pid})`)),console.log(O.dim(` Logs: tail -f ${w}`)),console.log(O.dim(" Stop: agentx daemon stop")),await new Promise(b=>setTimeout(b,1e3));try{process.kill($.pid,0)}catch{console.log(),console.log(O.yellow(` Daemon exited within 1s \u2014 check ${w} for the error:`)),console.log(O.dim(` tail -n 40 ${w}`))}return}let{readFileSync:o,writeFileSync:t,mkdirSync:n,existsSync:s}=await import("fs"),{resolve:i}=await import("path"),r=i(process.cwd(),".agentx");s(r)||n(r,{recursive:!0});let a=i(r,"daemon.pid");if(s(a)){let d=parseInt(o(a,"utf-8").trim(),10);if(d&&d!==process.pid){let m=!1;try{process.kill(d,0),m=!0}catch{}m&&await Tl(d)&&(console.error(`Another agentx daemon is already running (PID ${d}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{Nl(i(process.cwd(),".env"))}catch{}await new gs(e.config).start()});function Nl(e){if(!jl(e))return;let o=Cl(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}}Ve.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"))}});Ve.command("status").alias("st").description("show daemon status, agents, crons, and mesh").option("-c, --config <path>","path to agentx.json").option("--json","output as JSON").action(async e=>{try{let o=D(e.config),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}/health`,r=await(await fetch(s,{signal:AbortSignal.timeout(3e3)})).json();if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(O.bold(` ${r.node.name}`)+O.dim(` (${r.node.id})`)),console.log(O.green(" Status: running")+O.dim(` \u2014 uptime ${Rl(r.uptime)}`)),console.log(),console.log(O.bold(" Agents:"));for(let c of r.agents){let d=c.active>0?O.yellow(` [${c.active} active]`):"",m=c.errors>0?O.red(` (${c.errors} errors)`):"";console.log(` ${O.cyan(c.name)} ${O.dim(`(${c.tier})`)}${d}${m}`),console.log(O.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(O.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let d=c.enabled?O.green("\u25CF"):O.dim("\u25CB"),m=c.nextRun?O.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${d} ${c.id}${m}`)}}if(r.mesh?.length){console.log(),console.log(O.bold(" Mesh:"));for(let c of r.mesh){let d=c.healthy?O.green("\u25CF"):O.red("\u25CF"),m=c.skills?.length?O.dim(` (${c.skills.length} agents)`):"";console.log(` ${d} ${c.peer} ${O.dim(c.peerUrl)}${m}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError")console.log(O.red(" Daemon is not running")),console.log(O.dim(" Start with: agentx daemon start"));else try{let t=D(e.config),n=en(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}`))}}});Ve.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"})});Ve.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(D(e.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(O.dim(` Connecting to ${n}...`)),console.log(O.dim(` Press Ctrl+C to stop
12
+ `));try{let s=await fetch(n);if(!s.ok||!s.body){console.log(O.red(` Failed: ${s.status}`));return}let i=s.body.getReader(),r=new TextDecoder,a="";for(;;){let{done:c,value:d}=await i.read();if(c)break;a+=r.decode(d,{stream:!0});let m=a.split(`
13
+ `);a=m.pop()||"";for(let l of m)if(l.startsWith("data: "))try{let u=JSON.parse(l.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 l.startsWith("event: status")}}catch(s){console.log(O.red(` Connection failed: ${s.message}`)),console.log(O.dim(" Is the daemon running? Diagnostic order:")),console.log(O.dim(" 1) agentx daemon status # is the daemon up?")),console.log(O.dim(" 2) tail -n 60 /tmp/agentx-daemon.log # detach-mode crash log")),console.log(O.dim(" 3) journalctl -u agentx -n 60 # systemd-managed installs")),console.log(O.dim(" If the log file is missing, the daemon never started \u2014 re-run without --detach")),console.log(O.dim(" to see the error in the foreground."))}});Ve.command("send <agent> <message...>").description("send a task to an agent via the daemon API").option("-c, --config <path>","path to agentx.json").option("--peer <peer>","send to a mesh peer's agent").option("--json","output raw JSON response").action(async(e,o,t)=>{let n=o.join(" ");try{let s=D(t.config),[i,r]=s.node.bind.split(":"),a=`http://${i||"127.0.0.1"}:${r}`,c,d;t.peer?(c=`${a}/mesh/task`,d={peer:t.peer,message:n,agent:e}):(c=`${a}/task`,d={agent:e,message:n}),console.log(O.dim(` Sending to ${t.peer?`${t.peer}/${e}`:e}...`));let l=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)})).json();t.json?console.log(JSON.stringify(l,null,2)):l.error?console.log(O.red(` Error: ${l.error}`)):(console.log(),console.log(l.content||l.response||"No response"),l.duration&&console.log(O.dim(`
14
+ (${(l.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(O.red(` Failed: ${s.message}`)),console.log(O.dim(" Is the daemon running? Try: agentx daemon status"))}});Ve.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}`))}});Ve.action(async e=>{await new gs(e.config).start()});function Rl(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 _l}from"commander";import Je from"chalk";import{existsSync as jt,readFileSync as Dl,writeFileSync as Vr,mkdirSync as Xr}from"fs";import{hostname as Qr}from"os";import{resolve as Zo}from"path";var Zr=new _l().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=Zo(o,"agentx.json"),n=Zo(o,".env"),s=Zo(o,".agentx/sessions");if(console.log(),console.log(Je.bold(" agentx init")),console.log(),jt(t)&&!e.force){console.log(Je.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[Zo(o,"agentx.example.json"),Zo(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(jt(c)){r=Dl(c,"utf-8");break}r||(r=JSON.stringify({node:{id:Qr().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:Qr(),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)),Vr(t,r),console.log(Je.green(" \u2713 Created agentx.json")),jt(n)||(Vr(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
15
+ `)),console.log(Je.green(" \u2713 Created .env template"))),jt(s)||(Xr(s,{recursive:!0}),console.log(Je.green(" \u2713 Created .agentx/sessions/")));let a=Zo(o,".claude");jt(a)||(Xr(a,{recursive:!0}),console.log(Je.green(" \u2713 Created .claude/"))),console.log(),console.log(Je.bold(" Next steps:")),console.log(` 1. Edit ${Je.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${Je.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${Je.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${Je.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as Pl}from"commander";import Co from"chalk";import{spawn as oa}from"child_process";import{existsSync as Ll}from"fs";import{dirname as Ml,resolve as Ul}from"path";import{fileURLToPath as Fl}from"url";we();var ta=new Pl().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=jr(),t=e.port?parseInt(e.port,10):ql(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(Co.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(Co.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(Co.bold(` Opening ${n}`)),console.log(),await Bl(n).catch(()=>!1))console.log(Co.dim(" Dashboard is already running.")),e.open!==!1&&ea(n);else{console.log(Co.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=Wl(),r=oa(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&ea(n),await new Promise(a=>r.on("exit",()=>a()))}});function ql(){try{return D().dashboard.port||4202}catch{return 4202}}function Wl(){let e=Ul(Ml(Fl(import.meta.url)),"cli.js");return Ll(e)?e:process.argv[1]||e}async function Bl(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}function ea(e){let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=oa(o,[e],{stdio:"ignore",detached:!0});t.once("error",()=>{console.log(Co.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),t.unref()}catch{console.log(Co.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as Jl}from"commander";import xe from"chalk";var Ct=new Jl().name("token").description("scoped API tokens for external access (mesh peers, integrations)");Ct.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 mn,t=String(e.scope).split(",").map(r=>r.trim()).filter(Boolean),n=e.expires?parseInt(e.expires,10):void 0;if(e.expires&&(!n||n<1))throw new Error("--expires must be a positive integer (days)");let{token:s,record:i}=o.create({name:e.name,scopes:t,expiresInDays:n});console.log(),console.log(xe.bold(" Token created.")),console.log(),console.log(` id: ${xe.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||xe.dim("never")}`),console.log(),console.log(xe.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${xe.green.bold(s)}`),console.log(),console.log(xe.dim(" Use it via the Authorization header:")),console.log(xe.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});Ct.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new mn().list();if(e.length===0){console.log(xe.dim(`
27
16
  No tokens issued.
28
- `));return}console.log();for(let o of e){let t=o.revokedAt?xe.red("revoked"):o.expiresAt&&Date.parse(o.expiresAt)<Date.now()?xe.red("expired"):xe.green("active");console.log(` ${xe.cyan(o.id)} ${t} ${o.name}`),console.log(xe.dim(` prefix: ${o.prefix}\u2026 scopes: ${o.scopes.join(", ")}`)),console.log(xe.dim(` created: ${o.createdAt}${o.expiresAt?` expires: ${o.expiresAt}`:""}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(xe.red(` ${e.message}`)),process.exit(1)}});Ct.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new rn().revoke(e);o||(console.log(xe.red(` Token ${e} not found.`)),process.exit(1)),console.log(xe.green(`
17
+ `));return}console.log();for(let o of e){let t=o.revokedAt?xe.red("revoked"):o.expiresAt&&Date.parse(o.expiresAt)<Date.now()?xe.red("expired"):xe.green("active");console.log(` ${xe.cyan(o.id)} ${t} ${o.name}`),console.log(xe.dim(` prefix: ${o.prefix}\u2026 scopes: ${o.scopes.join(", ")}`)),console.log(xe.dim(` created: ${o.createdAt}${o.expiresAt?` expires: ${o.expiresAt}`:""}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(xe.red(` ${e.message}`)),process.exit(1)}});Ct.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new mn().revoke(e);o||(console.log(xe.red(` Token ${e} not found.`)),process.exit(1)),console.log(xe.green(`
29
18
  \u2713 Revoked ${e} (${o.name})
30
- `))}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});ve();import{Command as Qe}from"commander";import h from"chalk";import Oe from"prompts";import{readFileSync as po,writeFileSync as Zo,existsSync as ge,mkdirSync as Xe,cpSync as us,readdirSync as hs}from"fs";import{resolve as J,join as mo,dirname as Wl}from"path";import{fileURLToPath as Bl}from"url";function ne(){let e=J(process.cwd(),"agentx.json");if(!ge(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(po(e,"utf-8"))}function _e(e){return de(o=>{for(let t of Object.keys(o))delete o[t];Object.assign(o,e)}).then(o=>{if(!o.success){console.error(h.red(` Config save failed: ${o.error}`));return}o.reloaded?console.error(h.dim(" (daemon hot-reloaded)")):o.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(o.reloadSkipped)&&console.error(h.dim(` (daemon reload skipped: ${o.reloadSkipped})`))})}var jo=new Qe().name("agent").description("manage agents \u2014 add, list, remove");jo.command("list").alias("ls").description("list configured agents").action(()=>{let e=ne();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=t.mentions?.join(", ")||"";console.log(` ${h.cyan(o)} \u2014 ${t.name} (${t.tier})`),console.log(h.dim(` workspace: ${t.workspace}`)),n&&console.log(h.dim(` mentions: ${n}`))}console.log()});jo.command("add").description("add a new agent interactively").action(async()=>{let e=ne(),o=await Oe([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:d=>/^[a-z0-9-]+$/.test(d)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:J(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!o.id)return;let t=o.workspace.endsWith(o.id)?o.workspace:mo(o.workspace,o.id);Xe(J(t,".claude/skills"),{recursive:!0});let n={name:o.name,workspace:t,tier:o.tier,model:o.model,mentions:o.mentions?.map(d=>d.trim()).filter(Boolean)||[],maxConcurrent:o.maxConcurrent,systemPrompt:o.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-G6KGWPHY.js"),i=s(o.id,n,"19900",(...d)=>{console.log(h.dim(` ${d.join(" ")}`))}),r=J(process.cwd(),"src/wiki/SKILL.md"),a=J(Wl(Bl(import.meta.url)),"../wiki/SKILL.md"),c=ge(r)?r:a;ge(c)&&(Xe(J(t,".claude/skills/wiki"),{recursive:!0}),us(c,J(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await _e(e),console.log(h.green(`
31
- 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()});jo.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=ne();if(!o.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete o.agents[e],await _e(o),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});jo.command("capability <id>").alias("caps").description("set agent capability flags (intents, maxDelegationDepth, contextReferences, contextStrategy)").option("--intents <csv>","comma-separated intent allow-list (set to '-' to clear)").option("--max-delegation-depth <n>","max distinct upstream agents on the same subject before refusal (0 disables)").option("--context-references <bool>","render the deterministic [Verified References] block (true|false)").option("--context-strategy <name>","per-agent override: layered | planner").option("--max-execution-minutes <n>","wall-clock cap on a single Claude Code call (1\u2013240)").option("--show","just print the current capability fields").action(async(e,o)=>{let t=ne(),n=t.agents?.[e];if(n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1)),o.show){console.log(),console.log(h.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):h.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":h.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||h.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(o.intents!==void 0&&(o.intents==="-"||o.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(o.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),o.maxDelegationDepth!==void 0){let i=parseInt(o.maxDelegationDepth,10);(!Number.isFinite(i)||i<0||i>50)&&(console.log(h.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=i,s.push(`maxDelegationDepth=${i}`)}if(o.contextReferences!==void 0){let i=String(o.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(i)||(console.log(h.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=i==="true"||i==="on"||i==="1",s.push(`contextReferences=${n.contextReferences}`)}if(o.contextStrategy!==void 0&&(o.contextStrategy==="-"||o.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(o.contextStrategy)?(n.contextStrategy=o.contextStrategy,s.push(`contextStrategy=${o.contextStrategy}`)):(console.log(h.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),o.maxExecutionMinutes!==void 0){let i=parseInt(o.maxExecutionMinutes,10);(!Number.isFinite(i)||i<1||i>240)&&(console.log(h.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(h.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await _e(t),console.log(h.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(h.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var jt=new Qe().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");jt.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=ne().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(o.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(h.dim(`
19
+ `))}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});we();import{Command as Qe}from"commander";import h from"chalk";import Oe from"prompts";import{readFileSync as uo,writeFileSync as et,existsSync as ge,mkdirSync as Xe,cpSync as ys,readdirSync as bs}from"fs";import{resolve as J,join as po,dirname as Hl}from"path";import{fileURLToPath as Gl}from"url";function ne(){let e=J(process.cwd(),"agentx.json");if(!ge(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(uo(e,"utf-8"))}function _e(e){return de(o=>{for(let t of Object.keys(o))delete o[t];Object.assign(o,e)}).then(o=>{if(!o.success){console.error(h.red(` Config save failed: ${o.error}`));return}o.reloaded?console.error(h.dim(" (daemon hot-reloaded)")):o.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(o.reloadSkipped)&&console.error(h.dim(` (daemon reload skipped: ${o.reloadSkipped})`))})}var To=new Qe().name("agent").description("manage agents \u2014 add, list, remove");To.command("list").alias("ls").description("list configured agents").action(()=>{let e=ne();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=t.mentions?.join(", ")||"";console.log(` ${h.cyan(o)} \u2014 ${t.name} (${t.tier})`),console.log(h.dim(` workspace: ${t.workspace}`)),n&&console.log(h.dim(` mentions: ${n}`))}console.log()});To.command("add").description("add a new agent interactively").action(async()=>{let e=ne(),o=await Oe([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:d=>/^[a-z0-9-]+$/.test(d)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:J(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!o.id)return;let t=o.workspace.endsWith(o.id)?o.workspace:po(o.workspace,o.id);Xe(J(t,".claude/skills"),{recursive:!0});let n={name:o.name,workspace:t,tier:o.tier,model:o.model,mentions:o.mentions?.map(d=>d.trim()).filter(Boolean)||[],maxConcurrent:o.maxConcurrent,systemPrompt:o.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-G6KGWPHY.js"),i=s(o.id,n,"19900",(...d)=>{console.log(h.dim(` ${d.join(" ")}`))}),r=J(process.cwd(),"src/wiki/SKILL.md"),a=J(Hl(Gl(import.meta.url)),"../wiki/SKILL.md"),c=ge(r)?r:a;ge(c)&&(Xe(J(t,".claude/skills/wiki"),{recursive:!0}),ys(c,J(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await _e(e),console.log(h.green(`
20
+ Agent "${o.id}" added`)),console.log(h.dim(` Workspace: ${t}`)),console.log(h.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});To.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=ne();if(!o.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete o.agents[e],await _e(o),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});To.command("capability <id>").alias("caps").description("set agent capability flags (intents, maxDelegationDepth, contextReferences, contextStrategy)").option("--intents <csv>","comma-separated intent allow-list (set to '-' to clear)").option("--max-delegation-depth <n>","max distinct upstream agents on the same subject before refusal (0 disables)").option("--context-references <bool>","render the deterministic [Verified References] block (true|false)").option("--context-strategy <name>","per-agent override: layered | planner").option("--max-execution-minutes <n>","wall-clock cap on a single Claude Code call (1\u2013240)").option("--show","just print the current capability fields").action(async(e,o)=>{let t=ne(),n=t.agents?.[e];if(n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1)),o.show){console.log(),console.log(h.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):h.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":h.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||h.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(o.intents!==void 0&&(o.intents==="-"||o.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(o.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),o.maxDelegationDepth!==void 0){let i=parseInt(o.maxDelegationDepth,10);(!Number.isFinite(i)||i<0||i>50)&&(console.log(h.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=i,s.push(`maxDelegationDepth=${i}`)}if(o.contextReferences!==void 0){let i=String(o.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(i)||(console.log(h.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=i==="true"||i==="on"||i==="1",s.push(`contextReferences=${n.contextReferences}`)}if(o.contextStrategy!==void 0&&(o.contextStrategy==="-"||o.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(o.contextStrategy)?(n.contextStrategy=o.contextStrategy,s.push(`contextStrategy=${o.contextStrategy}`)):(console.log(h.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),o.maxExecutionMinutes!==void 0){let i=parseInt(o.maxExecutionMinutes,10);(!Number.isFinite(i)||i<1||i>240)&&(console.log(h.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(h.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await _e(t),console.log(h.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(h.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var Tt=new Qe().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");Tt.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=ne().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(o.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(h.dim(`
32
21
  ${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
33
- `));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,l]of Object.entries(c))typeof l=="string"&&/^[A-Z][A-Z0-9_]*$/.test(l)?a.push(process.env[l]?h.green(`${g}:${l}=set`):h.yellow(`${g}:${l}=UNSET`)):g==="auth"&&l==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof l=="string"&&a.push(h.dim(`sessionDir:${l}`));let d=Object.entries(i.metadata??{}).map(([g,l])=>`${g}=${l}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),d&&console.log(` ${h.dim(d)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});jt.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=ne();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-NPLE42XY.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Oe({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 Oe({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),d=String(o.sessionDir||"").trim();if(!a&&!c&&!d&&n){let u=await Oe({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 Oe({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"&&(d=((await Oe({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 Oe({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 l={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),l.tokenEnv=a),c==="keyring"&&(l.auth="keyring"),d&&(l.sessionDir=d),Object.keys(l).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(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:l,metadata:g,enabled:!0}),await _e(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});jt.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=ne(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(d=>d.kind===i&&(!r||d.label===r)||d.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await _e(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});jt.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=ne().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},d=[];for(let[g,l]of Object.entries(c))typeof l=="string"&&/^[A-Z][A-Z0-9_]*$/.test(l)&&!process.env[l]&&d.push(`${g}: env var ${l} is unset`);if(d.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of d)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});jo.addCommand(jt);var wn=new Qe().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");wn.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ne();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});wn.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ne(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Oe({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 Oe([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await _e(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Oe([{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 Oe([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await _e(e),Xe(J(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Oe([{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 Oe([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await _e(e),console.log(h.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(h.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(h.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(h.dim(` Secret token: ${s.webhookSecret}`)),console.log(h.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(h.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var et=new Qe().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");et.command("list").alias("ls").description("list cron jobs").action(()=>{let e=ne();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});et.command("add").description("add a cron job").action(async()=>{let e=ne(),o=Object.keys(e.agents||{}),t=await Oe([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:o.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!t.id||!t.schedule||(e.crons=e.crons||{},e.crons[t.id]={enabled:t.enabled,schedule:t.schedule,timezone:t.timezone,agent:t.agent,prompt:t.prompt,timeout:t.timeout,onError:["log"]},await _e(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});et.command("enable <id>").description("enable a cron job").action(async e=>{let o=ne();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!0,await _e(o),console.log(h.green(` Cron "${e}" enabled`))});et.command("disable <id>").description("disable a cron job").action(async e=>{let o=ne();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await _e(o),console.log(h.green(` Cron "${e}" disabled`))});var ot=new Qe().name("mesh").description("manage mesh peers \u2014 add, list, remove");ot.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=ne();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});ot.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=ne(),o=await Oe([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(h.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:o.url,name:o.name,...o.token?{token:o.token}:{}}),await _e(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});ot.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=ne();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await _e(o),console.log(h.green(` Peer "${e}" removed`)))});ot.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let o=ne();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await _e(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});var To=new Qe().name("skill").description("manage skills \u2014 add to agent(s), list");To.command("add <skillPath>").description("add a skill to agent(s)").option("-a, --agent <agents...>","target agent ID(s)").option("--all","add to all agents").action(async(e,o)=>{let t=ne(),n=J(e);if(!ge(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=ge(mo(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 Oe({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=J(a.workspace,".claude/skills",s);Xe(c,{recursive:!0}),ge(mo(n,"SKILL.md"))?us(n,c,{recursive:!0}):n.endsWith(".md")&&us(n,mo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});To.command("list").alias("ls").description("list skills per agent").action(()=>{let e=ne();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=J(t.workspace,".claude/skills"),s=ge(n)?hs(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});To.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[J(n,"src",e,"SKILL.md"),J(n,"skills",e,"SKILL.md")],i=s.find($=>ge($));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let $ of s)console.log(h.dim(` ${$}`));return}let r=po(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),d;try{d=L()}catch($){console.log(h.red(` Can't load agentx.json: ${$.message}`));return}let g=Object.entries(d.agents||{}),l=o.agent?g.filter(([$])=>$===o.agent):g;if(l.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,f=0,p=0,w=0;for(let[$,b]of l){let v=b.workspace;if(!v||!ge(v)){console.log(` ${h.yellow("\u2717")} ${$.padEnd(22)} ${h.dim("(workspace missing: "+(v||"undefined")+")")}`),w++;continue}let A=J(v,".claude/skills",e),x=J(A,"SKILL.md");if(!ge(x)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${$.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}o.dryRun||(Xe(A,{recursive:!0}),Zo(x,r)),console.log(` ${h.green("+")} ${$.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let E=po(x,"utf-8");if(t("sha256").update(E).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${$.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),p++;continue}let R=(E.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||Zo(x,r),console.log(` ${h.yellow("\u21BB")} ${$.padEnd(22)} ${h.dim(`v${R} \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()});To.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:o}=await import("./loader-BOKE5M5S.js"),{auditAll:t}=await import("./audit-4245CX6P.js"),{loadReferences:n}=await import("./loader-4ZGTK7LD.js"),{loadRecipes:s}=await import("./recipes-7S4MC5OJ.js"),i=[];if(e.workspace){let f=ne().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(J(f.workspace))}else if(e.allWorkspaces){let u=ne();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(J(f.workspace))}else i.push(J(e.cwd));let r=J(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>o(u)))).flat(),[d,g]=await Promise.all([n(r),s(r)]),l=t({skills:c,references:d,recipes:g});if(e.json)console.log(JSON.stringify(l.map(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 l)u[f.verdict]++;console.log();for(let f of l){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(l.some(u=>u.verdict==="FAILING")?1:0)});To.command("suggest").description("rank an agent's skills against a task (suggests, never loads)").argument("<task>","the task, in the words it arrived in").option("--agent <id>","whose skills to rank").option("--min <p>","minimum P(any skill applies)","0.6").option("--json","emit the ranking as JSON").action(async(e,o)=>{let t=ne(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-BOKE5M5S.js"),{pickSkillForTask:a}=await import("./select-WQXHYEPD.js"),c=await r(i.workspace);if(c.length===0){console.log(h.yellow(` ${s} has no skills`));return}let d=await a(c,e,{agent:s,minRelevant:Number(o.min)||.6});if(o.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:d.skill?.frontmatter.name??null,anyRelevant:d.anyRelevant,confidence:d.confidence,judged:d.judged,reason:d.reason,shortlist:d.shortlist},null,2));return}if(console.log(),d.skill?(console.log(` ${h.green("\u2192")} ${h.bold(d.skill.frontmatter.name)} ${h.dim(`\xB7 ${d.reason}`)}`),console.log(` ${h.dim(d.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${h.yellow("\xB7")} no skill for this ${h.dim(`\u2014 ${d.reason}`)}`),d.shortlist.length>1){console.log(h.dim(`
34
- shortlist (lexical -> judged)`));for(let g of d.shortlist.slice(0,6)){let l=g.p===void 0?" - ":g.p.toFixed(2);console.log(h.dim(` ${g.lexical.toFixed(2)} -> ${l} ${g.name}`))}}d.judged||console.log(h.dim(`
35
- (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var Tt=new Qe().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Tt.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=J(o.cwd),n=J(t,"references/example"),s=J(t,"references/recipes/example.yaml");ge(n)||(console.log(h.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=J(t,".agentx/references",e),r=J(t,".agentx/references/recipes");Xe(i,{recursive:!0}),Xe(r,{recursive:!0});let a=hs(n).filter(l=>l.endsWith(".yaml")||l.endsWith(".yml")),c=0,d=0;for(let l of a){let u=mo(i,l);if(ge(u)&&!o.force){console.log(h.dim(` skip ${u} (exists; --force to overwrite)`)),d++;continue}let p=po(mo(n,l),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);Zo(u,p),console.log(h.green(` + ${u}`)),c++}let g=mo(r,`${e}.yaml`);if(ge(g)&&!o.force)console.log(h.dim(` skip ${g} (exists; --force to overwrite)`)),d++;else if(ge(s)){let l=po(s,"utf-8").replaceAll("example.",`${e}.`);Zo(g,l),console.log(h.green(` + ${g}`)),c++}console.log(),console.log(h.dim(` ${c} written, ${d} skipped. Edit the placeholders, then:`)),console.log(h.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(h.dim(" 2. agentx skill audit # verify references resolve")),console.log(h.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});Tt.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.example.com)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-BOKE5M5S.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-D4VVRNAI.js"),i=J(o.cwd),r=o.from?String(o.from).split(",").map(w=>w.trim()).filter(Boolean):[e],a=await t(i),c=n(a,{namespace:e,filter:r,gitlabHost:o.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(h.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(h.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(h.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let d=Object.fromEntries(Object.entries(c.byKind).map(([w,y])=>[w,y.length]));console.log(` Discovered: ssh=${d.ssh} gitlab=${d.gitlab} paths=${d.path} contacts=${d.contact}`);let g=s(c,e),l=J(o.referencesCwd||o.cwd),u=J(l,".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(`
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[m,l]of Object.entries(c))typeof l=="string"&&/^[A-Z][A-Z0-9_]*$/.test(l)?a.push(process.env[l]?h.green(`${m}:${l}=set`):h.yellow(`${m}:${l}=UNSET`)):m==="auth"&&l==="keyring"?a.push(h.dim("auth:keyring")):m==="sessionDir"&&typeof l=="string"&&a.push(h.dim(`sessionDir:${l}`));let d=Object.entries(i.metadata??{}).map(([m,l])=>`${m}=${l}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),d&&console.log(` ${h.dim(d)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});Tt.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=ne();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-S3VHHVYW.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Oe({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 Oe({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),d=String(o.sessionDir||"").trim();if(!a&&!c&&!d&&n){let u=await Oe({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 Oe({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"&&(d=((await Oe({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let m={};if(o.metadata)for(let u of String(o.metadata).split(",")){let[f,...p]=u.split("=");f&&(m[f.trim()]=p.join("=").trim())}else if(n){let u=await Oe({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&&(m[p.trim()]=w.join("=").trim())}}let l={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),l.tokenEnv=a),c==="keyring"&&(l.auth="keyring"),d&&(l.sessionDir=d),Object.keys(l).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(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:l,metadata:m,enabled:!0}),await _e(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Tt.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=ne(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(d=>d.kind===i&&(!r||d.label===r)||d.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await _e(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Tt.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=ne().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},d=[];for(let[m,l]of Object.entries(c))typeof l=="string"&&/^[A-Z][A-Z0-9_]*$/.test(l)&&!process.env[l]&&d.push(`${m}: env var ${l} is unset`);if(d.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let m of d)console.log(` ${h.dim(m)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});To.addCommand(Tt);var vn=new Qe().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");vn.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ne();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});vn.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ne(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Oe({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 Oe([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await _e(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Oe([{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 Oe([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await _e(e),Xe(J(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Oe([{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 Oe([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await _e(e),console.log(h.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(h.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(h.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(h.dim(` Secret token: ${s.webhookSecret}`)),console.log(h.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(h.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var ot=new Qe().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");ot.command("list").alias("ls").description("list cron jobs").action(()=>{let e=ne();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});ot.command("add").description("add a cron job").action(async()=>{let e=ne(),o=Object.keys(e.agents||{}),t=await Oe([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:o.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!t.id||!t.schedule||(e.crons=e.crons||{},e.crons[t.id]={enabled:t.enabled,schedule:t.schedule,timezone:t.timezone,agent:t.agent,prompt:t.prompt,timeout:t.timeout,onError:["log"]},await _e(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});ot.command("enable <id>").description("enable a cron job").action(async e=>{let o=ne();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!0,await _e(o),console.log(h.green(` Cron "${e}" enabled`))});ot.command("disable <id>").description("disable a cron job").action(async e=>{let o=ne();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await _e(o),console.log(h.green(` Cron "${e}" disabled`))});var tt=new Qe().name("mesh").description("manage mesh peers \u2014 add, list, remove");tt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=ne();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});tt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=ne(),o=await Oe([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(h.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:o.url,name:o.name,...o.token?{token:o.token}:{}}),await _e(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});tt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=ne();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await _e(o),console.log(h.green(` Peer "${e}" removed`)))});tt.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let o=ne();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await _e(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});var No=new Qe().name("skill").description("manage skills \u2014 add to agent(s), list");No.command("add <skillPath>").description("add a skill to agent(s)").option("-a, --agent <agents...>","target agent ID(s)").option("--all","add to all agents").action(async(e,o)=>{let t=ne(),n=J(e);if(!ge(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=ge(po(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 Oe({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=J(a.workspace,".claude/skills",s);Xe(c,{recursive:!0}),ge(po(n,"SKILL.md"))?ys(n,c,{recursive:!0}):n.endsWith(".md")&&ys(n,po(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});No.command("list").alias("ls").description("list skills per agent").action(()=>{let e=ne();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=J(t.workspace,".claude/skills"),s=ge(n)?bs(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});No.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[J(n,"src",e,"SKILL.md"),J(n,"skills",e,"SKILL.md")],i=s.find($=>ge($));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let $ of s)console.log(h.dim(` ${$}`));return}let r=uo(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),d;try{d=D()}catch($){console.log(h.red(` Can't load agentx.json: ${$.message}`));return}let m=Object.entries(d.agents||{}),l=o.agent?m.filter(([$])=>$===o.agent):m;if(l.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,f=0,p=0,w=0;for(let[$,b]of l){let v=b.workspace;if(!v||!ge(v)){console.log(` ${h.yellow("\u2717")} ${$.padEnd(22)} ${h.dim("(workspace missing: "+(v||"undefined")+")")}`),w++;continue}let A=J(v,".claude/skills",e),x=J(A,"SKILL.md");if(!ge(x)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${$.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}o.dryRun||(Xe(A,{recursive:!0}),et(x,r)),console.log(` ${h.green("+")} ${$.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let E=uo(x,"utf-8");if(t("sha256").update(E).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${$.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),p++;continue}let N=(E.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||et(x,r),console.log(` ${h.yellow("\u21BB")} ${$.padEnd(22)} ${h.dim(`v${N} \u2192 v${c}`)}`),f++}console.log();let y=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${y} seed ${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()});No.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:o}=await import("./loader-BOKE5M5S.js"),{auditAll:t}=await import("./audit-4245CX6P.js"),{loadReferences:n}=await import("./loader-4ZGTK7LD.js"),{loadRecipes:s}=await import("./recipes-7S4MC5OJ.js"),i=[];if(e.workspace){let f=ne().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(J(f.workspace))}else if(e.allWorkspaces){let u=ne();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(J(f.workspace))}else i.push(J(e.cwd));let r=J(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>o(u)))).flat(),[d,m]=await Promise.all([n(r),s(r)]),l=t({skills:c,references:d,recipes:m});if(e.json)console.log(JSON.stringify(l.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 l)u[f.verdict]++;console.log();for(let f of l){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(l.some(u=>u.verdict==="FAILING")?1:0)});No.command("suggest").description("rank an agent's skills against a task (suggests, never loads)").argument("<task>","the task, in the words it arrived in").option("--agent <id>","whose skills to rank").option("--min <p>","minimum P(any skill applies)","0.6").option("--json","emit the ranking as JSON").action(async(e,o)=>{let t=ne(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([m])=>m===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-JL3JJJP4.js"),c=await r(i.workspace);if(c.length===0){console.log(h.yellow(` ${s} has no skills`));return}let d=await a(c,e,{agent:s,minRelevant:Number(o.min)||.6});if(o.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:d.skill?.frontmatter.name??null,anyRelevant:d.anyRelevant,confidence:d.confidence,judged:d.judged,reason:d.reason,shortlist:d.shortlist},null,2));return}if(console.log(),d.skill?(console.log(` ${h.green("\u2192")} ${h.bold(d.skill.frontmatter.name)} ${h.dim(`\xB7 ${d.reason}`)}`),console.log(` ${h.dim(d.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${h.yellow("\xB7")} no skill for this ${h.dim(`\u2014 ${d.reason}`)}`),d.shortlist.length>1){console.log(h.dim(`
23
+ shortlist (lexical -> judged)`));for(let m of d.shortlist.slice(0,6)){let l=m.p===void 0?" - ":m.p.toFixed(2);console.log(h.dim(` ${m.lexical.toFixed(2)} -> ${l} ${m.name}`))}}d.judged||console.log(h.dim(`
24
+ (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var Nt=new Qe().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Nt.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=J(o.cwd),n=J(t,"references/example"),s=J(t,"references/recipes/example.yaml");ge(n)||(console.log(h.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=J(t,".agentx/references",e),r=J(t,".agentx/references/recipes");Xe(i,{recursive:!0}),Xe(r,{recursive:!0});let a=bs(n).filter(l=>l.endsWith(".yaml")||l.endsWith(".yml")),c=0,d=0;for(let l of a){let u=po(i,l);if(ge(u)&&!o.force){console.log(h.dim(` skip ${u} (exists; --force to overwrite)`)),d++;continue}let p=uo(po(n,l),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);et(u,p),console.log(h.green(` + ${u}`)),c++}let m=po(r,`${e}.yaml`);if(ge(m)&&!o.force)console.log(h.dim(` skip ${m} (exists; --force to overwrite)`)),d++;else if(ge(s)){let l=uo(s,"utf-8").replaceAll("example.",`${e}.`);et(m,l),console.log(h.green(` + ${m}`)),c++}console.log(),console.log(h.dim(` ${c} written, ${d} skipped. Edit the placeholders, then:`)),console.log(h.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(h.dim(" 2. agentx skill audit # verify references resolve")),console.log(h.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});Nt.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.example.com)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-BOKE5M5S.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-D4VVRNAI.js"),i=J(o.cwd),r=o.from?String(o.from).split(",").map(w=>w.trim()).filter(Boolean):[e],a=await t(i),c=n(a,{namespace:e,filter:r,gitlabHost:o.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(h.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(h.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(h.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let d=Object.fromEntries(Object.entries(c.byKind).map(([w,y])=>[w,y.length]));console.log(` Discovered: ssh=${d.ssh} gitlab=${d.gitlab} paths=${d.path} contacts=${d.contact}`);let m=s(c,e),l=J(o.referencesCwd||o.cwd),u=J(l,".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(m))console.log(h.cyan(`
36
25
  --- ${w} ---`)),console.log(y.split(`
37
26
  `).slice(0,30).map($=>` ${$}`).join(`
38
27
  `)),y.split(`
39
28
  `).length>30&&console.log(h.dim(` \u2026 (${y.split(`
40
- `).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}Xe(u,{recursive:!0});let f=0,p=0;for(let[w,y]of Object.entries(g)){let $=mo(u,w);if(ge($)&&!o.force){console.log(h.dim(` skip ${$} (exists; --force to overwrite)`)),p++;continue}Zo($,y),console.log(h.green(` + ${$}`)),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()});Tt.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:o}=await import("./loader-4ZGTK7LD.js"),t=await o(J(e.cwd)),n=[...t.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(h.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=t.sourceById.get(s.id);console.log(` ${h.cyan(s.id)} ${h.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(h.dim(` ${i}`))}console.log(),console.log(h.dim(` ${n.length} reference(s) loaded.`)),console.log()});var ys=new Qe().name("hook").description("manage hooks \u2014 add to agent workspace");ys.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=ne().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=J(t.workspace,".claude/settings.json"),s=ge(n)?JSON.parse(po(n,"utf-8")):{},i=await Oe([{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),Xe(J(t.workspace,".claude"),{recursive:!0}),Zo(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var ws=new Qe().name("migrate").description("import configuration from OpenClaw or other tools");ws.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(e,o)=>{let t=[e,J(process.env.HOME||"",".openclaw/openclaw.json"),J(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of t)if(f&&ge(f)){n=f;break}if(!n){console.log(h.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(h.dim(` Reading: ${n}`));let s=JSON.parse(po(n,"utf-8")),i=ge(J(process.cwd(),"agentx.json"))?ne():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},r=s.agents?.list||[],a=s.bindings||[],c={};for(let f of a)f.match?.channel==="telegram"&&(c[f.match.accountId]=f.agentId);r.find(f=>f.id==="main"||f.default)&&(c.default="main");let d=0;for(let f of r){if(f.workspace?.startsWith("/data"))continue;let 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"},d++,!o.dryRun){Xe(J(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-G6KGWPHY.js");y(p,i.agents[p])}}console.log(` ${h.green(d)} agents imported (workspaces set up with Claude Code best practices)`);let g=s.channels?.telegram?.accounts||{},l=0;for(let[f,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,l++}console.log(` ${h.green(l)} Telegram accounts imported`);let u=J(n,"../cron/jobs.json");if(ge(u)){let f=JSON.parse(po(u,"utf-8")),p=0;for(let w of f.jobs||[]){let y=w.name||w.id,$=w.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[y]={enabled:w.enabled||!1,schedule:w.schedule?.expr||"0 9 * * *",timezone:w.schedule?.tz||"UTC",agent:$,prompt:w.payload?.message||"",timeout:w.payload?.timeoutSeconds||600,onError:["log"]},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}Xe(u,{recursive:!0});let f=0,p=0;for(let[w,y]of Object.entries(m)){let $=po(u,w);if(ge($)&&!o.force){console.log(h.dim(` skip ${$} (exists; --force to overwrite)`)),p++;continue}et($,y),console.log(h.green(` + ${$}`)),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()});Nt.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:o}=await import("./loader-4ZGTK7LD.js"),t=await o(J(e.cwd)),n=[...t.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(h.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=t.sourceById.get(s.id);console.log(` ${h.cyan(s.id)} ${h.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(h.dim(` ${i}`))}console.log(),console.log(h.dim(` ${n.length} reference(s) loaded.`)),console.log()});var $s=new Qe().name("hook").description("manage hooks \u2014 add to agent workspace");$s.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=ne().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=J(t.workspace,".claude/settings.json"),s=ge(n)?JSON.parse(uo(n,"utf-8")):{},i=await Oe([{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),Xe(J(t.workspace,".claude"),{recursive:!0}),et(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var ks=new Qe().name("migrate").description("import configuration from OpenClaw or other tools");ks.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(e,o)=>{let t=[e,J(process.env.HOME||"",".openclaw/openclaw.json"),J(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of t)if(f&&ge(f)){n=f;break}if(!n){console.log(h.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(h.dim(` Reading: ${n}`));let s=JSON.parse(uo(n,"utf-8")),i=ge(J(process.cwd(),"agentx.json"))?ne():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},r=s.agents?.list||[],a=s.bindings||[],c={};for(let f of a)f.match?.channel==="telegram"&&(c[f.match.accountId]=f.agentId);r.find(f=>f.id==="main"||f.default)&&(c.default="main");let d=0;for(let f of r){if(f.workspace?.startsWith("/data"))continue;let 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"},d++,!o.dryRun){Xe(J(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-G6KGWPHY.js");y(p,i.agents[p])}}console.log(` ${h.green(d)} agents imported (workspaces set up with Claude Code best practices)`);let m=s.channels?.telegram?.accounts||{},l=0;for(let[f,p]of Object.entries(m)){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,l++}console.log(` ${h.green(l)} Telegram accounts imported`);let u=J(n,"../cron/jobs.json");if(ge(u)){let f=JSON.parse(uo(u,"utf-8")),p=0;for(let w of f.jobs||[]){let y=w.name||w.id,$=w.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[y]={enabled:w.enabled||!1,schedule:w.schedule?.expr||"0 9 * * *",timezone:w.schedule?.tz||"UTC",agent:$,prompt:w.payload?.message||"",timeout:w.payload?.timeoutSeconds||600,onError:["log"]},p++}console.log(` ${h.green(p)} cron jobs imported`)}o.dryRun?(console.log(h.yellow(`
41
30
  Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await _e(i),console.log(h.green(`
42
- Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var uo=new Qe().name("config").description("validate and inspect configuration");uo.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=L(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=en(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=ge(J(r,".claude")),c=ge(J(r,"CLAUDE.md")),d=ge(J(r,".claude/settings.json")),g=ge(J(r,".claude/skills"))?hs(J(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,l=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",d?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${l.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});uo.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=L(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function Jl(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 fs(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}uo.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-FFTODESU.js"),{expandEnvVars:r}=await import("./config-NPLE42XY.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(h.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(t(a,"utf-8")),d=o.raw?c:r(c),g=i(d,e);o.json?console.log(JSON.stringify(g)):console.log(fs(g))});uo.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-FFTODESU.js"),r=Jl(o,!!t.string),a=await n(d=>{s(d,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(h.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would become: ${fs(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${fs(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})`)))});uo.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-FFTODESU.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.")))});uo.command("governance").description("show resolved governance flags (read-only; flags read once at startup)").option("-c, --config <path>","path to agentx.json").option("--json","emit JSON").action(e=>{let o=!1,t=0,n;try{let l=L(e.config);o=!!l.business?.enabled,t=(l.business?.projects??[]).length}catch(l){n=l?.message??String(l)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(h.bold(" Governance flags")),console.log(),n&&(console.log(h.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let d=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${d(s)}${c?"":h.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?h.green("active"):r?h.yellow("env=true but business.enabled=false \u2192 inactive"):h.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(h.dim(` business.enabled ${o?h.green("true"):h.dim("false")}`)),console.log(h.dim(` business.projects[] ${t}`)),console.log(),console.log(h.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(h.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as Hl}from"commander";import fo from"chalk";import{resolve as ho}from"path";import{existsSync as Gl}from"fs";var io=new Hl().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Ro(e){let o=ho(e,".agentx/db.sqlite");Gl(o)||(console.log(fo.red(` No SQLite at ${o}`)),console.log(fo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=Li({path:o});return t||(console.log(fo.red(` Could not open ${o}`)),console.log(fo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function No(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(fo.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])))}io.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=Ro(ho(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 fo=new Qe().name("config").description("validate and inspect configuration");fo.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async e=>{console.log();try{let o=D(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=en(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=ge(J(r,".claude")),c=ge(J(r,"CLAUDE.md")),d=ge(J(r,".claude/settings.json")),m=ge(J(r,".claude/skills"))?bs(J(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,l=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",d?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${m} skills`];console.log(` ${h.cyan(s)}: ${l.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});fo.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=D(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function zl(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 ws(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}fo.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-5B2YWZMK.js"),{expandEnvVars:r}=await import("./config-S3VHHVYW.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(h.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(t(a,"utf-8")),d=o.raw?c:r(c),m=i(d,e);o.json?console.log(JSON.stringify(m)):console.log(ws(m))});fo.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-5B2YWZMK.js"),r=zl(o,!!t.string),a=await n(d=>{s(d,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(h.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would become: ${ws(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${ws(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})`)))});fo.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-5B2YWZMK.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.")))});fo.command("governance").description("show resolved governance flags (read-only; flags read once at startup)").option("-c, --config <path>","path to agentx.json").option("--json","emit JSON").action(e=>{let o=!1,t=0,n;try{let l=D(e.config);o=!!l.business?.enabled,t=(l.business?.projects??[]).length}catch(l){n=l?.message??String(l)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(h.bold(" Governance flags")),console.log(),n&&(console.log(h.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let d=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${d(s)}${c?"":h.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let m=a?h.green("active"):r?h.yellow("env=true but business.enabled=false \u2192 inactive"):h.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${m}`),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 Yl}from"commander";import ho from"chalk";import{resolve as yo}from"path";import{existsSync as Kl}from"fs";var ro=new Yl().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Ro(e){let o=yo(e,".agentx/db.sqlite");Kl(o)||(console.log(ho.red(` No SQLite at ${o}`)),console.log(ho.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=Fi({path:o});return t||(console.log(ho.red(` Could not open ${o}`)),console.log(ho.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function _o(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(ho.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])))}ro.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=Ro(yo(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=`
43
32
  SELECT agent_id, channel, status, duration_ms,
44
33
  input_tokens, output_tokens,
45
34
  substr(message_preview, 1, 60) AS message,
@@ -48,7 +37,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
48
37
  ${t.length?"WHERE "+t.join(" AND "):""}
49
38
  ORDER BY started_at DESC
50
39
  LIMIT @limit
51
- `,i=o.prepare(s).all({...n,limit:Number(e.limit)});No(i,!!e.json)});io.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=Ro(ho(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)});_o(i,!!e.json)});ro.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=Ro(yo(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?`
52
41
  SELECT agent_id, reason, COUNT(*) AS n,
53
42
  ROUND(AVG(last_turn_input_tokens)) AS avg_input_tokens,
54
43
  MAX(last_turn_input_tokens) AS max_input_tokens
@@ -62,14 +51,14 @@ The AgentX daemon and a speech transcription backend must also be available. Run
62
51
  ${s}
63
52
  ORDER BY rotated_at DESC
64
53
  LIMIT @limit
65
- `,r=o.prepare(i).all({...n,limit:Number(e.limit)});No(r,!!e.json)});io.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=Ro(ho(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)});_o(r,!!e.json)});ro.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=Ro(yo(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=`
66
55
  SELECT day, agent_id, model, tasks,
67
56
  input_tokens AS in_tok, output_tokens AS out_tok,
68
57
  cache_read_tokens AS cache_read, cache_create_tokens AS cache_create
69
58
  FROM usage_daily
70
59
  ${t.length?"WHERE "+t.join(" AND "):""}
71
60
  ORDER BY day DESC, agent_id
72
- `,i=o.prepare(s).all(n);No(i,!!e.json)});io.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=Ro(ho(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);_o(i,!!e.json)});ro.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=Ro(yo(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?`
73
62
  SELECT channel, kind, deciding_stage, COUNT(*) AS n
74
63
  FROM route_traces
75
64
  ${s}
@@ -82,7 +71,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
82
71
  ${s}
83
72
  ORDER BY at DESC
84
73
  LIMIT @limit
85
- `,r=o.prepare(i).all({...n,limit:Number(e.limit)});No(r,!!e.json)});io.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=Ro(ho(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)});_o(r,!!e.json)});ro.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=Ro(yo(e.cwd)),t=["status = 'error'"],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent);let s=`
86
75
  SELECT agent_id, channel, duration_ms,
87
76
  substr(error, 1, 120) AS error,
88
77
  started_at
@@ -90,12 +79,12 @@ The AgentX daemon and a speech transcription backend must also be available. Run
90
79
  WHERE ${t.join(" AND ")}
91
80
  ORDER BY started_at DESC
92
81
  LIMIT @limit
93
- `,i=o.prepare(s).all({...n,limit:Number(e.limit)});No(i,!!e.json)});io.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=Ro(ho(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}));No(n,!!e.json)});io.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=Ro(ho(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(fo.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(fo.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();No(n,!!o.json)}catch(n){console.log(fo.red(` ${n.message}`)),process.exit(1)}});import{Command as Kl}from"commander";import G from"chalk";import{mkdtempSync as Vl}from"fs";import{tmpdir as Xl}from"os";import{resolve as ea,join as oa}from"path";import{existsSync as Ql}from"fs";import Zl from"better-sqlite3";function Zr(e,o,t,n=[]){let s=new Map;for(let c of o)s.set(c.id,c);let i=[];for(let c of t)i.push({kind:"decision",ts:c.decidedAt,decision:c});for(let c of n)i.push({kind:"resolution",ts:c.resolvedAt,resolution:c});i.sort((c,d)=>c.ts!==d.ts?c.ts-d.ts:c.kind===d.kind?0:c.kind==="decision"?-1:1);let r=[],a=0;for(let c of i){if(c.kind==="resolution"){try{e.recordResolution(c.resolution)}catch(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 d=c.decision,g=s.get(d.eventId);if(!g){r.push({eventId:d.eventId,decidedBy:d.decidedBy,expected:{agentId:d.agentId,outcome:d.outcome},actual:{agentId:null,outcome:"skipped"},reason:"decision references event not in snapshot"});continue}let l=zl(d),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=Pi(e,u,l,()=>d.decidedAt);a+=1,(f.outcome!==d.outcome||f.agentId!==d.agentId)&&r.push({eventId:g.id,decidedBy:d.decidedBy,expected:{agentId:d.agentId,outcome:d.outcome},actual:{agentId:f.agentId,outcome:f.outcome},reason:Yl(d,f)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function zl(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function Yl(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 yo=new Kl().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function tt(e){let o=ea(e.cwd??process.cwd()),t=ea(o,e.path??".agentx/intent/ledger.sqlite");Ql(t)||(console.log(G.red(` No ledger at ${t}`)),console.log(G.dim(' Make sure the daemon has run with INTENT_LEDGER_MODE != "off". The file is created on first ledger write.')),process.exit(1));try{return new Zl(t,{readonly:!0})}catch(n){console.log(G.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(G.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function _o(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(G.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}function ed(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 bn(e){if(!e)return;let o=ed(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(G.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}yo.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=tt(e),t=bn(e.since),n=t!==void 0?"WHERE ts >= @since":"",s=t!==void 0?"WHERE decided_at >= @since":"",i=n,r=o.prepare(`SELECT source, COUNT(*) as n FROM intent_events ${n} GROUP BY source ORDER BY n DESC`).all({since:t}),a=o.prepare(`SELECT COUNT(*) as n FROM intent_decisions ${s}`).get({since:t}).n,c=o.prepare(`SELECT outcome, COUNT(*) as n FROM intent_decisions ${s} GROUP BY outcome ORDER BY n DESC`).all({since:t}),d=o.prepare(`SELECT COUNT(*) as n FROM intent_divergences ${i}`).get({since:t}).n,g=o.prepare(`SELECT source, COUNT(*) as n FROM intent_divergences ${i} GROUP BY source ORDER BY n DESC`).all({since:t}),l=o.prepare(`
82
+ `,i=o.prepare(s).all({...n,limit:Number(e.limit)});_o(i,!!e.json)});ro.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=Ro(yo(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}));_o(n,!!e.json)});ro.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=Ro(yo(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(ho.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(ho.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();_o(n,!!o.json)}catch(n){console.log(ho.red(` ${n.message}`)),process.exit(1)}});import{Command as Ql}from"commander";import G from"chalk";import{mkdtempSync as Zl}from"fs";import{tmpdir as ed}from"os";import{resolve as sa,join as ia}from"path";import{existsSync as od}from"fs";import td from"better-sqlite3";function na(e,o,t,n=[]){let s=new Map;for(let c of o)s.set(c.id,c);let i=[];for(let c of t)i.push({kind:"decision",ts:c.decidedAt,decision:c});for(let c of n)i.push({kind:"resolution",ts:c.resolvedAt,resolution:c});i.sort((c,d)=>c.ts!==d.ts?c.ts-d.ts:c.kind===d.kind?0:c.kind==="decision"?-1:1);let r=[],a=0;for(let c of i){if(c.kind==="resolution"){try{e.recordResolution(c.resolution)}catch(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 d=c.decision,m=s.get(d.eventId);if(!m){r.push({eventId:d.eventId,decidedBy:d.decidedBy,expected:{agentId:d.agentId,outcome:d.outcome},actual:{agentId:null,outcome:"skipped"},reason:"decision references event not in snapshot"});continue}let l=Vl(d),u={id:m.id,ts:m.ts,source:m.source,sourceEventId:m.sourceEventId,project:m.project,subject:m.subject,intent:m.intent,rawJson:m.rawJson},f=Ui(e,u,l,()=>d.decidedAt);a+=1,(f.outcome!==d.outcome||f.agentId!==d.agentId)&&r.push({eventId:m.id,decidedBy:d.decidedBy,expected:{agentId:d.agentId,outcome:d.outcome},actual:{agentId:f.agentId,outcome:f.outcome},reason:Xl(d,f)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function Vl(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function Xl(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 wo=new Ql().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function nt(e){let o=sa(e.cwd??process.cwd()),t=sa(o,e.path??".agentx/intent/ledger.sqlite");od(t)||(console.log(G.red(` No ledger at ${t}`)),console.log(G.dim(' Make sure the daemon has run with INTENT_LEDGER_MODE != "off". The file is created on first ledger write.')),process.exit(1));try{return new td(t,{readonly:!0})}catch(n){console.log(G.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(G.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Do(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(G.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}function nd(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 xn(e){if(!e)return;let o=nd(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(G.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}wo.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=nt(e),t=xn(e.since),n=t!==void 0?"WHERE ts >= @since":"",s=t!==void 0?"WHERE decided_at >= @since":"",i=n,r=o.prepare(`SELECT source, COUNT(*) as n FROM intent_events ${n} GROUP BY source ORDER BY n DESC`).all({since:t}),a=o.prepare(`SELECT COUNT(*) as n FROM intent_decisions ${s}`).get({since:t}).n,c=o.prepare(`SELECT outcome, COUNT(*) as n FROM intent_decisions ${s} GROUP BY outcome ORDER BY n DESC`).all({since:t}),d=o.prepare(`SELECT COUNT(*) as n FROM intent_divergences ${i}`).get({since:t}).n,m=o.prepare(`SELECT source, COUNT(*) as n FROM intent_divergences ${i} GROUP BY source ORDER BY n DESC`).all({since:t}),l=o.prepare(`
94
83
  SELECT COUNT(*) as n FROM intent_decisions d
95
84
  LEFT JOIN intent_resolutions r
96
85
  ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
97
86
  WHERE d.outcome = 'dispatched' AND r.decision_event_id IS NULL
98
- `).get().n;if(e.json){console.log(JSON.stringify({since:t??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:d,divergencesBySource:g,inFlight:l},null,2));return}console.log(G.bold("Events by source")),_o(r,!1),console.log(),console.log(G.bold(`Decisions: ${a}`)),_o(c,!1),console.log(),console.log(G.bold(`Divergences: ${d}`)),_o(g,!1),console.log(),console.log(G.bold(`In-flight (dispatched, no resolution): ${l}`))});yo.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=tt(e),t=bn(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
87
+ `).get().n;if(e.json){console.log(JSON.stringify({since:t??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:d,divergencesBySource:m,inFlight:l},null,2));return}console.log(G.bold("Events by source")),Do(r,!1),console.log(),console.log(G.bold(`Decisions: ${a}`)),Do(c,!1),console.log(),console.log(G.bold(`Divergences: ${d}`)),Do(m,!1),console.log(),console.log(G.bold(`In-flight (dispatched, no resolution): ${l}`))});wo.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=nt(e),t=xn(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(`
99
88
  SELECT
100
89
  datetime(ts/1000, 'unixepoch') AS at,
101
90
  source,
@@ -109,7 +98,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
109
98
  ${i}
110
99
  ORDER BY ts DESC
111
100
  LIMIT @limit
112
- `).all(s);_o(r,!!e.json)});yo.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=tt(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);Do(r,!!e.json)});wo.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=nt(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(`
113
102
  SELECT
114
103
  datetime(d.decided_at/1000, 'unixepoch') AS dispatched_at,
115
104
  e.source,
@@ -125,7 +114,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
125
114
  WHERE ${t.join(" AND ")}
126
115
  ORDER BY d.decided_at DESC
127
116
  LIMIT @limit
128
- `).all(n);_o(s,!!e.json)});yo.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=tt(e),t=bn(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);Do(s,!!e.json)});wo.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=nt(e),t=xn(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(`
129
118
  SELECT
130
119
  datetime(ts/1000, 'unixepoch') AS at,
131
120
  source,
@@ -136,7 +125,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
136
125
  ${i}
137
126
  ORDER BY ts DESC
138
127
  LIMIT @limit
139
- `).all(s);_o(r,!!e.json)});yo.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=tt(o),n=null,s=null;if(o.bySubject){let l=e.indexOf(":");l<0&&(console.log(G.red(' --by-subject expects "<project>:<subject>"')),process.exit(1)),n=e.slice(0,l),s=e.slice(l+1)}else{let l=t.prepare("SELECT project, subject FROM intent_events WHERE id = ?").get(e);l||(console.log(G.red(` no event with id ${e}`)),process.exit(1)),n=l.project,s=l.subject,(n===null||s===null)&&(console.log(G.yellow(` event ${e} has no (project, subject) \u2014 lineage requires both`)),n&&console.log(G.dim(` project: ${n}`)),s&&console.log(G.dim(` subject: ${s}`)),process.exit(1))}let i=t.prepare(`SELECT id, ts, source, COALESCE(intent, '-') AS intent, COALESCE(source_event_id, '-') AS source_event_id
128
+ `).all(s);Do(r,!!e.json)});wo.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=nt(o),n=null,s=null;if(o.bySubject){let l=e.indexOf(":");l<0&&(console.log(G.red(' --by-subject expects "<project>:<subject>"')),process.exit(1)),n=e.slice(0,l),s=e.slice(l+1)}else{let l=t.prepare("SELECT project, subject FROM intent_events WHERE id = ?").get(e);l||(console.log(G.red(` no event with id ${e}`)),process.exit(1)),n=l.project,s=l.subject,(n===null||s===null)&&(console.log(G.yellow(` event ${e} has no (project, subject) \u2014 lineage requires both`)),n&&console.log(G.dim(` project: ${n}`)),s&&console.log(G.dim(` subject: ${s}`)),process.exit(1))}let i=t.prepare(`SELECT id, ts, source, COALESCE(intent, '-') AS intent, COALESCE(source_event_id, '-') AS source_event_id
140
129
  FROM intent_events WHERE project = ? AND subject = ? ORDER BY ts ASC`).all(n,s);if(i.length===0){console.log(G.dim(` (no events for ${n}:${s})`));return}let r=i.map(l=>l.id),a=r.map((l,u)=>`@id${u}`).join(", "),c=Object.fromEntries(r.map((l,u)=>[`id${u}`,l])),d=t.prepare(`
141
130
  SELECT d.event_id, d.decided_at, d.decided_by, d.agent_id, d.outcome, d.reason,
142
131
  r.resolved_at, r.status AS resolution_status, r.duration_ms, r.result_summary
@@ -145,13 +134,13 @@ The AgentX daemon and a speech transcription backend must also be available. Run
145
134
  ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
146
135
  WHERE d.event_id IN (${a})
147
136
  ORDER BY d.decided_at ASC
148
- `).all(c);if(o.json){let l=i.map(u=>({event:u,decisions:d.filter(f=>f.event_id===u.id)}));console.log(JSON.stringify({project:n,subject:s,lineage:l},null,2));return}let g=new Set;for(let l of d)l.outcome==="dispatched"&&l.agent_id&&g.add(l.agent_id);console.log(),console.log(G.bold(` Lineage for ${G.cyan(n+":"+s)}`)),console.log(G.dim(` ${i.length} event(s), ${d.length} decision(s), ${g.size} distinct agent(s) dispatched`)),console.log();for(let l of i){let u=new Date(l.ts).toISOString().slice(0,19).replace("T"," ");console.log(` ${G.dim(u)} ${G.bold(l.id)} ${G.dim(`(${l.source}/${l.intent})`)}`);let f=d.filter(p=>p.event_id===l.id);if(f.length===0){console.log(G.dim(" (no decisions yet)"));continue}for(let p of f){let w=p.outcome==="dispatched"?G.green(p.outcome):p.outcome==="dropped"?G.dim(p.outcome):G.yellow(p.outcome),y=p.agent_id?G.cyan(p.agent_id):G.dim("-"),$=p.reason?G.dim(` \u2014 ${p.reason.slice(0,60)}`):"";if(console.log(` ${G.dim(p.decided_by)} \u2192 ${w} ${y}${$}`),p.resolution_status){let b=p.resolution_status==="ok"?G.green(p.resolution_status):G.red(p.resolution_status),v=p.duration_ms?`${(p.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${G.dim("resolved")} ${b} ${G.dim(v)}`)}else p.outcome==="dispatched"&&console.log(` ${G.yellow("(in-flight, no resolution)")}`)}}console.log()});yo.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=tt(e),t=bn(e.since),n=[],s={};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=e.limit?`LIMIT ${Number(e.limit)}`:"",r=o.prepare(`
137
+ `).all(c);if(o.json){let l=i.map(u=>({event:u,decisions:d.filter(f=>f.event_id===u.id)}));console.log(JSON.stringify({project:n,subject:s,lineage:l},null,2));return}let m=new Set;for(let l of d)l.outcome==="dispatched"&&l.agent_id&&m.add(l.agent_id);console.log(),console.log(G.bold(` Lineage for ${G.cyan(n+":"+s)}`)),console.log(G.dim(` ${i.length} event(s), ${d.length} decision(s), ${m.size} distinct agent(s) dispatched`)),console.log();for(let l of i){let u=new Date(l.ts).toISOString().slice(0,19).replace("T"," ");console.log(` ${G.dim(u)} ${G.bold(l.id)} ${G.dim(`(${l.source}/${l.intent})`)}`);let f=d.filter(p=>p.event_id===l.id);if(f.length===0){console.log(G.dim(" (no decisions yet)"));continue}for(let p of f){let w=p.outcome==="dispatched"?G.green(p.outcome):p.outcome==="dropped"?G.dim(p.outcome):G.yellow(p.outcome),y=p.agent_id?G.cyan(p.agent_id):G.dim("-"),$=p.reason?G.dim(` \u2014 ${p.reason.slice(0,60)}`):"";if(console.log(` ${G.dim(p.decided_by)} \u2192 ${w} ${y}${$}`),p.resolution_status){let b=p.resolution_status==="ok"?G.green(p.resolution_status):G.red(p.resolution_status),v=p.duration_ms?`${(p.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${G.dim("resolved")} ${b} ${G.dim(v)}`)}else p.outcome==="dispatched"&&console.log(` ${G.yellow("(in-flight, no resolution)")}`)}}console.log()});wo.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=nt(e),t=xn(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(`
149
138
  SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
150
139
  FROM intent_events
151
140
  ${n.length?"WHERE "+n.join(" AND "):""}
152
141
  ORDER BY ts ASC
153
142
  ${i}
154
- `).all(s).map(p=>({id:p.id,ts:p.ts,source:p.source,sourceEventId:p.source_event_id,project:p.project,subject:p.subject,intent:p.intent,rawJson:p.raw_json}));if(r.length===0){console.log(G.dim(" (no events match filter)"));return}let a=new Set(r.map(p=>p.id)),c=r.map((p,w)=>`@id${w}`).join(", "),d=Object.fromEntries(r.map((p,w)=>[`id${w}`,p.id])),g=o.prepare(`
143
+ `).all(s).map(p=>({id:p.id,ts:p.ts,source:p.source,sourceEventId:p.source_event_id,project:p.project,subject:p.subject,intent:p.intent,rawJson:p.raw_json}));if(r.length===0){console.log(G.dim(" (no events match filter)"));return}let a=new Set(r.map(p=>p.id)),c=r.map((p,w)=>`@id${w}`).join(", "),d=Object.fromEntries(r.map((p,w)=>[`id${w}`,p.id])),m=o.prepare(`
155
144
  SELECT event_id, decided_at, decided_by, agent_id, outcome, reason
156
145
  FROM intent_decisions
157
146
  WHERE event_id IN (${c})
@@ -159,7 +148,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
159
148
  SELECT decision_event_id, decision_decided_by, resolved_at, status, duration_ms, result_summary
160
149
  FROM intent_resolutions
161
150
  WHERE decision_event_id IN (${c})
162
- `).all(d).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=Vl(oa(Xl(),"agentx-ledger-replay-")),f=new Ci({path:oa(u,"target.sqlite")});try{let p=Zr(f,r,g,l);if(e.json){console.log(JSON.stringify(p,null,2));return}console.log(G.bold(`Replayed ${p.eventsCount} events, ${p.decisionsCount} decisions, ${l.length} resolutions`)),p.divergences.length===0?console.log(G.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(G.red(` \u2717 ${p.divergences.length} divergences`)),_o(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();nl();sl();il();tl();xi();bt();import{Command as od}from"commander";import F from"chalk";import{existsSync as ta}from"fs";import{resolve as bs}from"path";import td from"better-sqlite3";var De=new od().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),He=".agentx/decisions/decisions.sqlite";function nd(e){return bs(bs(e.cwd??process.cwd()),e.path??He)}function eo(e,o=!1){let t=nd(e);ta(t)||(console.log(F.red(` No decision store at ${t}`)),console.log(F.dim(' Set decisions.enabled and give a seat mode "shadow" (or export AGENTX_DECISION_SEAT_<SEAT>=shadow). The file is created on the first recorded call.')),process.exit(1));try{return new Zt({path:t,readonly:!o})}catch(n){console.log(F.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(F.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Ze(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(F.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(F.bold(s(t)));for(let i of e)console.log(s(t.map(r=>i[r])))}function $s(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 ks(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:$s(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}De.command("stats").description("per-seat call counts, failure rate, repair rate and latency").option("--path <file>","store path",He).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let o=eo(e),t=$s(e.since)??0,n=o.db.prepare(`SELECT seat, mode, backend, model, structure_mode AS structureMode,
151
+ `).all(d).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=Zl(ia(ed(),"agentx-ledger-replay-")),f=new Ni({path:ia(u,"target.sqlite")});try{let p=na(f,r,m,l);if(e.json){console.log(JSON.stringify(p,null,2));return}console.log(G.bold(`Replayed ${p.eventsCount} events, ${p.decisionsCount} decisions, ${l.length} resolutions`)),p.divergences.length===0?console.log(G.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(G.red(` \u2717 ${p.divergences.length} divergences`)),Do(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();al();cl();ll();rl();Ai();$t();import{Command as sd}from"commander";import F from"chalk";import{existsSync as ra}from"fs";import{resolve as vs}from"path";import id from"better-sqlite3";var De=new sd().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),He=".agentx/decisions/decisions.sqlite";function rd(e){return vs(vs(e.cwd??process.cwd()),e.path??He)}function eo(e,o=!1){let t=rd(e);ra(t)||(console.log(F.red(` No decision store at ${t}`)),console.log(F.dim(' Set decisions.enabled and give a seat mode "shadow" (or export AGENTX_DECISION_SEAT_<SEAT>=shadow). The file is created on the first recorded call.')),process.exit(1));try{return new Zt({path:t,readonly:!o})}catch(n){console.log(F.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(F.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Ze(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(F.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(F.bold(s(t)));for(let i of e)console.log(s(t.map(r=>i[r])))}function xs(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 Ss(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:xs(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}De.command("stats").description("per-seat call counts, failure rate, repair rate and latency").option("--path <file>","store path",He).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let o=eo(e),t=xs(e.since)??0,n=o.db.prepare(`SELECT seat, mode, backend, model, structure_mode AS structureMode,
163
152
  COUNT(*) AS calls,
164
153
  SUM(CASE WHEN error IS NOT NULL THEN 1 ELSE 0 END) AS failed,
165
154
  SUM(retries) AS retries,
@@ -174,11 +163,11 @@ The AgentX daemon and a speech transcription backend must also be available. Run
174
163
  ORDER BY calls DESC`).all(t);!e.json&&s.length>0&&(console.log(F.bold(`
175
164
  policy`)),Ze(s,!1),console.log(F.dim(`
176
165
  explored=1 means the policy wanted to skip and the expensive path ran anyway.
177
- Those are the only rows in the skip region that can ever be graded.`))),o.close()});De.command("calls").description("recent calls").option("--path <file>","store path",He).option("--seat <seat>").option("--since <window>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=eo(e),t=["ts >= ?"],n=[$s(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()});De.command("calls").description("recent calls").option("--path <file>","store path",He).option("--seat <seat>").option("--since <window>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=eo(e),t=["ts >= ?"],n=[xs(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,
178
167
  structure_mode AS structure, latency_ms AS ms, retries, truncated, error
179
168
  FROM decision_calls WHERE ${t.join(" AND ")}
180
- ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));Ze(s,e.json),o.close()});De.command("answers <callId>").description("every answer on one call, with its incumbent and label").option("--path <file>","store path",He).option("--json").action((e,o)=>{let t=eo(o),n=t.gradedRows({}).filter(s=>s.callId===e);if(n.length===0){console.log(F.dim(` (no answers for ${e} \u2014 check \`decisions calls\`)`)),t.close();return}Ze(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()});De.command("label <callId> <question> <value>").description("attach ground truth to one answer (append-only; newest wins)").option("--path <file>","store path",He).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,o,t,n)=>{let s=eo(n,!0);s.label(e,o,t,{kind:n.kind,labeledBy:n.by,note:n.note}),console.log(F.green(` labeled ${e}.${o} = ${t}`)),s.close()});De.command("unlabeled").description("lowest-confidence unlabeled answers first \u2014 the most informative to label").option("--path <file>","store path",He).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=eo(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));Ze(t.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),o.close()});De.command("backfill-labels").description("derive ground truth from what actually happened (monitor-prefilter seat)").option("--path <file>","store path",He).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let o=eo(e,!0),t=bs(process.cwd(),e.db);ta(t)||(console.log(F.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new td(t,{readonly:!0});try{let s=Ji(n,o);console.log(F.green(` wrote ${s} label(s)`)),s===0&&console.log(F.dim(` Rows whose outcome is genuinely ambiguous stay unlabeled on purpose \u2014
181
- label those by hand: agentx decisions unlabeled --seat monitor-prefilter`))}finally{n.close(),o.close()}});De.command("calibrate").description("is this seat's confidence worth anything? reliability, ECE, Brier, temperature").option("--path <file>","store path",He).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=eo(e),t=o.gradedRows(ks(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(F.bold(`
169
+ ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));Ze(s,e.json),o.close()});De.command("answers <callId>").description("every answer on one call, with its incumbent and label").option("--path <file>","store path",He).option("--json").action((e,o)=>{let t=eo(o),n=t.gradedRows({}).filter(s=>s.callId===e);if(n.length===0){console.log(F.dim(` (no answers for ${e} \u2014 check \`decisions calls\`)`)),t.close();return}Ze(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()});De.command("label <callId> <question> <value>").description("attach ground truth to one answer (append-only; newest wins)").option("--path <file>","store path",He).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,o,t,n)=>{let s=eo(n,!0);s.label(e,o,t,{kind:n.kind,labeledBy:n.by,note:n.note}),console.log(F.green(` labeled ${e}.${o} = ${t}`)),s.close()});De.command("unlabeled").description("lowest-confidence unlabeled answers first \u2014 the most informative to label").option("--path <file>","store path",He).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=eo(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));Ze(t.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),o.close()});De.command("backfill-labels").description("derive ground truth from what actually happened (monitor-prefilter seat)").option("--path <file>","store path",He).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let o=eo(e,!0),t=vs(process.cwd(),e.db);ra(t)||(console.log(F.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new id(t,{readonly:!0});try{let s=zi(n,o);console.log(F.green(` wrote ${s} label(s)`)),s===0&&console.log(F.dim(` Rows whose outcome is genuinely ambiguous stay unlabeled on purpose \u2014
170
+ label those by hand: agentx decisions unlabeled --seat monitor-prefilter`))}finally{n.close(),o.close()}});De.command("calibrate").description("is this seat's confidence worth anything? reliability, ECE, Brier, temperature").option("--path <file>","store path",He).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=eo(e),t=o.gradedRows(Ss(e)),n=vi(t,{minN:Number(e.minN),bins:Number(e.bins)});if(e.json){console.log(JSON.stringify(n,null,2)),o.close();return}if(console.log(F.bold(`
182
171
  ${e.seat}${e.question?`.${e.question}`:""}`)),console.log(` ${n.n} answers, ${n.nLabeled} labeled`+(n.agreement.n>0?`, ${n.agreement.n} with an incumbent (agree ${(n.agreement.rate*100).toFixed(1)}%, kappa ${n.agreement.kappa.toFixed(3)})`:"")),n.insufficient){console.log(F.yellow(`
183
172
  Not enough ground truth: ${n.nLabeled} labeled rows, need ${n.minN}.`)),console.log(F.dim(" An ECE on this little data is noise, and a noisy number on a dashboard gets acted on.")),console.log(F.dim(` Label the most informative rows: agentx decisions unlabeled --seat ${e.seat}`)),o.close();return}console.log(`
184
173
  accuracy ${(n.accuracy*100).toFixed(1)}%`),console.log(` ECE ${n.ece.toFixed(4)} `+F.dim(`[95% CI ${n.eceInterval.lo.toFixed(4)}\u2013${n.eceInterval.hi.toFixed(4)}]`)),console.log(` ECE (mass) ${n.eceEqualMass.toFixed(4)} ${F.dim("equal-mass bins")}`),console.log(` MCE ${n.mce.toFixed(4)} ${F.dim("worst single bin")}`),console.log(` Brier ${n.brier.toFixed(4)} ${F.dim("proper score, lower is better")}`),console.log(` log loss ${n.logLoss.toFixed(4)}`);let s=n.temperature;console.log(`
@@ -186,21 +175,21 @@ The AgentX daemon and a speech transcription backend must also be available. Run
186
175
  skip region ${i.length} answers (${(i.length/t.length*100).toFixed(1)}% of traffic), ${r.length} gradeable`),r.length===0&&console.log(F.yellow(` Nothing in the skip region has been graded. Everything below describes
187
176
  only the decisions this policy chose NOT to skip \u2014 it cannot tell you
188
177
  what skipping would cost. Raise decisions.seats.<seat>.explore.`))),console.log(F.bold(`
189
- reliability (equal-width bins)`)),Ze(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()});De.command("recalibrate").description("is one global temperature enough, or does calibration differ by group?").option("--path <file>","store path",He).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=eo(e),t=o.gradedRows(ks(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=$i(t,{covariates:n},{folds:Number(e.folds),minN:Number(e.minN)});if(e.json){console.log(JSON.stringify(s,null,2)),o.close();return}if(s.insufficient){console.log(F.yellow(` ${s.n} labeled rows, need ${s.minN}.`)),o.close();return}console.log(F.bold(`
178
+ reliability (equal-width bins)`)),Ze(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()});De.command("recalibrate").description("is one global temperature enough, or does calibration differ by group?").option("--path <file>","store path",He).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=eo(e),t=o.gradedRows(Ss(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=xi(t,{covariates:n},{folds:Number(e.folds),minN:Number(e.minN)});if(e.json){console.log(JSON.stringify(s,null,2)),o.close();return}if(s.insufficient){console.log(F.yellow(` ${s.n} labeled rows, need ${s.minN}.`)),o.close();return}console.log(F.bold(`
190
179
  ${e.seat} \u2014 held-out comparison (${s.folds}-fold, n=${s.n})`)),console.log(F.dim(` Cross-validated, because more parameters always fit training data better.
191
180
  `)),Ze(s.scores.map(i=>({model:i.name,logLoss:i.logLoss.toFixed(4),brier:i.brier.toFixed(4),best:i.name===s.best?"<-":""})),!1),s.best==="covariate"?(console.log(F.green(`
192
181
  Calibration differs by ${n.join("/")} \u2014 a single temperature averages groups`)),console.log(F.dim(" that need different corrections."))):s.best==="temperature"?console.log(F.dim(`
193
182
  One global temperature is enough. ${n.join("/")} carries no calibration signal here.`)):console.log(F.dim(`
194
- Neither correction beats the raw confidence out of sample. Leave it alone.`)),o.close()});De.command("coverage").description("accuracy at each threshold against the traffic it keeps \u2014 read this to pick one").option("--path <file>","store path",He).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=eo(e),t=o.gradedRows({...ks(e),labeledOnly:!0}),n=wi(t,Number(e.steps));if(n.length===0){console.log(F.yellow(` No labeled rows for seat "${e.seat}".`)),o.close();return}Ze(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()});De.command("consistency").description("does the question hold still? resample one recorded state N times").option("--path <file>","store path",He).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=>{Bo();let o=eo(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()});De.command("coverage").description("accuracy at each threshold against the traffic it keeps \u2014 read this to pick one").option("--path <file>","store path",He).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=eo(e),t=o.gradedRows({...Ss(e),labeledOnly:!0}),n=ki(t,Number(e.steps));if(n.length===0){console.log(F.yellow(` No labeled rows for seat "${e.seat}".`)),o.close();return}Ze(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()});De.command("consistency").description("does the question hold still? resample one recorded state N times").option("--path <file>","store path",He).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=>{Jo();let o=eo(e),t=o.db.prepare(`SELECT id, backend, model, state_json, questions_json FROM decision_calls
195
184
  WHERE seat = ? AND state_json IS NOT NULL AND error IS NULL
196
185
  ${e.call?"AND id = ?":""}
197
- ORDER BY ts DESC LIMIT 1`).get(...e.call?[e.seat,e.call]:[e.seat]);if(!t){console.log(F.yellow(` No recorded call with stored state for seat "${e.seat}".`)),console.log(F.dim(" State is kept for the first `keepStateRows` per seat; see decisions.redactState.")),o.close();return}let n=e.backend??t.backend,s=e.model??(n===t.backend?t.model:void 0),i=await ki(n,JSON.parse(t.state_json),JSON.parse(t.questions_json),{samples:Number(e.samples),model:s});if(e.json){console.log(JSON.stringify(i,null,2)),o.close();return}console.log(F.bold(`
186
+ ORDER BY ts DESC LIMIT 1`).get(...e.call?[e.seat,e.call]:[e.seat]);if(!t){console.log(F.yellow(` No recorded call with stored state for seat "${e.seat}".`)),console.log(F.dim(" State is kept for the first `keepStateRows` per seat; see decisions.redactState.")),o.close();return}let n=e.backend??t.backend,s=e.model??(n===t.backend?t.model:void 0),i=await Si(n,JSON.parse(t.state_json),JSON.parse(t.questions_json),{samples:Number(e.samples),model:s});if(e.json){console.log(JSON.stringify(i,null,2)),o.close();return}console.log(F.bold(`
198
187
  ${e.seat} on ${i.backend} (${i.model})`)),console.log(F.dim(` ${i.samples} samples of call ${t.id}, ${i.totalMs}ms, ${i.usage.inputTokens.toLocaleString()} input tokens
199
188
  `)),Ze(i.questions.map(r=>({question:r.question,mean:r.mean.toFixed(4),stdev:r.stdev.toFixed(4),min:r.min.toFixed(3),max:r.max.toFixed(3),answers:r.distinctAnswers.join("/"),band:r.bands.join("/"),stable:r.crossesThreshold?F.red("NO"):"yes"})),!1),console.log(`
200
189
  mean stdev ${i.meanStdev.toFixed(4)}`),console.log(F.dim(" TypeSafe publish 0.0102 for jev across a 14-question rubric, as a reference.")),i.unstable.length>0?(console.log(F.red(`
201
190
  Unstable: ${i.unstable.join(", ")} \u2014 identical calls disagree about what to DO,`)),console.log(F.dim(` not merely by how much. Usually a compound question: one name, several questions.
202
191
  Split it, or narrow it to a single clause in the state's own vocabulary.`))):console.log(F.green(`
203
- Every question held its decision across all samples.`)),console.log(F.dim("\n Stability is not correctness. A question can hold perfectly still and be\n perfectly wrong \u2014 that is what `decisions calibrate` is for.")),o.close()});De.command("backends").description("registered decision backends and what they claim").action(()=>{Bo();let e=ui().map(o=>{let t=Qn(o).capabilities;return{backend:o,source:t.probabilitySource,calibrated:t.calibratedProbabilities?"yes":"no",maxOptions:t.maxChoiceOptions,maxStateChars:t.maxStateChars}});Ze(e,!1),console.log(F.dim(`
192
+ Every question held its decision across all samples.`)),console.log(F.dim("\n Stability is not correctness. A question can hold perfectly still and be\n perfectly wrong \u2014 that is what `decisions calibrate` is for.")),o.close()});De.command("backends").description("registered decision backends and what they claim").action(()=>{Jo();let e=yi().map(o=>{let t=os(o).capabilities;return{backend:o,source:t.probabilitySource,calibrated:t.calibratedProbabilities?"yes":"no",maxOptions:t.maxChoiceOptions,maxStateChars:t.maxStateChars}});Ze(e,!1),console.log(F.dim(`
204
193
  source where the numbers come from. "verbalized" means the model wrote them
205
194
  into its answer; "logits" means they were read off its next-token
206
195
  distribution. Logits are the model's actual posterior \u2014 verbalized
@@ -208,15 +197,15 @@ The AgentX daemon and a speech transcription backend must also be available. Run
208
197
  calibrated whether an answer given 0.8 is right about 80% of the time ON YOUR
209
198
  traffic. Reading real logits does not buy this: a posterior can be
210
199
  confidently wrong. It comes from a recalibrator fitted on your own
211
- labeled rows \u2014 see \`agentx decisions recalibrate\`.`))});De.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=>{Bo();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=Wo(s,"Which option fits this state?")}e.noul&&(o.verdict=no(String(e.noul))),Object.keys(o).length===0&&(console.log(F.red(" Give at least one of --choice or --noul.")),process.exit(1));let n=await Qn(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as sd}from"commander";import I from"chalk";import{resolve as na}from"path";import{existsSync as id}from"fs";import rd from"better-sqlite3";var Rt=new sd().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function xs(e){let o=na(e.cwd??process.cwd()),t=na(o,e.path??".agentx/db.sqlite");id(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 rd(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 ad(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 cd(e){if(!e)return;let o=ad(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 ld(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 vs(e){return e==="ok"?I.green:e==="error"||e==="timeout"?I.red:e==="in-flight"?I.yellow:I.dim}Rt.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=xs(e),t=Mi(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:cd(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=vs(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(ld(n.startedAt))}`),n.error&&console.log(` ${I.red("error:")} ${n.error}`)}});Rt.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=xs(o),n=ts(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}dd(n.task,n.steps)});function dd(e,o){let t=vs(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?vs(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(`
200
+ labeled rows \u2014 see \`agentx decisions recalibrate\`.`))});De.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=>{Jo();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=Bo(s,"Which option fits this state?")}e.noul&&(o.verdict=so(String(e.noul))),Object.keys(o).length===0&&(console.log(F.red(" Give at least one of --choice or --noul.")),process.exit(1));let n=await os(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as ad}from"commander";import I from"chalk";import{resolve as aa}from"path";import{existsSync as cd}from"fs";import ld from"better-sqlite3";var Rt=new ad().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function As(e){let o=aa(e.cwd??process.cwd()),t=aa(o,e.path??".agentx/db.sqlite");cd(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 ld(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 dd(e){let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!o)return null;let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function gd(e){if(!e)return;let o=dd(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(I.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}function md(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 Es(e){return e==="ok"?I.green:e==="error"||e==="timeout"?I.red:e==="in-flight"?I.yellow:I.dim}Rt.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=As(e),t=qi(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:gd(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=Es(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(md(n.startedAt))}`),n.error&&console.log(` ${I.red("error:")} ${n.error}`)}});Rt.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=As(o),n=is(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}pd(n.task,n.steps)});function pd(e,o){let t=Es(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?Es(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(`
212
201
  `).slice(0,8);console.log(r.map(a=>` ${I.dim("\u2192")} ${a}`).join(`
213
202
  `)),n.inputSummary.split(`
214
203
  `).length>8&&console.log(` ${I.dim("\u2026")}`)}if(n.outputSummary){let r=n.outputSummary.split(`
215
204
  `).slice(0,8);console.log(r.map(a=>` ${I.dim("\u2190")} ${a}`).join(`
216
205
  `)),n.outputSummary.split(`
217
- `).length>8&&console.log(` ${I.dim("\u2026")}`)}n.error&&console.log(` ${I.red("error:")} ${n.error}`)}}Rt.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=xs(o),n=ts(t,e);n||(console.log(I.red(` task not found: ${e}`)),console.log(I.dim(" agentx trace list \u2014 see what's available")),process.exit(1));let s=n.task,i=s.originalMessage??s.messagePreview;i||(console.log(I.red(` task ${e} has no recorded input message \u2014 cannot replay`)),process.exit(1)),!s.originalMessage&&s.messagePreview!=null&&console.log(I.yellow(" \u26A0 pre-migration-v8 row: input message was capped at 200 chars; replay uses the preview")),console.log(),console.log(I.bold(` replay ${I.cyan(e)}`)),console.log(I.dim(` agent=${s.agentId} channel=${s.channel??"\u2014"} chatId=${s.chatId??"\u2014"}`)),console.log(I.dim(` original status=${s.status} duration=${s.durationMs??"?"}ms tokens=in:${s.inputTokens??0}/out:${s.outputTokens??0}`)),console.log();let a=String(o.daemon).replace(/\/+$/,""),c={agent:s.agentId,message:i,freshSession:o.fresh!==!1,context:{channel:s.channel??"api",chatId:`replay-${e.toLowerCase().slice(-8)}-${Date.now().toString(36)}`}},d=Date.now(),g;try{g=await fetch(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})}catch(f){console.log(I.red(` daemon unreachable at ${a}: ${f.message||f}`)),process.exit(1)}let l=await g.json().catch(()=>({})),u=Date.now()-d;if(g.ok||(console.log(I.red(` replay failed (${g.status}): ${l.error||"unknown error"}`)),process.exit(1)),o.diff){console.log(I.bold(" INPUT (replayed verbatim)")),console.log(),$n(i),console.log(),console.log(I.bold(` ORIGINAL OUTPUT ${I.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?$n(s.finalResponse):console.log(I.yellow(" (not captured \u2014 pre-migration-v8 row, or response was empty)")),console.log(),console.log(I.bold(` CURRENT OUTPUT ${I.dim(`status=${l.error?"error":"ok"} ${u}ms tokens=in:${l.usage?.inputTokens??0}/out:${l.usage?.outputTokens??0}`)}`)),console.log(),$n(l.content??"(empty reply)"),l.error&&console.log(I.red(` error: ${l.error}`)),console.log();let f=(s.finalResponse??"").trim()===(l.content??"").trim();s.finalResponse&&(console.log(f?I.dim(" outputs are identical"):I.yellow(" outputs differ \u2014 read both blocks to see what changed")),console.log())}else console.log(I.green(` \u2713 replayed in ${u}ms`)),console.log(),$n(l.content??"(empty reply)"),l.error&&console.log(I.red(`
218
- error: ${l.error}`)),console.log(),console.log(I.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function $n(e){let o=e.split(`
219
- `),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 ud}from"commander";import ce from"chalk";import{existsSync as fd,mkdirSync as hd,writeFileSync as yd}from"fs";import{resolve as ra,join as ia,dirname as wd}from"path";var gd=`# AgentX destructive-action guardrails \u2014 global policy
206
+ `).length>8&&console.log(` ${I.dim("\u2026")}`)}n.error&&console.log(` ${I.red("error:")} ${n.error}`)}}Rt.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=As(o),n=is(t,e);n||(console.log(I.red(` task not found: ${e}`)),console.log(I.dim(" agentx trace list \u2014 see what's available")),process.exit(1));let s=n.task,i=s.originalMessage??s.messagePreview;i||(console.log(I.red(` task ${e} has no recorded input message \u2014 cannot replay`)),process.exit(1)),!s.originalMessage&&s.messagePreview!=null&&console.log(I.yellow(" \u26A0 pre-migration-v8 row: input message was capped at 200 chars; replay uses the preview")),console.log(),console.log(I.bold(` replay ${I.cyan(e)}`)),console.log(I.dim(` agent=${s.agentId} channel=${s.channel??"\u2014"} chatId=${s.chatId??"\u2014"}`)),console.log(I.dim(` original status=${s.status} duration=${s.durationMs??"?"}ms tokens=in:${s.inputTokens??0}/out:${s.outputTokens??0}`)),console.log();let a=String(o.daemon).replace(/\/+$/,""),c={agent:s.agentId,message:i,freshSession:o.fresh!==!1,context:{channel:s.channel??"api",chatId:`replay-${e.toLowerCase().slice(-8)}-${Date.now().toString(36)}`}},d=Date.now(),m;try{m=await fetch(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})}catch(f){console.log(I.red(` daemon unreachable at ${a}: ${f.message||f}`)),process.exit(1)}let l=await m.json().catch(()=>({})),u=Date.now()-d;if(m.ok||(console.log(I.red(` replay failed (${m.status}): ${l.error||"unknown error"}`)),process.exit(1)),o.diff){console.log(I.bold(" INPUT (replayed verbatim)")),console.log(),Sn(i),console.log(),console.log(I.bold(` ORIGINAL OUTPUT ${I.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?Sn(s.finalResponse):console.log(I.yellow(" (not captured \u2014 pre-migration-v8 row, or response was empty)")),console.log(),console.log(I.bold(` CURRENT OUTPUT ${I.dim(`status=${l.error?"error":"ok"} ${u}ms tokens=in:${l.usage?.inputTokens??0}/out:${l.usage?.outputTokens??0}`)}`)),console.log(),Sn(l.content??"(empty reply)"),l.error&&console.log(I.red(` error: ${l.error}`)),console.log();let f=(s.finalResponse??"").trim()===(l.content??"").trim();s.finalResponse&&(console.log(f?I.dim(" outputs are identical"):I.yellow(" outputs differ \u2014 read both blocks to see what changed")),console.log())}else console.log(I.green(` \u2713 replayed in ${u}ms`)),console.log(),Sn(l.content??"(empty reply)"),l.error&&console.log(I.red(`
207
+ error: ${l.error}`)),console.log(),console.log(I.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function Sn(e){let o=e.split(`
208
+ `),t=60,n=o.slice(0,t);for(let s of n)console.log(` ${I.dim("\u2502")} ${s}`);o.length>t&&console.log(` ${I.dim("\u2502")} ${I.dim(`\u2026+${o.length-t} more lines`)}`)}import{Command as yd}from"commander";import ce from"chalk";import{existsSync as wd,mkdirSync as bd,writeFileSync as $d}from"fs";import{resolve as da,join as la,dirname as kd}from"path";var ud=`# AgentX destructive-action guardrails \u2014 global policy
220
209
  #
221
210
  # This file + environments/*.yaml + agents/<id>.yaml are deep-merged
222
211
  # (most specific wins). The built-in catalog (prisma / rm -rf / docker /
@@ -242,7 +231,7 @@ defaults:
242
231
  # action: escalate
243
232
  # severity: high
244
233
  rules: []
245
- `,md=`# Production protected resources.
234
+ `,fd=`# Production protected resources.
246
235
  #
247
236
  # The catalog rules reference \`target_in: production\`, so DECLARING this set is
248
237
  # what arms them. \`resolve_env: true\` expands $VAR / \${VAR} and reads .env* in
@@ -264,7 +253,7 @@ protected_resources:
264
253
 
265
254
  # Production-only rules beyond the catalog:
266
255
  rules: []
267
- `,pd=`# Per-agent override for coder-agent. Top-level rules here are auto-scoped to
256
+ `,hd=`# Per-agent override for coder-agent. Top-level rules here are auto-scoped to
268
257
  # this agent (the filename names it). coder agents never touch production.
269
258
  rules:
270
259
  - id: coder-no-prod
@@ -273,7 +262,7 @@ rules:
273
262
  action: deny
274
263
  severity: critical
275
264
  message: "coder-agent is not permitted to run commands against production."
276
- `,sa=[{relPath:"policy.yaml",content:gd},{relPath:"environments/production.yaml",content:md},{relPath:"agents/coder-agent.yaml",content:pd}];var wo=new ud().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function Ss(e){return e==="deny"?ce.red:e==="escalate"||e==="ask"?ce.yellow:e==="warn"?ce.magenta:ce.green}function kn(e){return e.root?ra(e.root):cr()}wo.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 ar({root:kn(e),agentId:e.agent,env:e.env}),process.exit(0)});wo.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=kn(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=rr({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}bd(s,i,r)});function bd(e,o,t){let n=Ss(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":ce.dim(" (no rule matched)")}`),console.log(` enforced as ${Ss(e.effectiveAction)(e.effectiveAction)} ${ce.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${ce.cyan(e.ruleId)}${e.severity?ce.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${ce.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${ce.dim(`evaluated in ${t}ms`)}`),console.log()}wo.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=ir({root:kn(e),verdict:e.verdict,agentId:e.agent,taskId:e.task,limit:parseInt(e.limit,10)||30});if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(ce.dim(" (no guardrail decisions recorded yet)"));return}for(let t of o){let n=new Date(t.ts).toISOString().replace("T"," ").slice(0,19),s=Ss(t.verdict),i=t.effective_action!==t.verdict?ce.dim(`->${t.effective_action}`):"";console.log(` ${ce.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${ce.cyan((t.agent_id??"?").padEnd(16))} ${ce.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(ce.dim(` target: ${t.resolved_target}`))}});wo.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=ia(ra(e.root),nr),t=0;for(let n of sa){let s=ia(o,n.relPath);if(fd(s)&&!e.force){console.log(ce.dim(` skip (exists) ${n.relPath}`));continue}hd(wd(s),{recursive:!0}),yd(s,n.content),console.log(ce.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${ce.cyan(o)}`),console.log(ce.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(ce.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});wo.command("reload").description("signal the daemon to reload (note: guard policy is read live per tool call already)").option("--url <url>","daemon base url",process.env.AGENTX_DAEMON_URL||"http://localhost:19900").action(async e=>{try{let o=await fetch(`${String(e.url).replace(/\/$/,"")}/reload`,{method:"POST"});o.ok?console.log(ce.green(` daemon reloaded (${e.url})`)):console.log(ce.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(ce.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});wo.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=sr(kn(e),e.agent);console.log(JSON.stringify(o,null,2))});$t();import{Command as Od}from"commander";import{execFile as Id}from"child_process";import{promisify as Cd}from"util";import{existsSync as jd}from"fs";import Ge from"chalk";bt();var _t="ui-element";function vn(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:Nt(t.tried,80),screenChanged:t.changed,note:t.note?Nt(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:aa(t.role),label:Nt(t.label,120),value:t.value?Nt(t.value,80):null,enabled:t.enabled}))}}function xn(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${aa(t.role)}: ${Nt(n,80)}`}return{target:Wo(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:no("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 Sn(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 aa(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Nt(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}import{homedir as vd}from"node:os";import{execFile as xd}from"child_process";import{promisify as Sd}from"util";import{existsSync as Ed}from"fs";var $d=/^AX(Button|MenuItem|MenuButton|TextField|TextArea|CheckBox|RadioButton|PopUpButton|Link|Tab|Row|Cell|ComboBox|SearchField|Slider|Disclosure|Toolbar|StaticText)/;function kd(e){let o=new Map(e.map(i=>[i.id,i])),t=new Set(e.filter(i=>i.role==="AXWebArea").map(i=>i.id));if(t.size===0)return e;let n=i=>{let r=i;for(let a=0;r&&a<64;a++){if(t.has(r.id))return!0;if(r.parent<0)return!1;r=o.get(r.parent)}return!1},s=e.filter(n);return s.length>=2?s:e}function ca(e,o=60){let t=n=>/^AX(TextField|TextArea|SearchField|ComboBox)/.test(n)?0:/^AX(Button|MenuItem|MenuButton|PopUpButton|CheckBox|RadioButton|Tab|Link)/.test(n)?1:/^AX(Row|Cell|Slider|Disclosure|Toolbar)/.test(n)?2:3;return kd(e).filter(n=>$d.test(n.role)).filter(n=>n.width>=1&&n.height>=1).map((n,s)=>({e:n,i:s})).sort((n,s)=>t(n.e.role)-t(s.e.role)||n.i-s.i).map(({e:n})=>n).slice(0,o).map((n,s)=>({id:n.id,role:n.role,label:(n.label||n.value||"").trim()||`${n.role.replace(/^AX/,"")} ${s+1}`,value:n.value??null,enabled:n.enabled}))}var la=Sd(xd),Se=Nr(process.cwd(),vd(),process.env.AGENTX_MAC_HELPER),Ad=6;async function En(e={}){if(!Ed(Se))throw new Error("helper not built \u2014 run apps/mac-helper/build.sh");let{stdout:o}=await la(Se,["read","--max","400"]),t=JSON.parse(o),n=ca(t.elements,e.max??60),s=new Map;if(!(e.ocr!==!1&&n.length<Ad))return{app:t.app,window:t.window??null,candidates:n,elements:t.elements,usedOCR:!1,ocrRects:s};try{let{stdout:r}=await la(Se,["ocr"],{maxBuffer:8388608}),a=JSON.parse(r),c=Math.max(0,...t.elements.map(g=>g.id))+1,d=[];for(let g of a.hits){if(g.confidence<.5||g.text.length<2)continue;let l=c++;if(s.set(l,{x:g.x,y:g.y,width:g.width,height:g.height}),d.push({id:l,role:"OCRText",label:g.text,value:null,enabled:!0}),d.length>=(e.max??60))break}return{app:t.app,window:t.window??null,candidates:[...n,...d],elements:t.elements,usedOCR:d.length>0,ocrRects:s}}catch{return{app:t.app,window:t.window??null,candidates:n,elements:t.elements,usedOCR:!1,ocrRects:s}}}function Dt(e,o){let t=e.elements.find(n=>n.id===o);return t?{x:t.x,y:t.y,width:t.width,height:t.height}:e.ocrRects.get(o)??null}var da=Cd(Id),ga=new Od().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)=>{jd(Se)||(console.log(Ge.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await En({max:Number(o.max)||40})}catch(l){console.log(Ge.red(` could not read the screen: ${l?.message??l}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(Ge.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let l=Dt(t,n[0].id);l&&(console.log(Ge.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+Ge.bold(n[0].label)),await da(Se,["point","--x",String(l.x),"--y",String(l.y),"--w",String(l.width),"--h",String(l.height),"--label",n[0].label]));return}let s=await Ke(_t,vn({request:e,app:t.app,window:t.window,candidates:n}),xn(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(Ge.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${_t}.mode`)),process.exit(1));let i=Sn(s.answers,n),r=Dt(t,i.id),a=n.find(l=>l.id===i.id)?.label??"",c=t.ocrRects.has(i.id),d=Number(o.minPresent)||.5;if((i.present<d||!r)&&(console.log(Ge.yellow(` nothing on screen matches "${e}"`)+Ge.dim(` (P(exists)=${i.present.toFixed(2)} below ${d})`)),process.exit(2)),o.json){console.log(JSON.stringify({app:t.app,request:e,chosen:{...r,label:a,fromOCR:c},present:i.present,confidence:i.confidence,ranked:i.ranked.slice(0,5).map(l=>({...l,label:n.find(u=>u.id===l.id)?.label}))},null,2));return}let g=a;console.log(` ${Ge.green("\u2192")} ${Ge.bold(g)} `+Ge.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await da(Se,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",g])});import{Command as tg}from"commander";import Pe from"chalk";import{execFile as Td}from"child_process";import{promisify as Rd}from"util";import{existsSync as Nd,readFileSync as Es}from"fs";import{homedir as _d,tmpdir as Dd}from"os";import{join as ma}from"path";var Pd=Rd(Td),pa=12e5,Ld="https://openrouter.ai/api/v1/chat/completions",Md=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function Ud(e={kind:"window"},o=pa){if(!Nd(Se))throw new Error("helper not built \u2014 run apps/mac-helper/build.sh");let n=["capture","--out",ma(Dd(),`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 Pd(Se,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=Es(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 Fd=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
265
+ `,ca=[{relPath:"policy.yaml",content:ud},{relPath:"environments/production.yaml",content:fd},{relPath:"agents/coder-agent.yaml",content:hd}];var bo=new yd().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function Os(e){return e==="deny"?ce.red:e==="escalate"||e==="ask"?ce.yellow:e==="warn"?ce.magenta:ce.green}function En(e){return e.root?da(e.root):gr()}bo.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 dr({root:En(e),agentId:e.agent,env:e.env}),process.exit(0)});bo.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=En(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=lr({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}vd(s,i,r)});function vd(e,o,t){let n=Os(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":ce.dim(" (no rule matched)")}`),console.log(` enforced as ${Os(e.effectiveAction)(e.effectiveAction)} ${ce.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${ce.cyan(e.ruleId)}${e.severity?ce.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${ce.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${ce.dim(`evaluated in ${t}ms`)}`),console.log()}bo.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=cr({root:En(e),verdict:e.verdict,agentId:e.agent,taskId:e.task,limit:parseInt(e.limit,10)||30});if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(ce.dim(" (no guardrail decisions recorded yet)"));return}for(let t of o){let n=new Date(t.ts).toISOString().replace("T"," ").slice(0,19),s=Os(t.verdict),i=t.effective_action!==t.verdict?ce.dim(`->${t.effective_action}`):"";console.log(` ${ce.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${ce.cyan((t.agent_id??"?").padEnd(16))} ${ce.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(ce.dim(` target: ${t.resolved_target}`))}});bo.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=la(da(e.root),rr),t=0;for(let n of ca){let s=la(o,n.relPath);if(wd(s)&&!e.force){console.log(ce.dim(` skip (exists) ${n.relPath}`));continue}bd(kd(s),{recursive:!0}),$d(s,n.content),console.log(ce.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${ce.cyan(o)}`),console.log(ce.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(ce.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});bo.command("reload").description("signal the daemon to reload (note: guard policy is read live per tool call already)").option("--url <url>","daemon base url",process.env.AGENTX_DAEMON_URL||"http://localhost:19900").action(async e=>{try{let o=await fetch(`${String(e.url).replace(/\/$/,"")}/reload`,{method:"POST"});o.ok?console.log(ce.green(` daemon reloaded (${e.url})`)):console.log(ce.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(ce.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});bo.command("policy").description("print the resolved (merged) policy for an agent").option("--agent <id>","agent id").option("--root <dir>","AgentX install root").action(e=>{let o=ar(En(e),e.agent);console.log(JSON.stringify(o,null,2))});kt();import{Command as xd}from"commander";import{execFile as Sd}from"child_process";import{promisify as Ed}from"util";import{existsSync as Ad}from"fs";import Ge from"chalk";$t();var Dt="ui-element";function An(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:_t(t.tried,80),screenChanged:t.changed,note:t.note?_t(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:ga(t.role),label:_t(t.label,120),value:t.value?_t(t.value,80):null,enabled:t.enabled}))}}function On(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${ga(t.role)}: ${_t(n,80)}`}return{target:Bo(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:so("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 In(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 ga(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function _t(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}var ma=Ed(Sd),pa=new xd().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)=>{Ad(Se)||(console.log(Ge.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await gn({max:Number(o.max)||40})}catch(l){console.log(Ge.red(` could not read the screen: ${l?.message??l}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(Ge.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let l=Et(t,n[0].id);l&&(console.log(Ge.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+Ge.bold(n[0].label)),await ma(Se,["point","--x",String(l.x),"--y",String(l.y),"--w",String(l.width),"--h",String(l.height),"--label",n[0].label]));return}let s=await Ke(Dt,An({request:e,app:t.app,window:t.window,candidates:n}),On(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(Ge.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${Dt}.mode`)),process.exit(1));let i=In(s.answers,n),r=Et(t,i.id),a=n.find(l=>l.id===i.id)?.label??"",c=t.ocrRects.has(i.id),d=Number(o.minPresent)||.5;if((i.present<d||!r)&&(console.log(Ge.yellow(` nothing on screen matches "${e}"`)+Ge.dim(` (P(exists)=${i.present.toFixed(2)} below ${d})`)),process.exit(2)),o.json){console.log(JSON.stringify({app:t.app,request:e,chosen:{...r,label:a,fromOCR:c},present:i.present,confidence:i.confidence,ranked:i.ranked.slice(0,5).map(l=>({...l,label:n.find(u=>u.id===l.id)?.label}))},null,2));return}let m=a;console.log(` ${Ge.green("\u2192")} ${Ge.bold(m)} `+Ge.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await ma(Se,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",m])});import{Command as Qd}from"commander";import Pe from"chalk";import{execFile as Od}from"child_process";import{promisify as Id}from"util";import{existsSync as jd,readFileSync as Is}from"fs";import{homedir as Cd,tmpdir as Td}from"os";import{join as ua}from"path";var Nd=Id(Od),fa=12e5,Rd="https://openrouter.ai/api/v1/chat/completions",_d=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function Dd(e={kind:"window"},o=fa){if(!jd(Se))throw new Error("helper not built \u2014 run apps/mac-helper/build.sh");let n=["capture","--out",ua(Td(),`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 Nd(Se,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=Is(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 Pd=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
277
266
 
278
267
  Report only what is visible in this image.
279
268
 
@@ -281,10 +270,10 @@ The failure that matters: an application that performs an action is on screen, a
281
270
 
282
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.
283
272
 
284
- 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 qd(e,o,t,n){let s=Bd();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=Es(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 Ld(e,o,t,n){let s=Ud();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=Is(o.path).toString("base64"),r={model:t,max_tokens:700,messages:[{role:"user",content:[{type:"text",text:`Question: ${e}
285
274
 
286
- The image is the region ${Wd(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:Fd,tools:[{type:"function",function:{name:"report",description:"Report what is visible and how it bears on the question",parameters:{type:"object",properties:{observation:{type:"string",description:"What is visible in the image, factually, in one or two sentences."},evidence:{type:"string",description:"The specific visible detail that decides the question \u2014 where it is and what it looks like. Empty string if no such detail is visible."},reading:{type:"string",enum:["yes","no","unclear"],description:"Answer to the question, or unclear if the pixels do not settle it."}},required:["observation","evidence","reading"]}}}],tool_choice:{type:"function",function:{name:"report"}}},a=new AbortController,c=setTimeout(()=>a.abort(),n),d;try{d=await fetch(Ld,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`,"HTTP-Referer":"https://github.com/acme/agentx","X-Title":"agentx"},body:JSON.stringify(r),signal:a.signal})}finally{clearTimeout(c)}if(!d.ok){let p=await d.text().catch(()=>"");throw new Error(`vision model ${d.status}: ${p.slice(0,300)}`)}let g=await d.json(),l=g?.choices?.[0]?.message?.tool_calls?.[0];if(!l?.function?.arguments)throw new Error("vision model returned no structured report");let u=JSON.parse(l.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 An(e,o={}){let t=Date.now(),n=await Ud(o.region??{kind:"window"},o.maxPixels??pa),s=await qd(e,n,o.model??Md,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 Wd(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 Pt;function Bd(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(Pt!==void 0)return Pt??void 0;try{let e=Es(ma(_d(),".agentx","openrouter-key.txt"),"utf-8").trim();Pt=e.length>0?e:null}catch{Pt=null}return Pt??void 0}import{execFile as Jd}from"child_process";import{promisify as Hd}from"util";var Gd=Hd(Jd),zd=["screencapture"],Yd=["Screen Studio","OBS","QuickTime Player","Zoom"];async function fa(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await Kd()),t}async function Kd(){let e=await ua(zd);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 ua(Yd);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 ua(e){let o=[];for(let t of e)try{let{stdout:n}=await Gd("pgrep",["-x",t]),s=n.trim().split(`
287
- `)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}$t();bt();var ha="screen-state",ya={observable:no("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:no("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 wa(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 ba(e){return{observable:e.observable.noul,holds:e.holds.noul}}var Vd=.6,Xd=.7,Qd=.3;async function Lt(e,o={}){let[t,n]=await Promise.all([An(e,o),fa(e).catch(()=>[])]),s=o.observableFloor??Vd,i=await Ke(ha,wa({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:og(t),treeNote:o.treeNote,probes:n}),ya,{incumbent:{holds:t.reading==="yes"?1:0},features:{model:t.model,region:t.shot.region.height<=40?"menubar":"window"}});if(!i){let d=t.reading==="yes"?"confirmed":t.reading==="no"?"refuted":"unknown";return{claim:e,outcome:d,ok:d==="confirmed",observable:null,holds:null,calibrated:!1,reason:eg(d,t),sighting:t,probes:n}}let{observable:r,holds:a}=ba(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 (${On(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=Xd?"confirmed":a<=Qd?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:Zd(c,a,t),sighting:t,probes:n}}function Zd(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${On(o)}). ${n}`:e==="refuted"?`Not true (${On(1-o)} it is false). ${n}`:`Inconclusive (${On(o)}, between the thresholds). ${n}`}function eg(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 og(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 On=e=>`${Math.round(e*100)}%`;var $a=new tg().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(Pe.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 Lt(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"?Pe.green("\u2713"):s.outcome==="refuted"?Pe.red("\u2717"):Pe.yellow("?");console.log(` ${i} ${Pe.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(Pe.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(Pe.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 An(e,{region:t,model:o.model});if(o.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${Pe.bold(n.observation)}`),n.evidence&&console.log(Pe.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${ng(n.reading)}`),console.log(Pe.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(Pe.red(` ${n?.message??n}`)),process.exit(1)}});function ng(e){return e==="yes"?Pe.green(e):e==="no"?Pe.red(e):Pe.yellow(e)}$t();import{Command as rg}from"commander";import{execFile as Ia}from"child_process";import{promisify as ag}from"util";import{existsSync as cg,readFileSync as lg,writeFileSync as Ca,mkdirSync as dg}from"fs";import{homedir as gg}from"os";import{join as mg,dirname as pg}from"path";import Ce from"chalk";bt();var As="paste-transform";function ka(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function va(e){let o={};for(let t of e)o[t.id]=t.criterion;return{worthChanging:no("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:Wo(o,"What shape should this paste arrive in?")}}function xa(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 sg=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"]),ig=e=>/^https?:\/\/\S+$/i.test(e.trim()),Os=[{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 ${Md(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:Pd,tools:[{type:"function",function:{name:"report",description:"Report what is visible and how it bears on the question",parameters:{type:"object",properties:{observation:{type:"string",description:"What is visible in the image, factually, in one or two sentences."},evidence:{type:"string",description:"The specific visible detail that decides the question \u2014 where it is and what it looks like. Empty string if no such detail is visible."},reading:{type:"string",enum:["yes","no","unclear"],description:"Answer to the question, or unclear if the pixels do not settle it."}},required:["observation","evidence","reading"]}}}],tool_choice:{type:"function",function:{name:"report"}}},a=new AbortController,c=setTimeout(()=>a.abort(),n),d;try{d=await fetch(Rd,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`,"HTTP-Referer":"https://github.com/acme/agentx","X-Title":"agentx"},body:JSON.stringify(r),signal:a.signal})}finally{clearTimeout(c)}if(!d.ok){let p=await d.text().catch(()=>"");throw new Error(`vision model ${d.status}: ${p.slice(0,300)}`)}let m=await d.json(),l=m?.choices?.[0]?.message?.tool_calls?.[0];if(!l?.function?.arguments)throw new Error("vision model returned no structured report");let u=JSON.parse(l.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 m.model=="string"?m.model:t,usage:{inputTokens:m?.usage?.prompt_tokens??0,outputTokens:m?.usage?.completion_tokens??0}}}async function jn(e,o={}){let t=Date.now(),n=await Dd(o.region??{kind:"window"},o.maxPixels??fa),s=await Ld(e,n,o.model??_d,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 Md(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 Pt;function Ud(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(Pt!==void 0)return Pt??void 0;try{let e=Is(ua(Cd(),".agentx","openrouter-key.txt"),"utf-8").trim();Pt=e.length>0?e:null}catch{Pt=null}return Pt??void 0}import{execFile as Fd}from"child_process";import{promisify as qd}from"util";var Wd=qd(Fd),Bd=["screencapture"],Jd=["Screen Studio","OBS","QuickTime Player","Zoom"];async function ya(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await Hd()),t}async function Hd(){let e=await ha(Bd);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 ha(Jd);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 ha(e){let o=[];for(let t of e)try{let{stdout:n}=await Wd("pgrep",["-x",t]),s=n.trim().split(`
276
+ `)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}kt();$t();var wa="screen-state",ba={observable:so("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:so("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 $a(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 ka(e){return{observable:e.observable.noul,holds:e.holds.noul}}var Gd=.6,zd=.7,Yd=.3;async function Lt(e,o={}){let[t,n]=await Promise.all([jn(e,o),ya(e).catch(()=>[])]),s=o.observableFloor??Gd,i=await Ke(wa,$a({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:Xd(t),treeNote:o.treeNote,probes:n}),ba,{incumbent:{holds:t.reading==="yes"?1:0},features:{model:t.model,region:t.shot.region.height<=40?"menubar":"window"}});if(!i){let d=t.reading==="yes"?"confirmed":t.reading==="no"?"refuted":"unknown";return{claim:e,outcome:d,ok:d==="confirmed",observable:null,holds:null,calibrated:!1,reason:Vd(d,t),sighting:t,probes:n}}let{observable:r,holds:a}=ka(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 (${Cn(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=zd?"confirmed":a<=Yd?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:Kd(c,a,t),sighting:t,probes:n}}function Kd(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${Cn(o)}). ${n}`:e==="refuted"?`Not true (${Cn(1-o)} it is false). ${n}`:`Inconclusive (${Cn(o)}, between the thresholds). ${n}`}function Vd(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 Xd(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 Cn=e=>`${Math.round(e*100)}%`;var va=new Qd().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(Pe.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 Lt(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"?Pe.green("\u2713"):s.outcome==="refuted"?Pe.red("\u2717"):Pe.yellow("?");console.log(` ${i} ${Pe.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(Pe.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(Pe.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 jn(e,{region:t,model:o.model});if(o.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${Pe.bold(n.observation)}`),n.evidence&&console.log(Pe.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${Zd(n.reading)}`),console.log(Pe.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(Pe.red(` ${n?.message??n}`)),process.exit(1)}});function Zd(e){return e==="yes"?Pe.green(e):e==="no"?Pe.red(e):Pe.yellow(e)}kt();import{Command as tg}from"commander";import{execFile as Ca}from"child_process";import{promisify as ng}from"util";import{existsSync as sg,readFileSync as ig,writeFileSync as Ta,mkdirSync as rg}from"fs";import{homedir as ag}from"os";import{join as cg,dirname as lg}from"path";import je from"chalk";$t();var js="paste-transform";function xa(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function Sa(e){let o={};for(let t of e)o[t.id]=t.criterion;return{worthChanging:so("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:Bo(o,"What shape should this paste arrive in?")}}function Ea(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 eg=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"]),og=e=>/^https?:\/\/\S+$/i.test(e.trim()),Cs=[{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(`
288
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(`
289
278
  `).map(s=>s.trim()).filter(Boolean).join(" ")).filter(Boolean).join(`
290
279
 
@@ -292,68 +281,70 @@ The image is the region ${Wd(o)}.`},{type:"image_url",image_url:{url:`data:image
292
281
  `).map(t=>t.trim()).filter(Boolean);return o.length<2||o.every(t=>/^([-*+]|\d+[.)])\s/.test(t))?null:o.map(t=>`- ${t}`).join(`
293
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(`
294
283
  `);return o.every(t=>t.startsWith(">")||!t.trim())?null:o.map(t=>t.trim()?`> ${t}`:">").join(`
295
- `)}},{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(!ig(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])sg.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(!og(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])eg.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(`
296
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,`
297
- `).trim();return o===e?null:o}}];function Sa(e){let o=[];for(let t of Os){let n=t.apply(e);n!==null&&(t.id!=="asIs"&&n===e||o.push({transform:t,result:n}))}return o}function Ea(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 Aa(e){let o=[];for(let t of Cs){let n=t.apply(e);n!==null&&(t.id!=="asIs"&&n===e||o.push({transform:t,result:n}))}return o}function Oa(e,o=320){if(e.length<=o)return e;let t=Math.floor(o*.7),n=o-t;return`${e.slice(0,t)}
298
287
  \u2026[${e.length-o} more characters]\u2026
299
- ${e.slice(-n)}`}function Aa(e){let o=e.trim();return o.includes(`
300
- `)||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 Is=ag(Ia),ja=new rg().name("paste").description("reshape the clipboard to fit where it is being pasted").option("--apply","write the result back to the clipboard").option("--paste","apply, then press cmd-V into the focused control").option("--as <id>",`force a transform (${Os.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=fg();c===null&&(console.log(Ce.yellow(" nothing to undo")),process.exit(2)),await Ra(c),console.log(` ${Ce.green("\u2192")} clipboard restored`);return}let o=await hg();if(o||(console.log(Ce.yellow(" clipboard is empty")),process.exit(2)),Aa(o)){Ta(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=Sa(o),n=await yg();if(e.as){let c=t.find(d=>d.transform.id===e.as);c||(console.log(Ce.red(` "${e.as}" does not apply to this clipboard`)),console.log(Ce.dim(` available: ${t.map(d=>d.transform.id).join(", ")}`)),process.exit(1)),await nt(e,c.transform.id,c.result,o,"forced",1);return}if(t.length<2){await nt(e,"asIs",o,o,"nothing else applies",0);return}let s=await Ke(As,ka({preview:Ea(o),length:o.length,lineCount:o.split(`
301
- `).length,app:n.app,destination:n.role,destinationLabel:n.label}),va(t.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:t.length,chars:o.length}});if(!s){await nt(e,"asIs",o,o,`seat unavailable \u2014 set decisions.seats.${As}.mode`,0);return}let i=xa(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await nt(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 nt(e,"asIs",o,o,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await nt(e,a.transform.id,a.result,o,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function nt(e,o,t,n,s,i){let r=t!==n;r&&(e.apply||e.paste)&&(ug(n),await Ra(t)),Ta(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await Is(Se,["key","--name","v","--mod","command"]).catch(a=>{console.log(Ce.red(` could not paste: ${a?.message??a}`))})}function Ta(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(Oa(o.original))),console.log(Ce.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(Oa(o.result)),!e.apply&&!e.paste&&console.log(Ce.dim(`
302
- (dry run \u2014 pass --apply to write it back)`))}var Oa=(e,o=400)=>(e.length>o?`${e.slice(0,o)}\u2026`:e).split(`
288
+ ${e.slice(-n)}`}function Ia(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 Ts=ng(Ca),Na=new tg().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 (${Cs.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=gg();c===null&&(console.log(je.yellow(" nothing to undo")),process.exit(2)),await _a(c),console.log(` ${je.green("\u2192")} clipboard restored`);return}let o=await mg();if(o||(console.log(je.yellow(" clipboard is empty")),process.exit(2)),Ia(o)){Ra(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=Aa(o),n=await pg();if(e.as){let c=t.find(d=>d.transform.id===e.as);c||(console.log(je.red(` "${e.as}" does not apply to this clipboard`)),console.log(je.dim(` available: ${t.map(d=>d.transform.id).join(", ")}`)),process.exit(1)),await st(e,c.transform.id,c.result,o,"forced",1);return}if(t.length<2){await st(e,"asIs",o,o,"nothing else applies",0);return}let s=await Ke(js,xa({preview:Oa(o),length:o.length,lineCount:o.split(`
290
+ `).length,app:n.app,destination:n.role,destinationLabel:n.label}),Sa(t.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:t.length,chars:o.length}});if(!s){await st(e,"asIs",o,o,`seat unavailable \u2014 set decisions.seats.${js}.mode`,0);return}let i=Ea(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await st(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 st(e,"asIs",o,o,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await st(e,a.transform.id,a.result,o,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function st(e,o,t,n,s,i){let r=t!==n;r&&(e.apply||e.paste)&&(dg(n),await _a(t)),Ra(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await Ts(Se,["key","--name","v","--mod","command"]).catch(a=>{console.log(je.red(` could not paste: ${a?.message??a}`))})}function Ra(e,o){if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.changed){console.log(` ${je.dim("\u2192")} ${je.bold("unchanged")} ${je.dim(`\xB7 ${o.reason}`)}`);return}console.log(` ${je.green("\u2192")} ${je.bold(o.applied)} ${je.dim(`\xB7 ${o.reason}`)}`),console.log(je.dim(" \u2500\u2500\u2500 before \u2500\u2500\u2500")),console.log(je.dim(ja(o.original))),console.log(je.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(ja(o.result)),!e.apply&&!e.paste&&console.log(je.dim(`
291
+ (dry run \u2014 pass --apply to write it back)`))}var ja=(e,o=400)=>(e.length>o?`${e.slice(0,o)}\u2026`:e).split(`
303
292
  `).map(t=>` ${t}`).join(`
304
- `),In=mg(gg(),".agentx","paste-undo.txt");function ug(e){try{dg(pg(In),{recursive:!0}),Ca(In,e,{mode:384})}catch{}}function fg(){try{let e=lg(In,"utf-8");return Ca(In,"",{mode:384}),e.length?e:null}catch{return null}}async function hg(){let{stdout:e}=await Is("pbpaste",[],{maxBuffer:16777216});return e}async function Ra(e){await new Promise((o,t)=>{Ia("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function yg(){if(!cg(Se))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await Is(Se,["focused"]),o=JSON.parse(e);return o.ok===!1||!o.role?{app:"unknown",role:"an unknown control",label:null}:{app:o.app??"unknown",role:wg(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function wg(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 bg}from"commander";import ze from"chalk";var $g=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function kg(e,o){return async({title:t,message:n,channel:s,chatId:i})=>{let r=t&&!n.startsWith(t)?`${t}
305
- ${n}`:n,a=await fetch(`${$g}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:s??e,chatId:i??o,text:r})});if(!a.ok)throw new Error(`daemon ${a.status}: ${(await a.text().catch(()=>"")).slice(0,200)}`)}}var Na=new bg().name("notify").description("tell the operator something, holding it if they are in Focus").argument("[message]","what to say").option("--from <who>","who is speaking","agentx").option("--title <text>","notification title","Secretary").option("--priority <n>","1 (min) to 5 (max)","4").option("--urgent","deliver even during Focus").option("--channel <name>","delivery channel","ntfy").option("--chat-id <id>","channel address","default").option("--no-sound","do not play a sound on this machine").option("--status","show Focus state and anything being held").option("--flush","deliver everything held, as one message").option("--json","emit the result as JSON").action(async(e,o)=>{let t=new Qi,n=Vi(),s=o.sound===!1?!1:void 0;if(o.status){let r=t.list();if(o.json){console.log(JSON.stringify({focus:n,held:r},null,2));return}console.log(` ${n.active?ze.yellow("\u25D0"):ze.green("\u25CB")} ${Xi(n)} ${ze.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(ze.dim(` ${c} ${a.from}: ${a.message.slice(0,70)}`))}return}let i=kg(o.channel,o.chatId);if(o.flush){let r=await er(i,{queue:t,sound:s});console.log(r?ze.green(` delivered ${r} held notification(s)`):ze.dim(" nothing was held"));return}e?.trim()||(console.log(ze.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let r=await Zi({message:e.trim(),from:o.from,title:o.title,priority:Number(o.priority)||4,urgent:!!o.urgent,channel:o.channel,chatId:o.chatId},i,{queue:t,sound:s,focus:n});if(o.json){console.log(JSON.stringify(r,null,2));return}let a=r.delivered?ze.green("\u2192"):ze.yellow("\u23F8");console.log(` ${a} ${r.reason}`),r.held&&console.log(ze.dim(" it will arrive with the others when Focus ends"))}catch(r){console.log(ze.red(` ${r?.message??r}`)),s!==!1&&or(),process.exit(1)}});$t();xi();fi();bt();import{Command as vg}from"commander";import{readFileSync as xg}from"fs";var _a=new vg().name("decide").description("ask a typed question about some state and get a calibrated answer back").option("--file <path>","spec JSON file (default: stdin)").option("--backend <name>","decision backend","typesafe").option("--seat <name>","seat name the answers are recorded under","adhoc").option("--no-record","answer without writing a row").option("--timeout <ms>","abandon the call after this long","20000").action(async e=>{let o;try{o=e.file?xg(e.file,"utf8"):await Sg()}catch(r){Do(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return Do("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return Do(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return Do("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return Do("spec needs at least one entry in `questions`");try{yi(t.questions)}catch(r){return Do(r?.message??String(r))}let n=t.seat||e.seat;Bo(),process.env[Ei(n)]="active";let s=null;if(e.record!==!1)try{s=new Zt({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
306
- `)}Si({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await Ke(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return Do(`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 Do(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function Sg(){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")}$t();import{Command as Ig}from"commander";import{execFile as Cg,spawn as Da}from"child_process";import{promisify as jg}from"util";import{existsSync as Tg,writeFileSync as Rg,unlinkSync as Ng,statSync as _g}from"fs";import{join as Ts}from"path";import{tmpdir as Pa}from"os";import Q from"chalk";var Eg={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."}]},Ag={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."}]},Og={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."}]},Cs=[Eg,Ag,Og];ve();var Mt=jg(Cg),La=new Ig().name("teach").description("walk through something on screen, speaking and pointing as it goes").argument("[lesson]","lesson id (omit to list)").option("--voice <id>","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").action(async(e,o)=>{if(!e){console.log(Q.bold(`
293
+ `),Tn=cg(ag(),".agentx","paste-undo.txt");function dg(e){try{rg(lg(Tn),{recursive:!0}),Ta(Tn,e,{mode:384})}catch{}}function gg(){try{let e=ig(Tn,"utf-8");return Ta(Tn,"",{mode:384}),e.length?e:null}catch{return null}}async function mg(){let{stdout:e}=await Ts("pbpaste",[],{maxBuffer:16777216});return e}async function _a(e){await new Promise((o,t)=>{Ca("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function pg(){if(!sg(Se))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await Ts(Se,["focused"]),o=JSON.parse(e);return o.ok===!1||!o.role?{app:"unknown",role:"an unknown control",label:null}:{app:o.app??"unknown",role:ug(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function ug(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 fg}from"commander";import ze from"chalk";var hg=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function yg(e,o){return async({title:t,message:n,channel:s,chatId:i})=>{let r=t&&!n.startsWith(t)?`${t}
294
+ ${n}`:n,a=await fetch(`${hg}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:s??e,chatId:i??o,text:r})});if(!a.ok)throw new Error(`daemon ${a.status}: ${(await a.text().catch(()=>"")).slice(0,200)}`)}}var Da=new fg().name("notify").description("tell the operator something, holding it if they are in Focus").argument("[message]","what to say").option("--from <who>","who is speaking","agentx").option("--title <text>","notification title","Secretary").option("--priority <n>","1 (min) to 5 (max)","4").option("--urgent","deliver even during Focus").option("--channel <name>","delivery channel","ntfy").option("--chat-id <id>","channel address","default").option("--no-sound","do not play a sound on this machine").option("--status","show Focus state and anything being held").option("--flush","deliver everything held, as one message").option("--json","emit the result as JSON").action(async(e,o)=>{let t=new or,n=Zi(),s=o.sound===!1?!1:void 0;if(o.status){let r=t.list();if(o.json){console.log(JSON.stringify({focus:n,held:r},null,2));return}console.log(` ${n.active?ze.yellow("\u25D0"):ze.green("\u25CB")} ${er(n)} ${ze.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(ze.dim(` ${c} ${a.from}: ${a.message.slice(0,70)}`))}return}let i=yg(o.channel,o.chatId);if(o.flush){let r=await nr(i,{queue:t,sound:s});console.log(r?ze.green(` delivered ${r} held notification(s)`):ze.dim(" nothing was held"));return}e?.trim()||(console.log(ze.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let r=await tr({message:e.trim(),from:o.from,title:o.title,priority:Number(o.priority)||4,urgent:!!o.urgent,channel:o.channel,chatId:o.chatId},i,{queue:t,sound:s,focus:n});if(o.json){console.log(JSON.stringify(r,null,2));return}let a=r.delivered?ze.green("\u2192"):ze.yellow("\u23F8");console.log(` ${a} ${r.reason}`),r.held&&console.log(ze.dim(" it will arrive with the others when Focus ends"))}catch(r){console.log(ze.red(` ${r?.message??r}`)),s!==!1&&sr(),process.exit(1)}});kt();Ai();wi();$t();import{Command as wg}from"commander";import{readFileSync as bg}from"fs";var Pa=new wg().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?bg(e.file,"utf8"):await $g()}catch(r){Po(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return Po("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return Po(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return Po("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return Po("spec needs at least one entry in `questions`");try{$i(t.questions)}catch(r){return Po(r?.message??String(r))}let n=t.seat||e.seat;Jo(),process.env[Ii(n)]="active";let s=null;if(e.record!==!1)try{s=new Zt({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
295
+ `)}Oi({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await Ke(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return Po(`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 Po(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function $g(){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")}kt();import{Command as jg}from"commander";import{execFile as Cg,spawn as Ua}from"child_process";import{promisify as Tg}from"util";import{existsSync as Ng,writeFileSync as Rg,unlinkSync as _g,statSync as Dg}from"fs";import{join as _s}from"path";import{tmpdir as Fa}from"os";import X from"chalk";var kg={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."}]},vg={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."}]},xg={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."}]},Ns=[kg,vg,xg];we();we();import oo from"chalk";import{execFile as Sg}from"child_process";import{promisify as Eg}from"util";import{createInterface as Ag}from"readline";var La=Eg(Sg);function Og(e){e.type==="step"?console.log(`${oo.cyan(` ${e.n}. ${e.action}`)}${e.target?oo.dim(` "${e.target}"`):""} ${e.say}`):e.type==="changed"?console.log(oo.dim(` ${e.changed?"screen changed":"no change"}`)):e.type==="acted"?console.log(e.error?oo.red(` failed: ${e.error}`):oo.dim(" done it")):e.type==="door"?console.log(oo.cyan(` you: ${e.text}`)):e.type==="error"?console.log(oo.red(` error: ${e.error}`)):e.type==="end"&&console.log(oo.dim(` \xB7 ended (${e.reason})`))}async function Ig(e,o){let t=Date.now()+o;for(let n=0;Date.now()<t;n++){n&&n%10===0&&await La("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 Ma(e,o){let t=D(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=["teach","watch","act"].includes(o.mode??"")?o.mode:"teach",i;if(o.app&&(await La("open",["-a",o.app]),i=await Ig(o.app,15e3)??void 0,!i))throw new Error(`${o.app} did not come to the front`);let r=rn(n,t.agents,!1),a=vr(n,t.agents[n]),c=new hr({goal:e,app:i,mode:s,speaker:r,actionsAllowed:a.allowActions,maxSteps:Number(o.steps)||void 0},{readScreen:as,presence:new xr(a,Se),speech:new an,model:cn({system:fr(r.persona,"Anis")}),act:kr});c.on(Og),console.log(oo.bold(`
296
+ ${a.name} teaches: ${e}`)+oo.dim(` (${s}${s==="act"&&!a.allowActions?", actions not allowed":""}; type to cut in, "stop" to end)
297
+ `));let d=Ag({input:process.stdin});d.on("line",m=>{m.trim()&&c.door(m)}),process.once("SIGINT",()=>c.stop("interrupted")),await c.run(),d.close()}var Mt=Tg(Cg),qa=new jg().name("teach").description("walk through something on screen, speaking and pointing as it goes").argument("[lesson]","lesson id (omit to list)").option("--voice <id>","ElevenLabs voice id (overrides the agent's)").option("--agent <id>","speak in this agent's voice (default: AGENTX_VOICE_AGENT or node.defaultAgent)").option("--no-speak","point only, print the narration").option("--no-hud","skip the on-screen callout").option("--record","record the screen (screencapture) around the lesson").option("--record-dir <path>","where to write the recording").option("--live <goal>","no lesson: the agent reads the screen and teaches this, step by step").option("--mode <mode>","with --live: teach (you do each step), watch (you drive, it coaches) or act (it does it, if allowed)").option("--app <name>","with --live: open this app first").option("-c, --config <path>","with --live: agentx.json to read the agent from").option("--steps <n>","with --live: most steps before it stops (default 12)").action(async(e,o)=>{if(o.live)try{await Ma(String(o.live),o),process.exit(0)}catch(m){console.log(X.red(` ${m?.message??m}`)),process.exit(1)}if(!e){console.log(X.bold(`
307
298
  lessons
308
- `));for(let g of Cs)console.log(` ${Q.cyan(g.id.padEnd(22))} ${g.title}`),console.log(` ${" ".repeat(22)} ${Q.dim(g.appHint)}
309
- `);return}let t=Cs.find(g=>g.id===e);t||(console.log(Q.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),Tg(Se)||(console.log(Q.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let n=o.speak===!1?void 0:Lg(o.voice,o.agent);console.log(Q.bold(`
310
- ${t.title}`)),console.log(Q.dim(` ${t.appHint}
311
- `));try{t.start&&(await Mt("/usr/bin/open",Dg(t.start)),await bo(2e3),await Cn(t.start.ready))}catch(g){console.log(Q.red(` setup stopped: ${g?.message??g}`)),process.exitCode=3;return}let s=null,i=null;o.record&&(i=Ts(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(Q.dim(` recording \u2192 ${i}`)),s=Da("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await bo(2e3));let r=o.hud===!1?null:Da(Se,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(g,l,u,f)=>{try{r?.stdin?.write(JSON.stringify({title:g,body:l,state:u,avoid:f})+`
312
- `)}catch{}},c=[],d=!1;try{for(let[g,l]of t.steps.entries()){if(console.log(` ${Q.dim(String(g+1).padStart(2))} ${l.say}`),a(`Step ${g+1} of ${t.steps.length}`,l.say,"talking"),l.click||l.type||l.key){if(!l.before)throw new Error(`Step ${g+1} needs a before claim`);await Cn(l.before)}let u=o.speak===!1?Promise.resolve():Mg(l.say,n),f=l.find?await Pg(l.find,c):null;if(l.find&&!f)throw c.push({tried:l.find,changed:!1,note:"not found on screen"}),await u,new Error(`Could not find "${l.find}"; stopped before acting`);if(await u,f&&(a(`Step ${g+1} of ${t.steps.length}`,l.say,"pointing",{x:f.x,y:f.y,w:f.width,h:f.height}),await Mt(Se,["point","--x",String(f.x),"--y",String(f.y),"--w",String(f.width),"--h",String(f.height),"--label",l.label??l.find??"","--hold",String(l.click||l.type?.5:l.holdSeconds??2.6)]),l.click)){let{error:p,changed:w}=await js(["click"]);if(p)throw new Error(p);c.push({tried:l.label??l.find??"control",changed:w!==!1,note:p??void 0}),w===!1&&console.log(Q.yellow(" \xB7 clicked, but the screen did not change")),await bo(l.afterClickWaitMs??1500)}if(l.type){await Cn(l.before),a(`Step ${g+1} of ${t.steps.length}`,l.type,"typing");let{error:p}=await js(["type","--text",l.type]);if(p)throw console.log(Q.red(` \u2717 ${p}`)),a("Blocked",p,"waiting"),c.push({tried:`type into ${l.label??"the field"}`,changed:!1,note:p}),new Error(p)}if(l.key){await Cn(l.before),a(`Step ${g+1} of ${t.steps.length}`,`\u21B5 ${l.key}`,"typing");let{error:p}=await js(["key","--name",l.key]);if(p)throw console.log(Q.red(` \u2717 ${p}`)),a("Blocked",p,"waiting"),c.push({tried:`press ${l.key}`,changed:!1,note:p}),new Error(p)}if(!f&&!l.type&&!l.key?await bo((l.holdSeconds??1.2)*1e3):l.holdSeconds&&await bo(l.holdSeconds*1e3),l.verify){a(`Step ${g+1} of ${t.steps.length}`,"Checking that worked\u2026","waiting");let p;try{p=await Lt(l.verify)}catch(w){p=null,console.log(Q.yellow(` ? could not check: ${w?.message??w}`))}if(!p&&!l.verifyOptional)throw new Error(`Could not verify: ${l.verify}`);if(p){let w=p.outcome==="confirmed"?Q.green("\u2713"):p.outcome==="refuted"?Q.red("\u2717"):Q.yellow("?");if(console.log(` ${w} ${Q.dim(p.reason)}`),!p.ok&&!l.verifyOptional){a("Stopped",`That did not work: ${l.verify}`,"waiting"),console.log(Q.red(`
313
- stopping: could not confirm \u2014 ${l.verify}`)),console.log(Q.dim(` ${p.reason}`)),console.log(Q.dim(` screenshot: ${p.sighting.shot.path}`)),await bo(2500);try{r?.stdin?.end()}catch{}d=!0;break}}}}}catch(g){d=!0,console.log(Q.red(` stopping: ${g?.message??g}`)),a("Stopped",String(g?.message??g),"waiting")}finally{if(d)try{r?.stdin?.end()}catch{}}if(!d){a("Done",t.title,"done"),await bo(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await bo(2500);try{let{size:g}=_g(i);console.log(Q.green(` recorded ${(g/1048576).toFixed(1)} MB \u2192 ${i}`))}catch{console.log(Q.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(d){console.log(Q.red(` lesson stopped before the end.
314
- `)),process.exitCode=3;return}console.log(Q.green(`
299
+ `));for(let m of Ns)console.log(` ${X.cyan(m.id.padEnd(22))} ${m.title}`),console.log(` ${" ".repeat(22)} ${X.dim(m.appHint)}
300
+ `);return}let t=Ns.find(m=>m.id===e);t||(console.log(X.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),Ng(Se)||(console.log(X.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let n=o.speak===!1?void 0:Mg(o.voice,o.agent);console.log(X.bold(`
301
+ ${t.title}`)),console.log(X.dim(` ${t.appHint}
302
+ `));try{t.start&&(await Mt("/usr/bin/open",Pg(t.start)),await $o(2e3),await Nn(t.start.ready))}catch(m){console.log(X.red(` setup stopped: ${m?.message??m}`)),process.exitCode=3;return}let s=null,i=null;o.record&&(i=_s(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(X.dim(` recording \u2192 ${i}`)),s=Ua("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await $o(2e3));let r=o.hud===!1?null:Ua(Se,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(m,l,u,f)=>{try{r?.stdin?.write(JSON.stringify({title:m,body:l,state:u,avoid:f})+`
303
+ `)}catch{}},c=[],d=!1;try{for(let[m,l]of t.steps.entries()){if(console.log(` ${X.dim(String(m+1).padStart(2))} ${l.say}`),a(`Step ${m+1} of ${t.steps.length}`,l.say,"talking"),l.click||l.type||l.key){if(!l.before)throw new Error(`Step ${m+1} needs a before claim`);await Nn(l.before)}let u=o.speak===!1?Promise.resolve():Ug(l.say,n),f=l.find?await Lg(l.find,c):null;if(l.find&&!f)throw c.push({tried:l.find,changed:!1,note:"not found on screen"}),await u,new Error(`Could not find "${l.find}"; stopped before acting`);if(await u,f&&(a(`Step ${m+1} of ${t.steps.length}`,l.say,"pointing",{x:f.x,y:f.y,w:f.width,h:f.height}),await Mt(Se,["point","--x",String(f.x),"--y",String(f.y),"--w",String(f.width),"--h",String(f.height),"--label",l.label??l.find??"","--hold",String(l.click||l.type?.5:l.holdSeconds??2.6)]),l.click)){let{error:p,changed:w}=await Rs(["click"]);if(p)throw new Error(p);c.push({tried:l.label??l.find??"control",changed:w!==!1,note:p??void 0}),w===!1&&console.log(X.yellow(" \xB7 clicked, but the screen did not change")),await $o(l.afterClickWaitMs??1500)}if(l.type){await Nn(l.before),a(`Step ${m+1} of ${t.steps.length}`,l.type,"typing");let{error:p}=await Rs(["type","--text",l.type]);if(p)throw console.log(X.red(` \u2717 ${p}`)),a("Blocked",p,"waiting"),c.push({tried:`type into ${l.label??"the field"}`,changed:!1,note:p}),new Error(p)}if(l.key){await Nn(l.before),a(`Step ${m+1} of ${t.steps.length}`,`\u21B5 ${l.key}`,"typing");let{error:p}=await Rs(["key","--name",l.key]);if(p)throw console.log(X.red(` \u2717 ${p}`)),a("Blocked",p,"waiting"),c.push({tried:`press ${l.key}`,changed:!1,note:p}),new Error(p)}if(!f&&!l.type&&!l.key?await $o((l.holdSeconds??1.2)*1e3):l.holdSeconds&&await $o(l.holdSeconds*1e3),l.verify){a(`Step ${m+1} of ${t.steps.length}`,"Checking that worked\u2026","waiting");let p;try{p=await Lt(l.verify)}catch(w){p=null,console.log(X.yellow(` ? could not check: ${w?.message??w}`))}if(!p&&!l.verifyOptional)throw new Error(`Could not verify: ${l.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&&!l.verifyOptional){a("Stopped",`That did not work: ${l.verify}`,"waiting"),console.log(X.red(`
304
+ stopping: could not confirm \u2014 ${l.verify}`)),console.log(X.dim(` ${p.reason}`)),console.log(X.dim(` screenshot: ${p.sighting.shot.path}`)),await $o(2500);try{r?.stdin?.end()}catch{}d=!0;break}}}}}catch(m){d=!0,console.log(X.red(` stopping: ${m?.message??m}`)),a("Stopped",String(m?.message??m),"waiting")}finally{if(d)try{r?.stdin?.end()}catch{}}if(!d){a("Done",t.title,"done"),await $o(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await $o(2500);try{let{size:m}=Dg(i);console.log(X.green(` recorded ${(m/1048576).toFixed(1)} MB \u2192 ${i}`))}catch{console.log(X.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(d){console.log(X.red(` lesson stopped before the end.
305
+ `)),process.exitCode=3;return}console.log(X.green(`
315
306
  done.
316
- `))});function Dg(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${Ts(Pa(),"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 Cn(e){let o=await Lt(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function js(e){try{let{stdout:o}=await Mt(Se,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 Pg(e,o=[]){try{let t=await En({max:45});if(t.candidates.length<2)return null;let n=await Ke(_t,vn({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),xn(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=Sn(n.answers,t.candidates);return s.present<.5?null:Dt(t,s.id)}catch{return null}}function Lg(e,o){if(e)return xt(e);try{let t=L(),n=o||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;n&&!t.agents[n]&&console.log(Q.yellow(` no agent "${n}" in agentx.json \u2014 using the default voice`));let s=n?t.agents[n]:void 0;return xt(null,n&&s?lr(n,s).elevenlabsVoiceId:null)}catch(t){return console.log(Q.dim(` no agent voice (${String(t?.message??t).split(`
317
- `)[0]}) \u2014 using the default`)),xt()}}async function Mg(e,o){let t=gr();if(t)try{let n=o||xt(),s=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${n}`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:e,model_id:"eleven_turbo_v2_5"})});if(s.ok){let i=Ts(Pa(),`agentx-teach-${Date.now()}.mp3`);Rg(i,Buffer.from(await s.arrayBuffer())),await Mt("/usr/bin/afplay",[i]);try{Ng(i)}catch{}return}}catch{}await Mt("/usr/bin/say",[e]).catch(()=>{})}var bo=e=>new Promise(o=>setTimeout(o,e));ve();import{Command as Ma}from"commander";import Le from"chalk";import{createInterface as Ua}from"readline";var Ug=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function Ut(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(Ug()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function Fg(e){e.type==="line"?console.log(`${Le.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(Le.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(Le.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(Le.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(Le.dim(" \xB7 hushed")):e.type==="error"?console.log(Le.red(` error: ${e.error}`)):e.type==="end"&&console.log(Le.dim(` \xB7 ended (${e.reason})`))}function Fa(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 qg(e,o,t){let n=L(t.config).agents,s=e.filter(c=>!n[c]);if(s.length)throw new Error(`Unknown agent: ${s.join(", ")}`);let i=Date.now(),r=new dr({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:e.map(c=>ur(c,n,!0)),speech:new mr,model:(c,d)=>pr({system:d})});r.on(Fg),r.on(c=>{c.type==="line"&&c.turn===0&&console.log(Le.dim(` \xB7 first line written ${Date.now()-i} ms after start`))});let a=Ua({input:process.stdin});a.on("line",c=>{c.trim()&&r.door(c)}),process.once("SIGINT",()=>r.stop("interrupted")),await r.run(),a.close(),console.log(Le.dim(` ${Fa(r.gaps)}`))}async function Wg(e,o,t){let n=await Ut("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=Ua({input:process.stdin});s.on("line",a=>{a.trim()&&Ut("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void Ut("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await Ut("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${Le.bold(c[i].name)}: ${c[i].text}`);if(r=a.gaps??r,!a.active)break;await new Promise(d=>setTimeout(d,400))}s.close(),console.log(Le.dim(` ${Fa(r)}`))}var qa=new Ma().name("talk").description('two agents 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?qg:Wg)([e,o],s,n),process.exit(0)}catch(i){console.error(Le.red(` ${i?.message??i}`)),process.exit(1)}}),Wa=new Ma().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(Le.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await Ut("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(Le.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});import{Command as Bg}from"commander";import M from"chalk";var Po=new Bg().name("attach").description("wear an agentx agent identity in this Claude Code session"),Rs=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Ot()}`;function Ns(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function _s(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 Ds(e){let o=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(o)?`daemon not reachable \u2014 start it with ${M.cyan("agentx daemon start")}`:o}function Ba(e){return e==="auto"?M.yellow:e==="manual"?M.gray:M.green}function Jg(e,o=!1){let t=e.agentIds.length?e.agentIds.join(", "):M.gray("(not bound)"),n=e.pending?M.yellow(`${e.pending} pending`):M.gray("empty"),s=o?M.cyan(" \u2190 this session"):"";console.log(` ${M.bold(t)} ${Ba(e.mode)(e.mode)} ${n} ${M.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${M.gray(e.cwd)}`)}Po.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${es.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",Rs).action(async(e,o)=>{let t=Ns(o.session);t||(console.error(M.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${M.cyan("--session <id>")} (list them with ${M.cyan("agentx attach list")}).`),process.exit(1)),ji(o.mode)||(console.error(M.red(`Invalid mode "${o.mode}". Expected one of: ${es.join(", ")}`)),process.exit(1)),hn()||(console.error(M.yellow("Attach hooks are not installed yet.")),console.error(`Run ${M.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{let n=await _s(o.url,"/attach/bind",{sessionId:t,agentId:e,mode:o.mode,cwd:process.cwd()});console.log(`${M.green("\u2713")} This session is now wearing ${M.bold(e)} (${Ba(o.mode)(o.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(M.yellow(` ${s} message(s) already queued for it.`)),console.log(M.gray(o.mode==="auto"?" Queued messages will be answered automatically at the end of each turn.":o.mode==="notify"?" You'll be told when messages arrive; run /inbox to answer them.":" Nothing will interrupt you; run /inbox to check for messages."))}catch(n){console.error(M.red(`Bind failed: ${Ds(n)}`)),process.exit(1)}});Po.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",Rs).action(async e=>{let o=Ns(e.session);o||(console.error(M.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await _s(e.url,"/attach/detach",{sessionId:o,agentId:e.agent}),console.log(`${M.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(t){console.error(M.red(`Detach failed: ${Ds(t)}`)),process.exit(1)}});Po.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",Rs).option("--json","raw JSON output").action(async e=>{let o=Ns();try{let n=(await _s(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:hn(),sessions:n},null,2));return}console.log(),console.log(hn()?`${M.green("\u2713")} Attach hooks installed ${M.gray(At())}`:`${M.yellow("!")} Attach hooks not installed \u2014 run ${M.cyan("agentx attach install")}`),console.log();let s=n.filter(r=>r.agentIds.length>0);if(s.length===0)console.log(M.gray(" No session is wearing an identity right now."));else for(let r of s)Jg(r,r.sessionId===o);let i=n.length-s.length;i>0&&console.log(M.gray(`
318
- ${i} registered session(s) with no binding.`)),console.log()}catch(t){console.error(M.red(`Could not read attach state: ${Ds(t)}`)),process.exit(1)}});Po.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||Ot()),t=Wr(o,{path:e.path,withGuard:e.guard});console.log(t.changed?`${M.green("\u2713")} Installed attach hooks in ${M.gray(t.path)}`:`${M.green("\u2713")} Attach hooks already up to date in ${M.gray(t.path)}`),console.log(M.gray(` Events: ${t.events.join(", ")} \u2192 127.0.0.1:${o}`)),t.guardInstalled?(console.log(M.gray(" PreToolUse guard installed at user scope.")),console.log(M.gray(` (An attached session runs under your permissions, not the agent's workspace
307
+ `))});function Pg(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${_s(Fa(),"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 Nn(e){let o=await Lt(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function Rs(e){try{let{stdout:o}=await Mt(Se,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 Lg(e,o=[]){try{let t=await gn({max:45});if(t.candidates.length<2)return null;let n=await Ke(Dt,An({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),On(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=In(n.answers,t.candidates);return s.present<.5?null:Et(t,s.id)}catch{return null}}function Mg(e,o){if(e)return St(e);try{let t=D(),n=o||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;n&&!t.agents[n]&&console.log(X.yellow(` no agent "${n}" in agentx.json \u2014 using the default voice`));let s=n?t.agents[n]:void 0;return St(null,n&&s?mr(n,s).elevenlabsVoiceId:null)}catch(t){return console.log(X.dim(` no agent voice (${String(t?.message??t).split(`
308
+ `)[0]}) \u2014 using the default`)),St()}}async function Ug(e,o){let t=ur();if(t)try{let n=o||St(),s=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${n}`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:e,model_id:"eleven_turbo_v2_5"})});if(s.ok){let i=_s(Fa(),`agentx-teach-${Date.now()}.mp3`);Rg(i,Buffer.from(await s.arrayBuffer())),await Mt("/usr/bin/afplay",[i]);try{_g(i)}catch{}return}}catch{}await Mt("/usr/bin/say",[e]).catch(()=>{})}var $o=e=>new Promise(o=>setTimeout(o,e));we();import{Command as Wa}from"commander";import Le from"chalk";import{createInterface as Ba}from"readline";var Fg=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function Ut(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(Fg()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function qg(e){e.type==="line"?console.log(`${Le.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(Le.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(Le.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(Le.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(Le.dim(" \xB7 hushed")):e.type==="error"?console.log(Le.red(` error: ${e.error}`)):e.type==="end"&&console.log(Le.dim(` \xB7 ended (${e.reason})`))}function Ja(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 Wg(e,o,t){let n=D(t.config).agents,s=e.filter(c=>!n[c]);if(s.length)throw new Error(`Unknown agent: ${s.join(", ")}`);let i=Date.now(),r=new pr({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:e.map(c=>rn(c,n,!0)),speech:new an,model:(c,d)=>cn({system:d})});r.on(qg),r.on(c=>{c.type==="line"&&c.turn===0&&console.log(Le.dim(` \xB7 first line written ${Date.now()-i} ms after start`))});let a=Ba({input:process.stdin});a.on("line",c=>{c.trim()&&r.door(c)}),process.once("SIGINT",()=>r.stop("interrupted")),await r.run(),a.close(),console.log(Le.dim(` ${Ja(r.gaps)}`))}async function Bg(e,o,t){let n=await Ut("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=Ba({input:process.stdin});s.on("line",a=>{a.trim()&&Ut("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void Ut("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await Ut("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${Le.bold(c[i].name)}: ${c[i].text}`);if(r=a.gaps??r,!a.active)break;await new Promise(d=>setTimeout(d,400))}s.close(),console.log(Le.dim(` ${Ja(r)}`))}var Ha=new Wa().name("talk").description('two agents 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?Wg:Bg)([e,o],s,n),process.exit(0)}catch(i){console.error(Le.red(` ${i?.message??i}`)),process.exit(1)}}),Ga=new Wa().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(Le.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await Ut("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(Le.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});import{Command as Jg}from"commander";import M from"chalk";var Lo=new Jg().name("attach").description("wear an agentx agent identity in this Claude Code session"),Ds=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${It()}`;function Ps(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function Ls(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 Ms(e){let o=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(o)?`daemon not reachable \u2014 start it with ${M.cyan("agentx daemon start")}`:o}function za(e){return e==="auto"?M.yellow:e==="manual"?M.gray:M.green}function Hg(e,o=!1){let t=e.agentIds.length?e.agentIds.join(", "):M.gray("(not bound)"),n=e.pending?M.yellow(`${e.pending} pending`):M.gray("empty"),s=o?M.cyan(" \u2190 this session"):"";console.log(` ${M.bold(t)} ${za(e.mode)(e.mode)} ${n} ${M.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${M.gray(e.cwd)}`)}Lo.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${ns.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",Ds).action(async(e,o)=>{let t=Ps(o.session);t||(console.error(M.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${M.cyan("--session <id>")} (list them with ${M.cyan("agentx attach list")}).`),process.exit(1)),Ri(o.mode)||(console.error(M.red(`Invalid mode "${o.mode}". Expected one of: ${ns.join(", ")}`)),process.exit(1)),$n()||(console.error(M.yellow("Attach hooks are not installed yet.")),console.error(`Run ${M.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{let n=await Ls(o.url,"/attach/bind",{sessionId:t,agentId:e,mode:o.mode,cwd:process.cwd()});console.log(`${M.green("\u2713")} This session is now wearing ${M.bold(e)} (${za(o.mode)(o.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(M.yellow(` ${s} message(s) already queued for it.`)),console.log(M.gray(o.mode==="auto"?" Queued messages will be answered automatically at the end of each turn.":o.mode==="notify"?" You'll be told when messages arrive; run /inbox to answer them.":" Nothing will interrupt you; run /inbox to check for messages."))}catch(n){console.error(M.red(`Bind failed: ${Ms(n)}`)),process.exit(1)}});Lo.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",Ds).action(async e=>{let o=Ps(e.session);o||(console.error(M.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await Ls(e.url,"/attach/detach",{sessionId:o,agentId:e.agent}),console.log(`${M.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(t){console.error(M.red(`Detach failed: ${Ms(t)}`)),process.exit(1)}});Lo.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",Ds).option("--json","raw JSON output").action(async e=>{let o=Ps();try{let n=(await Ls(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:$n(),sessions:n},null,2));return}console.log(),console.log($n()?`${M.green("\u2713")} Attach hooks installed ${M.gray(Ot())}`:`${M.yellow("!")} Attach hooks not installed \u2014 run ${M.cyan("agentx attach install")}`),console.log();let s=n.filter(r=>r.agentIds.length>0);if(s.length===0)console.log(M.gray(" No session is wearing an identity right now."));else for(let r of s)Hg(r,r.sessionId===o);let i=n.length-s.length;i>0&&console.log(M.gray(`
309
+ ${i} registered session(s) with no binding.`)),console.log()}catch(t){console.error(M.red(`Could not read attach state: ${Ms(t)}`)),process.exit(1)}});Lo.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||It()),t=Gr(o,{path:e.path,withGuard:e.guard});console.log(t.changed?`${M.green("\u2713")} Installed attach hooks in ${M.gray(t.path)}`:`${M.green("\u2713")} Attach hooks already up to date in ${M.gray(t.path)}`),console.log(M.gray(` Events: ${t.events.join(", ")} \u2192 127.0.0.1:${o}`)),t.guardInstalled?(console.log(M.gray(" PreToolUse guard installed at user scope.")),console.log(M.gray(` (An attached session runs under your permissions, not the agent's workspace
319
310
  settings \u2014 without this an attached production identity would be less
320
- guarded than a spawned one.)`))):console.log(M.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${M.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(M.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Po.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=Br({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${M.green("\u2713")} Removed attach hooks from ${M.gray(o.path)} (${o.events.join(", ")})`:`${M.gray("Nothing to remove.")}`),e.removeGuard||console.log(M.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(M.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});ve();import{Command as Hg}from"commander";import pe from"chalk";var jn=new Hg().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Ha(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=L(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 Ga(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function Ja(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 Gg(e){return e==="busy"?pe.magenta:e==="warm-hot"?pe.green:e==="warm-cold"?pe.cyan:e==="idle"?pe.yellow:e==="dead"?pe.red:pe.dim}jn.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}=Ha(e),n;try{n=await fetch(`${o}/api/processes`,{headers:Ga(t)})}catch(r){console.log(pe.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(pe.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(pe.red(` HTTP ${n.status} from ${o}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(pe.dim(" (no processes)"));return}for(let r of i){let a=Gg(r.state)(r.state.padEnd(9)),c=Ja(r.spawnedAt),d=r.lastTurnAt?Ja(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?pe.dim(`last_in=${r.lastInputTokens} tok`):"",l=r.claudeSessionId?pe.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):pe.dim("sess=\u2014"),u=r.pendingTaskId?pe.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${pe.bold(r.key.agentId)}${pe.dim(":"+r.key.channel+":"+r.key.chatId)} ${pe.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${d} ${l} ${g} ${u}`),r.deadReason&&console.log(` ${pe.red("dead:")} ${r.deadReason}`)}});jn.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}=Ha(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Ga(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(pe.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(pe.dim(" daemon has no persistent-process registry"));return}if(!r.ok){let a=`HTTP ${r.status}`;try{let c=await r.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(pe.red(` ${a}`)),process.exit(1)}console.log(pe.green(` killed ${e}:${o}:${t}`))});import{Command as zg}from"commander";import je from"chalk";import{existsSync as Ps,rmSync as Yg}from"fs";import{resolve as Ls}from"path";var st=new zg().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");st.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(je.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await _i(e,o,{verbose:n}),r=Date.now()-s;console.log(je.green(` \u2713 indexed ${i.docs} doc(s) for ${je.bold(e)} in ${r}ms`)),console.log(je.dim(` \u2192 ${i.path}`))});st.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=Ls(e.cwd,".agentx","rag");if(!Ps(o)){console.log(je.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>Ps(Ls(o,s,"index.json")));if(n.length===0){console.log(je.dim(" (no indexes)"));return}for(let s of n.sort()){let i=os(s);console.log(` ${je.bold(s)} ${i.docs} doc(s) ${je.dim(i.path)}`)}});st.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=Di(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=os(e);i.exists?console.log(je.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(je.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${je.bold(i.title)} ${je.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${je.dim(i.path)}`),console.log(` ${je.dim(i.snippet.slice(0,200))}`)});st.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=Ls(process.cwd(),".agentx","rag",e);if(!Ps(o)){console.log(je.dim(` no index for ${e} \u2014 nothing to clear`));return}Yg(o,{recursive:!0,force:!0}),console.log(je.green(` \u2713 cleared index for ${e}`))});ve();import{Command as Kg}from"commander";import V from"chalk";import it from"prompts";var Lo=new Kg().name("backlog").description("manage the local backlog used by business workSource=backlog");function Ft(e){let o=L(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new fr(n)}}function Vg(e){return e?V.cyan(`${e.type}:${e.project}#${e.iid}`):V.dim("manual")}function Xg(e){return{todo:V.gray("todo"),doing:V.yellow("doing"),blocked:V.red("blocked"),done:V.green("done")}[e]}Lo.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}=Ft(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(V.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?V.magenta(`@${n.assignee}`):V.dim("unassigned");console.log(` ${Xg(n.status).padEnd(7)} ${Vg(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(V.dim(` ${n.source.url}`))}console.log(),console.log(V.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});Lo.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=Ft(t.config);n.store.findById(e)||(console.error(V.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(V.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=hr([o],i.source,n.config),a=await ss(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(V.dim(" sync:"),...c));console.log(a.ok?V.dim(` synced -> ${a.url??i.source.type}`):V.yellow(` sync failed: ${a.error}`))}});Lo.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=Ft(o.config);t.store.findById(e)||(console.error(V.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(V.green(` done: ${s.title}`)),s.source){let i=await ss(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(V.dim(" sync:"),...r));console.log(i.ok?V.dim(` synced -> ${i.url??s.source.type}`):V.yellow(` sync failed: ${i.error}`))}});Lo.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}=Ft(o.config);t.remove(e)||(console.error(V.red(` item ${e} not found`)),process.exit(1)),console.log(V.green(` removed ${e}`))});Lo.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=Ft(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(V.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 it({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!t&&(console.error(V.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(V.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?Zg(o.config):em(o.config);y.length?(i=(await it({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 it({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await it({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await it({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(V.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await om(o.config,i,a):await tm(o.config,i,a);if(!c.length){console.log(V.yellow(" no open issues matched"));return}console.log(V.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let d=i,g=new Set(o.store.list().map(y=>y.id)),l=c.map(y=>{let $=ns({type:s,project:d,iid:y.iid,url:y.url}),b=g.has($),v=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${v}${b?V.dim(" (already imported)"):""}`,value:y,disabled:b}}),f=(await it({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:l,min:1})).selected||[];if(!f.length){console.log(V.dim(" nothing selected"));return}let p=f.map(y=>{let $={type:s,host:s==="gitlab"?Qg(o.config):void 0,project:d,iid:y.iid,url:y.url};return{id:ns($),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:$,importedAt:new Date().toISOString()}}),w=o.store.addMany(p);console.log(V.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(V.dim(` ${y.id} \u2014 ${y.title}`))});function Qg(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Zg(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 em(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 om(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 tm(e,o,t){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(t){let c=`repo:${o} is:issue is:open ${t}`;i=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let d=await fetch(i,{headers:s});if(!d.ok)throw new Error(`GitHub ${d.status}: ${await d.text().catch(()=>"")}`);return((await d.json()).items??[]).map(za)}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(za):[]}function za(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 im}from"commander";import z from"chalk";import{existsSync as rm,readFileSync as am}from"fs";import{resolve as cm}from"path";import lm from"prompts";ve();import nm from"cronstrue";var Ms={sun:0,sunday:0,mon:1,monday:1,tue:2,tuesday:2,tues:2,wed:3,wednesday:3,thu:4,thursday:4,thurs:4,fri:5,friday:5,sat:6,saturday:6},Tn={morning:{h:9,m:0},afternoon:{h:14,m:0},evening:{h:18,m:0},night:{h:22,m:0},noon:{h:12,m:0},midnight:{h:0,m:0}};function oo(e){try{return nm.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function sm(e){if(/\b(noon|midday)\b/.test(e))return Tn.noon;if(/\bmidnight\b/.test(e))return Tn.midnight;let o=e.match(/\b(?:at|by|@)\s*(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/);if(o){let t=parseInt(o[1],10),n=o[2]?parseInt(o[2],10):0,s=o[3];return s==="pm"&&t<12&&(t+=12),s==="am"&&t===12&&(t=0),t>23||n>59?null:{h:t,m:n}}return null}function Us(e){let o=e.trim().toLowerCase();if(!o)return null;let t;if(t=o.match(/\bevery\s+(\d+)\s*(minutes|mins|m)\b/)){let l=parseInt(t[1],10);return l<1||l>59?null:{cron:`*/${l} * * * *`,human:oo(`*/${l} * * * *`),matched:t[0]}}if(/\bevery\s+minute\b/.test(o))return{cron:"* * * * *",human:oo("* * * * *"),matched:"every minute"};if(t=o.match(/\bevery\s+(\d+)\s*(hours|hrs|h)\b/)){let l=parseInt(t[1],10);return l<1||l>23?null:{cron:`0 */${l} * * *`,human:oo(`0 */${l} * * *`),matched:t[0]}}if(/\b(every hour|hourly)\b/.test(o))return{cron:"0 * * * *",human:oo("0 * * * *"),matched:"every hour"};let n=sm(o),s=null;for(let[l,u]of Object.entries(Tn))if(!(l==="noon"||l==="midnight")&&new RegExp(`\\b(every\\s+)?${l}s?\\b`).test(o)){s=u;break}let i=n||s,r=o.match(/\b(first|1st|2nd|3rd|last|(\d+)(?:st|nd|rd|th)?)\s+(day\s+)?of\s+(every|each|the)\s+month\b/);if(r){let l=r[1],u=1;if(l==="last"||(/^\d+(st|nd|rd|th)?$/.test(l)?u=parseInt(l,10):l==="first"||l==="1st"?u=1:l==="2nd"?u=2:l==="3rd"&&(u=3),u<1||u>31))return null;let f=i||{h:9,m:0},p=`${f.m} ${f.h} ${u} * *`;return{cron:p,human:oo(p),matched:r[0]}}let a=[],c=Object.keys(Ms).join("|"),d=new RegExp(`\\b(?:every|on|each|by)\\s+((?:${c})s?(?:\\s*(?:,|and|&)\\s*(?:${c})s?)*)\\b`),g=o.match(d);if(g){let l=g[1];for(let u of Object.keys(Ms))if(new RegExp(`\\b${u}s?\\b`).test(l)){let f=Ms[u];a.includes(f)||a.push(f)}}if(a.length){let l=i||{h:9,m:0};a.sort((p,w)=>p-w);let u=a.join(","),f=`${l.m} ${l.h} * * ${u}`;return{cron:f,human:oo(f),matched:`on ${u}`}}if(/\b(weekday|workday|business day)s?\b/.test(o)){let l=i||{h:9,m:0},u=`${l.m} ${l.h} * * 1-5`;return{cron:u,human:oo(u),matched:"weekdays"}}if(/\bweekends?\b/.test(o)){let l=i||{h:9,m:0},u=`${l.m} ${l.h} * * 0,6`;return{cron:u,human:oo(u),matched:"weekends"}}if(/\b(every day|daily|each day)\b/.test(o)||s){let l=i||{h:9,m:0},u=`${l.m} ${l.h} * * *`;return{cron:u,human:oo(u),matched:s&&Object.entries(Tn).find(([,f])=>f===s)?.[0]||"daily"}}if(n){let l=`${n.m} ${n.h} * * *`;return{cron:l,human:oo(l),matched:`at ${n.h}:${String(n.m).padStart(2,"0")}`}}return null}function Ya(e,o){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"job"}-${o}`}function Ka(e){let o=e||cm(process.cwd(),"agentx.json");return rm(o)||(console.log(z.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(am(o,"utf-8"))}function dm(e){return e?e.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o==="log"||o==="notify"||o==="disable"):["log"]}async function gm(e,o){if(!e)return;if(e==="me"){let n=o?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(z.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await lm([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let t=e.split(":");if(t.length>=2)return{channel:t[0],chatId:t[1],accountId:t[2]};console.log(z.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var $o=new im().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');$o.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>","IANA timezone (default: Africa/Tunis)","Africa/Tunis").option("--timeout <seconds>","max run time","600").option("--model <model>","override model").option("--disabled","create but leave disabled").option("--dry-run","print what would be written without writing").action(async(e,o)=>{if(!e){$o.help();return}o.agent||(console.log(z.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(z.red(' --do "<prompt>" is required')),process.exit(1));let t=Us(e);t||(console.log(z.red(` Couldn't parse: "${e}"`)),console.log(z.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(z.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(z.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=Ka(o.config),s=hi(n);n.agents?.[o.agent]||(console.log(z.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(z.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=dm(o.onError),r=await gm(o.notify,s);r&&!i.includes("notify")&&i.push("notify");let a=o.id||Ya(t.matched,o.agent),c={enabled:!o.disabled,schedule:t.cron,timezone:o.timezone,agent:o.agent,prompt:o.do,timeout:parseInt(o.timeout,10),onError:i};o.model&&(c.model=o.model),r&&(c.notify=r);let d=await de(l=>we(l,`crons.${a}`,c),{configPath:o.config,dryRun:!!o.dryRun});d.success||(console.log(z.red(` \u2717 ${d.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(z.green(` \u2713 ${g} cron ${z.cyan(a)}`)),console.log(z.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(z.dim(` Agent: ${o.agent}`)),r&&console.log(z.dim(` Notify: ${r.channel} ${r.chatId}`)),i.length&&console.log(z.dim(` On error: ${i.join(", ")}`)),!o.dryRun&&d.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});$o.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=Ka(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(z.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.enabled?z.green("\u25CF"):z.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}console.log(` ${r} ${z.cyan(s.padEnd(32))} ${z.dim(i.schedule.padEnd(14))} ${z.dim("\u2192")} ${i.agent}`),console.log(z.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(z.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`))}console.log()});for(let[e,o]of[["on",!0],["off",!1]])$o.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await de(s=>{if(!Io(s,`crons.${t}`))throw new Error(`cron "${t}" not found`);we(s,`crons.${t}.enabled`,o)});n.success||(console.log(z.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(z.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});$o.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await de(t=>{if(!Io(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);Ui(t,`crons.${e}`)});o.success||(console.log(z.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(z.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});$o.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Us(o);t||(console.log(z.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(z.green(` "${o}"`)),console.log(z.dim(` \u2192 ${t.cron}`)),console.log(z.dim(` \u2192 ${t.human}`))});import{Command as _m}from"commander";import rt from"chalk";import Z from"chalk";import Wt from"prompts";import{readFileSync as mm,writeFileSync as pm,existsSync as um}from"fs";import{resolve as Va}from"path";var fm=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function hm(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function Fs(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Xa(e=".env"){let o=Va(e);if(!um(o))return[];let t=mm(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(fm);i?n.push({kind:"kv",key:i[1],value:hm(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function ym(e){return e.map(o=>o.kind==="kv"?`${o.key}=${Fs(o.value)}`:o.raw).join(`
311
+ guarded than a spawned one.)`))):console.log(M.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${M.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(M.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Lo.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=zr({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${M.green("\u2713")} Removed attach hooks from ${M.gray(o.path)} (${o.events.join(", ")})`:`${M.gray("Nothing to remove.")}`),e.removeGuard||console.log(M.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(M.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});we();import{Command as Gg}from"commander";import pe from"chalk";var Rn=new Gg().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Ka(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=D(e.config);o||(o=n.dashboard?.daemonUrl||""),t||(t=n.dashboard?.token||"")}catch{}return o||(o="http://localhost:18800"),{baseUrl:o.replace(/\/+$/,""),token:t}}function Va(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function Ya(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 zg(e){return e==="busy"?pe.magenta:e==="warm-hot"?pe.green:e==="warm-cold"?pe.cyan:e==="idle"?pe.yellow:e==="dead"?pe.red:pe.dim}Rn.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}=Ka(e),n;try{n=await fetch(`${o}/api/processes`,{headers:Va(t)})}catch(r){console.log(pe.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(pe.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(pe.red(` HTTP ${n.status} from ${o}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(pe.dim(" (no processes)"));return}for(let r of i){let a=zg(r.state)(r.state.padEnd(9)),c=Ya(r.spawnedAt),d=r.lastTurnAt?Ya(r.lastTurnAt)+" ago":"\u2014",m=r.lastInputTokens?pe.dim(`last_in=${r.lastInputTokens} tok`):"",l=r.claudeSessionId?pe.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):pe.dim("sess=\u2014"),u=r.pendingTaskId?pe.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${pe.bold(r.key.agentId)}${pe.dim(":"+r.key.channel+":"+r.key.chatId)} ${pe.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${d} ${l} ${m} ${u}`),r.deadReason&&console.log(` ${pe.red("dead:")} ${r.deadReason}`)}});Rn.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}=Ka(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Va(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(pe.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(pe.dim(" daemon has no persistent-process registry"));return}if(!r.ok){let a=`HTTP ${r.status}`;try{let c=await r.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(pe.red(` ${a}`)),process.exit(1)}console.log(pe.green(` killed ${e}:${o}:${t}`))});import{Command as Yg}from"commander";import Ce from"chalk";import{existsSync as Us,rmSync as Kg}from"fs";import{resolve as Fs}from"path";var it=new Yg().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");it.command("add <agentId>").description("build or refresh an agent's lexical index from one or more globs").argument("<globs...>","glob patterns relative to cwd (e.g. './docs/**/*.md')").option("-v, --verbose","log each indexed file").action(async(e,o,t)=>{o.length===0&&(console.log(Ce.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await Li(e,o,{verbose:n}),r=Date.now()-s;console.log(Ce.green(` \u2713 indexed ${i.docs} doc(s) for ${Ce.bold(e)} in ${r}ms`)),console.log(Ce.dim(` \u2192 ${i.path}`))});it.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=Fs(e.cwd,".agentx","rag");if(!Us(o)){console.log(Ce.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>Us(Fs(o,s,"index.json")));if(n.length===0){console.log(Ce.dim(" (no indexes)"));return}for(let s of n.sort()){let i=ss(s);console.log(` ${Ce.bold(s)} ${i.docs} doc(s) ${Ce.dim(i.path)}`)}});it.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=Mi(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=ss(e);i.exists?console.log(Ce.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Ce.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Ce.bold(i.title)} ${Ce.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Ce.dim(i.path)}`),console.log(` ${Ce.dim(i.snippet.slice(0,200))}`)});it.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=Fs(process.cwd(),".agentx","rag",e);if(!Us(o)){console.log(Ce.dim(` no index for ${e} \u2014 nothing to clear`));return}Kg(o,{recursive:!0,force:!0}),console.log(Ce.green(` \u2713 cleared index for ${e}`))});we();import{Command as Vg}from"commander";import V from"chalk";import rt from"prompts";var Mo=new Vg().name("backlog").description("manage the local backlog used by business workSource=backlog");function Ft(e){let o=D(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new Sr(n)}}function Xg(e){return e?V.cyan(`${e.type}:${e.project}#${e.iid}`):V.dim("manual")}function Qg(e){return{todo:V.gray("todo"),doing:V.yellow("doing"),blocked:V.red("blocked"),done:V.green("done")}[e]}Mo.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}=Ft(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(V.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?V.magenta(`@${n.assignee}`):V.dim("unassigned");console.log(` ${Qg(n.status).padEnd(7)} ${Xg(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(V.dim(` ${n.source.url}`))}console.log(),console.log(V.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});Mo.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=Ft(t.config);n.store.findById(e)||(console.error(V.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(V.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=Er([o],i.source,n.config),a=await ls(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(V.dim(" sync:"),...c));console.log(a.ok?V.dim(` synced -> ${a.url??i.source.type}`):V.yellow(` sync failed: ${a.error}`))}});Mo.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=Ft(o.config);t.store.findById(e)||(console.error(V.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(V.green(` done: ${s.title}`)),s.source){let i=await ls(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(V.dim(" sync:"),...r));console.log(i.ok?V.dim(` synced -> ${i.url??s.source.type}`):V.yellow(` sync failed: ${i.error}`))}});Mo.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}=Ft(o.config);t.remove(e)||(console.error(V.red(` item ${e} not found`)),process.exit(1)),console.log(V.green(` removed ${e}`))});Mo.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=Ft(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(V.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 rt({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!t&&(console.error(V.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(V.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?em(o.config):om(o.config);y.length?(i=(await rt({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 rt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await rt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await rt({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(V.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await tm(o.config,i,a):await nm(o.config,i,a);if(!c.length){console.log(V.yellow(" no open issues matched"));return}console.log(V.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let d=i,m=new Set(o.store.list().map(y=>y.id)),l=c.map(y=>{let $=cs({type:s,project:d,iid:y.iid,url:y.url}),b=m.has($),v=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${v}${b?V.dim(" (already imported)"):""}`,value:y,disabled:b}}),f=(await rt({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:l,min:1})).selected||[];if(!f.length){console.log(V.dim(" nothing selected"));return}let p=f.map(y=>{let $={type:s,host:s==="gitlab"?Zg(o.config):void 0,project:d,iid:y.iid,url:y.url};return{id:cs($),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:$,importedAt:new Date().toISOString()}}),w=o.store.addMany(p);console.log(V.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(V.dim(` ${y.id} \u2014 ${y.title}`))});function Zg(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function em(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 om(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 tm(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 nm(e,o,t){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(t){let c=`repo:${o} is:issue is:open ${t}`;i=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let d=await fetch(i,{headers:s});if(!d.ok)throw new Error(`GitHub ${d.status}: ${await d.text().catch(()=>"")}`);return((await d.json()).items??[]).map(Xa)}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(Xa):[]}function Xa(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 rm}from"commander";import z from"chalk";import{existsSync as am,readFileSync as cm}from"fs";import{resolve as lm}from"path";import dm from"prompts";we();import sm from"cronstrue";var qs={sun:0,sunday:0,mon:1,monday:1,tue:2,tuesday:2,tues:2,wed:3,wednesday:3,thu:4,thursday:4,thurs:4,fri:5,friday:5,sat:6,saturday:6},_n={morning:{h:9,m:0},afternoon:{h:14,m:0},evening:{h:18,m:0},night:{h:22,m:0},noon:{h:12,m:0},midnight:{h:0,m:0}};function to(e){try{return sm.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function im(e){if(/\b(noon|midday)\b/.test(e))return _n.noon;if(/\bmidnight\b/.test(e))return _n.midnight;let o=e.match(/\b(?:at|by|@)\s*(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/);if(o){let t=parseInt(o[1],10),n=o[2]?parseInt(o[2],10):0,s=o[3];return s==="pm"&&t<12&&(t+=12),s==="am"&&t===12&&(t=0),t>23||n>59?null:{h:t,m:n}}return null}function Ws(e){let o=e.trim().toLowerCase();if(!o)return null;let t;if(t=o.match(/\bevery\s+(\d+)\s*(minutes|mins|m)\b/)){let l=parseInt(t[1],10);return l<1||l>59?null:{cron:`*/${l} * * * *`,human:to(`*/${l} * * * *`),matched:t[0]}}if(/\bevery\s+minute\b/.test(o))return{cron:"* * * * *",human:to("* * * * *"),matched:"every minute"};if(t=o.match(/\bevery\s+(\d+)\s*(hours|hrs|h)\b/)){let l=parseInt(t[1],10);return l<1||l>23?null:{cron:`0 */${l} * * *`,human:to(`0 */${l} * * *`),matched:t[0]}}if(/\b(every hour|hourly)\b/.test(o))return{cron:"0 * * * *",human:to("0 * * * *"),matched:"every hour"};let n=im(o),s=null;for(let[l,u]of Object.entries(_n))if(!(l==="noon"||l==="midnight")&&new RegExp(`\\b(every\\s+)?${l}s?\\b`).test(o)){s=u;break}let i=n||s,r=o.match(/\b(first|1st|2nd|3rd|last|(\d+)(?:st|nd|rd|th)?)\s+(day\s+)?of\s+(every|each|the)\s+month\b/);if(r){let l=r[1],u=1;if(l==="last"||(/^\d+(st|nd|rd|th)?$/.test(l)?u=parseInt(l,10):l==="first"||l==="1st"?u=1:l==="2nd"?u=2:l==="3rd"&&(u=3),u<1||u>31))return null;let f=i||{h:9,m:0},p=`${f.m} ${f.h} ${u} * *`;return{cron:p,human:to(p),matched:r[0]}}let a=[],c=Object.keys(qs).join("|"),d=new RegExp(`\\b(?:every|on|each|by)\\s+((?:${c})s?(?:\\s*(?:,|and|&)\\s*(?:${c})s?)*)\\b`),m=o.match(d);if(m){let l=m[1];for(let u of Object.keys(qs))if(new RegExp(`\\b${u}s?\\b`).test(l)){let f=qs[u];a.includes(f)||a.push(f)}}if(a.length){let l=i||{h:9,m:0};a.sort((p,w)=>p-w);let u=a.join(","),f=`${l.m} ${l.h} * * ${u}`;return{cron:f,human:to(f),matched:`on ${u}`}}if(/\b(weekday|workday|business day)s?\b/.test(o)){let l=i||{h:9,m:0},u=`${l.m} ${l.h} * * 1-5`;return{cron:u,human:to(u),matched:"weekdays"}}if(/\bweekends?\b/.test(o)){let l=i||{h:9,m:0},u=`${l.m} ${l.h} * * 0,6`;return{cron:u,human:to(u),matched:"weekends"}}if(/\b(every day|daily|each day)\b/.test(o)||s){let l=i||{h:9,m:0},u=`${l.m} ${l.h} * * *`;return{cron:u,human:to(u),matched:s&&Object.entries(_n).find(([,f])=>f===s)?.[0]||"daily"}}if(n){let l=`${n.m} ${n.h} * * *`;return{cron:l,human:to(l),matched:`at ${n.h}:${String(n.m).padStart(2,"0")}`}}return null}function Qa(e,o){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"job"}-${o}`}function Za(e){let o=e||lm(process.cwd(),"agentx.json");return am(o)||(console.log(z.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(cm(o,"utf-8"))}function gm(e){return e?e.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o==="log"||o==="notify"||o==="disable"):["log"]}async function mm(e,o){if(!e)return;if(e==="me"){let n=o?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(z.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await dm([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let t=e.split(":");if(t.length>=2)return{channel:t[0],chatId:t[1],accountId:t[2]};console.log(z.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var ko=new rm().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');ko.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>","IANA timezone (default: Africa/Tunis)","Africa/Tunis").option("--timeout <seconds>","max run time","600").option("--model <model>","override model").option("--disabled","create but leave disabled").option("--dry-run","print what would be written without writing").action(async(e,o)=>{if(!e){ko.help();return}o.agent||(console.log(z.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(z.red(' --do "<prompt>" is required')),process.exit(1));let t=Ws(e);t||(console.log(z.red(` Couldn't parse: "${e}"`)),console.log(z.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(z.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(z.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=Za(o.config),s=bi(n);n.agents?.[o.agent]||(console.log(z.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(z.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=gm(o.onError),r=await mm(o.notify,s);r&&!i.includes("notify")&&i.push("notify");let a=o.id||Qa(t.matched,o.agent),c={enabled:!o.disabled,schedule:t.cron,timezone:o.timezone,agent:o.agent,prompt:o.do,timeout:parseInt(o.timeout,10),onError:i};o.model&&(c.model=o.model),r&&(c.notify=r);let d=await de(l=>be(l,`crons.${a}`,c),{configPath:o.config,dryRun:!!o.dryRun});d.success||(console.log(z.red(` \u2717 ${d.error}`)),process.exit(1));let m=o.dryRun?"would add":"Added";console.log(z.green(` \u2713 ${m} cron ${z.cyan(a)}`)),console.log(z.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(z.dim(` Agent: ${o.agent}`)),r&&console.log(z.dim(` Notify: ${r.channel} ${r.chatId}`)),i.length&&console.log(z.dim(` On error: ${i.join(", ")}`)),!o.dryRun&&d.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});ko.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=Za(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(z.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.enabled?z.green("\u25CF"):z.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}console.log(` ${r} ${z.cyan(s.padEnd(32))} ${z.dim(i.schedule.padEnd(14))} ${z.dim("\u2192")} ${i.agent}`),console.log(z.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(z.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`))}console.log()});for(let[e,o]of[["on",!0],["off",!1]])ko.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await de(s=>{if(!jo(s,`crons.${t}`))throw new Error(`cron "${t}" not found`);be(s,`crons.${t}.enabled`,o)});n.success||(console.log(z.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(z.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});ko.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await de(t=>{if(!jo(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);Wi(t,`crons.${e}`)});o.success||(console.log(z.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(z.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});ko.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Ws(o);t||(console.log(z.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(z.green(` "${o}"`)),console.log(z.dim(` \u2192 ${t.cron}`)),console.log(z.dim(` \u2192 ${t.human}`))});import{Command as Dm}from"commander";import at from"chalk";import Z from"chalk";import Wt from"prompts";import{readFileSync as pm,writeFileSync as um,existsSync as fm}from"fs";import{resolve as ec}from"path";var hm=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function ym(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function Bs(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function oc(e=".env"){let o=ec(e);if(!fm(o))return[];let t=pm(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(hm);i?n.push({kind:"kv",key:i[1],value:ym(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function wm(e){return e.map(o=>o.kind==="kv"?`${o.key}=${Bs(o.value)}`:o.raw).join(`
321
312
  `)+`
322
- `}function qt(e,o,t=".env"){let n=Va(t),s=Xa(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Fs(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Fs(o)}`})),pm(n,ym(s))}function qs(e,o=".env"){return Xa(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var Qa="https://t.me/BotFather";async function wm(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 bm(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 Za(e={}){console.log(),console.log(Z.bold(" Connect Telegram")),console.log(),console.log(Z.dim(` 1. Open ${Qa}`)),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 Wt({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),v=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(v,[Qa],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Wt({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 wm(t.trim());n||(console.log(Z.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Z.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(Z.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),d=Object.keys(c.agents||{});d.length===0&&(console.log(Z.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Wt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:d.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(Z.red(" Aborted")),process.exit(1));let l=c.channels?.telegram?.accounts||{},u=e.account||g;l[u]&&l[u].agentBinding!==g&&(u=(await Wt({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),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 de(b=>{we(b,"channels.telegram.enabled",!0),we(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let v=Io(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),we(b,`agents.${g}.mentions`,v))},{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 Wt({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 bm(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 $=await de(b=>{we(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{configPath:e.configPath});if(!$.success){console.log(Z.red(` \u2717 failed to save destination: ${$.error}`));return}console.log(Z.green(" \u2713 Default --notify target set")),console.log(Z.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Z.dim(" From now on, --notify me resolves to this chat.")),$.reloaded&&console.log(Z.dim(" Daemon hot-reloaded."))}import ue from"chalk";import Ws from"prompts";import{existsSync as Js,mkdirSync as $m,readdirSync as km,readFileSync as ec}from"fs";import{resolve as Bs}from"path";var vm=".agentx/whatsapp-sessions";function xm(){let e=Bs(process.cwd(),".agentx/daemon.pid");if(!Js(e))return!1;try{let o=parseInt(ec(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Sm(e){if(!Js(e))return!1;try{return km(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Em(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ue.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ue.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;$m(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},d=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return d.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(ue.yellow(" Timed out waiting for scan (2min)."));try{d.end(void 0)}catch{}g(!1)},12e4);d.ev.on("connection.update",async f=>{if(f.qr){o(ue.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(ue.green(" \u2713 Paired"));try{d.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(ue.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function oc(e={}){if(console.log(),console.log(ue.bold(" Connect WhatsApp")),console.log(),xm()){console.log(ue.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ue.dim(" agentx daemon stop")),console.log();let{cont:d}=await Ws({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});d||(console.log(ue.red(" Aborted")),process.exit(1))}let o=e.configPath||Bs(process.cwd(),"agentx.json");Js(o)||(console.log(ue.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(ec(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||vm,s=Bs(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ue.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Ws({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ue.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Sm(s)&&a){let{keep:d}=await Ws({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!d,d&&console.log(ue.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Em(s,g=>console.log(g))||(console.log(ue.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await de(d=>{we(d,"channels.whatsapp.enabled",!0),we(d,"channels.whatsapp.sessionDir",n),we(d,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ue.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ue.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ue.dim(` Session: ${n}`)),console.log(ue.dim(" Start the daemon to begin receiving:")),console.log(ue.dim(" agentx daemon start")),console.log(ue.dim(" Add routes later with:")),console.log(ue.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Am}from"crypto";import be from"chalk";import tc from"prompts";var Rn="agentx-mesh:",Nn="//join/";function Om(e){return Buffer.from(e,"utf-8").toString("base64url")}function Im(e){return Buffer.from(e,"base64url").toString("utf-8")}function Cm(e){return`${Rn}${Nn}${Om(JSON.stringify(e))}`}function jm(e){if(!e.startsWith(`${Rn}${Nn}`))throw new Error(`Not a mesh invite link \u2014 expected ${Rn}${Nn}\u2026`);let o=e.slice(Rn.length+Nn.length),t=JSON.parse(Im(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 Tm(){return Am(32).toString("hex")}function Rm(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Nm(e){return e?.node?.name||e?.node?.id||"node"}async function nc(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(be.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=qs("MESH_TOKEN");r||(r=Tm(),qt("MESH_TOKEN",r),console.log(be.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Rm(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:l}=await tc({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://"});l||(console.log(be.red(" Aborted")),process.exit(1)),a=l}let d=await de(l=>{we(l,"mesh.enabled",!0)},{configPath:e.configPath});d.success||(console.log(be.red(` \u2717 ${d.error}`)),process.exit(1));let g=Cm({url:a,token:r,name:Nm(i),version:1});console.log(),console.log(be.bold(" Mesh invite")),console.log(),console.log(` ${be.cyan(g)}`),console.log(),console.log(be.dim(" Run on the other node:")),console.log(be.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(be.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function sc(e,o={}){let t;try{t=jm(e)}catch(i){console.log(be.red(` \u2717 ${i.message}`)),process.exit(1)}let n=qs("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await tc({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(be.red(" Aborted (keeping existing .env)")),process.exit(1))}qt("MESH_TOKEN",t.token);let s=await de(i=>{we(i,"mesh.enabled",!0);let r=Io(i,"mesh.peers")||[],a=r.findIndex(d=>d.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),we(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(be.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(be.green(" \u2713 Joined mesh")),console.log(be.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(be.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(be.dim(" Daemon hot-reloaded.")):console.log(be.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(be.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(be.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(be.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var at=new _m().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");at.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 Za({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});at.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 oc({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var ic=at.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");ic.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 nc({url:e.url,configPath:e.config})});ic.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 sc(e,{configPath:o.config})});at.action(()=>{console.log(),console.log(rt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${rt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${rt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${rt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${rt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(rt.dim(" GitLab connect is the next slice.")),console.log()});ve();import{Command as Dm}from"commander";import le from"chalk";var Bt=new Dm().name("usage").description("token usage analysis and reporting");Bt.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=L(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(le.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(le.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${le.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${le.red(String(s.totalErrors))}`),console.log(),console.log(le.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let d=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${le.cyan(a)}: ${d} tokens (${c.tasks} tasks) ${le.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(le.red(" Daemon not running. Start with: agentx daemon start")):console.log(le.red(` ${e.message}`))}});Bt.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(le.red(` Script not found: ${s}`)),console.log(le.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(le.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(le.red(" Analysis failed. Is Python 3 installed?"))}});Bt.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-ISXECD4J.js"),r=await i(),a=new Set(n.filter(l=>l.kind==="cli").map(l=>l.name)),c=[],d=(l,u)=>{for(let f of l.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),d(f,p)}};d(r,"");let g=c.filter(l=>!a.has(l)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(le.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let l of g)console.log(` ${le.dim("\xB7")} ${l}`);console.log(),console.log(le.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(le.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(le.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(le.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(le.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(le.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=le.dim(`${i.days}d`);console.log(` ${le.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(le.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Pm}from"commander";import fe from"chalk";import{resolve as Lm}from"path";ve();var ko=new Pm().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");ko.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{Ai(Lm(process.cwd(),".env"))}catch{}let o=Mm(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-74OLMLAD.js");t(o)}catch(o){console.log(fe.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(fe.dim(o.stack)),process.exit(1)}});function Mm(e,o){try{let t=L();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(fe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(fe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
323
- `)),{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}}}}ko.command("list").description("list configured boards").action(()=>{try{let e=L();if(!e.boards?.length){console.log(fe.dim(`
313
+ `}function qt(e,o,t=".env"){let n=ec(t),s=oc(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Bs(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Bs(o)}`})),um(n,wm(s))}function Js(e,o=".env"){return oc(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var tc="https://t.me/BotFather";async function bm(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 $m(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 nc(e={}){console.log(),console.log(Z.bold(" Connect Telegram")),console.log(),console.log(Z.dim(` 1. Open ${tc}`)),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 Wt({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),v=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(v,[tc],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Wt({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 bm(t.trim());n||(console.log(Z.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Z.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(Z.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),d=Object.keys(c.agents||{});d.length===0&&(console.log(Z.red(" No agents configured. Run: agentx agent add")),process.exit(1));let m=e.agent;m||(m=(await Wt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:d.map(v=>({title:v,value:v})),initial:0})).agent),m||(console.log(Z.red(" Aborted")),process.exit(1));let l=c.channels?.telegram?.accounts||{},u=e.account||m;l[u]&&l[u].agentBinding!==m&&(u=(await Wt({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${m}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"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 de(b=>{be(b,"channels.telegram.enabled",!0),be(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:m});let v=jo(b,`agents.${m}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),be(b,`agents.${m}.mentions`,v))},{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 "${m}"`)),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 Wt({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 $m(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 $=await de(b=>{be(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{configPath:e.configPath});if(!$.success){console.log(Z.red(` \u2717 failed to save destination: ${$.error}`));return}console.log(Z.green(" \u2713 Default --notify target set")),console.log(Z.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Z.dim(" From now on, --notify me resolves to this chat.")),$.reloaded&&console.log(Z.dim(" Daemon hot-reloaded."))}import ue from"chalk";import Hs from"prompts";import{existsSync as zs,mkdirSync as km,readdirSync as vm,readFileSync as sc}from"fs";import{resolve as Gs}from"path";var xm=".agentx/whatsapp-sessions";function Sm(){let e=Gs(process.cwd(),".agentx/daemon.pid");if(!zs(e))return!1;try{let o=parseInt(sc(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Em(e){if(!zs(e))return!1;try{return vm(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Am(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ue.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ue.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;km(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},d=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return d.ev.on("creds.update",r),await new Promise(m=>{let u=setTimeout(()=>{o(ue.yellow(" Timed out waiting for scan (2min)."));try{d.end(void 0)}catch{}m(!1)},12e4);d.ev.on("connection.update",async f=>{if(f.qr){o(ue.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(ue.green(" \u2713 Paired"));try{d.end(void 0)}catch{}m(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(ue.red(" \u2717 Authorization failed \u2014 rescan required")),m(!1))})})}async function ic(e={}){if(console.log(),console.log(ue.bold(" Connect WhatsApp")),console.log(),Sm()){console.log(ue.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ue.dim(" agentx daemon stop")),console.log();let{cont:d}=await Hs({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});d||(console.log(ue.red(" Aborted")),process.exit(1))}let o=e.configPath||Gs(process.cwd(),"agentx.json");zs(o)||(console.log(ue.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(sc(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||xm,s=Gs(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ue.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Hs({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(m=>({title:m,value:m})),initial:0})).agent),r||(console.log(ue.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Em(s)&&a){let{keep:d}=await Hs({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!d,d&&console.log(ue.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Am(s,m=>console.log(m))||(console.log(ue.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await de(d=>{be(d,"channels.whatsapp.enabled",!0),be(d,"channels.whatsapp.sessionDir",n),be(d,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ue.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ue.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ue.dim(` Session: ${n}`)),console.log(ue.dim(" Start the daemon to begin receiving:")),console.log(ue.dim(" agentx daemon start")),console.log(ue.dim(" Add routes later with:")),console.log(ue.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Om}from"crypto";import $e from"chalk";import rc from"prompts";var Dn="agentx-mesh:",Pn="//join/";function Im(e){return Buffer.from(e,"utf-8").toString("base64url")}function jm(e){return Buffer.from(e,"base64url").toString("utf-8")}function Cm(e){return`${Dn}${Pn}${Im(JSON.stringify(e))}`}function Tm(e){if(!e.startsWith(`${Dn}${Pn}`))throw new Error(`Not a mesh invite link \u2014 expected ${Dn}${Pn}\u2026`);let o=e.slice(Dn.length+Pn.length),t=JSON.parse(jm(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 Nm(){return Om(32).toString("hex")}function Rm(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function _m(e){return e?.node?.name||e?.node?.id||"node"}async function ac(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log($e.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Js("MESH_TOKEN");r||(r=Nm(),qt("MESH_TOKEN",r),console.log($e.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Rm(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:l}=await rc({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://"});l||(console.log($e.red(" Aborted")),process.exit(1)),a=l}let d=await de(l=>{be(l,"mesh.enabled",!0)},{configPath:e.configPath});d.success||(console.log($e.red(` \u2717 ${d.error}`)),process.exit(1));let m=Cm({url:a,token:r,name:_m(i),version:1});console.log(),console.log($e.bold(" Mesh invite")),console.log(),console.log(` ${$e.cyan(m)}`),console.log(),console.log($e.dim(" Run on the other node:")),console.log($e.dim(` agentx connect mesh join "${m}"`)),console.log(),console.log($e.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function cc(e,o={}){let t;try{t=Tm(e)}catch(i){console.log($e.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Js("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await rc({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log($e.red(" Aborted (keeping existing .env)")),process.exit(1))}qt("MESH_TOKEN",t.token);let s=await de(i=>{be(i,"mesh.enabled",!0);let r=jo(i,"mesh.peers")||[],a=r.findIndex(d=>d.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),be(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log($e.red(` \u2717 ${s.error}`)),process.exit(1)),console.log($e.green(" \u2713 Joined mesh")),console.log($e.dim(` Peer: ${t.name} @ ${t.url}`)),console.log($e.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log($e.dim(" Daemon hot-reloaded.")):console.log($e.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log($e.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log($e.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log($e.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var ct=new Dm().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");ct.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 nc({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});ct.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 ic({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var lc=ct.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");lc.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 ac({url:e.url,configPath:e.config})});lc.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 cc(e,{configPath:o.config})});ct.action(()=>{console.log(),console.log(at.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${at.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${at.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${at.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${at.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(at.dim(" GitLab connect is the next slice.")),console.log()});we();import{Command as Pm}from"commander";import le from"chalk";var Bt=new Pm().name("usage").description("token usage analysis and reporting");Bt.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=D(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(le.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(le.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${le.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${le.red(String(s.totalErrors))}`),console.log(),console.log(le.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let d=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),m=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${le.cyan(a)}: ${d} tokens (${c.tasks} tasks) ${le.dim(m)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(le.red(" Daemon not running. Start with: agentx daemon start")):console.log(le.red(` ${e.message}`))}});Bt.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(le.red(` Script not found: ${s}`)),console.log(le.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(le.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(le.red(" Analysis failed. Is Python 3 installed?"))}});Bt.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-XJEQAWN3.js"),r=await i(),a=new Set(n.filter(l=>l.kind==="cli").map(l=>l.name)),c=[],d=(l,u)=>{for(let f of l.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),d(f,p)}};d(r,"");let m=c.filter(l=>!a.has(l)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:m},null,2));return}console.log(),console.log(le.bold(` Never used in the last ${e.days} days (${m.length}/${c.length})`)),console.log();for(let l of m)console.log(` ${le.dim("\xB7")} ${l}`);console.log(),console.log(le.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(le.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(le.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(le.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(le.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(le.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=le.dim(`${i.days}d`);console.log(` ${le.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(le.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Lm}from"commander";import fe from"chalk";import{resolve as Mm}from"path";we();var vo=new Lm().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");vo.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{ji(Mm(process.cwd(),".env"))}catch{}let o=Um(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-CBOESBMD.js");t(o)}catch(o){console.log(fe.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(fe.dim(o.stack)),process.exit(1)}});function Um(e,o){try{let t=D();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(fe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(fe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
314
+ `)),{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}}}}vo.command("list").description("list configured boards").action(()=>{try{let e=D();if(!e.boards?.length){console.log(fe.dim(`
324
315
  No boards configured.
325
- `));return}console.log();for(let o of e.boards){console.log(` ${fe.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(fe.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(fe.dim(` primary label: ${o.primaryToolLabel}`)),console.log(fe.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(fe.red(` ${e.message}`)),process.exit(1)}});ko.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{Jt(t=>{if(Array.isArray(t.boards)||(t.boards=[]),t.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(o.projects).split(",").map(i=>i.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:o.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(o.days,10)||30,closedWindowDays:parseInt(o.closedDays,10)||30};return o.label&&(s.primaryToolLabel=o.label),t.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(t){console.log(fe.red(` ${t.message}`)),process.exit(1)}});ko.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{Jt(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(o.name&&(s.name=o.name,i.push(`name="${o.name}"`)),o.projects){let r=String(o.projects).split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:r},i.push(`projects=${r.length}`)}if(o.label!==void 0&&(o.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=o.label,i.push(`label="${o.label}"`))),o.days&&(s.timeRangeDays=parseInt(o.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),o.closedDays&&(s.closedWindowDays=parseInt(o.closedDays,10)||s.closedWindowDays,i.push(`closed-days=${s.closedWindowDays}`)),i.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${i.join(", ")})`})}catch(t){console.log(fe.red(` ${t.message}`)),process.exit(1)}});var Hs=ko.command("column").description("manage a board's columns (add / remove / edit / list)");Hs.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(el("fs").readFileSync("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!t)throw new Error(`board "${e}" not found`);let n=t.columns||[];if(n.length===0){console.log(fe.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let i=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${fe.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${fe.dim(i)}`)}}catch(o){console.log(fe.red(` ${o.message}`)),process.exit(1)}});Hs.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{Jt(n=>{let i=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!i)throw new Error(`board "${e}" not found`);if(i.columns=i.columns||[],i.columns.find(a=>a.id===o))throw new Error(`column "${o}" already exists on board "${e}"`);let r={id:o,title:t.title,kind:t.kind,scopedPrefix:t.scopedPrefix};if(t.kind==="scoped-label"){if(!t.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=t.scoped}if(t.kind==="label"){if(!t.label)throw new Error("--label required for kind=label");r.mapsToLabel=t.label}return t.accent&&(r.accent=t.accent),i.columns.push(r),`column "${o}" added to board "${e}"`})}catch(n){console.log(fe.red(` ${n.message}`)),process.exit(1)}});Hs.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{Jt(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(r=>r.id!==o),s.columns.length===i)throw new Error(`column "${o}" not found`);return`column "${o}" removed from board "${e}"`})}catch(t){console.log(fe.red(` ${t.message}`)),process.exit(1)}});ko.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Jt(o=>{if(!Array.isArray(o.boards)||o.boards.length===0)throw new Error("no boards configured");let t=o.boards.length;if(o.boards=o.boards.filter(n=>n.id!==e),o.boards.length===t)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(o){console.log(fe.red(` ${o.message}`)),process.exit(1)}});function Jt(e){let{summary:o,backupPath:t}=Ko(n=>e(n));console.log(fe.green(`
316
+ `));return}console.log();for(let o of e.boards){console.log(` ${fe.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(fe.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(fe.dim(` primary label: ${o.primaryToolLabel}`)),console.log(fe.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(fe.red(` ${e.message}`)),process.exit(1)}});vo.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{Jt(t=>{if(Array.isArray(t.boards)||(t.boards=[]),t.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(o.projects).split(",").map(i=>i.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:o.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(o.days,10)||30,closedWindowDays:parseInt(o.closedDays,10)||30};return o.label&&(s.primaryToolLabel=o.label),t.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(t){console.log(fe.red(` ${t.message}`)),process.exit(1)}});vo.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{Jt(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(o.name&&(s.name=o.name,i.push(`name="${o.name}"`)),o.projects){let r=String(o.projects).split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:r},i.push(`projects=${r.length}`)}if(o.label!==void 0&&(o.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=o.label,i.push(`label="${o.label}"`))),o.days&&(s.timeRangeDays=parseInt(o.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),o.closedDays&&(s.closedWindowDays=parseInt(o.closedDays,10)||s.closedWindowDays,i.push(`closed-days=${s.closedWindowDays}`)),i.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${i.join(", ")})`})}catch(t){console.log(fe.red(` ${t.message}`)),process.exit(1)}});var Ys=vo.command("column").description("manage a board's columns (add / remove / edit / list)");Ys.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(sl("fs").readFileSync("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!t)throw new Error(`board "${e}" not found`);let n=t.columns||[];if(n.length===0){console.log(fe.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let i=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${fe.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${fe.dim(i)}`)}}catch(o){console.log(fe.red(` ${o.message}`)),process.exit(1)}});Ys.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{Jt(n=>{let i=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!i)throw new Error(`board "${e}" not found`);if(i.columns=i.columns||[],i.columns.find(a=>a.id===o))throw new Error(`column "${o}" already exists on board "${e}"`);let r={id:o,title:t.title,kind:t.kind,scopedPrefix:t.scopedPrefix};if(t.kind==="scoped-label"){if(!t.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=t.scoped}if(t.kind==="label"){if(!t.label)throw new Error("--label required for kind=label");r.mapsToLabel=t.label}return t.accent&&(r.accent=t.accent),i.columns.push(r),`column "${o}" added to board "${e}"`})}catch(n){console.log(fe.red(` ${n.message}`)),process.exit(1)}});Ys.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{Jt(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(r=>r.id!==o),s.columns.length===i)throw new Error(`column "${o}" not found`);return`column "${o}" removed from board "${e}"`})}catch(t){console.log(fe.red(` ${t.message}`)),process.exit(1)}});vo.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Jt(o=>{if(!Array.isArray(o.boards)||o.boards.length===0)throw new Error("no boards configured");let t=o.boards.length;if(o.boards=o.boards.filter(n=>n.id!==e),o.boards.length===t)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(o){console.log(fe.red(` ${o.message}`)),process.exit(1)}});function Jt(e){let{summary:o,backupPath:t}=Vo(n=>e(n));console.log(fe.green(`
326
317
  \u2713 ${o}
327
318
  `)),t&&console.log(fe.dim(` Backup: ${t}`)),console.log(fe.dim(` Restart the dashboard to pick up the change if not auto-reloading.
328
- `))}import{Command as Um}from"commander";import m from"chalk";import{resolve as q,relative as rc,dirname as ac}from"path";import{execSync as Mo}from"child_process";import{writeFileSync as Uo,mkdirSync as ro,readFileSync as Ht,readdirSync as Fm,renameSync as _n,rmSync as qm,existsSync as We}from"fs";function $e(e,o){return new Zn(Gt(e),void 0,o||"graph")}function Gt(e){return e||q(process.cwd(),".agentx/wiki")}function zs(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var ee=new Um().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=$e(e.dir,o),n=t.summary(),i=t.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${zs(o)}]`)),console.log(),console.log(` Total raw entries: ${i}`),console.log(` Agents: ${n.length}`),console.log();for(let a of n){let c=a.unabsorbed>0?m.yellow(`${a.unabsorbed} unabsorbed`):m.green("up to date");if(console.log(` ${m.cyan(a.agentId)}`),console.log(` Entries: ${a.totalEntries} Articles: ${a.totalArticles} ${c}`),a.articles.length>0){for(let d of a.articles.slice(0,3))console.log(m.dim(` - ${d.title} [${(d.tags||[]).slice(0,3).join(", ")}]`));a.articles.length>3&&console.log(m.dim(` ... and ${a.articles.length-3} more`))}console.log()}let r=n.reduce((a,c)=>a+c.unabsorbed,0);r>0&&(console.log(m.dim(` ${r} raw entries on disk. Absorb is deprecated \u2014 see 'agentx wiki absorb --help'.`)),console.log())});ee.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(e=>{let o=$e(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=$e(e.dir,o),n=e.agent?[e.agent]:t.listAgents(),s=parseInt(e.max),i=(()=>{try{let u=q(process.cwd(),".agentx/graph");return We(u)?new lo({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)},d=(u,f)=>{let p=new Map;for(let y of u){let $=f.find(x=>x.id===y);if(!$)continue;let b=c($);if(!b?.length)continue;let v=b.join("/"),A=p.get(v);A?A.n++:p.set(v,{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,l=0;for(let u of n){let f=typeof e.since=="string"?e.since.trim():"",p=t.getUnabsorbedEntries(u).filter(k=>!f||(k.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 k of p.slice(0,3))console.log(m.dim(` [${k.date} via ${k.source}] ${k.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(),$=w.getWorldview()||t.getSharedStore().getWorldview()||"",b=p.map(k=>`--- ENTRY ${k.id} [${k.date} ${k.agentId} via ${k.source}] ---
319
+ `))}import{Command as Fm}from"commander";import g from"chalk";import{resolve as q,relative as dc,dirname as gc}from"path";import{execSync as Uo}from"child_process";import{writeFileSync as Fo,mkdirSync as ao,readFileSync as Ht,readdirSync as qm,renameSync as Ln,rmSync as Wm,existsSync as We}from"fs";function ke(e,o){return new ts(Gt(e),void 0,o||"graph")}function Gt(e){return e||q(process.cwd(),".agentx/wiki")}function Vs(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var ee=new Fm().name("wiki").description("wiki knowledge base management");ee.command("status").description("show wiki status per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").action(e=>{let o=e.mode,t=ke(e.dir,o),n=t.summary(),i=t.getSharedStore().listEntries().length;console.log(),console.log(g.bold(` Wiki Hub Status [${Vs(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?g.yellow(`${a.unabsorbed} unabsorbed`):g.green("up to date");if(console.log(` ${g.cyan(a.agentId)}`),console.log(` Entries: ${a.totalEntries} Articles: ${a.totalArticles} ${c}`),a.articles.length>0){for(let d of a.articles.slice(0,3))console.log(g.dim(` - ${d.title} [${(d.tags||[]).slice(0,3).join(", ")}]`));a.articles.length>3&&console.log(g.dim(` ... and ${a.articles.length-3} more`))}console.log()}let r=n.reduce((a,c)=>a+c.unabsorbed,0);r>0&&(console.log(g.dim(` ${r} raw entries on disk. Absorb is deprecated \u2014 see 'agentx wiki absorb --help'.`)),console.log())});ee.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(e=>{let o=ke(e.dir,e.mode),t=e.agent?[e.agent]:o.listAgents(),n=0;console.log();for(let s of t){let r=o.getAgentWiki(s).lint();if(n+=r.length,r.length===0)console.log(` ${g.cyan(s)}: ${g.green("healthy")}`);else{console.log(` ${g.cyan(s)}: ${g.yellow(`${r.length} issues`)}`);for(let a of r){let c=a.type==="broken-link"?"x":a.type==="orphan"?"?":"!";console.log(` [${c}] ${g.dim(a.type)} ${a.article}: ${a.message}`)}}}console.log(),n===0&&console.log(g.green(" All agent wikis are healthy")),console.log()});ee.command("absorb").description("compile unabsorbed entries into typed per-agent wiki articles (Farzapedia-faithful)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","absorb only this agent").option("--dry-run","preview without running").option("--no-facts","skip the system-of-record lookups").option("--max <n>","max entries per agent","10").option("--since <date>","only entries dated on or after YYYY-MM-DD").action(async e=>{let o=e.mode,t=ke(e.dir,o),n=e.agent?[e.agent]:t.listAgents(),s=parseInt(e.max),i=(()=>{try{let u=q(process.cwd(),".agentx/graph");return We(u)?new go({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)},d=(u,f)=>{let p=new Map;for(let y of u){let $=f.find(x=>x.id===y);if(!$)continue;let b=c($);if(!b?.length)continue;let v=b.join("/"),A=p.get(v);A?A.n++:p.set(v,{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},m=0,l=0;for(let u of n){let f=typeof e.since=="string"?e.since.trim():"",p=t.getUnabsorbedEntries(u).filter(k=>!f||(k.date??"")>=f).slice(0,s);if(p.length===0){console.log(` ${g.cyan(u)}: ${g.green("all absorbed")}`);continue}console.log(),console.log(g.bold(` ${g.cyan(u)}: ${p.length} entries to absorb`));for(let k of p.slice(0,3))console.log(g.dim(` [${k.date} via ${k.source}] ${k.content.slice(0,80)}...`));if(p.length>3&&console.log(g.dim(` ... and ${p.length-3} more`)),e.dryRun)continue;let w=t.getAgentWiki(u),y=w.rebuildIndex(),$=w.getWorldview()||t.getSharedStore().getWorldview()||"",b=p.map(k=>`--- ENTRY ${k.id} [${k.date} ${k.agentId} via ${k.source}] ---
329
320
  ${k.content}
330
321
  --- END ENTRY ---`).join(`
331
322
 
332
- `),v="";if(e.facts!==!1){let{extractHints:k,resolveFacts:R,mergeRecords:j,renderFactsBlock:C,installPrompts:D,defaultSources:W,recordsFromEntries:P}=await import("./facts-YVEJOM7O.js");if(!a){let B=new Set;for(let ke of t.listAgents())for(let he of t.getAgentWiki(ke).listArticles(ke))he.meta.type==="person"&&B.add(he.meta.title);a=[...B]}let H=k(p.map(B=>({context:B.sourceContext,content:B.content,sender:typeof B.meta?.sender=="string"?B.meta.sender:void 0})),{known:a}),ae=P(p);if(H.length>0||ae.length>0){let B=W(),{records:ke,results:he}=H.length>0?await R(H,{sources:B}):{records:[],results:[]},_=j([...ae,...ke]);v=C(_);let Fe=[...ae.length>0?[`entries:${ae.length}`]:[],...he.filter(ye=>ye.records.length>0).map(ye=>`${ye.source}:${ye.records.length}`)];console.log(m.dim(` Facts: ${H.length} entities \u2192 ${_.length} resolved${Fe.length?` (${Fe.join(" ")})`:""}`));for(let ye of D(he,B))console.log(m.yellow(` ! ${ye.source} ${ye.kind} \u2014 would supply ${ye.provides.join(", ")}`)),console.log(m.dim(` ${ye.hint}`))}}let A=zi(o,u,$,y.articles,b,p.length,v);console.log(m.dim(` Mode: ${zs(o)}`));let x=q(w.baseDir,"_tmp");ro(x,{recursive:!0});let E=q(x,"absorb-prompt.txt");Uo(E,A),console.log(m.dim(" Compiling with Claude..."));try{let k;try{k=Mo(`cat '${E}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Jo({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(_){if(k=_.stdout||"",!k)throw _}let R=k;try{let _=JSON.parse(k);R=_.result||_.content||"",R||(console.log(m.dim(` Claude envelope keys: ${Object.keys(_).join(", ")}`)),console.log(m.dim(` is_error: ${_.is_error}, stop_reason: ${_.stop_reason}`)))}catch{}let j,C=[],D=R.indexOf("{"),W=R.indexOf("["),P=D>=0&&(W<0||D<W)?D:W;if(P===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(R.slice(0,500)));continue}let H=R[P],ae=H==="{"?"}":"]",B=0,ke=-1;for(let _=P;_<R.length;_++)if(R[_]===H)B++;else if(R[_]===ae&&(B--,B===0)){ke=_+1;break}if(ke===-1){console.log(m.red(" Unbalanced JSON"));continue}let he=R.slice(P,ke);try{let _=JSON.parse(he);Array.isArray(_)?j=_:(j=_.articles||[],C=_.gaps||[])}catch(_){console.log(m.red(` JSON parse error: ${_.message}`)),console.log(m.dim(` First 300 chars: ${he.slice(0,300)}`));continue}for(let _ of j){let Fe=new Date().toISOString().slice(0,10),ye=d(_.sources||[],p);w.writeArticle(_.path,{title:_.title,type:_.type,related:Array.isArray(_.related)?_.related:void 0,tags:_.tags||[],owner:u,access:"public",created:Fe,lastUpdated:Fe,sources:_.sources||[],graphPath:ye},_.content,u);let Ao=_.type?m.magenta(`[${_.type}]`)+" ":"",T=Array.isArray(_.related)&&_.related.length?` \u2192 ${_.related.slice(0,3).join(", ")}${_.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${Ao}${_.path}: ${_.title}${m.dim(T)}`);let me=(_.tags||[]).slice(0,4).join(", ");me&&console.log(m.dim(` tags: ${me}`)),ye?.length&&(console.log(m.dim(` graphPath: ${ye.join(" \u203A ")}`)),l++),g++}if(C.length>0){console.log(),console.log(m.yellow(` Gaps detected (${C.length} missing pieces):`));for(let _ of C)console.log(m.yellow(` ? ${_}`));try{let{QuestionStore:_}=await import("./questions-4B4KSPXG.js"),Fe=new _(Gt(e.dir)).add(C.map(ye=>({kind:"article",agentId:u,path:"",subject:String(ye).slice(0,120),question:`No article yet for: ${String(ye).slice(0,160)}`})));Fe.added>0&&console.log(m.dim(` queued ${Fe.added} for follow-up (agentx wiki questions)`))}catch{}}w.rebuildIndex()}catch(k){console.log(m.red(` Absorb failed: ${k.message?.slice(0,200)}`)),k.stderr&&console.log(m.dim(String(k.stderr).slice(0,300))),k.stdout&&console.log(m.dim("stdout: "+String(k.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let u=g>0?Math.round(l/g*100):0;console.log(m.dim(` ${l}/${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=Wm(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-UTS4RX4U.js"),{default:c}=await import("better-sqlite3"),d=q(process.cwd(),".agentx/db.sqlite");if(!We(d))console.log(m.yellow(` --reviews: no ${d}`));else{let g=new c(d,{readonly:!0});try{let l=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(o??6048e5));i=a(l,{kinds:String(e.reviewKinds).split(",").map(p=>p.trim()).filter(Boolean)});let u=i.filter(p=>(p.occurrences??1)>1).length;console.log(m.dim(` ${l.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 Yi({extraCandidates:i,wikiDir:e.dir?q(e.dir):void 0,memoryRoot:e.memoryDir?q(e.memoryDir):void 0,sinceMs:o,agentFilter:e.agent,types:t,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,log:a=>console.log(m.dim(` ${a}`))});if(r.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.clusters){let c=a.candidates[0],d=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${d} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${c.memory.description}`))}if(console.log(),r.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to promote")),console.log();return}for(let a of r.written){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",d=a.related?.length?` \u2192 ${a.related.slice(0,3).join(", ")}${a.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${c}${a.path}: ${a.title}${m.dim(d)}`),console.log(m.dim(` from: ${a.stamps.join(", ")}`))}for(let a of r.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(m.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(m.dim(` ! ${a}`));for(let a of r.errors)console.log(m.red(` x ${a}`));console.log(),console.log(r.errors.length?m.red(` ${r.written.length} promoted, ${r.errors.length} error(s)`):m.green(` ${r.written.length} promoted, ${r.skipped.length} skipped`)),console.log(),r.errors.length&&process.exit(1)});function Wm(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());o||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}ee.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",q(process.cwd(),".agentx/task-history")).option("--n <n>","number of messages to sample (newest first)","10").option("--out <path>","markdown output file (default: stdout)").option("--selector-model <m>","agentic selector model","haiku").option("--synth-model <m>","agentic synthesis model","sonnet").action(async e=>{let{agenticQuery:o}=await import("./query-XLJ6I34S.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=$e(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let d=a.getAgentWiki(c),g=parseInt(e.n),l=i(e.history,c);if(!s(l)){console.log(m.yellow(` no task-history at ${l}`));return}let u=[],f=t(l).sort().reverse();for(let y of f){let $=r(l,y),b=[];try{b=t($).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of b){if(u.length>=g)break;try{let A=JSON.parse(n(r($,v),"utf-8")),x=A.message||A.task?.message;typeof x=="string"&&x.trim().length>10&&u.push({id:A.id||v.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 ${l}`));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 $=u[y];process.stdout.write(m.dim(` [${y+1}/${u.length}] querying... `));let v=d.findRelevant($.message,c,3).map(x=>`- **${x.meta.title}** [${x.meta.type||"?"}] (${x.path})`).join(`
323
+ `),v="";if(e.facts!==!1){let{extractHints:k,resolveFacts:N,mergeRecords:C,renderFactsBlock:j,installPrompts:P,defaultSources:W,recordsFromEntries:L}=await import("./facts-YVEJOM7O.js");if(!a){let B=new Set;for(let ve of t.listAgents())for(let he of t.getAgentWiki(ve).listArticles(ve))he.meta.type==="person"&&B.add(he.meta.title);a=[...B]}let H=k(p.map(B=>({context:B.sourceContext,content:B.content,sender:typeof B.meta?.sender=="string"?B.meta.sender:void 0})),{known:a}),ae=L(p);if(H.length>0||ae.length>0){let B=W(),{records:ve,results:he}=H.length>0?await N(H,{sources:B}):{records:[],results:[]},_=C([...ae,...ve]);v=j(_);let Fe=[...ae.length>0?[`entries:${ae.length}`]:[],...he.filter(ye=>ye.records.length>0).map(ye=>`${ye.source}:${ye.records.length}`)];console.log(g.dim(` Facts: ${H.length} entities \u2192 ${_.length} resolved${Fe.length?` (${Fe.join(" ")})`:""}`));for(let ye of P(he,B))console.log(g.yellow(` ! ${ye.source} ${ye.kind} \u2014 would supply ${ye.provides.join(", ")}`)),console.log(g.dim(` ${ye.hint}`))}}let A=Vi(o,u,$,y.articles,b,p.length,v);console.log(g.dim(` Mode: ${Vs(o)}`));let x=q(w.baseDir,"_tmp");ao(x,{recursive:!0});let E=q(x,"absorb-prompt.txt");Fo(E,A),console.log(g.dim(" Compiling with Claude..."));try{let k;try{k=Uo(`cat '${E}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Ho({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(_){if(k=_.stdout||"",!k)throw _}let N=k;try{let _=JSON.parse(k);N=_.result||_.content||"",N||(console.log(g.dim(` Claude envelope keys: ${Object.keys(_).join(", ")}`)),console.log(g.dim(` is_error: ${_.is_error}, stop_reason: ${_.stop_reason}`)))}catch{}let C,j=[],P=N.indexOf("{"),W=N.indexOf("["),L=P>=0&&(W<0||P<W)?P:W;if(L===-1){console.log(g.red(" No JSON found in response")),console.log(g.dim(N.slice(0,500)));continue}let H=N[L],ae=H==="{"?"}":"]",B=0,ve=-1;for(let _=L;_<N.length;_++)if(N[_]===H)B++;else if(N[_]===ae&&(B--,B===0)){ve=_+1;break}if(ve===-1){console.log(g.red(" Unbalanced JSON"));continue}let he=N.slice(L,ve);try{let _=JSON.parse(he);Array.isArray(_)?C=_:(C=_.articles||[],j=_.gaps||[])}catch(_){console.log(g.red(` JSON parse error: ${_.message}`)),console.log(g.dim(` First 300 chars: ${he.slice(0,300)}`));continue}for(let _ of C){let Fe=new Date().toISOString().slice(0,10),ye=d(_.sources||[],p);w.writeArticle(_.path,{title:_.title,type:_.type,related:Array.isArray(_.related)?_.related:void 0,tags:_.tags||[],owner:u,access:"public",created:Fe,lastUpdated:Fe,sources:_.sources||[],graphPath:ye},_.content,u);let Oo=_.type?g.magenta(`[${_.type}]`)+" ":"",T=Array.isArray(_.related)&&_.related.length?` \u2192 ${_.related.slice(0,3).join(", ")}${_.related.length>3?", \u2026":""}`:"";console.log(` ${g.green("+")} ${Oo}${_.path}: ${_.title}${g.dim(T)}`);let me=(_.tags||[]).slice(0,4).join(", ");me&&console.log(g.dim(` tags: ${me}`)),ye?.length&&(console.log(g.dim(` graphPath: ${ye.join(" \u203A ")}`)),l++),m++}if(j.length>0){console.log(),console.log(g.yellow(` Gaps detected (${j.length} missing pieces):`));for(let _ of j)console.log(g.yellow(` ? ${_}`));try{let{QuestionStore:_}=await import("./questions-4B4KSPXG.js"),Fe=new _(Gt(e.dir)).add(j.map(ye=>({kind:"article",agentId:u,path:"",subject:String(ye).slice(0,120),question:`No article yet for: ${String(ye).slice(0,160)}`})));Fe.added>0&&console.log(g.dim(` queued ${Fe.added} for follow-up (agentx wiki questions)`))}catch{}}w.rebuildIndex()}catch(k){console.log(g.red(` Absorb failed: ${k.message?.slice(0,200)}`)),k.stderr&&console.log(g.dim(String(k.stderr).slice(0,300))),k.stdout&&console.log(g.dim("stdout: "+String(k.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(g.dim(" Dry run \u2014 no changes made"));else if(m>0&&(console.log(g.green(` ${m} articles compiled across ${n.length} agent(s)`)),i)){let u=m>0?Math.round(l/m*100):0;console.log(g.dim(` ${l}/${m} 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=Bm(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(g.red(` Invalid memory type "${s}". Valid: ${n.join(", ")}`)),process.exit(1)),e.commit&&!e.via&&!e.model&&(console.log(g.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1)),console.log(),console.log(g.bold(" Memory \u2192 Wiki Promotion")),console.log();let i=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-7QKNMRGU.js"),{default:c}=await import("better-sqlite3"),d=q(process.cwd(),".agentx/db.sqlite");if(!We(d))console.log(g.yellow(` --reviews: no ${d}`));else{let m=new c(d,{readonly:!0});try{let l=m.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(o??6048e5));i=a(l,{kinds:String(e.reviewKinds).split(",").map(p=>p.trim()).filter(Boolean)});let u=i.filter(p=>(p.occurrences??1)>1).length;console.log(g.dim(` ${l.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(g.dim(` most recurrent (${f.occurrences} sessions): ${f.memory.description.slice(0,84)}`))}finally{m.close()}}}let r=await Xi({extraCandidates:i,wikiDir:e.dir?q(e.dir):void 0,memoryRoot:e.memoryDir?q(e.memoryDir):void 0,sinceMs:o,agentFilter:e.agent,types:t,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,log:a=>console.log(g.dim(` ${a}`))});if(r.candidates.length===0){console.log(g.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.clusters){let c=a.candidates[0],d=a.corroboratingAgents.length>1?g.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${g.cyan(`[${c.memory.type}]`)} ${c.memory.name}${d} ${g.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(g.dim(` ${c.memory.description}`))}if(console.log(),r.dryRun){console.log(g.dim(" Dry run \u2014 pass --commit to promote")),console.log();return}for(let a of r.written){let c=a.type?g.magenta(`[${a.type}]`)+" ":"",d=a.related?.length?` \u2192 ${a.related.slice(0,3).join(", ")}${a.related.length>3?", \u2026":""}`:"";console.log(` ${g.green("+")} ${c}${a.path}: ${a.title}${g.dim(d)}`),console.log(g.dim(` from: ${a.stamps.join(", ")}`))}for(let a of r.skipped)console.log(` ${g.yellow("-")} ${a.stamp} ${g.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(g.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(g.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(g.dim(` ! ${a}`));for(let a of r.errors)console.log(g.red(` x ${a}`));console.log(),console.log(r.errors.length?g.red(` ${r.written.length} promoted, ${r.errors.length} error(s)`):g.green(` ${r.written.length} promoted, ${r.skipped.length} skipped`)),console.log(),r.errors.length&&process.exit(1)});function Bm(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());o||(console.log(g.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}ee.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",q(process.cwd(),".agentx/task-history")).option("--n <n>","number of messages to sample (newest first)","10").option("--out <path>","markdown output file (default: stdout)").option("--selector-model <m>","agentic selector model","haiku").option("--synth-model <m>","agentic synthesis model","sonnet").action(async e=>{let{agenticQuery:o}=await import("./query-EDW72Q4O.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=ke(e.dir),c=e.agent;if(!c){console.log(g.red(" --agent <id> is required"));return}let d=a.getAgentWiki(c),m=parseInt(e.n),l=i(e.history,c);if(!s(l)){console.log(g.yellow(` no task-history at ${l}`));return}let u=[],f=t(l).sort().reverse();for(let y of f){let $=r(l,y),b=[];try{b=t($).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of b){if(u.length>=m)break;try{let A=JSON.parse(n(r($,v),"utf-8")),x=A.message||A.task?.message;typeof x=="string"&&x.trim().length>10&&u.push({id:A.id||v.replace(".json",""),message:x.trim(),ts:A.at||A.timestamp||y})}catch{}}if(u.length>=m)break}if(u.length===0){console.log(g.yellow(` no task messages found under ${l}`));return}console.log(),console.log(g.bold(` A/B harness \u2014 ${u.length} messages from ${c}`)),console.log(g.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(g.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 $=u[y];process.stdout.write(g.dim(` [${y+1}/${u.length}] querying... `));let v=d.findRelevant($.message,c,3).map(x=>`- **${x.meta.title}** [${x.meta.type||"?"}] (${x.path})`).join(`
333
324
  `)||"_(none returned)_",A;try{let x=await o($.message,d,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(x.status!=="ok")A=`_(status: ${x.status}${x.error?" \u2014 "+x.error:""})_`;else{let E=x.citations.map(k=>`\`${k.title}\` [${k.type||"?"}]`).join(", ");A=`**Answer:**
334
325
 
335
326
  ${x.answer}
336
327
 
337
- **Citations:** ${E}`}}catch(x){A=`_(error: ${x.message})_`}console.log(m.dim("done")),p.push(`## ${y+1}. ${$.id}`,"",`> ${$.message.replace(/\n/g," ").slice(0,400)}${$.message.length>400?"\u2026":""}`,"","### OLD \u2014 BM25 preload (top 3)","",v,"","### NEW \u2014 agentic query","",A,"","| Path | Rating 0\u20132 | Notes |","|---|---|---|","| OLD | | |","| NEW | | |","")}let w=p.join(`
338
- `);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?Ht(e.answers,"utf-8").split(/\r?\n/).filter(T=>T.length>0):null,i=0;if(!e.agent){console.log(m.red(" --agent <id> is required. The article will be owned by this agent."));return}let r=$e(e.dir),a;try{a=r.getAgentWiki(e.agent)}catch(T){console.log(m.red(` can't open wiki for agent "${e.agent}": ${T.message}`));return}let c=s?null:o.createInterface({input:process.stdin,output:process.stdout}),d=async T=>{if(s){let me=s[i++]??"";return process.stdout.write(T+m.dim(`[scripted] ${me.slice(0,80)}${me.length>80?"\u2026":""}`)+`
339
- `),me.trim()}return(await c.question(T)).trim()};console.log(),console.log(m.bold(" Wiki Interview")),console.log(m.dim(" One article per session. Empty answer = skip field. /done = stop & synthesize. /abort = quit.")),console.log();let g=e.topic||"";if(!g&&(g=await d(m.cyan(" Topic? ")+m.dim("(a person, a procedure, a past event, \u2026) ")),!g||g==="/abort")){c?.close();return}let l=(e.type||"").toLowerCase(),u=new Set(n);if(!u.has(l)){console.log(m.dim(` Types: ${n.join(" | ")}`));let T=await d(m.cyan(" Type? "));if(T==="/abort"){c?.close();return}u.has(T)?l=T:(console.log(m.yellow(` "${T}" isn't a valid type. Falling back to "concept".`)),l="concept")}let f={person:["Full name (and any aliases / Telegram handle / GitLab username)?","Role or title?","Which org or team are they part of (use the article title if you have one)?","Key responsibilities in OUR work?","Preferred channel to reach them (Telegram, email, in-person, \u2026)?","Who do they report to? (skip if none)","Notable decisions, events, or patterns they're involved in?","Anything quirky we should remember (timezone, working hours, style)?"],project:["One-line description \u2014 what is this project?","Who owns it? (person article title)","Tech stack or key tools involved?","Current status (active / paused / archived)?","Repo / URL / path on disk?","Two or three key decisions made so far?","Any open blockers, risks, or known issues?","Related projects or patterns?"],place:["Kind \u2014 office / server / environment / domain / URL?","Address \u2014 URL, IP, hostname, or physical location?","Owner (person or team)?","How to access it (SSH host, login, VPN, \u2026)?","What lives there (services, people, data)?","Known quirks (timezone, uptime, access restrictions)?"],concept:["Define it in one sentence \u2014 what does this term mean in OUR work?","Where did we first adopt it (origin story, date)?","Two or three concrete examples from our team?","What does it replace or extend (older concept, related concept)?","Common misunderstandings to avoid?"],event:["Date (YYYY-MM-DD)?","One-line summary \u2014 what happened?","Who was involved?","Timeline \u2014 key moments (start \u2192 resolution)?","Impact \u2014 what broke, what got delivered, who was affected?","Resolution / outcome?","Follow-ups or lessons captured?"],decision:["Context \u2014 what was the situation forcing a choice?","Options that were considered?","Chosen option \u2014 and one-sentence why?","Alternatives rejected \u2014 and one-sentence why not?","Who decided, and when (date)?","Is this reversible, and what would trigger a revisit?"],pattern:["Trigger \u2014 when should someone follow this pattern?","Inputs required (what do you need before starting)?","Steps in order \u2014 keep it tight, one line per step?","Expected output \u2014 how do you know it worked?","Common failure modes?","Related patterns, decisions, or runbooks?"]},p=f[l]||f.concept;console.log(),console.log(m.bold(` Topic: ${m.cyan(g)} \xB7 Type: ${m.magenta(l)}`)),console.log(m.dim(` ${p.length} questions. Skip with empty answer. /done to stop early.`)),console.log();let w=[],y=!1;for(let T=0;T<p.length;T++){let me=p[T],Be=await d(` ${m.dim(`[${T+1}/${p.length}]`)} ${me}
340
- ${m.green(">")} `);if(Be==="/abort"){y=!0;break}if(Be==="/done")break;Be!=="/skip"&&Be&&w.push({q:me,a:Be})}if(!y){let T=await d(`
341
- ${m.dim("Anything else worth capturing?")}
342
- ${m.green(">")} `);T&&T!=="/abort"&&T!=="/done"&&w.push({q:"Anything else worth capturing?",a:T})}if(y||w.length===0){console.log(m.yellow(`
328
+ **Citations:** ${E}`}}catch(x){A=`_(error: ${x.message})_`}console.log(g.dim("done")),p.push(`## ${y+1}. ${$.id}`,"",`> ${$.message.replace(/\n/g," ").slice(0,400)}${$.message.length>400?"\u2026":""}`,"","### OLD \u2014 BM25 preload (top 3)","",v,"","### NEW \u2014 agentic query","",A,"","| Path | Rating 0\u20132 | Notes |","|---|---|---|","| OLD | | |","| NEW | | |","")}let w=p.join(`
329
+ `);e.out?((await import("fs")).writeFileSync(e.out,w),console.log(),console.log(g.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?Ht(e.answers,"utf-8").split(/\r?\n/).filter(T=>T.length>0):null,i=0;if(!e.agent){console.log(g.red(" --agent <id> is required. The article will be owned by this agent."));return}let r=ke(e.dir),a;try{a=r.getAgentWiki(e.agent)}catch(T){console.log(g.red(` can't open wiki for agent "${e.agent}": ${T.message}`));return}let c=s?null:o.createInterface({input:process.stdin,output:process.stdout}),d=async T=>{if(s){let me=s[i++]??"";return process.stdout.write(T+g.dim(`[scripted] ${me.slice(0,80)}${me.length>80?"\u2026":""}`)+`
330
+ `),me.trim()}return(await c.question(T)).trim()};console.log(),console.log(g.bold(" Wiki Interview")),console.log(g.dim(" One article per session. Empty answer = skip field. /done = stop & synthesize. /abort = quit.")),console.log();let m=e.topic||"";if(!m&&(m=await d(g.cyan(" Topic? ")+g.dim("(a person, a procedure, a past event, \u2026) ")),!m||m==="/abort")){c?.close();return}let l=(e.type||"").toLowerCase(),u=new Set(n);if(!u.has(l)){console.log(g.dim(` Types: ${n.join(" | ")}`));let T=await d(g.cyan(" Type? "));if(T==="/abort"){c?.close();return}u.has(T)?l=T:(console.log(g.yellow(` "${T}" isn't a valid type. Falling back to "concept".`)),l="concept")}let f={person:["Full name (and any aliases / Telegram handle / GitLab username)?","Role or title?","Which org or team are they part of (use the article title if you have one)?","Key responsibilities in OUR work?","Preferred channel to reach them (Telegram, email, in-person, \u2026)?","Who do they report to? (skip if none)","Notable decisions, events, or patterns they're involved in?","Anything quirky we should remember (timezone, working hours, style)?"],project:["One-line description \u2014 what is this project?","Who owns it? (person article title)","Tech stack or key tools involved?","Current status (active / paused / archived)?","Repo / URL / path on disk?","Two or three key decisions made so far?","Any open blockers, risks, or known issues?","Related projects or patterns?"],place:["Kind \u2014 office / server / environment / domain / URL?","Address \u2014 URL, IP, hostname, or physical location?","Owner (person or team)?","How to access it (SSH host, login, VPN, \u2026)?","What lives there (services, people, data)?","Known quirks (timezone, uptime, access restrictions)?"],concept:["Define it in one sentence \u2014 what does this term mean in OUR work?","Where did we first adopt it (origin story, date)?","Two or three concrete examples from our team?","What does it replace or extend (older concept, related concept)?","Common misunderstandings to avoid?"],event:["Date (YYYY-MM-DD)?","One-line summary \u2014 what happened?","Who was involved?","Timeline \u2014 key moments (start \u2192 resolution)?","Impact \u2014 what broke, what got delivered, who was affected?","Resolution / outcome?","Follow-ups or lessons captured?"],decision:["Context \u2014 what was the situation forcing a choice?","Options that were considered?","Chosen option \u2014 and one-sentence why?","Alternatives rejected \u2014 and one-sentence why not?","Who decided, and when (date)?","Is this reversible, and what would trigger a revisit?"],pattern:["Trigger \u2014 when should someone follow this pattern?","Inputs required (what do you need before starting)?","Steps in order \u2014 keep it tight, one line per step?","Expected output \u2014 how do you know it worked?","Common failure modes?","Related patterns, decisions, or runbooks?"]},p=f[l]||f.concept;console.log(),console.log(g.bold(` Topic: ${g.cyan(m)} \xB7 Type: ${g.magenta(l)}`)),console.log(g.dim(` ${p.length} questions. Skip with empty answer. /done to stop early.`)),console.log();let w=[],y=!1;for(let T=0;T<p.length;T++){let me=p[T],Be=await d(` ${g.dim(`[${T+1}/${p.length}]`)} ${me}
331
+ ${g.green(">")} `);if(Be==="/abort"){y=!0;break}if(Be==="/done")break;Be!=="/skip"&&Be&&w.push({q:me,a:Be})}if(!y){let T=await d(`
332
+ ${g.dim("Anything else worth capturing?")}
333
+ ${g.green(">")} `);T&&T!=="/abort"&&T!=="/done"&&w.push({q:"Anything else worth capturing?",a:T})}if(y||w.length===0){console.log(g.yellow(`
343
334
  Nothing captured. Exiting.`)),c?.close();return}let b=a.listArticles(e.agent).slice(0,40).map(T=>`- ${T.meta.title} [${T.meta.type||"?"}]`).join(`
344
- `),v=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${g}`,`**Type:** ${l}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...w.map(T=>`
335
+ `),v=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${m}`,`**Type:** ${l}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...w.map(T=>`
345
336
  Q: ${T.q}
346
337
  A: ${T.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",b||"(none yet)","","## Output rules","- Output EXACTLY one markdown file: frontmatter (---) + body. No code fences, no preamble.","- Frontmatter fields in this exact order: title, type, related, tags, owner, access, created, last_updated, sources.",' - `title`: "\u2026"',` - \`type\`: ${l}`,' - `related`: ["Article Title", \u2026] (titles that exist in the catalog above; drop if none)'," - `tags`: 2-4 specific tags, lowercase-kebab \u2014 no dates unless type=event",` - \`owner\`: ${e.agent}`," - `access`: public (unless the content is sensitive)",` - \`created\`: ${new Date().toISOString().slice(0,10)}`,` - \`last_updated\`: ${new Date().toISOString().slice(0,10)}`,` - \`sources\`: ["interview-${new Date().toISOString().slice(0,10)}"]`,"- Body: 20-80 lines, Wikipedia-style, organized by theme (not by question), synthesized (not verbatim Q&A).","- Use [[Title]] inline every time you reference something that has an article in the catalog.","- Do NOT invent facts. If the transcript didn't cover something, skip that sub-topic."].join(`
347
- `),A=q(a.baseDir,"_tmp");ro(A,{recursive:!0});let x=q(A,`interview-${t().slice(0,8)}.txt`);Uo(x,v),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let E="";try{let T=`cat '${x}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,me=Mo(T,{env:Jo({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Be=JSON.parse(me);E=String(Be.result||Be.content||"")}catch{E=me}}catch(T){console.log(m.red(` synthesis failed: ${T.message?.slice(0,200)}`)),c?.close();return}E=E.trim();let k=E.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);k&&(E=k[1].trim());let R=E.indexOf("---");R>0&&(E=E.slice(R));let j=E.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(E.slice(0,600)),c?.close();return}let C={};for(let T of j[1].split(`
348
- `)){let me=T.match(/^(\w+):\s*(.+)$/);me&&(C[me[1]]=me[2].trim().replace(/^"(.*)"$/,"$1"))}let D=j[2],W=C.title||g,P=W.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),ae=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[l]||l+"s"}/${P}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${ae}`)),console.log(),console.log(E),console.log();let B=await d(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),B==="scrap"||B==="/abort"){console.log(m.dim(" Discarded."));return}if(!e.commit){console.log(m.dim(" --no-commit: not writing.")),console.log(m.dim(` Draft kept at ${x} (prompt only; no article file)`));return}let ke=D,he={title:W,type:C.type||l,related:C.related?C.related.replace(/^\[|\]$/g,"").split(",").map(T=>T.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:C.tags?C.tags.replace(/^\[|\]$/g,"").split(",").map(T=>T.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:C.access||"public",created:C.created||new Date().toISOString().slice(0,10),lastUpdated:C.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(B==="edit"){let T=process.env.EDITOR||"vi",me=q(A,`draft-${t().slice(0,8)}.md`);Uo(me,E);try{Mo(`${T} '${me}'`,{stdio:"inherit"});let Vn=Ht(me,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(Vn){let co={};for(let wt of Vn[1].split(`
349
- `)){let Xn=wt.match(/^(\w+):\s*(.+)$/);Xn&&(co[Xn[1]]=Xn[2].trim().replace(/^"(.*)"$/,"$1"))}ke=Vn[2],he={...he,title:co.title||he.title,type:co.type||he.type,access:co.access||he.access,related:co.related?co.related.replace(/^\[|\]$/g,"").split(",").map(wt=>wt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):he.related,tags:co.tags?co.tags.replace(/^\[|\]$/g,"").split(",").map(wt=>wt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):he.tags}}}catch(Be){console.log(m.red(` editor failed: ${Be.message}`));return}}if(!a.writeArticle(ae,he,ke,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${ae} saved.`));let Fe=a.extractWikilinks(ke),ye=new Map;for(let T of a.listArticles(e.agent))ye.set(T.meta.title.toLowerCase(),!0);let Ao=Fe.filter(T=>!ye.has(T.toLowerCase()));if(Ao.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let T of Ao.slice(0,8))console.log(m.dim(` - ${T}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});ee.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{agenticQuery:n}=await import("./query-XLJ6I34S.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=$e(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=Ht(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(v=>v.trim());if(y.length<2)continue;let $=y[0].replace(/^Q:\s*/i,"").trim(),b=y.slice(1).join(" ").trim();$&&b&&r.push({q:$,verdict:b})}}let a=r?null:o.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",d=Math.min(parseInt(e.rounds)||20,r?.length??999),g=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${d} \xB7 ${g?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let l=[],u=0;for(let f=0;f<d;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(ae=>`${ae.title} [${ae.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
350
- `)),console.log(m.dim(" citations: "+H))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let $={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)")),l.push($);continue}let v=b[1].toLowerCase(),A=(b[2]||"").trim();if(l.push($),v==="/ok"||v==="/skip")continue;if(!A){console.log(m.yellow(` ${v} without note \u2014 skipping.`));continue}let x=y.citations[0];if(!x){console.log(m.yellow(" no cited article to patch."));continue}let E=i.readArticle(x.path);if(!E){console.log(m.red(` can't read ${x.path} to patch.`));continue}console.log(m.dim(` patching ${x.title} (${x.path})...`));let k=Jm(E.content,v,A,E.meta.title,E.meta.type),R=q(i.baseDir,"_tmp");ro(R,{recursive:!0});let j=q(R,`quiz-patch-${t().slice(0,8)}.txt`);Uo(j,k);let C="";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"`,ae=Mo(H,{env:Jo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let ke=JSON.parse(ae);C=String(ke.result||ke.content||"")}catch{C=ae}let B=C.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);B&&(C=B[1].trim()),C=C.trim()}catch(H){console.log(m.red(` patch failed: ${H.message?.slice(0,120)}`));continue}if(!C||C.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let D=E.content.split(`
351
- `).length,W=C.split(`
352
- `).length;if(console.log(m.dim(` diff: ${D} \u2192 ${W} lines (${W-D>=0?"+":""}${W-D})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),$.patched=x.path+" (dry)";continue}if(!i.writeArticle(x.path,{...E.meta,lastUpdated:new Date().toISOString().slice(0,10)},C,e.agent)){console.log(m.red(" write failed (permission?)"));continue}u++,$.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: ${l.length} rounds, ${u} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${l.length} rounds \xB7 ${u} patches_`,""];for(let p=0;p<l.length;p++){let w=l[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}\``:""),"")}Uo(e.out,f.join(`
353
- `)),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=$e(t.dir),s;try{s=n.getAgentWiki(e)}catch(d){console.log(m.red(` can't open wiki for agent "${e}": ${d.message}`));return}let i=dc(s,o,e);if(!i){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`)),console.log(m.dim(` Tip: ${m.green("agentx wiki status")} lists agents; ${m.green(`agentx wiki search "term" --agent ${e}`)} finds by content.`));return}let r=q(s.baseDir,i),a=t.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${i} in ${a}...`));try{Mo(`${a} '${r}'`,{stdio:"inherit"})}catch(d){console.log(m.red(` editor exited with error: ${d.message?.slice(0,150)}`));return}let c=s.readArticle(i);if(c){let d=new Set,g=s.extractWikilinks(c.content).filter(f=>d.has(f)?!1:(d.add(f),!0)),l=c.meta.related||[];(g.some(f=>!l.includes(f))||l.some(f=>!g.includes(f)))&&(s.writeArticle(i,{...c.meta,related:g.length?g:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.content,e),console.log(m.dim(` (synced frontmatter.related from body: ${g.length} wikilink${g.length===1?"":"s"})`)))}try{s.rebuildIndex(),console.log(m.green(` \u2713 ${i} saved. Catalog rebuilt.`))}catch(d){console.log(m.yellow(` saved, but catalog rebuild failed: ${d.message?.slice(0,100)}`))}});ee.command("patch <agent> <titleOrPath> <instruction>").description("LLM-patch an article from a free-form instruction; shows diff + confirms before writing").option("--dir <path>","wiki directory").option("--patch-model <m>","patch model","sonnet").option("--yes","skip confirmation and write immediately").option("--no-commit","show the patched body but don't write").action(async(e,o,t,n)=>{let s=await import("node:readline/promises"),{randomUUID:i}=await import("node:crypto"),r=$e(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=dc(a,o,e);if(!c){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`));return}let d=a.readArticle(c);if(!d){console.log(m.red(` can't read ${c}.`));return}let g=Bm(d.content,d.meta.title,d.meta.type,t),l=q(a.baseDir,"_tmp");ro(l,{recursive:!0});let u=q(l,`patch-${i().slice(0,8)}.txt`);Uo(u,g),console.log(),console.log(m.dim(` Target: ${d.meta.title} (${c})`)),console.log(m.dim(` Patching with ${n.patchModel}...`));let f="";try{let x=`cat '${u}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,E=Mo(x,{env:Jo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let R=JSON.parse(E);f=String(R.result||R.content||"")}catch{f=E}let k=f.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);k&&(f=k[1].trim()),f=f.trim()}catch(x){console.log(m.red(` patch failed: ${x.message?.slice(0,150)}`));return}if(!f||f.length<20){console.log(m.yellow(" patch returned nothing usable."));return}let p=d.content.split(`
338
+ `),A=q(a.baseDir,"_tmp");ao(A,{recursive:!0});let x=q(A,`interview-${t().slice(0,8)}.txt`);Fo(x,v),console.log(),console.log(g.dim(` Synthesizing draft with ${e.model}...`));let E="";try{let T=`cat '${x}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,me=Uo(T,{env:Ho({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Be=JSON.parse(me);E=String(Be.result||Be.content||"")}catch{E=me}}catch(T){console.log(g.red(` synthesis failed: ${T.message?.slice(0,200)}`)),c?.close();return}E=E.trim();let k=E.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);k&&(E=k[1].trim());let N=E.indexOf("---");N>0&&(E=E.slice(N));let C=E.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!C){console.log(g.red(" LLM output is not a valid frontmatter+body article:")),console.log(E.slice(0,600)),c?.close();return}let j={};for(let T of C[1].split(`
339
+ `)){let me=T.match(/^(\w+):\s*(.+)$/);me&&(j[me[1]]=me[2].trim().replace(/^"(.*)"$/,"$1"))}let P=C[2],W=j.title||m,L=W.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),ae=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[l]||l+"s"}/${L}.md`;console.log(),console.log(g.bold(" === Draft preview ===")),console.log(g.dim(` Path: ${ae}`)),console.log(),console.log(E),console.log();let B=await d(` ${g.green("save")} / ${g.yellow("edit (opens $EDITOR)")} / ${g.red("scrap")} ? `);if(c?.close(),B==="scrap"||B==="/abort"){console.log(g.dim(" Discarded."));return}if(!e.commit){console.log(g.dim(" --no-commit: not writing.")),console.log(g.dim(` Draft kept at ${x} (prompt only; no article file)`));return}let ve=P,he={title:W,type:j.type||l,related:j.related?j.related.replace(/^\[|\]$/g,"").split(",").map(T=>T.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:j.tags?j.tags.replace(/^\[|\]$/g,"").split(",").map(T=>T.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:j.access||"public",created:j.created||new Date().toISOString().slice(0,10),lastUpdated:j.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(B==="edit"){let T=process.env.EDITOR||"vi",me=q(A,`draft-${t().slice(0,8)}.md`);Fo(me,E);try{Uo(`${T} '${me}'`,{stdio:"inherit"});let Zn=Ht(me,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(Zn){let lo={};for(let bt of Zn[1].split(`
340
+ `)){let es=bt.match(/^(\w+):\s*(.+)$/);es&&(lo[es[1]]=es[2].trim().replace(/^"(.*)"$/,"$1"))}ve=Zn[2],he={...he,title:lo.title||he.title,type:lo.type||he.type,access:lo.access||he.access,related:lo.related?lo.related.replace(/^\[|\]$/g,"").split(",").map(bt=>bt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):he.related,tags:lo.tags?lo.tags.replace(/^\[|\]$/g,"").split(",").map(bt=>bt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):he.tags}}}catch(Be){console.log(g.red(` editor failed: ${Be.message}`));return}}if(!a.writeArticle(ae,he,ve,e.agent)){console.log(g.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(g.green(` \u2713 ${ae} saved.`));let Fe=a.extractWikilinks(ve),ye=new Map;for(let T of a.listArticles(e.agent))ye.set(T.meta.title.toLowerCase(),!0);let Oo=Fe.filter(T=>!ye.has(T.toLowerCase()));if(Oo.length){console.log(),console.log(g.bold(" Gaps referenced but not yet covered:"));for(let T of Oo.slice(0,8))console.log(g.dim(` - ${T}`));console.log(g.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-EDW72Q4O.js");if(!e.agent){console.log(g.red(" --agent <id> is required."));return}let s=ke(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(f){console.log(g.red(` can't open wiki for agent "${e.agent}": ${f.message}`));return}let r=null;if(e.script){let p=Ht(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(v=>v.trim());if(y.length<2)continue;let $=y[0].replace(/^Q:\s*/i,"").trim(),b=y.slice(1).join(" ").trim();$&&b&&r.push({q:$,verdict:b})}}let a=r?null:o.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",d=Math.min(parseInt(e.rounds)||20,r?.length??999),m=e.commit!==!1;console.log(),console.log(g.bold(" Wiki Quiz")),console.log(g.dim(` Agent: ${e.agent} \xB7 Rounds: ${d} \xB7 ${m?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(g.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let l=[],u=0;for(let f=0;f<d;f++){let p,w;if(r){let H=r[f];if(!H)break;p=H.q,w=H.verdict,console.log(g.cyan(` [${f+1}] Q: `)+p)}else{if(p=await c(g.cyan(` [${f+1}] Q: `)),!p||p==="/done"||p==="/abort")break;w=""}process.stdout.write(g.dim(" querying... "));let y;try{y=await n(p,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(H){console.log(g.red(`failed: ${H.message?.slice(0,120)}`));continue}if(console.log(g.dim("done")),y.status!=="ok")console.log(g.yellow(` (status: ${y.status}${y.error?" \u2014 "+y.error:""})`));else{let H=y.citations.map(ae=>`${ae.title} [${ae.type||"?"}]`).join(" \xB7 ");console.log(),console.log(g.dim(" A: ")+y.answer.replace(/\n/g,`
341
+ `)),console.log(g.dim(" citations: "+H))}r||(w=await c(g.cyan(" verdict > "))),console.log(g.dim(" verdict: ")+w);let $={q:p,answer:y.answer,citations:y.citations,verdict:w},b=w.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!b){console.log(g.yellow(" (verdict not recognised \u2014 treating as /skip)")),l.push($);continue}let v=b[1].toLowerCase(),A=(b[2]||"").trim();if(l.push($),v==="/ok"||v==="/skip")continue;if(!A){console.log(g.yellow(` ${v} without note \u2014 skipping.`));continue}let x=y.citations[0];if(!x){console.log(g.yellow(" no cited article to patch."));continue}let E=i.readArticle(x.path);if(!E){console.log(g.red(` can't read ${x.path} to patch.`));continue}console.log(g.dim(` patching ${x.title} (${x.path})...`));let k=Hm(E.content,v,A,E.meta.title,E.meta.type),N=q(i.baseDir,"_tmp");ao(N,{recursive:!0});let C=q(N,`quiz-patch-${t().slice(0,8)}.txt`);Fo(C,k);let j="";try{let H=`cat '${C}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,ae=Uo(H,{env:Ho({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let ve=JSON.parse(ae);j=String(ve.result||ve.content||"")}catch{j=ae}let B=j.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);B&&(j=B[1].trim()),j=j.trim()}catch(H){console.log(g.red(` patch failed: ${H.message?.slice(0,120)}`));continue}if(!j||j.length<20){console.log(g.yellow(" patch returned nothing usable."));continue}let P=E.content.split(`
342
+ `).length,W=j.split(`
343
+ `).length;if(console.log(g.dim(` diff: ${P} \u2192 ${W} lines (${W-P>=0?"+":""}${W-P})`)),!m){console.log(g.dim(" (--no-commit: patch not written)")),$.patched=x.path+" (dry)";continue}if(!i.writeArticle(x.path,{...E.meta,lastUpdated:new Date().toISOString().slice(0,10)},j,e.agent)){console.log(g.red(" write failed (permission?)"));continue}u++,$.patched=x.path,console.log(g.green(` \u2713 patched ${x.path}`))}if(a&&a.close(),u>0&&m&&i.rebuildIndex(),console.log(),console.log(g.bold(` Session done: ${l.length} rounds, ${u} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${l.length} rounds \xB7 ${u} patches_`,""];for(let p=0;p<l.length;p++){let w=l[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}\``:""),"")}Fo(e.out,f.join(`
344
+ `)),console.log(g.dim(` Transcript written to ${e.out}`))}});ee.command("edit <agent> <titleOrPath>").description("open an article in $EDITOR (resolves by title or path), rebuild catalog on exit").option("--dir <path>","wiki directory").option("--editor <cmd>","override $EDITOR for this run").action((e,o,t)=>{let n=ke(t.dir),s;try{s=n.getAgentWiki(e)}catch(d){console.log(g.red(` can't open wiki for agent "${e}": ${d.message}`));return}let i=uc(s,o,e);if(!i){console.log(g.yellow(` no article matches "${o}" in ${e}'s wiki.`)),console.log(g.dim(` Tip: ${g.green("agentx wiki status")} lists agents; ${g.green(`agentx wiki search "term" --agent ${e}`)} finds by content.`));return}let r=q(s.baseDir,i),a=t.editor||process.env.EDITOR||"vi";console.log(g.dim(` opening ${i} in ${a}...`));try{Uo(`${a} '${r}'`,{stdio:"inherit"})}catch(d){console.log(g.red(` editor exited with error: ${d.message?.slice(0,150)}`));return}let c=s.readArticle(i);if(c){let d=new Set,m=s.extractWikilinks(c.content).filter(f=>d.has(f)?!1:(d.add(f),!0)),l=c.meta.related||[];(m.some(f=>!l.includes(f))||l.some(f=>!m.includes(f)))&&(s.writeArticle(i,{...c.meta,related:m.length?m:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.content,e),console.log(g.dim(` (synced frontmatter.related from body: ${m.length} wikilink${m.length===1?"":"s"})`)))}try{s.rebuildIndex(),console.log(g.green(` \u2713 ${i} saved. Catalog rebuilt.`))}catch(d){console.log(g.yellow(` saved, but catalog rebuild failed: ${d.message?.slice(0,100)}`))}});ee.command("patch <agent> <titleOrPath> <instruction>").description("LLM-patch an article from a free-form instruction; shows diff + confirms before writing").option("--dir <path>","wiki directory").option("--patch-model <m>","patch model","sonnet").option("--yes","skip confirmation and write immediately").option("--no-commit","show the patched body but don't write").action(async(e,o,t,n)=>{let s=await import("node:readline/promises"),{randomUUID:i}=await import("node:crypto"),r=ke(n.dir),a;try{a=r.getAgentWiki(e)}catch(x){console.log(g.red(` can't open wiki for agent "${e}": ${x.message}`));return}let c=uc(a,o,e);if(!c){console.log(g.yellow(` no article matches "${o}" in ${e}'s wiki.`));return}let d=a.readArticle(c);if(!d){console.log(g.red(` can't read ${c}.`));return}let m=Jm(d.content,d.meta.title,d.meta.type,t),l=q(a.baseDir,"_tmp");ao(l,{recursive:!0});let u=q(l,`patch-${i().slice(0,8)}.txt`);Fo(u,m),console.log(),console.log(g.dim(` Target: ${d.meta.title} (${c})`)),console.log(g.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"`,E=Uo(x,{env:Ho({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let N=JSON.parse(E);f=String(N.result||N.content||"")}catch{f=E}let k=f.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);k&&(f=k[1].trim()),f=f.trim()}catch(x){console.log(g.red(` patch failed: ${x.message?.slice(0,150)}`));return}if(!f||f.length<20){console.log(g.yellow(" patch returned nothing usable."));return}let p=d.content.split(`
354
345
  `).length,w=f.split(`
355
- `).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}),E=(await x.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();x.close(),y=E==="y"||E==="yes"}if(!y){console.log(m.dim(" aborted."));return}let $=new Set,b=a.extractWikilinks(f).filter(x=>$.has(x)?!1:($.add(x),!0));if(!a.writeArticle(c,{...d.meta,related:b.length?b:void 0,lastUpdated:new Date().toISOString().slice(0,10)},f,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex();let A=(d.meta.related||[]).filter(x=>!b.includes(x));A.length&&console.log(m.dim(` (pruned stale related: ${A.slice(0,3).join(", ")}${A.length>3?", \u2026":""})`)),console.log(m.green(` \u2713 ${c} patched.`))});function dc(e,o,t){let n=o.trim(),s=e.listArticles(t),i=n.toLowerCase(),r=s.find(d=>d.meta.title.toLowerCase()===i);if(r)return r.path;if(n.includes("/")||n.endsWith(".md")){let d=n.endsWith(".md")?n:`${n}.md`,g=s.find(l=>l.path===d||l.path===n);if(g)return g.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(d=>{let g=d.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return g===a||g.includes(a)||d.path.toLowerCase().includes(a)});return c?c.path:null}function Bm(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(`
356
- `)}function Jm(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
346
+ `).length;if(console.log(),console.log(g.bold(" === Patched preview ===")),console.log(g.dim(` diff: ${p} \u2192 ${w} lines (${w-p>=0?"+":""}${w-p})`)),console.log(),console.log(f),console.log(),!n.commit){console.log(g.dim(" --no-commit: preview only, not written."));return}let y=!!n.yes;if(!y){let x=s.createInterface({input:process.stdin,output:process.stdout}),E=(await x.question(g.cyan(" apply? [y/N] "))).trim().toLowerCase();x.close(),y=E==="y"||E==="yes"}if(!y){console.log(g.dim(" aborted."));return}let $=new Set,b=a.extractWikilinks(f).filter(x=>$.has(x)?!1:($.add(x),!0));if(!a.writeArticle(c,{...d.meta,related:b.length?b:void 0,lastUpdated:new Date().toISOString().slice(0,10)},f,e)){console.log(g.red(" write failed (permission?)"));return}a.rebuildIndex();let A=(d.meta.related||[]).filter(x=>!b.includes(x));A.length&&console.log(g.dim(` (pruned stale related: ${A.slice(0,3).join(", ")}${A.length>3?", \u2026":""})`)),console.log(g.green(` \u2713 ${c} patched.`))});function uc(e,o,t){let n=o.trim(),s=e.listArticles(t),i=n.toLowerCase(),r=s.find(d=>d.meta.title.toLowerCase()===i);if(r)return r.path;if(n.includes("/")||n.endsWith(".md")){let d=n.endsWith(".md")?n:`${n}.md`,m=s.find(l=>l.path===d||l.path===n);if(m)return m.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(d=>{let m=d.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return m===a||m.includes(a)||d.path.toLowerCase().includes(a)});return c?c.path:null}function Jm(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(`
347
+ `)}function Hm(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
357
348
 
358
349
  ${t}
359
350
 
@@ -366,8 +357,8 @@ Incorporate it into the most relevant existing section, or create a short new se
366
357
  ${t}
367
358
 
368
359
  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(`
369
- `)}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=$e(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=!!e.commit,s=e.dir?q(e.dir):q(process.cwd(),".agentx/wiki"),i="graph",r=["flat","unified"];console.log(),console.log(m.bold(n?" Pruning (commit)":" Pruning (dry-run)")),console.log(m.dim(` Canonical: ${i}/ \xB7 Legacy to collapse: ${r.join("/, ")}/`));let a=0,c=0,d=0,g=0;for(let l of t){let u=q(s,"agents",l);if(!We(u))continue;let f=q(u,i),p=r.map(b=>({mode:b,dir:q(u,b)})).filter(b=>We(b.dir));if(p.length===0)continue;let w=new Map;Gs(f,b=>{let v=rc(f,b);if(v.startsWith("_")||v.startsWith("raw/")||v.includes("_tmp/"))return;let A=cc(Ht(b,"utf-8"));A?.meta.title&&w.set(A.meta.title.trim().toLowerCase(),{relPath:v,type:A.meta.type,lastUpdated:A.meta.lastUpdated||""})});let y=[];for(let b of p)Gs(b.dir,v=>{let A=rc(b.dir,v);if(A.startsWith("_")||A.startsWith("raw/")||A.includes("_tmp/"))return;let x=cc(Ht(v,"utf-8"));x?.meta.title&&y.push({mode:b.mode,relPath:A,absPath:v,title:x.meta.title.trim(),type:x.meta.type,lastUpdated:x.meta.lastUpdated||""})});if(a+=y.length,y.length===0)continue;console.log();let $=p.map(b=>b.mode).join("+");console.log(m.bold(` ${m.cyan(l)}: ${y.length} legacy article(s) across ${$}`));for(let b of y){let v=b.title.toLowerCase(),A=w.get(v),x;A?!A.type&&b.type||!!A.type==!!b.type&&b.lastUpdated&&A.lastUpdated&&b.lastUpdated>A.lastUpdated?x="upgrade":x="archive":x="promote";let E=b.type?m.magenta(`[${b.type}]`):m.yellow("[untyped]"),k=x==="promote"?m.green("\u2192 promote "):x==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),R=b.relPath.length>46?b.relPath.slice(0,43)+"...":b.relPath.padEnd(46);if(console.log(` ${k} ${E} ${m.dim(b.mode+"/")}${R}`),x==="upgrade"&&console.log(m.dim(` (replaces ${A.relPath}, old version kept under _versions/)`)),!n){x==="promote"?c++:x==="upgrade"?d++:g++;continue}try{if(x==="promote"){let j=q(f,b.relPath);We(j)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${b.relPath}`)),lc(u,b),g++):(ro(ac(j),{recursive:!0}),_n(b.absPath,j),w.set(v,{relPath:b.relPath,type:b.type,lastUpdated:b.lastUpdated}),c++)}else if(x==="upgrade"){let j=q(f,A.relPath);if(We(j)){let C=q(u,"_versions",A.relPath.replace(/\.md$/,""));ro(C,{recursive:!0});let D=new Date().toISOString().replace(/[:.]/g,"-");_n(j,q(C,`${D}.md`))}ro(ac(j),{recursive:!0}),_n(b.absPath,j),w.set(v,{relPath:A.relPath,type:b.type,lastUpdated:b.lastUpdated}),d++}else lc(u,b),g++}catch(j){console.log(m.red(` ! ${x} failed: ${j.message?.slice(0,120)}`))}}if(n){for(let b of p)try{qm(b.dir,{recursive:!0,force:!0})}catch{}try{o.getAgentWiki(l).rebuildIndex()}catch(b){console.log(m.dim(` (catalog rebuild skipped: ${b.message?.slice(0,80)})`))}}}console.log(),console.log(m.dim(` Legacy scanned: ${a}`)),n?(console.log(m.green(` Promoted: ${c} \xB7 Upgraded canonical: ${d} \xB7 Archived: ${g}`)),console.log(m.dim(" Archived losers preserved under <agent>/_versions/. Legacy mode dirs deleted."))):(console.log(m.dim(` Would: promote ${c} \xB7 upgrade ${d} \xB7 archive ${g}`)),console.log(m.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function Gs(e,o){if(We(e))for(let t of Fm(e,{withFileTypes:!0})){let n=q(e,t.name);t.isDirectory()?Gs(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function cc(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
370
- `)){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 lc(e,o){let t=q(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));ro(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");_n(o.absPath,q(t,`${n}.md`))}ee.command("migrate").description("backfill type + related on legacy articles (one-shot)").option("--dir <path>","wiki directory").option("--agent <id>","migrate only this agent's articles").option("--commit","write changes (default: dry-run, reports what would change)").option("--batch <n>","articles per LLM call","10").option("--max <n>","cap articles this run (for spot-checks)").option("--model <m>","classifier model","sonnet").action(async e=>{let o=$e(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=Math.max(1,parseInt(e.batch)||10),s=e.max?parseInt(e.max):1/0,i=!!e.commit;console.log(),console.log(m.bold(i?" Migrating (commit)":" Migrating (dry-run)")),console.log(m.dim(` Batch size: ${n} \xB7 Model: ${e.model}`)),console.log();let r=0,a=0,c=0;for(let d of t){let g=o.getAgentWiki(d),l=g.listArticles(d),u=l.filter($=>!$.meta.type);if(r+=l.length,a+=u.length,u.length===0){console.log(` ${m.cyan(d)}: ${m.green("all typed")} (${l.length} articles)`);continue}let f=Math.max(0,s-c),p=Math.min(u.length,f);if(p===0){console.log(m.dim(` ${d}: skipped (--max reached)`));continue}console.log(),console.log(m.bold(` ${m.cyan(d)}: ${p}/${u.length} untyped articles`));let w=g.baseDir,y=q(w,"_tmp");ro(y,{recursive:!0});for(let $=0;$<p;$+=n){let b=u.slice($,Math.min($+n,p)),v=Gm(b),A=q(y,"migrate-prompt.txt");Uo(A,v);let x;try{let E=`cat '${A}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,k=Mo(E,{env:Jo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),R=JSON.parse(k),C=String(R.result||R.content||"").match(/\[[\s\S]*\]/);if(!C)throw new Error("no JSON array in classifier response");x=JSON.parse(C[0])}catch(E){console.log(m.red(` LLM classify failed: ${E.message?.slice(0,150)}`));continue}for(let E of b){let k=x.find(P=>P.path===E.path),R=Hm(k?.type);if(!k||!R){console.log(m.yellow(` ? ${E.path}: unclassified${k?` (got "${k.type}")`:""}`));continue}let j=g.extractWikilinks(E.content),C={...E.meta,type:R.type,related:j.length?j:void 0,lastUpdated:new Date().toISOString().slice(0,10)},D=j.length?m.dim(` \u2192 ${j.slice(0,3).join(", ")}${j.length>3?", \u2026":""}`):"",W=R.alias?m.dim(` (from "${R.alias}")`):"";console.log(` ${m.green("+")} ${m.magenta("["+R.type+"]")}${W} ${E.path}${D}`),i&&(g.writeArticle(E.path,C,E.content,d),c++)}}i&&g.rebuildIndex()}console.log(),console.log(m.dim(` Scanned ${r} articles; ${a} needed migration`)),console.log(i?m.green(` Applied ${c} patches.`):m.dim(" Dry-run \u2014 add --commit to write changes.")),console.log()});function Hm(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 Gm(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}"
360
+ `)}ee.command("prune").description("collapse legacy flat/unified mode dirs into graph/ (dedup by title; losers archived)").option("--dir <path>","wiki directory").option("--agent <id>","prune only this agent's wiki").option("--commit","execute moves + archives (default: dry-run)").action(async e=>{let o=ke(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=!!e.commit,s=e.dir?q(e.dir):q(process.cwd(),".agentx/wiki"),i="graph",r=["flat","unified"];console.log(),console.log(g.bold(n?" Pruning (commit)":" Pruning (dry-run)")),console.log(g.dim(` Canonical: ${i}/ \xB7 Legacy to collapse: ${r.join("/, ")}/`));let a=0,c=0,d=0,m=0;for(let l of t){let u=q(s,"agents",l);if(!We(u))continue;let f=q(u,i),p=r.map(b=>({mode:b,dir:q(u,b)})).filter(b=>We(b.dir));if(p.length===0)continue;let w=new Map;Ks(f,b=>{let v=dc(f,b);if(v.startsWith("_")||v.startsWith("raw/")||v.includes("_tmp/"))return;let A=mc(Ht(b,"utf-8"));A?.meta.title&&w.set(A.meta.title.trim().toLowerCase(),{relPath:v,type:A.meta.type,lastUpdated:A.meta.lastUpdated||""})});let y=[];for(let b of p)Ks(b.dir,v=>{let A=dc(b.dir,v);if(A.startsWith("_")||A.startsWith("raw/")||A.includes("_tmp/"))return;let x=mc(Ht(v,"utf-8"));x?.meta.title&&y.push({mode:b.mode,relPath:A,absPath:v,title:x.meta.title.trim(),type:x.meta.type,lastUpdated:x.meta.lastUpdated||""})});if(a+=y.length,y.length===0)continue;console.log();let $=p.map(b=>b.mode).join("+");console.log(g.bold(` ${g.cyan(l)}: ${y.length} legacy article(s) across ${$}`));for(let b of y){let v=b.title.toLowerCase(),A=w.get(v),x;A?!A.type&&b.type||!!A.type==!!b.type&&b.lastUpdated&&A.lastUpdated&&b.lastUpdated>A.lastUpdated?x="upgrade":x="archive":x="promote";let E=b.type?g.magenta(`[${b.type}]`):g.yellow("[untyped]"),k=x==="promote"?g.green("\u2192 promote "):x==="upgrade"?g.cyan("\u27F3 upgrade "):g.dim("\u2717 archive "),N=b.relPath.length>46?b.relPath.slice(0,43)+"...":b.relPath.padEnd(46);if(console.log(` ${k} ${E} ${g.dim(b.mode+"/")}${N}`),x==="upgrade"&&console.log(g.dim(` (replaces ${A.relPath}, old version kept under _versions/)`)),!n){x==="promote"?c++:x==="upgrade"?d++:m++;continue}try{if(x==="promote"){let C=q(f,b.relPath);We(C)?(console.log(g.yellow(` ! target path already exists, archiving instead: ${b.relPath}`)),pc(u,b),m++):(ao(gc(C),{recursive:!0}),Ln(b.absPath,C),w.set(v,{relPath:b.relPath,type:b.type,lastUpdated:b.lastUpdated}),c++)}else if(x==="upgrade"){let C=q(f,A.relPath);if(We(C)){let j=q(u,"_versions",A.relPath.replace(/\.md$/,""));ao(j,{recursive:!0});let P=new Date().toISOString().replace(/[:.]/g,"-");Ln(C,q(j,`${P}.md`))}ao(gc(C),{recursive:!0}),Ln(b.absPath,C),w.set(v,{relPath:A.relPath,type:b.type,lastUpdated:b.lastUpdated}),d++}else pc(u,b),m++}catch(C){console.log(g.red(` ! ${x} failed: ${C.message?.slice(0,120)}`))}}if(n){for(let b of p)try{Wm(b.dir,{recursive:!0,force:!0})}catch{}try{o.getAgentWiki(l).rebuildIndex()}catch(b){console.log(g.dim(` (catalog rebuild skipped: ${b.message?.slice(0,80)})`))}}}console.log(),console.log(g.dim(` Legacy scanned: ${a}`)),n?(console.log(g.green(` Promoted: ${c} \xB7 Upgraded canonical: ${d} \xB7 Archived: ${m}`)),console.log(g.dim(" Archived losers preserved under <agent>/_versions/. Legacy mode dirs deleted."))):(console.log(g.dim(` Would: promote ${c} \xB7 upgrade ${d} \xB7 archive ${m}`)),console.log(g.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function Ks(e,o){if(We(e))for(let t of qm(e,{withFileTypes:!0})){let n=q(e,t.name);t.isDirectory()?Ks(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function mc(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
361
+ `)){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 pc(e,o){let t=q(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));ao(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");Ln(o.absPath,q(t,`${n}.md`))}ee.command("migrate").description("backfill type + related on legacy articles (one-shot)").option("--dir <path>","wiki directory").option("--agent <id>","migrate only this agent's articles").option("--commit","write changes (default: dry-run, reports what would change)").option("--batch <n>","articles per LLM call","10").option("--max <n>","cap articles this run (for spot-checks)").option("--model <m>","classifier model","sonnet").action(async e=>{let o=ke(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=Math.max(1,parseInt(e.batch)||10),s=e.max?parseInt(e.max):1/0,i=!!e.commit;console.log(),console.log(g.bold(i?" Migrating (commit)":" Migrating (dry-run)")),console.log(g.dim(` Batch size: ${n} \xB7 Model: ${e.model}`)),console.log();let r=0,a=0,c=0;for(let d of t){let m=o.getAgentWiki(d),l=m.listArticles(d),u=l.filter($=>!$.meta.type);if(r+=l.length,a+=u.length,u.length===0){console.log(` ${g.cyan(d)}: ${g.green("all typed")} (${l.length} articles)`);continue}let f=Math.max(0,s-c),p=Math.min(u.length,f);if(p===0){console.log(g.dim(` ${d}: skipped (--max reached)`));continue}console.log(),console.log(g.bold(` ${g.cyan(d)}: ${p}/${u.length} untyped articles`));let w=m.baseDir,y=q(w,"_tmp");ao(y,{recursive:!0});for(let $=0;$<p;$+=n){let b=u.slice($,Math.min($+n,p)),v=zm(b),A=q(y,"migrate-prompt.txt");Fo(A,v);let x;try{let E=`cat '${A}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,k=Uo(E,{env:Ho({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),N=JSON.parse(k),j=String(N.result||N.content||"").match(/\[[\s\S]*\]/);if(!j)throw new Error("no JSON array in classifier response");x=JSON.parse(j[0])}catch(E){console.log(g.red(` LLM classify failed: ${E.message?.slice(0,150)}`));continue}for(let E of b){let k=x.find(L=>L.path===E.path),N=Gm(k?.type);if(!k||!N){console.log(g.yellow(` ? ${E.path}: unclassified${k?` (got "${k.type}")`:""}`));continue}let C=m.extractWikilinks(E.content),j={...E.meta,type:N.type,related:C.length?C:void 0,lastUpdated:new Date().toISOString().slice(0,10)},P=C.length?g.dim(` \u2192 ${C.slice(0,3).join(", ")}${C.length>3?", \u2026":""}`):"",W=N.alias?g.dim(` (from "${N.alias}")`):"";console.log(` ${g.green("+")} ${g.magenta("["+N.type+"]")}${W} ${E.path}${P}`),i&&(m.writeArticle(E.path,j,E.content,d),c++)}}i&&m.rebuildIndex()}console.log(),console.log(g.dim(` Scanned ${r} articles; ${a} needed migration`)),console.log(i?g.green(` Applied ${c} patches.`):g.dim(" Dry-run \u2014 add --commit to write changes.")),console.log()});function Gm(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 zm(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}"
371
362
  title: "${t.meta.title}"
372
363
  tags: [${i}]
373
364
  body: ${s}${t.content.length>400?"\u2026":""}`}).join(`
@@ -407,45 +398,45 @@ Output (JSON array, one entry per input article, same order):
407
398
  [
408
399
  {"path": "path/to/article.md", "type": "project"},
409
400
  ...
410
- ]`}ee.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=$e(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});ee.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let o=e.dir||q(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-NPLE42XY.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(),Er(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-UA2ROH3V.js"),c=$e(e.dir,e.mode),d=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),l=parseFloat(e.min),u=[];e:for(let y of d){let $=c.getAgentWiki(y);for(let b of $.listArticles(y)){if(u.length>=g)break e;let v=$.readArticle(b.path);if(!v||e.type&&v.meta.type!==e.type)continue;let A={...o(v.meta.type),...e.fields?i(v.meta.type):{}},x=await a(s,t({path:b.path,title:v.meta.title,type:v.meta.type,tags:v.meta.tags,body:v.content}),A,{links:[{kind:"article",id:b.path}],features:{agent:y,type:v.meta.type??"?"}});if(!x){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let E=n(x.answers),k=e.fields?r(v.meta.type,x.answers):null;E.completeness>=l&&!(k&&!k.fit)||u.push({agent:y,type:v.meta.type??"?",score:E.completeness.toFixed(2),standsAlone:E.standsAlone.toFixed(2),gap:E.biggestGap,...k?{missing:k.missingCritical.join(",")||"-",cov:`${Math.round(k.coverage*100)}%`}:{},title:v.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(" no articles below the threshold"));return}u.sort((y,$)=>parseFloat(y.score)-parseFloat($.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($=>String($[y]).length))),w=y=>y.map(($,b)=>String($).padEnd(p[b])).join(" ");console.log(),console.log(m.bold(w(f)));for(let y of u)console.log(w(f.map($=>y[$])));if(e.fields){let y=u.filter($=>$.missing!=="-").length;console.log(m.dim(`
411
- ${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(`
412
- ${u.length} article(s) below ${l}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});ee.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,o)=>{let{agenticQuery:t}=await import("./query-XLJ6I34S.js"),n=$e(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let d=n.getAgentWiki(c),g=q(d.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(m.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(m.dim(" Citations:"));for(let c of a.citations){let d=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${d} (${c.path})`))}console.log()}if(o.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(d=>!a.candidates.some(g=>g.path===d.path));console.log(m.dim(` followed: ${c.map(d=>`${d.title}@h${d.hop}`).join(" | ")}`))}console.log()}});ee.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,o)=>{let t=$e(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=$e(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=q(process.cwd(),".agentx/graph");if(!We(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new lo({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[l,u]of Object.entries(i.entries))r.set(l,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,d=0,g=0;for(let l of t){let u=o.getAgentWiki(l),f=u.listArticles(l),p=o.getSharedStore().listEntries(),w=new Map(p.map(v=>[v.id,v])),y=0,$=0,b=0;for(let v of f){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;y++,c++;let A=new Map;for(let E of v.meta.sources){let k=w.get(E);if(!k)continue;let R=String(k.meta?.sender??""),j=s.fingerprint({text:k.content,channel:k.source,sender:R}),C=r.get(j);if(!C?.length)continue;let D=C.join("/"),W=A.get(D);W?W.n++:A.set(D,{path:C,n:1})}if(A.size===0)continue;$++,d++;let x;for(let E of A.values())(!x||E.n>x.n)&&(x=E);x&&(e.dryRun||(u.writeArticle(v.path,{...v.meta,graphPath:x.path},v.content,l),b++,g++))}console.log(` ${m.cyan(l)}: ${m.bold(f.length)} articles \xB7 ${y} eligible \xB7 ${$} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${d} matched (${Math.round(d/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});ee.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let t=$e(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-NPLE42XY.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(m.red(" No --peer specified and no daemon config found")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(n.length===0){console.log(m.dim(" No mesh peers configured"));return}let s=new Set(t.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(m.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(m.red(` HTTP ${a.status}`));continue}let c=await a.json(),d=c.entries||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${d.length} entries`));let l=0;for(let u of d)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)),l++);l>0?console.log(m.green(` ${l} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=l;try{let 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||q(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let d=new Zn(o,void 0,c),l=d.getAgentWiki(t).rebuildIndex(),u=d.getAgentEntries(t),f=d.getUnabsorbedEntries(t),p=new Set,w=0,y=new Set;for(let b of l.articles){for(let v of b.tags||[])p.add(v);w+=b.tags?.length||0;for(let v of b.sources||[])y.add(v)}let $=new Set(l.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:zs(c),articles:l.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:l.articles.length>0?(w/l.articles.length).toFixed(1):"0",dirs:$.size,coverage:y.size,articleList:l.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,d]of r){let g=s.map(l=>d(l).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,d)=>{let g=Math.max(...s.map(u=>u[c])),l=s.filter(u=>u[c]===g).map(u=>u.label);g>0&&console.log(m.dim(` Best ${d}: ${l.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});ee.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,o)=>{let t=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");We(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?q(process.cwd(),e):q(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=q(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),d=c("tar",a,{stdio:"inherit"});d.status!==0&&(console.log(m.red(` tar exited with ${d.status}`)),process.exit(d.status||1));let{statSync:g}=await import("fs"),l=We(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${zm(l)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});ee.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-L4D2BOGY.js"),{askSeat:a}=await import("./seat-UA2ROH3V.js"),{QuestionStore:c}=await import("./questions-4B4KSPXG.js"),d=$e(e.dir,e.mode),g=[],l=e.agent?[e.agent]:d.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let E of l){let k=d.getAgentWiki(E);for(let R of k.listArticles(E)){if(f>=u)break e;let j=k.readArticle(R.path);if(!j||e.type&&j.meta.type!==e.type)continue;f++;let C=await a(r,n({title:j.meta.title,type:j.meta.type,body:j.content}),o(j.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:E,type:j.meta.type??"?"}});if(!C){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let D=t(j.meta.type,C.answers);for(let W of s(D,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&W.needsHuman||(e.ask&&W.needsHuman&&g.push({kind:"field",agentId:E,path:R.path,subject:j.meta.title,field:W.field,tier:W.tier,question:`${j.meta.title} (${j.meta.type??"?"}) \u2014 ${W.label}?`}),p.push({tier:W.tier,need:W.field,how:W.needsHuman?m.yellow("ask"):W.sources.join("/"),uncertain:W.uncertain?"?":"",agent:E,article:j.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&g.length>0&&(w=new c(Gt(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"],$=E=>String(E).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(E=>Math.max(E.length,...p.map(k=>$(k[E]).length))),v=(E,k)=>String(E)+" ".repeat(Math.max(0,b[k]-$(E).length));console.log(),console.log(m.bold(y.map((E,k)=>v(E,k)).join(" ")));for(let E of p)console.log(y.map((k,R)=>v(E[k],R)).join(" "));let A=p.filter(E=>E.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:E}=await import("./article-fields-L4D2BOGY.js"),k=E[e.notifyTier]??E.pillar,R=g.filter(j=>(E[j.tier??"furniture"]??9)<=k);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:j}=await import("./config-NPLE42XY.js"),C=j(),D=C?.notifications?.destination;if(!D?.channel||!D?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let W=R.slice(0,10).map(B=>`\u2022 ${B.question}`).join(`
413
- `),P=R.length>10?`
414
- \u2026and ${R.length-10} more`:"",H=`${R.length} wiki gap(s) need you (${e.notifyTier}+):
415
- ${W}${P}
416
-
417
- agentx wiki questions`,ae=C?.daemon?.port??C?.port??18800;try{let B=await fetch(`http://127.0.0.1:${ae}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:D.channel,chatId:D.chatId,accountId:D.accountId,text:H})});console.log(B.ok?m.cyan(` Pushed ${R.length} question(s) to ${D.channel}.`):m.yellow(` Push failed (${B.status}) \u2014 questions are still queued.`))}catch(B){console.log(m.yellow(` Push failed (${String(B?.message??B).slice(0,80)}) \u2014 questions are still queued.`))}}}}});ee.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-L4D2BOGY.js"),{askSeat:r}=await import("./seat-UA2ROH3V.js"),{resolveFacts:a,mergeRecords:c,installPrompts:d,defaultSources:g,recordsFromEntries:l}=await import("./facts-YVEJOM7O.js"),{backfillArticle:u}=await import("./backfill-MTD2B62I.js"),f=$e(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=g(),$=c(l(f.getSharedStore().listEntries())),b=new Map($.map(C=>[C.name.toLowerCase().trim(),C])),v=0,A=0,x=[],E=!1;e:for(let C of p){let D=f.getAgentWiki(C);for(let W of D.listArticles(C)){if(v>=w)break e;if(W.meta.type!=="person")continue;let P=D.readArticle(W.path);if(!P)continue;v++;let H=await r(s,n({title:P.meta.title,type:P.meta.type,body:P.content}),o(P.meta.type),{links:[{kind:"article",id:W.path}],features:{agent:C,op:"backfill"}});if(!H){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let B=t(P.meta.type,H.answers).missing.filter(T=>i.includes(T));if(B.length===0)continue;let{records:ke,results:he}=await a([{name:P.meta.title,type:"person"}],{sources:y}),_=b.get(P.meta.title.toLowerCase().trim());if(!E){for(let T of d(he,y))console.log(m.yellow(` ! ${T.source} ${T.kind} \u2014 would supply ${T.provides.join(", ")}`)),console.log(m.dim(` ${T.hint}`));E=!0}let Fe=c([..._?[{name:_.name,source:"entries",fields:Object.fromEntries(Object.entries(_.fields).map(([T,me])=>[T,me.value]))}]:[],...ke]);if(Fe.length===0)continue;let{content:ye,edits:Ao}=u(P.content,Fe[0],B);if(Ao.length!==0){for(let T of Ao)x.push({agent:C,article:P.meta.title.slice(0,32),field:T.field,action:T.replaced?"replace":"add",got:`${T.value.split(";").length} value(s)`});e.apply&&(D.writeArticle(W.path,P.meta,ye,C)?A++:console.log(m.red(` could not write ${W.path}`)))}}}if(e.json){console.log(JSON.stringify(x,null,2));return}if(x.length===0){console.log(m.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let k=["agent","article","field","action","got"],R=k.map(C=>Math.max(C.length,...x.map(D=>String(D[C]).length))),j=C=>C.map((D,W)=>String(D).padEnd(R[W])).join(" ");console.log(),console.log(m.bold(j(k)));for(let C of x)console.log(j(k.map(D=>C[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 ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});ee.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:o}=await import("./questions-4B4KSPXG.js"),{TIER_RANK:t}=await import("./article-fields-L4D2BOGY.js"),n=new o(Gt(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(Gt(t.dir));if(t.dismiss){let f=r.resolve(e,"dismissed");console.log(f?m.dim(` dismissed: ${f.question}`):m.red(` no question matching "${e}"`));return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let a=r.resolve(e,"answered",o);if(!a){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${a.question}`)),a.kind!=="field"||!a.field||!a.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[a.field]){console.log(m.dim(` recorded against ${a.path}. "${a.field}" has no fixed slot, so nothing was rewritten.`));return}let d=$e(t.dir,t.mode).getAgentWiki(a.agentId),g=d.readArticle(a.path);if(!g){console.log(m.yellow(` article gone: ${a.path}`));return}let l=s(g.content,a.field,`${o} (answered by operator)`);if(!l){console.log(m.dim(" already present \u2014 nothing to write."));return}let u=d.writeArticle(a.path,g.meta,l.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-UA2ROH3V.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:d,sweepPolicies:g}=await import("./triage-backtest-JNO7RKX7.js"),{calibrationReport:l}=await import("./calibration-ILS5OI44.js"),f=$e(e.dir,"graph").getSharedStore(),p=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(P=>P.id)),{labeled:y,backlog:$}=r(p,w),b=a(y,P=>P.absorbed,parseInt(e.n)),v={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},A=[],x=0,E=Date.now();if(e.load){let{readFileSync:P}=await import("fs");A.push(...JSON.parse(P(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${$} in backlog) \u2014 grading ${b.length}`));for(let P of e.load?[]:b){let H=await i(o,n(P),t,{features:{source:P.source??"",absorbed:P.absorbed}});if(!H){x++;continue}let ae=H.answers;A.push({entry:P,verdict:s(H.answers,v),citeWorthy:ae.citeWorthy?.noul})}if(A.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:P}=await import("fs");P(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let k=c(A,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),R=d(A,"seat","seat"),j=l(R,{minN:50}),C=((Date.now()-E)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:k,calibration:j,failures:x,elapsed:C},null,2));return}let D=P=>`${(P*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${k.n} (${k.positives} kept by absorb, ${k.negatives} passed over)`),console.log(` recall ${D(k.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${D(k.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${D(k.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${k.lostPositives>0?m.yellow(`lost ${k.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in j)||!j.insufficient)&&console.log(` ECE ${j.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),k.lostPositives>0){let P=k.droppedBy;console.log(m.dim(` dropped by: type ${P.type} \xB7 worth ${P.worth} \xB7 durability ${P.durability} (a positive can fail several)`))}let W=k.positiveMeans;if(console.log(m.dim(` positives avg: worth ${W.worth.toFixed(2)} \xB7 durability ${W.durability.toFixed(2)} \xB7 typeConf ${W.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${C}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 P=parseFloat(e.minRecall),{best:H,points:ae}=g(A,{minRecall:P});if(console.log(),console.log(m.bold(` threshold sweep (${ae.length} policies, recall floor ${D(P)})`)),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(P)} recall \u2014 not even keeping everything typed.`));let B=ae.slice().sort((ke,he)=>he.recall-ke.recall)[0];B&&console.log(m.dim(` Best recall available: ${D(B.recall)} at ${B.requireTyped?`type>=${B.minType}`:"type gate OFF"} worth>=${B.minWorth} dur>=${B.minDurability}, filtering ${D(B.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});ee.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,o)=>{let t=q(process.cwd(),e);We(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");We(n)&&!o.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=q(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function zm(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"}rl();import{Command as Ym}from"commander";import N from"chalk";import{resolve as Dn}from"path";import{existsSync as Km}from"fs";ve();var ct=new Ym().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");ct.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=L();if(!o.graph?.enabled){console.log(N.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(N.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(N.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 lo({baseDir:Dn(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(N.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(N.bold(` Graph review \u2014 ${r.length} pending`)),console.log(N.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let d=0,g=0,l=0,u=0;for(let p=0;p<r.length;p++){let w=r[p],y=on(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${N.cyan(w.msgHash.slice(0,8))} ${N.dim(y)} ... `);let $=Vm(w,a,c),b=null;try{b=await Xm(n,t,$,o.dashboard?.token)}catch(x){u++,console.log(N.red(`ERR ${x.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(N.red("ERR no decision"));continue}let v=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(N.green("APPROVE")+" "+N.dim(A)),e.dryRun)d++;else try{Qm(i,w,a,c,t),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:t,reviewReason:A}),d++}catch(x){console.log(N.yellow(` (commit failed, staying pending: ${x.message?.slice(0,100)})`)),u++}else v==="reject"?(console.log(N.red("REJECT")+" "+N.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:t,reviewReason:A}),g++):(console.log(N.yellow("SKIP")+" "+N.dim(A||v)),l++)}console.log();let f=e.dryRun?"would":"did";console.log(N.dim(` Summary: ${f} approve ${d}, ${f} reject ${g}, ${l} skipped, ${u} errors.`)),e.dryRun&&(d>0||g>0)&&console.log(N.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});ct.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=L();if(!o.graph){console.log(N.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=Dn(process.cwd(),o.graph.baseDir);if(!Km(t)){console.log(N.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-V4WN2VVM.js"),s=new lo({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(N.dim(" "),...a)});console.log(),console.log(N.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(N.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(N.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(N.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});ct.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=L();if(!o.graph?.enabled){console.log(N.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 lo({baseDir:Dn(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(k=>k.id));console.log(),console.log(N.bold(` graph pull \u2190 ${t}`));let d,g,l;try{let k=await fetch(`${t}/graph/schema`,{headers:s});if(!k.ok)throw new Error(`schema HTTP ${k.status}`);d=(await k.json()).schema;let j=await fetch(`${t}/graph/nodes`,{headers:s});if(!j.ok)throw new Error(`nodes HTTP ${j.status}`);g=(await j.json()).nodes||[];let C=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!C.ok)throw new Error(`classifications HTTP ${C.status}`);l=(await C.json()).classifications||[]}catch(k){console.log(N.red(` fetch failed: ${k.message}`));return}let u=r.levels.map(k=>k.id).join(","),f=d?.levels?.map(k=>k.id).join(","),p=u===f;p?console.log(N.dim(` schema matches (${r.levels.length} levels)`)):(console.log(N.yellow(" \u26A0 schema levels differ:")),console.log(N.dim(` local: ${u}`)),console.log(N.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(N.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(d)):console.log(N.yellow(" keeping local schema; node import may fail if levels disagree")));let w=p?r:d,y=new Map;w.levels.forEach((k,R)=>y.set(k.id,R));let $=[...g].sort((k,R)=>(y.get(k.level)??99)-(y.get(R.level)??99)),b=0,v=0,A=0;for(let k of $){if(c.has(k.id)){v++;continue}if(e.dryRun){b++,c.add(k.id);continue}try{i.addNode({...k,createdBy:k.createdBy?`${k.createdBy} (sync)`:`sync:${t}`}),c.add(k.id),b++}catch(R){A++,console.log(N.yellow(` skip node ${k.id}: ${R.message?.slice(0,100)}`))}}console.log(N.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${A} failed`));let x=0,E=0;for(let k of l)if(!(!k.msgHash||!Array.isArray(k.path))){if(i.getFingerprint(k.msgHash)){E++;continue}if(e.dryRun){x++;continue}i.setFingerprint(k.msgHash,{path:k.path,leaf:k.leaf||{}}),x++}console.log(N.dim(` fingerprints: +${x} cached \xB7 ${E} already-present`)),console.log(),e.dryRun?console.log(N.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(N.green(` \u2713 pulled from ${t}`)),console.log()});function Vm(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(`
401
+ ]`}ee.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=ke(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(g.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${g.dim(s.date)} ${g.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(g.dim(` ... showing last 20 of ${n.length}`)),console.log()});ee.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let o=e.dir||q(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-S3VHHVYW.js");n=(s().mesh?.peers||[]).map(r=>r.url)}catch{}console.log(),console.log(g.bold(" AgentX Wiki Server")),console.log(),console.log(` ${g.green(">")} http://localhost:${t}`),e.agent?console.log(` Agent: ${g.cyan(e.agent)}`):console.log(` Mode: ${g.cyan("Hub")} (all agents)`),n.length>0&&console.log(` Mesh: ${g.cyan(n.length+" peer(s)")} \u2014 ${n.join(", ")}`),console.log(g.dim(` Wiki: ${o}`)),console.log(g.dim(" Press Ctrl+C to stop")),console.log(),_r(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-U57NWHKC.js"),c=ke(e.dir,e.mode),d=e.agent?[e.agent]:c.listAgents(),m=parseInt(e.limit),l=parseFloat(e.min),u=[];e:for(let y of d){let $=c.getAgentWiki(y);for(let b of $.listArticles(y)){if(u.length>=m)break e;let v=$.readArticle(b.path);if(!v||e.type&&v.meta.type!==e.type)continue;let A={...o(v.meta.type),...e.fields?i(v.meta.type):{}},x=await a(s,t({path:b.path,title:v.meta.title,type:v.meta.type,tags:v.meta.tags,body:v.content}),A,{links:[{kind:"article",id:b.path}],features:{agent:y,type:v.meta.type??"?"}});if(!x){console.log(g.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let E=n(x.answers),k=e.fields?r(v.meta.type,x.answers):null;E.completeness>=l&&!(k&&!k.fit)||u.push({agent:y,type:v.meta.type??"?",score:E.completeness.toFixed(2),standsAlone:E.standsAlone.toFixed(2),gap:E.biggestGap,...k?{missing:k.missingCritical.join(",")||"-",cov:`${Math.round(k.coverage*100)}%`}:{},title:v.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(g.green(" no articles below the threshold"));return}u.sort((y,$)=>parseFloat(y.score)-parseFloat($.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($=>String($[y]).length))),w=y=>y.map(($,b)=>String($).padEnd(p[b])).join(" ");console.log(),console.log(g.bold(w(f)));for(let y of u)console.log(w(f.map($=>y[$])));if(e.fields){let y=u.filter($=>$.missing!=="-").length;console.log(g.dim(`
402
+ ${u.length} article(s) flagged; ${y} missing a required field.`)),console.log(g.dim(" 'missing' is the actionable column \u2014 a named field beats a score."))}else console.log(g.dim(`
403
+ ${u.length} article(s) below ${l}. standsAlone is the one that matters:`)),console.log(g.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-EDW72Q4O.js"),n=ke(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let d=n.getAgentWiki(c),m=q(d.baseDir,"_index.md");try{if((await import("fs")).existsSync(m)){i=c;break}}catch{}}if(!i){console.log(g.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(g.bold(` Q: ${e}`)),console.log(g.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(g.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(g.dim(" Citations:"));for(let c of a.citations){let d=c.type?g.magenta(` [${c.type}]`):"";console.log(g.dim(` - ${c.title}${d} (${c.path})`))}console.log()}if(o.trace&&a.trace){if(console.log(g.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(g.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(d=>!a.candidates.some(m=>m.path===d.path));console.log(g.dim(` followed: ${c.map(d=>`${d.title}@h${d.hop}`).join(" | ")}`))}console.log()}});ee.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,o)=>{let t=ke(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=await t.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(g.bold(` ${g.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(g.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(g.dim(" No matching articles")),console.log()});ee.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let o=ke(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=q(process.cwd(),".agentx/graph");if(!We(n)){console.log(g.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new go({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[l,u]of Object.entries(i.entries))r.set(l,u.path);if(r.size===0){console.log(g.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(g.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,d=0,m=0;for(let l of t){let u=o.getAgentWiki(l),f=u.listArticles(l),p=o.getSharedStore().listEntries(),w=new Map(p.map(v=>[v.id,v])),y=0,$=0,b=0;for(let v of f){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;y++,c++;let A=new Map;for(let E of v.meta.sources){let k=w.get(E);if(!k)continue;let N=String(k.meta?.sender??""),C=s.fingerprint({text:k.content,channel:k.source,sender:N}),j=r.get(C);if(!j?.length)continue;let P=j.join("/"),W=A.get(P);W?W.n++:A.set(P,{path:j,n:1})}if(A.size===0)continue;$++,d++;let x;for(let E of A.values())(!x||E.n>x.n)&&(x=E);x&&(e.dryRun||(u.writeArticle(v.path,{...v.meta,graphPath:x.path},v.content,l),b++,m++))}console.log(` ${g.cyan(l)}: ${g.bold(f.length)} articles \xB7 ${y} eligible \xB7 ${$} matched \xB7 ${g.green(b)} written`)}console.log(),console.log(g.bold(` Total: ${a} articles, ${c} missing graphPath, ${d} matched (${Math.round(d/Math.max(1,c)*100)}%), ${m} written`)),e.dryRun&&console.log(g.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});ee.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let t=ke(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-S3VHHVYW.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(g.red(" No --peer specified and no daemon config found")),console.log(g.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(n.length===0){console.log(g.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(g.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(g.red(` HTTP ${a.status}`));continue}let c=await a.json(),d=c.entries||[],m=c.nodeId||"unknown";console.log(g.dim(` Node: ${m} \u2014 ${d.length} entries`));let l=0;for(let u of d)s.has(u.id)||(e.dryRun||(t.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${m}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),l++);l>0?console.log(g.green(` ${l} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(g.dim(" Already up to date")),i+=l;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(g.dim(` ${p.agentId}: ${p.totalEntries} entries, ${p.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(g.red(" Connection refused")):console.log(g.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(g.green(` ${i} entries synced.`)):i>0?console.log(g.dim(` ${i} entries would be synced (dry run)`)):console.log(g.dim(" All peers up to date")),console.log()});ee.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let o=e.dir||q(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let d=new ts(o,void 0,c),l=d.getAgentWiki(t).rebuildIndex(),u=d.getAgentEntries(t),f=d.getUnabsorbedEntries(t),p=new Set,w=0,y=new Set;for(let b of l.articles){for(let v of b.tags||[])p.add(v);w+=b.tags?.length||0;for(let v of b.sources||[])y.add(v)}let $=new Set(l.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:Vs(c),articles:l.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:l.articles.length>0?(w/l.articles.length).toFixed(1):"0",dirs:$.size,coverage:y.size,articleList:l.articles}});console.log(),console.log(g.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,d]of r){let m=s.map(l=>d(l).padEnd(i));console.log(` ${c.padEnd(20)} ${m.join(" ")}`)}console.log();let a=(c,d)=>{let m=Math.max(...s.map(u=>u[c])),l=s.filter(u=>u[c]===m).map(u=>u.label);m>0&&console.log(g.dim(` Best ${d}: ${l.join(", ")} (${m})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});ee.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,o)=>{let t=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");We(t)||(console.log(g.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?q(process.cwd(),e):q(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=q(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(g.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),d=c("tar",a,{stdio:"inherit"});d.status!==0&&(console.log(g.red(` tar exited with ${d.status}`)),process.exit(d.status||1));let{statSync:m}=await import("fs"),l=We(s)?m(s).size:0;console.log(),console.log(g.green(` \u2713 wrote ${s} (${Ym(l)})`)),console.log(g.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-U57NWHKC.js"),{QuestionStore:c}=await import("./questions-4B4KSPXG.js"),d=ke(e.dir,e.mode),m=[],l=e.agent?[e.agent]:d.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let E of l){let k=d.getAgentWiki(E);for(let N of k.listArticles(E)){if(f>=u)break e;let C=k.readArticle(N.path);if(!C||e.type&&C.meta.type!==e.type)continue;f++;let j=await a(r,n({title:C.meta.title,type:C.meta.type,body:C.content}),o(C.meta.type),{links:[{kind:"article",id:N.path}],features:{agent:E,type:C.meta.type??"?"}});if(!j){console.log(g.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=t(C.meta.type,j.answers);for(let W of s(P,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&W.needsHuman||(e.ask&&W.needsHuman&&m.push({kind:"field",agentId:E,path:N.path,subject:C.meta.title,field:W.field,tier:W.tier,question:`${C.meta.title} (${C.meta.type??"?"}) \u2014 ${W.label}?`}),p.push({tier:W.tier,need:W.field,how:W.needsHuman?g.yellow("ask"):W.sources.join("/"),uncertain:W.uncertain?"?":"",agent:E,article:C.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&m.length>0&&(w=new c(Gt(e.dir)).add(m)),e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(g.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],$=E=>String(E).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(E=>Math.max(E.length,...p.map(k=>$(k[E]).length))),v=(E,k)=>String(E)+" ".repeat(Math.max(0,b[k]-$(E).length));console.log(),console.log(g.bold(y.map((E,k)=>v(E,k)).join(" ")));for(let E of p)console.log(y.map((k,N)=>v(E[k],N)).join(" "));let A=p.filter(E=>E.how!==g.yellow("ask")).length;console.log(),console.log(g.dim(` ${p.length} gap(s) across ${f} article(s).`)),console.log(g.dim(` ${A} can be closed by a lookup; ${p.length-A} need a person.`));let x=p[0]?.tier;if(x&&console.log(g.dim(` Start at ${x} \u2014 ${i[x]}.`)),e.ask&&(console.log(g.cyan(` Queued ${w.added} question(s) for a person (${w.skipped} already asked).`)),console.log(g.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&w.added>0){let{TIER_RANK:E}=await import("./article-fields-L4D2BOGY.js"),k=E[e.notifyTier]??E.pillar,N=m.filter(C=>(E[C.tier??"furniture"]??9)<=k);if(N.length===0)console.log(g.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:C}=await import("./config-S3VHHVYW.js"),j=C(),P=j?.notifications?.destination;if(!P?.channel||!P?.chatId)console.log(g.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let W=N.slice(0,10).map(B=>`\u2022 ${B.question}`).join(`
404
+ `),L=N.length>10?`
405
+ \u2026and ${N.length-10} more`:"",H=`${N.length} wiki gap(s) need you (${e.notifyTier}+):
406
+ ${W}${L}
407
+
408
+ agentx wiki questions`,ae=j?.daemon?.port??j?.port??18800;try{let B=await fetch(`http://127.0.0.1:${ae}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:H})});console.log(B.ok?g.cyan(` Pushed ${N.length} question(s) to ${P.channel}.`):g.yellow(` Push failed (${B.status}) \u2014 questions are still queued.`))}catch(B){console.log(g.yellow(` Push failed (${String(B?.message??B).slice(0,80)}) \u2014 questions are still queued.`))}}}}});ee.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-L4D2BOGY.js"),{askSeat:r}=await import("./seat-U57NWHKC.js"),{resolveFacts:a,mergeRecords:c,installPrompts:d,defaultSources:m,recordsFromEntries:l}=await import("./facts-YVEJOM7O.js"),{backfillArticle:u}=await import("./backfill-MTD2B62I.js"),f=ke(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=m(),$=c(l(f.getSharedStore().listEntries())),b=new Map($.map(j=>[j.name.toLowerCase().trim(),j])),v=0,A=0,x=[],E=!1;e:for(let j of p){let P=f.getAgentWiki(j);for(let W of P.listArticles(j)){if(v>=w)break e;if(W.meta.type!=="person")continue;let L=P.readArticle(W.path);if(!L)continue;v++;let H=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),o(L.meta.type),{links:[{kind:"article",id:W.path}],features:{agent:j,op:"backfill"}});if(!H){console.log(g.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let B=t(L.meta.type,H.answers).missing.filter(T=>i.includes(T));if(B.length===0)continue;let{records:ve,results:he}=await a([{name:L.meta.title,type:"person"}],{sources:y}),_=b.get(L.meta.title.toLowerCase().trim());if(!E){for(let T of d(he,y))console.log(g.yellow(` ! ${T.source} ${T.kind} \u2014 would supply ${T.provides.join(", ")}`)),console.log(g.dim(` ${T.hint}`));E=!0}let Fe=c([..._?[{name:_.name,source:"entries",fields:Object.fromEntries(Object.entries(_.fields).map(([T,me])=>[T,me.value]))}]:[],...ve]);if(Fe.length===0)continue;let{content:ye,edits:Oo}=u(L.content,Fe[0],B);if(Oo.length!==0){for(let T of Oo)x.push({agent:j,article:L.meta.title.slice(0,32),field:T.field,action:T.replaced?"replace":"add",got:`${T.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(W.path,L.meta,ye,j)?A++:console.log(g.red(` could not write ${W.path}`)))}}}if(e.json){console.log(JSON.stringify(x,null,2));return}if(x.length===0){console.log(g.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let k=["agent","article","field","action","got"],N=k.map(j=>Math.max(j.length,...x.map(P=>String(P[j]).length))),C=j=>j.map((P,W)=>String(P).padEnd(N[W])).join(" ");console.log(),console.log(g.bold(C(k)));for(let j of x)console.log(C(k.map(P=>j[P])));console.log(),e.apply?(console.log(g.green(` ${x.length} field(s) written across ${A} article(s).`)),console.log(g.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(g.dim(` ${x.length} field(s) would be written across ${v} article(s) considered.`)),console.log(g.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(Gt(e.dir)).list(e.status);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(g.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?g.dim(`[${s.tier}]`):"";console.log(` ${g.cyan(s.id)} ${i} ${s.question}`),s.answer&&console.log(g.dim(` \u2192 ${s.answer}`))}console.log(),console.log(g.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(Gt(t.dir));if(t.dismiss){let f=r.resolve(e,"dismissed");console.log(f?g.dim(` dismissed: ${f.question}`):g.red(` no question matching "${e}"`));return}if(!o){console.log(g.red(" give a value, or pass --dismiss"));return}let a=r.resolve(e,"answered",o);if(!a){console.log(g.red(` no question matching "${e}"`));return}if(console.log(g.green(` answered: ${a.question}`)),a.kind!=="field"||!a.field||!a.path){console.log(g.dim(" recorded. No article to patch yet."));return}if(!i[a.field]){console.log(g.dim(` recorded against ${a.path}. "${a.field}" has no fixed slot, so nothing was rewritten.`));return}let d=ke(t.dir,t.mode).getAgentWiki(a.agentId),m=d.readArticle(a.path);if(!m){console.log(g.yellow(` article gone: ${a.path}`));return}let l=s(m.content,a.field,`${o} (answered by operator)`);if(!l){console.log(g.dim(" already present \u2014 nothing to write."));return}let u=d.writeArticle(a.path,m.meta,l.content,a.agentId);console.log(u?g.green(` wrote ${a.field} into ${a.path} (prior version kept)`):g.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-U57NWHKC.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:d,sweepPolicies:m}=await import("./triage-backtest-JNO7RKX7.js"),{calibrationReport:l}=await import("./calibration-ILS5OI44.js"),f=ke(e.dir,"graph").getSharedStore(),p=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:y,backlog:$}=r(p,w),b=a(y,L=>L.absorbed,parseInt(e.n)),v={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},A=[],x=0,E=Date.now();if(e.load){let{readFileSync:L}=await import("fs");A.push(...JSON.parse(L(e.load,"utf-8"))),console.log(g.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(g.dim(` ${y.length} labelled (${$} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let H=await i(o,n(L),t,{features:{source:L.source??"",absorbed:L.absorbed}});if(!H){x++;continue}let ae=H.answers;A.push({entry:L,verdict:s(H.answers,v),citeWorthy:ae.citeWorthy?.noul})}if(A.length===0){console.log(g.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(A)),console.log(g.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let k=c(A,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),N=d(A,"seat","seat"),C=l(N,{minN:50}),j=((Date.now()-E)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:k,calibration:C,failures:x,elapsed:j},null,2));return}let P=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(g.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${k.n} (${k.positives} kept by absorb, ${k.negatives} passed over)`),console.log(` recall ${P(k.recall)} ${g.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P(k.precision)} ${g.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P(k.filtered)} ${g.dim("never reaches the writing model")}`),console.log(` ${k.lostPositives>0?g.yellow(`lost ${k.lostPositives} article(s) absorb would have written`):g.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in C)||!C.insufficient)&&console.log(` ECE ${C.ece?.toFixed(3)??"n/a"} ${g.dim("on P(worth keeping)")}`),k.lostPositives>0){let L=k.droppedBy;console.log(g.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let W=k.positiveMeans;if(console.log(g.dim(` positives avg: worth ${W.worth.toFixed(2)} \xB7 durability ${W.durability.toFixed(2)} \xB7 typeConf ${W.typeConfidence.toFixed(2)}`)),console.log(g.dim(` ${j}s, ${x} seat failure(s)`)),console.log(),console.log(g.dim(" Recall is the number that decides this: a dropped positive is")),console.log(g.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let L=parseFloat(e.minRecall),{best:H,points:ae}=m(A,{minRecall:L});if(console.log(),console.log(g.bold(` threshold sweep (${ae.length} policies, recall floor ${P(L)})`)),H)console.log(` best: ${H.requireTyped?`typed & type>=${H.minType}`:"type gate OFF"} worth>=${H.minWorth} durability>=${H.minDurability}`),console.log(` recall ${P(H.recall)} \xB7 filtered ${P(H.filtered)} \xB7 precision ${P(H.precision)} \xB7 lost ${H.lostPositives}`),console.log(g.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(g.red(` No policy reaches ${P(L)} recall \u2014 not even keeping everything typed.`));let B=ae.slice().sort((ve,he)=>he.recall-ve.recall)[0];B&&console.log(g.dim(` Best recall available: ${P(B.recall)} at ${B.requireTyped?`type>=${B.minType}`:"type gate OFF"} worth>=${B.minWorth} dur>=${B.minDurability}, filtering ${P(B.filtered)}`)),console.log(g.yellow(" The gate is not safe to run in active mode on this evidence."))}}});ee.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,o)=>{let t=q(process.cwd(),e);We(t)||(console.log(g.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");We(n)&&!o.force&&(console.log(g.yellow(` ${n} already exists.`)),console.log(g.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=q(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(g.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(g.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(g.green(` \u2713 restored to ${n}`)),console.log(g.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function Ym(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"}dl();import{Command as Km}from"commander";import R from"chalk";import{resolve as Mn}from"path";import{existsSync as Vm}from"fs";we();var lt=new Km().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");lt.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let o=D();if(!o.graph?.enabled){console.log(R.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(R.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(R.red(` agent "${t}" not in config`));return}let n=(e.daemonUrl||o.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new go({baseDir:Mn(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(R.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(R.bold(` Graph review \u2014 ${r.length} pending`)),console.log(R.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let d=0,m=0,l=0,u=0;for(let p=0;p<r.length;p++){let w=r[p],y=on(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 $=Xm(w,a,c),b=null;try{b=await Qm(n,t,$,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 v=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(R.green("APPROVE")+" "+R.dim(A)),e.dryRun)d++;else try{Zm(i,w,a,c,t),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:t,reviewReason:A}),d++}catch(x){console.log(R.yellow(` (commit failed, staying pending: ${x.message?.slice(0,100)})`)),u++}else v==="reject"?(console.log(R.red("REJECT")+" "+R.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:t,reviewReason:A}),m++):(console.log(R.yellow("SKIP")+" "+R.dim(A||v)),l++)}console.log();let f=e.dryRun?"would":"did";console.log(R.dim(` Summary: ${f} approve ${d}, ${f} reject ${m}, ${l} skipped, ${u} errors.`)),e.dryRun&&(d>0||m>0)&&console.log(R.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});lt.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let o=D();if(!o.graph){console.log(R.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=Mn(process.cwd(),o.graph.baseDir);if(!Vm(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 go({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()});lt.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let o=D();if(!o.graph?.enabled){console.log(R.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let t=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new go({baseDir:Mn(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(k=>k.id));console.log(),console.log(R.bold(` graph pull \u2190 ${t}`));let d,m,l;try{let k=await fetch(`${t}/graph/schema`,{headers:s});if(!k.ok)throw new Error(`schema HTTP ${k.status}`);d=(await k.json()).schema;let C=await fetch(`${t}/graph/nodes`,{headers:s});if(!C.ok)throw new Error(`nodes HTTP ${C.status}`);m=(await C.json()).nodes||[];let j=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!j.ok)throw new Error(`classifications HTTP ${j.status}`);l=(await j.json()).classifications||[]}catch(k){console.log(R.red(` fetch failed: ${k.message}`));return}let u=r.levels.map(k=>k.id).join(","),f=d?.levels?.map(k=>k.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(d)):console.log(R.yellow(" keeping local schema; node import may fail if levels disagree")));let w=p?r:d,y=new Map;w.levels.forEach((k,N)=>y.set(k.id,N));let $=[...m].sort((k,N)=>(y.get(k.level)??99)-(y.get(N.level)??99)),b=0,v=0,A=0;for(let k of $){if(c.has(k.id)){v++;continue}if(e.dryRun){b++,c.add(k.id);continue}try{i.addNode({...k,createdBy:k.createdBy?`${k.createdBy} (sync)`:`sync:${t}`}),c.add(k.id),b++}catch(N){A++,console.log(R.yellow(` skip node ${k.id}: ${N.message?.slice(0,100)}`))}}console.log(R.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${A} failed`));let x=0,E=0;for(let k of l)if(!(!k.msgHash||!Array.isArray(k.path))){if(i.getFingerprint(k.msgHash)){E++;continue}if(e.dryRun){x++;continue}i.setFingerprint(k.msgHash,{path:k.path,leaf:k.leaf||{}}),x++}console.log(R.dim(` fingerprints: +${x} cached \xB7 ${E} already-present`)),console.log(),e.dryRun?console.log(R.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(R.green(` \u2713 pulled from ${t}`)),console.log()});function Xm(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(`
418
409
  `),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(`
419
- `)}async function Xm(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 Qm(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function Ys(){let e=L();if(!e.graph?.baseDir)return console.log(N.red(" graph.baseDir is not configured")),null;let o=Dn(process.cwd(),e.graph.baseDir);return{store:new lo({baseDir:o}),baseDir:o}}var Ks=ct.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");Ks.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=Ys();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(N.green(" nothing left unreviewed"));return}let a=o.store.loadNodes().nodes;console.log();for(let c of r){let d=typeof c.confidence=="number"?c.confidence.toFixed(2):N.dim("cache");console.log(` ${N.cyan(c.msgHash.slice(0,8))} ${d.padStart(5)} ${N.bold(on(c.path,a)||c.path.join(" \u203A "))}`),c.preview&&console.log(N.dim(` ${String(c.preview).replace(/\s+/g," ").slice(0,96)}`))}console.log(),console.log(N.dim(` ${r.length} to check (${e.strategy}).`)),console.log(N.dim(" agentx graph label mark <hash> correct|wrong|unsure [--path a/b/c]"))});Ks.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(N.red(" verdict must be correct | wrong | unsure"));return}let n=Ys();if(!n)return;let{ReviewStore:s}=await import("./review-store-B4YE3EFK.js"),r=n.store.listAllClassifications().filter(d=>d.msgHash===e||d.msgHash.startsWith(e));if(r.length===0){console.log(N.red(` no classification matching "${e}"`));return}if(r.length>1){console.log(N.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(N.green(` ${o}: ${on(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(N.dim(` should have been: ${t.path}`))});Ks.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=Ys();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} ${N.dim("reviewed rows that carry a confidence")}`),r.byBin.length>0){console.log(),console.log(N.bold(" reliability \u2014 confidence vs how often it was right"));for(let c of r.byBin){let d=Math.abs(parseFloat(c.bin.split("-")[0])+.05-c.accuracy),g=c.n>=5&&d>.15?N.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(N.dim(` ${100-r.calibratable} more labelled rows before a calibration report means anything.`)):console.log(N.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as sp}from"commander";import Y from"chalk";import{Command as mc}from"commander";import se from"chalk";import{existsSync as Zm}from"fs";import{resolve as ep}from"path";import op from"better-sqlite3";function tp(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(o){let n=Number(o[1]),s=o[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(se.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function np(e){let o=ep(process.cwd(),e);return Zm(o)||(console.log(se.red(` No db at ${o}`)),process.exit(1)),new op(o,{readonly:!0})}var pc=new mc().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(vt)).option("--max <n>","max clusters distilled per run",String(sn)).option("--via <agentId>","route the LLM call through a running agent \u2014 uses the agent's own session").option("--model <model>","direct Anthropic API model \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--commit","write drafts and persist recurrence counts",!1).action(async e=>{e.commit&&!e.via&&!e.model&&(console.log(se.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=np(e.path),t=await Ki(o,{since:tp(e.since),agentId:e.agent,sessions:new Ii(process.cwd()),minOccurrences:Number(e.minOccurrences)||vt,max:Number(e.max)||sn,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(se.dim(` ${n}`))});console.log(),console.log(` ${t.episodes} episode(s) \u2192 ${t.clusters} cluster(s), ${t.ready.length} at threshold`);for(let n of t.ready)console.log(` ${se.cyan(n.key)} ${se.bold(`\xD7${n.count}`)} ${se.dim(n.status)}`),n.sampleMessage&&console.log(se.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(se.dim(`
410
+ `)}async function Qm(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 Ei((c?.content||"").toString())}finally{clearTimeout(r)}}function Zm(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function Xs(){let e=D();if(!e.graph?.baseDir)return console.log(R.red(" graph.baseDir is not configured")),null;let o=Mn(process.cwd(),e.graph.baseDir);return{store:new go({baseDir:o}),baseDir:o}}var Qs=lt.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");Qs.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=Xs();if(!o)return;let{ReviewStore:t,buildQueue:n}=await import("./review-store-B4YE3EFK.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,new Set(i.keys()),{n:parseInt(e.n),strategy:e.strategy});if(e.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(R.green(" nothing left unreviewed"));return}let a=o.store.loadNodes().nodes;console.log();for(let c of r){let d=typeof c.confidence=="number"?c.confidence.toFixed(2):R.dim("cache");console.log(` ${R.cyan(c.msgHash.slice(0,8))} ${d.padStart(5)} ${R.bold(on(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]"))});Qs.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=Xs();if(!n)return;let{ReviewStore:s}=await import("./review-store-B4YE3EFK.js"),r=n.store.listAllClassifications().filter(d=>d.msgHash===e||d.msgHash.startsWith(e));if(r.length===0){console.log(R.red(` no classification matching "${e}"`));return}if(r.length>1){console.log(R.red(` "${e}" matches ${r.length} rows \u2014 use more characters`));return}new s(n.baseDir).record({msgHash:r[0].msgHash,verdict:o,correctPath:t.path?String(t.path).split("/").filter(Boolean):void 0,note:t.note,reviewer:t.by});let c=n.store.loadNodes().nodes;console.log(R.green(` ${o}: ${on(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(R.dim(` should have been: ${t.path}`))});Qs.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=Xs();if(!o)return;let{ReviewStore:t,labelStats:n}=await import("./review-store-B4YE3EFK.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,i);if(e.json){console.log(JSON.stringify(r,null,2));return}let a=c=>`${(c*100).toFixed(1)}%`;if(console.log(),console.log(` classifications ${r.classifications}`),console.log(` reviewed ${r.reviewed} (${r.correct} correct \xB7 ${r.wrong} wrong \xB7 ${r.unsure} unsure)`),r.correct+r.wrong>0&&console.log(` accuracy ${a(r.accuracy)}`),console.log(` calibratable ${r.calibratable} ${R.dim("reviewed rows that carry a confidence")}`),r.byBin.length>0){console.log(),console.log(R.bold(" reliability \u2014 confidence vs how often it was right"));for(let c of r.byBin){let d=Math.abs(parseFloat(c.bin.split("-")[0])+.05-c.accuracy),m=c.n>=5&&d>.15?R.yellow(" \u2190 miscalibrated"):"";console.log(` ${c.bin} n=${String(c.n).padStart(3)} right ${a(c.accuracy).padStart(6)}${m}`)}}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 ip}from"commander";import Y from"chalk";import{Command as hc}from"commander";import se from"chalk";import{existsSync as ep}from"fs";import{resolve as op}from"path";import tp from"better-sqlite3";function np(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(o){let n=Number(o[1]),s=o[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(se.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function sp(e){let o=op(process.cwd(),e);return ep(o)||(console.log(se.red(` No db at ${o}`)),process.exit(1)),new tp(o,{readonly:!0})}var yc=new hc().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(xt)).option("--max <n>","max clusters distilled per run",String(sn)).option("--via <agentId>","route the LLM call through a running agent \u2014 uses the agent's own session").option("--model <model>","direct Anthropic API model \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--commit","write drafts and persist recurrence counts",!1).action(async e=>{e.commit&&!e.via&&!e.model&&(console.log(se.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=sp(e.path),t=await Qi(o,{since:np(e.since),agentId:e.agent,sessions:new Ti(process.cwd()),minOccurrences:Number(e.minOccurrences)||xt,max:Number(e.max)||sn,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(se.dim(` ${n}`))});console.log(),console.log(` ${t.episodes} episode(s) \u2192 ${t.clusters} cluster(s), ${t.ready.length} at threshold`);for(let n of t.ready)console.log(` ${se.cyan(n.key)} ${se.bold(`\xD7${n.count}`)} ${se.dim(n.status)}`),n.sampleMessage&&console.log(se.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(se.dim(`
420
411
  near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(se.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(se.green(` \u2713 draft written: ${n.id}`)+se.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(se.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(se.yellow(` \u26A0 ${n}`));t.dryRun?console.log(se.dim(`
421
412
  dry run only; pass --commit --via <agentId> to write drafts`)):t.drafted.length&&console.log(se.dim(`
422
- review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),gc={hourly:"0 * * * *",daily:"0 3 * * *"},uc=new mc().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(vt)).option("--timezone <tz>","IANA timezone","Africa/Tunis").option("-c, --config <path>","path to agentx.json").option("--dry-run","print what would be written without writing").action(async e=>{let o=e.off?void 0:e.cron??(e.hourly?gc.hourly:e.daily?gc.daily:void 0);!e.off&&!o&&!e.onTask&&(console.log(se.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(se.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let t=Number(e.minOccurrences)||vt,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 ${sn} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
423
- `),i=await de(a=>{we(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&we(a,"crons.procedure-extract.enabled",!1):o&&we(a,"crons.procedure-extract",{enabled:!0,schedule:o,timezone:e.timezone,agent:e.via,prompt:s,timeout:900,onError:"log"})},{configPath:e.config,dryRun:!!e.dryRun});i.success||(console.log(se.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(se.green(` \u2713 ${r} procedure extraction: off`)):(console.log(se.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(se.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(se.dim(" on-task counting: enabled")),console.log(se.dim(` threshold: ${t} occurrences`))),console.log(se.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var Ye=new sp().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");Ye.addCommand(pc);Ye.addCommand(uc);Ye.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 go,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"}.`))});Ye.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 go,t=e.steps?String(e.steps):`## Steps
413
+ review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),fc={hourly:"0 * * * *",daily:"0 3 * * *"},wc=new hc().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(xt)).option("--timezone <tz>","IANA timezone","Africa/Tunis").option("-c, --config <path>","path to agentx.json").option("--dry-run","print what would be written without writing").action(async e=>{let o=e.off?void 0:e.cron??(e.hourly?fc.hourly:e.daily?fc.daily:void 0);!e.off&&!o&&!e.onTask&&(console.log(se.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(se.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let t=Number(e.minOccurrences)||xt,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 ${sn} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
414
+ `),i=await de(a=>{be(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&be(a,"crons.procedure-extract.enabled",!1):o&&be(a,"crons.procedure-extract",{enabled:!0,schedule:o,timezone:e.timezone,agent:e.via,prompt:s,timeout:900,onError:"log"})},{configPath:e.config,dryRun:!!e.dryRun});i.success||(console.log(se.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(se.green(` \u2713 ${r} procedure extraction: off`)):(console.log(se.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(se.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(se.dim(" on-task counting: enabled")),console.log(se.dim(` threshold: ${t} occurrences`))),console.log(se.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var Ye=new ip().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");Ye.addCommand(yc);Ye.addCommand(wc);Ye.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 mo,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"}.`))});Ye.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 mo,t=e.steps?String(e.steps):`## Steps
424
415
 
425
416
  1. (fill in)
426
417
 
427
418
  ## Notes
428
419
 
429
- `;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)}});Ye.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new go,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()});Ye.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new go;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)}});Ye.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new go;try{o.rejectDraft(e),console.log(Y.green(` \u2713 rejected: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Ye.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new go;try{o.deprecate(e),console.log(Y.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Ye.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 go,n=Fi(e,t.list(),{limit:Number(o.limit)||3,minScore:Number(o.minScore)||.2});if(!n.length){console.log(Y.dim(" no matching procedures"));return}for(let s of n)console.log(` ${Y.cyan(s.procedure.meta.id)} ${Y.bold(s.score.toFixed(2))} ${Y.dim(s.reasons.join(", "))}`),console.log(Y.dim(` ${s.procedure.meta.trigger}`))});import{Command as ap}from"commander";import S from"chalk";import{resolve as dt,basename as cp}from"path";import{existsSync as Vs,readFileSync as Xs,writeFileSync as Pn}from"fs";import v$ from"better-sqlite3";import{readFileSync as ip}from"fs";import{resolve as lt,dirname as fc}from"path";import{fileURLToPath as rp}from"url";var zt=[{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 hc(e){let o=fc(rp(import.meta.url)),t=process.argv[1]?fc(process.argv[1]):"",n=[lt(o,`${e}.yaml`),lt(o,"workflows/templates",`${e}.yaml`),lt(o,"..","workflows/templates",`${e}.yaml`),lt(o,"../..","workflows/templates",`${e}.yaml`),t?lt(t,"workflows/templates",`${e}.yaml`):"",t?lt(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return ip(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
420
+ `;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)}});Ye.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new mo,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()});Ye.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new mo;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)}});Ye.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new mo;try{o.rejectDraft(e),console.log(Y.green(` \u2713 rejected: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Ye.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new mo;try{o.deprecate(e),console.log(Y.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Ye.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 mo,n=Bi(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 cp}from"commander";import S from"chalk";import{resolve as gt,basename as lp}from"path";import{existsSync as Zs,readFileSync as ei,writeFileSync as Un}from"fs";import A$ from"better-sqlite3";import{readFileSync as rp}from"fs";import{resolve as dt,dirname as bc}from"path";import{fileURLToPath as ap}from"url";var zt=[{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 $c(e){let o=bc(ap(import.meta.url)),t=process.argv[1]?bc(process.argv[1]):"",n=[dt(o,`${e}.yaml`),dt(o,"workflows/templates",`${e}.yaml`),dt(o,"..","workflows/templates",`${e}.yaml`),dt(o,"../..","workflows/templates",`${e}.yaml`),t?dt(t,"workflows/templates",`${e}.yaml`):"",t?dt(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return rp(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
430
421
  ${n.join(`
431
- `)}`)}var Me=new ap().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Me.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new Oo().list();if(!o.length){console.log(S.dim(" no workflows yet. Add one by writing .agentx/workflows/<id>.json"));return}console.log();for(let t of o){let s=t.nodes.find(a=>a.type.startsWith("trigger."))?.config??{},i=[s.filter?.project,s.filter?.repo,s.filter?.chat].filter(Boolean).join(" / "),r=t.state==="active"?S.green("dispatch: active"):S.yellow(`dispatch: ${t.state}`);console.log(` ${S.cyan(t.id)} ${S.bold(t.title)} ${S.dim(`v${t.version} \xB7`)} ${r} ${S.dim(`\xB7 review: ${t.status}`)}`),console.log(` ${S.dim("trigger:")} ${s.source??"?"}${i?` ${S.dim(i)}`:""}`),console.log(` ${S.dim("nodes: ")} ${t.nodes.length} (${t.nodes.map(a=>a.type).join(", ")})`)}console.log(),console.log(S.dim(` ${o.length} workflow${o.length===1?"":"s"}.`))});Me.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 Oo().get(e);n||(console.log(S.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=o.format.toLowerCase();s==="yaml"||s==="yml"?console.log(Ti(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(S.red(` unknown format "${o.format}" \u2014 use json or yaml`)),process.exit(1))});Me.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=dt(process.cwd(),e);Vs(i)||(console.log(S.red(` file not found: ${i}`)),process.exit(1));try{let r=Xs(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?zo(r,{filePath:e}):JSON.parse(r),d=Go.safeParse(c);if(!d.success){console.log(S.red(` \u2717 ${i}`));for(let l of d.error.issues)console.log(` ${l.path.join(".")||"<root>"}: ${l.message}`);process.exit(1)}let g=tn(d.data);if(g.length){console.log(S.yellow(` ! ${i} (lint)`));for(let l of g)console.log(` ${l}`);process.exit(1)}console.log(S.green(` \u2713 ${d.data.id} \u2014 valid`))}catch(r){let a=r instanceof nn?r.message:`parse error: ${r?.message??r}`;console.log(S.red(` ${a}`)),process.exit(1)}return}let t=new Oo().validateAll(),n=0,s=0;for(let i of t)if(i.isValid)console.log(S.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(S.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(S.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});Me.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${zt.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");zt.some(a=>a.name===t)||(console.log(S.red(` unknown template "${o.template}"`)),console.log(S.dim(` available: ${zt.map(a=>a.name).join(", ")}`)),process.exit(1)),/^[a-z0-9][a-z0-9_-]*$/.test(e)||(console.log(S.red(` workflow id must be lower-kebab (got "${e}")`)),process.exit(1));let n=new Oo;!o.force&&n.get(e)&&(console.log(S.red(` workflow "${e}" already exists. Use --force to overwrite or pick a new id.`)),process.exit(1));let s=hc(t);s=s.replace(/__ID__/g,e).replace(/__TITLE__/g,o.title?String(o.title):`${t} workflow ${e}`).replace(/__AGENT__/g,String(o.agent)).replace(/__REVIEWER__/g,String(o.reviewer));try{let a=zo(s,{filePath:`${e}.yaml`}),c=Go.safeParse(a);if(!c.success){console.log(S.red(` template "${t}" failed schema validation after substitution:`));for(let d of c.error.issues)console.log(` ${d.path.join(".")||"<root>"}: ${d.message}`);process.exit(1)}}catch(a){console.log(S.red(` template parse failed: ${a?.message??a}`)),process.exit(1)}let i=o.json?"json":"yaml",r=dt(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=zo(s,{filePath:`${e}.yaml`}),c=Go.parse(a);Pn(r,JSON.stringify(c,null,2)+`
432
- `)}else Pn(r,s);console.log(),console.log(S.green(` \u2713 scaffolded ${r}`)),console.log(S.dim(` template: ${t}`)),console.log(),console.log(S.dim(" Next:")),console.log(S.dim(` 1. edit ${r}`)),console.log(S.dim(` 2. agentx workflow validate ${r}`)),console.log(S.dim(` 3. agentx workflow run ${e} --watch`)),console.log()});Me.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of zt)console.log(` ${S.cyan(e.name.padEnd(20))} ${S.bold(e.title)}`),console.log(` ${" ".repeat(20)} ${S.dim(e.description)}`);console.log(),console.log(S.dim(" Use: agentx workflow init <id> --template <name>")),console.log()});Me.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=dt(process.cwd(),e);Vs(t)||(console.log(S.red(` file not found: ${t}`)),process.exit(1));let n=Xs(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?zo(n,{filePath:e}):JSON.parse(n)}catch(u){let f=u instanceof nn?u.message:`parse error: ${u?.message??u}`;console.log(S.red(` ${f}`)),process.exit(1)}let r=Go.safeParse(i);if(!r.success){console.log(S.red(" \u2717 schema:"));for(let u of r.error.issues)console.log(` ${u.path.join(".")||"<root>"}: ${u.message}`);process.exit(1)}let a=tn(r.data);if(a.length){console.log(S.red(" \u2717 lint:"));for(let u of a)console.log(` ${u}`);process.exit(1)}let c=new Oo,d=s?cp(e).match(/\.yml$/i)?"yml":"yaml":"json",g=dt(c.baseDir,`${r.data.id}.${d}`);if(Pn(g,s?n:JSON.stringify(r.data,null,2)+`
433
- `),console.log(S.green(` \u2713 ${r.data.id} \u2192 ${g}`)),o.reload===!1){console.log(S.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let l=`${String(o.daemon).replace(/\/$/,"")}/reload`;try{let u=await fetch(l,{method:"POST"});u.ok?console.log(S.dim(" \u2713 daemon reloaded")):console.log(S.dim(` daemon /reload returned ${u.status} \u2014 restart manually if needed`))}catch{console.log(S.dim(` daemon not reachable at ${o.daemon} \u2014 start it or restart to pick up the new workflow`))}});Me.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 kt({nodeId:t}).list({workflowId:e,limit:Number(o.limit)});if(!n.length){console.log(S.dim(` no runs yet${e?` for "${e}"`:""}.`));return}console.log();for(let s of n){let i=s.history.at(-1),r=s.pending[0]??(s.status==="completed"?"\u2205":"\u2014"),a=s.status==="running"?S.cyan:s.status==="failed"?S.red:S.green;console.log(` ${S.dim(s.id.slice(0,8))} ${S.bold(s.workflowId)} ${a(r)} ${S.dim(s.status)}`),console.log(` ${S.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${S.dim("home: ")} ${s.homeNode}`),console.log(` ${S.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${S.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(S.dim(` ${n.length} run${n.length===1?"":"s"}.`))});Me.command("run <id-or-file>").description("manually trigger a workflow by id, or load + register + run a YAML/JSON file").option("--input <json>","JSON object merged into the trigger event payload").option("--force","fire even if the trigger isn't `trigger.manual` (uses a synthesized event)",!1).option("--watch","tail per-step traces while the run executes",!1).option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").action(async(e,o)=>{let t={};if(o.input)try{t=JSON.parse(o.input)}catch{console.log(S.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=dt(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&Vs(s)){let c=Xs(s,"utf-8"),d=/\.(ya?ml)$/i.test(e),g;try{g=d?zo(c,{filePath:e}):JSON.parse(c)}catch(b){let v=b instanceof nn?b.message:`parse error: ${b?.message??b}`;console.log(S.red(` ${v}`)),process.exit(1)}let l=Go.safeParse(g);if(!l.success){console.log(S.red(" \u2717 schema:"));for(let b of l.error.issues)console.log(` ${b.path.join(".")||"<root>"}: ${b.message}`);process.exit(1)}let u=tn(l.data);if(u.length){console.log(S.red(" \u2717 lint:"));for(let b of u)console.log(` ${b}`);process.exit(1)}let f=new Oo,p=l.data.id.startsWith("_adhoc-")?l.data.id:`_adhoc-${l.data.id}-${Date.now().toString(36)}`,w=d?"yaml":"json",y=dt(f.baseDir,`${p}.${w}`),$=d?c.replace(new RegExp(`^id:\\s*${l.data.id}\\b`,"m"),`id: ${p}`):JSON.stringify({...l.data,id:p},null,2)+`
434
- `;Pn(y,$),n=p,console.log(S.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(S.red(` run failed (${c.status}): ${g.slice(0,300)}`)),c.status===409&&console.log(S.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let d=await c.json();a=d.runId,console.log(S.green(` \u2713 run started: ${a||"(unknown id)"}${d.force?S.dim(` (forced, source=${d.source})`):""}`))}catch(c){console.log(S.red(` request to daemon failed: ${c.message}`)),process.exit(1)}o.watch&&a&&await lp({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function lp(e){let o=new Set,t=new Map,n=Date.now(),s=15*60*1e3;for(;Date.now()-n<s;){let i=[];try{let r=await fetch(`${e.daemonUrl}/traces?workflowRunId=${encodeURIComponent(e.runId)}&limit=200`);r.ok&&(i=(await r.json()).traces||[])}catch{}for(let r of i){if(!r.taskId||o.has(r.taskId)||(o.add(r.taskId),t.set(r.taskId,r),e.quiet))continue;let a=r.status||"running",c=a==="ok"?S.green:a==="error"?S.red:S.cyan,d=r.totalTokens!=null?S.dim(`${r.totalTokens}t`):"",g=r.durationMs!=null?S.dim(`${r.durationMs}ms`):"";console.log(` ${c(a.padEnd(5))} ${S.bold(r.nodeId||r.label||"(node)")} ${d} ${g}`),r.error&&console.log(` ${S.red(String(r.error).slice(0,200))}`)}try{let r=await fetch(`${e.daemonUrl}/api/workflows/runs/${encodeURIComponent(e.runId)}`);if(r.ok){let c=(await r.json()).run;if(c&&c.status&&c.status!=="running")return e.quiet||(console.log(),console.log(` ${S.dim("run finished:")} ${c.status}`),console.log(S.dim(` full traces: ${e.daemonUrl}/traces?workflowRunId=${e.runId}`))),Array.from(t.values())}}catch{}await new Promise(r=>setTimeout(r,500))}return e.quiet||console.log(S.yellow(" watch timed out after 15min. Run is still active \u2014 check /traces")),Array.from(t.values())}Me.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}yc(r);return}}catch{}let n;try{let i=await fetch(`${t}/traces?workflowRunId=${encodeURIComponent(e)}&limit=200`);i.ok||(console.log(S.red(` /traces returned ${i.status}`)),process.exit(1)),n=await i.json()}catch(i){console.log(S.red(` daemon request failed: ${i.message}`)),process.exit(1)}let s=n.traces||[];if(s.length===0){console.log(S.yellow(` no traces for "${e}"`)),console.log(S.dim(" (sqlite must be opened \u2014 check 'agentx doctor' if the daemon logged 'sqlite: not opened')"));return}if(o.json){console.log(JSON.stringify(s,null,2));return}console.log(),console.log(S.bold(` ${s.length} step${s.length===1?"":"s"} for run ${e}:`)),console.log();for(let i of s)yc(i)});function yc(e){let o=e.status||"ok",t=o==="ok"?S.green:o==="error"?S.red:S.cyan,n=e.totalTokens!=null?`${e.totalTokens}t`:"\u2014",s=e.durationMs!=null?`${e.durationMs}ms`:"\u2014",i=e.model||"\u2014";console.log(` ${t(o.padEnd(5))} ${S.bold(String(e.nodeId||e.label||"(node)"))}`),console.log(` ${S.dim("taskId:")} ${e.taskId||"\u2014"}`),console.log(` ${S.dim("model:")} ${i}`),console.log(` ${S.dim("tokens:")} ${n} ${S.dim("duration:")} ${s}`),e.error&&console.log(` ${S.dim("error:")} ${S.red(String(e.error).slice(0,300))}`),console.log()}Me.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 kt({nodeId:t}).setStatus(e,"paused")||(console.log(S.yellow(` no such run: ${e}`)),process.exit(1)),console.log(S.green(` \u2713 paused ${e}`))});Me.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 kt({nodeId:t}).setStatus(e,"running")||(console.log(S.yellow(` no such run: ${e}`)),process.exit(1)),console.log(S.green(` \u2713 resumed ${e}`))});Me.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 kt({nodeId:t}).setStatus(e,"canceled")||(console.log(S.yellow(` no such run: ${e}`)),process.exit(1)),console.log(S.green(` \u2713 canceled ${e}`))});import{Command as wc}from"commander";import oe from"chalk";import Fo from"prompts";import{readFileSync as dp,existsSync as gp}from"fs";import{resolve as mp}from"path";var Yt=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],Qs=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),bc={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 $c(){let e=mp(process.cwd(),"agentx.json");if(!gp(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(dp(e,"utf-8"))}function pp(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?oe.yellow("\u26A0 no signing secret"):oe.green("\u2713 active"):oe.dim("disabled")}function up(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=Qs.has(e.source)?oe.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${oe.cyan(e.id)} ${pp(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 ao=new wc().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");ao.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=$c(),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(`
422
+ `)}`)}var Me=new cp().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Me.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new Io().list();if(!o.length){console.log(S.dim(" no workflows yet. Add one by writing .agentx/workflows/<id>.json"));return}console.log();for(let t of o){let s=t.nodes.find(a=>a.type.startsWith("trigger."))?.config??{},i=[s.filter?.project,s.filter?.repo,s.filter?.chat].filter(Boolean).join(" / "),r=t.state==="active"?S.green("dispatch: active"):S.yellow(`dispatch: ${t.state}`);console.log(` ${S.cyan(t.id)} ${S.bold(t.title)} ${S.dim(`v${t.version} \xB7`)} ${r} ${S.dim(`\xB7 review: ${t.status}`)}`),console.log(` ${S.dim("trigger:")} ${s.source??"?"}${i?` ${S.dim(i)}`:""}`),console.log(` ${S.dim("nodes: ")} ${t.nodes.length} (${t.nodes.map(a=>a.type).join(", ")})`)}console.log(),console.log(S.dim(` ${o.length} workflow${o.length===1?"":"s"}.`))});Me.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 Io().get(e);n||(console.log(S.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=o.format.toLowerCase();s==="yaml"||s==="yml"?console.log(_i(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(S.red(` unknown format "${o.format}" \u2014 use json or yaml`)),process.exit(1))});Me.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=gt(process.cwd(),e);Zs(i)||(console.log(S.red(` file not found: ${i}`)),process.exit(1));try{let r=ei(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?Yo(r,{filePath:e}):JSON.parse(r),d=zo.safeParse(c);if(!d.success){console.log(S.red(` \u2717 ${i}`));for(let l of d.error.issues)console.log(` ${l.path.join(".")||"<root>"}: ${l.message}`);process.exit(1)}let m=tn(d.data);if(m.length){console.log(S.yellow(` ! ${i} (lint)`));for(let l of m)console.log(` ${l}`);process.exit(1)}console.log(S.green(` \u2713 ${d.data.id} \u2014 valid`))}catch(r){let a=r instanceof nn?r.message:`parse error: ${r?.message??r}`;console.log(S.red(` ${a}`)),process.exit(1)}return}let t=new Io().validateAll(),n=0,s=0;for(let i of t)if(i.isValid)console.log(S.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(S.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(S.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});Me.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${zt.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");zt.some(a=>a.name===t)||(console.log(S.red(` unknown template "${o.template}"`)),console.log(S.dim(` available: ${zt.map(a=>a.name).join(", ")}`)),process.exit(1)),/^[a-z0-9][a-z0-9_-]*$/.test(e)||(console.log(S.red(` workflow id must be lower-kebab (got "${e}")`)),process.exit(1));let n=new Io;!o.force&&n.get(e)&&(console.log(S.red(` workflow "${e}" already exists. Use --force to overwrite or pick a new id.`)),process.exit(1));let s=$c(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=Yo(s,{filePath:`${e}.yaml`}),c=zo.safeParse(a);if(!c.success){console.log(S.red(` template "${t}" failed schema validation after substitution:`));for(let d of c.error.issues)console.log(` ${d.path.join(".")||"<root>"}: ${d.message}`);process.exit(1)}}catch(a){console.log(S.red(` template parse failed: ${a?.message??a}`)),process.exit(1)}let i=o.json?"json":"yaml",r=gt(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=Yo(s,{filePath:`${e}.yaml`}),c=zo.parse(a);Un(r,JSON.stringify(c,null,2)+`
423
+ `)}else Un(r,s);console.log(),console.log(S.green(` \u2713 scaffolded ${r}`)),console.log(S.dim(` template: ${t}`)),console.log(),console.log(S.dim(" Next:")),console.log(S.dim(` 1. edit ${r}`)),console.log(S.dim(` 2. agentx workflow validate ${r}`)),console.log(S.dim(` 3. agentx workflow run ${e} --watch`)),console.log()});Me.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of zt)console.log(` ${S.cyan(e.name.padEnd(20))} ${S.bold(e.title)}`),console.log(` ${" ".repeat(20)} ${S.dim(e.description)}`);console.log(),console.log(S.dim(" Use: agentx workflow init <id> --template <name>")),console.log()});Me.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=gt(process.cwd(),e);Zs(t)||(console.log(S.red(` file not found: ${t}`)),process.exit(1));let n=ei(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?Yo(n,{filePath:e}):JSON.parse(n)}catch(u){let f=u instanceof nn?u.message:`parse error: ${u?.message??u}`;console.log(S.red(` ${f}`)),process.exit(1)}let r=zo.safeParse(i);if(!r.success){console.log(S.red(" \u2717 schema:"));for(let u of r.error.issues)console.log(` ${u.path.join(".")||"<root>"}: ${u.message}`);process.exit(1)}let a=tn(r.data);if(a.length){console.log(S.red(" \u2717 lint:"));for(let u of a)console.log(` ${u}`);process.exit(1)}let c=new Io,d=s?lp(e).match(/\.yml$/i)?"yml":"yaml":"json",m=gt(c.baseDir,`${r.data.id}.${d}`);if(Un(m,s?n:JSON.stringify(r.data,null,2)+`
424
+ `),console.log(S.green(` \u2713 ${r.data.id} \u2192 ${m}`)),o.reload===!1){console.log(S.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let l=`${String(o.daemon).replace(/\/$/,"")}/reload`;try{let u=await fetch(l,{method:"POST"});u.ok?console.log(S.dim(" \u2713 daemon reloaded")):console.log(S.dim(` daemon /reload returned ${u.status} \u2014 restart manually if needed`))}catch{console.log(S.dim(` daemon not reachable at ${o.daemon} \u2014 start it or restart to pick up the new workflow`))}});Me.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 vt({nodeId:t}).list({workflowId:e,limit:Number(o.limit)});if(!n.length){console.log(S.dim(` no runs yet${e?` for "${e}"`:""}.`));return}console.log();for(let s of n){let i=s.history.at(-1),r=s.pending[0]??(s.status==="completed"?"\u2205":"\u2014"),a=s.status==="running"?S.cyan:s.status==="failed"?S.red:S.green;console.log(` ${S.dim(s.id.slice(0,8))} ${S.bold(s.workflowId)} ${a(r)} ${S.dim(s.status)}`),console.log(` ${S.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${S.dim("home: ")} ${s.homeNode}`),console.log(` ${S.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${S.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(S.dim(` ${n.length} run${n.length===1?"":"s"}.`))});Me.command("run <id-or-file>").description("manually trigger a workflow by id, or load + register + run a YAML/JSON file").option("--input <json>","JSON object merged into the trigger event payload").option("--force","fire even if the trigger isn't `trigger.manual` (uses a synthesized event)",!1).option("--watch","tail per-step traces while the run executes",!1).option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").action(async(e,o)=>{let t={};if(o.input)try{t=JSON.parse(o.input)}catch{console.log(S.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=gt(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&Zs(s)){let c=ei(s,"utf-8"),d=/\.(ya?ml)$/i.test(e),m;try{m=d?Yo(c,{filePath:e}):JSON.parse(c)}catch(b){let v=b instanceof nn?b.message:`parse error: ${b?.message??b}`;console.log(S.red(` ${v}`)),process.exit(1)}let l=zo.safeParse(m);if(!l.success){console.log(S.red(" \u2717 schema:"));for(let b of l.error.issues)console.log(` ${b.path.join(".")||"<root>"}: ${b.message}`);process.exit(1)}let u=tn(l.data);if(u.length){console.log(S.red(" \u2717 lint:"));for(let b of u)console.log(` ${b}`);process.exit(1)}let f=new Io,p=l.data.id.startsWith("_adhoc-")?l.data.id:`_adhoc-${l.data.id}-${Date.now().toString(36)}`,w=d?"yaml":"json",y=gt(f.baseDir,`${p}.${w}`),$=d?c.replace(new RegExp(`^id:\\s*${l.data.id}\\b`,"m"),`id: ${p}`):JSON.stringify({...l.data,id:p},null,2)+`
425
+ `;Un(y,$),n=p,console.log(S.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 m=await c.text();console.log(S.red(` run failed (${c.status}): ${m.slice(0,300)}`)),c.status===409&&console.log(S.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let d=await c.json();a=d.runId,console.log(S.green(` \u2713 run started: ${a||"(unknown id)"}${d.force?S.dim(` (forced, source=${d.source})`):""}`))}catch(c){console.log(S.red(` request to daemon failed: ${c.message}`)),process.exit(1)}o.watch&&a&&await dp({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function dp(e){let o=new Set,t=new Map,n=Date.now(),s=15*60*1e3;for(;Date.now()-n<s;){let i=[];try{let r=await fetch(`${e.daemonUrl}/traces?workflowRunId=${encodeURIComponent(e.runId)}&limit=200`);r.ok&&(i=(await r.json()).traces||[])}catch{}for(let r of i){if(!r.taskId||o.has(r.taskId)||(o.add(r.taskId),t.set(r.taskId,r),e.quiet))continue;let a=r.status||"running",c=a==="ok"?S.green:a==="error"?S.red:S.cyan,d=r.totalTokens!=null?S.dim(`${r.totalTokens}t`):"",m=r.durationMs!=null?S.dim(`${r.durationMs}ms`):"";console.log(` ${c(a.padEnd(5))} ${S.bold(r.nodeId||r.label||"(node)")} ${d} ${m}`),r.error&&console.log(` ${S.red(String(r.error).slice(0,200))}`)}try{let r=await fetch(`${e.daemonUrl}/api/workflows/runs/${encodeURIComponent(e.runId)}`);if(r.ok){let c=(await r.json()).run;if(c&&c.status&&c.status!=="running")return e.quiet||(console.log(),console.log(` ${S.dim("run finished:")} ${c.status}`),console.log(S.dim(` full traces: ${e.daemonUrl}/traces?workflowRunId=${e.runId}`))),Array.from(t.values())}}catch{}await new Promise(r=>setTimeout(r,500))}return e.quiet||console.log(S.yellow(" watch timed out after 15min. Run is still active \u2014 check /traces")),Array.from(t.values())}Me.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}kc(r);return}}catch{}let n;try{let i=await fetch(`${t}/traces?workflowRunId=${encodeURIComponent(e)}&limit=200`);i.ok||(console.log(S.red(` /traces returned ${i.status}`)),process.exit(1)),n=await i.json()}catch(i){console.log(S.red(` daemon request failed: ${i.message}`)),process.exit(1)}let s=n.traces||[];if(s.length===0){console.log(S.yellow(` no traces for "${e}"`)),console.log(S.dim(" (sqlite must be opened \u2014 check 'agentx doctor' if the daemon logged 'sqlite: not opened')"));return}if(o.json){console.log(JSON.stringify(s,null,2));return}console.log(),console.log(S.bold(` ${s.length} step${s.length===1?"":"s"} for run ${e}:`)),console.log();for(let i of s)kc(i)});function kc(e){let o=e.status||"ok",t=o==="ok"?S.green:o==="error"?S.red:S.cyan,n=e.totalTokens!=null?`${e.totalTokens}t`:"\u2014",s=e.durationMs!=null?`${e.durationMs}ms`:"\u2014",i=e.model||"\u2014";console.log(` ${t(o.padEnd(5))} ${S.bold(String(e.nodeId||e.label||"(node)"))}`),console.log(` ${S.dim("taskId:")} ${e.taskId||"\u2014"}`),console.log(` ${S.dim("model:")} ${i}`),console.log(` ${S.dim("tokens:")} ${n} ${S.dim("duration:")} ${s}`),e.error&&console.log(` ${S.dim("error:")} ${S.red(String(e.error).slice(0,300))}`),console.log()}Me.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 vt({nodeId:t}).setStatus(e,"paused")||(console.log(S.yellow(` no such run: ${e}`)),process.exit(1)),console.log(S.green(` \u2713 paused ${e}`))});Me.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 vt({nodeId:t}).setStatus(e,"running")||(console.log(S.yellow(` no such run: ${e}`)),process.exit(1)),console.log(S.green(` \u2713 resumed ${e}`))});Me.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 vt({nodeId:t}).setStatus(e,"canceled")||(console.log(S.yellow(` no such run: ${e}`)),process.exit(1)),console.log(S.green(` \u2713 canceled ${e}`))});import{Command as vc}from"commander";import oe from"chalk";import qo from"prompts";import{readFileSync as gp,existsSync as mp}from"fs";import{resolve as pp}from"path";var Yt=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],oi=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),xc={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 Sc(){let e=pp(process.cwd(),"agentx.json");if(!mp(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(gp(e,"utf-8"))}function up(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?oe.yellow("\u26A0 no signing secret"):oe.green("\u2713 active"):oe.dim("disabled")}function fp(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=oi.has(e.source)?oe.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${oe.cyan(e.id)} ${up(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 co=new vc().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");co.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=Sc(),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(`
435
426
  No webhooks registered. Add one with: agentx webhook add
436
- `));return}console.log();for(let n of t)up(n)});ao.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${Yt.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=$c(),n=Object.keys(t.agents||{}),s=(t.mesh?.peers||[]).map(f=>f.name).filter(Boolean),i=String(o.node||"").trim();if(!n.length&&!i)throw new Error("No local agents configured. Add one with: agentx agent add \u2014 or use --node <peer> to forward to a mesh peer.");let r=(e||"").trim(),a=String(o.source||"").trim(),c=String(o.agent||"").trim(),d=String(o.secretEnv||"").trim(),g=String(o.description||"").trim(),l=o.prompt!==!1;if(!r&&l&&(r=((await Fo({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&&l&&(a=(await Fo({type:"select",name:"source",message:"Source",choices:Yt.map(p=>({title:`${p}${Qs.has(p)?" \u2713 wired":""}`,value:p,description:bc[p]}))})).source),!Yt.includes(a))throw new Error(`Source must be one of: ${Yt.join(", ")}`);if(!c&&l&&(i?c=((await Fo({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await Fo({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.`);!d&&l&&a!=="custom"&&(d=((await Fo({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&l&&(g=((await Fo({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let u=await de(f=>{if(f.webhooks=Array.isArray(f.webhooks)?f.webhooks:[],f.webhooks.find(w=>w.id===r))throw new Error(`Webhook "${r}" already exists.`);let p={id:r,source:a,agentId:c,enabled:!0};d&&(p.secretEnv=d),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")),!d&&a!=="custom"&&console.log(oe.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});ao.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await Fo({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await de(n=>{let s=(n.webhooks||[]).length;if(n.webhooks=(n.webhooks||[]).filter(i=>i.id!==e),n.webhooks.length===s)throw new Error(`Webhook "${e}" not found.`)});if(!t.success)throw new Error(t.error);console.log(oe.green(`\u2713 removed webhook "${e}"`))});function kc(e){return async o=>{let t=await de(n=>{let s=(n.webhooks||[]).find(i=>i.id===o);if(!s)throw new Error(`Webhook "${o}" not found.`);s.enabled=e});if(!t.success)throw new Error(t.error);console.log(oe.green(`\u2713 ${e?"enabled":"disabled"} webhook "${o}"`))}}ao.command("enable <id>").description("enable a webhook entry").action(kc(!0));ao.command("disable <id>").description("disable a webhook entry").action(kc(!1));var Ln=new wc().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");Ln.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await de(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);i.triggers=i.triggers&&typeof i.triggers=="object"?i.triggers:{},i.triggers[o]=t});if(!n.success)throw new Error(n.error);console.log(oe.green(`\u2713 ${e}: ${o} \u2192 ${t}`))});Ln.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await de(n=>{let s=(n.webhooks||[]).find(i=>i.id===e);if(!s)throw new Error(`Webhook "${e}" not found.`);s.triggers&&typeof s.triggers=="object"&&delete s.triggers[o]});if(!t.success)throw new Error(t.error);console.log(oe.green(`\u2713 removed trigger ${o} from "${e}"`))});Ln.command("default <id> <workflowId>").description("set the default workflow when no event-type matches (use '-' to clear)").action(async(e,o)=>{let t=o==="-"||o==="",n=await de(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);t?delete i.defaultWorkflow:i.defaultWorkflow=o});if(!n.success)throw new Error(n.error);console.log(oe.green(`\u2713 ${e}: defaultWorkflow ${t?"cleared":`\u2192 ${o}`}`))});ao.addCommand(Ln);ao.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=Yt.map(t=>({source:t,wired:Qs.has(t),hint:bc[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 fp}from"commander";import te from"chalk";ve();function gt(e){let{summary:o,backupPath:t}=Ko(n=>e(n));console.log(te.green(`
427
+ `));return}console.log();for(let n of t)fp(n)});co.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${Yt.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=Sc(),n=Object.keys(t.agents||{}),s=(t.mesh?.peers||[]).map(f=>f.name).filter(Boolean),i=String(o.node||"").trim();if(!n.length&&!i)throw new Error("No local agents configured. Add one with: agentx agent add \u2014 or use --node <peer> to forward to a mesh peer.");let r=(e||"").trim(),a=String(o.source||"").trim(),c=String(o.agent||"").trim(),d=String(o.secretEnv||"").trim(),m=String(o.description||"").trim(),l=o.prompt!==!1;if(!r&&l&&(r=((await qo({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&&l&&(a=(await qo({type:"select",name:"source",message:"Source",choices:Yt.map(p=>({title:`${p}${oi.has(p)?" \u2713 wired":""}`,value:p,description:xc[p]}))})).source),!Yt.includes(a))throw new Error(`Source must be one of: ${Yt.join(", ")}`);if(!c&&l&&(i?c=((await qo({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await qo({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.`);!d&&l&&a!=="custom"&&(d=((await qo({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!m&&l&&(m=((await qo({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let u=await de(f=>{if(f.webhooks=Array.isArray(f.webhooks)?f.webhooks:[],f.webhooks.find(w=>w.id===r))throw new Error(`Webhook "${r}" already exists.`);let p={id:r,source:a,agentId:c,enabled:!0};d&&(p.secretEnv=d),m&&(p.description=m),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")),!d&&a!=="custom"&&console.log(oe.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});co.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await qo({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await de(n=>{let s=(n.webhooks||[]).length;if(n.webhooks=(n.webhooks||[]).filter(i=>i.id!==e),n.webhooks.length===s)throw new Error(`Webhook "${e}" not found.`)});if(!t.success)throw new Error(t.error);console.log(oe.green(`\u2713 removed webhook "${e}"`))});function Ec(e){return async o=>{let t=await de(n=>{let s=(n.webhooks||[]).find(i=>i.id===o);if(!s)throw new Error(`Webhook "${o}" not found.`);s.enabled=e});if(!t.success)throw new Error(t.error);console.log(oe.green(`\u2713 ${e?"enabled":"disabled"} webhook "${o}"`))}}co.command("enable <id>").description("enable a webhook entry").action(Ec(!0));co.command("disable <id>").description("disable a webhook entry").action(Ec(!1));var Fn=new vc().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");Fn.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await de(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);i.triggers=i.triggers&&typeof i.triggers=="object"?i.triggers:{},i.triggers[o]=t});if(!n.success)throw new Error(n.error);console.log(oe.green(`\u2713 ${e}: ${o} \u2192 ${t}`))});Fn.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await de(n=>{let s=(n.webhooks||[]).find(i=>i.id===e);if(!s)throw new Error(`Webhook "${e}" not found.`);s.triggers&&typeof s.triggers=="object"&&delete s.triggers[o]});if(!t.success)throw new Error(t.error);console.log(oe.green(`\u2713 removed trigger ${o} from "${e}"`))});Fn.command("default <id> <workflowId>").description("set the default workflow when no event-type matches (use '-' to clear)").action(async(e,o)=>{let t=o==="-"||o==="",n=await de(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);t?delete i.defaultWorkflow:i.defaultWorkflow=o});if(!n.success)throw new Error(n.error);console.log(oe.green(`\u2713 ${e}: defaultWorkflow ${t?"cleared":`\u2192 ${o}`}`))});co.addCommand(Fn);co.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=Yt.map(t=>({source:t,wired:oi.has(t),hint:xc[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 hp}from"commander";import te from"chalk";we();function mt(e){let{summary:o,backupPath:t}=Vo(n=>e(n));console.log(te.green(`
437
428
  \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.
438
- `))}function Mn(){try{return L().business||{}}catch{return{}}}var mt=new fp().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");mt.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=Mn();if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o||!o.enabled){console.log(),console.log(te.yellow(" business block not enabled (or missing).")),console.log(te.dim(" Add a `business` key to agentx.json to opt in.")),console.log();return}let t=o.orgChart||{},n=o.projects||[],s=o.contactMap||[];console.log(),console.log(te.bold(" Org chart"));let i=Object.entries(t);if(i.length===0)console.log(te.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?te.dim(` \u2192 reports to ${a.reportsTo}`):"",d=a.schedule?te.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${te.cyan(r)} ${a.role}${c}${d}`)}if(console.log(),console.log(te.bold(` Projects (${n.length})`)),n.length===0)console.log(te.dim(" (empty)"));else for(let r of n){let a=r.pm?te.dim(` \xB7 pm=${r.pm}`):"",c=r.client?te.dim(` \xB7 client=${r.client}`):"";console.log(` ${te.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(te.bold(` Contact map (${s.length})`)),s.length===0)console.log(te.dim(" (empty)"));else for(let r of s){let a=r.chatId?`chatId=${r.chatId}`:r.username?`username=${r.username}`:r.senderId?`senderId=${r.senderId}`:"?",c=r.channel?`${r.channel}/`:"";console.log(` ${te.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?te.dim(` (${r.displayName})`):""}`)}console.log()});var Zs=mt.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");Zs.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=Mn(),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}`):""}`)});Zs.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);gt(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}`:""})`))});Zs.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{gt(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 ei=mt.command("project").description("manage business.projects \u2014 id, pm, client");ei.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=Mn().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())});ei.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)=>{gt(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`})});ei.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{gt(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=mt.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=Mn().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)),gt(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=>{gt(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 hp}from"commander";import Te from"chalk";ve();var yp={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function ti(e){let o=yp[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function Un(){let o=L().business?.standup?.plansDir||".agentx/plans";return new yr(o)}var pt=new hp().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");pt.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=Un(),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(`
439
- `):(console.error(Te.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(t,s);console.log(Te.green(` \u2713 ${t} plan saved \u2192 ${i.path}`));let r=is(s);if(r.length){console.log(Te.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(Te.dim(` \u2022 ${a}`))}});pt.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=Un();if(e){let n=ti(e),s=o.read(n);if(!s){console.log(Te.dim(` No ${n} plan set.`));return}vc(s.tier,s.date,s.content);return}let t=o.resolve();if(!t){console.log(Te.yellow(" No plan set at any tier.")),console.log(Te.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(Te.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}vc(t.tier,t.date,t.content)});pt.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=Un().list(parseInt(e.limit,10)||20);if(!t.length){console.log(Te.dim(" No plans yet."));return}for(let n of t)console.log(` ${Te.cyan(n.tier.padEnd(5))} ${Te.bold(n.date.padEnd(11))} ${Te.dim(n.path)}`)});pt.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=ti(e),n=Un().read(o);if(!n){console.log(Te.dim(` No ${o} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(Te.green(` \u2713 ${o} plan cleared (${n.path})`))});function vc(e,o,t){console.log(Te.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
440
- `))console.log(` ${s}`);console.log();let n=is(t);n.length&&console.log(Te.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as wp}from"commander";import qe from"chalk";ve();function bp(){try{return L().notifications||{}}catch{return{}}}function Fn(e){let{summary:o,backupPath:t}=Ko(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(qe.green(`
429
+ `))}function qn(){try{return D().business||{}}catch{return{}}}var pt=new hp().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");pt.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=qn();if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o||!o.enabled){console.log(),console.log(te.yellow(" business block not enabled (or missing).")),console.log(te.dim(" Add a `business` key to agentx.json to opt in.")),console.log();return}let t=o.orgChart||{},n=o.projects||[],s=o.contactMap||[];console.log(),console.log(te.bold(" Org chart"));let i=Object.entries(t);if(i.length===0)console.log(te.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?te.dim(` \u2192 reports to ${a.reportsTo}`):"",d=a.schedule?te.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${te.cyan(r)} ${a.role}${c}${d}`)}if(console.log(),console.log(te.bold(` Projects (${n.length})`)),n.length===0)console.log(te.dim(" (empty)"));else for(let r of n){let a=r.pm?te.dim(` \xB7 pm=${r.pm}`):"",c=r.client?te.dim(` \xB7 client=${r.client}`):"";console.log(` ${te.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(te.bold(` Contact map (${s.length})`)),s.length===0)console.log(te.dim(" (empty)"));else for(let r of s){let a=r.chatId?`chatId=${r.chatId}`:r.username?`username=${r.username}`:r.senderId?`senderId=${r.senderId}`:"?",c=r.channel?`${r.channel}/`:"";console.log(` ${te.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?te.dim(` (${r.displayName})`):""}`)}console.log()});var ti=pt.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");ti.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=qn(),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}`):""}`)});ti.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);mt(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}`:""})`))});ti.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{mt(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 ni=pt.command("project").description("manage business.projects \u2014 id, pm, client");ni.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=qn().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())});ni.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)=>{mt(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`})});ni.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{mt(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 si=pt.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");si.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let t=qn().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:""}`)}});si.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)),mt(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`})});si.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=>{mt(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 yp}from"commander";import Te from"chalk";we();var wp={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function ii(e){let o=wp[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function Wn(){let o=D().business?.standup?.plansDir||".agentx/plans";return new Ar(o)}var ut=new yp().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");ut.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=ii(e),n=Wn(),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(`
430
+ `):(console.error(Te.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(t,s);console.log(Te.green(` \u2713 ${t} plan saved \u2192 ${i.path}`));let r=ds(s);if(r.length){console.log(Te.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(Te.dim(` \u2022 ${a}`))}});ut.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=Wn();if(e){let n=ii(e),s=o.read(n);if(!s){console.log(Te.dim(` No ${n} plan set.`));return}Ac(s.tier,s.date,s.content);return}let t=o.resolve();if(!t){console.log(Te.yellow(" No plan set at any tier.")),console.log(Te.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(Te.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}Ac(t.tier,t.date,t.content)});ut.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=Wn().list(parseInt(e.limit,10)||20);if(!t.length){console.log(Te.dim(" No plans yet."));return}for(let n of t)console.log(` ${Te.cyan(n.tier.padEnd(5))} ${Te.bold(n.date.padEnd(11))} ${Te.dim(n.path)}`)});ut.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=ii(e),n=Wn().read(o);if(!n){console.log(Te.dim(` No ${o} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(Te.green(` \u2713 ${o} plan cleared (${n.path})`))});function Ac(e,o,t){console.log(Te.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
431
+ `))console.log(` ${s}`);console.log();let n=ds(t);n.length&&console.log(Te.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as bp}from"commander";import qe from"chalk";we();function $p(){try{return D().notifications||{}}catch{return{}}}function Bn(e){let{summary:o,backupPath:t}=Vo(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(qe.green(`
441
432
  \u2713 ${o}`)),t&&console.log(qe.dim(` Backup: ${t}`)),console.log(qe.dim(` Restart the daemon (or POST /reload) for the change to take effect.
442
- `))}var ut=new wp().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");ut.command("show").description("print current notifications config").option("--json","JSON output").action(e=>{let o=bp();if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.destination){let n=o.destination.accountId?` \xB7 account=${o.destination.accountId}`:"";console.log(` destination ${qe.cyan(o.destination.channel+":"+o.destination.chatId)}${qe.dim(n)}`)}else console.log(` destination ${qe.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${qe.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?qe.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?qe.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":qe.dim("off")}`),console.log()});ut.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){Fn(o=>(delete o.destination,"notifications destination cleared"));return}Fn(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})`:""}`))});ut.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(qe.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(qe.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";Fn(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});ut.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(qe.red(" threshold must be a non-negative integer")),process.exit(1)),Fn(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});import{Command as $p}from"commander";import vo from"chalk";import{readdirSync as ni,statSync as xc,unlinkSync as kp,rmSync as vp,existsSync as Sc}from"fs";import{resolve as Ec,join as Ac}from"path";var Oc=[{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 si(e,o){if(!Sc(e))return[];let t=[];for(let n of ni(e,{withFileTypes:!0})){let s=Ac(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...si(s,!0))}return t}var Wn=new $p().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");Wn.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of Oc){let t=Ec(process.cwd(),o.dir),n=si(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=xc(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(` ${vo.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${qn(s).padStart(10)} oldest=${r}`)}console.log(vo.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${qn(e).padStart(10)} total`)),console.log(),console.log(vo.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});Wn.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(vo.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(vo.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?vo.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of Oc){if(n&&r.dir!==n)continue;let a=Ec(process.cwd(),r.dir),c=si(a,!!r.recursive),d=0,g=0;for(let u of c)try{let f=xc(u);if(f.mtimeMs<t&&(g+=f.size,d++,!e.dryRun))try{kp(u)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{Ic(a)}catch{}let l=e.dryRun?"would remove":"removed";console.log(` ${vo.cyan(r.dir.padEnd(22))} ${l} ${String(d).padStart(5)} files (${qn(g)})`),s+=d,i+=g}console.log(),console.log(vo.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${qn(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function Ic(e){if(Sc(e))for(let o of ni(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=Ac(e,o.name);Ic(t);try{ni(t).length===0&&vp(t,{recursive:!1})}catch{}}}function qn(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 xp}from"commander";import U from"chalk";var xo=new xp().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");xo.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new Yo().list();if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(),console.log(U.dim(" No actions yet. Add one with `agentx actions add` or `agentx actions create`.")),console.log();return}console.log();for(let n of t){let s=n.inputs?.length?U.dim(` (${n.inputs.length} input${n.inputs.length===1?"":"s"})`):"",i=n.kind==="shell"?`shell: ${n.command.slice(0,50)}`:`${n.method} ${n.url.slice(0,50)}`;console.log(` ${U.cyan(n.id.padEnd(24))} ${n.title}${s}`),console.log(` ${" ".repeat(24)} ${U.dim(i)}`)}console.log()});xo.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new Yo().get(e);if(n||(console.log(U.red(` no action "${e}"`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),console.log(U.bold(` ${n.title}`)),n.description&&console.log(U.dim(` ${n.description}`)),console.log(),console.log(` id ${n.id}`),console.log(` kind ${n.kind}`),console.log(` timeout ${n.timeoutMs}ms`),n.kind==="shell"?(console.log(` command ${n.command}`),n.cwd&&console.log(` cwd ${n.cwd}`),n.env&&console.log(` env ${JSON.stringify(n.env)}`)):(console.log(` ${n.method.padEnd(9)} ${n.url}`),n.headers&&console.log(` headers ${JSON.stringify(n.headers)}`),n.body&&console.log(` body ${n.body.slice(0,200)}`)),n.inputs.length){console.log(),console.log(U.bold(" Inputs:"));for(let s of n.inputs){let i=s.required?U.red("*"):" ",r=s.defaultValue!==void 0?U.dim(` default=${JSON.stringify(s.defaultValue)}`):"",a=s.description?U.dim(` \u2014 ${s.description}`):"";console.log(` ${i} ${U.cyan(s.name)} (${s.type})${r}${a}`)}}console.log()});xo.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=Sp(o.inputs),n={id:e,title:o.title,description:o.description,inputs:t,timeoutMs:parseInt(o.timeout,10)||3e4,kind:o.kind};if(o.kind==="shell")o.command||(console.log(U.red(" --command required for kind=shell")),process.exit(1)),n.command=o.command,o.cwd&&(n.cwd=o.cwd);else if(o.kind==="http"){if(o.url||(console.log(U.red(" --url required for kind=http")),process.exit(1)),n.url=o.url,n.method=o.method,o.headers)try{n.headers=JSON.parse(o.headers)}catch{console.log(U.red(" --headers must be valid JSON")),process.exit(1)}o.body&&(n.body=o.body)}else console.log(U.red(" --kind must be shell|http")),process.exit(1);let s=Ri.safeParse(n);if(!s.success){console.log(U.red(" validation failed:"));for(let a of s.error.issues)console.log(U.red(` ${a.path.join(".")}: ${a.message}`));process.exit(1)}let r=new Yo().save(s.data);console.log(U.green(`
433
+ `))}var ft=new bp().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");ft.command("show").description("print current notifications config").option("--json","JSON output").action(e=>{let o=$p();if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.destination){let n=o.destination.accountId?` \xB7 account=${o.destination.accountId}`:"";console.log(` destination ${qe.cyan(o.destination.channel+":"+o.destination.chatId)}${qe.dim(n)}`)}else console.log(` destination ${qe.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${qe.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?qe.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?qe.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":qe.dim("off")}`),console.log()});ft.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){Bn(o=>(delete o.destination,"notifications destination cleared"));return}Bn(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})`:""}`))});ft.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(qe.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(qe.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";Bn(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});ft.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(qe.red(" threshold must be a non-negative integer")),process.exit(1)),Bn(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});import{Command as kp}from"commander";import xo from"chalk";import{readdirSync as ri,statSync as Oc,unlinkSync as vp,rmSync as xp,existsSync as Ic}from"fs";import{resolve as jc,join as Cc}from"path";var Tc=[{dir:".agentx/sessions",label:"Per-day session JSON"},{dir:".agentx/drift",label:"Drift snapshots",recursive:!0},{dir:".agentx/router",label:"Router-decision logs",recursive:!0},{dir:".agentx/patterns",label:"Self-improving pattern store",recursive:!0}];function ai(e,o){if(!Ic(e))return[];let t=[];for(let n of ri(e,{withFileTypes:!0})){let s=Cc(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...ai(s,!0))}return t}var Hn=new kp().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");Hn.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of Tc){let t=jc(process.cwd(),o.dir),n=ai(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=Oc(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(` ${xo.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${Jn(s).padStart(10)} oldest=${r}`)}console.log(xo.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${Jn(e).padStart(10)} total`)),console.log(),console.log(xo.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});Hn.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(xo.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(xo.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?xo.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of Tc){if(n&&r.dir!==n)continue;let a=jc(process.cwd(),r.dir),c=ai(a,!!r.recursive),d=0,m=0;for(let u of c)try{let f=Oc(u);if(f.mtimeMs<t&&(m+=f.size,d++,!e.dryRun))try{vp(u)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{Nc(a)}catch{}let l=e.dryRun?"would remove":"removed";console.log(` ${xo.cyan(r.dir.padEnd(22))} ${l} ${String(d).padStart(5)} files (${Jn(m)})`),s+=d,i+=m}console.log(),console.log(xo.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${Jn(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function Nc(e){if(Ic(e))for(let o of ri(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=Cc(e,o.name);Nc(t);try{ri(t).length===0&&xp(t,{recursive:!1})}catch{}}}function Jn(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 Sp}from"commander";import U from"chalk";var So=new Sp().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");So.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new Ko().list();if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(),console.log(U.dim(" No actions yet. Add one with `agentx actions add` or `agentx actions create`.")),console.log();return}console.log();for(let n of t){let s=n.inputs?.length?U.dim(` (${n.inputs.length} input${n.inputs.length===1?"":"s"})`):"",i=n.kind==="shell"?`shell: ${n.command.slice(0,50)}`:`${n.method} ${n.url.slice(0,50)}`;console.log(` ${U.cyan(n.id.padEnd(24))} ${n.title}${s}`),console.log(` ${" ".repeat(24)} ${U.dim(i)}`)}console.log()});So.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new Ko().get(e);if(n||(console.log(U.red(` no action "${e}"`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),console.log(U.bold(` ${n.title}`)),n.description&&console.log(U.dim(` ${n.description}`)),console.log(),console.log(` id ${n.id}`),console.log(` kind ${n.kind}`),console.log(` timeout ${n.timeoutMs}ms`),n.kind==="shell"?(console.log(` command ${n.command}`),n.cwd&&console.log(` cwd ${n.cwd}`),n.env&&console.log(` env ${JSON.stringify(n.env)}`)):(console.log(` ${n.method.padEnd(9)} ${n.url}`),n.headers&&console.log(` headers ${JSON.stringify(n.headers)}`),n.body&&console.log(` body ${n.body.slice(0,200)}`)),n.inputs.length){console.log(),console.log(U.bold(" Inputs:"));for(let s of n.inputs){let i=s.required?U.red("*"):" ",r=s.defaultValue!==void 0?U.dim(` default=${JSON.stringify(s.defaultValue)}`):"",a=s.description?U.dim(` \u2014 ${s.description}`):"";console.log(` ${i} ${U.cyan(s.name)} (${s.type})${r}${a}`)}}console.log()});So.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=Ep(o.inputs),n={id:e,title:o.title,description:o.description,inputs:t,timeoutMs:parseInt(o.timeout,10)||3e4,kind:o.kind};if(o.kind==="shell")o.command||(console.log(U.red(" --command required for kind=shell")),process.exit(1)),n.command=o.command,o.cwd&&(n.cwd=o.cwd);else if(o.kind==="http"){if(o.url||(console.log(U.red(" --url required for kind=http")),process.exit(1)),n.url=o.url,n.method=o.method,o.headers)try{n.headers=JSON.parse(o.headers)}catch{console.log(U.red(" --headers must be valid JSON")),process.exit(1)}o.body&&(n.body=o.body)}else console.log(U.red(" --kind must be shell|http")),process.exit(1);let s=Di.safeParse(n);if(!s.success){console.log(U.red(" validation failed:"));for(let a of s.error.issues)console.log(U.red(` ${a.path.join(".")}: ${a.message}`));process.exit(1)}let r=new Ko().save(s.data);console.log(U.green(`
443
434
  \u2713 action "${r.id}" saved (${r.kind}).`)),console.log(U.dim(` Test: agentx actions run ${r.id}
444
- `))});xo.command("remove <id>").alias("rm").description("delete an action").action(e=>{new Yo().delete(e)||(console.log(U.red(` no action "${e}"`)),process.exit(1)),console.log(U.green(` \u2713 action "${e}" removed`))});xo.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 Yo().get(e);n||(console.log(U.red(` no action "${e}"`)),process.exit(1));let s={};for(let i of o.input||[]){let r=i.indexOf("=");r<0&&(console.log(U.red(` --input "${i}" must be key=value`)),process.exit(1)),s[i.slice(0,r)]=i.slice(r+1)}try{let i=await Ni(n,s);if(o.json){console.log(JSON.stringify(i,null,2));return}console.log(),console.log(` ${i.ok?U.green("\u2713 ok"):U.red("\u2717 failed")} status=${i.status} ${i.durationMs}ms`),console.log(),i.output&&(console.log(U.dim(" --- output ---")),console.log(i.output)),i.errors&&(console.log(U.dim(" --- errors ---")),console.log(U.red(i.errors))),console.log(),i.ok||process.exit(1)}catch(i){console.log(U.red(` ${i.message}`)),process.exit(1)}});xo.command("builtin [name]").description("list registered built-in actions, or run one with --input").option("--input <json>","JSON input matching the action's inputSchema").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output (omit chrome)").option("--schema","show the action's input/output schema instead of running it").action(async(e,o)=>{let t=String(o.daemon).replace(/\/+$/,"");if(!e){try{let s=await fetch(`${t}/api/actions/builtin`);s.ok||(console.log(U.red(` list failed (${s.status}): ${(await s.text()).slice(0,200)}`)),process.exit(1));let r=(await s.json()).actions||[];if(o.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(U.dim(" No built-in actions registered. Daemon may not be running, or registerAllBuiltins() didn't fire at boot."));return}console.log(),console.log(U.bold(" Built-in typed actions")),console.log(U.dim(" Invoke: agentx actions builtin <name> --input '<json>'")),console.log();for(let a of r){let c=a.timeoutMs?U.dim(` (timeout=${Math.round(a.timeoutMs/1e3)}s)`):"";console.log(` ${U.cyan(a.name.padEnd(22))} ${a.description||""}${c}`)}console.log()}catch(s){console.log(U.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}return}if(o.schema){try{let r=((await(await fetch(`${t}/api/actions/builtin`)).json()).actions||[]).find(a=>a.name===e);if(r||(console.log(U.red(` unknown action: ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(U.bold(` ${r.name}`)),r.description&&console.log(U.dim(` ${r.description}`)),console.log(),console.log(U.dim(" --- input schema ---")),console.log(JSON.stringify(r.inputSchema??{},null,2)),r.outputSchema&&(console.log(),console.log(U.dim(" --- output schema ---")),console.log(JSON.stringify(r.outputSchema,null,2))),console.log()}catch(s){console.log(U.red(` schema fetch failed: ${s.message||s}`)),process.exit(1)}return}let n={};if(o.input)try{n=JSON.parse(o.input)}catch(s){console.log(U.red(` --input must be valid JSON: ${s.message}`)),process.exit(1)}try{let s=await fetch(`${t}/api/actions/builtin/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json().catch(()=>({}));if(s.ok||(o.json&&(console.log(JSON.stringify(i,null,2)),process.exit(1)),console.log(U.red(` action failed (${s.status}): ${i.error||JSON.stringify(i).slice(0,300)}`)),process.exit(1)),o.json){console.log(JSON.stringify(i,null,2));return}console.log(JSON.stringify(i,null,2))}catch(s){console.log(U.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}});function Sp(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}ve();import{Command as Ep}from"commander";import X from"chalk";var Cc=new Ep().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=L(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(X.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(X.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(X.green(" connected \u2014 Ctrl-C to stop")),console.log("");let a=r.body.getReader(),c=new TextDecoder,d="";for(;;){let{done:g,value:l}=await a.read();if(g)break;d+=c.decode(l,{stream:!0});let u;for(;(u=d.indexOf(`
435
+ `))});So.command("remove <id>").alias("rm").description("delete an action").action(e=>{new Ko().delete(e)||(console.log(U.red(` no action "${e}"`)),process.exit(1)),console.log(U.green(` \u2713 action "${e}" removed`))});So.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 Ko().get(e);n||(console.log(U.red(` no action "${e}"`)),process.exit(1));let s={};for(let i of o.input||[]){let r=i.indexOf("=");r<0&&(console.log(U.red(` --input "${i}" must be key=value`)),process.exit(1)),s[i.slice(0,r)]=i.slice(r+1)}try{let i=await Pi(n,s);if(o.json){console.log(JSON.stringify(i,null,2));return}console.log(),console.log(` ${i.ok?U.green("\u2713 ok"):U.red("\u2717 failed")} status=${i.status} ${i.durationMs}ms`),console.log(),i.output&&(console.log(U.dim(" --- output ---")),console.log(i.output)),i.errors&&(console.log(U.dim(" --- errors ---")),console.log(U.red(i.errors))),console.log(),i.ok||process.exit(1)}catch(i){console.log(U.red(` ${i.message}`)),process.exit(1)}});So.command("builtin [name]").description("list registered built-in actions, or run one with --input").option("--input <json>","JSON input matching the action's inputSchema").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output (omit chrome)").option("--schema","show the action's input/output schema instead of running it").action(async(e,o)=>{let t=String(o.daemon).replace(/\/+$/,"");if(!e){try{let s=await fetch(`${t}/api/actions/builtin`);s.ok||(console.log(U.red(` list failed (${s.status}): ${(await s.text()).slice(0,200)}`)),process.exit(1));let r=(await s.json()).actions||[];if(o.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(U.dim(" No built-in actions registered. Daemon may not be running, or registerAllBuiltins() didn't fire at boot."));return}console.log(),console.log(U.bold(" Built-in typed actions")),console.log(U.dim(" Invoke: agentx actions builtin <name> --input '<json>'")),console.log();for(let a of r){let c=a.timeoutMs?U.dim(` (timeout=${Math.round(a.timeoutMs/1e3)}s)`):"";console.log(` ${U.cyan(a.name.padEnd(22))} ${a.description||""}${c}`)}console.log()}catch(s){console.log(U.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}return}if(o.schema){try{let r=((await(await fetch(`${t}/api/actions/builtin`)).json()).actions||[]).find(a=>a.name===e);if(r||(console.log(U.red(` unknown action: ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(U.bold(` ${r.name}`)),r.description&&console.log(U.dim(` ${r.description}`)),console.log(),console.log(U.dim(" --- input schema ---")),console.log(JSON.stringify(r.inputSchema??{},null,2)),r.outputSchema&&(console.log(),console.log(U.dim(" --- output schema ---")),console.log(JSON.stringify(r.outputSchema,null,2))),console.log()}catch(s){console.log(U.red(` schema fetch failed: ${s.message||s}`)),process.exit(1)}return}let n={};if(o.input)try{n=JSON.parse(o.input)}catch(s){console.log(U.red(` --input must be valid JSON: ${s.message}`)),process.exit(1)}try{let s=await fetch(`${t}/api/actions/builtin/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json().catch(()=>({}));if(s.ok||(o.json&&(console.log(JSON.stringify(i,null,2)),process.exit(1)),console.log(U.red(` action failed (${s.status}): ${i.error||JSON.stringify(i).slice(0,300)}`)),process.exit(1)),o.json){console.log(JSON.stringify(i,null,2));return}console.log(JSON.stringify(i,null,2))}catch(s){console.log(U.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}});function Ep(e){if(!e)return[];let o=[];for(let t of e.split(",").map(n=>n.trim()).filter(Boolean)){let n=t.endsWith("!"),s=n?t.slice(0,-1):t,i=s.indexOf(":"),r=i>=0?s.slice(0,i):s,a=i>=0?s.slice(i+1):"string";o.push({name:r,type:a,required:n})}return o}we();import{Command as Ap}from"commander";import Q from"chalk";var Rc=new Ap().name("watch").description("stream live daemon events \u2014 workflow runs, user tasks, signals, mesh health").option("-c, --config <path>","daemon config file").option("-t, --type <kinds>","comma-separated event kinds (run,task,signal,mesh,channel,status)").option("-w, --workflow <id>","only events for this workflow id").option("-a, --actor <id>","only task events involving this actor id").option("-r, --run <id>","only events for this run id").option("--channel <name>","only channel events on this channel (telegram/whatsapp/\u2026)").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let r=D(e.config);o||(o=r.dashboard?.daemonUrl||""),t||(t=r.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n=[];typeof e.type=="string"&&n.push(`type=${encodeURIComponent(e.type)}`),typeof e.workflow=="string"&&n.push(`workflow=${encodeURIComponent(e.workflow)}`),typeof e.actor=="string"&&n.push(`actor=${encodeURIComponent(e.actor)}`),typeof e.run=="string"&&n.push(`run=${encodeURIComponent(e.run)}`),typeof e.channel=="string"&&n.push(`channel=${encodeURIComponent(e.channel)}`);let s=`${o.replace(/\/+$/,"")}/events${n.length?`?${n.join("&")}`:""}`;console.log(Q.dim(` connecting to ${s}`));let i={Accept:"text/event-stream"};t&&(i.Authorization=`Bearer ${t}`);try{let r=await fetch(s,{headers:i});(!r.ok||!r.body)&&(console.error(Q.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(Q.green(" connected \u2014 Ctrl-C to stop")),console.log("");let a=r.body.getReader(),c=new TextDecoder,d="";for(;;){let{done:m,value:l}=await a.read();if(m)break;d+=c.decode(l,{stream:!0});let u;for(;(u=d.indexOf(`
445
436
 
446
- `))>=0;){let f=d.slice(0,u);d=d.slice(u+2),Ap(f)}}}catch(r){console.error(X.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function Ap(e){let o="message",t="";for(let i of e.split(`
447
- `))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?X.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=X.cyan(n.phase?.padEnd(9)??"run"),r=X.bold(n.workflowId??""),a=X.dim((n.runId??"").slice(0,8)),c=n.nodeId?X.yellow(n.nodeId):"",d=n.note?X.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${d}`);break}case"task":{let i=X.magenta(`task.${n.phase}`.padEnd(14)),r=X.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?X.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${X.cyan(a)} ${c}`);break}case"signal":{let i=X.green("signal".padEnd(9)),r=X.bold(n.name),a=X.dim(`(${n.scope})`),c=n.workflowId?X.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=X.blue("mesh".padEnd(9)),r=X.bold(n.peer),a=n.healthy?X.green("\u2713 healthy"):X.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${X.dim(n.delta??"")}`);break}case"channel":{let i=X.yellow("channel".padEnd(9)),r=n.direction==="in"?X.cyan("\u2190"):X.magenta("\u2192"),a=X.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?X.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(X.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 Ip}from"commander";import Bn from"chalk";import{spawn as Cp}from"node:child_process";import{execFileSync as Op}from"node:child_process";function jc(e=()=>Op("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 Tc=new Ip().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(Bn.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-CAGQYJML.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:jc();if(n?.ok){let{fetchAgents:d}=await import("./client-CAGQYJML.js"),g=await d(t);if(!g.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let l=e.agent||g[0].id;if(!g.some(y=>y.id===l))throw new Error(`Unknown AgentX agent: ${l}`);let 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/${l}`,providers:{...u.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:f}}})};console.error(Bn.dim(`Opening ${n.version} with AgentX model ${l}.`));let w=Cp("opencode",["--standalone"],{stdio:"inherit",env:p});await new Promise((y,$)=>{w.once("error",$),w.once("exit",b=>b===0?y():$(new Error(`OpenCode exited with code ${b??"unknown"}`)))});return}n&&!n.ok&&(console.error(Bn.yellow(n.reason)),console.error(Bn.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-QHPZXA42.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 jp}from"commander";import K from"chalk";import{randomUUID as _c}from"crypto";import{createInterface as Tp}from"node:readline/promises";import Rp from"ora";import Jn from"chalk";function Rc(e){console.error(),console.error(Jn.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(Jn.dim(` ${e.why}`)),console.error(),console.error(` Use ${Jn.cyan(e.instead)} instead.`),e.note&&console.error(Jn.dim(` ${e.note}`)),console.error()}var Nc={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 Dc=new jp().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)=>{Rc({what:"agentx chat",...Nc});let t=Ar({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${_c().slice(0,12)}`,r=[];try{r=await an(t)}catch(g){console.error(K.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(K.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(K.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(K.red(` unknown agent: @${n}`)),console.error(K.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(K.dim(` no agent given \u2014 defaulting to @${n}`))),process.stdout.isTTY&&process.stdin.isTTY){let{render:g}=await import("ink"),{ChatApp:l}=await import("./ChatApp-EAHHH365.js"),u=(await import("react")).default;await g(u.createElement(l,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}_p(t.baseUrl,n,i,s);let a=Tp({input:process.stdin,output:process.stdout}),c=!1,d=!1;for(a.on("close",()=>{if(c){d=!0;return}console.log(K.dim(`
448
- bye`)),process.exit(0)});;){let g;try{g=(await a.question(K.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(K.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${_c().slice(0,12)}`,console.log(K.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?K.green("\u25CF"):K.dim("\u25CB");console.log(` ${y} @${w.id} ${K.dim(w.tier)} ${w.model??""}`)}}catch(p){console.error(K.red(` failed to list agents: ${p?.message||p}`))}continue}if(g.startsWith("/agent ")){let p=g.slice(7).replace(/^@/,"").trim();if(!p){console.log(K.red(" usage: /agent <id>"));continue}try{if(!(await an(t)).find(y=>y.id===p)){console.log(K.red(` unknown agent: @${p}`));continue}n=p,console.log(K.dim(` now talking to @${n}`))}catch(w){console.error(K.red(` failed to switch agent: ${w?.message||w}`))}continue}if(g.startsWith("/")){console.log(K.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(K.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let l=Rp({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),f=Np(n);try{let p=await Or(t,n,g,{channel:s,chatId:i,onText:y=>{l.stop(),f.text(y)},onThinking:()=>{},onTool:y=>{l.stop(),f.tool(y)}});l.stop();let w=Math.round((Date.now()-u)/100)/10;p.error?f.finishError(p.error):f.finish(w,p.usage)}catch(p){l.stop(),f.finishError(p?.message||String(p))}finally{c=!1}if(d){console.log(K.dim(" bye"));return}}});function Np(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${K.green(`@${e}`)}
437
+ `))>=0;){let f=d.slice(0,u);d=d.slice(u+2),Op(f)}}}catch(r){console.error(Q.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function Op(e){let o="message",t="";for(let i of e.split(`
438
+ `))i.startsWith("event: ")?o=i.slice(7):i.startsWith("data: ")&&(t=i.slice(6));if(!t)return;let n={};try{n=JSON.parse(t)}catch{console.log(`${o}: ${t}`);return}let s=n.at?Q.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=Q.cyan(n.phase?.padEnd(9)??"run"),r=Q.bold(n.workflowId??""),a=Q.dim((n.runId??"").slice(0,8)),c=n.nodeId?Q.yellow(n.nodeId):"",d=n.note?Q.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${d}`);break}case"task":{let i=Q.magenta(`task.${n.phase}`.padEnd(14)),r=Q.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?Q.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${Q.cyan(a)} ${c}`);break}case"signal":{let i=Q.green("signal".padEnd(9)),r=Q.bold(n.name),a=Q.dim(`(${n.scope})`),c=n.workflowId?Q.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=Q.blue("mesh".padEnd(9)),r=Q.bold(n.peer),a=n.healthy?Q.green("\u2713 healthy"):Q.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${Q.dim(n.delta??"")}`);break}case"channel":{let i=Q.yellow("channel".padEnd(9)),r=n.direction==="in"?Q.cyan("\u2190"):Q.magenta("\u2192"),a=Q.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?Q.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(Q.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${o} ${JSON.stringify(n)}`)}}import{Command as jp}from"commander";import Gn from"chalk";import{spawn as Cp}from"node:child_process";import{execFileSync as Ip}from"node:child_process";function _c(e=()=>Ip("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 Dc=new jp().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(Gn.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-APAWETTA.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:_c();if(n?.ok){let{fetchAgents:d}=await import("./client-APAWETTA.js"),m=await d(t);if(!m.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let l=e.agent||m[0].id;if(!m.some(y=>y.id===l))throw new Error(`Unknown AgentX agent: ${l}`);let u={};try{u=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(m.map(y=>[y.id,{name:`AgentX ${y.name||y.id}`}])),p={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...u,model:`agentx/${l}`,providers:{...u.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:f}}})};console.error(Gn.dim(`Opening ${n.version} with AgentX model ${l}.`));let w=Cp("opencode",["--standalone"],{stdio:"inherit",env:p});await new Promise((y,$)=>{w.once("error",$),w.once("exit",b=>b===0?y():$(new Error(`OpenCode exited with code ${b??"unknown"}`)))});return}n&&!n.ok&&(console.error(Gn.yellow(n.reason)),console.error(Gn.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-K5J52F7O.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 Tp}from"commander";import K from"chalk";import{randomUUID as Mc}from"crypto";import{createInterface as Np}from"node:readline/promises";import Rp from"ora";import zn from"chalk";function Pc(e){console.error(),console.error(zn.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(zn.dim(` ${e.why}`)),console.error(),console.error(` Use ${zn.cyan(e.instead)} instead.`),e.note&&console.error(zn.dim(` ${e.note}`)),console.error()}var Lc={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 Uc=new Tp().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)=>{Pc({what:"agentx chat",...Lc});let t=Dr({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${Mc().slice(0,12)}`,r=[];try{r=await pn(t)}catch(m){console.error(K.red(` cannot reach daemon at ${t.baseUrl}: ${m?.message||m}`)),console.error(K.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(K.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(m=>m.id===n)||(console.error(K.red(` unknown agent: @${n}`)),console.error(K.dim(` registered: ${r.map(m=>`@${m.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(K.dim(` no agent given \u2014 defaulting to @${n}`))),process.stdout.isTTY&&process.stdin.isTTY){let{render:m}=await import("ink"),{ChatApp:l}=await import("./ChatApp-LRRAPZH7.js"),u=(await import("react")).default;await m(u.createElement(l,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}Dp(t.baseUrl,n,i,s);let a=Np({input:process.stdin,output:process.stdout}),c=!1,d=!1;for(a.on("close",()=>{if(c){d=!0;return}console.log(K.dim(`
439
+ bye`)),process.exit(0)});;){let m;try{m=(await a.question(K.cyan("you \u203A "))).trim()}catch{a.close();return}if(!m)continue;if(m==="/exit"||m==="/quit"){a.close();return}if(m==="/who"){console.log(K.dim(` @${n} chatId=${i} channel=${s}`));continue}if(m==="/clear"){i=`chat-cli:${Mc().slice(0,12)}`,console.log(K.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(m==="/agents"){try{let p=await pn(t);for(let w of p){let y=w.id===n?K.green("\u25CF"):K.dim("\u25CB");console.log(` ${y} @${w.id} ${K.dim(w.tier)} ${w.model??""}`)}}catch(p){console.error(K.red(` failed to list agents: ${p?.message||p}`))}continue}if(m.startsWith("/agent ")){let p=m.slice(7).replace(/^@/,"").trim();if(!p){console.log(K.red(" usage: /agent <id>"));continue}try{if(!(await pn(t)).find(y=>y.id===p)){console.log(K.red(` unknown agent: @${p}`));continue}n=p,console.log(K.dim(` now talking to @${n}`))}catch(w){console.error(K.red(` failed to switch agent: ${w?.message||w}`))}continue}if(m.startsWith("/")){console.log(K.red(` unknown command: ${m.split(/\s+/)[0]}`)),console.log(K.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let l=Rp({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),f=_p(n);try{let p=await Pr(t,n,m,{channel:s,chatId:i,onText:y=>{l.stop(),f.text(y)},onThinking:()=>{},onTool:y=>{l.stop(),f.tool(y)}});l.stop();let w=Math.round((Date.now()-u)/100)/10;p.error?f.finishError(p.error):f.finish(w,p.usage)}catch(p){l.stop(),f.finishError(p?.message||String(p))}finally{c=!1}if(d){console.log(K.dim(" bye"));return}}});function _p(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${K.green(`@${e}`)}
449
440
  `),o=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)t&&a!==`
450
441
  `&&(process.stdout.write(" "),t=!1),process.stdout.write(a),a===`
451
442
  `&&(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(`
@@ -460,17 +451,17 @@ agentx wiki questions`,ae=C?.daemon?.port??C?.port??18800;try{let B=await fetch(
460
451
  `))},finishError(r){o&&!t&&process.stdout.write(`
461
452
  `),process.stdout.write(K.red(` \u2717 ${r}
462
453
 
463
- `))}}}function _p(e,o,t,n){console.log(),console.log(K.bold(" agentx chat")),console.log(K.dim(` daemon: ${e} \xB7 channel: ${n} \xB7 chatId: ${t}`)),console.log(K.dim(` agent: @${o} \xB7 /exit to quit \xB7 /agent <id> to switch`)),console.log()}import{Command as Dp}from"commander";import Re from"chalk";import{readFileSync as Pp}from"fs";var Hn=["user","feedback","project","reference"],qo=new Dp().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");qo.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(!Hn.includes(e.type)){console.error(Re.red(` --type must be one of: ${Hn.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await Lp();else try{o=Pp(e.file,"utf-8")}catch(s){console.error(Re.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(Re.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new Ho().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(Re.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});qo.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 Ho().list(e.agent);if(e.type){if(!Hn.includes(e.type)){console.error(Re.red(` --type must be one of: ${Hn.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.length){console.log(Re.dim(` no memories for agent "${e.agent}"${e.type?` of type "${e.type}"`:""}`));return}console.log();let n=null;for(let s of t)s.type!==n&&(console.log(Re.bold(` ${s.type}`)),n=s.type),console.log(` ${Re.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(Re.dim(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});qo.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 Ho().get(o.agent,e);if(!n){console.error(Re.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Re.bold(`${n.type}/${n.name}`)+Re.dim(` (${n.description})`)),console.log(Re.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});qo.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new Ho().remove(o.agent,e)){console.error(Re.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Re.green(` \u2713 memory "${e}" removed`))});qo.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 Ho().indexMarkdown(e.agent);if(!t){console.log(Re.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});async function Lp(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}ol();import ii from"chalk";import{Command as Mp}from"commander";import{resolve as Up}from"path";var Pc=new Mp().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(Up(e.cwd)),e.stdio!==!1?await Wi():(to.error("Only stdio transport is currently supported."),to.info(`Usage: ${ii.green("agentx serve --stdio")} or configure in your MCP client.`),to.break(),to.info("Add to Claude Code:"),to.info(ii.dim(" claude mcp add agentx -- npx agentx serve --stdio")),to.break(),to.info("Add to Cursor/MCP config:"),to.info(ii.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){wr(o)}});import{Command as Fp}from"commander";import ie from"chalk";import{spawn as ri}from"child_process";import{mkdirSync as qp,writeFileSync as Yn,readFileSync as Wp,readdirSync as Bp,rmSync as Mc,openSync as Uc,existsSync as Gn}from"fs";import{resolve as Jp,join as Ne}from"path";import{randomBytes as Hp}from"crypto";var Lc={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 Fc="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",Gp="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function zp(e,o){return[{dir:Ne(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(Lc,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:Ne(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:Ne(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 Yp(e,o,t){let n=Ne(e.dir,"workspaces",e.agentId);qp(n,{recursive:!0}),Yn(Ne(n,"CLAUDE.md"),`# ${e.agentName}
454
+ `))}}}function Dp(e,o,t,n){console.log(),console.log(K.bold(" agentx chat")),console.log(K.dim(` daemon: ${e} \xB7 channel: ${n} \xB7 chatId: ${t}`)),console.log(K.dim(` agent: @${o} \xB7 /exit to quit \xB7 /agent <id> to switch`)),console.log()}import{Command as Pp}from"commander";import Ne from"chalk";import{readFileSync as Lp}from"fs";var Yn=["user","feedback","project","reference"],Wo=new Pp().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");Wo.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(!Yn.includes(e.type)){console.error(Ne.red(` --type must be one of: ${Yn.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await Mp();else try{o=Lp(e.file,"utf-8")}catch(s){console.error(Ne.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(Ne.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new Go().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(Ne.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});Wo.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 Go().list(e.agent);if(e.type){if(!Yn.includes(e.type)){console.error(Ne.red(` --type must be one of: ${Yn.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.length){console.log(Ne.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(Ne.bold(` ${s.type}`)),n=s.type),console.log(` ${Ne.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(Ne.dim(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});Wo.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 Go().get(o.agent,e);if(!n){console.error(Ne.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Ne.bold(`${n.type}/${n.name}`)+Ne.dim(` (${n.description})`)),console.log(Ne.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});Wo.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new Go().remove(o.agent,e)){console.error(Ne.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Ne.green(` \u2713 memory "${e}" removed`))});Wo.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 Go().indexMarkdown(e.agent);if(!t){console.log(Ne.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});async function Mp(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}il();import ci from"chalk";import{Command as Up}from"commander";import{resolve as Fp}from"path";var Fc=new Up().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(Fp(e.cwd)),e.stdio!==!1?await Hi():(no.error("Only stdio transport is currently supported."),no.info(`Usage: ${ci.green("agentx serve --stdio")} or configure in your MCP client.`),no.break(),no.info("Add to Claude Code:"),no.info(ci.dim(" claude mcp add agentx -- npx agentx serve --stdio")),no.break(),no.info("Add to Cursor/MCP config:"),no.info(ci.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){Or(o)}});import{Command as qp}from"commander";import ie from"chalk";import{spawn as li}from"child_process";import{mkdirSync as Wp,writeFileSync as Xn,readFileSync as Bp,readdirSync as Jp,rmSync as Wc,openSync as Bc,existsSync as Kn}from"fs";import{resolve as Hp,join as Re}from"path";import{randomBytes as Gp}from"crypto";var qc={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 Jc="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",zp="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function Yp(e,o){return[{dir:Re(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(qc,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:Re(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:Re(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 Kp(e,o,t){let n=Re(e.dir,"workspaces",e.agentId);Wp(n,{recursive:!0}),Xn(Re(n,"CLAUDE.md"),`# ${e.agentName}
464
455
 
465
456
  ${e.persona}
466
- `),Yn(Ne(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}};Yn(Ne(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function ai(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 ci(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 zn(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
457
+ `),Xn(Re(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}};Xn(Re(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 gi(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 Vn(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
467
458
  `).join(`
468
- `)}`)}var qc=new Fp().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=Jp(process.cwd(),".agentx-demo"),n=zp(t,o),s=Ne(t,"mesh-token"),i=!!e.reuse&&Gn(s)&&Gn(Ne(n[0].dir,"agentx.json")),r=i?Wp(s,"utf8").trim():Hp(24).toString("hex"),a=e.keep||e.reuse,c=[],d=process.argv[1];if((!d||!Gn(d))&&(console.error(ie.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!i){if(Gn(t))for(let f of Bp(t))Mc(Ne(t,f),{recursive:!0,force:!0});for(let f of n)Yp(f,n,r);Yn(s,r+`
469
- `,{mode:384})}console.log(),console.log(ie.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(ie.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(ie.dim(" Run `agentx setup` to wire real agents.\n"));let g=!1,l=f=>{if(!g){g=!0;for(let p of c)try{p.kill("SIGTERM")}catch{}setTimeout(()=>{if(!a)try{Mc(t,{recursive:!0,force:!0})}catch{}process.exit(f)},800)}};process.on("SIGINT",()=>l(0)),process.on("SIGTERM",()=>l(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 $=Uc(Ne(y.dir,"daemon.log"),"a"),b=ri(process.execPath,[d,"daemon","start","-c",Ne(y.dir,"agentx.json")],{cwd:y.dir,env:{...u,MESH_TOKEN:r,AGENTX_DEMO_SCRIPT:Ne(y.dir,"demo-script.json")},stdio:["ignore",$,$]});c.push(b),console.log(ie.dim(` \u25B8 ${y.name} starting on 127.0.0.1:${y.port} (log: ${Ne(y.dir,"daemon.log")})`))}for(let y of n)await ai(`${y.name} /health`,async()=>(await fetch(`http://127.0.0.1:${y.port}/health`)).ok,3e4);console.log(ie.green(" \u2713 three daemons up"));let f=n[0].port+10;{let y=Uc(Ne(n[0].dir,"board.log"),"a"),$=ri(process.execPath,[d,"board","serve","--bind",e.bind],{cwd:n[0].dir,env:{...u,MESH_TOKEN:r},stdio:["ignore",y,y]});c.push($)}await ai("dashboard /live",async()=>(await fetch(`http://127.0.0.1:${f}/live`)).ok,3e4),console.log(ie.green(" \u2713 dashboard up")),await ai("mesh discovery (laptop sees both peers)",async()=>((await(await fetch(`http://127.0.0.1:${n[0].port}/health`)).json()).mesh||[]).filter(v=>v.healthy&&v.skills?.length).length>=2,3e4),console.log(ie.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let p=`http://127.0.0.1:${f}/live`;if(console.log(),console.log(` Dashboard: ${ie.cyan(p)} (all three nodes via the mesh)`),console.log(ie.dim(` Daemon APIs: ${n.map(y=>`127.0.0.1:${y.port}`).join(" \xB7 ")}`)),e.open!==!1){let y=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{ri(y,[p],{stdio:"ignore",detached:!0}).unref()}catch{}}let w=async()=>{console.log(),console.log(ie.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),zn("You \u2192 @cx (laptop-paris)",Fc,ie.cyan);let y=await ci(n[0].port,"/task",{agent:"cx",message:Fc});zn("@cx (laptop-paris)",y.content||"(no content)",ie.green),console.log(),console.log(ie.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let $=await ci(n[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:Gp}),b=typeof $.messageId=="string"?$.messageId:$.content||"(no reply)";zn("@builder (vps-nyc)",b,ie.yellow);let v=await ci(n[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${b}`});zn("@cx (laptop-paris)",v.content||"(no content)",ie.green),console.log(),console.log(ie.dim(` Inspect the run: ${p} \xB7 ledger rows on each node record every dispatch`)),console.log(ie.dim(` Worth your time? A star helps others find it: ${ie.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(i?console.log(ie.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await w(),e.once){console.log(),console.log(ie.dim(" --once: shutting down.")),l(0);return}console.log(),console.log(ie.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{w().catch(y=>console.error(ie.red(` Replay failed: ${y.message}`)))}),process.stdin.resume()}catch(f){console.error(),console.error(ie.red(` Demo failed: ${f.message}`)),console.error(ie.dim(` Node logs: ${n.map(p=>Ne(p.dir,"daemon.log")).join(", ")}`)),l(1)}});import{Command as Kp}from"commander";import{randomUUID as Vp}from"crypto";import{readFileSync as Xp}from"fs";import{resolve as Qp}from"path";ve();var Bc=new Kp().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??Xp(0,"utf8")).trim();t||Wc("no task given (pass it as an argument or on stdin)");let n=L(o.config?Qp(o.config):void 0),s=n.agents[o.agent];s||Wc(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`);let i=(...d)=>console.error("[agentx exec]",...d);if(o.setupWorkspace){let d=n.node.bind.split(":")[1]||"19900";Oi(o.agent,s,d,i)}let r=new qi(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-${Vp()}`,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})+`
459
+ `)}`)}var Hc=new qp().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=Hp(process.cwd(),".agentx-demo"),n=Yp(t,o),s=Re(t,"mesh-token"),i=!!e.reuse&&Kn(s)&&Kn(Re(n[0].dir,"agentx.json")),r=i?Bp(s,"utf8").trim():Gp(24).toString("hex"),a=e.keep||e.reuse,c=[],d=process.argv[1];if((!d||!Kn(d))&&(console.error(ie.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!i){if(Kn(t))for(let f of Jp(t))Wc(Re(t,f),{recursive:!0,force:!0});for(let f of n)Kp(f,n,r);Xn(s,r+`
460
+ `,{mode:384})}console.log(),console.log(ie.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(ie.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(ie.dim(" Run `agentx setup` to wire real agents.\n"));let m=!1,l=f=>{if(!m){m=!0;for(let p of c)try{p.kill("SIGTERM")}catch{}setTimeout(()=>{if(!a)try{Wc(t,{recursive:!0,force:!0})}catch{}process.exit(f)},800)}};process.on("SIGINT",()=>l(0)),process.on("SIGTERM",()=>l(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 $=Bc(Re(y.dir,"daemon.log"),"a"),b=li(process.execPath,[d,"daemon","start","-c",Re(y.dir,"agentx.json")],{cwd:y.dir,env:{...u,MESH_TOKEN:r,AGENTX_DEMO_SCRIPT:Re(y.dir,"demo-script.json")},stdio:["ignore",$,$]});c.push(b),console.log(ie.dim(` \u25B8 ${y.name} starting on 127.0.0.1:${y.port} (log: ${Re(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(ie.green(" \u2713 three daemons up"));let f=n[0].port+10;{let y=Bc(Re(n[0].dir,"board.log"),"a"),$=li(process.execPath,[d,"board","serve","--bind",e.bind],{cwd:n[0].dir,env:{...u,MESH_TOKEN:r},stdio:["ignore",y,y]});c.push($)}await di("dashboard /live",async()=>(await fetch(`http://127.0.0.1:${f}/live`)).ok,3e4),console.log(ie.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(v=>v.healthy&&v.skills?.length).length>=2,3e4),console.log(ie.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let p=`http://127.0.0.1:${f}/live`;if(console.log(),console.log(` Dashboard: ${ie.cyan(p)} (all three nodes via the mesh)`),console.log(ie.dim(` Daemon APIs: ${n.map(y=>`127.0.0.1:${y.port}`).join(" \xB7 ")}`)),e.open!==!1){let y=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{li(y,[p],{stdio:"ignore",detached:!0}).unref()}catch{}}let w=async()=>{console.log(),console.log(ie.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),Vn("You \u2192 @cx (laptop-paris)",Jc,ie.cyan);let y=await gi(n[0].port,"/task",{agent:"cx",message:Jc});Vn("@cx (laptop-paris)",y.content||"(no content)",ie.green),console.log(),console.log(ie.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let $=await gi(n[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:zp}),b=typeof $.messageId=="string"?$.messageId:$.content||"(no reply)";Vn("@builder (vps-nyc)",b,ie.yellow);let v=await gi(n[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${b}`});Vn("@cx (laptop-paris)",v.content||"(no content)",ie.green),console.log(),console.log(ie.dim(` Inspect the run: ${p} \xB7 ledger rows on each node record every dispatch`)),console.log(ie.dim(` Worth your time? A star helps others find it: ${ie.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(i?console.log(ie.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await w(),e.once){console.log(),console.log(ie.dim(" --once: shutting down.")),l(0);return}console.log(),console.log(ie.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{w().catch(y=>console.error(ie.red(` Replay failed: ${y.message}`)))}),process.stdin.resume()}catch(f){console.error(),console.error(ie.red(` Demo failed: ${f.message}`)),console.error(ie.dim(` Node logs: ${n.map(p=>Re(p.dir,"daemon.log")).join(", ")}`)),l(1)}});import{Command as Vp}from"commander";import{randomUUID as Xp}from"crypto";import{readFileSync as Qp}from"fs";import{resolve as Zp}from"path";we();var zc=new Vp().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??Qp(0,"utf8")).trim();t||Gc("no task given (pass it as an argument or on stdin)");let n=D(o.config?Zp(o.config):void 0),s=n.agents[o.agent];s||Gc(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`);let i=(...d)=>console.error("[agentx exec]",...d);if(o.setupWorkspace){let d=n.node.bind.split(":")[1]||"19900";Ci(o.agent,s,d,i)}let r=new Ji(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-${Xp()}`,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})+`
470
461
  `):c.error?console.error(c.error):process.stdout.write(c.content+`
471
- `),process.exit(c.error?1:0)});function Wc(e){console.error(`agentx exec: ${e}`),process.exit(1)}ve();import{Command as Zp}from"commander";import Ee from"chalk";var So=new Zp().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");So.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 Kt("/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(Ee.dim(" no chats cached yet"));return}console.log(),console.log(Ee.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?Ee.cyan("group"):Ee.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Ee.dim(n.jid.padEnd(40))} ${Ee.dim(i)}`)}console.log()}catch(o){ft(o)}});So.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 Kt("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Ee.dim(" no contacts cached yet"));return}console.log(),console.log(Ee.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} ${Ee.dim(i)} ${Ee.dim(n.jid)}`)}console.log()}catch(o){ft(o)}});So.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);li(t,!!e.dryRun)}catch(o){ft(o)}});So.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);li(n,!!o.dryRun)}catch(t){ft(t)}});So.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);li(n,!!o.dryRun)}catch(t){ft(t)}});So.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await Kt("/whatsapp/state"),o=await Kt("/whatsapp/chats"),t=await Kt("/whatsapp/contacts");console.log(),console.log(Ee.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){ft(e)}});function li(e,o){if(console.log(),console.log(Ee.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(Ee.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(Ee.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(Ee.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(Ee.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Ee.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function Jc(){try{let e=L(),[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 Kt(e){let o=await fetch(`${Jc()}${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(`${Jc()}${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 ft(e){console.error(Ee.red(` ${e.message||e}`)),process.exit(1)}ve();import{Command as eu}from"commander";import re from"chalk";import{existsSync as ou,mkdirSync as Hc,writeFileSync as Vt}from"fs";import{join as ht,resolve as tu}from"path";var Xt=new eu().name("plugin").description("manage agentx plugins (Move B)");Xt.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=L().plugins??[];if(console.log(),o.length===0){console.log(re.dim(" No plugins configured.")),console.log(re.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(re.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${re.cyan(t)}`);console.log(),console.log(re.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(re.red(` ${e.message}`)),process.exitCode=1}});Xt.command("init <name>").description("scaffold a new plugin package (npm-publishable, with manifest + setup hook)").option("--cwd <cwd>","directory to create the package under",process.cwd()).option("--description <text>","short package description").option("--force","overwrite an existing directory").action((e,o)=>{/^(@[a-z0-9-]+\/)?[a-z0-9][a-z0-9._-]*$/i.test(e)||(console.log(re.red(` invalid package name "${e}". Use lowercase letters, digits, hyphens; optional @scope/ prefix.`)),process.exit(1));let t=e.startsWith("@")?e.split("/")[1]:e,n=tu(o.cwd,t);ou(n)&&!o.force&&(console.log(re.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),Hc(n,{recursive:!0}),Hc(ht(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;Vt(ht(n,"package.json"),ru(e,s)),Vt(ht(n,"tsconfig.json"),au()),Vt(ht(n,"src/index.ts"),cu(e)),Vt(ht(n,"README.md"),lu(e,s)),Vt(ht(n,".gitignore"),du()),console.log(),console.log(re.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(re.bold(" Next steps:")),console.log(re.dim(` cd ${t}`)),console.log(re.dim(" pnpm install")),console.log(re.dim(" pnpm build")),console.log(re.dim(" pnpm link --global # for local testing")),console.log(re.dim(" # then in your agentx project:")),console.log(re.dim(` pnpm link --global ${e}`)),console.log(re.dim(` agentx config set plugins[0] "${e}"`)),console.log(re.dim(" agentx plugin doctor")),console.log()});Xt.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let o=L().plugins??[];if(console.log(),o.length===0){console.log(re.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await nu(n);s.kind==="ok"?console.log(` ${re.green("\u2713")} ${re.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${re.red("\u2717")} ${re.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(re.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(re.red(` ${e.message}`)),process.exitCode=1}});async function nu(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=su(o);if(!iu(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=tr.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 su(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 iu(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function ru(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)+`
472
- `}function au(){return JSON.stringify({compilerOptions:{target:"es2020",module:"commonjs",lib:["es2020"],declaration:!0,outDir:"dist",strict:!0,esModuleInterop:!0,skipLibCheck:!0,moduleResolution:"node"},include:["src/**/*.ts"]},null,2)+`
473
- `}function cu(e){return`// ${e} \u2014 AgentX plugin
462
+ `),process.exit(c.error?1:0)});function Gc(e){console.error(`agentx exec: ${e}`),process.exit(1)}we();import{Command as eu}from"commander";import Ee from"chalk";var Eo=new eu().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Eo.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 Kt("/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(Ee.dim(" no chats cached yet"));return}console.log(),console.log(Ee.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?Ee.cyan("group"):Ee.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Ee.dim(n.jid.padEnd(40))} ${Ee.dim(i)}`)}console.log()}catch(o){ht(o)}});Eo.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 Kt("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Ee.dim(" no contacts cached yet"));return}console.log(),console.log(Ee.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} ${Ee.dim(i)} ${Ee.dim(n.jid)}`)}console.log()}catch(o){ht(o)}});Eo.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 pi("/whatsapp/ingest",o);mi(t,!!e.dryRun)}catch(o){ht(o)}});Eo.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 pi("/whatsapp/ingest",t);mi(n,!!o.dryRun)}catch(t){ht(t)}});Eo.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 pi("/whatsapp/ingest",t);mi(n,!!o.dryRun)}catch(t){ht(t)}});Eo.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await Kt("/whatsapp/state"),o=await Kt("/whatsapp/chats"),t=await Kt("/whatsapp/contacts");console.log(),console.log(Ee.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){ht(e)}});function mi(e,o){if(console.log(),console.log(Ee.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(Ee.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(Ee.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(Ee.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(Ee.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Ee.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function Yc(){try{let e=D(),[o,t]=e.node.bind.split(":");return`http://${o||"127.0.0.1"}:${t||"19900"}`}catch{return"http://127.0.0.1:19900"}}async function Kt(e){let o=await fetch(`${Yc()}${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 pi(e,o){let t=await fetch(`${Yc()}${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 ht(e){console.error(Ee.red(` ${e.message||e}`)),process.exit(1)}we();import{Command as ou}from"commander";import re from"chalk";import{existsSync as tu,mkdirSync as Kc,writeFileSync as Vt}from"fs";import{join as yt,resolve as nu}from"path";var Xt=new ou().name("plugin").description("manage agentx plugins (Move B)");Xt.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=D().plugins??[];if(console.log(),o.length===0){console.log(re.dim(" No plugins configured.")),console.log(re.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(re.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${re.cyan(t)}`);console.log(),console.log(re.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(re.red(` ${e.message}`)),process.exitCode=1}});Xt.command("init <name>").description("scaffold a new plugin package (npm-publishable, with manifest + setup hook)").option("--cwd <cwd>","directory to create the package under",process.cwd()).option("--description <text>","short package description").option("--force","overwrite an existing directory").action((e,o)=>{/^(@[a-z0-9-]+\/)?[a-z0-9][a-z0-9._-]*$/i.test(e)||(console.log(re.red(` invalid package name "${e}". Use lowercase letters, digits, hyphens; optional @scope/ prefix.`)),process.exit(1));let t=e.startsWith("@")?e.split("/")[1]:e,n=nu(o.cwd,t);tu(n)&&!o.force&&(console.log(re.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),Kc(n,{recursive:!0}),Kc(yt(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;Vt(yt(n,"package.json"),au(e,s)),Vt(yt(n,"tsconfig.json"),cu()),Vt(yt(n,"src/index.ts"),lu(e)),Vt(yt(n,"README.md"),du(e,s)),Vt(yt(n,".gitignore"),gu()),console.log(),console.log(re.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(re.bold(" Next steps:")),console.log(re.dim(` cd ${t}`)),console.log(re.dim(" pnpm install")),console.log(re.dim(" pnpm build")),console.log(re.dim(" pnpm link --global # for local testing")),console.log(re.dim(" # then in your agentx project:")),console.log(re.dim(` pnpm link --global ${e}`)),console.log(re.dim(` agentx config set plugins[0] "${e}"`)),console.log(re.dim(" agentx plugin doctor")),console.log()});Xt.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let o=D().plugins??[];if(console.log(),o.length===0){console.log(re.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await su(n);s.kind==="ok"?console.log(` ${re.green("\u2713")} ${re.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${re.red("\u2717")} ${re.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(re.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(re.red(` ${e.message}`)),process.exitCode=1}});async function su(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=iu(o);if(!ru(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=ir.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 iu(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 ru(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function au(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)+`
463
+ `}function cu(){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)+`
464
+ `}function lu(e){return`// ${e} \u2014 AgentX plugin
474
465
  //
475
466
  // A plugin's default export is { manifest, setup }. The daemon calls
476
467
  // setup(ctx) once at boot. ctx.on() subscribes to the bus; ctx.addChannel()
@@ -506,7 +497,7 @@ const plugin = {
506
497
  }
507
498
 
508
499
  export default plugin
509
- `}function lu(e,o){return`# ${e}
500
+ `}function du(e,o){return`# ${e}
510
501
 
511
502
  ${o}
512
503
 
@@ -533,19 +524,19 @@ agentx plugin doctor
533
524
  \`\`\`
534
525
 
535
526
  Restart the daemon to activate.
536
- `}function du(){return`node_modules/
527
+ `}function gu(){return`node_modules/
537
528
  dist/
538
529
  *.log
539
530
  .env
540
- `}import{Command as gu}from"commander";import Ae from"chalk";import{writeFileSync as mu,mkdirSync as pu,existsSync as Kn,readFileSync as Gc,appendFileSync as zc}from"fs";import{resolve as yt,dirname as Vc}from"path";import{homedir as mi}from"os";var Xc=new gu().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-ISXECD4J.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=hu(t);break;case"bash":s=ku(t);break;case"fish":s=vu(t);break;default:console.error(Ae.red(`unsupported shell: ${n}`)),console.error(Ae.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?yt(String(e.output)):uu(n);pu(Vc(i),{recursive:!0}),mu(i,s),console.log(Ae.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),fu(n,i,!!e.yes)});function uu(e){let o=mi();switch(e){case"zsh":return yt(o,".zsh","completions","_agentx");case"bash":return yt(o,".bash_completion.d","agentx.bash");case"fish":return yt(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function fu(e,o,t){if(e==="zsh"){let n=yt(mi(),".zshrc"),s=Vc(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Kn(n)?Gc(n,"utf-8"):"",c=!a.includes(s),d=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!d){console.log(Ae.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Kn(n)){let g=["","# agentx completion"];c&&g.push(i),d&&g.push(r),zc(n,g.join(`
531
+ `}import{Command as mu}from"commander";import Ae from"chalk";import{writeFileSync as pu,mkdirSync as uu,existsSync as Qn,readFileSync as Vc,appendFileSync as Xc}from"fs";import{resolve as wt,dirname as el}from"path";import{homedir as fi}from"os";var ol=new mu().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-XJEQAWN3.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=yu(t);break;case"bash":s=vu(t);break;case"fish":s=xu(t);break;default:console.error(Ae.red(`unsupported shell: ${n}`)),console.error(Ae.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?wt(String(e.output)):fu(n);uu(el(i),{recursive:!0}),pu(i,s),console.log(Ae.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),hu(n,i,!!e.yes)});function fu(e){let o=fi();switch(e){case"zsh":return wt(o,".zsh","completions","_agentx");case"bash":return wt(o,".bash_completion.d","agentx.bash");case"fish":return wt(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function hu(e,o,t){if(e==="zsh"){let n=wt(fi(),".zshrc"),s=el(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Qn(n)?Vc(n,"utf-8"):"",c=!a.includes(s),d=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!d){console.log(Ae.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Qn(n)){let m=["","# agentx completion"];c&&m.push(i),d&&m.push(r),Xc(n,m.join(`
541
532
  `)+`
542
- `),console.log(Ae.green("\u2713 Patched ~/.zshrc")),console.log(Ae.dim("Reload your shell: exec zsh"));return}console.log(Ae.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Ae.cyan(` ${i}`)),d&&console.log(Ae.cyan(` ${r}`)),console.log(),console.log(Ae.dim("Then reload: exec zsh")),console.log(Ae.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=yt(mi(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((Kn(n)?Gc(n,"utf-8"):"").includes(o)){console.log(Ae.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&Kn(n)){zc(n,`
533
+ `),console.log(Ae.green("\u2713 Patched ~/.zshrc")),console.log(Ae.dim("Reload your shell: exec zsh"));return}console.log(Ae.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Ae.cyan(` ${i}`)),d&&console.log(Ae.cyan(` ${r}`)),console.log(),console.log(Ae.dim("Then reload: exec zsh")),console.log(Ae.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=wt(fi(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((Qn(n)?Vc(n,"utf-8"):"").includes(o)){console.log(Ae.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&Qn(n)){Xc(n,`
543
534
  # agentx completion
544
535
  ${s}
545
- `),console.log(Ae.green("\u2713 Patched ~/.bashrc")),console.log(Ae.dim("Reload your shell: exec bash"));return}console.log(Ae.dim("Add this to ~/.bashrc:")),console.log(Ae.cyan(` ${s}`)),console.log(),console.log(Ae.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(Ae.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function Ue(e){return e._name||e.name()||""}function Eo(e){return e.commands.filter(o=>{let t=Ue(o);return!(!t||t==="help")})}function Qt(e){return e.options.filter(o=>!o.hidden)}function hu(e){let o=[];return o.push("#compdef agentx"),o.push(""),Qc(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
546
- `)}function Yc(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function Qc(e,o,t){let n=Eo(e),i=Qt(e).map(bu).filter(c=>!!c),r=Yc(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($u).join(" ");a.push(` "1: :_values 'command' ${c}"`),a.push(' "*::arg:->args"')}t.push(" _arguments -C \\");for(let c=0;c<a.length;c++){let d=c===a.length-1;t.push(`${a[c]}${d?"":" \\"}`)}if(n.length>0){t.push(""),t.push(" case $state in"),t.push(" (args)"),t.push(" case $line[1] in");for(let c of n){let d=Yc([...o,Ue(c)]);t.push(` (${Ue(c)}) ${d} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)Qc(c,[...o,Ue(c)],t)}function yu(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function wu(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function bu(e){let o=e.short||void 0,t=e.long||void 0;if(!o&&!t)return null;let n=yu(e.description||"");return o&&t?` "(${t} ${o})"{${t},${o}}"[${n}]"`:` "${t||o}[${n}]"`}function $u(e){let o=wu(e.description()||"");return`'${Ue(e)}[${o}]'`}function ku(e){let o=Eo(e),t=[];t.push("# bash completion for agentx"),t.push("_agentx_complete() {"),t.push(" local cur prev words cword"),t.push(" COMPREPLY=()"),t.push(' cur="${COMP_WORDS[COMP_CWORD]}"'),t.push(' prev="${COMP_WORDS[COMP_CWORD-1]}"'),t.push(""),t.push(` local top="${o.map(Ue).join(" ")}"`),t.push(""),t.push(" if [[ $COMP_CWORD -eq 1 ]]; then"),t.push(' COMPREPLY=( $(compgen -W "$top" -- "$cur") )'),t.push(" return 0"),t.push(" fi"),t.push(""),t.push(' local cmd="${COMP_WORDS[1]}"'),t.push(' local sub2="${COMP_WORDS[2]:-}"'),t.push(' case "$cmd" in');for(let n of o){let s=Eo(n).map(Ue),i=Kc(n);if(t.push(` ${Ue(n)})`),s.length>0){t.push(" if [[ $COMP_CWORD -eq 2 ]]; then"),t.push(` COMPREPLY=( $(compgen -W "${s.join(" ")} ${i}" -- "$cur") )`),t.push(" return 0"),t.push(" fi"),t.push(' case "$sub2" in');for(let r of Eo(n)){let a=Kc(r);t.push(` ${Ue(r)})`),t.push(` COMPREPLY=( $(compgen -W "${a}" -- "$cur") )`),t.push(" return 0"),t.push(" ;;")}t.push(" esac")}else t.push(` COMPREPLY=( $(compgen -W "${i}" -- "$cur") )`);t.push(" ;;")}return t.push(" esac"),t.push("}"),t.push(""),t.push("complete -F _agentx_complete agentx"),t.push(""),t.join(`
547
- `)}function Kc(e){let o=[];for(let t of Qt(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function vu(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 Eo(e)){let n=pi(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${Ue(t)}" -d "${n}"`)}o.push("");for(let t of Qt(e)){let n=gi(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of Eo(e)){let n=Ue(t);o.push(`# ${n}`);for(let s of Qt(t)){let i=gi(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of Eo(t)){let i=pi(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${Eo(t).map(Ue).join(" ")}" -a "${Ue(s)}" -d "${i}"`);for(let r of Qt(s)){let a=gi(r,[`__fish_seen_subcommand_from ${Ue(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
548
- `)}function pi(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function gi(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=pi(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 yx(){let e=await br(),o=new xu().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=xr(n);Sr(s)&&vr("cli",s)});for(let t of[Qr,Kr,at,Xo,Ve,kr,jo,wn,$o,Po,yn,Tc,wo,ga,$a,ja,Na,_a,La,qa,Wa,Bt,Pc,Ct,uo,Xc])o.addCommand(t);for(let t of Zc)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Zc.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Su(t,74," "),""].join(`
549
- `)}),o}var Zc=[ee,ct,qo,Ye,Tt,st,Me,ao,ko,Lo,mt,pt,yo,De,Rt,jn,Cc,io,ot,Ir,To,Xt,ys,xo,et,ws,Wn,ut,So,qc,Bc,Dc];function Su(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(`
550
- `)}export{yx as a};
551
- //# sourceMappingURL=chunk-6WGTLDME.js.map
536
+ `),console.log(Ae.green("\u2713 Patched ~/.bashrc")),console.log(Ae.dim("Reload your shell: exec bash"));return}console.log(Ae.dim("Add this to ~/.bashrc:")),console.log(Ae.cyan(` ${s}`)),console.log(),console.log(Ae.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(Ae.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function Ue(e){return e._name||e.name()||""}function Ao(e){return e.commands.filter(o=>{let t=Ue(o);return!(!t||t==="help")})}function Qt(e){return e.options.filter(o=>!o.hidden)}function yu(e){let o=[];return o.push("#compdef agentx"),o.push(""),tl(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
537
+ `)}function Qc(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function tl(e,o,t){let n=Ao(e),i=Qt(e).map($u).filter(c=>!!c),r=Qc(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(ku).join(" ");a.push(` "1: :_values 'command' ${c}"`),a.push(' "*::arg:->args"')}t.push(" _arguments -C \\");for(let c=0;c<a.length;c++){let d=c===a.length-1;t.push(`${a[c]}${d?"":" \\"}`)}if(n.length>0){t.push(""),t.push(" case $state in"),t.push(" (args)"),t.push(" case $line[1] in");for(let c of n){let d=Qc([...o,Ue(c)]);t.push(` (${Ue(c)}) ${d} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)tl(c,[...o,Ue(c)],t)}function wu(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function bu(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function $u(e){let o=e.short||void 0,t=e.long||void 0;if(!o&&!t)return null;let n=wu(e.description||"");return o&&t?` "(${t} ${o})"{${t},${o}}"[${n}]"`:` "${t||o}[${n}]"`}function ku(e){let o=bu(e.description()||"");return`'${Ue(e)}[${o}]'`}function vu(e){let o=Ao(e),t=[];t.push("# bash completion for agentx"),t.push("_agentx_complete() {"),t.push(" local cur prev words cword"),t.push(" COMPREPLY=()"),t.push(' cur="${COMP_WORDS[COMP_CWORD]}"'),t.push(' prev="${COMP_WORDS[COMP_CWORD-1]}"'),t.push(""),t.push(` local top="${o.map(Ue).join(" ")}"`),t.push(""),t.push(" if [[ $COMP_CWORD -eq 1 ]]; then"),t.push(' COMPREPLY=( $(compgen -W "$top" -- "$cur") )'),t.push(" return 0"),t.push(" fi"),t.push(""),t.push(' local cmd="${COMP_WORDS[1]}"'),t.push(' local sub2="${COMP_WORDS[2]:-}"'),t.push(' case "$cmd" in');for(let n of o){let s=Ao(n).map(Ue),i=Zc(n);if(t.push(` ${Ue(n)})`),s.length>0){t.push(" if [[ $COMP_CWORD -eq 2 ]]; then"),t.push(` COMPREPLY=( $(compgen -W "${s.join(" ")} ${i}" -- "$cur") )`),t.push(" return 0"),t.push(" fi"),t.push(' case "$sub2" in');for(let r of Ao(n)){let a=Zc(r);t.push(` ${Ue(r)})`),t.push(` COMPREPLY=( $(compgen -W "${a}" -- "$cur") )`),t.push(" return 0"),t.push(" ;;")}t.push(" esac")}else t.push(` COMPREPLY=( $(compgen -W "${i}" -- "$cur") )`);t.push(" ;;")}return t.push(" esac"),t.push("}"),t.push(""),t.push("complete -F _agentx_complete agentx"),t.push(""),t.join(`
538
+ `)}function Zc(e){let o=[];for(let t of Qt(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function xu(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 Ao(e)){let n=hi(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${Ue(t)}" -d "${n}"`)}o.push("");for(let t of Qt(e)){let n=ui(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of Ao(e)){let n=Ue(t);o.push(`# ${n}`);for(let s of Qt(t)){let i=ui(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of Ao(t)){let i=hi(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${Ao(t).map(Ue).join(" ")}" -a "${Ue(s)}" -d "${i}"`);for(let r of Qt(s)){let a=ui(r,[`__fish_seen_subcommand_from ${Ue(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
539
+ `)}function hi(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function ui(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=hi(e.description||""),r=["complete -c agentx",o.map(a=>`-n "${a}"`).join(" ")];return t&&r.push(`-s ${t}`),n&&r.push(`-l ${n}`),r.push(`-d "${s}"`),r.join(" ")}async function kx(){let e=await Ir(),o=new Su().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=Nr(n);Rr(s)&&Tr("cli",s)});for(let t of[ta,Zr,ct,Qo,Ve,Cr,To,vn,ko,Lo,kn,Dc,bo,pa,va,Na,Da,Pa,qa,Ha,Ga,Bt,Fc,Ct,fo,ol])o.addCommand(t);for(let t of nl)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=nl.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Eu(t,74," "),""].join(`
540
+ `)}),o}var nl=[ee,lt,Wo,Ye,Nt,it,Me,co,vo,Mo,pt,ut,wo,De,Rt,Rn,Rc,ro,tt,Lr,No,Xt,$s,So,ot,ks,Hn,ft,Eo,Hc,zc,Uc];function Eu(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(`
541
+ `)}export{kx as a};
542
+ //# sourceMappingURL=chunk-HPY6OOFO.js.map