agentix-cli 0.35.0 → 0.37.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 (93) hide show
  1. package/apps/mac-helper/Sources/AgentXHelper/Presence.swift +117 -89
  2. package/apps/mac-helper/Sources/AgentXHelper/PresenceTag.swift +147 -0
  3. package/apps/mac-helper/Sources/AgentXHelper/main.swift +3 -1
  4. package/apps/mac-voice/Sources/AgentXVoice/AgentClient.swift +33 -25
  5. package/apps/mac-voice/Sources/AgentXVoice/Config.swift +4 -0
  6. package/apps/mac-voice/Sources/AgentXVoice/Progress.swift +4 -4
  7. package/apps/mac-voice/Sources/AgentXVoice/Speech.swift +81 -13
  8. package/apps/mac-voice/Sources/AgentXVoice/main.swift +114 -68
  9. package/dist/{App-K5J52F7O.js → App-TW5N7JY2.js} +2 -2
  10. package/dist/{ChatApp-LRRAPZH7.js → ChatApp-MRGX7JBT.js} +2 -2
  11. package/dist/{agent-XEXAYH5J.js → agent-FQHWBQP2.js} +2 -2
  12. package/dist/{board-dashboard-CBOESBMD.js → board-dashboard-2YEYVCUS.js} +4 -4
  13. package/dist/{chunk-PBVEYPZB.js → chunk-3SKFX6G3.js} +2 -2
  14. package/dist/{chunk-DXXWYYZI.js → chunk-4ZGX4L6Q.js} +196 -185
  15. package/dist/chunk-4ZGX4L6Q.js.map +1 -0
  16. package/dist/{chunk-WRBW4A2U.js → chunk-ADRAW342.js} +2 -2
  17. package/dist/{chunk-3PL3WLIR.js → chunk-AKIYB3IJ.js} +2 -2
  18. package/dist/{chunk-JSZRGMSA.js → chunk-EJWIRM52.js} +2 -2
  19. package/dist/{chunk-ZSNTLADV.js → chunk-FHF4RA4Q.js} +2 -2
  20. package/dist/{chunk-SYJUZ3F2.js → chunk-GL7VC26K.js} +2 -2
  21. package/dist/{chunk-3TNK7VGH.js → chunk-HEV3AVFJ.js} +2 -2
  22. package/dist/{chunk-FLNN3KSX.js → chunk-IEE475O2.js} +2 -2
  23. package/dist/{chunk-WEN2P4RS.js → chunk-JLEADOCC.js} +2 -2
  24. package/dist/{chunk-GYBYKREN.js → chunk-MC6I6ZLY.js} +2 -2
  25. package/dist/{chunk-4QNZI4WE.js → chunk-N6APC3DF.js} +5 -5
  26. package/dist/{chunk-LLKILWWO.js → chunk-RRLIZLBH.js} +2 -2
  27. package/dist/{chunk-LQFEH3SA.js → chunk-SR6TVIIS.js} +2 -2
  28. package/dist/{chunk-HPY6OOFO.js → chunk-UORMWVLP.js} +150 -142
  29. package/dist/chunk-UORMWVLP.js.map +1 -0
  30. package/dist/chunk-WFKS4O34.js +13 -0
  31. package/dist/chunk-WFKS4O34.js.map +1 -0
  32. package/dist/cli.js +1 -1
  33. package/dist/client-4KD2UA75.js +2 -0
  34. package/dist/config-WN3R3BPU.js +2 -0
  35. package/dist/config-mutator-2FIUL4DA.js +2 -0
  36. package/dist/doctor-BNO46EOR.js +2 -0
  37. package/dist/index.d.ts +129 -1
  38. package/dist/index.js +1 -1
  39. package/dist/index.js.map +1 -1
  40. package/dist/program-Z6EK44PV.js +2 -0
  41. package/dist/query-TKUDIOBZ.js +2 -0
  42. package/dist/{registry-GWN34G4J.js → registry-TDYF7HGH.js} +2 -2
  43. package/dist/{request-planner-V7T6BQU7.js → request-planner-DF74JHQB.js} +2 -2
  44. package/dist/{review-candidates-7QKNMRGU.js → review-candidates-SEAGMKI6.js} +2 -2
  45. package/dist/{routing-BHQXFUSH.js → routing-JKWL3L3Q.js} +2 -2
  46. package/dist/scheduler-7CYBDKQ7.js +2 -0
  47. package/dist/{seat-U57NWHKC.js → seat-C6TOB63Q.js} +2 -2
  48. package/dist/{select-JL3JJJP4.js → select-YB5KF27O.js} +2 -2
  49. package/dist/wiki-7FCINSKJ.js +2 -0
  50. package/package.json +1 -1
  51. package/dist/chunk-DXXWYYZI.js.map +0 -1
  52. package/dist/chunk-HPY6OOFO.js.map +0 -1
  53. package/dist/chunk-LA6AKS4N.js +0 -13
  54. package/dist/chunk-LA6AKS4N.js.map +0 -1
  55. package/dist/client-APAWETTA.js +0 -2
  56. package/dist/config-S3VHHVYW.js +0 -2
  57. package/dist/config-mutator-5B2YWZMK.js +0 -2
  58. package/dist/doctor-SCECRUJ7.js +0 -2
  59. package/dist/program-XJEQAWN3.js +0 -2
  60. package/dist/query-EDW72Q4O.js +0 -2
  61. package/dist/scheduler-LY4RBPB6.js +0 -2
  62. package/dist/wiki-AQ4K3F7V.js +0 -2
  63. /package/dist/{App-K5J52F7O.js.map → App-TW5N7JY2.js.map} +0 -0
  64. /package/dist/{ChatApp-LRRAPZH7.js.map → ChatApp-MRGX7JBT.js.map} +0 -0
  65. /package/dist/{agent-XEXAYH5J.js.map → agent-FQHWBQP2.js.map} +0 -0
  66. /package/dist/{board-dashboard-CBOESBMD.js.map → board-dashboard-2YEYVCUS.js.map} +0 -0
  67. /package/dist/{chunk-PBVEYPZB.js.map → chunk-3SKFX6G3.js.map} +0 -0
  68. /package/dist/{chunk-WRBW4A2U.js.map → chunk-ADRAW342.js.map} +0 -0
  69. /package/dist/{chunk-3PL3WLIR.js.map → chunk-AKIYB3IJ.js.map} +0 -0
  70. /package/dist/{chunk-JSZRGMSA.js.map → chunk-EJWIRM52.js.map} +0 -0
  71. /package/dist/{chunk-ZSNTLADV.js.map → chunk-FHF4RA4Q.js.map} +0 -0
  72. /package/dist/{chunk-SYJUZ3F2.js.map → chunk-GL7VC26K.js.map} +0 -0
  73. /package/dist/{chunk-3TNK7VGH.js.map → chunk-HEV3AVFJ.js.map} +0 -0
  74. /package/dist/{chunk-FLNN3KSX.js.map → chunk-IEE475O2.js.map} +0 -0
  75. /package/dist/{chunk-WEN2P4RS.js.map → chunk-JLEADOCC.js.map} +0 -0
  76. /package/dist/{chunk-GYBYKREN.js.map → chunk-MC6I6ZLY.js.map} +0 -0
  77. /package/dist/{chunk-4QNZI4WE.js.map → chunk-N6APC3DF.js.map} +0 -0
  78. /package/dist/{chunk-LLKILWWO.js.map → chunk-RRLIZLBH.js.map} +0 -0
  79. /package/dist/{chunk-LQFEH3SA.js.map → chunk-SR6TVIIS.js.map} +0 -0
  80. /package/dist/{client-APAWETTA.js.map → client-4KD2UA75.js.map} +0 -0
  81. /package/dist/{config-S3VHHVYW.js.map → config-WN3R3BPU.js.map} +0 -0
  82. /package/dist/{config-mutator-5B2YWZMK.js.map → config-mutator-2FIUL4DA.js.map} +0 -0
  83. /package/dist/{doctor-SCECRUJ7.js.map → doctor-BNO46EOR.js.map} +0 -0
  84. /package/dist/{program-XJEQAWN3.js.map → program-Z6EK44PV.js.map} +0 -0
  85. /package/dist/{query-EDW72Q4O.js.map → query-TKUDIOBZ.js.map} +0 -0
  86. /package/dist/{registry-GWN34G4J.js.map → registry-TDYF7HGH.js.map} +0 -0
  87. /package/dist/{request-planner-V7T6BQU7.js.map → request-planner-DF74JHQB.js.map} +0 -0
  88. /package/dist/{review-candidates-7QKNMRGU.js.map → review-candidates-SEAGMKI6.js.map} +0 -0
  89. /package/dist/{routing-BHQXFUSH.js.map → routing-JKWL3L3Q.js.map} +0 -0
  90. /package/dist/{scheduler-LY4RBPB6.js.map → scheduler-7CYBDKQ7.js.map} +0 -0
  91. /package/dist/{seat-U57NWHKC.js.map → seat-C6TOB63Q.js.map} +0 -0
  92. /package/dist/{select-JL3JJJP4.js.map → select-YB5KF27O.js.map} +0 -0
  93. /package/dist/{wiki-AQ4K3F7V.js.map → wiki-7FCINSKJ.js.map} +0 -0
@@ -1,34 +1,34 @@
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)}
1
+ import{a as Jr,b as hn,g as Hr}from"./chunk-FHF4RA4Q.js";import{b as Ur}from"./chunk-ADRAW342.js";import{a as Qo,b as Mr,f as fn,j as Br}from"./chunk-GL7VC26K.js";import{a as Fr,c as qr,d as Wr}from"./chunk-2TJ5L7CB.js";import{a as Ko}from"./chunk-GV7S5BAX.js";import{e as qi}from"./chunk-GSX4NK2N.js";import{c as Wi}from"./chunk-SZDACK6O.js";import{$ as Cr,A as ds,B as an,C as wr,D as cn,E as gs,F as br,G as ln,H as dn,I as $r,J as kr,K as vr,L as Xo,M as xr,N as gn,O as Sr,P as Er,Q as ms,R as mn,S as pn,T as Ar,U as Or,V as Ir,W as jr,X as Se,Y as un,Z as It,_ as ps,a as Xi,aa as Tr,b as Qi,ba as Nr,ca as Dr,da as hs,ea as ys,fa as Pr,ga as Lr,h as tr,i as nr,j as At,k as rn,l as sr,m as ir,n as rr,o as ar,p as cr,q as lr,r as dr,s as gr,t as mr,u as pr,v as ur,w as fr,x as hr,y as yr,z as Ot}from"./chunk-4ZGX4L6Q.js";import{i as Rr,j as us,k as _r,l as fs}from"./chunk-F6CNF7V3.js";import{a as Zi,d as er,e as or}from"./chunk-AKIYB3IJ.js";import{J as Ki,m as Li,o as zo,q as as,r as Ui,t as po,z as Vi}from"./chunk-N6APC3DF.js";import{b as Yo,c as nn,d as sn,e as Vo,f as Fi,g as jo,h as Et}from"./chunk-IEE475O2.js";import{d as ls,f as zi}from"./chunk-VMDA2SX2.js";import{a as Gi}from"./chunk-QLTM3F7M.js";import{a as Mi,e as Hi}from"./chunk-RRLIZLBH.js";import{f as Bi,g as Ji,h as cs}from"./chunk-76Z4VHDX.js";import{a as de,b as be,c as Co,d as Yi}from"./chunk-3SKFX6G3.js";import{h as Pi}from"./chunk-DWADWDMU.js";import{b as mo,d as tn,f as rs}from"./chunk-MC6I6ZLY.js";import{b as Go,d as Di}from"./chunk-2GIDVZ4H.js";import{a as is,b as xi,c as hl,d as en,e as Si,f as ji,g as wl,h as Ci,i as bl,m as Ho,n as Ni,o as Ri,s as _i,v as Ke,w as St}from"./chunk-SR6TVIIS.js";import{a as Ti,b as $l}from"./chunk-AJONZWLT.js";import{a as io,b as Jo,e as Ai,f as xt}from"./chunk-F4HZTZHW.js";import{a as so,b as fl}from"./chunk-L2WSPY6S.js";import{f as Ei,g as D,h as on,j as we}from"./chunk-WFKS4O34.js";import{g as Oi,k as Ii,l as yl}from"./chunk-BH3GTCZ6.js";import{a as ul}from"./chunk-FIOB3MEX.js";import{Command as kl}from"commander";var Gr=new kl().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 Qi({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 vl}from"commander";import{execFileSync as ro}from"node:child_process";import{cpSync as zr,existsSync as $s,mkdirSync as ws,mkdtempSync as xl,readFileSync as Sl,rmSync as El,writeFileSync as Yr}from"node:fs";import{dirname as bs,join as Ie,resolve as Vr}from"node:path";import{homedir as yn,release as Al,tmpdir as Ol}from"node:os";import{fileURLToPath as Il}from"node:url";import{setTimeout as jl}from"node:timers/promises";function wn(){let e=Ar(process.platform,process.arch,Al());if(e)throw new Error(e)}function jt(){return`gui/${process.getuid()}/${ms}`}function Zo(){return Ie(yn(),"Library/LaunchAgents",`${ms}.plist`)}async function Kr(){try{ro("launchctl",["bootout",jt()],{stdio:"pipe"})}catch{}for(let e=0;e<30;e++){try{ro("launchctl",["print",jt()],{stdio:"pipe"})}catch{return}await jl(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Xr(){if(!$s(Zo()))throw new Error("Run agentx desktop install first.");let e=!0;try{ro("launchctl",["print",jt()],{stdio:"pipe"})}catch{e=!1}e||ro("launchctl",["bootstrap",`gui/${process.getuid()}`,Zo()],{stdio:"pipe"}),ro("launchctl",["kickstart",jt()],{stdio:"pipe"})}function Cl(){let e=bs(Il(import.meta.url));for(let o of[Vr(e,".."),Vr(e,"../.."),process.cwd()])try{if(JSON.parse(Sl(Ie(o,"package.json"),"utf8")).name==="agentix-cli"&&$s(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 et=new vl("desktop").description("install and control the macOS desktop assistant");et.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","agent to use (defaults to the first configured agent)").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{wn();let o=D(),t=Or(o.agents,e.agent),n=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,s=Cl(),i=Ie(yn(),"Applications");if(console.log(`Desktop assistant \u2192 ${Ie(i,mn)}
2
+ Computer-use helper \u2192 ${Ie(i,pn)}
3
3
  Agent \u2192 ${t}
4
4
  Daemon \u2192 ${n}
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.
5
+ Starts at login \u2192 ${Zo()}`),e.dryRun)return;try{ro("xcrun",["--find","swiftc"],{stdio:"pipe"})}catch{throw new Error("Apple command-line tools are required. Run xcode-select --install, finish installation, then retry.")}let r=xl(Ie(Ol(),"agentx-desktop-"));try{for(let g of["mac-helper","mac-voice"])zr(Ie(s,"apps",g),Ie(r,g),{recursive:!0,filter:l=>!l.split("/").includes("build")}),ro("/bin/bash",[Ie(r,g,"build.sh")],{stdio:"inherit"});let a=Ie(yn(),"Library/Logs/agentx-desktop.err.log"),c=Ir({executable:Ie(i,mn,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:t,url:n,helper:jr(yn()),cli:Ie(s,"dist/cli.js"),node:process.execPath,log:a}),d=Ie(r,"desktop.plist");Yr(d,c,{mode:384}),ro("plutil",["-lint",d],{stdio:"pipe"}),await Kr(),ws(i,{recursive:!0});for(let[g,l,p]of[["mac-voice","AgentX Voice.app",mn],["mac-helper",pn,pn]])zr(Ie(r,g,"build",l),Ie(i,p),{recursive:!0});ws(bs(Zo()),{recursive:!0}),ws(bs(a),{recursive:!0}),Yr(Zo(),c,{mode:384}),Xr(),console.log(`Desktop assistant is running. Hold Option\u2013Space to speak; Command\u2013Option\u2013V for smart paste.
6
6
  Allow Microphone for the app and Accessibility / Screen Recording for the helper when macOS asks.
7
- The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{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(`
7
+ The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{El(r,{recursive:!0,force:!0})}});et.command("start").description("start the installed desktop assistant").action(()=>{wn(),Xr(),console.log("Desktop assistant started.")});et.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{wn(),await Kr(),console.log("Desktop assistant stopped.")});et.command("status").description("show the desktop login service status").action(()=>{wn();try{console.log(ro("launchctl",["print",jt()],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log($s(Zo())?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as Pl}from"commander";import{open as Ll}from"fs/promises";import{existsSync as kn,mkdirSync as Tl,readFileSync as vn,writeFileSync as Qr}from"fs";import{homedir as Nl}from"os";import{dirname as Rl,resolve as ks}from"path";var vs="/attach/",Zr="/guard/check";function ea(e,o,t=""){return`curl -s --max-time 3 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${o}${e}${t}`}' 2>/dev/null || true`}function bn(e,o,t){let n={hooks:[{type:"command",command:ea(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function _l(e){return{SessionStart:[bn("/attach/session-start",e,"")],UserPromptSubmit:[bn("/attach/prompt",e)],Stop:[bn("/attach/stop",e)],SessionEnd:[bn("/attach/session-end",e)]}}function Dl(e){let o=ea("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function $n(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function Ct(){return ks(Nl(),".claude/settings.json")}function Tt(e=process.cwd()){for(let o of[e,ks(e,"..")]){let t=ks(o,"agentx.json");if(kn(t))try{let n=JSON.parse(vn(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function oa(e,o={}){let t=o.path??Ct(),n=o.withGuard!==!1,s={};if(kn(t))try{s=JSON.parse(vn(t,"utf-8"))}catch(g){throw new Error(`${t} is not valid JSON (${g?.message}) \u2014 refusing to overwrite it`)}let i=JSON.stringify(s),r=s.hooks??={},a=[];for(let[g,l]of Object.entries(_l(e))){let p=Array.isArray(r[g])?r[g].filter(f=>!$n(f,vs)):[];r[g]=[...p,...l],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(l=>!$n(l,Zr)):[];r.PreToolUse=[...g,...Dl(e)],c=!0}let d=JSON.stringify(s)!==i;return d&&(Tl(Rl(t),{recursive:!0}),Qr(t,`${JSON.stringify(s,null,2)}
8
+ `)),{path:t,changed:d,events:a,guardInstalled:c}}function ta(e={}){let o=e.path??Ct();if(!kn(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(vn(o,"utf-8"))}catch(a){throw new Error(`${o} is not valid JSON (${a?.message}) \u2014 refusing to rewrite it`)}let n=JSON.stringify(t),s=t.hooks,i=[];if(s&&typeof s=="object"){for(let a of Object.keys(s)){if(!Array.isArray(s[a]))continue;let c=a==="PreToolUse"?Zr:vs;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let d=s[a].filter(g=>!$n(g,c));d.length!==s[a].length&&i.push(a),d.length===0?delete s[a]:s[a]=d}Object.keys(s).length===0&&delete t.hooks}let r=JSON.stringify(t)!==n;return r&&Qr(o,`${JSON.stringify(t,null,2)}
9
+ `),{path:o,changed:r,events:i,guardInstalled:!1}}function xn(e=Ct()){if(!kn(e))return!1;try{return!!JSON.parse(vn(e,"utf-8"))?.hooks?.Stop?.some?.(t=>$n(t,vs))}catch{return!1}}var Sn=new Pl("monitor").description("Register external CLI sessions and report ended runs to the briefing"),na=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Tt()}`;async function sa(e,o,t){let n=process.env.MESH_TOKEN,s=await fetch(e.replace(/\/$/,"")+"/monitor/"+o,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify(t),signal:AbortSignal.timeout(8e3)});if(!s.ok)throw new Error(`Monitor HTTP ${s.status}: ${(await s.text()).slice(0,300)}`)}Sn.command("register").requiredOption("--session <id>","Native session ID").requiredOption("--runtime <name>","claude, codex, gemini, opencode, or another CLI").requiredOption("--label <label>","Human-readable task label").option("--url <url>","Daemon URL",na).action(async e=>{try{await sa(e.url,"register",er.parse({id:e.session,runtime:e.runtime,label:e.label})),console.log("Session registered. Report each stopped run with agentx monitor ended.")}catch(o){console.error(o.message),process.exitCode=1}});Sn.command("ended").requiredOption("--session <id>","Registered session ID").requiredOption("--run <id>","Stable unique turn ID; reuse this ID when retrying delivery").requiredOption("--transcript <file>","Local transcript file; only the last 90 KB is submitted").option("--url <url>","Daemon URL",na).action(async e=>{try{let o=await Ll(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 sa(e.url,"ended",or.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 Fu}from"commander";import{Command as Ml}from"commander";we();import O from"chalk";import{existsSync as Ul,readFileSync as Fl}from"fs";async function ql(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 Xe=new Ml().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");Xe.command("start").description("start the daemon (default if no subcommand)").option("-c, --config <path>","path to agentx.json").option("-d, --detach","run in background (detached)").option("--port <port>","override bind port").action(async e=>{if(e.detach){let{spawn:d}=await import("child_process"),{openSync:g,writeFileSync:l,existsSync:p}=await import("fs"),f=process.argv[1];(!f||!p(f))&&(console.error(O.red(` Cannot resolve agentx CLI entrypoint (process.argv[1]=${f||"?"}).`)),console.error(O.dim(" Try running without --detach to see the underlying error.")),process.exit(1));let u=[f,"daemon","start"];e.config&&u.push("-c",e.config),e.port&&u.push("--port",e.port);let w="/tmp/agentx-daemon.log",y;try{y=g(w,"a")}catch(b){console.error(O.red(` Failed to open ${w} for writing: ${b.message}`)),process.exit(1)}let $=d(process.execPath,u,{detached:!0,stdio:["ignore",y,y],cwd:process.cwd()});$.unref(),l("/tmp/agentx-daemon.pid",String($.pid)),console.log(O.green(`Daemon started in background (PID: ${$.pid})`)),console.log(O.dim(` Logs: tail -f ${w}`)),console.log(O.dim(" Stop: agentx daemon stop")),await new Promise(b=>setTimeout(b,1e3));try{process.kill($.pid,0)}catch{console.log(),console.log(O.yellow(` Daemon exited within 1s \u2014 check ${w} for the error:`)),console.log(O.dim(` tail -n 40 ${w}`))}return}let{readFileSync:o,writeFileSync:t,mkdirSync:n,existsSync:s}=await import("fs"),{resolve:i}=await import("path"),r=i(process.cwd(),".agentx");s(r)||n(r,{recursive:!0});let a=i(r,"daemon.pid");if(s(a)){let d=parseInt(o(a,"utf-8").trim(),10);if(d&&d!==process.pid){let g=!1;try{process.kill(d,0),g=!0}catch{}g&&await ql(d)&&(console.error(`Another agentx daemon is already running (PID ${d}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{Wl(i(process.cwd(),".env"))}catch{}await new ys(e.config).start()});function Wl(e){if(!Ul(e))return;let o=Fl(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}}Xe.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"))}});Xe.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 ${Bl(r.uptime)}`)),console.log(),console.log(O.bold(" Agents:"));for(let c of r.agents){let d=c.active>0?O.yellow(` [${c.active} active]`):"",g=c.errors>0?O.red(` (${c.errors} errors)`):"";console.log(` ${O.cyan(c.name)} ${O.dim(`(${c.tier})`)}${d}${g}`),console.log(O.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(O.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let d=c.enabled?O.green("\u25CF"):O.dim("\u25CB"),g=c.nextRun?O.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${d} ${c.id}${g}`)}}if(r.mesh?.length){console.log(),console.log(O.bold(" Mesh:"));for(let c of r.mesh){let d=c.healthy?O.green("\u25CF"):O.red("\u25CF"),g=c.skills?.length?O.dim(` (${c.skills.length} agents)`):"";console.log(` ${d} ${c.peer} ${O.dim(c.peerUrl)}${g}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError")console.log(O.red(" Daemon is not running")),console.log(O.dim(" Start with: agentx daemon start"));else try{let t=D(e.config),n=on(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}`))}}});Xe.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"})});Xe.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 g=a.split(`
13
+ `);a=g.pop()||"";for(let l of g)if(l.startsWith("data: "))try{let p=JSON.parse(l.slice(6)),f=new Date(p.time).toLocaleTimeString(),u=p.message?.replace(/^\[agentx\]\s*/,"")||"";u.includes("executing")?console.log(`${O.dim(f)} ${O.cyan("\u25B6")} ${u}`):u.includes("completed")?console.log(`${O.dim(f)} ${O.green("\u2713")} ${u}`):u.includes("error")||u.includes("Error")?console.log(`${O.dim(f)} ${O.red("\u2717")} ${u}`):u.includes("Routing")?console.log(`${O.dim(f)} ${O.yellow("\u2192")} ${u}`):u.includes("mention")?console.log(`${O.dim(f)} ${O.magenta("@")} ${u}`):u.includes("Skipping")?console.log(`${O.dim(f)} ${O.dim("\u2298")} ${O.dim(u)}`):console.log(`${O.dim(f)} ${u}`)}catch{}else l.startsWith("event: status")}}catch(s){console.log(O.red(` Connection failed: ${s.message}`)),console.log(O.dim(" Is the daemon running? Diagnostic order:")),console.log(O.dim(" 1) agentx daemon status # is the daemon up?")),console.log(O.dim(" 2) tail -n 60 /tmp/agentx-daemon.log # detach-mode crash log")),console.log(O.dim(" 3) journalctl -u agentx -n 60 # systemd-managed installs")),console.log(O.dim(" If the log file is missing, the daemon never started \u2014 re-run without --detach")),console.log(O.dim(" to see the error in the foreground."))}});Xe.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"))}});Xe.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}`))}});Xe.action(async e=>{await new ys(e.config).start()});function Bl(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 Jl}from"commander";import He from"chalk";import{existsSync as Nt,readFileSync as Hl,writeFileSync as ia,mkdirSync as ra}from"fs";import{hostname as aa}from"os";import{resolve as ot}from"path";var ca=new Jl().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=ot(o,"agentx.json"),n=ot(o,".env"),s=ot(o,".agentx/sessions");if(console.log(),console.log(He.bold(" agentx init")),console.log(),Nt(t)&&!e.force){console.log(He.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[ot(o,"agentx.example.json"),ot(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(Nt(c)){r=Hl(c,"utf-8");break}r||(r=JSON.stringify({node:{id:aa().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:aa(),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)),ia(t,r),console.log(He.green(" \u2713 Created agentx.json")),Nt(n)||(ia(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
15
+ `)),console.log(He.green(" \u2713 Created .env template"))),Nt(s)||(ra(s,{recursive:!0}),console.log(He.green(" \u2713 Created .agentx/sessions/")));let a=ot(o,".claude");Nt(a)||(ra(a,{recursive:!0}),console.log(He.green(" \u2713 Created .claude/"))),console.log(),console.log(He.bold(" Next steps:")),console.log(` 1. Edit ${He.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${He.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${He.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${He.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as Gl}from"commander";import To from"chalk";import{spawn as da}from"child_process";import{existsSync as zl}from"fs";import{dirname as Yl,resolve as Vl}from"path";import{fileURLToPath as Kl}from"url";we();var ga=new Gl().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=Mr(),t=e.port?parseInt(e.port,10):Xl(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(To.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(To.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(To.bold(` Opening ${n}`)),console.log(),await Zl(n).catch(()=>!1))console.log(To.dim(" Dashboard is already running.")),e.open!==!1&&la(n);else{console.log(To.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=Ql(),r=da(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&la(n),await new Promise(a=>r.on("exit",()=>a()))}});function Xl(){try{return D().dashboard.port||4202}catch{return 4202}}function Ql(){let e=Vl(Yl(Kl(import.meta.url)),"cli.js");return zl(e)?e:process.argv[1]||e}async function Zl(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}function la(e){let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=da(o,[e],{stdio:"ignore",detached:!0});t.once("error",()=>{console.log(To.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),t.unref()}catch{console.log(To.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as ed}from"commander";import xe from"chalk";var Rt=new ed().name("token").description("scoped API tokens for external access (mesh peers, integrations)");Rt.command("create").description("mint a new token \u2014 prints the secret once, store it somewhere safe").requiredOption("--name <name>","human-readable label (e.g. 'Slack integration')").option("--scope <scopes>","comma-separated scopes (default: dashboard:read)","dashboard:read").option("--expires <days>","expire after N days (default: no expiry)").action(e=>{try{let o=new fn,t=String(e.scope).split(",").map(r=>r.trim()).filter(Boolean),n=e.expires?parseInt(e.expires,10):void 0;if(e.expires&&(!n||n<1))throw new Error("--expires must be a positive integer (days)");let{token:s,record:i}=o.create({name:e.name,scopes:t,expiresInDays:n});console.log(),console.log(xe.bold(" Token created.")),console.log(),console.log(` id: ${xe.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||xe.dim("never")}`),console.log(),console.log(xe.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${xe.green.bold(s)}`),console.log(),console.log(xe.dim(" Use it via the Authorization header:")),console.log(xe.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});Rt.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new fn().list();if(e.length===0){console.log(xe.dim(`
16
16
  No tokens issued.
17
- `));return}console.log();for(let o of e){let t=o.revokedAt?xe.red("revoked"):o.expiresAt&&Date.parse(o.expiresAt)<Date.now()?xe.red("expired"):xe.green("active");console.log(` ${xe.cyan(o.id)} ${t} ${o.name}`),console.log(xe.dim(` prefix: ${o.prefix}\u2026 scopes: ${o.scopes.join(", ")}`)),console.log(xe.dim(` created: ${o.createdAt}${o.expiresAt?` expires: ${o.expiresAt}`:""}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(xe.red(` ${e.message}`)),process.exit(1)}});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(`
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)}});Rt.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new fn().revoke(e);o||(console.log(xe.red(` Token ${e} not found.`)),process.exit(1)),console.log(xe.green(`
18
18
  \u2713 Revoked ${e} (${o.name})
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(`
19
+ `))}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});we();import{Command as Ze}from"commander";import h from"chalk";import Oe from"prompts";import{readFileSync as fo,writeFileSync as tt,existsSync as ge,mkdirSync as Qe,cpSync as xs,readdirSync as Es}from"fs";import{resolve as J,join as uo,dirname as od}from"path";import{fileURLToPath as td}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(fo(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 No=new Ze().name("agent").description("manage agents \u2014 add, list, remove");No.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()});No.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:uo(o.workspace,o.id);Qe(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(od(td(import.meta.url)),"../wiki/SKILL.md"),c=ge(r)?r:a;ge(c)&&(Qe(J(t,".claude/skills/wiki"),{recursive:!0}),xs(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()});No.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)`))});No.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 _t=new Ze().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");_t.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=ne().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(o.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(h.dim(`
21
21
  ${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
22
- `));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[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(`
22
+ `));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,l]of Object.entries(c))typeof l=="string"&&/^[A-Z][A-Z0-9_]*$/.test(l)?a.push(process.env[l]?h.green(`${g}:${l}=set`):h.yellow(`${g}:${l}=UNSET`)):g==="auth"&&l==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof l=="string"&&a.push(h.dim(`sessionDir:${l}`));let d=Object.entries(i.metadata??{}).map(([g,l])=>`${g}=${l}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),d&&console.log(` ${h.dim(d)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});_t.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-WN3R3BPU.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 p=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"}]});p.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():p.scheme==="keyring"?c="keyring":p.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 p of String(o.metadata).split(",")){let[f,...u]=p.split("=");f&&(g[f.trim()]=u.join("=").trim())}else if(n){let p=await Oe({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(p.metadata)for(let f of String(p.metadata).split(",")){let[u,...w]=f.split("=");u&&(g[u.trim()]=w.join("=").trim())}}let l={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),l.tokenEnv=a),c==="keyring"&&(l.auth="keyring"),d&&(l.sessionDir=d),Object.keys(l).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(p=>p.kind===i&&p.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:l,metadata:g,enabled:!0}),await _e(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});_t.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}`))});_t.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)});No.addCommand(_t);var En=new Ze().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");En.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ne();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});En.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ne(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await 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),Qe(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 nt=new Ze().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");nt.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()});nt.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())});nt.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`))});nt.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 st=new Ze().name("mesh").description("manage mesh peers \u2014 add, list, remove");st.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()});st.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()}});st.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`)))});st.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 Ro=new Ze().name("skill").description("manage skills \u2014 add to agent(s), list");Ro.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(uo(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);Qe(c,{recursive:!0}),ge(uo(n,"SKILL.md"))?xs(n,c,{recursive:!0}):n.endsWith(".md")&&xs(n,uo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Ro.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)?Es(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});Ro.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=fo(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),d;try{d=D()}catch($){console.log(h.red(` Can't load agentx.json: ${$.message}`));return}let g=Object.entries(d.agents||{}),l=o.agent?g.filter(([$])=>$===o.agent):g;if(l.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let p=0,f=0,u=0,w=0;for(let[$,b]of l){let v=b.workspace;if(!v||!ge(v)){console.log(` ${h.yellow("\u2717")} ${$.padEnd(22)} ${h.dim("(workspace missing: "+(v||"undefined")+")")}`),w++;continue}let A=J(v,".claude/skills",e),x=J(A,"SKILL.md");if(!ge(x)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${$.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}o.dryRun||(Qe(A,{recursive:!0}),tt(x,r)),console.log(` ${h.green("+")} ${$.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),p++;continue}let E=fo(x,"utf-8");if(t("sha256").update(E).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${$.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),u++;continue}let N=(E.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||tt(x,r),console.log(` ${h.yellow("\u21BB")} ${$.padEnd(22)} ${h.dim(`v${N} \u2192 v${c}`)}`),f++}console.log();let y=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${y} seed ${p}, ${y} update ${f}, ${u} already current, ${w} skipped.`)),o.dryRun&&(p>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Ro.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:o}=await import("./loader-BOKE5M5S.js"),{auditAll:t}=await import("./audit-4245CX6P.js"),{loadReferences:n}=await import("./loader-4ZGTK7LD.js"),{loadRecipes:s}=await import("./recipes-7S4MC5OJ.js"),i=[];if(e.workspace){let f=ne().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(J(f.workspace))}else if(e.allWorkspaces){let p=ne();for(let f of Object.values(p.agents||{}))f?.workspace&&i.push(J(f.workspace))}else i.push(J(e.cwd));let r=J(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(p=>o(p)))).flat(),[d,g]=await Promise.all([n(r),s(r)]),l=t({skills:c,references:d,recipes:g});if(e.json)console.log(JSON.stringify(l.map(p=>({name:p.name,verdict:p.verdict,reasons:p.reasons,path:p.skill?.path})),null,2));else{let p={PASS:0,REVIEW:0,FAILING:0};for(let f of l)p[f.verdict]++;console.log();for(let f of l){let u=f.verdict==="PASS"?h.green("PASS "):f.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${u} ${h.bold(f.name)}${f.skill?.path?h.dim(` (${f.skill.path})`):""}`);for(let w of f.reasons)console.log(` ${h.dim("\xB7")} ${w}`)}console.log(),console.log(` ${h.green(`${p.PASS} PASS`)} ${h.yellow(`${p.REVIEW} REVIEW`)} ${h.red(`${p.FAILING} FAILING`)}`),console.log()}process.exit(l.some(p=>p.verdict==="FAILING")?1:0)});Ro.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-YB5KF27O.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 g of d.shortlist.slice(0,6)){let l=g.p===void 0?" - ":g.p.toFixed(2);console.log(h.dim(` ${g.lexical.toFixed(2)} -> ${l} ${g.name}`))}}d.judged||console.log(h.dim(`
24
+ (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var Dt=new Ze().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Dt.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");Qe(i,{recursive:!0}),Qe(r,{recursive:!0});let a=Es(n).filter(l=>l.endsWith(".yaml")||l.endsWith(".yml")),c=0,d=0;for(let l of a){let p=uo(i,l);if(ge(p)&&!o.force){console.log(h.dim(` skip ${p} (exists; --force to overwrite)`)),d++;continue}let u=fo(uo(n,l),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);tt(p,u),console.log(h.green(` + ${p}`)),c++}let g=uo(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=fo(s,"utf-8").replaceAll("example.",`${e}.`);tt(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()});Dt.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.example.com)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-BOKE5M5S.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-D4VVRNAI.js"),i=J(o.cwd),r=o.from?String(o.from).split(",").map(w=>w.trim()).filter(Boolean):[e],a=await t(i),c=n(a,{namespace:e,filter:r,gitlabHost:o.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(h.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(h.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(h.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let d=Object.fromEntries(Object.entries(c.byKind).map(([w,y])=>[w,y.length]));console.log(` Discovered: ssh=${d.ssh} gitlab=${d.gitlab} paths=${d.path} contacts=${d.contact}`);let g=s(c,e),l=J(o.referencesCwd||o.cwd),p=J(l,".agentx/references",e);if(!o.write){console.log(),console.log(h.dim(` Dry-run \u2014 would write to ${p}/`));for(let[w,y]of Object.entries(g))console.log(h.cyan(`
25
25
  --- ${w} ---`)),console.log(y.split(`
26
26
  `).slice(0,30).map($=>` ${$}`).join(`
27
27
  `)),y.split(`
28
28
  `).length>30&&console.log(h.dim(` \u2026 (${y.split(`
29
- `).length-30} more lines truncated in preview)`));console.log(),console.log(h.dim(` Re-run with --write to commit these to ${u}/`)),console.log();return}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(`
29
+ `).length-30} more lines truncated in preview)`));console.log(),console.log(h.dim(` Re-run with --write to commit these to ${p}/`)),console.log();return}Qe(p,{recursive:!0});let f=0,u=0;for(let[w,y]of Object.entries(g)){let $=uo(p,w);if(ge($)&&!o.force){console.log(h.dim(` skip ${$} (exists; --force to overwrite)`)),u++;continue}tt($,y),console.log(h.green(` + ${$}`)),f++}console.log(),console.log(h.dim(` ${f} written, ${u} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(h.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});Dt.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 As=new Ze().name("hook").description("manage hooks \u2014 add to agent workspace");As.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(fo(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),Qe(J(t.workspace,".claude"),{recursive:!0}),tt(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var Os=new Ze().name("migrate").description("import configuration from OpenClaw or other tools");Os.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(fo(n,"utf-8")),i=ge(J(process.cwd(),"agentx.json"))?ne():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},r=s.agents?.list||[],a=s.bindings||[],c={};for(let f of a)f.match?.channel==="telegram"&&(c[f.match.accountId]=f.agentId);r.find(f=>f.id==="main"||f.default)&&(c.default="main");let d=0;for(let f of r){if(f.workspace?.startsWith("/data"))continue;let u=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),w=f.groupChat?.mentionPatterns||[];if(w.some(y=>y===u)||w.push(u),i.agents[u]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:w,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},d++,!o.dryRun){Qe(J(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-G6KGWPHY.js");y(u,i.agents[u])}}console.log(` ${h.green(d)} agents imported (workspaces set up with Claude Code best practices)`);let g=s.channels?.telegram?.accounts||{},l=0;for(let[f,u]of Object.entries(g)){if(!u.botToken)continue;let y=c[f]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[f]={token:u.botToken,agentBinding:y},i.channels.telegram.enabled=!0,l++}console.log(` ${h.green(l)} Telegram accounts imported`);let p=J(n,"../cron/jobs.json");if(ge(p)){let f=JSON.parse(fo(p,"utf-8")),u=0;for(let w of f.jobs||[]){let y=w.name||w.id,$=w.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[y]={enabled:w.enabled||!1,schedule:w.schedule?.expr||"0 9 * * *",timezone:w.schedule?.tz||"UTC",agent:$,prompt:w.payload?.message||"",timeout:w.payload?.timeoutSeconds||600,onError:["log"]},u++}console.log(` ${h.green(u)} cron jobs imported`)}o.dryRun?(console.log(h.yellow(`
30
30
  Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await _e(i),console.log(h.green(`
31
- Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var 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=`
31
+ Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var ho=new Ze().name("config").description("validate and inspect configuration");ho.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=on(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"))?Es(J(r,".claude/skills")).filter(p=>!p.startsWith(".")).length:0,l=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",d?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${l.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});ho.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 nd(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 Ss(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}ho.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-2FIUL4DA.js"),{expandEnvVars:r}=await import("./config-WN3R3BPU.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(Ss(g))});ho.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-2FIUL4DA.js"),r=nd(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: ${Ss(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${Ss(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})`)))});ho.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-2FIUL4DA.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.")))});ho.command("governance").description("show resolved governance flags (read-only; flags read once at startup)").option("-c, --config <path>","path to agentx.json").option("--json","emit JSON").action(e=>{let o=!1,t=0,n;try{let l=D(e.config);o=!!l.business?.enabled,t=(l.business?.projects??[]).length}catch(l){n=l?.message??String(l)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(h.bold(" Governance flags")),console.log(),n&&(console.log(h.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let d=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${d(s)}${c?"":h.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?h.green("active"):r?h.yellow("env=true but business.enabled=false \u2192 inactive"):h.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(h.dim(` business.enabled ${o?h.green("true"):h.dim("false")}`)),console.log(h.dim(` business.projects[] ${t}`)),console.log(),console.log(h.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(h.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as sd}from"commander";import yo from"chalk";import{resolve as wo}from"path";import{existsSync as id}from"fs";var ao=new sd().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function _o(e){let o=wo(e,".agentx/db.sqlite");id(o)||(console.log(yo.red(` No SQLite at ${o}`)),console.log(yo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=Gi({path:o});return t||(console.log(yo.red(` Could not open ${o}`)),console.log(yo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function Do(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(yo.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}ao.command("tasks").description("recent task_history rows (one per agent task)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by start day (UTC)").option("-s, --status <status>","ok | error").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=_o(wo(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(t.push("status = @status"),n.status=e.status);let s=`
32
32
  SELECT agent_id, channel, status, duration_ms,
33
33
  input_tokens, output_tokens,
34
34
  substr(message_preview, 1, 60) AS message,
@@ -37,7 +37,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
37
37
  ${t.length?"WHERE "+t.join(" AND "):""}
38
38
  ORDER BY started_at DESC
39
39
  LIMIT @limit
40
- `,i=o.prepare(s).all({...n,limit:Number(e.limit)});_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?`
40
+ `,i=o.prepare(s).all({...n,limit:Number(e.limit)});Do(i,!!e.json)});ao.command("rotations").description("session rotation events (stale | tier-2 | max-turns)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-r, --reason <r>","stale | tier-2 | max-turns").option("-n, --limit <n>","max rows","20").option("--summary","group by agent + reason").option("--json","emit JSON").action(e=>{let o=_o(wo(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.reason&&(t.push("reason = @reason"),n.reason=e.reason);let s=t.length?"WHERE "+t.join(" AND "):"",i=e.summary?`
41
41
  SELECT agent_id, reason, COUNT(*) AS n,
42
42
  ROUND(AVG(last_turn_input_tokens)) AS avg_input_tokens,
43
43
  MAX(last_turn_input_tokens) AS max_input_tokens
@@ -51,14 +51,14 @@ The AgentX daemon and a speech transcription backend must also be available. Run
51
51
  ${s}
52
52
  ORDER BY rotated_at DESC
53
53
  LIMIT @limit
54
- `,r=o.prepare(i).all({...n,limit:Number(e.limit)});_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=`
54
+ `,r=o.prepare(i).all({...n,limit:Number(e.limit)});Do(r,!!e.json)});ao.command("usage").description("token usage rolled up per (agent, model, day)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by day (UTC)").option("--json","emit JSON").action(e=>{let o=_o(wo(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("day = @day"),n.day=e.day);let s=`
55
55
  SELECT day, agent_id, model, tasks,
56
56
  input_tokens AS in_tok, output_tokens AS out_tok,
57
57
  cache_read_tokens AS cache_read, cache_create_tokens AS cache_create
58
58
  FROM usage_daily
59
59
  ${t.length?"WHERE "+t.join(" AND "):""}
60
60
  ORDER BY day DESC, agent_id
61
- `,i=o.prepare(s).all(n);_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?`
61
+ `,i=o.prepare(s).all(n);Do(i,!!e.json)});ao.command("routes").description("inbound routing decisions captured by the pipeline trace").option("--cwd <cwd>","working directory",process.cwd()).option("-c, --channel <ch>","filter by channel (telegram, gitlab, github, ...)").option("-k, --kind <k>","match | drop").option("-n, --limit <n>","max rows","20").option("--summary","group by channel + kind + deciding stage").option("--json","emit JSON").action(e=>{let o=_o(wo(e.cwd)),t=[],n={};e.channel&&(t.push("channel = @channel"),n.channel=e.channel),e.kind&&(t.push("kind = @kind"),n.kind=e.kind);let s=t.length?"WHERE "+t.join(" AND "):"",i=e.summary?`
62
62
  SELECT channel, kind, deciding_stage, COUNT(*) AS n
63
63
  FROM route_traces
64
64
  ${s}
@@ -71,7 +71,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
71
71
  ${s}
72
72
  ORDER BY at DESC
73
73
  LIMIT @limit
74
- `,r=o.prepare(i).all({...n,limit:Number(e.limit)});_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=`
74
+ `,r=o.prepare(i).all({...n,limit:Number(e.limit)});Do(r,!!e.json)});ao.command("errors").description("failed tasks (status='error') with their error message").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=_o(wo(e.cwd)),t=["status = 'error'"],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent);let s=`
75
75
  SELECT agent_id, channel, duration_ms,
76
76
  substr(error, 1, 120) AS error,
77
77
  started_at
@@ -79,12 +79,12 @@ The AgentX daemon and a speech transcription backend must also be available. Run
79
79
  WHERE ${t.join(" AND ")}
80
80
  ORDER BY started_at DESC
81
81
  LIMIT @limit
82
- `,i=o.prepare(s).all({...n,limit:Number(e.limit)});_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(`
82
+ `,i=o.prepare(s).all({...n,limit:Number(e.limit)});Do(i,!!e.json)});ao.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=_o(wo(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}));Do(n,!!e.json)});ao.command("query <sql>").description("run an arbitrary read-only SQL query (escape hatch)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action((e,o)=>{let t=_o(wo(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(yo.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(yo.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();Do(n,!!o.json)}catch(n){console.log(yo.red(` ${n.message}`)),process.exit(1)}});import{Command as cd}from"commander";import G from"chalk";import{mkdtempSync as ld}from"fs";import{tmpdir as dd}from"os";import{resolve as pa,join as ua}from"path";import{existsSync as gd}from"fs";import md from"better-sqlite3";function ma(e,o,t,n=[]){let s=new Map;for(let c of o)s.set(c.id,c);let i=[];for(let c of t)i.push({kind:"decision",ts:c.decidedAt,decision:c});for(let c of n)i.push({kind:"resolution",ts:c.resolvedAt,resolution:c});i.sort((c,d)=>c.ts!==d.ts?c.ts-d.ts:c.kind===d.kind?0:c.kind==="decision"?-1:1);let r=[],a=0;for(let c of i){if(c.kind==="resolution"){try{e.recordResolution(c.resolution)}catch(u){r.push({eventId:c.resolution.decisionEventId,decidedBy:c.resolution.decisionDecidedBy,expected:{agentId:null,outcome:"resolved"},actual:{agentId:null,outcome:"resolution-failed"},reason:`recordResolution threw: ${u?.message??u}`})}continue}let d=c.decision,g=s.get(d.eventId);if(!g){r.push({eventId:d.eventId,decidedBy:d.decidedBy,expected:{agentId:d.agentId,outcome:d.outcome},actual:{agentId:null,outcome:"skipped"},reason:"decision references event not in snapshot"});continue}let l=rd(d),p={id:g.id,ts:g.ts,source:g.source,sourceEventId:g.sourceEventId,project:g.project,subject:g.subject,intent:g.intent,rawJson:g.rawJson},f=Hi(e,p,l,()=>d.decidedAt);a+=1,(f.outcome!==d.outcome||f.agentId!==d.agentId)&&r.push({eventId:g.id,decidedBy:d.decidedBy,expected:{agentId:d.agentId,outcome:d.outcome},actual:{agentId:f.agentId,outcome:f.outcome},reason:ad(d,f)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function rd(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function ad(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 bo=new cd().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function it(e){let o=pa(e.cwd??process.cwd()),t=pa(o,e.path??".agentx/intent/ledger.sqlite");gd(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 md(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 Po(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 pd(e){let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!o)return null;let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function An(e){if(!e)return;let o=pd(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}bo.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=it(e),t=An(e.since),n=t!==void 0?"WHERE ts >= @since":"",s=t!==void 0?"WHERE decided_at >= @since":"",i=n,r=o.prepare(`SELECT source, COUNT(*) as n FROM intent_events ${n} GROUP BY source ORDER BY n DESC`).all({since:t}),a=o.prepare(`SELECT COUNT(*) as n FROM intent_decisions ${s}`).get({since:t}).n,c=o.prepare(`SELECT outcome, COUNT(*) as n FROM intent_decisions ${s} GROUP BY outcome ORDER BY n DESC`).all({since:t}),d=o.prepare(`SELECT COUNT(*) as n FROM intent_divergences ${i}`).get({since:t}).n,g=o.prepare(`SELECT source, COUNT(*) as n FROM intent_divergences ${i} GROUP BY source ORDER BY n DESC`).all({since:t}),l=o.prepare(`
83
83
  SELECT COUNT(*) as n FROM intent_decisions d
84
84
  LEFT JOIN intent_resolutions r
85
85
  ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
86
86
  WHERE d.outcome = 'dispatched' AND r.decision_event_id IS NULL
87
- `).get().n;if(e.json){console.log(JSON.stringify({since:t??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:d,divergencesBySource: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(`
87
+ `).get().n;if(e.json){console.log(JSON.stringify({since:t??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:d,divergencesBySource:g,inFlight:l},null,2));return}console.log(G.bold("Events by source")),Po(r,!1),console.log(),console.log(G.bold(`Decisions: ${a}`)),Po(c,!1),console.log(),console.log(G.bold(`Divergences: ${d}`)),Po(g,!1),console.log(),console.log(G.bold(`In-flight (dispatched, no resolution): ${l}`))});bo.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=it(e),t=An(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
88
88
  SELECT
89
89
  datetime(ts/1000, 'unixepoch') AS at,
90
90
  source,
@@ -98,7 +98,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
98
98
  ${i}
99
99
  ORDER BY ts DESC
100
100
  LIMIT @limit
101
- `).all(s);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(`
101
+ `).all(s);Po(r,!!e.json)});bo.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=it(e),t=["d.outcome = 'dispatched'","r.decision_event_id IS NULL"],n={limit:Number(e.limit)};e.source&&(t.push("e.source = @source"),n.source=e.source);let s=o.prepare(`
102
102
  SELECT
103
103
  datetime(d.decided_at/1000, 'unixepoch') AS dispatched_at,
104
104
  e.source,
@@ -114,7 +114,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
114
114
  WHERE ${t.join(" AND ")}
115
115
  ORDER BY d.decided_at DESC
116
116
  LIMIT @limit
117
- `).all(n);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(`
117
+ `).all(n);Po(s,!!e.json)});bo.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=it(e),t=An(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),e.project&&(n.push("project = @project"),s.project=e.project),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
118
118
  SELECT
119
119
  datetime(ts/1000, 'unixepoch') AS at,
120
120
  source,
@@ -125,8 +125,8 @@ The AgentX daemon and a speech transcription backend must also be available. Run
125
125
  ${i}
126
126
  ORDER BY ts DESC
127
127
  LIMIT @limit
128
- `).all(s);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
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(`
128
+ `).all(s);Po(r,!!e.json)});bo.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=it(o),n=null,s=null;if(o.bySubject){let l=e.indexOf(":");l<0&&(console.log(G.red(' --by-subject expects "<project>:<subject>"')),process.exit(1)),n=e.slice(0,l),s=e.slice(l+1)}else{let l=t.prepare("SELECT project, subject FROM intent_events WHERE id = ?").get(e);l||(console.log(G.red(` no event with id ${e}`)),process.exit(1)),n=l.project,s=l.subject,(n===null||s===null)&&(console.log(G.yellow(` event ${e} has no (project, subject) \u2014 lineage requires both`)),n&&console.log(G.dim(` project: ${n}`)),s&&console.log(G.dim(` subject: ${s}`)),process.exit(1))}let i=t.prepare(`SELECT id, ts, source, COALESCE(intent, '-') AS intent, COALESCE(source_event_id, '-') AS source_event_id
129
+ FROM intent_events WHERE project = ? AND subject = ? ORDER BY ts ASC`).all(n,s);if(i.length===0){console.log(G.dim(` (no events for ${n}:${s})`));return}let r=i.map(l=>l.id),a=r.map((l,p)=>`@id${p}`).join(", "),c=Object.fromEntries(r.map((l,p)=>[`id${p}`,l])),d=t.prepare(`
130
130
  SELECT d.event_id, d.decided_at, d.decided_by, d.agent_id, d.outcome, d.reason,
131
131
  r.resolved_at, r.status AS resolution_status, r.duration_ms, r.result_summary
132
132
  FROM intent_decisions d
@@ -134,21 +134,21 @@ The AgentX daemon and a speech transcription backend must also be available. Run
134
134
  ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
135
135
  WHERE d.event_id IN (${a})
136
136
  ORDER BY d.decided_at ASC
137
- `).all(c);if(o.json){let l=i.map(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(`
137
+ `).all(c);if(o.json){let l=i.map(p=>({event:p,decisions:d.filter(f=>f.event_id===p.id)}));console.log(JSON.stringify({project:n,subject:s,lineage:l},null,2));return}let g=new Set;for(let l of d)l.outcome==="dispatched"&&l.agent_id&&g.add(l.agent_id);console.log(),console.log(G.bold(` Lineage for ${G.cyan(n+":"+s)}`)),console.log(G.dim(` ${i.length} event(s), ${d.length} decision(s), ${g.size} distinct agent(s) dispatched`)),console.log();for(let l of i){let p=new Date(l.ts).toISOString().slice(0,19).replace("T"," ");console.log(` ${G.dim(p)} ${G.bold(l.id)} ${G.dim(`(${l.source}/${l.intent})`)}`);let f=d.filter(u=>u.event_id===l.id);if(f.length===0){console.log(G.dim(" (no decisions yet)"));continue}for(let u of f){let w=u.outcome==="dispatched"?G.green(u.outcome):u.outcome==="dropped"?G.dim(u.outcome):G.yellow(u.outcome),y=u.agent_id?G.cyan(u.agent_id):G.dim("-"),$=u.reason?G.dim(` \u2014 ${u.reason.slice(0,60)}`):"";if(console.log(` ${G.dim(u.decided_by)} \u2192 ${w} ${y}${$}`),u.resolution_status){let b=u.resolution_status==="ok"?G.green(u.resolution_status):G.red(u.resolution_status),v=u.duration_ms?`${(u.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${G.dim("resolved")} ${b} ${G.dim(v)}`)}else u.outcome==="dispatched"&&console.log(` ${G.yellow("(in-flight, no resolution)")}`)}}console.log()});bo.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=it(e),t=An(e.since),n=[],s={};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=e.limit?`LIMIT ${Number(e.limit)}`:"",r=o.prepare(`
138
138
  SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
139
139
  FROM intent_events
140
140
  ${n.length?"WHERE "+n.join(" AND "):""}
141
141
  ORDER BY ts ASC
142
142
  ${i}
143
- `).all(s).map(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(`
143
+ `).all(s).map(u=>({id:u.id,ts:u.ts,source:u.source,sourceEventId:u.source_event_id,project:u.project,subject:u.subject,intent:u.intent,rawJson:u.raw_json}));if(r.length===0){console.log(G.dim(" (no events match filter)"));return}let a=new Set(r.map(u=>u.id)),c=r.map((u,w)=>`@id${w}`).join(", "),d=Object.fromEntries(r.map((u,w)=>[`id${w}`,u.id])),g=o.prepare(`
144
144
  SELECT event_id, decided_at, decided_by, agent_id, outcome, reason
145
145
  FROM intent_decisions
146
146
  WHERE event_id IN (${c})
147
- `).all(d).map(p=>({eventId:p.event_id,decidedAt:p.decided_at,decidedBy:p.decided_by,agentId:p.agent_id,outcome:p.outcome,reason:p.reason})),l=o.prepare(`
147
+ `).all(d).map(u=>({eventId:u.event_id,decidedAt:u.decided_at,decidedBy:u.decided_by,agentId:u.agent_id,outcome:u.outcome,reason:u.reason})),l=o.prepare(`
148
148
  SELECT decision_event_id, decision_decided_by, resolved_at, status, duration_ms, result_summary
149
149
  FROM intent_resolutions
150
150
  WHERE decision_event_id IN (${c})
151
- `).all(d).map(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,
151
+ `).all(d).map(u=>({decisionEventId:u.decision_event_id,decisionDecidedBy:u.decision_decided_by,resolvedAt:u.resolved_at,status:u.status,durationMs:u.duration_ms,resultSummary:u.result_summary})),p=ld(ua(dd(),"agentx-ledger-replay-")),f=new Mi({path:ua(p,"target.sqlite")});try{let u=ma(f,r,g,l);if(e.json){console.log(JSON.stringify(u,null,2));return}console.log(G.bold(`Replayed ${u.eventsCount} events, ${u.decisionsCount} decisions, ${l.length} resolutions`)),u.divergences.length===0?console.log(G.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(G.red(` \u2717 ${u.divergences.length} divergences`)),Po(u.divergences.map(w=>({event_id:w.eventId,decided_by:w.decidedBy,recorded:`${w.expected.outcome}/${w.expected.agentId??"-"}`,replayed:`${w.actual.outcome}/${w.actual.agentId??"-"}`,reason:w.reason.slice(0,80)})),!1))}finally{f.close()}});Si();yl();wl();bl();hl();Ni();xt();import{Command as ud}from"commander";import F from"chalk";import{existsSync as fa}from"fs";import{resolve as Is}from"path";import fd from"better-sqlite3";var De=new ud().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),Ge=".agentx/decisions/decisions.sqlite";function hd(e){return Is(Is(e.cwd??process.cwd()),e.path??Ge)}function oo(e,o=!1){let t=hd(e);fa(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 en({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 eo(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 js(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 Cs(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:js(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",Ge).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let o=oo(e),t=js(e.since)??0,n=o.db.prepare(`SELECT seat, mode, backend, model, structure_mode AS structureMode,
152
152
  COUNT(*) AS calls,
153
153
  SUM(CASE WHEN error IS NOT NULL THEN 1 ELSE 0 END) AS failed,
154
154
  SUM(retries) AS retries,
@@ -158,16 +158,16 @@ The AgentX daemon and a speech transcription backend must also be available. Run
158
158
  FROM decision_calls
159
159
  WHERE ts >= ?
160
160
  GROUP BY seat, mode, backend, model, structure_mode
161
- ORDER BY calls DESC`).all(t);Ze(n,e.json);let s=o.db.prepare(`SELECT seat, mode, COALESCE(action,'(none)') AS action, explored, COUNT(*) AS calls
161
+ ORDER BY calls DESC`).all(t);eo(n,e.json);let s=o.db.prepare(`SELECT seat, mode, COALESCE(action,'(none)') AS action, explored, COUNT(*) AS calls
162
162
  FROM decision_calls WHERE ts >= ? GROUP BY seat, mode, action, explored
163
163
  ORDER BY calls DESC`).all(t);!e.json&&s.length>0&&(console.log(F.bold(`
164
- policy`)),Ze(s,!1),console.log(F.dim(`
164
+ policy`)),eo(s,!1),console.log(F.dim(`
165
165
  explored=1 means the policy wanted to skip and the expensive path ran anyway.
166
- Those are the only rows in the skip region that can ever be graded.`))),o.close()});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,
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",Ge).option("--seat <seat>").option("--since <window>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=oo(e),t=["ts >= ?"],n=[js(e.since)??0];e.seat&&(t.push("seat = ?"),n.push(e.seat));let s=o.db.prepare(`SELECT id, datetime(ts/1000, 'unixepoch') AS at, seat, mode, backend, model,
167
167
  structure_mode AS structure, latency_ms AS ms, retries, truncated, error
168
168
  FROM decision_calls WHERE ${t.join(" AND ")}
169
- ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));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(`
169
+ ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));eo(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",Ge).option("--json").action((e,o)=>{let t=oo(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}eo(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",Ge).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,o,t,n)=>{let s=oo(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",Ge).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=oo(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));eo(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",Ge).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let o=oo(e,!0),t=Is(process.cwd(),e.db);fa(t)||(console.log(F.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new fd(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",Ge).requiredOption("--seat <seat>").option("--question <name>").option("--backend <name>","grade one backend in isolation").option("--model <id>").option("--structure-mode <mode>","never pool verbalized and logprob rows").option("--since <window>").option("--explored","only rows the policy wanted to skip \u2014 the unbiased skip-region sample").option("--min-n <n>","refuse to report below this many labeled rows","100").option("--bins <n>","default 10","10").option("--json").action(e=>{let o=oo(e),t=o.gradedRows(Cs(e)),n=Ii(t,{minN:Number(e.minN),bins:Number(e.bins)});if(e.json){console.log(JSON.stringify(n,null,2)),o.close();return}if(console.log(F.bold(`
171
171
  ${e.seat}${e.question?`.${e.question}`:""}`)),console.log(` ${n.n} answers, ${n.nLabeled} labeled`+(n.agreement.n>0?`, ${n.agreement.n} with an incumbent (agree ${(n.agreement.rate*100).toFixed(1)}%, kappa ${n.agreement.kappa.toFixed(3)})`:"")),n.insufficient){console.log(F.yellow(`
172
172
  Not enough ground truth: ${n.nLabeled} labeled rows, need ${n.minN}.`)),console.log(F.dim(" An ECE on this little data is noise, and a noisy number on a dashboard gets acted on.")),console.log(F.dim(` Label the most informative rows: agentx decisions unlabeled --seat ${e.seat}`)),o.close();return}console.log(`
173
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(`
@@ -175,21 +175,21 @@ The AgentX daemon and a speech transcription backend must also be available. Run
175
175
  skip region ${i.length} answers (${(i.length/t.length*100).toFixed(1)}% of traffic), ${r.length} gradeable`),r.length===0&&console.log(F.yellow(` Nothing in the skip region has been graded. Everything below describes
176
176
  only the decisions this policy chose NOT to skip \u2014 it cannot tell you
177
177
  what skipping would cost. Raise decisions.seats.<seat>.explore.`))),console.log(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(`
178
+ reliability (equal-width bins)`)),eo(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",Ge).requiredOption("--seat <seat>").option("--question <name>").option("--since <window>").option("--by <names>","comma-separated covariates","agent,question").option("--folds <n>","cross-validation folds","5").option("--min-n <n>","default 100","100").option("--json").action(e=>{let o=oo(e),t=o.gradedRows(Cs(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=ji(t,{covariates:n},{folds:Number(e.folds),minN:Number(e.minN)});if(e.json){console.log(JSON.stringify(s,null,2)),o.close();return}if(s.insufficient){console.log(F.yellow(` ${s.n} labeled rows, need ${s.minN}.`)),o.close();return}console.log(F.bold(`
179
179
  ${e.seat} \u2014 held-out comparison (${s.folds}-fold, n=${s.n})`)),console.log(F.dim(` Cross-validated, because more parameters always fit training data better.
180
- `)),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(`
180
+ `)),eo(s.scores.map(i=>({model:i.name,logLoss:i.logLoss.toFixed(4),brier:i.brier.toFixed(4),best:i.name===s.best?"<-":""})),!1),s.best==="covariate"?(console.log(F.green(`
181
181
  Calibration differs by ${n.join("/")} \u2014 a single temperature averages groups`)),console.log(F.dim(" that need different corrections."))):s.best==="temperature"?console.log(F.dim(`
182
182
  One global temperature is enough. ${n.join("/")} carries no calibration signal here.`)):console.log(F.dim(`
183
- Neither correction beats the raw confidence out of sample. Leave it alone.`)),o.close()});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
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",Ge).requiredOption("--seat <seat>").option("--question <name>").option("--since <window>").option("--explored","only rows the policy wanted to skip").option("--steps <n>","default 20","20").option("--json").action(e=>{let o=oo(e),t=o.gradedRows({...Cs(e),labeledOnly:!0}),n=Oi(t,Number(e.steps));if(n.length===0){console.log(F.yellow(` No labeled rows for seat "${e.seat}".`)),o.close();return}eo(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",Ge).requiredOption("--seat <seat>").option("--backend <name>","default: the backend that recorded the row").option("--model <id>").option("--call <id>","a specific call id; default is the newest with stored state").option("-n, --samples <n>","default 15","15").option("--json").action(async e=>{Ho();let o=oo(e),t=o.db.prepare(`SELECT id, backend, model, state_json, questions_json FROM decision_calls
184
184
  WHERE seat = ? AND state_json IS NOT NULL AND error IS NULL
185
185
  ${e.call?"AND id = ?":""}
186
- ORDER BY ts DESC LIMIT 1`).get(...e.call?[e.seat,e.call]:[e.seat]);if(!t){console.log(F.yellow(` No recorded call with stored state for seat "${e.seat}".`)),console.log(F.dim(" State is kept for the first `keepStateRows` per seat; see decisions.redactState.")),o.close();return}let n=e.backend??t.backend,s=e.model??(n===t.backend?t.model:void 0),i=await 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(`
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 Ci(n,JSON.parse(t.state_json),JSON.parse(t.questions_json),{samples:Number(e.samples),model:s});if(e.json){console.log(JSON.stringify(i,null,2)),o.close();return}console.log(F.bold(`
187
187
  ${e.seat} on ${i.backend} (${i.model})`)),console.log(F.dim(` ${i.samples} samples of call ${t.id}, ${i.totalMs}ms, ${i.usage.inputTokens.toLocaleString()} input tokens
188
- `)),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(`
188
+ `)),eo(i.questions.map(r=>({question:r.question,mean:r.mean.toFixed(4),stdev:r.stdev.toFixed(4),min:r.min.toFixed(3),max:r.max.toFixed(3),answers:r.distinctAnswers.join("/"),band:r.bands.join("/"),stable:r.crossesThreshold?F.red("NO"):"yes"})),!1),console.log(`
189
189
  mean stdev ${i.meanStdev.toFixed(4)}`),console.log(F.dim(" TypeSafe publish 0.0102 for jev across a 14-question rubric, as a reference.")),i.unstable.length>0?(console.log(F.red(`
190
190
  Unstable: ${i.unstable.join(", ")} \u2014 identical calls disagree about what to DO,`)),console.log(F.dim(` not merely by how much. Usually a compound question: one name, several questions.
191
191
  Split it, or narrow it to a single clause in the state's own vocabulary.`))):console.log(F.green(`
192
- Every question held its decision across all samples.`)),console.log(F.dim("\n Stability is not correctness. A question can hold perfectly still and be\n perfectly wrong \u2014 that is what `decisions calibrate` is for.")),o.close()});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(`
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(()=>{Ho();let e=xi().map(o=>{let t=is(o).capabilities;return{backend:o,source:t.probabilitySource,calibrated:t.calibratedProbabilities?"yes":"no",maxOptions:t.maxChoiceOptions,maxStateChars:t.maxStateChars}});eo(e,!1),console.log(F.dim(`
193
193
  source where the numbers come from. "verbalized" means the model wrote them
194
194
  into its answer; "logits" means they were read off its next-token
195
195
  distribution. Logits are the model's actual posterior \u2014 verbalized
@@ -197,15 +197,15 @@ The AgentX daemon and a speech transcription backend must also be available. Run
197
197
  calibrated whether an answer given 0.8 is right about 80% of the time ON YOUR
198
198
  traffic. Reading real logits does not buy this: a posterior can be
199
199
  confidently wrong. It comes from a recalibrator fitted on your own
200
- labeled rows \u2014 see \`agentx decisions recalibrate\`.`))});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(`
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=>{Ho();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=Jo(s,"Which option fits this state?")}e.noul&&(o.verdict=io(String(e.noul))),Object.keys(o).length===0&&(console.log(F.red(" Give at least one of --choice or --noul.")),process.exit(1));let n=await is(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as yd}from"commander";import I from"chalk";import{resolve as ha}from"path";import{existsSync as wd}from"fs";import bd from"better-sqlite3";var Pt=new yd().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function Ns(e){let o=ha(e.cwd??process.cwd()),t=ha(o,e.path??".agentx/db.sqlite");wd(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 bd(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 $d(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 kd(e){if(!e)return;let o=$d(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 vd(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 Ts(e){return e==="ok"?I.green:e==="error"||e==="timeout"?I.red:e==="in-flight"?I.yellow:I.dim}Pt.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=Ns(e),t=zi(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:kd(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=Ts(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(vd(n.startedAt))}`),n.error&&console.log(` ${I.red("error:")} ${n.error}`)}});Pt.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=Ns(o),n=ls(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}xd(n.task,n.steps)});function xd(e,o){let t=Ts(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?Ts(n.status)(n.status):I.dim("\u2014"),i=n.action?I.cyan(n.action):"";if(console.log(` ${I.dim(`#${n.seq}`)} ${I.bold(n.name)}${i?" "+i:""} ${s}${n.ms!=null?I.dim(` ${n.ms}ms`):""}`),n.inputSummary){let r=n.inputSummary.split(`
201
201
  `).slice(0,8);console.log(r.map(a=>` ${I.dim("\u2192")} ${a}`).join(`
202
202
  `)),n.inputSummary.split(`
203
203
  `).length>8&&console.log(` ${I.dim("\u2026")}`)}if(n.outputSummary){let r=n.outputSummary.split(`
204
204
  `).slice(0,8);console.log(r.map(a=>` ${I.dim("\u2190")} ${a}`).join(`
205
205
  `)),n.outputSummary.split(`
206
- `).length>8&&console.log(` ${I.dim("\u2026")}`)}n.error&&console.log(` ${I.red("error:")} ${n.error}`)}}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
206
+ `).length>8&&console.log(` ${I.dim("\u2026")}`)}n.error&&console.log(` ${I.red("error:")} ${n.error}`)}}Pt.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=Ns(o),n=ls(t,e);n||(console.log(I.red(` task not found: ${e}`)),console.log(I.dim(" agentx trace list \u2014 see what's available")),process.exit(1));let s=n.task,i=s.originalMessage??s.messagePreview;i||(console.log(I.red(` task ${e} has no recorded input message \u2014 cannot replay`)),process.exit(1)),!s.originalMessage&&s.messagePreview!=null&&console.log(I.yellow(" \u26A0 pre-migration-v8 row: input message was capped at 200 chars; replay uses the preview")),console.log(),console.log(I.bold(` replay ${I.cyan(e)}`)),console.log(I.dim(` agent=${s.agentId} channel=${s.channel??"\u2014"} chatId=${s.chatId??"\u2014"}`)),console.log(I.dim(` original status=${s.status} duration=${s.durationMs??"?"}ms tokens=in:${s.inputTokens??0}/out:${s.outputTokens??0}`)),console.log();let a=String(o.daemon).replace(/\/+$/,""),c={agent:s.agentId,message:i,freshSession:o.fresh!==!1,context:{channel:s.channel??"api",chatId:`replay-${e.toLowerCase().slice(-8)}-${Date.now().toString(36)}`}},d=Date.now(),g;try{g=await fetch(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})}catch(f){console.log(I.red(` daemon unreachable at ${a}: ${f.message||f}`)),process.exit(1)}let l=await g.json().catch(()=>({})),p=Date.now()-d;if(g.ok||(console.log(I.red(` replay failed (${g.status}): ${l.error||"unknown error"}`)),process.exit(1)),o.diff){console.log(I.bold(" INPUT (replayed verbatim)")),console.log(),On(i),console.log(),console.log(I.bold(` ORIGINAL OUTPUT ${I.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?On(s.finalResponse):console.log(I.yellow(" (not captured \u2014 pre-migration-v8 row, or response was empty)")),console.log(),console.log(I.bold(` CURRENT OUTPUT ${I.dim(`status=${l.error?"error":"ok"} ${p}ms tokens=in:${l.usage?.inputTokens??0}/out:${l.usage?.outputTokens??0}`)}`)),console.log(),On(l.content??"(empty reply)"),l.error&&console.log(I.red(` error: ${l.error}`)),console.log();let f=(s.finalResponse??"").trim()===(l.content??"").trim();s.finalResponse&&(console.log(f?I.dim(" outputs are identical"):I.yellow(" outputs differ \u2014 read both blocks to see what changed")),console.log())}else console.log(I.green(` \u2713 replayed in ${p}ms`)),console.log(),On(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 On(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 Od}from"commander";import ce from"chalk";import{existsSync as Id,mkdirSync as jd,writeFileSync as Cd}from"fs";import{resolve as ba,join as wa,dirname as Td}from"path";var Sd=`# AgentX destructive-action guardrails \u2014 global policy
209
209
  #
210
210
  # This file + environments/*.yaml + agents/<id>.yaml are deep-merged
211
211
  # (most specific wins). The built-in catalog (prisma / rm -rf / docker /
@@ -231,7 +231,7 @@ defaults:
231
231
  # action: escalate
232
232
  # severity: high
233
233
  rules: []
234
- `,fd=`# Production protected resources.
234
+ `,Ed=`# Production protected resources.
235
235
  #
236
236
  # The catalog rules reference \`target_in: production\`, so DECLARING this set is
237
237
  # what arms them. \`resolve_env: true\` expands $VAR / \${VAR} and reads .env* in
@@ -253,7 +253,7 @@ protected_resources:
253
253
 
254
254
  # Production-only rules beyond the catalog:
255
255
  rules: []
256
- `,hd=`# Per-agent override for coder-agent. Top-level rules here are auto-scoped to
256
+ `,Ad=`# Per-agent override for coder-agent. Top-level rules here are auto-scoped to
257
257
  # this agent (the filename names it). coder agents never touch production.
258
258
  rules:
259
259
  - id: coder-no-prod
@@ -262,7 +262,7 @@ rules:
262
262
  action: deny
263
263
  severity: critical
264
264
  message: "coder-agent is not permitted to run commands against production."
265
- `,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.
265
+ `,ya=[{relPath:"policy.yaml",content:Sd},{relPath:"environments/production.yaml",content:Ed},{relPath:"agents/coder-agent.yaml",content:Ad}];var $o=new Od().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function Rs(e){return e==="deny"?ce.red:e==="escalate"||e==="ask"?ce.yellow:e==="warn"?ce.magenta:ce.green}function In(e){return e.root?ba(e.root):yr()}$o.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 hr({root:In(e),agentId:e.agent,env:e.env}),process.exit(0)});$o.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=In(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=fr({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}Nd(s,i,r)});function Nd(e,o,t){let n=Rs(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":ce.dim(" (no rule matched)")}`),console.log(` enforced as ${Rs(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()}$o.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=ur({root:In(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=Rs(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}`))}});$o.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=wa(ba(e.root),mr),t=0;for(let n of ya){let s=wa(o,n.relPath);if(Id(s)&&!e.force){console.log(ce.dim(` skip (exists) ${n.relPath}`));continue}jd(Td(s),{recursive:!0}),Cd(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.'))});$o.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.`))}});$o.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=pr(In(e),e.agent);console.log(JSON.stringify(o,null,2))});St();import{Command as Rd}from"commander";import{execFile as _d}from"child_process";import{promisify as Dd}from"util";import{existsSync as Pd}from"fs";import ze from"chalk";xt();var Mt="ui-element";function jn(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:Lt(t.tried,80),screenChanged:t.changed,note:t.note?Lt(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:$a(t.role),label:Lt(t.label,120),value:t.value?Lt(t.value,80):null,enabled:t.enabled}))}}function Cn(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${$a(t.role)}: ${Lt(n,80)}`}return{target:Jo(o,"Which control does the request refer to? If `alreadyTried` shows a control was clicked and the screen did not change, that one did not work \u2014 choose differently."),present:io("The screen actually contains a control matching the request.",{true:"One of the listed controls is plainly the thing the request names, or is the obvious way to perform it.",false:"Nothing listed corresponds to the request \u2014 the right control is on another screen, behind a menu, not yet visible, or this application simply cannot do what was asked."})}}function Tn(e,o){let t=e.target,n=o.map(s=>({id:s.id,score:t.probabilities[String(s.id)]??0})).sort((s,i)=>i.score-s.score);return{id:Number(t.choice),confidence:t.confidence,present:e.present.noul,ranked:n}}function $a(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Lt(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}var ka=Dd(_d),va=new Rd().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)=>{Pd(Se)||(console.log(ze.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await un({max:Number(o.max)||40})}catch(l){console.log(ze.red(` could not read the screen: ${l?.message??l}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(ze.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let l=It(t,n[0].id);l&&(console.log(ze.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+ze.bold(n[0].label)),await ka(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(Mt,jn({request:e,app:t.app,window:t.window,candidates:n}),Cn(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(ze.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${Mt}.mode`)),process.exit(1));let i=Tn(s.answers,n),r=It(t,i.id),a=n.find(l=>l.id===i.id)?.label??"",c=t.ocrRects.has(i.id),d=Number(o.minPresent)||.5;if((i.present<d||!r)&&(console.log(ze.yellow(` nothing on screen matches "${e}"`)+ze.dim(` (P(exists)=${i.present.toFixed(2)} below ${d})`)),process.exit(2)),o.json){console.log(JSON.stringify({app:t.app,request:e,chosen:{...r,label:a,fromOCR:c},present:i.present,confidence:i.confidence,ranked:i.ranked.slice(0,5).map(l=>({...l,label:n.find(p=>p.id===l.id)?.label}))},null,2));return}let g=a;console.log(` ${ze.green("\u2192")} ${ze.bold(g)} `+ze.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await ka(Se,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",g])});import{Command as cg}from"commander";import Pe from"chalk";import{execFile as Ld}from"child_process";import{promisify as Md}from"util";import{existsSync as Ud,readFileSync as _s}from"fs";import{homedir as Fd,tmpdir as qd}from"os";import{join as xa}from"path";var Wd=Md(Ld),Sa=12e5,Bd="https://openrouter.ai/api/v1/chat/completions",Jd=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function Hd(e={kind:"window"},o=Sa){if(!Ud(Se))throw new Error("helper not built \u2014 run apps/mac-helper/build.sh");let n=["capture","--out",xa(qd(),`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 Wd(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=_s(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 Gd=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
266
266
 
267
267
  Report only what is visible in this image.
268
268
 
@@ -270,10 +270,10 @@ The failure that matters: an application that performs an action is on screen, a
270
270
 
271
271
  State indicators are usually small and specific: a coloured dot, a pill or badge in the menu bar, an elapsed timer, a filled or highlighted toggle, a progress bar, a changed icon. If the question turns on such an indicator, say whether you can see it and what it looks like.
272
272
 
273
- Answer "unclear" when the deciding detail is not in frame, too small to read, or covered. "unclear" is a useful answer. A confident guess is not.`;async function 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}
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 zd(e,o,t,n){let s=Vd();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=_s(o.path).toString("base64"),r={model:t,max_tokens:700,messages:[{role:"user",content:[{type:"text",text:`Question: ${e}
274
274
 
275
- The image is the region ${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(`
275
+ The image is the region ${Yd(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:Gd,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(Bd,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`,"HTTP-Referer":"https://github.com/acme/agentx","X-Title":"agentx"},body:JSON.stringify(r),signal:a.signal})}finally{clearTimeout(c)}if(!d.ok){let u=await d.text().catch(()=>"");throw new Error(`vision model ${d.status}: ${u.slice(0,300)}`)}let g=await d.json(),l=g?.choices?.[0]?.message?.tool_calls?.[0];if(!l?.function?.arguments)throw new Error("vision model returned no structured report");let p=JSON.parse(l.function.arguments),f=p.reading==="yes"||p.reading==="no"?p.reading:"unclear";return{observation:(p.observation??"").trim(),evidence:(p.evidence??"").trim(),reading:f,model:typeof g.model=="string"?g.model:t,usage:{inputTokens:g?.usage?.prompt_tokens??0,outputTokens:g?.usage?.completion_tokens??0}}}async function Nn(e,o={}){let t=Date.now(),n=await Hd(o.region??{kind:"window"},o.maxPixels??Sa),s=await zd(e,n,o.model??Jd,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 Yd(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 Ut;function Vd(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(Ut!==void 0)return Ut??void 0;try{let e=_s(xa(Fd(),".agentx","openrouter-key.txt"),"utf-8").trim();Ut=e.length>0?e:null}catch{Ut=null}return Ut??void 0}import{execFile as Kd}from"child_process";import{promisify as Xd}from"util";var Qd=Xd(Kd),Zd=["screencapture"],eg=["Screen Studio","OBS","QuickTime Player","Zoom"];async function Aa(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await og()),t}async function og(){let e=await Ea(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 Ea(eg);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 Ea(e){let o=[];for(let t of e)try{let{stdout:n}=await Qd("pgrep",["-x",t]),s=n.trim().split(`
276
+ `)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}St();xt();var Oa="screen-state",Ia={observable:io("The evidence gathered \u2014 the screenshot and the system checks together \u2014 is enough to settle the claim, either way.",{true:"Something in the evidence decides it. Either the observation names a specific visible detail that bears on the claim and was legible, or a system check directly establishes the claim true or false. A system check alone is sufficient: it does not need the image to agree with it, or the image to have shown anything at all.",false:"Nothing decides it. The deciding detail is not in frame, too small or blurred, or covered; the observation only describes context \u2014 which application is open, what the screen generally shows \u2014 without the detail itself; and no system check settles it either. Absence of evidence in a capture that could not have shown the evidence is not evidence of absence. This is also false when a check says the question is not answerable from a screenshot and the observation nonetheless claims to have seen it: that is a guess, however specific it sounds."}),holds:io("The claim is true of the screen right now.",{true:"The visible evidence shows the claimed state is in effect: the indicator is present, the text is there, the element is visible and unobstructed, the action has plainly already happened.",false:"The visible evidence shows the claimed state is NOT in effect. An application being open, capable of the action, or offering it, is not the action having happened \u2014 a recorder on screen is not a recording, an unpressed button is not a pressed one, an offered dialog is not a chosen one. A system check that directly contradicts the observation outweighs it: the checks are deterministic readings of the machine, the observation is a model's reading of an image."})};function ja(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 Ca(e){return{observable:e.observable.noul,holds:e.holds.noul}}var tg=.6,ng=.7,sg=.3;async function Ft(e,o={}){let[t,n]=await Promise.all([Nn(e,o),Aa(e).catch(()=>[])]),s=o.observableFloor??tg,i=await Ke(Oa,ja({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:ag(t),treeNote:o.treeNote,probes:n}),Ia,{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:rg(d,t),sighting:t,probes:n}}let{observable:r,holds:a}=Ca(i.answers);if(r<s)return{claim:e,outcome:"unknown",ok:!1,observable:r,holds:a,calibrated:!0,reason:`Could not tell from the screenshot or the system checks (${Rn(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=ng?"confirmed":a<=sg?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:ig(c,a,t),sighting:t,probes:n}}function ig(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${Rn(o)}). ${n}`:e==="refuted"?`Not true (${Rn(1-o)} it is false). ${n}`:`Inconclusive (${Rn(o)}, between the thresholds). ${n}`}function rg(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 ag(e){let o=e.shot.region;return o.y<=1&&o.height<=40?"the macOS menu bar":`a ${Math.round(o.width)}x${Math.round(o.height)} region of the screen`}var Rn=e=>`${Math.round(e*100)}%`;var Ta=new cg().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 Ft(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 Nn(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: ${lg(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 lg(e){return e==="yes"?Pe.green(e):e==="no"?Pe.red(e):Pe.yellow(e)}St();import{Command as mg}from"commander";import{execFile as Ua}from"child_process";import{promisify as pg}from"util";import{existsSync as ug,readFileSync as fg,writeFileSync as Fa,mkdirSync as hg}from"fs";import{homedir as yg}from"os";import{join as wg,dirname as bg}from"path";import je from"chalk";xt();var Ds="paste-transform";function Na(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function Ra(e){let o={};for(let t of e)o[t.id]=t.criterion;return{worthChanging:io("The text is in the wrong shape for where it is being pasted, and a mechanical reshaping would fix it.",{true:"The destination renders or stores formatted text, and the clipboard arrived in a shape that will not come out right: lines hard-wrapped mid-sentence going into prose, a link carrying campaign or tracking parameters, JSON collapsed onto one line, separate items going somewhere that renders a list, text padded with stray whitespace from a web page. The fix is mechanical and is what the person would have done by hand after pasting.",false:"The text is already in the right shape for this destination, OR its exact bytes carry meaning that reformatting would destroy \u2014 a credential, a command, a path, code, an identifier, a search query \u2014 OR the destination is a terminal, a password field, a URL bar or a code editor, where introduced formatting would corrupt what is pasted."}),shape:Jo(o,"What shape should this paste arrive in?")}}function _a(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 dg=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"]),gg=e=>/^https?:\/\/\S+$/i.test(e.trim()),Ps=[{id:"asIs",criterion:"Paste it unchanged. The text is already in the right shape for where it is going, or it is something whose exact bytes matter \u2014 a password, a token, a command, code, an identifier.",label:"unchanged",apply:e=>e},{id:"unwrap",criterion:"Join lines that were hard-wrapped back into continuous paragraphs, keeping blank lines as paragraph breaks. For text copied out of a PDF, an email or a terminal, where every line ends at a fixed width mid-sentence.",label:"unwrap lines",apply:e=>{let o=e.split(`
277
277
  `);if(o.length<3)return null;let t=0;for(let n=0;n<o.length-1;n++){let s=o[n].trim(),i=o[n+1].trim();s.length>40&&i.length>0&&!/[.!?:;]$/.test(s)&&t++}return t<2?null:e.split(/\n\s*\n/).map(n=>n.split(`
278
278
  `).map(s=>s.trim()).filter(Boolean).join(" ")).filter(Boolean).join(`
279
279
 
@@ -281,70 +281,78 @@ The image is the region ${Md(o)}.`},{type:"image_url",image_url:{url:`data:image
281
281
  `).map(t=>t.trim()).filter(Boolean);return o.length<2||o.every(t=>/^([-*+]|\d+[.)])\s/.test(t))?null:o.map(t=>`- ${t}`).join(`
282
282
  `)}},{id:"quote",criterion:"Prefix every line with a markdown blockquote marker. For quoting someone else's words into a document, an issue or a message.",label:"blockquote",apply:e=>{let o=e.split(`
283
283
  `);return o.every(t=>t.startsWith(">")||!t.trim())?null:o.map(t=>t.trim()?`> ${t}`:">").join(`
284
- `)}},{id:"codeFence",criterion:"Wrap it in a fenced code block. For code, a command, a log line or structured output going somewhere that renders markdown.",label:"code block",apply:e=>e.trim().startsWith("```")?null:"```\n"+e.replace(/\n+$/,"")+"\n```"},{id:"prettyJson",criterion:"Re-indent it as readable JSON. Only for text that already parses as JSON.",label:"format JSON",apply:e=>{let o=e.trim();if(!/^[[{]/.test(o))return null;try{let t=JSON.parse(o),n=JSON.stringify(t,null,2);return n===o?null:n}catch{return null}}},{id:"cleanUrl",criterion:"Strip campaign and tracking parameters from the link, keeping the rest of it intact. For a URL copied out of a share sheet, a newsletter or a social post.",label:"clean the link",apply:e=>{let o=e.trim();if(!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(`
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(!gg(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])dg.has(s.toLowerCase())&&(t.searchParams.delete(s),n++);return n===0?null:t.toString().replace(/\?$/,"")}catch{return null}}},{id:"slug",criterion:"Convert to a lowercase hyphenated slug. For a title or phrase going into a branch name, a filename or a URL path.",label:"slug",apply:e=>{let o=e.trim();if(o.includes(`
285
285
  `)||o.length>90||o.length<3)return null;let t=o.normalize("NFKD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t&&t!==o?t:null}},{id:"collapseSpace",criterion:"Collapse runs of whitespace and trim the ends, leaving one clean line. For text copied out of a web page that arrived padded with stray spaces, tabs and newlines.",label:"tidy whitespace",apply:e=>{let o=e.replace(/[ \t]+/g," ").replace(/\s*\n\s*/g,`
286
- `).trim();return o===e?null:o}}];function 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)}
286
+ `).trim();return o===e?null:o}}];function Da(e){let o=[];for(let t of Ps){let n=t.apply(e);n!==null&&(t.id!=="asIs"&&n===e||o.push({transform:t,result:n}))}return o}function Pa(e,o=320){if(e.length<=o)return e;let t=Math.floor(o*.7),n=o-t;return`${e.slice(0,t)}
287
287
  \u2026[${e.length-o} more characters]\u2026
288
- ${e.slice(-n)}`}function 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(`
288
+ ${e.slice(-n)}`}function La(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 Ls=pg(Ua),qa=new mg().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 (${Ps.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=kg();c===null&&(console.log(je.yellow(" nothing to undo")),process.exit(2)),await Ba(c),console.log(` ${je.green("\u2192")} clipboard restored`);return}let o=await vg();if(o||(console.log(je.yellow(" clipboard is empty")),process.exit(2)),La(o)){Wa(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=Da(o),n=await xg();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 rt(e,c.transform.id,c.result,o,"forced",1);return}if(t.length<2){await rt(e,"asIs",o,o,"nothing else applies",0);return}let s=await Ke(Ds,Na({preview:Pa(o),length:o.length,lineCount:o.split(`
290
+ `).length,app:n.app,destination:n.role,destinationLabel:n.label}),Ra(t.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:t.length,chars:o.length}});if(!s){await rt(e,"asIs",o,o,`seat unavailable \u2014 set decisions.seats.${Ds}.mode`,0);return}let i=_a(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await rt(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 rt(e,"asIs",o,o,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await rt(e,a.transform.id,a.result,o,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function rt(e,o,t,n,s,i){let r=t!==n;r&&(e.apply||e.paste)&&($g(n),await Ba(t)),Wa(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await Ls(Se,["key","--name","v","--mod","command"]).catch(a=>{console.log(je.red(` could not paste: ${a?.message??a}`))})}function Wa(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(Ma(o.original))),console.log(je.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(Ma(o.result)),!e.apply&&!e.paste&&console.log(je.dim(`
291
+ (dry run \u2014 pass --apply to write it back)`))}var Ma=(e,o=400)=>(e.length>o?`${e.slice(0,o)}\u2026`:e).split(`
292
292
  `).map(t=>` ${t}`).join(`
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(`
293
+ `),_n=wg(yg(),".agentx","paste-undo.txt");function $g(e){try{hg(bg(_n),{recursive:!0}),Fa(_n,e,{mode:384})}catch{}}function kg(){try{let e=fg(_n,"utf-8");return Fa(_n,"",{mode:384}),e.length?e:null}catch{return null}}async function vg(){let{stdout:e}=await Ls("pbpaste",[],{maxBuffer:16777216});return e}async function Ba(e){await new Promise((o,t)=>{Ua("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function xg(){if(!ug(Se))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await Ls(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:Sg(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function Sg(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 Eg}from"commander";import Ye from"chalk";var Ag=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function Og(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(`${Ag}/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 Ja=new Eg().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 ar,n=ir(),s=o.sound===!1?!1:void 0;if(o.status){let r=t.list();if(o.json){console.log(JSON.stringify({focus:n,held:r},null,2));return}console.log(` ${n.active?Ye.yellow("\u25D0"):Ye.green("\u25CB")} ${rr(n)} ${Ye.dim(`\xB7 ${n.reason}`)}`),console.log(` ${r.length} held`);for(let a of r.slice(0,8)){let c=new Date(a.at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(Ye.dim(` ${c} ${a.from}: ${a.message.slice(0,70)}`))}return}let i=Og(o.channel,o.chatId);if(o.flush){let r=await lr(i,{queue:t,sound:s});console.log(r?Ye.green(` delivered ${r} held notification(s)`):Ye.dim(" nothing was held"));return}e?.trim()||(console.log(Ye.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let r=await cr({message:e.trim(),from:o.from,title:o.title,priority:Number(o.priority)||4,urgent:!!o.urgent,channel:o.channel,chatId:o.chatId},i,{queue:t,sound:s,focus:n});if(o.json){console.log(JSON.stringify(r,null,2));return}let a=r.delivered?Ye.green("\u2192"):Ye.yellow("\u23F8");console.log(` ${a} ${r.reason}`),r.held&&console.log(Ye.dim(" it will arrive with the others when Focus ends"))}catch(r){console.log(Ye.red(` ${r?.message??r}`)),s!==!1&&dr(),process.exit(1)}});St();Ni();Si();xt();import{Command as Ig}from"commander";import{readFileSync as jg}from"fs";var Ha=new Ig().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?jg(e.file,"utf8"):await Cg()}catch(r){Lo(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return Lo("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return Lo(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return Lo("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return Lo("spec needs at least one entry in `questions`");try{Ai(t.questions)}catch(r){return Lo(r?.message??String(r))}let n=t.seat||e.seat;Ho(),process.env[_i(n)]="active";let s=null;if(e.record!==!1)try{s=new en({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
295
+ `)}Ri({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 Lo(`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 Lo(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function Cg(){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")}St();import{Command as Ug}from"commander";import{execFile as Fg,spawn as Ya}from"child_process";import{promisify as qg}from"util";import{existsSync as Wg,statSync as Bg}from"fs";import{join as Va}from"path";import{tmpdir as Jg}from"os";import X from"chalk";var Tg={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."}]},Ng={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."}]},Rg={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."}]},Ms=[Tg,Ng,Rg];we();we();import to from"chalk";import{execFile as _g}from"child_process";import{promisify as Dg}from"util";import{createInterface as Pg}from"readline";var Ga=Dg(_g);function Lg(e){e.type==="step"?console.log(`${to.cyan(` ${e.n}. ${e.action}`)}${e.target?to.dim(` "${e.target}"`):""} ${e.say}`):e.type==="changed"?console.log(to.dim(` ${e.changed?"screen changed":"no change"}`)):e.type==="acted"?console.log(e.error?to.red(` failed: ${e.error}`):to.dim(" done it")):e.type==="door"?console.log(to.cyan(` you: ${e.text}`)):e.type==="error"?console.log(to.red(` error: ${e.error}`)):e.type==="end"&&console.log(to.dim(` \xB7 ended (${e.reason})`))}async function Mg(e,o){let t=Date.now()+o;for(let n=0;Date.now()<t;n++){n&&n%10===0&&await Ga("open",["-a",e]).catch(()=>{});try{let s=(await ps()).app;if(s.toLowerCase()===e.replace(/\.app$/i,"").toLowerCase())return s}catch{}await new Promise(s=>setTimeout(s,500))}return null}async function za(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 Ga("open",["-a",o.app]),i=await Mg(o.app,15e3)??void 0,!i))throw new Error(`${o.app} did not come to the front`);let r=dn(n,t.agents,!1),a=Tr(n,t.agents[n]),c=new Er({goal:e,app:i,mode:s,speaker:r,actionsAllowed:a.allowActions,maxSteps:Number(o.steps)||void 0},{readScreen:ps,presence:new Nr(a,Se,n),speech:new Xo,model:gn({system:Sr(r.persona,"Anis")}),act:Cr});c.on(Lg),console.log(to.bold(`
296
+ ${a.name} teaches: ${e}`)+to.dim(` (${s}${s==="act"&&!a.allowActions?", actions not allowed":""}; type to cut in, "stop" to end)
297
+ `));let d=Pg({input:process.stdin});d.on("line",g=>{g.trim()&&c.door(g)}),process.once("SIGINT",()=>c.stop("interrupted")),await c.run(),d.close()}var Fs=qg(Fg),Ka=new Ug().name("teach").description("walk through something on screen, speaking and pointing as it goes").argument("[lesson]","lesson id (omit to list)").option("--voice <voice>","system voice name or ElevenLabs voice id (overrides the agent's)").option("--agent <id>","speak in this agent's voice (default: AGENTX_VOICE_AGENT or node.defaultAgent)").option("--no-speak","point only, print the narration").option("--no-hud","skip the on-screen callout").option("--record","record the screen (screencapture) around the lesson").option("--record-dir <path>","where to write the recording").option("--live <goal>","no lesson: the agent reads the screen and teaches this, step by step").option("--mode <mode>","with --live: teach (you do each step), watch (you drive, it coaches) or act (it does it, if allowed)").option("--app <name>","with --live: open this app first").option("-c, --config <path>","with --live: agentx.json to read the agent from").option("--steps <n>","with --live: most steps before it stops (default 12)").action(async(e,o)=>{if(o.live)try{await za(String(o.live),o),process.exit(0)}catch(g){console.log(X.red(` ${g?.message??g}`)),process.exit(1)}if(!e){console.log(X.bold(`
298
298
  lessons
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(`
299
+ `));for(let g of Ms)console.log(` ${X.cyan(g.id.padEnd(22))} ${g.title}`),console.log(` ${" ".repeat(22)} ${X.dim(g.appHint)}
300
+ `);return}let t=Ms.find(g=>g.id===e);t||(console.log(X.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),Wg(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:zg(o.voice,o.agent);console.log(X.bold(`
301
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.
302
+ `));try{t.start&&(await Fs("/usr/bin/open",Hg(t.start)),await ko(2e3),await Dn(t.start.ready))}catch(g){console.log(X.red(` setup stopped: ${g?.message??g}`)),process.exitCode=3;return}let s=null,i=null;o.record&&(i=Va(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(X.dim(` recording \u2192 ${i}`)),s=Ya("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await ko(2e3));let r=o.hud===!1?null:Ya(Se,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(g,l,p,f)=>{try{r?.stdin?.write(JSON.stringify({title:g,body:l,state:p,avoid:f})+`
303
+ `)}catch{}},c=[],d=!1;try{for(let[g,l]of t.steps.entries()){if(console.log(` ${X.dim(String(g+1).padStart(2))} ${l.say}`),a(`Step ${g+1} of ${t.steps.length}`,l.say,"talking"),l.click||l.type||l.key){if(!l.before)throw new Error(`Step ${g+1} needs a before claim`);await Dn(l.before)}let p=o.speak===!1?Promise.resolve():Vg(l.say,n),f=l.find?await Gg(l.find,c):null;if(l.find&&!f)throw c.push({tried:l.find,changed:!1,note:"not found on screen"}),await p,new Error(`Could not find "${l.find}"; stopped before acting`);if(await p,f&&(a(`Step ${g+1} of ${t.steps.length}`,l.say,"pointing",{x:f.x,y:f.y,w:f.width,h:f.height}),await Fs(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:u,changed:w}=await Us(["click"]);if(u)throw new Error(u);c.push({tried:l.label??l.find??"control",changed:w!==!1,note:u??void 0}),w===!1&&console.log(X.yellow(" \xB7 clicked, but the screen did not change")),await ko(l.afterClickWaitMs??1500)}if(l.type){await Dn(l.before),a(`Step ${g+1} of ${t.steps.length}`,l.type,"typing");let{error:u}=await Us(["type","--text",l.type]);if(u)throw console.log(X.red(` \u2717 ${u}`)),a("Blocked",u,"waiting"),c.push({tried:`type into ${l.label??"the field"}`,changed:!1,note:u}),new Error(u)}if(l.key){await Dn(l.before),a(`Step ${g+1} of ${t.steps.length}`,`\u21B5 ${l.key}`,"typing");let{error:u}=await Us(["key","--name",l.key]);if(u)throw console.log(X.red(` \u2717 ${u}`)),a("Blocked",u,"waiting"),c.push({tried:`press ${l.key}`,changed:!1,note:u}),new Error(u)}if(!f&&!l.type&&!l.key?await ko((l.holdSeconds??1.2)*1e3):l.holdSeconds&&await ko(l.holdSeconds*1e3),l.verify){a(`Step ${g+1} of ${t.steps.length}`,"Checking that worked\u2026","waiting");let u;try{u=await Ft(l.verify)}catch(w){u=null,console.log(X.yellow(` ? could not check: ${w?.message??w}`))}if(!u&&!l.verifyOptional)throw new Error(`Could not verify: ${l.verify}`);if(u){let w=u.outcome==="confirmed"?X.green("\u2713"):u.outcome==="refuted"?X.red("\u2717"):X.yellow("?");if(console.log(` ${w} ${X.dim(u.reason)}`),!u.ok&&!l.verifyOptional){a("Stopped",`That did not work: ${l.verify}`,"waiting"),console.log(X.red(`
304
+ stopping: could not confirm \u2014 ${l.verify}`)),console.log(X.dim(` ${u.reason}`)),console.log(X.dim(` screenshot: ${u.sighting.shot.path}`)),await ko(2500);try{r?.stdin?.end()}catch{}d=!0;break}}}}}catch(g){d=!0,console.log(X.red(` stopping: ${g?.message??g}`)),a("Stopped",String(g?.message??g),"waiting")}finally{if(d)try{r?.stdin?.end()}catch{}}if(!d){a("Done",t.title,"done"),await ko(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await ko(2500);try{let{size:g}=Bg(i);console.log(X.green(` recorded ${(g/1048576).toFixed(1)} MB \u2192 ${i}`))}catch{console.log(X.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(d){console.log(X.red(` lesson stopped before the end.
305
305
  `)),process.exitCode=3;return}console.log(X.green(`
306
306
  done.
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
307
+ `))});function Hg(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${Va(Jg(),"agentx-teach-chrome")}`,"--no-first-run","--no-default-browser-check","--window-position=0,200","--window-size=1440,680",`--app=${e.url}`]:["-a",e.app,e.url]}async function Dn(e){let o=await Ft(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function Us(e){try{let{stdout:o}=await Fs(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 Gg(e,o=[]){try{let t=await un({max:45});if(t.candidates.length<2)return null;let n=await Ke(Mt,jn({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),Cn(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=Tn(n.answers,t.candidates);return s.present<.5?null:It(t,s.id)}catch{return null}}function zg(e,o){let t=e?an(e,Ot()):null;if(t)return{provider:"system",elevenlabs:ln(),system:t.id,fallback:!0};if(e)return{provider:"elevenlabs",elevenlabs:e,system:null,fallback:!0};try{let n=D(),s=o||process.env.AGENTX_VOICE_AGENT||n.node.defaultAgent;return s&&!n.agents[s]&&console.log(X.yellow(` no agent "${s}" in agentx.json \u2014 using the default voice`)),s&&n.agents[s]?br(wr(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:ln(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(X.dim(` no agent voice (${String(n?.message??n).split(`
308
+ `)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:ln(),system:null,fallback:!0}}}var Yg=new Xo;async function Vg(e,o){o&&await Yg.say({voice:o,text:e})}var ko=e=>new Promise(o=>setTimeout(o,e));we();import{Command as Xa}from"commander";import Le from"chalk";import{createInterface as Qa}from"readline";var Kg=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function at(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(Kg()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function Xg(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 Za(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=D(t.config),s=n.agents,i;if(e.some(l=>!s[l])){let l=await at("GET","/mesh").then(p=>Array.isArray(p.data)?p.data:[]).catch(()=>[]);i=new kr(()=>n,()=>l),i.usePool(await $r(vr()))}let r=e.map(l=>s[l]?dn(l,s,!0):i?.speaker(l,!0)),a=e.filter((l,p)=>!r[p]);if(a.length)throw new Error(`Unknown agent: ${a.join(", ")}`);let c=Date.now(),d=new xr({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new Xo,model:(l,p)=>gn({system:p})});d.on(Xg),d.on(l=>{l.type==="line"&&l.turn===0&&console.log(Le.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=Qa({input:process.stdin});g.on("line",l=>{l.trim()&&d.door(l)}),process.once("SIGINT",()=>d.stop("interrupted")),await d.run(),g.close(),console.log(Le.dim(` ${Za(d.gaps)}`))}async function Zg(e,o,t){let n=await at("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=Qa({input:process.stdin});s.on("line",a=>{a.trim()&&at("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void at("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await at("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(` ${Za(r)}`))}var ec=new Xa().name("talk").description('two agents, local or on a mesh peer, talk a topic through out loud; type to cut in, "stop" to end').argument("<agentA>").argument("<agentB>").argument("<topic...>").option("--context <text>","a few lines of context both agents should know").option("--turns <n>","most lines before they wrap up (default 10)").option("--local","run the talk in this process instead of the daemon").option("-c, --config <path>","agentx.json for --local (default: the usual lookup)").action(async(e,o,t,n)=>{let s=t.join(" ");try{await(n.local?Qg:Zg)([e,o],s,n),process.exit(0)}catch(i){console.error(Le.red(` ${i?.message??i}`)),process.exit(1)}}),oc=new Xa().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 at("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))});we();import{Command as em}from"commander";import Me from"chalk";import{existsSync as om,readFileSync as tm,writeFileSync as nm}from"fs";import{resolve as tc}from"path";var Pn=new em().name("voice").description("list installed system voices and pick each agent's voice");function sm(e){let o=e?[e]:[tc(process.cwd(),"agentx.json"),tc(process.cwd(),".agentx/config.json")],t=o.find(n=>om(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function im(e,o,t,n,s){let i=e?.agents?.[o];if(!i)throw new Error(`No agent "${o}" in agentx.json`);if(n&&n!=="system"&&n!=="elevenlabs")throw new Error("--provider must be system or elevenlabs");if(!t&&!n)throw new Error("Give a voice, a --provider, or both");let r={...i.voice??{}};n&&(r.provider=n);let a=r.provider??e?.voice?.provider??"system",c=n?`provider ${n}`:"";if(t){let d=an(t,s,e?.voice?.locale);if(d&&a==="system")r.system=t,c=[c,`system voice ${cn(d)}`].filter(Boolean).join(", ");else if(a==="elevenlabs"&&!d)r.elevenlabsVoiceId=t,c=[c,`ElevenLabs voice ${t}`].filter(Boolean).join(", ");else if(d)r.system=t,c=[c,`fallback system voice ${cn(d)}`].filter(Boolean).join(", ");else throw new Error(`"${t}" is not an installed system voice. Run \`agentx voice list\`, or add --provider elevenlabs for an ElevenLabs voice id.`)}return{raw:{...e,agents:{...e.agents,[o]:{...i,voice:r}}},summary:c}}Pn.command("list").alias("ls").description("installed system voices, best first, and which agent uses which").option("--all","every language, not only the configured one").option("-c, --config <path>","agentx.json to read").action(e=>{let o=Ot(),t;try{t=D(e.config)}catch{}let n=t?.voice.locale??"en",s=new Map;if(t)for(let[i,r]of gs(t.agents,t.voice,o))s.set(r.id,[...s.get(r.id)??[],i]);if(!o.length)console.log(Me.yellow(`
309
+ No system voices found (system voices need macOS).
310
+ `));else{let i=e.all?ds(o,""):ds(o,n);console.log(Me.bold(`
311
+ System voices${e.all?"":` (${n})`}, best first
312
+ `));for(let r of i){let a=r.quality==="standard"?Me.dim("standard"):Me.green(r.quality),c=s.get(r.id)?.join(", ");console.log(` ${r.name.padEnd(12)} ${r.locale.padEnd(6)} ${a.padEnd(18)} ${Me.dim((r.gender??"").padEnd(7))} ${c?Me.cyan(c):""}`)}o.some(r=>r.quality!=="standard")||(console.log(Me.dim(`
313
+ More natural voices are free: System Settings \u2192 Accessibility \u2192 Spoken Content \u2192`)),console.log(Me.dim(" System Voice \u2192 Manage Voices, then download a Premium or Enhanced voice.")))}if(t){console.log(Me.bold(`
314
+ Agents
315
+ `));let i=gs(t.agents,t.voice,o);for(let[r,a]of Object.entries(t.agents)){let c=a.voice?.provider??t.voice.provider,d=i.get(r),g=c==="elevenlabs"?`elevenlabs ${a.voice?.elevenlabsVoiceId??Me.dim("(default voice)")}`:`system ${d?cn(d):Me.dim("(OS default)")}`;console.log(` ${r.padEnd(24)} ${g}`)}}console.log()});Pn.command("set <agent> [voice]").description("pick an agent's voice: a system voice name, or an ElevenLabs id with --provider elevenlabs").option("--provider <provider>","system or elevenlabs").option("-c, --config <path>","agentx.json to change").action((e,o,t)=>{try{let n=sm(t.config),{raw:s,summary:i}=im(JSON.parse(tm(n,"utf8")),e,o,t.provider,Ot());nm(n,JSON.stringify(s,null,2)+`
316
+ `),console.log(Me.green(` ${e}: ${i}`)),console.log(Me.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(Me.red(` ${n.message}`)),process.exit(1)}});import{Command as rm}from"commander";import M from"chalk";var Mo=new rm().name("attach").description("wear an agentx agent identity in this Claude Code session"),qs=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Tt()}`;function Ws(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function Bs(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 Js(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 nc(e){return e==="auto"?M.yellow:e==="manual"?M.gray:M.green}function am(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)} ${nc(e.mode)(e.mode)} ${n} ${M.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${M.gray(e.cwd)}`)}Mo.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${as.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",qs).action(async(e,o)=>{let t=Ws(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)),Ui(o.mode)||(console.error(M.red(`Invalid mode "${o.mode}". Expected one of: ${as.join(", ")}`)),process.exit(1)),xn()||(console.error(M.yellow("Attach hooks are not installed yet.")),console.error(`Run ${M.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{let n=await Bs(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)} (${nc(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: ${Js(n)}`)),process.exit(1)}});Mo.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",qs).action(async e=>{let o=Ws(e.session);o||(console.error(M.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await Bs(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: ${Js(t)}`)),process.exit(1)}});Mo.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",qs).option("--json","raw JSON output").action(async e=>{let o=Ws();try{let n=(await Bs(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:xn(),sessions:n},null,2));return}console.log(),console.log(xn()?`${M.green("\u2713")} Attach hooks installed ${M.gray(Ct())}`:`${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)am(r,r.sessionId===o);let i=n.length-s.length;i>0&&console.log(M.gray(`
317
+ ${i} registered session(s) with no binding.`)),console.log()}catch(t){console.error(M.red(`Could not read attach state: ${Js(t)}`)),process.exit(1)}});Mo.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||Tt()),t=oa(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
310
318
  settings \u2014 without this an attached production identity would be less
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(`
319
+ guarded than a spawned one.)`))):console.log(M.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${M.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(M.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Mo.command("uninstall").description("remove the attach hooks from ~/.claude/settings.json").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--remove-guard","also remove the PreToolUse guard hook").action(e=>{try{let o=ta({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${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 cm}from"commander";import pe from"chalk";var Ln=new cm().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function ic(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 rc(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function sc(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 lm(e){return e==="busy"?pe.magenta:e==="warm-hot"?pe.green:e==="warm-cold"?pe.cyan:e==="idle"?pe.yellow:e==="dead"?pe.red:pe.dim}Ln.command("list").description("list every live persistent claude process").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("--json","emit JSON").action(async e=>{let{baseUrl:o,token:t}=ic(e),n;try{n=await fetch(`${o}/api/processes`,{headers:rc(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=lm(r.state)(r.state.padEnd(9)),c=sc(r.spawnedAt),d=r.lastTurnAt?sc(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?pe.dim(`last_in=${r.lastInputTokens} tok`):"",l=r.claudeSessionId?pe.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):pe.dim("sess=\u2014"),p=r.pendingTaskId?pe.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${pe.bold(r.key.agentId)}${pe.dim(":"+r.key.channel+":"+r.key.chatId)} ${pe.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${d} ${l} ${g} ${p}`),r.deadReason&&console.log(` ${pe.red("dead:")} ${r.deadReason}`)}});Ln.command("kill <agentId> <channel> <chatId>").description("force-kill one persistent process (the next dispatch will spawn fresh)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("-r, --reason <reason>","kill reason (recorded on the dead-process snapshot)","operator-cli").action(async(e,o,t,n)=>{let{baseUrl:s,token:i}=ic(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:rc(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 dm}from"commander";import Ce from"chalk";import{existsSync as Hs,rmSync as gm}from"fs";import{resolve as Gs}from"path";var ct=new dm().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");ct.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 Bi(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}`))});ct.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=Gs(e.cwd,".agentx","rag");if(!Hs(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=>Hs(Gs(o,s,"index.json")));if(n.length===0){console.log(Ce.dim(" (no indexes)"));return}for(let s of n.sort()){let i=cs(s);console.log(` ${Ce.bold(s)} ${i.docs} doc(s) ${Ce.dim(i.path)}`)}});ct.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=Ji(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=cs(e);i.exists?console.log(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))}`)});ct.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=Gs(process.cwd(),".agentx","rag",e);if(!Hs(o)){console.log(Ce.dim(` no index for ${e} \u2014 nothing to clear`));return}gm(o,{recursive:!0,force:!0}),console.log(Ce.green(` \u2713 cleared index for ${e}`))});we();import{Command as mm}from"commander";import K from"chalk";import lt from"prompts";var Uo=new mm().name("backlog").description("manage the local backlog used by business workSource=backlog");function qt(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 Rr(n)}}function pm(e){return e?K.cyan(`${e.type}:${e.project}#${e.iid}`):K.dim("manual")}function um(e){return{todo:K.gray("todo"),doing:K.yellow("doing"),blocked:K.red("blocked"),done:K.green("done")}[e]}Uo.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}=qt(e.config),t=o.list();if(e.status&&(t=t.filter(n=>n.status===e.status)),e.assignee&&(t=t.filter(n=>n.assignee===e.assignee)),e.source&&(t=t.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!t.length){console.log(K.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?K.magenta(`@${n.assignee}`):K.dim("unassigned");console.log(` ${um(n.status).padEnd(7)} ${pm(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(K.dim(` ${n.source.url}`))}console.log(),console.log(K.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});Uo.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=qt(t.config);n.store.findById(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(K.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=_r([o],i.source,n.config),a=await fs(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(K.dim(" sync:"),...c));console.log(a.ok?K.dim(` synced -> ${a.url??i.source.type}`):K.yellow(` sync failed: ${a.error}`))}});Uo.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=qt(o.config);t.store.findById(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(K.green(` done: ${s.title}`)),s.source){let i=await fs(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(K.dim(" sync:"),...r));console.log(i.ok?K.dim(` synced -> ${i.url??s.source.type}`):K.yellow(` sync failed: ${i.error}`))}});Uo.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}=qt(o.config);t.remove(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1)),console.log(K.green(` removed ${e}`))});Uo.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=qt(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(K.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let y=[t&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await lt({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!t&&(console.error(K.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(K.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?hm(o.config):ym(o.config);y.length?(i=(await lt({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 lt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await lt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await lt({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(K.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await wm(o.config,i,a):await bm(o.config,i,a);if(!c.length){console.log(K.yellow(" no open issues matched"));return}console.log(K.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let d=i,g=new Set(o.store.list().map(y=>y.id)),l=c.map(y=>{let $=us({type:s,project:d,iid:y.iid,url:y.url}),b=g.has($),v=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${v}${b?K.dim(" (already imported)"):""}`,value:y,disabled:b}}),f=(await lt({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:l,min:1})).selected||[];if(!f.length){console.log(K.dim(" nothing selected"));return}let u=f.map(y=>{let $={type:s,host:s==="gitlab"?fm(o.config):void 0,project:d,iid:y.iid,url:y.url};return{id:us($),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:$,importedAt:new Date().toISOString()}}),w=o.store.addMany(u);console.log(K.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(K.dim(` ${y.id} \u2014 ${y.title}`))});function fm(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function hm(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 ym(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 wm(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 bm(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(ac)}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(ac):[]}function ac(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 vm}from"commander";import z from"chalk";import{existsSync as xm,readFileSync as Sm}from"fs";import{resolve as Em}from"path";import Am from"prompts";we();import $m from"cronstrue";var zs={sun:0,sunday:0,mon:1,monday:1,tue:2,tuesday:2,tues:2,wed:3,wednesday:3,thu:4,thursday:4,thurs:4,fri:5,friday:5,sat:6,saturday:6},Mn={morning:{h:9,m:0},afternoon:{h:14,m:0},evening:{h:18,m:0},night:{h:22,m:0},noon:{h:12,m:0},midnight:{h:0,m:0}};function no(e){try{return $m.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function km(e){if(/\b(noon|midday)\b/.test(e))return Mn.noon;if(/\bmidnight\b/.test(e))return Mn.midnight;let o=e.match(/\b(?:at|by|@)\s*(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/);if(o){let t=parseInt(o[1],10),n=o[2]?parseInt(o[2],10):0,s=o[3];return s==="pm"&&t<12&&(t+=12),s==="am"&&t===12&&(t=0),t>23||n>59?null:{h:t,m:n}}return null}function Ys(e){let o=e.trim().toLowerCase();if(!o)return null;let t;if(t=o.match(/\bevery\s+(\d+)\s*(minutes|mins|m)\b/)){let l=parseInt(t[1],10);return l<1||l>59?null:{cron:`*/${l} * * * *`,human:no(`*/${l} * * * *`),matched:t[0]}}if(/\bevery\s+minute\b/.test(o))return{cron:"* * * * *",human:no("* * * * *"),matched:"every minute"};if(t=o.match(/\bevery\s+(\d+)\s*(hours|hrs|h)\b/)){let l=parseInt(t[1],10);return l<1||l>23?null:{cron:`0 */${l} * * *`,human:no(`0 */${l} * * *`),matched:t[0]}}if(/\b(every hour|hourly)\b/.test(o))return{cron:"0 * * * *",human:no("0 * * * *"),matched:"every hour"};let n=km(o),s=null;for(let[l,p]of Object.entries(Mn))if(!(l==="noon"||l==="midnight")&&new RegExp(`\\b(every\\s+)?${l}s?\\b`).test(o)){s=p;break}let i=n||s,r=o.match(/\b(first|1st|2nd|3rd|last|(\d+)(?:st|nd|rd|th)?)\s+(day\s+)?of\s+(every|each|the)\s+month\b/);if(r){let l=r[1],p=1;if(l==="last"||(/^\d+(st|nd|rd|th)?$/.test(l)?p=parseInt(l,10):l==="first"||l==="1st"?p=1:l==="2nd"?p=2:l==="3rd"&&(p=3),p<1||p>31))return null;let f=i||{h:9,m:0},u=`${f.m} ${f.h} ${p} * *`;return{cron:u,human:no(u),matched:r[0]}}let a=[],c=Object.keys(zs).join("|"),d=new RegExp(`\\b(?:every|on|each|by)\\s+((?:${c})s?(?:\\s*(?:,|and|&)\\s*(?:${c})s?)*)\\b`),g=o.match(d);if(g){let l=g[1];for(let p of Object.keys(zs))if(new RegExp(`\\b${p}s?\\b`).test(l)){let f=zs[p];a.includes(f)||a.push(f)}}if(a.length){let l=i||{h:9,m:0};a.sort((u,w)=>u-w);let p=a.join(","),f=`${l.m} ${l.h} * * ${p}`;return{cron:f,human:no(f),matched:`on ${p}`}}if(/\b(weekday|workday|business day)s?\b/.test(o)){let l=i||{h:9,m:0},p=`${l.m} ${l.h} * * 1-5`;return{cron:p,human:no(p),matched:"weekdays"}}if(/\bweekends?\b/.test(o)){let l=i||{h:9,m:0},p=`${l.m} ${l.h} * * 0,6`;return{cron:p,human:no(p),matched:"weekends"}}if(/\b(every day|daily|each day)\b/.test(o)||s){let l=i||{h:9,m:0},p=`${l.m} ${l.h} * * *`;return{cron:p,human:no(p),matched:s&&Object.entries(Mn).find(([,f])=>f===s)?.[0]||"daily"}}if(n){let l=`${n.m} ${n.h} * * *`;return{cron:l,human:no(l),matched:`at ${n.h}:${String(n.m).padStart(2,"0")}`}}return null}function cc(e,o){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"job"}-${o}`}function lc(e){let o=e||Em(process.cwd(),"agentx.json");return xm(o)||(console.log(z.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Sm(o,"utf-8"))}function Om(e){return e?e.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o==="log"||o==="notify"||o==="disable"):["log"]}async function Im(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 Am([{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 vo=new vm().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');vo.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){vo.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=Ys(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=lc(o.config),s=Ei(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=Om(o.onError),r=await Im(o.notify,s);r&&!i.includes("notify")&&i.push("notify");let a=o.id||cc(t.matched,o.agent),c={enabled:!o.disabled,schedule:t.cron,timezone:o.timezone,agent:o.agent,prompt:o.do,timeout:parseInt(o.timeout,10),onError:i};o.model&&(c.model=o.model),r&&(c.notify=r);let d=await de(l=>be(l,`crons.${a}`,c),{configPath:o.config,dryRun:!!o.dryRun});d.success||(console.log(z.red(` \u2717 ${d.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(z.green(` \u2713 ${g} cron ${z.cyan(a)}`)),console.log(z.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(z.dim(` Agent: ${o.agent}`)),r&&console.log(z.dim(` Notify: ${r.channel} ${r.chatId}`)),i.length&&console.log(z.dim(` On error: ${i.join(", ")}`)),!o.dryRun&&d.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});vo.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=lc(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]])vo.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await de(s=>{if(!Co(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."))});vo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await de(t=>{if(!Co(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);Yi(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."))});vo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Ys(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 Xm}from"commander";import dt from"chalk";import Z from"chalk";import Bt from"prompts";import{readFileSync as jm,writeFileSync as Cm,existsSync as Tm}from"fs";import{resolve as dc}from"path";var Nm=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Rm(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function Vs(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function gc(e=".env"){let o=dc(e);if(!Tm(o))return[];let t=jm(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(Nm);i?n.push({kind:"kv",key:i[1],value:Rm(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function _m(e){return e.map(o=>o.kind==="kv"?`${o.key}=${Vs(o.value)}`:o.raw).join(`
312
320
  `)+`
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(`
321
+ `}function Wt(e,o,t=".env"){let n=dc(t),s=gc(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Vs(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Vs(o)}`})),Cm(n,_m(s))}function Ks(e,o=".env"){return gc(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var mc="https://t.me/BotFather";async function Dm(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 Pm(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 pc(e={}){console.log(),console.log(Z.bold(" Connect Telegram")),console.log(),console.log(Z.dim(` 1. Open ${mc}`)),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 Bt({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,[mc],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Bt({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 Dm(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 Bt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:d.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(Z.red(" Aborted")),process.exit(1));let l=c.channels?.telegram?.accounts||{},p=e.account||g;l[p]&&l[p].agentBinding!==g&&(p=(await Bt({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(Z.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Wt(f,t.trim()),process.env[f]=t.trim();let u=await de(b=>{be(b,"channels.telegram.enabled",!0),be(b,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:g});let v=Co(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),be(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(u.success||(console.log(Z.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(Z.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(Z.dim(` Token stored in .env as ${f}`)),console.log(Z.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(Z.dim(" Daemon hot-reloaded.")):console.log(Z.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await Bt({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 Pm(t.trim(),9e4);if(!y){console.log(Z.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Z.dim(" agentx config set notifications.destination.channel telegram")),console.log(Z.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Z.dim(` agentx config set notifications.destination.accountId ${p}`));return}let $=await de(b=>{be(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:p})},{configPath:e.configPath});if(!$.success){console.log(Z.red(` \u2717 failed to save destination: ${$.error}`));return}console.log(Z.green(" \u2713 Default --notify target set")),console.log(Z.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Z.dim(" From now on, --notify me resolves to this chat.")),$.reloaded&&console.log(Z.dim(" Daemon hot-reloaded."))}import ue from"chalk";import Xs from"prompts";import{existsSync as Zs,mkdirSync as Lm,readdirSync as Mm,readFileSync as uc}from"fs";import{resolve as Qs}from"path";var Um=".agentx/whatsapp-sessions";function Fm(){let e=Qs(process.cwd(),".agentx/daemon.pid");if(!Zs(e))return!1;try{let o=parseInt(uc(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function qm(e){if(!Zs(e))return!1;try{return Mm(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Wm(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;Lm(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},d=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return d.ev.on("creds.update",r),await new Promise(g=>{let p=setTimeout(()=>{o(ue.yellow(" Timed out waiting for scan (2min)."));try{d.end(void 0)}catch{}g(!1)},12e4);d.ev.on("connection.update",async f=>{if(f.qr){o(ue.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:u}=await import("qrcode-terminal");u.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(p),o(ue.green(" \u2713 Paired"));try{d.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),o(ue.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function fc(e={}){if(console.log(),console.log(ue.bold(" Connect WhatsApp")),console.log(),Fm()){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 Xs({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});d||(console.log(ue.red(" Aborted")),process.exit(1))}let o=e.configPath||Qs(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(uc(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Um,s=Qs(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 Xs({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(qm(s)&&a){let{keep:d}=await Xs({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 Wm(s,g=>console.log(g))||(console.log(ue.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await de(d=>{be(d,"channels.whatsapp.enabled",!0),be(d,"channels.whatsapp.sessionDir",n),be(d,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ue.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ue.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ue.dim(` Session: ${n}`)),console.log(ue.dim(" Start the daemon to begin receiving:")),console.log(ue.dim(" agentx daemon start")),console.log(ue.dim(" Add routes later with:")),console.log(ue.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Bm}from"crypto";import $e from"chalk";import hc from"prompts";var Un="agentx-mesh:",Fn="//join/";function Jm(e){return Buffer.from(e,"utf-8").toString("base64url")}function Hm(e){return Buffer.from(e,"base64url").toString("utf-8")}function Gm(e){return`${Un}${Fn}${Jm(JSON.stringify(e))}`}function zm(e){if(!e.startsWith(`${Un}${Fn}`))throw new Error(`Not a mesh invite link \u2014 expected ${Un}${Fn}\u2026`);let o=e.slice(Un.length+Fn.length),t=JSON.parse(Hm(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 Ym(){return Bm(32).toString("hex")}function Vm(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Km(e){return e?.node?.name||e?.node?.id||"node"}async function yc(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=Ks("MESH_TOKEN");r||(r=Ym(),Wt("MESH_TOKEN",r),console.log($e.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Vm(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:l}=await hc({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});l||(console.log($e.red(" Aborted")),process.exit(1)),a=l}let d=await de(l=>{be(l,"mesh.enabled",!0)},{configPath:e.configPath});d.success||(console.log($e.red(` \u2717 ${d.error}`)),process.exit(1));let g=Gm({url:a,token:r,name:Km(i),version:1});console.log(),console.log($e.bold(" Mesh invite")),console.log(),console.log(` ${$e.cyan(g)}`),console.log(),console.log($e.dim(" Run on the other node:")),console.log($e.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log($e.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function wc(e,o={}){let t;try{t=zm(e)}catch(i){console.log($e.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Ks("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await hc({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))}Wt("MESH_TOKEN",t.token);let s=await de(i=>{be(i,"mesh.enabled",!0);let r=Co(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 gt=new Xm().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");gt.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 pc({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});gt.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 fc({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var bc=gt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");bc.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 yc({url:e.url,configPath:e.config})});bc.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 wc(e,{configPath:o.config})});gt.action(()=>{console.log(),console.log(dt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${dt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${dt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${dt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${dt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(dt.dim(" GitLab connect is the next slice.")),console.log()});we();import{Command as Qm}from"commander";import le from"chalk";var Jt=new Qm().name("usage").description("token usage analysis and reporting");Jt.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=D(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(le.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(le.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${le.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${le.red(String(s.totalErrors))}`),console.log(),console.log(le.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let d=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${le.cyan(a)}: ${d} tokens (${c.tasks} tasks) ${le.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(le.red(" Daemon not running. Start with: agentx daemon start")):console.log(le.red(` ${e.message}`))}});Jt.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?"))}});Jt.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-Z6EK44PV.js"),r=await i(),a=new Set(n.filter(l=>l.kind==="cli").map(l=>l.name)),c=[],d=(l,p)=>{for(let f of l.commands??[]){let u=p?`${p} ${f.name()}`:f.name();c.push(u),d(f,u)}};d(r,"");let g=c.filter(l=>!a.has(l)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(le.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let l of g)console.log(` ${le.dim("\xB7")} ${l}`);console.log(),console.log(le.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(le.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(le.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(le.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(le.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(le.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=le.dim(`${i.days}d`);console.log(` ${le.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(le.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Zm}from"commander";import fe from"chalk";import{resolve as ep}from"path";we();var xo=new Zm().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");xo.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{Di(ep(process.cwd(),".env"))}catch{}let o=op(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-2YEYVCUS.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 op(e,o){try{let t=D();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(fe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(fe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
322
+ `)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:o||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}xo.command("list").description("list configured boards").action(()=>{try{let e=D();if(!e.boards?.length){console.log(fe.dim(`
315
323
  No boards configured.
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(`
324
+ `));return}console.log();for(let o of e.boards){console.log(` ${fe.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(fe.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(fe.dim(` primary label: ${o.primaryToolLabel}`)),console.log(fe.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(fe.red(` ${e.message}`)),process.exit(1)}});xo.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{Ht(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)}});xo.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{Ht(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 ei=xo.command("column").description("manage a board's columns (add / remove / edit / list)");ei.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(ul("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)}});ei.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{Ht(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)}});ei.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{Ht(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)}});xo.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Ht(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 Ht(e){let{summary:o,backupPath:t}=Qo(n=>e(n));console.log(fe.green(`
317
325
  \u2713 ${o}
318
326
  `)),t&&console.log(fe.dim(` Backup: ${t}`)),console.log(fe.dim(` Restart the dashboard to pick up the change if not auto-reloading.
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}] ---
327
+ `))}import{Command as tp}from"commander";import m from"chalk";import{resolve as q,relative as $c,dirname as kc}from"path";import{execSync as Fo}from"child_process";import{writeFileSync as qo,mkdirSync as co,readFileSync as Gt,readdirSync as np,renameSync as qn,rmSync as sp,existsSync as Be}from"fs";function ke(e,o){return new rs(zt(e),void 0,o||"graph")}function zt(e){return e||q(process.cwd(),".agentx/wiki")}function ti(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var ee=new tp().name("wiki").description("wiki knowledge base management");ee.command("status").description("show wiki status per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").action(e=>{let o=e.mode,t=ke(e.dir,o),n=t.summary(),i=t.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${ti(o)}]`)),console.log(),console.log(` Total raw entries: ${i}`),console.log(` Agents: ${n.length}`),console.log();for(let a of n){let c=a.unabsorbed>0?m.yellow(`${a.unabsorbed} unabsorbed`):m.green("up to date");if(console.log(` ${m.cyan(a.agentId)}`),console.log(` Entries: ${a.totalEntries} Articles: ${a.totalArticles} ${c}`),a.articles.length>0){for(let d of a.articles.slice(0,3))console.log(m.dim(` - ${d.title} [${(d.tags||[]).slice(0,3).join(", ")}]`));a.articles.length>3&&console.log(m.dim(` ... and ${a.articles.length-3} more`))}console.log()}let r=n.reduce((a,c)=>a+c.unabsorbed,0);r>0&&(console.log(m.dim(` ${r} raw entries on disk. Absorb is deprecated \u2014 see 'agentx wiki absorb --help'.`)),console.log())});ee.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(e=>{let o=ke(e.dir,e.mode),t=e.agent?[e.agent]:o.listAgents(),n=0;console.log();for(let s of t){let r=o.getAgentWiki(s).lint();if(n+=r.length,r.length===0)console.log(` ${m.cyan(s)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(s)}: ${m.yellow(`${r.length} issues`)}`);for(let a of r){let c=a.type==="broken-link"?"x":a.type==="orphan"?"?":"!";console.log(` [${c}] ${m.dim(a.type)} ${a.article}: ${a.message}`)}}}console.log(),n===0&&console.log(m.green(" All agent wikis are healthy")),console.log()});ee.command("absorb").description("compile unabsorbed entries into typed per-agent wiki articles (Farzapedia-faithful)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","absorb only this agent").option("--dry-run","preview without running").option("--no-facts","skip the system-of-record lookups").option("--max <n>","max entries per agent","10").option("--since <date>","only entries dated on or after YYYY-MM-DD").action(async e=>{let o=e.mode,t=ke(e.dir,o),n=e.agent?[e.agent]:t.listAgents(),s=parseInt(e.max),i=(()=>{try{let p=q(process.cwd(),".agentx/graph");return Be(p)?new mo({baseDir:p}):null}catch{return null}})(),r=new Map;if(i)try{let p=i.loadIndex();for(let[f,u]of Object.entries(p.entries))r.set(f,u.path)}catch{}let a,c=p=>{let f=p.meta?.intentPath;if(Array.isArray(f)&&f.every(y=>typeof y=="string")&&f.length>0)return f;if(!i||r.size===0)return;let u=String(p.meta?.sender??""),w=i.fingerprint({text:p.content,channel:p.source,sender:u});return r.get(w)},d=(p,f)=>{let u=new Map;for(let y of p){let $=f.find(x=>x.id===y);if(!$)continue;let b=c($);if(!b?.length)continue;let v=b.join("/"),A=u.get(v);A?A.n++:u.set(v,{path:b,n:1})}if(u.size===0)return;let w;for(let y of u.values())(!w||y.n>w.n)&&(w=y);return w?.path},g=0,l=0;for(let p of n){let f=typeof e.since=="string"?e.since.trim():"",u=t.getUnabsorbedEntries(p).filter(k=>!f||(k.date??"")>=f).slice(0,s);if(u.length===0){console.log(` ${m.cyan(p)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(p)}: ${u.length} entries to absorb`));for(let k of u.slice(0,3))console.log(m.dim(` [${k.date} via ${k.source}] ${k.content.slice(0,80)}...`));if(u.length>3&&console.log(m.dim(` ... and ${u.length-3} more`)),e.dryRun)continue;let w=t.getAgentWiki(p),y=w.rebuildIndex(),$=w.getWorldview()||t.getSharedStore().getWorldview()||"",b=u.map(k=>`--- ENTRY ${k.id} [${k.date} ${k.agentId} via ${k.source}] ---
320
328
  ${k.content}
321
329
  --- END ENTRY ---`).join(`
322
330
 
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(`
331
+ `),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(u.map(B=>({context:B.sourceContext,content:B.content,sender:typeof B.meta?.sender=="string"?B.meta.sender:void 0})),{known:a}),ae=L(u);if(H.length>0||ae.length>0){let B=W(),{records:ve,results:he}=H.length>0?await N(H,{sources:B}):{records:[],results:[]},_=C([...ae,...ve]);v=j(_);let qe=[...ae.length>0?[`entries:${ae.length}`]:[],...he.filter(ye=>ye.records.length>0).map(ye=>`${ye.source}:${ye.records.length}`)];console.log(m.dim(` Facts: ${H.length} entities \u2192 ${_.length} resolved${qe.length?` (${qe.join(" ")})`:""}`));for(let ye of P(he,B))console.log(m.yellow(` ! ${ye.source} ${ye.kind} \u2014 would supply ${ye.provides.join(", ")}`)),console.log(m.dim(` ${ye.hint}`))}}let A=tr(o,p,$,y.articles,b,u.length,v);console.log(m.dim(` Mode: ${ti(o)}`));let x=q(w.baseDir,"_tmp");co(x,{recursive:!0});let E=q(x,"absorb-prompt.txt");qo(E,A),console.log(m.dim(" Compiling with Claude..."));try{let k;try{k=Fo(`cat '${E}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Go({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(_){if(k=_.stdout||"",!k)throw _}let N=k;try{let _=JSON.parse(k);N=_.result||_.content||"",N||(console.log(m.dim(` Claude envelope keys: ${Object.keys(_).join(", ")}`)),console.log(m.dim(` is_error: ${_.is_error}, stop_reason: ${_.stop_reason}`)))}catch{}let C,j=[],P=N.indexOf("{"),W=N.indexOf("["),L=P>=0&&(W<0||P<W)?P:W;if(L===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(N.slice(0,500)));continue}let H=N[L],ae=H==="{"?"}":"]",B=0,ve=-1;for(let _=L;_<N.length;_++)if(N[_]===H)B++;else if(N[_]===ae&&(B--,B===0)){ve=_+1;break}if(ve===-1){console.log(m.red(" Unbalanced JSON"));continue}let he=N.slice(L,ve);try{let _=JSON.parse(he);Array.isArray(_)?C=_:(C=_.articles||[],j=_.gaps||[])}catch(_){console.log(m.red(` JSON parse error: ${_.message}`)),console.log(m.dim(` First 300 chars: ${he.slice(0,300)}`));continue}for(let _ of C){let qe=new Date().toISOString().slice(0,10),ye=d(_.sources||[],u);w.writeArticle(_.path,{title:_.title,type:_.type,related:Array.isArray(_.related)?_.related:void 0,tags:_.tags||[],owner:p,access:"public",created:qe,lastUpdated:qe,sources:_.sources||[],graphPath:ye},_.content,p);let Io=_.type?m.magenta(`[${_.type}]`)+" ":"",T=Array.isArray(_.related)&&_.related.length?` \u2192 ${_.related.slice(0,3).join(", ")}${_.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${Io}${_.path}: ${_.title}${m.dim(T)}`);let me=(_.tags||[]).slice(0,4).join(", ");me&&console.log(m.dim(` tags: ${me}`)),ye?.length&&(console.log(m.dim(` graphPath: ${ye.join(" \u203A ")}`)),l++),g++}if(j.length>0){console.log(),console.log(m.yellow(` Gaps detected (${j.length} missing pieces):`));for(let _ of j)console.log(m.yellow(` ? ${_}`));try{let{QuestionStore:_}=await import("./questions-4B4KSPXG.js"),qe=new _(zt(e.dir)).add(j.map(ye=>({kind:"article",agentId:p,path:"",subject:String(ye).slice(0,120),question:`No article yet for: ${String(ye).slice(0,160)}`})));qe.added>0&&console.log(m.dim(` queued ${qe.added} for follow-up (agentx wiki questions)`))}catch{}}w.rebuildIndex()}catch(k){console.log(m.red(` Absorb failed: ${k.message?.slice(0,200)}`)),k.stderr&&console.log(m.dim(String(k.stderr).slice(0,300))),k.stdout&&console.log(m.dim("stdout: "+String(k.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let p=g>0?Math.round(l/g*100):0;console.log(m.dim(` ${l}/${g} carry graphPath (${p}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});ee.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--commit","write articles and ledger (default: dry-run)",!1).action(async e=>{let o=ip(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-SEAGMKI6.js"),{default:c}=await import("better-sqlite3"),d=q(process.cwd(),".agentx/db.sqlite");if(!Be(d))console.log(m.yellow(` --reviews: no ${d}`));else{let g=new c(d,{readonly:!0});try{let l=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(o??6048e5));i=a(l,{kinds:String(e.reviewKinds).split(",").map(u=>u.trim()).filter(Boolean)});let p=i.filter(u=>(u.occurrences??1)>1).length;console.log(m.dim(` ${l.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${p} seen in more than one session`));let f=i[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.memory.description.slice(0,84)}`))}finally{g.close()}}}let r=await nr({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 ip(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-TKUDIOBZ.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=ke(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let d=a.getAgentWiki(c),g=parseInt(e.n),l=i(e.history,c);if(!s(l)){console.log(m.yellow(` no task-history at ${l}`));return}let p=[],f=t(l).sort().reverse();for(let y of f){let $=r(l,y),b=[];try{b=t($).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of b){if(p.length>=g)break;try{let A=JSON.parse(n(r($,v),"utf-8")),x=A.message||A.task?.message;typeof x=="string"&&x.trim().length>10&&p.push({id:A.id||v.replace(".json",""),message:x.trim(),ts:A.at||A.timestamp||y})}catch{}}if(p.length>=g)break}if(p.length===0){console.log(m.yellow(` no task messages found under ${l}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${p.length} messages from ${c}`)),console.log(m.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(m.dim(` NEW: agenticQuery() catalog+wikilink walk (selector=${e.selectorModel}, synth=${e.synthModel})`)),console.log();let u=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${p.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let y=0;y<p.length;y++){let $=p[y];process.stdout.write(m.dim(` [${y+1}/${p.length}] querying... `));let v=d.findRelevant($.message,c,3).map(x=>`- **${x.meta.title}** [${x.meta.type||"?"}] (${x.path})`).join(`
324
332
  `)||"_(none returned)_",A;try{let x=await o($.message,d,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(x.status!=="ok")A=`_(status: ${x.status}${x.error?" \u2014 "+x.error:""})_`;else{let E=x.citations.map(k=>`\`${k.title}\` [${k.type||"?"}]`).join(", ");A=`**Answer:**
325
333
 
326
334
  ${x.answer}
327
335
 
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(`
336
+ **Citations:** ${E}`}}catch(x){A=`_(error: ${x.message})_`}console.log(m.dim("done")),u.push(`## ${y+1}. ${$.id}`,"",`> ${$.message.replace(/\n/g," ").slice(0,400)}${$.message.length>400?"\u2026":""}`,"","### OLD \u2014 BM25 preload (top 3)","",v,"","### NEW \u2014 agentic query","",A,"","| Path | Rating 0\u20132 | Notes |","|---|---|---|","| OLD | | |","| NEW | | |","")}let w=u.join(`
337
+ `);e.out?((await import("fs")).writeFileSync(e.out,w),console.log(),console.log(m.green(` Wrote ${w.length} bytes to ${e.out}`))):(console.log(),console.log(w))});ee.command("interview").description("interactive interview session \u2014 Q&A with an LLM synthesizer, produces one typed wiki article").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to write to (required)").option("--topic <text>","what to interview about (e.g. 'Globex deployment procedure')").option("--type <t>","article type hint (person|project|place|concept|event|decision|pattern)").option("--model <m>","synthesis model","sonnet").option("--no-commit","show the draft but don't write").option("--answers <path>","non-interactive: one answer per line (same order as questions); last line = save|edit|scrap").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{WIKI_ARTICLE_TYPES:n}=await import("./types-OIFU3KSQ.js"),s=e.answers?Gt(e.answers,"utf-8").split(/\r?\n/).filter(T=>T.length>0):null,i=0;if(!e.agent){console.log(m.red(" --agent <id> is required. The article will be owned by this agent."));return}let r=ke(e.dir),a;try{a=r.getAgentWiki(e.agent)}catch(T){console.log(m.red(` can't open wiki for agent "${e.agent}": ${T.message}`));return}let c=s?null:o.createInterface({input:process.stdin,output:process.stdout}),d=async T=>{if(s){let me=s[i++]??"";return process.stdout.write(T+m.dim(`[scripted] ${me.slice(0,80)}${me.length>80?"\u2026":""}`)+`
338
+ `),me.trim()}return(await c.question(T)).trim()};console.log(),console.log(m.bold(" Wiki Interview")),console.log(m.dim(" One article per session. Empty answer = skip field. /done = stop & synthesize. /abort = quit.")),console.log();let g=e.topic||"";if(!g&&(g=await d(m.cyan(" Topic? ")+m.dim("(a person, a procedure, a past event, \u2026) ")),!g||g==="/abort")){c?.close();return}let l=(e.type||"").toLowerCase(),p=new Set(n);if(!p.has(l)){console.log(m.dim(` Types: ${n.join(" | ")}`));let T=await d(m.cyan(" Type? "));if(T==="/abort"){c?.close();return}p.has(T)?l=T:(console.log(m.yellow(` "${T}" isn't a valid type. Falling back to "concept".`)),l="concept")}let f={person:["Full name (and any aliases / Telegram handle / GitLab username)?","Role or title?","Which org or team are they part of (use the article title if you have one)?","Key responsibilities in OUR work?","Preferred channel to reach them (Telegram, email, in-person, \u2026)?","Who do they report to? (skip if none)","Notable decisions, events, or patterns they're involved in?","Anything quirky we should remember (timezone, working hours, style)?"],project:["One-line description \u2014 what is this project?","Who owns it? (person article title)","Tech stack or key tools involved?","Current status (active / paused / archived)?","Repo / URL / path on disk?","Two or three key decisions made so far?","Any open blockers, risks, or known issues?","Related projects or patterns?"],place:["Kind \u2014 office / server / environment / domain / URL?","Address \u2014 URL, IP, hostname, or physical location?","Owner (person or team)?","How to access it (SSH host, login, VPN, \u2026)?","What lives there (services, people, data)?","Known quirks (timezone, uptime, access restrictions)?"],concept:["Define it in one sentence \u2014 what does this term mean in OUR work?","Where did we first adopt it (origin story, date)?","Two or three concrete examples from our team?","What does it replace or extend (older concept, related concept)?","Common misunderstandings to avoid?"],event:["Date (YYYY-MM-DD)?","One-line summary \u2014 what happened?","Who was involved?","Timeline \u2014 key moments (start \u2192 resolution)?","Impact \u2014 what broke, what got delivered, who was affected?","Resolution / outcome?","Follow-ups or lessons captured?"],decision:["Context \u2014 what was the situation forcing a choice?","Options that were considered?","Chosen option \u2014 and one-sentence why?","Alternatives rejected \u2014 and one-sentence why not?","Who decided, and when (date)?","Is this reversible, and what would trigger a revisit?"],pattern:["Trigger \u2014 when should someone follow this pattern?","Inputs required (what do you need before starting)?","Steps in order \u2014 keep it tight, one line per step?","Expected output \u2014 how do you know it worked?","Common failure modes?","Related patterns, decisions, or runbooks?"]},u=f[l]||f.concept;console.log(),console.log(m.bold(` Topic: ${m.cyan(g)} \xB7 Type: ${m.magenta(l)}`)),console.log(m.dim(` ${u.length} questions. Skip with empty answer. /done to stop early.`)),console.log();let w=[],y=!1;for(let T=0;T<u.length;T++){let me=u[T],Je=await d(` ${m.dim(`[${T+1}/${u.length}]`)} ${me}
339
+ ${m.green(">")} `);if(Je==="/abort"){y=!0;break}if(Je==="/done")break;Je!=="/skip"&&Je&&w.push({q:me,a:Je})}if(!y){let T=await d(`
340
+ ${m.dim("Anything else worth capturing?")}
341
+ ${m.green(">")} `);T&&T!=="/abort"&&T!=="/done"&&w.push({q:"Anything else worth capturing?",a:T})}if(y||w.length===0){console.log(m.yellow(`
334
342
  Nothing captured. Exiting.`)),c?.close();return}let b=a.listArticles(e.agent).slice(0,40).map(T=>`- ${T.meta.title} [${T.meta.type||"?"}]`).join(`
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=>`
343
+ `),v=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${g}`,`**Type:** ${l}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...w.map(T=>`
336
344
  Q: ${T.q}
337
345
  A: ${T.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",b||"(none yet)","","## Output rules","- Output EXACTLY one markdown file: frontmatter (---) + body. No code fences, no preamble.","- Frontmatter fields in this exact order: title, type, related, tags, owner, access, created, last_updated, sources.",' - `title`: "\u2026"',` - \`type\`: ${l}`,' - `related`: ["Article Title", \u2026] (titles that exist in the catalog above; drop if none)'," - `tags`: 2-4 specific tags, lowercase-kebab \u2014 no dates unless type=event",` - \`owner\`: ${e.agent}`," - `access`: public (unless the content is sensitive)",` - \`created\`: ${new Date().toISOString().slice(0,10)}`,` - \`last_updated\`: ${new Date().toISOString().slice(0,10)}`,` - \`sources\`: ["interview-${new Date().toISOString().slice(0,10)}"]`,"- Body: 20-80 lines, Wikipedia-style, organized by theme (not by question), synthesized (not verbatim Q&A).","- Use [[Title]] inline every time you reference something that has an article in the catalog.","- Do NOT invent facts. If the transcript didn't cover something, skip that sub-topic."].join(`
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(`
346
+ `),A=q(a.baseDir,"_tmp");co(A,{recursive:!0});let x=q(A,`interview-${t().slice(0,8)}.txt`);qo(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=Fo(T,{env:Go({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Je=JSON.parse(me);E=String(Je.result||Je.content||"")}catch{E=me}}catch(T){console.log(m.red(` synthesis failed: ${T.message?.slice(0,200)}`)),c?.close();return}E=E.trim();let k=E.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);k&&(E=k[1].trim());let N=E.indexOf("---");N>0&&(E=E.slice(N));let C=E.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!C){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(E.slice(0,600)),c?.close();return}let j={};for(let T of C[1].split(`
347
+ `)){let me=T.match(/^(\w+):\s*(.+)$/);me&&(j[me[1]]=me[2].trim().replace(/^"(.*)"$/,"$1"))}let P=C[2],W=j.title||g,L=W.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),ae=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[l]||l+"s"}/${L}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${ae}`)),console.log(),console.log(E),console.log();let B=await d(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),B==="scrap"||B==="/abort"){console.log(m.dim(" Discarded."));return}if(!e.commit){console.log(m.dim(" --no-commit: not writing.")),console.log(m.dim(` Draft kept at ${x} (prompt only; no article file)`));return}let ve=P,he={title:W,type: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`);qo(me,E);try{Fo(`${T} '${me}'`,{stdio:"inherit"});let ns=Gt(me,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(ns){let go={};for(let vt of ns[1].split(`
348
+ `)){let ss=vt.match(/^(\w+):\s*(.+)$/);ss&&(go[ss[1]]=ss[2].trim().replace(/^"(.*)"$/,"$1"))}ve=ns[2],he={...he,title:go.title||he.title,type:go.type||he.type,access:go.access||he.access,related:go.related?go.related.replace(/^\[|\]$/g,"").split(",").map(vt=>vt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):he.related,tags:go.tags?go.tags.replace(/^\[|\]$/g,"").split(",").map(vt=>vt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):he.tags}}}catch(Je){console.log(m.red(` editor failed: ${Je.message}`));return}}if(!a.writeArticle(ae,he,ve,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${ae} saved.`));let qe=a.extractWikilinks(ve),ye=new Map;for(let T of a.listArticles(e.agent))ye.set(T.meta.title.toLowerCase(),!0);let Io=qe.filter(T=>!ye.has(T.toLowerCase()));if(Io.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let T of Io.slice(0,8))console.log(m.dim(` - ${T}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});ee.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{agenticQuery:n}=await import("./query-TKUDIOBZ.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=ke(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(f){console.log(m.red(` can't open wiki for agent "${e.agent}": ${f.message}`));return}let r=null;if(e.script){let u=Gt(e.script,"utf-8").split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);r=[];for(let w of u){let y=w.split(/\r?\n/).filter(v=>v.trim());if(y.length<2)continue;let $=y[0].replace(/^Q:\s*/i,"").trim(),b=y.slice(1).join(" ").trim();$&&b&&r.push({q:$,verdict:b})}}let a=r?null:o.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",d=Math.min(parseInt(e.rounds)||20,r?.length??999),g=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${d} \xB7 ${g?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let l=[],p=0;for(let f=0;f<d;f++){let u,w;if(r){let H=r[f];if(!H)break;u=H.q,w=H.verdict,console.log(m.cyan(` [${f+1}] Q: `)+u)}else{if(u=await c(m.cyan(` [${f+1}] Q: `)),!u||u==="/done"||u==="/abort")break;w=""}process.stdout.write(m.dim(" querying... "));let y;try{y=await n(u,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(H){console.log(m.red(`failed: ${H.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),y.status!=="ok")console.log(m.yellow(` (status: ${y.status}${y.error?" \u2014 "+y.error:""})`));else{let H=y.citations.map(ae=>`${ae.title} [${ae.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
349
+ `)),console.log(m.dim(" citations: "+H))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let $={q:u,answer:y.answer,citations:y.citations,verdict:w},b=w.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!b){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),l.push($);continue}let v=b[1].toLowerCase(),A=(b[2]||"").trim();if(l.push($),v==="/ok"||v==="/skip")continue;if(!A){console.log(m.yellow(` ${v} without note \u2014 skipping.`));continue}let x=y.citations[0];if(!x){console.log(m.yellow(" no cited article to patch."));continue}let E=i.readArticle(x.path);if(!E){console.log(m.red(` can't read ${x.path} to patch.`));continue}console.log(m.dim(` patching ${x.title} (${x.path})...`));let k=ap(E.content,v,A,E.meta.title,E.meta.type),N=q(i.baseDir,"_tmp");co(N,{recursive:!0});let C=q(N,`quiz-patch-${t().slice(0,8)}.txt`);qo(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=Fo(H,{env:Go({...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(m.red(` patch failed: ${H.message?.slice(0,120)}`));continue}if(!j||j.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let P=E.content.split(`
342
350
  `).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(`
351
+ `).length;if(console.log(m.dim(` diff: ${P} \u2192 ${W} lines (${W-P>=0?"+":""}${W-P})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),$.patched=x.path+" (dry)";continue}if(!i.writeArticle(x.path,{...E.meta,lastUpdated:new Date().toISOString().slice(0,10)},j,e.agent)){console.log(m.red(" write failed (permission?)"));continue}p++,$.patched=x.path,console.log(m.green(` \u2713 patched ${x.path}`))}if(a&&a.close(),p>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${l.length} rounds, ${p} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${l.length} rounds \xB7 ${p} patches_`,""];for(let u=0;u<l.length;u++){let w=l[u];f.push(`## ${u+1}. Q: ${w.q}`,"",`**A:** ${w.answer}`,"",`**Citations:** ${w.citations.map(y=>`\`${y.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${w.verdict}\``+(w.patched?` \u2192 patched \`${w.patched}\``:""),"")}qo(e.out,f.join(`
352
+ `)),console.log(m.dim(` Transcript written to ${e.out}`))}});ee.command("edit <agent> <titleOrPath>").description("open an article in $EDITOR (resolves by title or path), rebuild catalog on exit").option("--dir <path>","wiki directory").option("--editor <cmd>","override $EDITOR for this run").action((e,o,t)=>{let n=ke(t.dir),s;try{s=n.getAgentWiki(e)}catch(d){console.log(m.red(` can't open wiki for agent "${e}": ${d.message}`));return}let i=Sc(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{Fo(`${a} '${r}'`,{stdio:"inherit"})}catch(d){console.log(m.red(` editor exited with error: ${d.message?.slice(0,150)}`));return}let c=s.readArticle(i);if(c){let d=new Set,g=s.extractWikilinks(c.content).filter(f=>d.has(f)?!1:(d.add(f),!0)),l=c.meta.related||[];(g.some(f=>!l.includes(f))||l.some(f=>!g.includes(f)))&&(s.writeArticle(i,{...c.meta,related:g.length?g:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.content,e),console.log(m.dim(` (synced frontmatter.related from body: ${g.length} wikilink${g.length===1?"":"s"})`)))}try{s.rebuildIndex(),console.log(m.green(` \u2713 ${i} saved. Catalog rebuilt.`))}catch(d){console.log(m.yellow(` saved, but catalog rebuild failed: ${d.message?.slice(0,100)}`))}});ee.command("patch <agent> <titleOrPath> <instruction>").description("LLM-patch an article from a free-form instruction; shows diff + confirms before writing").option("--dir <path>","wiki directory").option("--patch-model <m>","patch model","sonnet").option("--yes","skip confirmation and write immediately").option("--no-commit","show the patched body but don't write").action(async(e,o,t,n)=>{let s=await import("node:readline/promises"),{randomUUID:i}=await import("node:crypto"),r=ke(n.dir),a;try{a=r.getAgentWiki(e)}catch(x){console.log(m.red(` can't open wiki for agent "${e}": ${x.message}`));return}let c=Sc(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=rp(d.content,d.meta.title,d.meta.type,t),l=q(a.baseDir,"_tmp");co(l,{recursive:!0});let p=q(l,`patch-${i().slice(0,8)}.txt`);qo(p,g),console.log(),console.log(m.dim(` Target: ${d.meta.title} (${c})`)),console.log(m.dim(` Patching with ${n.patchModel}...`));let f="";try{let x=`cat '${p}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,E=Fo(x,{env:Go({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let N=JSON.parse(E);f=String(N.result||N.content||"")}catch{f=E}let k=f.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);k&&(f=k[1].trim()),f=f.trim()}catch(x){console.log(m.red(` patch failed: ${x.message?.slice(0,150)}`));return}if(!f||f.length<20){console.log(m.yellow(" patch returned nothing usable."));return}let u=d.content.split(`
345
353
  `).length,w=f.split(`
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:
354
+ `).length;if(console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${u} \u2192 ${w} lines (${w-u>=0?"+":""}${w-u})`)),console.log(),console.log(f),console.log(),!n.commit){console.log(m.dim(" --no-commit: preview only, not written."));return}let y=!!n.yes;if(!y){let x=s.createInterface({input:process.stdin,output:process.stdout}),E=(await x.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();x.close(),y=E==="y"||E==="yes"}if(!y){console.log(m.dim(" aborted."));return}let $=new Set,b=a.extractWikilinks(f).filter(x=>$.has(x)?!1:($.add(x),!0));if(!a.writeArticle(c,{...d.meta,related:b.length?b:void 0,lastUpdated:new Date().toISOString().slice(0,10)},f,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex();let A=(d.meta.related||[]).filter(x=>!b.includes(x));A.length&&console.log(m.dim(` (pruned stale related: ${A.slice(0,3).join(", ")}${A.length>3?", \u2026":""})`)),console.log(m.green(` \u2713 ${c} patched.`))});function Sc(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 rp(e,o,t,n){return["You are editing a single wiki article to incorporate an operator instruction.","",`## Article: "${o}" (type: ${t||"untyped"})`,"","<article-body>",e,"</article-body>","","## Operator instruction",n,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the instruction requires changing them.","- Make the MINIMUM edit that satisfies the instruction \u2014 don't rewrite untouched sections.","- If the instruction is ambiguous or can't be applied, return the original body unchanged."].join(`
355
+ `)}function ap(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
348
356
 
349
357
  ${t}
350
358
 
@@ -357,8 +365,8 @@ Incorporate it into the most relevant existing section, or create a short new se
357
365
  ${t}
358
366
 
359
367
  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(`
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}"
368
+ `)}ee.command("prune").description("collapse legacy flat/unified mode dirs into graph/ (dedup by title; losers archived)").option("--dir <path>","wiki directory").option("--agent <id>","prune only this agent's wiki").option("--commit","execute moves + archives (default: dry-run)").action(async e=>{let o=ke(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=!!e.commit,s=e.dir?q(e.dir):q(process.cwd(),".agentx/wiki"),i="graph",r=["flat","unified"];console.log(),console.log(m.bold(n?" Pruning (commit)":" Pruning (dry-run)")),console.log(m.dim(` Canonical: ${i}/ \xB7 Legacy to collapse: ${r.join("/, ")}/`));let a=0,c=0,d=0,g=0;for(let l of t){let p=q(s,"agents",l);if(!Be(p))continue;let f=q(p,i),u=r.map(b=>({mode:b,dir:q(p,b)})).filter(b=>Be(b.dir));if(u.length===0)continue;let w=new Map;oi(f,b=>{let v=$c(f,b);if(v.startsWith("_")||v.startsWith("raw/")||v.includes("_tmp/"))return;let A=vc(Gt(b,"utf-8"));A?.meta.title&&w.set(A.meta.title.trim().toLowerCase(),{relPath:v,type:A.meta.type,lastUpdated:A.meta.lastUpdated||""})});let y=[];for(let b of u)oi(b.dir,v=>{let A=$c(b.dir,v);if(A.startsWith("_")||A.startsWith("raw/")||A.includes("_tmp/"))return;let x=vc(Gt(v,"utf-8"));x?.meta.title&&y.push({mode:b.mode,relPath:A,absPath:v,title:x.meta.title.trim(),type:x.meta.type,lastUpdated:x.meta.lastUpdated||""})});if(a+=y.length,y.length===0)continue;console.log();let $=u.map(b=>b.mode).join("+");console.log(m.bold(` ${m.cyan(l)}: ${y.length} legacy article(s) across ${$}`));for(let b of y){let v=b.title.toLowerCase(),A=w.get(v),x;A?!A.type&&b.type||!!A.type==!!b.type&&b.lastUpdated&&A.lastUpdated&&b.lastUpdated>A.lastUpdated?x="upgrade":x="archive":x="promote";let E=b.type?m.magenta(`[${b.type}]`):m.yellow("[untyped]"),k=x==="promote"?m.green("\u2192 promote "):x==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),N=b.relPath.length>46?b.relPath.slice(0,43)+"...":b.relPath.padEnd(46);if(console.log(` ${k} ${E} ${m.dim(b.mode+"/")}${N}`),x==="upgrade"&&console.log(m.dim(` (replaces ${A.relPath}, old version kept under _versions/)`)),!n){x==="promote"?c++:x==="upgrade"?d++:g++;continue}try{if(x==="promote"){let C=q(f,b.relPath);Be(C)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${b.relPath}`)),xc(p,b),g++):(co(kc(C),{recursive:!0}),qn(b.absPath,C),w.set(v,{relPath:b.relPath,type:b.type,lastUpdated:b.lastUpdated}),c++)}else if(x==="upgrade"){let C=q(f,A.relPath);if(Be(C)){let j=q(p,"_versions",A.relPath.replace(/\.md$/,""));co(j,{recursive:!0});let P=new Date().toISOString().replace(/[:.]/g,"-");qn(C,q(j,`${P}.md`))}co(kc(C),{recursive:!0}),qn(b.absPath,C),w.set(v,{relPath:A.relPath,type:b.type,lastUpdated:b.lastUpdated}),d++}else xc(p,b),g++}catch(C){console.log(m.red(` ! ${x} failed: ${C.message?.slice(0,120)}`))}}if(n){for(let b of u)try{sp(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 oi(e,o){if(Be(e))for(let t of np(e,{withFileTypes:!0})){let n=q(e,t.name);t.isDirectory()?oi(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function vc(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
369
+ `)){let s=n.match(/^(\w+):\s*(.+)$/);if(!s)continue;let i=s[1]==="last_updated"?"lastUpdated":s[1];t[i]=s[2].trim().replace(/^"(.*)"$/,"$1")}return{meta:t}}function xc(e,o){let t=q(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));co(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");qn(o.absPath,q(t,`${n}.md`))}ee.command("migrate").description("backfill type + related on legacy articles (one-shot)").option("--dir <path>","wiki directory").option("--agent <id>","migrate only this agent's articles").option("--commit","write changes (default: dry-run, reports what would change)").option("--batch <n>","articles per LLM call","10").option("--max <n>","cap articles this run (for spot-checks)").option("--model <m>","classifier model","sonnet").action(async e=>{let o=ke(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=Math.max(1,parseInt(e.batch)||10),s=e.max?parseInt(e.max):1/0,i=!!e.commit;console.log(),console.log(m.bold(i?" Migrating (commit)":" Migrating (dry-run)")),console.log(m.dim(` Batch size: ${n} \xB7 Model: ${e.model}`)),console.log();let r=0,a=0,c=0;for(let d of t){let g=o.getAgentWiki(d),l=g.listArticles(d),p=l.filter($=>!$.meta.type);if(r+=l.length,a+=p.length,p.length===0){console.log(` ${m.cyan(d)}: ${m.green("all typed")} (${l.length} articles)`);continue}let f=Math.max(0,s-c),u=Math.min(p.length,f);if(u===0){console.log(m.dim(` ${d}: skipped (--max reached)`));continue}console.log(),console.log(m.bold(` ${m.cyan(d)}: ${u}/${p.length} untyped articles`));let w=g.baseDir,y=q(w,"_tmp");co(y,{recursive:!0});for(let $=0;$<u;$+=n){let b=p.slice($,Math.min($+n,u)),v=lp(b),A=q(y,"migrate-prompt.txt");qo(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=Fo(E,{env:Go({...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(m.red(` LLM classify failed: ${E.message?.slice(0,150)}`));continue}for(let E of b){let k=x.find(L=>L.path===E.path),N=cp(k?.type);if(!k||!N){console.log(m.yellow(` ? ${E.path}: unclassified${k?` (got "${k.type}")`:""}`));continue}let C=g.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?m.dim(` \u2192 ${C.slice(0,3).join(", ")}${C.length>3?", \u2026":""}`):"",W=N.alias?m.dim(` (from "${N.alias}")`):"";console.log(` ${m.green("+")} ${m.magenta("["+N.type+"]")}${W} ${E.path}${P}`),i&&(g.writeArticle(E.path,j,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 cp(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 lp(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}"
362
370
  title: "${t.meta.title}"
363
371
  tags: [${i}]
364
372
  body: ${s}${t.content.length>400?"\u2026":""}`}).join(`
@@ -398,70 +406,70 @@ Output (JSON array, one entry per input article, same order):
398
406
  [
399
407
  {"path": "path/to/article.md", "type": "project"},
400
408
  ...
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(`
409
+ ]`}ee.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=ke(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});ee.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let o=e.dir||q(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-WN3R3BPU.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(),Br(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-C6TOB63Q.js"),c=ke(e.dir,e.mode),d=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),l=parseFloat(e.min),p=[];e:for(let y of d){let $=c.getAgentWiki(y);for(let b of $.listArticles(y)){if(p.length>=g)break e;let v=$.readArticle(b.path);if(!v||e.type&&v.meta.type!==e.type)continue;let A={...o(v.meta.type),...e.fields?i(v.meta.type):{}},x=await a(s,t({path:b.path,title:v.meta.title,type:v.meta.type,tags:v.meta.tags,body:v.content}),A,{links:[{kind:"article",id:b.path}],features:{agent:y,type:v.meta.type??"?"}});if(!x){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let E=n(x.answers),k=e.fields?r(v.meta.type,x.answers):null;E.completeness>=l&&!(k&&!k.fit)||p.push({agent:y,type:v.meta.type??"?",score:E.completeness.toFixed(2),standsAlone:E.standsAlone.toFixed(2),gap:E.biggestGap,...k?{missing:k.missingCritical.join(",")||"-",cov:`${Math.round(k.coverage*100)}%`}:{},title:v.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(" no articles below the threshold"));return}p.sort((y,$)=>parseFloat(y.score)-parseFloat($.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],u=f.map(y=>Math.max(y.length,...p.map($=>String($[y]).length))),w=y=>y.map(($,b)=>String($).padEnd(u[b])).join(" ");console.log(),console.log(m.bold(w(f)));for(let y of p)console.log(w(f.map($=>y[$])));if(e.fields){let y=p.filter($=>$.missing!=="-").length;console.log(m.dim(`
410
+ ${p.length} article(s) flagged; ${y} missing a required field.`)),console.log(m.dim(" 'missing' is the actionable column \u2014 a named field beats a score."))}else console.log(m.dim(`
411
+ ${p.length} article(s) below ${l}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});ee.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,o)=>{let{agenticQuery:t}=await import("./query-TKUDIOBZ.js"),n=ke(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let d=n.getAgentWiki(c),g=q(d.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(m.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(m.dim(" Citations:"));for(let c of a.citations){let d=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${d} (${c.path})`))}console.log()}if(o.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(d=>!a.candidates.some(g=>g.path===d.path));console.log(m.dim(` followed: ${c.map(d=>`${d.title}@h${d.hop}`).join(" | ")}`))}console.log()}});ee.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,o)=>{let t=ke(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=await t.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});ee.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let o=ke(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=q(process.cwd(),".agentx/graph");if(!Be(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new mo({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[l,p]of Object.entries(i.entries))r.set(l,p.path);if(r.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,d=0,g=0;for(let l of t){let p=o.getAgentWiki(l),f=p.listArticles(l),u=o.getSharedStore().listEntries(),w=new Map(u.map(v=>[v.id,v])),y=0,$=0,b=0;for(let v of f){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;y++,c++;let A=new Map;for(let E of v.meta.sources){let k=w.get(E);if(!k)continue;let N=String(k.meta?.sender??""),C=s.fingerprint({text:k.content,channel:k.source,sender:N}),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||(p.writeArticle(v.path,{...v.meta,graphPath:x.path},v.content,l),b++,g++))}console.log(` ${m.cyan(l)}: ${m.bold(f.length)} articles \xB7 ${y} eligible \xB7 ${$} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${d} matched (${Math.round(d/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});ee.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let t=ke(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-WN3R3BPU.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(m.red(" No --peer specified and no daemon config found")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(n.length===0){console.log(m.dim(" No mesh peers configured"));return}let s=new Set(t.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(m.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(m.red(` HTTP ${a.status}`));continue}let c=await a.json(),d=c.entries||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${d.length} entries`));let l=0;for(let p of d)s.has(p.id)||(e.dryRun||(t.addEntry({id:p.id,date:p.date,agentId:p.agentId,source:`${p.source}@${g}`,sourceContext:p.sourceContext,content:p.content}),s.add(p.id)),l++);l>0?console.log(m.green(` ${l} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=l;try{let p=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(p.ok){let f=await p.json();for(let u of f.agents||[])u.totalEntries>0&&console.log(m.dim(` ${u.agentId}: ${u.totalEntries} entries, ${u.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});ee.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let o=e.dir||q(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let d=new rs(o,void 0,c),l=d.getAgentWiki(t).rebuildIndex(),p=d.getAgentEntries(t),f=d.getUnabsorbedEntries(t),u=new Set,w=0,y=new Set;for(let b of l.articles){for(let v of b.tags||[])u.add(v);w+=b.tags?.length||0;for(let v of b.sources||[])y.add(v)}let $=new Set(l.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:ti(c),articles:l.articles.length,entries:p.length,unabsorbed:f.length,uniqueTags:u.size,avgTags:l.articles.length>0?(w/l.articles.length).toFixed(1):"0",dirs:$.size,coverage:y.size,articleList:l.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,d]of r){let g=s.map(l=>d(l).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,d)=>{let g=Math.max(...s.map(p=>p[c])),l=s.filter(p=>p[c]===g).map(p=>p.label);g>0&&console.log(m.dim(` Best ${d}: ${l.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});ee.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,o)=>{let t=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");Be(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?q(process.cwd(),e):q(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=q(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),d=c("tar",a,{stdio:"inherit"});d.status!==0&&(console.log(m.red(` tar exited with ${d.status}`)),process.exit(d.status||1));let{statSync:g}=await import("fs"),l=Be(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${dp(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-C6TOB63Q.js"),{QuestionStore:c}=await import("./questions-4B4KSPXG.js"),d=ke(e.dir,e.mode),g=[],l=e.agent?[e.agent]:d.listAgents(),p=parseInt(e.limit),f=0,u=[];e:for(let E of l){let k=d.getAgentWiki(E);for(let N of k.listArticles(E)){if(f>=p)break e;let C=k.readArticle(N.path);if(!C||e.type&&C.meta.type!==e.type)continue;f++;let 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(m.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&&g.push({kind:"field",agentId:E,path:N.path,subject:C.meta.title,field:W.field,tier:W.tier,question:`${C.meta.title} (${C.meta.type??"?"}) \u2014 ${W.label}?`}),u.push({tier:W.tier,need:W.field,how:W.needsHuman?m.yellow("ask"):W.sources.join("/"),uncertain:W.uncertain?"?":"",agent:E,article:C.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&g.length>0&&(w=new c(zt(e.dir)).add(g)),e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],$=E=>String(E).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(E=>Math.max(E.length,...u.map(k=>$(k[E]).length))),v=(E,k)=>String(E)+" ".repeat(Math.max(0,b[k]-$(E).length));console.log(),console.log(m.bold(y.map((E,k)=>v(E,k)).join(" ")));for(let E of u)console.log(y.map((k,N)=>v(E[k],N)).join(" "));let A=u.filter(E=>E.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${u.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${A} can be closed by a lookup; ${u.length-A} need a person.`));let x=u[0]?.tier;if(x&&console.log(m.dim(` Start at ${x} \u2014 ${i[x]}.`)),e.ask&&(console.log(m.cyan(` Queued ${w.added} question(s) for a person (${w.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&w.added>0){let{TIER_RANK:E}=await import("./article-fields-L4D2BOGY.js"),k=E[e.notifyTier]??E.pillar,N=g.filter(C=>(E[C.tier??"furniture"]??9)<=k);if(N.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:C}=await import("./config-WN3R3BPU.js"),j=C(),P=j?.notifications?.destination;if(!P?.channel||!P?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let W=N.slice(0,10).map(B=>`\u2022 ${B.question}`).join(`
404
412
  `),L=N.length>10?`
405
413
  \u2026and ${N.length-10} more`:"",H=`${N.length} wiki gap(s) need you (${e.notifyTier}+):
406
414
  ${W}${L}
407
415
 
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(`
416
+ 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?m.cyan(` Pushed ${N.length} question(s) to ${P.channel}.`):m.yellow(` Push failed (${B.status}) \u2014 questions are still queued.`))}catch(B){console.log(m.yellow(` Push failed (${String(B?.message??B).slice(0,80)}) \u2014 questions are still queued.`))}}}}});ee.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-L4D2BOGY.js"),{askSeat:r}=await import("./seat-C6TOB63Q.js"),{resolveFacts:a,mergeRecords:c,installPrompts:d,defaultSources:g,recordsFromEntries:l}=await import("./facts-YVEJOM7O.js"),{backfillArticle:p}=await import("./backfill-MTD2B62I.js"),f=ke(e.dir,e.mode),u=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=g(),$=c(l(f.getSharedStore().listEntries())),b=new Map($.map(j=>[j.name.toLowerCase().trim(),j])),v=0,A=0,x=[],E=!1;e:for(let j of u){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(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let B=t(L.meta.type,H.answers).missing.filter(T=>i.includes(T));if(B.length===0)continue;let{records:ve,results:he}=await a([{name:L.meta.title,type:"person"}],{sources:y}),_=b.get(L.meta.title.toLowerCase().trim());if(!E){for(let T of d(he,y))console.log(m.yellow(` ! ${T.source} ${T.kind} \u2014 would supply ${T.provides.join(", ")}`)),console.log(m.dim(` ${T.hint}`));E=!0}let qe=c([..._?[{name:_.name,source:"entries",fields:Object.fromEntries(Object.entries(_.fields).map(([T,me])=>[T,me.value]))}]:[],...ve]);if(qe.length===0)continue;let{content:ye,edits:Io}=p(L.content,qe[0],B);if(Io.length!==0){for(let T of Io)x.push({agent: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(m.red(` could not write ${W.path}`)))}}}if(e.json){console.log(JSON.stringify(x,null,2));return}if(x.length===0){console.log(m.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let k=["agent","article","field","action","got"],N=k.map(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(m.bold(C(k)));for(let j of x)console.log(C(k.map(P=>j[P])));console.log(),e.apply?(console.log(m.green(` ${x.length} field(s) written across ${A} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${x.length} field(s) would be written across ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});ee.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:o}=await import("./questions-4B4KSPXG.js"),{TIER_RANK:t}=await import("./article-fields-L4D2BOGY.js"),n=new o(zt(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(zt(t.dir));if(t.dismiss){let f=r.resolve(e,"dismissed");console.log(f?m.dim(` dismissed: ${f.question}`):m.red(` no question matching "${e}"`));return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let a=r.resolve(e,"answered",o);if(!a){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${a.question}`)),a.kind!=="field"||!a.field||!a.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[a.field]){console.log(m.dim(` recorded against ${a.path}. "${a.field}" has no fixed slot, so nothing was rewritten.`));return}let d=ke(t.dir,t.mode).getAgentWiki(a.agentId),g=d.readArticle(a.path);if(!g){console.log(m.yellow(` article gone: ${a.path}`));return}let l=s(g.content,a.field,`${o} (answered by operator)`);if(!l){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=d.writeArticle(a.path,g.meta,l.content,a.agentId);console.log(p?m.green(` wrote ${a.field} into ${a.path} (prior version kept)`):m.red(` could not write ${a.path}`))});ee.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:o,entryTriageQuestions:t,triageState:n,triage:s}=await import("./entry-triage-LK34TSQD.js"),{askSeat:i}=await import("./seat-C6TOB63Q.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:d,sweepPolicies:g}=await import("./triage-backtest-JNO7RKX7.js"),{calibrationReport:l}=await import("./calibration-ILS5OI44.js"),f=ke(e.dir,"graph").getSharedStore(),u=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:y,backlog:$}=r(u,w),b=a(y,L=>L.absorbed,parseInt(e.n)),v={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},A=[],x=0,E=Date.now();if(e.load){let{readFileSync:L}=await import("fs");A.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${$} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let H=await i(o,n(L),t,{features:{source:L.source??"",absorbed:L.absorbed}});if(!H){x++;continue}let ae=H.answers;A.push({entry:L,verdict:s(H.answers,v),citeWorthy:ae.citeWorthy?.noul})}if(A.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let k=c(A,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),N=d(A,"seat","seat"),C=l(N,{minN:50}),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(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${k.n} (${k.positives} kept by absorb, ${k.negatives} passed over)`),console.log(` recall ${P(k.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P(k.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P(k.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${k.lostPositives>0?m.yellow(`lost ${k.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in C)||!C.insufficient)&&console.log(` ECE ${C.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),k.lostPositives>0){let L=k.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let W=k.positiveMeans;if(console.log(m.dim(` positives avg: worth ${W.worth.toFixed(2)} \xB7 durability ${W.durability.toFixed(2)} \xB7 typeConf ${W.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${j}s, ${x} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let L=parseFloat(e.minRecall),{best:H,points:ae}=g(A,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${ae.length} policies, recall floor ${P(L)})`)),H)console.log(` best: ${H.requireTyped?`typed & type>=${H.minType}`:"type gate OFF"} worth>=${H.minWorth} durability>=${H.minDurability}`),console.log(` recall ${P(H.recall)} \xB7 filtered ${P(H.filtered)} \xB7 precision ${P(H.precision)} \xB7 lost ${H.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${P(L)} recall \u2014 not even keeping everything typed.`));let B=ae.slice().sort((ve,he)=>he.recall-ve.recall)[0];B&&console.log(m.dim(` Best recall available: ${P(B.recall)} at ${B.requireTyped?`type>=${B.minType}`:"type gate OFF"} worth>=${B.minWorth} dur>=${B.minDurability}, filtering ${P(B.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});ee.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,o)=>{let t=q(process.cwd(),e);Be(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");Be(n)&&!o.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=q(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function dp(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"}$l();import{Command as gp}from"commander";import R from"chalk";import{resolve as Wn}from"path";import{existsSync as mp}from"fs";we();var mt=new gp().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");mt.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let o=D();if(!o.graph?.enabled){console.log(R.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(R.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(R.red(` agent "${t}" not in config`));return}let n=(e.daemonUrl||o.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new mo({baseDir:Wn(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(R.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(R.bold(` Graph review \u2014 ${r.length} pending`)),console.log(R.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let d=0,g=0,l=0,p=0;for(let u=0;u<r.length;u++){let w=r[u],y=tn(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${u+1}/${r.length}] ${R.cyan(w.msgHash.slice(0,8))} ${R.dim(y)} ... `);let $=pp(w,a,c),b=null;try{b=await up(n,t,$,o.dashboard?.token)}catch(x){p++,console.log(R.red(`ERR ${x.message?.slice(0,80)}`));continue}if(!b||!b.decision){p++,console.log(R.red("ERR no decision"));continue}let v=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(R.green("APPROVE")+" "+R.dim(A)),e.dryRun)d++;else try{fp(i,w,a,c,t),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:t,reviewReason:A}),d++}catch(x){console.log(R.yellow(` (commit failed, staying pending: ${x.message?.slice(0,100)})`)),p++}else v==="reject"?(console.log(R.red("REJECT")+" "+R.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:t,reviewReason:A}),g++):(console.log(R.yellow("SKIP")+" "+R.dim(A||v)),l++)}console.log();let f=e.dryRun?"would":"did";console.log(R.dim(` Summary: ${f} approve ${d}, ${f} reject ${g}, ${l} skipped, ${p} errors.`)),e.dryRun&&(d>0||g>0)&&console.log(R.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});mt.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let o=D();if(!o.graph){console.log(R.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=Wn(process.cwd(),o.graph.baseDir);if(!mp(t)){console.log(R.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-V4WN2VVM.js"),s=new mo({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(R.dim(" "),...a)});console.log(),console.log(R.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(R.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(R.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(R.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});mt.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let o=D();if(!o.graph?.enabled){console.log(R.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let t=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new mo({baseDir:Wn(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(k=>k.id));console.log(),console.log(R.bold(` graph pull \u2190 ${t}`));let d,g,l;try{let k=await fetch(`${t}/graph/schema`,{headers:s});if(!k.ok)throw new Error(`schema HTTP ${k.status}`);d=(await k.json()).schema;let C=await fetch(`${t}/graph/nodes`,{headers:s});if(!C.ok)throw new Error(`nodes HTTP ${C.status}`);g=(await C.json()).nodes||[];let 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 p=r.levels.map(k=>k.id).join(","),f=d?.levels?.map(k=>k.id).join(","),u=p===f;u?console.log(R.dim(` schema matches (${r.levels.length} levels)`)):(console.log(R.yellow(" \u26A0 schema levels differ:")),console.log(R.dim(` local: ${p}`)),console.log(R.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(R.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(d)):console.log(R.yellow(" keeping local schema; node import may fail if levels disagree")));let w=u?r:d,y=new Map;w.levels.forEach((k,N)=>y.set(k.id,N));let $=[...g].sort((k,N)=>(y.get(k.level)??99)-(y.get(N.level)??99)),b=0,v=0,A=0;for(let k of $){if(c.has(k.id)){v++;continue}if(e.dryRun){b++,c.add(k.id);continue}try{i.addNode({...k,createdBy:k.createdBy?`${k.createdBy} (sync)`:`sync:${t}`}),c.add(k.id),b++}catch(N){A++,console.log(R.yellow(` skip node ${k.id}: ${N.message?.slice(0,100)}`))}}console.log(R.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${A} failed`));let x=0,E=0;for(let k of l)if(!(!k.msgHash||!Array.isArray(k.path))){if(i.getFingerprint(k.msgHash)){E++;continue}if(e.dryRun){x++;continue}i.setFingerprint(k.msgHash,{path:k.path,leaf:k.leaf||{}}),x++}console.log(R.dim(` fingerprints: +${x} cached \xB7 ${E} already-present`)),console.log(),e.dryRun?console.log(R.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(R.green(` \u2713 pulled from ${t}`)),console.log()});function pp(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(`
409
417
  `),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(`
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(`
418
+ `)}async function up(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 Ti((c?.content||"").toString())}finally{clearTimeout(r)}}function fp(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function ni(){let e=D();if(!e.graph?.baseDir)return console.log(R.red(" graph.baseDir is not configured")),null;let o=Wn(process.cwd(),e.graph.baseDir);return{store:new mo({baseDir:o}),baseDir:o}}var si=mt.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");si.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=ni();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(tn(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]"))});si.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=ni();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}: ${tn(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(R.dim(` should have been: ${t.path}`))});si.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=ni();if(!o)return;let{ReviewStore:t,labelStats:n}=await import("./review-store-B4YE3EFK.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,i);if(e.json){console.log(JSON.stringify(r,null,2));return}let a=c=>`${(c*100).toFixed(1)}%`;if(console.log(),console.log(` classifications ${r.classifications}`),console.log(` reviewed ${r.reviewed} (${r.correct} correct \xB7 ${r.wrong} wrong \xB7 ${r.unsure} unsure)`),r.correct+r.wrong>0&&console.log(` accuracy ${a(r.accuracy)}`),console.log(` calibratable ${r.calibratable} ${R.dim("reviewed rows that carry a confidence")}`),r.byBin.length>0){console.log(),console.log(R.bold(" reliability \u2014 confidence vs how often it was right"));for(let c of r.byBin){let d=Math.abs(parseFloat(c.bin.split("-")[0])+.05-c.accuracy),g=c.n>=5&&d>.15?R.yellow(" \u2190 miscalibrated"):"";console.log(` ${c.bin} n=${String(c.n).padStart(3)} right ${a(c.accuracy).padStart(6)}${g}`)}}console.log(),r.calibratable<100?console.log(R.dim(` ${100-r.calibratable} more labelled rows before a calibration report means anything.`)):console.log(R.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as kp}from"commander";import Y from"chalk";import{Command as Ac}from"commander";import se from"chalk";import{existsSync as hp}from"fs";import{resolve as yp}from"path";import wp from"better-sqlite3";function bp(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 $p(e){let o=yp(process.cwd(),e);return hp(o)||(console.log(se.red(` No db at ${o}`)),process.exit(1)),new wp(o,{readonly:!0})}var Oc=new Ac().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(At)).option("--max <n>","max clusters distilled per run",String(rn)).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=$p(e.path),t=await sr(o,{since:bp(e.since),agentId:e.agent,sessions:new Li(process.cwd()),minOccurrences:Number(e.minOccurrences)||At,max:Number(e.max)||rn,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(`
411
419
  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(`
412
420
  dry run only; pass --commit --via <agentId> to write drafts`)):t.drafted.length&&console.log(se.dim(`
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
421
+ review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),Ec={hourly:"0 * * * *",daily:"0 3 * * *"},Ic=new Ac().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(At)).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?Ec.hourly:e.daily?Ec.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)||At,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 ${rn} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
422
+ `),i=await de(a=>{be(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&be(a,"crons.procedure-extract.enabled",!1):o&&be(a,"crons.procedure-extract",{enabled:!0,schedule:o,timezone:e.timezone,agent:e.via,prompt:s,timeout:900,onError:"log"})},{configPath:e.config,dryRun:!!e.dryRun});i.success||(console.log(se.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(se.green(` \u2713 ${r} procedure extraction: off`)):(console.log(se.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(se.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(se.dim(" on-task counting: enabled")),console.log(se.dim(` threshold: ${t} occurrences`))),console.log(se.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var Ve=new kp().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");Ve.addCommand(Oc);Ve.addCommand(Ic);Ve.command("list").description("list procedures with their trigger line").option("--drafts","list unreviewed drafts instead",!1).option("--all","list active procedures and drafts",!1).action(e=>{let o=new po,t=[...e.drafts?[]:o.list(),...e.drafts||e.all?o.listDrafts():[]];if(!t.length){console.log(Y.dim(e.drafts?" no procedure drafts. Mine some with: agentx procedure extract":" no procedures yet. Try: agentx procedure extract \xB7 or: agentx procedure add"));return}console.log();for(let n of t){let s=n.meta.status==="active"?Y.green(n.meta.status):n.meta.status==="draft"?Y.yellow(n.meta.status):Y.dim(n.meta.status);console.log(` ${Y.cyan(n.meta.id)} ${Y.bold(n.meta.title)} ${s}`),console.log(` ${Y.dim("trigger:")} ${n.meta.trigger}`),n.meta.source&&console.log(` ${Y.dim("source:")} ${Y.dim(n.meta.source)}`),n.meta.kpis?.length&&console.log(` ${Y.dim("kpis:")} ${n.meta.kpis.join(", ")}`)}console.log(),console.log(Y.dim(` ${t.length} procedure${t.length===1?"":"s"}.`))});Ve.command("add").description("add a new procedure (non-interactive; pass all fields as flags)").requiredOption("--id <id>","procedure id (lower-kebab, e.g. deploy-peer)").requiredOption("--title <t>","human-readable title").requiredOption("--trigger <t>","when this procedure applies (one sentence)").option("--input <i...>","required input (repeatable)",(e,o=[])=>[...o,e]).option("--expected <t>","expected output / success criterion").option("--kpi <k...>","KPI (repeatable)",(e,o=[])=>[...o,e]).option("--owner <id>","owning agent or person").option("--tag <t...>","tag (repeatable)",(e,o=[])=>[...o,e]).option("--related <r...>","related procedure id or wiki article title (repeatable)",(e,o=[])=>[...o,e]).option("--steps <md>","markdown body \u2014 usually numbered steps").action(e=>{let o=new po,t=e.steps?String(e.steps):`## Steps
415
423
 
416
424
  1. (fill in)
417
425
 
418
426
  ## Notes
419
427
 
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:
428
+ `;try{let n=o.add({id:e.id,title:e.title,trigger:e.trigger,inputs:e.input||[],expected:e.expected,kpis:e.kpi||[],owner:e.owner,tags:e.tag||[],related:e.related||[]},t);console.log(Y.green(` \u2713 procedure added: ${n.meta.id}`)),console.log(Y.dim(` ${o.baseDir}/${n.path}`))}catch(n){console.log(Y.red(` add failed: ${n.message}`)),process.exit(1)}});Ve.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new po,t=o.get(e)??o.getDraft(e);t||(console.log(Y.yellow(` no procedure matches "${e}". Try: agentx procedure list --all`)),process.exit(1)),console.log(),console.log(Y.bold(` ${t.meta.title}`)+Y.dim(` (${t.meta.id}, ${t.meta.status})`)),console.log(Y.dim(` trigger: ${t.meta.trigger}`)),t.meta.inputs?.length&&console.log(Y.dim(` inputs: ${t.meta.inputs.join(", ")}`)),t.meta.expected&&console.log(Y.dim(` expected: ${t.meta.expected}`)),t.meta.kpis?.length&&console.log(Y.dim(` kpis: ${t.meta.kpis.join(", ")}`)),t.meta.owner&&console.log(Y.dim(` owner: ${t.meta.owner}`)),t.meta.source&&console.log(Y.dim(` source: ${t.meta.source}`)),t.meta.related?.length&&console.log(Y.dim(` related: ${t.meta.related.join(", ")}`)),console.log(),console.log(t.body),console.log()});Ve.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new po;try{let t=o.promoteDraft(e);console.log(Y.green(` \u2713 promoted: ${t.meta.id}`)),console.log(Y.dim(` agents will now follow it when a task matches: "${t.meta.trigger}"`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Ve.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new po;try{o.rejectDraft(e),console.log(Y.green(` \u2713 rejected: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Ve.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new po;try{o.deprecate(e),console.log(Y.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Ve.command("match <text>").description("find active procedures matching a task description").option("--limit <n>","max matches","3").option("--min-score <s>","minimum score 0..1","0.2").action((e,o)=>{let t=new po,n=Vi(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 Sp}from"commander";import S from"chalk";import{resolve as ut,basename as Ep}from"path";import{existsSync as ii,readFileSync as ri,writeFileSync as Bn}from"fs";import Q$ from"better-sqlite3";import{readFileSync as vp}from"fs";import{resolve as pt,dirname as jc}from"path";import{fileURLToPath as xp}from"url";var Yt=[{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 Cc(e){let o=jc(xp(import.meta.url)),t=process.argv[1]?jc(process.argv[1]):"",n=[pt(o,`${e}.yaml`),pt(o,"workflows/templates",`${e}.yaml`),pt(o,"..","workflows/templates",`${e}.yaml`),pt(o,"../..","workflows/templates",`${e}.yaml`),t?pt(t,"workflows/templates",`${e}.yaml`):"",t?pt(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return vp(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
421
429
  ${n.join(`
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(`
430
+ `)}`)}var Ue=new Sp().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Ue.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new jo().list();if(!o.length){console.log(S.dim(" no workflows yet. Add one by writing .agentx/workflows/<id>.json"));return}console.log();for(let t of o){let s=t.nodes.find(a=>a.type.startsWith("trigger."))?.config??{},i=[s.filter?.project,s.filter?.repo,s.filter?.chat].filter(Boolean).join(" / "),r=t.state==="active"?S.green("dispatch: active"):S.yellow(`dispatch: ${t.state}`);console.log(` ${S.cyan(t.id)} ${S.bold(t.title)} ${S.dim(`v${t.version} \xB7`)} ${r} ${S.dim(`\xB7 review: ${t.status}`)}`),console.log(` ${S.dim("trigger:")} ${s.source??"?"}${i?` ${S.dim(i)}`:""}`),console.log(` ${S.dim("nodes: ")} ${t.nodes.length} (${t.nodes.map(a=>a.type).join(", ")})`)}console.log(),console.log(S.dim(` ${o.length} workflow${o.length===1?"":"s"}.`))});Ue.command("show <id>").description("show a single workflow's full definition").option("--format <fmt>","output format: json (default) or yaml","json").action((e,o)=>{let n=new jo().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(Fi(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(S.red(` unknown format "${o.format}" \u2014 use json or yaml`)),process.exit(1))});Ue.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=ut(process.cwd(),e);ii(i)||(console.log(S.red(` file not found: ${i}`)),process.exit(1));try{let r=ri(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?Vo(r,{filePath:e}):JSON.parse(r),d=Yo.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=nn(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 sn?r.message:`parse error: ${r?.message??r}`;console.log(S.red(` ${a}`)),process.exit(1)}return}let t=new jo().validateAll(),n=0,s=0;for(let i of t)if(i.isValid)console.log(S.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(S.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(S.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});Ue.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${Yt.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");Yt.some(a=>a.name===t)||(console.log(S.red(` unknown template "${o.template}"`)),console.log(S.dim(` available: ${Yt.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 jo;!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=Cc(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=Vo(s,{filePath:`${e}.yaml`}),c=Yo.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=ut(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=Vo(s,{filePath:`${e}.yaml`}),c=Yo.parse(a);Bn(r,JSON.stringify(c,null,2)+`
431
+ `)}else Bn(r,s);console.log(),console.log(S.green(` \u2713 scaffolded ${r}`)),console.log(S.dim(` template: ${t}`)),console.log(),console.log(S.dim(" Next:")),console.log(S.dim(` 1. edit ${r}`)),console.log(S.dim(` 2. agentx workflow validate ${r}`)),console.log(S.dim(` 3. agentx workflow run ${e} --watch`)),console.log()});Ue.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of Yt)console.log(` ${S.cyan(e.name.padEnd(20))} ${S.bold(e.title)}`),console.log(` ${" ".repeat(20)} ${S.dim(e.description)}`);console.log(),console.log(S.dim(" Use: agentx workflow init <id> --template <name>")),console.log()});Ue.command("add <file>").description("import a YAML/JSON workflow file into .agentx/workflows and hot-reload").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--no-reload","skip the POST /reload after writing").action(async(e,o)=>{let t=ut(process.cwd(),e);ii(t)||(console.log(S.red(` file not found: ${t}`)),process.exit(1));let n=ri(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?Vo(n,{filePath:e}):JSON.parse(n)}catch(p){let f=p instanceof sn?p.message:`parse error: ${p?.message??p}`;console.log(S.red(` ${f}`)),process.exit(1)}let r=Yo.safeParse(i);if(!r.success){console.log(S.red(" \u2717 schema:"));for(let p of r.error.issues)console.log(` ${p.path.join(".")||"<root>"}: ${p.message}`);process.exit(1)}let a=nn(r.data);if(a.length){console.log(S.red(" \u2717 lint:"));for(let p of a)console.log(` ${p}`);process.exit(1)}let c=new jo,d=s?Ep(e).match(/\.yml$/i)?"yml":"yaml":"json",g=ut(c.baseDir,`${r.data.id}.${d}`);if(Bn(g,s?n:JSON.stringify(r.data,null,2)+`
432
+ `),console.log(S.green(` \u2713 ${r.data.id} \u2192 ${g}`)),o.reload===!1){console.log(S.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let l=`${String(o.daemon).replace(/\/$/,"")}/reload`;try{let p=await fetch(l,{method:"POST"});p.ok?console.log(S.dim(" \u2713 daemon reloaded")):console.log(S.dim(` daemon /reload returned ${p.status} \u2014 restart manually if needed`))}catch{console.log(S.dim(` daemon not reachable at ${o.daemon} \u2014 start it or restart to pick up the new workflow`))}});Ue.command("runs [id]").description("list recent runs (optionally filtered to a single workflow)").option("--limit <n>","max runs to show","20").option("--node <id>",'home-node id for this daemon (defaults to WF_NODE_ID env or "local")').action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local",n=new Et({nodeId:t}).list({workflowId:e,limit:Number(o.limit)});if(!n.length){console.log(S.dim(` no runs yet${e?` for "${e}"`:""}.`));return}console.log();for(let s of n){let i=s.history.at(-1),r=s.pending[0]??(s.status==="completed"?"\u2205":"\u2014"),a=s.status==="running"?S.cyan:s.status==="failed"?S.red:S.green;console.log(` ${S.dim(s.id.slice(0,8))} ${S.bold(s.workflowId)} ${a(r)} ${S.dim(s.status)}`),console.log(` ${S.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${S.dim("home: ")} ${s.homeNode}`),console.log(` ${S.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${S.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(S.dim(` ${n.length} run${n.length===1?"":"s"}.`))});Ue.command("run <id-or-file>").description("manually trigger a workflow by id, or load + register + run a YAML/JSON file").option("--input <json>","JSON object merged into the trigger event payload").option("--force","fire even if the trigger isn't `trigger.manual` (uses a synthesized event)",!1).option("--watch","tail per-step traces while the run executes",!1).option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").action(async(e,o)=>{let t={};if(o.input)try{t=JSON.parse(o.input)}catch{console.log(S.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=ut(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&ii(s)){let c=ri(s,"utf-8"),d=/\.(ya?ml)$/i.test(e),g;try{g=d?Vo(c,{filePath:e}):JSON.parse(c)}catch(b){let v=b instanceof sn?b.message:`parse error: ${b?.message??b}`;console.log(S.red(` ${v}`)),process.exit(1)}let l=Yo.safeParse(g);if(!l.success){console.log(S.red(" \u2717 schema:"));for(let b of l.error.issues)console.log(` ${b.path.join(".")||"<root>"}: ${b.message}`);process.exit(1)}let p=nn(l.data);if(p.length){console.log(S.red(" \u2717 lint:"));for(let b of p)console.log(` ${b}`);process.exit(1)}let f=new jo,u=l.data.id.startsWith("_adhoc-")?l.data.id:`_adhoc-${l.data.id}-${Date.now().toString(36)}`,w=d?"yaml":"json",y=ut(f.baseDir,`${u}.${w}`),$=d?c.replace(new RegExp(`^id:\\s*${l.data.id}\\b`,"m"),`id: ${u}`):JSON.stringify({...l.data,id:u},null,2)+`
433
+ `;Bn(y,$),n=u,console.log(S.dim(` ad-hoc registered as "${u}" \u2192 ${y}`));try{await fetch(`${String(o.daemon).replace(/\/$/,"")}/reload`,{method:"POST"})}catch{}}let r=`${String(o.daemon).replace(/\/$/,"")}/workflows/${encodeURIComponent(n)}/run`,a;try{let c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:t,force:!!o.force})});if(!c.ok){let g=await c.text();console.log(S.red(` run failed (${c.status}): ${g.slice(0,300)}`)),c.status===409&&console.log(S.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let d=await c.json();a=d.runId,console.log(S.green(` \u2713 run started: ${a||"(unknown id)"}${d.force?S.dim(` (forced, source=${d.source})`):""}`))}catch(c){console.log(S.red(` request to daemon failed: ${c.message}`)),process.exit(1)}o.watch&&a&&await Ap({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function Ap(e){let o=new Set,t=new Map,n=Date.now(),s=15*60*1e3;for(;Date.now()-n<s;){let i=[];try{let r=await fetch(`${e.daemonUrl}/traces?workflowRunId=${encodeURIComponent(e.runId)}&limit=200`);r.ok&&(i=(await r.json()).traces||[])}catch{}for(let r of i){if(!r.taskId||o.has(r.taskId)||(o.add(r.taskId),t.set(r.taskId,r),e.quiet))continue;let a=r.status||"running",c=a==="ok"?S.green:a==="error"?S.red:S.cyan,d=r.totalTokens!=null?S.dim(`${r.totalTokens}t`):"",g=r.durationMs!=null?S.dim(`${r.durationMs}ms`):"";console.log(` ${c(a.padEnd(5))} ${S.bold(r.nodeId||r.label||"(node)")} ${d} ${g}`),r.error&&console.log(` ${S.red(String(r.error).slice(0,200))}`)}try{let r=await fetch(`${e.daemonUrl}/api/workflows/runs/${encodeURIComponent(e.runId)}`);if(r.ok){let c=(await r.json()).run;if(c&&c.status&&c.status!=="running")return e.quiet||(console.log(),console.log(` ${S.dim("run finished:")} ${c.status}`),console.log(S.dim(` full traces: ${e.daemonUrl}/traces?workflowRunId=${e.runId}`))),Array.from(t.values())}}catch{}await new Promise(r=>setTimeout(r,500))}return e.quiet||console.log(S.yellow(" watch timed out after 15min. Run is still active \u2014 check /traces")),Array.from(t.values())}Ue.command("trace <id>").description("pretty-print a task's execution trace (taskId or runId)").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output",!1).action(async(e,o)=>{let t=String(o.daemon).replace(/\/$/,"");try{let i=await fetch(`${t}/traces/${encodeURIComponent(e)}`);if(i.ok){let r=await i.json();if(o.json){console.log(JSON.stringify(r,null,2));return}Tc(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)Tc(i)});function Tc(e){let o=e.status||"ok",t=o==="ok"?S.green:o==="error"?S.red:S.cyan,n=e.totalTokens!=null?`${e.totalTokens}t`:"\u2014",s=e.durationMs!=null?`${e.durationMs}ms`:"\u2014",i=e.model||"\u2014";console.log(` ${t(o.padEnd(5))} ${S.bold(String(e.nodeId||e.label||"(node)"))}`),console.log(` ${S.dim("taskId:")} ${e.taskId||"\u2014"}`),console.log(` ${S.dim("model:")} ${i}`),console.log(` ${S.dim("tokens:")} ${n} ${S.dim("duration:")} ${s}`),e.error&&console.log(` ${S.dim("error:")} ${S.red(String(e.error).slice(0,300))}`),console.log()}Ue.command("pause <runId>").description("pause an active run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new Et({nodeId:t}).setStatus(e,"paused")||(console.log(S.yellow(` no such run: ${e}`)),process.exit(1)),console.log(S.green(` \u2713 paused ${e}`))});Ue.command("resume <runId>").description("resume a paused run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new Et({nodeId:t}).setStatus(e,"running")||(console.log(S.yellow(` no such run: ${e}`)),process.exit(1)),console.log(S.green(` \u2713 resumed ${e}`))});Ue.command("cancel <runId>").description("cancel an active run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new Et({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 Nc}from"commander";import oe from"chalk";import Wo from"prompts";import{readFileSync as Op,existsSync as Ip}from"fs";import{resolve as jp}from"path";var Vt=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],ai=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),Rc={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=jp(process.cwd(),"agentx.json");if(!Ip(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Op(e,"utf-8"))}function Cp(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?oe.yellow("\u26A0 no signing secret"):oe.green("\u2713 active"):oe.dim("disabled")}function Tp(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=ai.has(e.source)?oe.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${oe.cyan(e.id)} ${Cp(e)}`),console.log(` ${oe.dim(e.source)} \u2192 ${oe.bold(e.agentId)}${n}`),console.log(` POST ${oe.dim(t)}`),e.secretEnv&&console.log(` secret: ${oe.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${oe.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${oe.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${oe.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var lo=new Nc().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");lo.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=_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(`
426
434
  No webhooks registered. Add one with: agentx webhook add
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(`
435
+ `));return}console.log();for(let n of t)Tp(n)});lo.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${Vt.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 Wo({type:"text",name:"id",message:"Webhook id (lowercase, e.g. globex-gitlab)",validate:u=>/^[a-z0-9][a-z0-9_-]*$/.test(u)||"Use lowercase letters, digits, -, _"})).id||"").trim()),!r)throw new Error("Webhook id is required.");if(!/^[a-z0-9][a-z0-9_-]*$/.test(r))throw new Error("Webhook id must be lowercase (letters, digits, -, _).");if(!a&&l&&(a=(await Wo({type:"select",name:"source",message:"Source",choices:Vt.map(u=>({title:`${u}${ai.has(u)?" \u2713 wired":""}`,value:u,description:Rc[u]}))})).source),!Vt.includes(a))throw new Error(`Source must be one of: ${Vt.join(", ")}`);if(!c&&l&&(i?c=((await Wo({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await Wo({type:"select",name:"agentId",message:"Agent",choices:n.map(u=>({title:u,value:u}))})).agentId),!c)throw new Error("Agent is required.");if(i){if(!s.includes(i))throw new Error(`Mesh peer "${i}" not found in mesh.peers. Add the peer first or omit --node.`)}else if(!t.agents?.[c])throw new Error(`Unknown agent "${c}". Add it locally, or use --node <peer> to forward to a mesh peer.`);!d&&l&&a!=="custom"&&(d=((await Wo({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&l&&(g=((await Wo({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let p=await de(f=>{if(f.webhooks=Array.isArray(f.webhooks)?f.webhooks:[],f.webhooks.find(w=>w.id===r))throw new Error(`Webhook "${r}" already exists.`);let u={id:r,source:a,agentId:c,enabled:!0};d&&(u.secretEnv=d),g&&(u.description=g),i&&(u.node=i),f.webhooks.push(u)});if(!p.success)throw new Error(p.error);console.log(oe.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),p.reloaded&&console.log(oe.dim(" daemon hot-reloaded")),!d&&a!=="custom"&&console.log(oe.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});lo.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await Wo({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 Dc(e){return async o=>{let t=await de(n=>{let s=(n.webhooks||[]).find(i=>i.id===o);if(!s)throw new Error(`Webhook "${o}" not found.`);s.enabled=e});if(!t.success)throw new Error(t.error);console.log(oe.green(`\u2713 ${e?"enabled":"disabled"} webhook "${o}"`))}}lo.command("enable <id>").description("enable a webhook entry").action(Dc(!0));lo.command("disable <id>").description("disable a webhook entry").action(Dc(!1));var Jn=new Nc().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");Jn.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await de(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);i.triggers=i.triggers&&typeof i.triggers=="object"?i.triggers:{},i.triggers[o]=t});if(!n.success)throw new Error(n.error);console.log(oe.green(`\u2713 ${e}: ${o} \u2192 ${t}`))});Jn.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await de(n=>{let s=(n.webhooks||[]).find(i=>i.id===e);if(!s)throw new Error(`Webhook "${e}" not found.`);s.triggers&&typeof s.triggers=="object"&&delete s.triggers[o]});if(!t.success)throw new Error(t.error);console.log(oe.green(`\u2713 removed trigger ${o} from "${e}"`))});Jn.command("default <id> <workflowId>").description("set the default workflow when no event-type matches (use '-' to clear)").action(async(e,o)=>{let t=o==="-"||o==="",n=await de(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);t?delete i.defaultWorkflow:i.defaultWorkflow=o});if(!n.success)throw new Error(n.error);console.log(oe.green(`\u2713 ${e}: defaultWorkflow ${t?"cleared":`\u2192 ${o}`}`))});lo.addCommand(Jn);lo.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=Vt.map(t=>({source:t,wired:ai.has(t),hint:Rc[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 Np}from"commander";import te from"chalk";we();function ft(e){let{summary:o,backupPath:t}=Qo(n=>e(n));console.log(te.green(`
428
436
  \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.
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(`
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.
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(`
437
+ `))}function Hn(){try{return D().business||{}}catch{return{}}}var ht=new Np().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");ht.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=Hn();if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o||!o.enabled){console.log(),console.log(te.yellow(" business block not enabled (or missing).")),console.log(te.dim(" Add a `business` key to agentx.json to opt in.")),console.log();return}let t=o.orgChart||{},n=o.projects||[],s=o.contactMap||[];console.log(),console.log(te.bold(" Org chart"));let i=Object.entries(t);if(i.length===0)console.log(te.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?te.dim(` \u2192 reports to ${a.reportsTo}`):"",d=a.schedule?te.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${te.cyan(r)} ${a.role}${c}${d}`)}if(console.log(),console.log(te.bold(` Projects (${n.length})`)),n.length===0)console.log(te.dim(" (empty)"));else for(let r of n){let a=r.pm?te.dim(` \xB7 pm=${r.pm}`):"",c=r.client?te.dim(` \xB7 client=${r.client}`):"";console.log(` ${te.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(te.bold(` Contact map (${s.length})`)),s.length===0)console.log(te.dim(" (empty)"));else for(let r of s){let a=r.chatId?`chatId=${r.chatId}`:r.username?`username=${r.username}`:r.senderId?`senderId=${r.senderId}`:"?",c=r.channel?`${r.channel}/`:"";console.log(` ${te.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?te.dim(` (${r.displayName})`):""}`)}console.log()});var ci=ht.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");ci.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=Hn(),t=Object.entries(o.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(t),null,2));return}if(t.length===0){console.log(te.dim(" no entries"));return}for(let[n,s]of t)console.log(` ${te.cyan(n)} ${s.role}${s.reportsTo?te.dim(` \u2192 ${s.reportsTo}`):""}`)});ci.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);ft(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}`:""})`))});ci.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{ft(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 li=ht.command("project").description("manage business.projects \u2014 id, pm, client");li.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=Hn().projects||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(te.dim(" no projects"));return}for(let n of t)console.log(` ${te.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});li.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)=>{ft(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`})});li.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{ft(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 di=ht.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");di.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let t=Hn().contactMap||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(te.dim(" no entries"));return}for(let n of t){let s=n.chatId?`chatId=${n.chatId}`:n.username?`username=${n.username}`:n.senderId?`senderId=${n.senderId}`:"?";console.log(` ${n.channel?n.channel+"/":""}${te.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});di.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)),ft(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`})});di.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=>{ft(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 Rp}from"commander";import Te from"chalk";we();var _p={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function gi(e){let o=_p[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function Gn(){let o=D().business?.standup?.plansDir||".agentx/plans";return new Dr(o)}var yt=new Rp().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");yt.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=gi(e),n=Gn(),s;if(o.file){let{readFileSync:a}=await import("fs");s=a(o.file,"utf-8")}else o.markdown?s=o.markdown:o.priority?.length?s=o.priority.map(a=>`- ${a}`).join(`
438
+ `):(console.error(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=hs(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}`))}});yt.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=Gn();if(e){let n=gi(e),s=o.read(n);if(!s){console.log(Te.dim(` No ${n} plan set.`));return}Pc(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}Pc(t.tier,t.date,t.content)});yt.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=Gn().list(parseInt(e.limit,10)||20);if(!t.length){console.log(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)}`)});yt.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=gi(e),n=Gn().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 Pc(e,o,t){console.log(Te.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
439
+ `))console.log(` ${s}`);console.log();let n=hs(t);n.length&&console.log(Te.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as Dp}from"commander";import We from"chalk";we();function Pp(){try{return D().notifications||{}}catch{return{}}}function zn(e){let{summary:o,backupPath:t}=Qo(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(We.green(`
440
+ \u2713 ${o}`)),t&&console.log(We.dim(` Backup: ${t}`)),console.log(We.dim(` Restart the daemon (or POST /reload) for the change to take effect.
441
+ `))}var wt=new Dp().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");wt.command("show").description("print current notifications config").option("--json","JSON output").action(e=>{let o=Pp();if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.destination){let n=o.destination.accountId?` \xB7 account=${o.destination.accountId}`:"";console.log(` destination ${We.cyan(o.destination.channel+":"+o.destination.chatId)}${We.dim(n)}`)}else console.log(` destination ${We.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${We.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?We.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?We.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":We.dim("off")}`),console.log()});wt.command("route").description("set the destination channel/chatId for notifications").requiredOption("--channel <name>","telegram | whatsapp | slack | discord").requiredOption("--chat-id <id>","native chat id (e.g. -100\u2026, JID, channel id)").option("--account-id <id>","channel account id when the channel is multi-account (telegram with multiple bots)").option("--clear","clear the destination instead of setting it").action(e=>{if(e.clear){zn(o=>(delete o.destination,"notifications destination cleared"));return}zn(o=>(o.destination={channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}},`notifications destination \u2192 ${e.channel}:${e.chatId}${e.accountId?` (account=${e.accountId})`:""}`))});wt.command("event <name> <state>").description("toggle an event: name in {taskComplete, taskError, taskQueued}; state in {on, off}").action((e,o)=>{let t=["taskComplete","taskError","taskQueued"];t.includes(e)||(console.log(We.red(` unknown event "${e}". Pick from: ${t.join(", ")}`)),process.exit(1));let n=o.toLowerCase();["on","off","true","false","1","0"].includes(n)||(console.log(We.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";zn(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});wt.command("threshold <seconds>").description("set the long-task threshold in seconds (0 disables long-task pings)").action(e=>{let o=parseInt(e,10);(!Number.isFinite(o)||o<0)&&(console.log(We.red(" threshold must be a non-negative integer")),process.exit(1)),zn(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});import{Command as Lp}from"commander";import So from"chalk";import{readdirSync as mi,statSync as Lc,unlinkSync as Mp,rmSync as Up,existsSync as Mc}from"fs";import{resolve as Uc,join as Fc}from"path";var qc=[{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 pi(e,o){if(!Mc(e))return[];let t=[];for(let n of mi(e,{withFileTypes:!0})){let s=Fc(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...pi(s,!0))}return t}var Vn=new Lp().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");Vn.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of qc){let t=Uc(process.cwd(),o.dir),n=pi(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=Lc(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(` ${So.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${Yn(s).padStart(10)} oldest=${r}`)}console.log(So.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${Yn(e).padStart(10)} total`)),console.log(),console.log(So.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});Vn.command("prune").description("delete files older than --days from each retention target").option("--days <n>","max age in days; everything older is deleted","30").option("--dry-run","list candidates, don't delete").option("--target <name>","limit to one target dir (e.g. .agentx/sessions)").action(e=>{let o=parseInt(e.days,10);(!Number.isFinite(o)||o<1)&&(console.log(So.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(So.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?So.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of qc){if(n&&r.dir!==n)continue;let a=Uc(process.cwd(),r.dir),c=pi(a,!!r.recursive),d=0,g=0;for(let p of c)try{let f=Lc(p);if(f.mtimeMs<t&&(g+=f.size,d++,!e.dryRun))try{Mp(p)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{Wc(a)}catch{}let l=e.dryRun?"would remove":"removed";console.log(` ${So.cyan(r.dir.padEnd(22))} ${l} ${String(d).padStart(5)} files (${Yn(g)})`),s+=d,i+=g}console.log(),console.log(So.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${Yn(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function Wc(e){if(Mc(e))for(let o of mi(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=Fc(e,o.name);Wc(t);try{mi(t).length===0&&Up(t,{recursive:!1})}catch{}}}function Yn(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}import{Command as Fp}from"commander";import U from"chalk";var Eo=new Fp().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");Eo.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()});Eo.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()});Eo.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=qp(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=qi.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(`
434
442
  \u2713 action "${r.id}" saved (${r.kind}).`)),console.log(U.dim(` Test: agentx actions run ${r.id}
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(`
443
+ `))});Eo.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`))});Eo.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 Wi(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)}});Eo.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 qp(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 Wp}from"commander";import Q from"chalk";var Bc=new Wp().name("watch").description("stream live daemon events \u2014 workflow runs, user tasks, signals, mesh health").option("-c, --config <path>","daemon config file").option("-t, --type <kinds>","comma-separated event kinds (run,task,signal,mesh,channel,status)").option("-w, --workflow <id>","only events for this workflow id").option("-a, --actor <id>","only task events involving this actor id").option("-r, --run <id>","only events for this run id").option("--channel <name>","only channel events on this channel (telegram/whatsapp/\u2026)").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let r=D(e.config);o||(o=r.dashboard?.daemonUrl||""),t||(t=r.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n=[];typeof e.type=="string"&&n.push(`type=${encodeURIComponent(e.type)}`),typeof e.workflow=="string"&&n.push(`workflow=${encodeURIComponent(e.workflow)}`),typeof e.actor=="string"&&n.push(`actor=${encodeURIComponent(e.actor)}`),typeof e.run=="string"&&n.push(`run=${encodeURIComponent(e.run)}`),typeof e.channel=="string"&&n.push(`channel=${encodeURIComponent(e.channel)}`);let s=`${o.replace(/\/+$/,"")}/events${n.length?`?${n.join("&")}`:""}`;console.log(Q.dim(` connecting to ${s}`));let i={Accept:"text/event-stream"};t&&(i.Authorization=`Bearer ${t}`);try{let r=await fetch(s,{headers:i});(!r.ok||!r.body)&&(console.error(Q.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(Q.green(" connected \u2014 Ctrl-C to stop")),console.log("");let a=r.body.getReader(),c=new TextDecoder,d="";for(;;){let{done:g,value:l}=await a.read();if(g)break;d+=c.decode(l,{stream:!0});let p;for(;(p=d.indexOf(`
436
444
 
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}`)}
445
+ `))>=0;){let f=d.slice(0,p);d=d.slice(p+2),Bp(f)}}}catch(r){console.error(Q.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function Bp(e){let o="message",t="";for(let i of e.split(`
446
+ `))i.startsWith("event: ")?o=i.slice(7):i.startsWith("data: ")&&(t=i.slice(6));if(!t)return;let n={};try{n=JSON.parse(t)}catch{console.log(`${o}: ${t}`);return}let s=n.at?Q.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=Q.cyan(n.phase?.padEnd(9)??"run"),r=Q.bold(n.workflowId??""),a=Q.dim((n.runId??"").slice(0,8)),c=n.nodeId?Q.yellow(n.nodeId):"",d=n.note?Q.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${d}`);break}case"task":{let i=Q.magenta(`task.${n.phase}`.padEnd(14)),r=Q.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?Q.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${Q.cyan(a)} ${c}`);break}case"signal":{let i=Q.green("signal".padEnd(9)),r=Q.bold(n.name),a=Q.dim(`(${n.scope})`),c=n.workflowId?Q.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=Q.blue("mesh".padEnd(9)),r=Q.bold(n.peer),a=n.healthy?Q.green("\u2713 healthy"):Q.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${Q.dim(n.delta??"")}`);break}case"channel":{let i=Q.yellow("channel".padEnd(9)),r=n.direction==="in"?Q.cyan("\u2190"):Q.magenta("\u2192"),a=Q.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?Q.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(Q.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${o} ${JSON.stringify(n)}`)}}import{Command as Hp}from"commander";import Kn from"chalk";import{spawn as Gp}from"node:child_process";import{execFileSync as Jp}from"node:child_process";function Jc(e=()=>Jp("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 Hc=new Hp().name("tui").description("open the AgentX console in OpenCode").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","daemon mesh bearer token for remote nodes").option("--agent <id>","AgentX agent to use as the OpenCode model").option("--legacy","open the built-in Ink terminal UI").option("--poll <ms>","legacy UI snapshot poll interval in ms","3000").action(async e=>{process.stdout.isTTY||(console.error(Kn.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-4KD2UA75.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-4KD2UA75.js"),g=await d(t);if(!g.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let l=e.agent||g[0].id;if(!g.some(y=>y.id===l))throw new Error(`Unknown AgentX agent: ${l}`);let p={};try{p=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(y=>[y.id,{name:`AgentX ${y.name||y.id}`}])),u={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...p,model:`agentx/${l}`,providers:{...p.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:f}}})};console.error(Kn.dim(`Opening ${n.version} with AgentX model ${l}.`));let w=Gp("opencode",["--standalone"],{stdio:"inherit",env:u});await new Promise((y,$)=>{w.once("error",$),w.once("exit",b=>b===0?y():$(new Error(`OpenCode exited with code ${b??"unknown"}`)))});return}n&&!n.ok&&(console.error(Kn.yellow(n.reason)),console.error(Kn.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-TW5N7JY2.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 zp}from"commander";import V from"chalk";import{randomUUID as Yc}from"crypto";import{createInterface as Yp}from"node:readline/promises";import Vp from"ora";import Xn from"chalk";function Gc(e){console.error(),console.error(Xn.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(Xn.dim(` ${e.why}`)),console.error(),console.error(` Use ${Xn.cyan(e.instead)} instead.`),e.note&&console.error(Xn.dim(` ${e.note}`)),console.error()}var zc={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 Vc=new zp().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)=>{Gc({what:"agentx chat",...zc});let t=Jr({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${Yc().slice(0,12)}`,r=[];try{r=await hn(t)}catch(g){console.error(V.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(V.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(V.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(V.red(` unknown agent: @${n}`)),console.error(V.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(V.dim(` no agent given \u2014 defaulting to @${n}`))),process.stdout.isTTY&&process.stdin.isTTY){let{render:g}=await import("ink"),{ChatApp:l}=await import("./ChatApp-MRGX7JBT.js"),p=(await import("react")).default;await g(p.createElement(l,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}Xp(t.baseUrl,n,i,s);let a=Yp({input:process.stdin,output:process.stdout}),c=!1,d=!1;for(a.on("close",()=>{if(c){d=!0;return}console.log(V.dim(`
447
+ bye`)),process.exit(0)});;){let g;try{g=(await a.question(V.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(V.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${Yc().slice(0,12)}`,console.log(V.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let u=await hn(t);for(let w of u){let y=w.id===n?V.green("\u25CF"):V.dim("\u25CB");console.log(` ${y} @${w.id} ${V.dim(w.tier)} ${w.model??""}`)}}catch(u){console.error(V.red(` failed to list agents: ${u?.message||u}`))}continue}if(g.startsWith("/agent ")){let u=g.slice(7).replace(/^@/,"").trim();if(!u){console.log(V.red(" usage: /agent <id>"));continue}try{if(!(await hn(t)).find(y=>y.id===u)){console.log(V.red(` unknown agent: @${u}`));continue}n=u,console.log(V.dim(` now talking to @${n}`))}catch(w){console.error(V.red(` failed to switch agent: ${w?.message||w}`))}continue}if(g.startsWith("/")){console.log(V.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(V.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let l=Vp({text:`@${n}\u2026`,color:"cyan"}).start(),p=Date.now(),f=Kp(n);try{let u=await Hr(t,n,g,{channel:s,chatId:i,onText:y=>{l.stop(),f.text(y)},onThinking:()=>{},onTool:y=>{l.stop(),f.tool(y)}});l.stop();let w=Math.round((Date.now()-p)/100)/10;u.error?f.finishError(u.error):f.finish(w,u.usage)}catch(u){l.stop(),f.finishError(u?.message||String(u))}finally{c=!1}if(d){console.log(V.dim(" bye"));return}}});function Kp(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${V.green(`@${e}`)}
440
448
  `),o=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)t&&a!==`
441
449
  `&&(process.stdout.write(" "),t=!1),process.stdout.write(a),a===`
442
450
  `&&(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(`
443
- `),t=!0);let c=r.arg?K.dim(`(${r.arg})`):"";process.stdout.write(` ${K.green("\u25CF")} ${K.bold(r.name)}${c}
451
+ `),t=!0);let c=r.arg?V.dim(`(${r.arg})`):"";process.stdout.write(` ${V.green("\u25CF")} ${V.bold(r.name)}${c}
444
452
  `)}else r.status==="result"&&r.error&&(t||(process.stdout.write(`
445
- `),t=!0),process.stdout.write(` ${K.red("\u25CF")} ${K.dim(`${r.name??"tool"} failed`)}
446
- `))},finish(r,a){if(!o){process.stdout.write(`${K.green(`@${e}`)} ${K.dim("\xB7 (empty reply)")}
453
+ `),t=!0),process.stdout.write(` ${V.red("\u25CF")} ${V.dim(`${r.name??"tool"} failed`)}
454
+ `))},finish(r,a){if(!o){process.stdout.write(`${V.green(`@${e}`)} ${V.dim("\xB7 (empty reply)")}
447
455
 
448
456
  `);return}t||process.stdout.write(`
449
- `);let c=a?.outputTokens!=null?`, ${a.outputTokens} tok`:"";process.stdout.write(K.dim(` \xB7 ${r}s${c}
457
+ `);let c=a?.outputTokens!=null?`, ${a.outputTokens} tok`:"";process.stdout.write(V.dim(` \xB7 ${r}s${c}
450
458
 
451
459
  `))},finishError(r){o&&!t&&process.stdout.write(`
452
- `),process.stdout.write(K.red(` \u2717 ${r}
460
+ `),process.stdout.write(V.red(` \u2717 ${r}
453
461
 
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}
462
+ `))}}}function Xp(e,o,t,n){console.log(),console.log(V.bold(" agentx chat")),console.log(V.dim(` daemon: ${e} \xB7 channel: ${n} \xB7 chatId: ${t}`)),console.log(V.dim(` agent: @${o} \xB7 /exit to quit \xB7 /agent <id> to switch`)),console.log()}import{Command as Qp}from"commander";import Ne from"chalk";import{readFileSync as Zp}from"fs";var Qn=["user","feedback","project","reference"],Bo=new Qp().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");Bo.command("add").description("add a memory for an agent").requiredOption("--agent <id>","agent id").requiredOption("--type <type>","one of: user, feedback, project, reference").requiredOption("--name <slug>","short slug, unique per agent (e.g. deep-backend)").requiredOption("--description <line>","one-line hook shown in MEMORY.md").option("--body <text>","memory body (markdown); repeat --body or use --file").option("--file <path>","read body from a file (use '-' for stdin)").action(async e=>{if(!Qn.includes(e.type)){console.error(Ne.red(` --type must be one of: ${Qn.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await eu();else try{o=Zp(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 zo().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}`))});Bo.command("list").description("list memories for an agent").requiredOption("--agent <id>","agent id").option("--type <type>","filter by memory type").action(e=>{let t=new zo().list(e.agent);if(e.type){if(!Qn.includes(e.type)){console.error(Ne.red(` --type must be one of: ${Qn.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.length){console.log(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}`))});Bo.command("show").description("print the full body of a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{let n=new zo().get(o.agent,e);if(!n){console.error(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)});Bo.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new zo().remove(o.agent,e)){console.error(Ne.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Ne.green(` \u2713 memory "${e}" removed`))});Bo.command("index").description("print the MEMORY.md index content an agent sees in its prompt").requiredOption("--agent <id>","agent id").action(e=>{let t=new zo().indexMarkdown(e.agent);if(!t){console.log(Ne.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});async function eu(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}fl();import ui from"chalk";import{Command as ou}from"commander";import{resolve as tu}from"path";var Kc=new ou().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(tu(e.cwd)),e.stdio!==!1?await Xi():(so.error("Only stdio transport is currently supported."),so.info(`Usage: ${ui.green("agentx serve --stdio")} or configure in your MCP client.`),so.break(),so.info("Add to Claude Code:"),so.info(ui.dim(" claude mcp add agentx -- npx agentx serve --stdio")),so.break(),so.info("Add to Cursor/MCP config:"),so.info(ui.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){Pr(o)}});import{Command as nu}from"commander";import ie from"chalk";import{spawn as fi}from"child_process";import{mkdirSync as su,writeFileSync as os,readFileSync as iu,readdirSync as ru,rmSync as Qc,openSync as Zc,existsSync as Zn}from"fs";import{resolve as au,join as Re}from"path";import{randomBytes as cu}from"crypto";var Xc={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 el="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",lu="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function du(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(Xc,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 gu(e,o,t){let n=Re(e.dir,"workspaces",e.agentId);su(n,{recursive:!0}),os(Re(n,"CLAUDE.md"),`# ${e.agentName}
455
463
 
456
464
  ${e.persona}
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(`
465
+ `),os(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}};os(Re(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function hi(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 yi(e,o,t){let n=await fetch(`http://127.0.0.1:${e}${o}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),s=await n.json().catch(()=>({}));if(!n.ok||s.error)throw new Error(s.error||`${o} HTTP ${n.status}`);return s}function es(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
458
466
  `).join(`
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})+`
467
+ `)}`)}var ol=new nu().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=au(process.cwd(),".agentx-demo"),n=du(t,o),s=Re(t,"mesh-token"),i=!!e.reuse&&Zn(s)&&Zn(Re(n[0].dir,"agentx.json")),r=i?iu(s,"utf8").trim():cu(24).toString("hex"),a=e.keep||e.reuse,c=[],d=process.argv[1];if((!d||!Zn(d))&&(console.error(ie.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!i){if(Zn(t))for(let f of ru(t))Qc(Re(t,f),{recursive:!0,force:!0});for(let f of n)gu(f,n,r);os(s,r+`
468
+ `,{mode:384})}console.log(),console.log(ie.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(ie.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(ie.dim(" Run `agentx setup` to wire real agents.\n"));let g=!1,l=f=>{if(!g){g=!0;for(let u of c)try{u.kill("SIGTERM")}catch{}setTimeout(()=>{if(!a)try{Qc(t,{recursive:!0,force:!0})}catch{}process.exit(f)},800)}};process.on("SIGINT",()=>l(0)),process.on("SIGTERM",()=>l(0));let p={...process.env};delete p.ANTHROPIC_API_KEY,delete p.ANTHROPIC_API_KEY_OLD,delete p.OPENAI_API_KEY,delete p.DEEPSEEK_API_KEY;try{for(let y of n){let $=Zc(Re(y.dir,"daemon.log"),"a"),b=fi(process.execPath,[d,"daemon","start","-c",Re(y.dir,"agentx.json")],{cwd:y.dir,env:{...p,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 hi(`${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=Zc(Re(n[0].dir,"board.log"),"a"),$=fi(process.execPath,[d,"board","serve","--bind",e.bind],{cwd:n[0].dir,env:{...p,MESH_TOKEN:r},stdio:["ignore",y,y]});c.push($)}await hi("dashboard /live",async()=>(await fetch(`http://127.0.0.1:${f}/live`)).ok,3e4),console.log(ie.green(" \u2713 dashboard up")),await hi("mesh discovery (laptop sees both peers)",async()=>((await(await fetch(`http://127.0.0.1:${n[0].port}/health`)).json()).mesh||[]).filter(v=>v.healthy&&v.skills?.length).length>=2,3e4),console.log(ie.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let u=`http://127.0.0.1:${f}/live`;if(console.log(),console.log(` Dashboard: ${ie.cyan(u)} (all three nodes via the mesh)`),console.log(ie.dim(` Daemon APIs: ${n.map(y=>`127.0.0.1:${y.port}`).join(" \xB7 ")}`)),e.open!==!1){let y=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{fi(y,[u],{stdio:"ignore",detached:!0}).unref()}catch{}}let w=async()=>{console.log(),console.log(ie.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),es("You \u2192 @cx (laptop-paris)",el,ie.cyan);let y=await yi(n[0].port,"/task",{agent:"cx",message:el});es("@cx (laptop-paris)",y.content||"(no content)",ie.green),console.log(),console.log(ie.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let $=await yi(n[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:lu}),b=typeof $.messageId=="string"?$.messageId:$.content||"(no reply)";es("@builder (vps-nyc)",b,ie.yellow);let v=await yi(n[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${b}`});es("@cx (laptop-paris)",v.content||"(no content)",ie.green),console.log(),console.log(ie.dim(` Inspect the run: ${u} \xB7 ledger rows on each node record every dispatch`)),console.log(ie.dim(` Worth your time? A star helps others find it: ${ie.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(i?console.log(ie.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await w(),e.once){console.log(),console.log(ie.dim(" --once: shutting down.")),l(0);return}console.log(),console.log(ie.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{w().catch(y=>console.error(ie.red(` Replay failed: ${y.message}`)))}),process.stdin.resume()}catch(f){console.error(),console.error(ie.red(` Demo failed: ${f.message}`)),console.error(ie.dim(` Node logs: ${n.map(u=>Re(u.dir,"daemon.log")).join(", ")}`)),l(1)}});import{Command as mu}from"commander";import{randomUUID as pu}from"crypto";import{readFileSync as uu}from"fs";import{resolve as fu}from"path";we();var nl=new mu().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??uu(0,"utf8")).trim();t||tl("no task given (pass it as an argument or on stdin)");let n=D(o.config?fu(o.config):void 0),s=n.agents[o.agent];s||tl(`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";Pi(o.agent,s,d,i)}let r=new Ki(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-${pu()}`,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})+`
461
469
  `):c.error?console.error(c.error):process.stdout.write(c.content+`
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
470
+ `),process.exit(c.error?1:0)});function tl(e){console.error(`agentx exec: ${e}`),process.exit(1)}we();import{Command as hu}from"commander";import Ee from"chalk";var Ao=new hu().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Ao.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){bt(o)}});Ao.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){bt(o)}});Ao.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 bi("/whatsapp/ingest",o);wi(t,!!e.dryRun)}catch(o){bt(o)}});Ao.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 bi("/whatsapp/ingest",t);wi(n,!!o.dryRun)}catch(t){bt(t)}});Ao.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 bi("/whatsapp/ingest",t);wi(n,!!o.dryRun)}catch(t){bt(t)}});Ao.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){bt(e)}});function wi(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 sl(){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(`${sl()}${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 bi(e,o){let t=await fetch(`${sl()}${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 bt(e){console.error(Ee.red(` ${e.message||e}`)),process.exit(1)}we();import{Command as yu}from"commander";import re from"chalk";import{existsSync as wu,mkdirSync as il,writeFileSync as Xt}from"fs";import{join as $t,resolve as bu}from"path";var Qt=new yu().name("plugin").description("manage agentx plugins (Move B)");Qt.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}});Qt.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=bu(o.cwd,t);wu(n)&&!o.force&&(console.log(re.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),il(n,{recursive:!0}),il($t(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;Xt($t(n,"package.json"),xu(e,s)),Xt($t(n,"tsconfig.json"),Su()),Xt($t(n,"src/index.ts"),Eu(e)),Xt($t(n,"README.md"),Au(e,s)),Xt($t(n,".gitignore"),Ou()),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()});Qt.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 $u(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 $u(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=ku(o);if(!vu(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=gr.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 ku(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 vu(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function xu(e,o){return JSON.stringify({name:e,version:"0.1.0",description:o,main:"dist/index.js",types:"dist/index.d.ts",files:["dist"],scripts:{build:"tsc",prepublishOnly:"pnpm build"},keywords:["agentx","agentx-plugin"],license:"MIT",devDependencies:{typescript:"^5.4.0","@types/node":"^20.0.0"}},null,2)+`
471
+ `}function Su(){return JSON.stringify({compilerOptions:{target:"es2020",module:"commonjs",lib:["es2020"],declaration:!0,outDir:"dist",strict:!0,esModuleInterop:!0,skipLibCheck:!0,moduleResolution:"node"},include:["src/**/*.ts"]},null,2)+`
472
+ `}function Eu(e){return`// ${e} \u2014 AgentX plugin
465
473
  //
466
474
  // A plugin's default export is { manifest, setup }. The daemon calls
467
475
  // setup(ctx) once at boot. ctx.on() subscribes to the bus; ctx.addChannel()
@@ -497,7 +505,7 @@ const plugin = {
497
505
  }
498
506
 
499
507
  export default plugin
500
- `}function du(e,o){return`# ${e}
508
+ `}function Au(e,o){return`# ${e}
501
509
 
502
510
  ${o}
503
511
 
@@ -524,19 +532,19 @@ agentx plugin doctor
524
532
  \`\`\`
525
533
 
526
534
  Restart the daemon to activate.
527
- `}function gu(){return`node_modules/
535
+ `}function Ou(){return`node_modules/
528
536
  dist/
529
537
  *.log
530
538
  .env
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(`
539
+ `}import{Command as Iu}from"commander";import Ae from"chalk";import{writeFileSync as ju,mkdirSync as Cu,existsSync as ts,readFileSync as rl,appendFileSync as al}from"fs";import{resolve as kt,dirname as dl}from"path";import{homedir as ki}from"os";var gl=new Iu().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-Z6EK44PV.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Ru(t);break;case"bash":s=Mu(t);break;case"fish":s=Uu(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?kt(String(e.output)):Tu(n);Cu(dl(i),{recursive:!0}),ju(i,s),console.log(Ae.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Nu(n,i,!!e.yes)});function Tu(e){let o=ki();switch(e){case"zsh":return kt(o,".zsh","completions","_agentx");case"bash":return kt(o,".bash_completion.d","agentx.bash");case"fish":return kt(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Nu(e,o,t){if(e==="zsh"){let n=kt(ki(),".zshrc"),s=dl(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=ts(n)?rl(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&&ts(n)){let g=["","# agentx completion"];c&&g.push(i),d&&g.push(r),al(n,g.join(`
532
540
  `)+`
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,`
541
+ `),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=kt(ki(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((ts(n)?rl(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&&ts(n)){al(n,`
534
542
  # agentx completion
535
543
  ${s}
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
544
+ `),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 Fe(e){return e._name||e.name()||""}function Oo(e){return e.commands.filter(o=>{let t=Fe(o);return!(!t||t==="help")})}function Zt(e){return e.options.filter(o=>!o.hidden)}function Ru(e){let o=[];return o.push("#compdef agentx"),o.push(""),ml(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
545
+ `)}function cl(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function ml(e,o,t){let n=Oo(e),i=Zt(e).map(Pu).filter(c=>!!c),r=cl(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(Lu).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=cl([...o,Fe(c)]);t.push(` (${Fe(c)}) ${d} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)ml(c,[...o,Fe(c)],t)}function _u(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Du(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Pu(e){let o=e.short||void 0,t=e.long||void 0;if(!o&&!t)return null;let n=_u(e.description||"");return o&&t?` "(${t} ${o})"{${t},${o}}"[${n}]"`:` "${t||o}[${n}]"`}function Lu(e){let o=Du(e.description()||"");return`'${Fe(e)}[${o}]'`}function Mu(e){let o=Oo(e),t=[];t.push("# bash completion for agentx"),t.push("_agentx_complete() {"),t.push(" local cur prev words cword"),t.push(" COMPREPLY=()"),t.push(' cur="${COMP_WORDS[COMP_CWORD]}"'),t.push(' prev="${COMP_WORDS[COMP_CWORD-1]}"'),t.push(""),t.push(` local top="${o.map(Fe).join(" ")}"`),t.push(""),t.push(" if [[ $COMP_CWORD -eq 1 ]]; then"),t.push(' COMPREPLY=( $(compgen -W "$top" -- "$cur") )'),t.push(" return 0"),t.push(" fi"),t.push(""),t.push(' local cmd="${COMP_WORDS[1]}"'),t.push(' local sub2="${COMP_WORDS[2]:-}"'),t.push(' case "$cmd" in');for(let n of o){let s=Oo(n).map(Fe),i=ll(n);if(t.push(` ${Fe(n)})`),s.length>0){t.push(" if [[ $COMP_CWORD -eq 2 ]]; then"),t.push(` COMPREPLY=( $(compgen -W "${s.join(" ")} ${i}" -- "$cur") )`),t.push(" return 0"),t.push(" fi"),t.push(' case "$sub2" in');for(let r of Oo(n)){let a=ll(r);t.push(` ${Fe(r)})`),t.push(` COMPREPLY=( $(compgen -W "${a}" -- "$cur") )`),t.push(" return 0"),t.push(" ;;")}t.push(" esac")}else t.push(` COMPREPLY=( $(compgen -W "${i}" -- "$cur") )`);t.push(" ;;")}return t.push(" esac"),t.push("}"),t.push(""),t.push("complete -F _agentx_complete agentx"),t.push(""),t.join(`
546
+ `)}function ll(e){let o=[];for(let t of Zt(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function Uu(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 Oo(e)){let n=vi(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${Fe(t)}" -d "${n}"`)}o.push("");for(let t of Zt(e)){let n=$i(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of Oo(e)){let n=Fe(t);o.push(`# ${n}`);for(let s of Zt(t)){let i=$i(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of Oo(t)){let i=vi(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${Oo(t).map(Fe).join(" ")}" -a "${Fe(s)}" -d "${i}"`);for(let r of Zt(s)){let a=$i(r,[`__fish_seen_subcommand_from ${Fe(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
547
+ `)}function vi(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function $i(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=vi(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 Lr(),o=new Fu().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=qr(n);Wr(s)&&Fr("cli",s)});for(let t of[ga,ca,gt,et,Xe,Ur,No,En,vo,Mo,Sn,Hc,$o,va,Ta,qa,Ja,Ha,Ka,ec,oc,Pn,Jt,Kc,Rt,ho,gl])o.addCommand(t);for(let t of pl)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=pl.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,qu(t,74," "),""].join(`
548
+ `)}),o}var pl=[ee,mt,Bo,Ve,Dt,ct,Ue,lo,xo,Uo,ht,yt,bo,De,Pt,Ln,Bc,ao,st,Gr,Ro,Qt,As,Eo,nt,Os,Vn,wt,Ao,ol,nl,Vc];function qu(e,o,t){let n=[],s="";for(let i of e)s&&s.length+i.length+2>o&&(n.push(t+s),s=""),s+=(s?", ":"")+i;return s&&n.push(t+s),n.join(`
549
+ `)}export{Yx as a};
550
+ //# sourceMappingURL=chunk-UORMWVLP.js.map