agentix-cli 0.42.0 → 0.44.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 (116) hide show
  1. package/apps/mac-helper/Resources/AppIcon.png +0 -0
  2. package/apps/mac-helper/Sources/AgentXHelper/Notify.swift +51 -0
  3. package/apps/mac-helper/Sources/AgentXHelper/main.swift +15 -1
  4. package/apps/mac-helper/build.sh +25 -2
  5. package/dist/{App-HSRGG5VA.js → App-QTUGMHG7.js} +2 -2
  6. package/dist/{ChatApp-4FOU6Q3S.js → ChatApp-634FDG3W.js} +2 -2
  7. package/dist/{agent-54NUP2Z3.js → agent-3XDPLWMX.js} +2 -2
  8. package/dist/{board-dashboard-HLTVSSGW.js → board-dashboard-OYGL7Z7X.js} +455 -161
  9. package/dist/board-dashboard-OYGL7Z7X.js.map +1 -0
  10. package/dist/{chunk-H4MIYENA.js → chunk-6HMZ5TTM.js} +2 -2
  11. package/dist/{chunk-SJPLXXCI.js → chunk-7A7RC3R4.js} +2 -2
  12. package/dist/{chunk-FZ3ZDG6T.js → chunk-7HHVZJO4.js} +195 -211
  13. package/dist/chunk-7HHVZJO4.js.map +1 -0
  14. package/dist/chunk-BIFJSQB5.js +123 -0
  15. package/dist/chunk-BIFJSQB5.js.map +1 -0
  16. package/dist/{chunk-WBGROLOX.js → chunk-BTGPZ6B7.js} +2 -2
  17. package/dist/{chunk-X763UOES.js → chunk-ICZPZYYR.js} +2 -2
  18. package/dist/{chunk-RCVGIKC2.js → chunk-MTVRYTLL.js} +2 -2
  19. package/dist/{chunk-B32HVIDN.js → chunk-NSYY5NCR.js} +3 -3
  20. package/dist/chunk-NSYY5NCR.js.map +1 -0
  21. package/dist/chunk-P2Y7DFFP.js +36 -0
  22. package/dist/chunk-P2Y7DFFP.js.map +1 -0
  23. package/dist/{chunk-2IYOKDVI.js → chunk-Q3Q6FTFY.js} +194 -164
  24. package/dist/chunk-Q3Q6FTFY.js.map +1 -0
  25. package/dist/chunk-QJANPP4C.js +15 -0
  26. package/dist/chunk-QJANPP4C.js.map +1 -0
  27. package/dist/{chunk-REPZID5M.js → chunk-SAFAI4AV.js} +43 -43
  28. package/dist/chunk-SAFAI4AV.js.map +1 -0
  29. package/dist/chunk-T76YTN34.js +178 -0
  30. package/dist/chunk-T76YTN34.js.map +1 -0
  31. package/dist/chunk-TCJ3SMOF.js +9 -0
  32. package/dist/chunk-TCJ3SMOF.js.map +1 -0
  33. package/dist/{chunk-RQKUQOFC.js → chunk-TNFOGJWZ.js} +2 -2
  34. package/dist/{chunk-FAJEBVZE.js → chunk-V5FZJUK4.js} +2 -2
  35. package/dist/chunk-WLVQDEOT.js +2 -0
  36. package/dist/chunk-WLVQDEOT.js.map +1 -0
  37. package/dist/{chunk-B5HKRYCU.js → chunk-YQVR2HQS.js} +2 -2
  38. package/dist/cli.js +1 -1
  39. package/dist/cli.js.map +1 -1
  40. package/dist/client-NTC667CA.js +2 -0
  41. package/dist/config-5V444ZFW.js +2 -0
  42. package/dist/config-mutator-E6NQLFWR.js +2 -0
  43. package/dist/doctor-5HDW5F66.js +2 -0
  44. package/dist/{editor-chat-OB7IQOB5.js → editor-chat-MOMQHMO4.js} +2 -2
  45. package/dist/editor-chat-MOMQHMO4.js.map +1 -0
  46. package/dist/index.d.ts +462 -46
  47. package/dist/index.js +1 -1
  48. package/dist/index.js.map +1 -1
  49. package/dist/program-HGI5C2MP.js +2 -0
  50. package/dist/query-6EMTLCHQ.js +2 -0
  51. package/dist/registry-5QOY65FS.js +2 -0
  52. package/dist/{request-planner-326NOKPZ.js → request-planner-KYQCJDAW.js} +2 -2
  53. package/dist/{review-candidates-LEOPEOEG.js → review-candidates-BFAWNDOR.js} +2 -2
  54. package/dist/routing-OC3QJI3W.js +2 -0
  55. package/dist/schedule-tool-VQCNMBJF.js +8 -0
  56. package/dist/schedule-tool-VQCNMBJF.js.map +1 -0
  57. package/dist/scheduler-NRXPVG7P.js +2 -0
  58. package/dist/seat-3WT3VJC2.js +2 -0
  59. package/dist/{select-L4VIYSFJ.js → select-KPQWIC22.js} +2 -2
  60. package/dist/web/activity-graph.global.js.map +1 -1
  61. package/dist/web/workflow-editor.global.js +1 -1
  62. package/dist/web/workflow-editor.global.js.map +1 -1
  63. package/dist/wiki-5JORBO4G.js +2 -0
  64. package/package.json +2 -1
  65. package/dist/board-dashboard-HLTVSSGW.js.map +0 -1
  66. package/dist/chunk-2IYOKDVI.js.map +0 -1
  67. package/dist/chunk-B32HVIDN.js.map +0 -1
  68. package/dist/chunk-DIKZWTL5.js +0 -170
  69. package/dist/chunk-DIKZWTL5.js.map +0 -1
  70. package/dist/chunk-F6CNF7V3.js +0 -25
  71. package/dist/chunk-F6CNF7V3.js.map +0 -1
  72. package/dist/chunk-FZ3ZDG6T.js.map +0 -1
  73. package/dist/chunk-IAG6FI3Q.js +0 -13
  74. package/dist/chunk-IAG6FI3Q.js.map +0 -1
  75. package/dist/chunk-NZ6AQIKJ.js +0 -121
  76. package/dist/chunk-NZ6AQIKJ.js.map +0 -1
  77. package/dist/chunk-P7LNYB53.js +0 -9
  78. package/dist/chunk-P7LNYB53.js.map +0 -1
  79. package/dist/chunk-REPZID5M.js.map +0 -1
  80. package/dist/client-6BGTH2TT.js +0 -2
  81. package/dist/config-SRTXHGSK.js +0 -2
  82. package/dist/config-mutator-KJ5GEMVV.js +0 -2
  83. package/dist/doctor-J4FLV45L.js +0 -2
  84. package/dist/editor-chat-OB7IQOB5.js.map +0 -1
  85. package/dist/program-LAACUZWW.js +0 -2
  86. package/dist/query-ZSUBNWOL.js +0 -2
  87. package/dist/registry-OMUDCBKM.js +0 -2
  88. package/dist/routing-AWIRBYGU.js +0 -2
  89. package/dist/scheduler-PGGYW5AB.js +0 -2
  90. package/dist/seat-XB4EGUKJ.js +0 -2
  91. package/dist/wiki-GBC6I7ZX.js +0 -2
  92. /package/dist/{App-HSRGG5VA.js.map → App-QTUGMHG7.js.map} +0 -0
  93. /package/dist/{ChatApp-4FOU6Q3S.js.map → ChatApp-634FDG3W.js.map} +0 -0
  94. /package/dist/{agent-54NUP2Z3.js.map → agent-3XDPLWMX.js.map} +0 -0
  95. /package/dist/{chunk-H4MIYENA.js.map → chunk-6HMZ5TTM.js.map} +0 -0
  96. /package/dist/{chunk-SJPLXXCI.js.map → chunk-7A7RC3R4.js.map} +0 -0
  97. /package/dist/{chunk-WBGROLOX.js.map → chunk-BTGPZ6B7.js.map} +0 -0
  98. /package/dist/{chunk-X763UOES.js.map → chunk-ICZPZYYR.js.map} +0 -0
  99. /package/dist/{chunk-RCVGIKC2.js.map → chunk-MTVRYTLL.js.map} +0 -0
  100. /package/dist/{chunk-RQKUQOFC.js.map → chunk-TNFOGJWZ.js.map} +0 -0
  101. /package/dist/{chunk-FAJEBVZE.js.map → chunk-V5FZJUK4.js.map} +0 -0
  102. /package/dist/{chunk-B5HKRYCU.js.map → chunk-YQVR2HQS.js.map} +0 -0
  103. /package/dist/{client-6BGTH2TT.js.map → client-NTC667CA.js.map} +0 -0
  104. /package/dist/{config-SRTXHGSK.js.map → config-5V444ZFW.js.map} +0 -0
  105. /package/dist/{config-mutator-KJ5GEMVV.js.map → config-mutator-E6NQLFWR.js.map} +0 -0
  106. /package/dist/{doctor-J4FLV45L.js.map → doctor-5HDW5F66.js.map} +0 -0
  107. /package/dist/{program-LAACUZWW.js.map → program-HGI5C2MP.js.map} +0 -0
  108. /package/dist/{query-ZSUBNWOL.js.map → query-6EMTLCHQ.js.map} +0 -0
  109. /package/dist/{registry-OMUDCBKM.js.map → registry-5QOY65FS.js.map} +0 -0
  110. /package/dist/{request-planner-326NOKPZ.js.map → request-planner-KYQCJDAW.js.map} +0 -0
  111. /package/dist/{review-candidates-LEOPEOEG.js.map → review-candidates-BFAWNDOR.js.map} +0 -0
  112. /package/dist/{routing-AWIRBYGU.js.map → routing-OC3QJI3W.js.map} +0 -0
  113. /package/dist/{scheduler-PGGYW5AB.js.map → scheduler-NRXPVG7P.js.map} +0 -0
  114. /package/dist/{seat-XB4EGUKJ.js.map → seat-3WT3VJC2.js.map} +0 -0
  115. /package/dist/{select-L4VIYSFJ.js.map → select-KPQWIC22.js.map} +0 -0
  116. /package/dist/{wiki-GBC6I7ZX.js.map → wiki-5JORBO4G.js.map} +0 -0
@@ -1,34 +1,34 @@
1
- import{a as ta,b as xn,g as na}from"./chunk-SJPLXXCI.js";import{b as Xr}from"./chunk-B5HKRYCU.js";import{a as nt,b as Kr,f as vn,j as oa}from"./chunk-REPZID5M.js";import{a as Qr,c as Zr,d as ea}from"./chunk-2TJ5L7CB.js";import{a as et}from"./chunk-GV7S5BAX.js";import{e as er}from"./chunk-GSX4NK2N.js";import{c as or}from"./chunk-SZDACK6O.js";import{$ as Dt,A as ks,B as fn,C as Cr,D as ot,E as ho,F as Nr,G as vs,H as xs,I as Rr,J as Dr,K as Rt,L as hn,M as _r,N as Pr,O as Lr,P as tt,Q as Mr,R as Fr,S as Ss,T as yn,U as wn,V as Ur,W as qr,X as Wr,Y as Br,Z as $e,_ as bn,a as dr,aa as Es,b as gr,ba as Jr,ca as $n,da as kn,ea as zr,fa as Ts,ga as Is,h as fr,ha as Yr,i as hr,ia as Vr,j as Ct,k as un,l as yr,m as wr,n as br,o as $r,p as kr,q as vr,r as xr,s as Sr,t as Er,u as Ar,v as Or,w as Tr,x as Ir,y as jr,z as Nt}from"./chunk-FZ3ZDG6T.js";import{i as Gr,j as As,k as Hr,l as Os}from"./chunk-F6CNF7V3.js";import{a as mr,d as pr,e as ur}from"./chunk-FAJEBVZE.js";import{J as lr,m as Ki,o as Xo,q as ws,r as Qi,t as fo,z as cr}from"./chunk-DIKZWTL5.js";import{b as Qo,c as mn,d as pn,e as Zo,f as Zi,g as No,h as jt}from"./chunk-P7LNYB53.js";import{d as $s,f as rr}from"./chunk-VMDA2SX2.js";import{a as ir}from"./chunk-QLTM3F7M.js";import{a as Xi,e as sr}from"./chunk-NZ6AQIKJ.js";import{f as tr,g as nr,h as bs}from"./chunk-76Z4VHDX.js";import{a as de,b as be,c as Ro,d as ar}from"./chunk-B32HVIDN.js";import{h as Vi}from"./chunk-DWADWDMU.js";import{b as uo,d as gn,f as ys}from"./chunk-RCVGIKC2.js";import{b as Ko,d as Yi}from"./chunk-2GIDVZ4H.js";import{a as hs,b as Pi,c as Ll,d as ln,e as Li,f as Wi,g as Fl,h as Bi,i as Ul,m as Vo,n as Gi,o as Hi,s as zi,v as Qe,w as It}from"./chunk-H4MIYENA.js";import{a as Ji,b as ql}from"./chunk-AJONZWLT.js";import{a as ao,b as Yo,e as Fi,f as Tt}from"./chunk-F4HZTZHW.js";import{a as ro,b as Pl}from"./chunk-L2WSPY6S.js";import{f as Mi,g as _,h as dn,j as pe}from"./chunk-IAG6FI3Q.js";import{g as Ui,k as qi,l as Ml}from"./chunk-BH3GTCZ6.js";import{a as _l}from"./chunk-FIOB3MEX.js";import{Command as Wl}from"commander";var sa=new Wl().name("a2a").description("start an A2A (Agent-to-Agent) protocol server for external agent integration").option("--port <port>","server port","3171").option("--host <host>","server host","0.0.0.0").option("-p, --provider <provider>","AI provider","claude-code").option("-m, --model <model>","model to use").option("--api-key <key>","API key for the provider").option("-c, --cwd <cwd>","working directory",process.cwd()).option("--no-cors","disable CORS headers").action(async e=>{await new gr({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});pe();import{Command as Bl}from"commander";import{execFileSync as co}from"node:child_process";import{cpSync as ia,existsSync as Ns,mkdirSync as js,mkdtempSync as Jl,readFileSync as Gl,rmSync as Hl,writeFileSync as ra}from"node:fs";import{dirname as Cs,join as Ie,resolve as aa}from"node:path";import{homedir as Sn,release as zl,tmpdir as Yl}from"node:os";import{fileURLToPath as Vl}from"node:url";import{setTimeout as Kl}from"node:timers/promises";function En(){let e=Ur(process.platform,process.arch,zl());if(e)throw new Error(e)}function _t(){return`gui/${process.getuid()}/${Ss}`}function st(){return Ie(Sn(),"Library/LaunchAgents",`${Ss}.plist`)}async function ca(){try{co("launchctl",["bootout",_t()],{stdio:"pipe"})}catch{}for(let e=0;e<30;e++){try{co("launchctl",["print",_t()],{stdio:"pipe"})}catch{return}await Kl(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function la(){if(!Ns(st()))throw new Error("Run agentx desktop install first.");let e=!0;try{co("launchctl",["print",_t()],{stdio:"pipe"})}catch{e=!1}e||co("launchctl",["bootstrap",`gui/${process.getuid()}`,st()],{stdio:"pipe"}),co("launchctl",["kickstart",_t()],{stdio:"pipe"})}function Xl(){let e=Cs(Vl(import.meta.url));for(let o of[aa(e,".."),aa(e,"../.."),process.cwd()])try{if(JSON.parse(Gl(Ie(o,"package.json"),"utf8")).name==="agentix-cli"&&Ns(Ie(o,"apps/mac-voice/build.sh")))return o}catch{}throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var it=new Bl("desktop").description("install and control the macOS desktop assistant");it.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","agent to use (defaults to the first configured agent)").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{En();let o=_(),t=qr(o.agents,e.agent),n=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,s=Xl(),i=Ie(Sn(),"Applications");if(console.log(`Desktop assistant \u2192 ${Ie(i,yn)}
2
- Computer-use helper \u2192 ${Ie(i,wn)}
1
+ import{a as ha,b as An,g as ya}from"./chunk-7A7RC3R4.js";import{b as da}from"./chunk-YQVR2HQS.js";import{a as Do,b as la,f as En,i as Cs,j as ua,l as fa}from"./chunk-SAFAI4AV.js";import{a as ga,c as ma,d as pa}from"./chunk-2TJ5L7CB.js";import{a as $s,b as pr,c as ks,g as ur,h as fr,j as hr,k as yr,m as wr,n as br,o as $r}from"./chunk-WLVQDEOT.js";import{a as tt}from"./chunk-GV7S5BAX.js";import{e as sr}from"./chunk-GSX4NK2N.js";import{c as ir}from"./chunk-SZDACK6O.js";import{$ as aa,A as zr,B as st,C as yo,D as Yr,E as Ss,F as Es,G as Vr,H as Kr,I as _t,J as kn,K as Xr,L as Qr,M as Zr,N as ea,O as it,P as oa,Q as ta,R as $e,S as vn,T as Pt,U as As,V as na,W as xn,X as Sn,Y as ra,Z as Is,_ as js,a as kr,aa as ca,b as vr,h as Ar,i as Or,j as Rt,k as hn,l as Tr,m as Ir,n as jr,o as Cr,p as Fr,q as Ur,r as qr,s as Wr,t as Br,u as Jr,v as Gr,w as Hr,x as Dt,y as xs,z as $n}from"./chunk-7HHVZJO4.js";import{A as Ts,k as vs,l as yn,m as wn,n as Nr,o as Rr,p as Dr,q as _r,r as Pr,u as bn,v as Mr,w as Lr,x as sa,y as Os,z as ia}from"./chunk-P2Y7DFFP.js";import{a as xr,d as Sr,e as Er}from"./chunk-V5FZJUK4.js";import{D as gr,N as mr,h as Zi,q as er,s as Zo,u as ys,v as tr,x as ho}from"./chunk-T76YTN34.js";import{b as et,c as un,d as fn,e as ot,f as nr,g as Ro,h as Nt}from"./chunk-TCJ3SMOF.js";import{d as bs,f as lr}from"./chunk-VMDA2SX2.js";import{a as Qi}from"./chunk-QLTM3F7M.js";import{a as or,e as cr}from"./chunk-BIFJSQB5.js";import{f as rr,g as ar,h as ws}from"./chunk-76Z4VHDX.js";import{b as ue,c as Se,d as nt,e as dr}from"./chunk-NSYY5NCR.js";import{h as Xi}from"./chunk-DWADWDMU.js";import{b as fo,d as pn,f as hs}from"./chunk-MTVRYTLL.js";import{b as Qo,d as Ki}from"./chunk-2GIDVZ4H.js";import{a as fs,b as Li,c as Zl,d as gn,e as Fi,f as Ji,g as od,h as Gi,i as td,m as Xo,n as zi,o as Yi,s as Vi,v as Ze,w as Ct}from"./chunk-6HMZ5TTM.js";import{a as ro,b as Ko,e as qi,f as jt}from"./chunk-F4HZTZHW.js";import{a as Hi,b as nd}from"./chunk-AJONZWLT.js";import{a as io,b as Ql}from"./chunk-L2WSPY6S.js";import{k as Ui,l as _,m as mn,o as ge}from"./chunk-QJANPP4C.js";import{g as Wi,k as Bi,l as ed}from"./chunk-BH3GTCZ6.js";import{a as Xl}from"./chunk-FIOB3MEX.js";import{Command as sd}from"commander";var wa=new sd().name("a2a").description("start an A2A (Agent-to-Agent) protocol server for external agent integration").option("--port <port>","server port","3171").option("--host <host>","server host","0.0.0.0").option("-p, --provider <provider>","AI provider","claude-code").option("-m, --model <model>","model to use").option("--api-key <key>","API key for the provider").option("-c, --cwd <cwd>","working directory",process.cwd()).option("--no-cors","disable CORS headers").action(async e=>{await new vr({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});ge();import{Command as id}from"commander";import{execFileSync as ao}from"node:child_process";import{cpSync as ba,existsSync as Ds,mkdirSync as Ns,mkdtempSync as rd,readFileSync as ad,rmSync as cd,writeFileSync as $a}from"node:fs";import{dirname as Rs,join as je,resolve as ka}from"node:path";import{homedir as On,release as ld,tmpdir as dd}from"node:os";import{fileURLToPath as gd}from"node:url";import{setTimeout as md}from"node:timers/promises";function Tn(){let e=Nr(process.platform,process.arch,ld());if(e)throw new Error(e)}function Mt(){return`gui/${process.getuid()}/${vs}`}function rt(){return je(On(),"Library/LaunchAgents",`${vs}.plist`)}async function va(){try{ao("launchctl",["bootout",Mt()],{stdio:"pipe"})}catch{}for(let e=0;e<30;e++){try{ao("launchctl",["print",Mt()],{stdio:"pipe"})}catch{return}await md(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function xa(){if(!Ds(rt()))throw new Error("Run agentx desktop install first.");let e=!0;try{ao("launchctl",["print",Mt()],{stdio:"pipe"})}catch{e=!1}e||ao("launchctl",["bootstrap",`gui/${process.getuid()}`,rt()],{stdio:"pipe"}),ao("launchctl",["kickstart",Mt()],{stdio:"pipe"})}function pd(){let e=Rs(gd(import.meta.url));for(let o of[ka(e,".."),ka(e,"../.."),process.cwd()])try{if(JSON.parse(ad(je(o,"package.json"),"utf8")).name==="agentix-cli"&&Ds(je(o,"apps/mac-voice/build.sh")))return o}catch{}throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var at=new id("desktop").description("install and control the macOS desktop assistant");at.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","agent to use (defaults to the first configured agent)").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{Tn();let o=_(),t=Rr(o.agents,e.agent),n=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,s=pd(),i=je(On(),"Applications");if(console.log(`Desktop assistant \u2192 ${je(i,yn)}
2
+ Computer-use helper \u2192 ${je(i,wn)}
3
3
  Agent \u2192 ${t}
4
4
  Daemon \u2192 ${n}
5
- Starts at login \u2192 ${st()}`),e.dryRun)return;try{co("xcrun",["--find","swiftc"],{stdio:"pipe"})}catch{throw new Error("Apple command-line tools are required. Run xcode-select --install, finish installation, then retry.")}let r=Jl(Ie(Yl(),"agentx-desktop-"));try{for(let g of["mac-helper","mac-voice"])ia(Ie(s,"apps",g),Ie(r,g),{recursive:!0,filter:l=>!l.split("/").includes("build")}),co("/bin/bash",[Ie(r,g,"build.sh")],{stdio:"inherit"});let a=Ie(Sn(),"Library/Logs/agentx-desktop.err.log"),c=Wr({executable:Ie(i,yn,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:t,url:n,helper:Br(Sn()),cli:Ie(s,"dist/cli.js"),node:process.execPath,log:a}),d=Ie(r,"desktop.plist");ra(d,c,{mode:384}),co("plutil",["-lint",d],{stdio:"pipe"}),await ca(),js(i,{recursive:!0});for(let[g,l,p]of[["mac-voice","AgentX Voice.app",yn],["mac-helper",wn,wn]])ia(Ie(r,g,"build",l),Ie(i,p),{recursive:!0});js(Cs(st()),{recursive:!0}),js(Cs(a),{recursive:!0}),ra(st(),c,{mode:384}),la(),console.log(`Desktop assistant is running. Hold Option\u2013Space to speak; Command\u2013Option\u2013V for smart paste.
5
+ Starts at login \u2192 ${rt()}`),e.dryRun)return;try{ao("xcrun",["--find","swiftc"],{stdio:"pipe"})}catch{throw new Error("Apple command-line tools are required. Run xcode-select --install, finish installation, then retry.")}let r=rd(je(dd(),"agentx-desktop-"));try{for(let g of["mac-helper","mac-voice"]){ba(je(s,"apps",g),je(r,g),{recursive:!0,filter:u=>!u.split("/").includes("build")});let d=g==="mac-helper"?_r(o.notifications.local.icon):[];ao("/bin/bash",[je(r,g,"build.sh"),...d],{stdio:"inherit"})}let a=je(On(),"Library/Logs/agentx-desktop.err.log"),c=Dr({executable:je(i,yn,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:t,url:n,helper:Pr(On()),cli:je(s,"dist/cli.js"),node:process.execPath,log:a}),l=je(r,"desktop.plist");$a(l,c,{mode:384}),ao("plutil",["-lint",l],{stdio:"pipe"}),await va(),Ns(i,{recursive:!0});for(let[g,d,u]of[["mac-voice","AgentX Voice.app",yn],["mac-helper",wn,wn]])ba(je(r,g,"build",d),je(i,u),{recursive:!0});Ns(Rs(rt()),{recursive:!0}),Ns(Rs(a),{recursive:!0}),$a(rt(),c,{mode:384}),xa(),console.log(`Desktop assistant is running. Hold Option\u2013Space to speak; Command\u2013Option\u2013V for smart paste.
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{Hl(r,{recursive:!0,force:!0})}});it.command("start").description("start the installed desktop assistant").action(()=>{En(),la(),console.log("Desktop assistant started.")});it.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{En(),await ca(),console.log("Desktop assistant stopped.")});it.command("status").description("show the desktop login service status").action(()=>{En();try{console.log(co("launchctl",["print",_t()],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(Ns(st())?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as nd}from"commander";import{open as sd}from"fs/promises";import{existsSync as Tn,mkdirSync as Ql,readFileSync as In,writeFileSync as da}from"fs";import{homedir as Zl}from"os";import{dirname as ed,resolve as Rs}from"path";var Ds="/attach/",ga="/guard/check";function ma(e,o,t=""){return`curl -s --max-time 3 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${o}${e}${t}`}' 2>/dev/null || true`}function An(e,o,t){let n={hooks:[{type:"command",command:ma(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function od(e){return{SessionStart:[An("/attach/session-start",e,"")],UserPromptSubmit:[An("/attach/prompt",e)],Stop:[An("/attach/stop",e)],SessionEnd:[An("/attach/session-end",e)]}}function td(e){let o=ma("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function On(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function Pt(){return Rs(Zl(),".claude/settings.json")}function Lt(e=process.cwd()){for(let o of[e,Rs(e,"..")]){let t=Rs(o,"agentx.json");if(Tn(t))try{let n=JSON.parse(In(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function pa(e,o={}){let t=o.path??Pt(),n=o.withGuard!==!1,s={};if(Tn(t))try{s=JSON.parse(In(t,"utf-8"))}catch(g){throw new Error(`${t} is not valid JSON (${g?.message}) \u2014 refusing to overwrite it`)}let i=JSON.stringify(s),r=s.hooks??={},a=[];for(let[g,l]of Object.entries(od(e))){let p=Array.isArray(r[g])?r[g].filter(f=>!On(f,Ds)):[];r[g]=[...p,...l],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(l=>!On(l,ga)):[];r.PreToolUse=[...g,...td(e)],c=!0}let d=JSON.stringify(s)!==i;return d&&(Ql(ed(t),{recursive:!0}),da(t,`${JSON.stringify(s,null,2)}
8
- `)),{path:t,changed:d,events:a,guardInstalled:c}}function ua(e={}){let o=e.path??Pt();if(!Tn(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(In(o,"utf-8"))}catch(a){throw new Error(`${o} is not valid JSON (${a?.message}) \u2014 refusing to rewrite it`)}let n=JSON.stringify(t),s=t.hooks,i=[];if(s&&typeof s=="object"){for(let a of Object.keys(s)){if(!Array.isArray(s[a]))continue;let c=a==="PreToolUse"?ga:Ds;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let d=s[a].filter(g=>!On(g,c));d.length!==s[a].length&&i.push(a),d.length===0?delete s[a]:s[a]=d}Object.keys(s).length===0&&delete t.hooks}let r=JSON.stringify(t)!==n;return r&&da(o,`${JSON.stringify(t,null,2)}
9
- `),{path:o,changed:r,events:i,guardInstalled:!1}}function jn(e=Pt()){if(!Tn(e))return!1;try{return!!JSON.parse(In(e,"utf-8"))?.hooks?.Stop?.some?.(t=>On(t,Ds))}catch{return!1}}var Cn=new nd("monitor").description("Register external CLI sessions and report ended runs to the briefing"),fa=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Lt()}`;async function ha(e,o,t){let n=process.env.MESH_TOKEN,s=await fetch(e.replace(/\/$/,"")+"/monitor/"+o,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify(t),signal:AbortSignal.timeout(8e3)});if(!s.ok)throw new Error(`Monitor HTTP ${s.status}: ${(await s.text()).slice(0,300)}`)}Cn.command("register").requiredOption("--session <id>","Native session ID").requiredOption("--runtime <name>","claude, codex, gemini, opencode, or another CLI").requiredOption("--label <label>","Human-readable task label").option("--url <url>","Daemon URL",fa).action(async e=>{try{await ha(e.url,"register",pr.parse({id:e.session,runtime:e.runtime,label:e.label})),console.log("Session registered. Report each stopped run with agentx monitor ended.")}catch(o){console.error(o.message),process.exitCode=1}});Cn.command("ended").requiredOption("--session <id>","Registered session ID").requiredOption("--run <id>","Stable unique turn ID; reuse this ID when retrying delivery").requiredOption("--transcript <file>","Local transcript file; only the last 90 KB is submitted").option("--url <url>","Daemon URL",fa).action(async e=>{try{let o=await sd(e.transcript,"r"),t;try{let n=await o.stat();if(!n.isFile())throw new Error("Transcript must be a regular file");let s=Math.min(n.size,9e4),i=Buffer.alloc(s),{bytesRead:r}=await o.read(i,0,s,Math.max(0,n.size-s));t=(n.size>s?`[Transcript truncated: last 90 KB only]
10
- `:"")+i.subarray(0,r).toString("utf8")}finally{await o.close()}await ha(e.url,"ended",ur.parse({sessionId:e.session,runId:e.run,transcript:t})),console.log("Run queued for review.")}catch(o){console.error(o.message),process.exitCode=1}});import{Command as Of}from"commander";import{Command as id}from"commander";pe();import O from"chalk";import{existsSync as rd,readFileSync as ad}from"fs";async function cd(e){try{let{execFileSync:o}=await import("child_process"),t=o("ps",["-p",String(e),"-o","command="],{encoding:"utf-8",timeout:2e3}).trim();return t?/\bnode\b/.test(t)||/agentx|agentix|cli\.js/.test(t):!1}catch{return!0}}var Ze=new id().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");Ze.command("start").description("start the daemon (default if no subcommand)").option("-c, --config <path>","path to agentx.json").option("-d, --detach","run in background (detached)").option("--port <port>","override bind port").action(async e=>{if(e.detach){let{spawn:d}=await import("child_process"),{openSync:g,writeFileSync:l,existsSync:p}=await import("fs"),f=process.argv[1];(!f||!p(f))&&(console.error(O.red(` Cannot resolve agentx CLI entrypoint (process.argv[1]=${f||"?"}).`)),console.error(O.dim(" Try running without --detach to see the underlying error.")),process.exit(1));let u=[f,"daemon","start"];e.config&&u.push("-c",e.config),e.port&&u.push("--port",e.port);let w="/tmp/agentx-daemon.log",y;try{y=g(w,"a")}catch(b){console.error(O.red(` Failed to open ${w} for writing: ${b.message}`)),process.exit(1)}let k=d(process.execPath,u,{detached:!0,stdio:["ignore",y,y],cwd:process.cwd()});k.unref(),l("/tmp/agentx-daemon.pid",String(k.pid)),console.log(O.green(`Daemon started in background (PID: ${k.pid})`)),console.log(O.dim(` Logs: tail -f ${w}`)),console.log(O.dim(" Stop: agentx daemon stop")),await new Promise(b=>setTimeout(b,1e3));try{process.kill(k.pid,0)}catch{console.log(),console.log(O.yellow(` Daemon exited within 1s \u2014 check ${w} for the error:`)),console.log(O.dim(` tail -n 40 ${w}`))}return}let{readFileSync:o,writeFileSync:t,mkdirSync:n,existsSync:s}=await import("fs"),{resolve:i}=await import("path"),r=i(process.cwd(),".agentx");s(r)||n(r,{recursive:!0});let a=i(r,"daemon.pid");if(s(a)){let d=parseInt(o(a,"utf-8").trim(),10);if(d&&d!==process.pid){let g=!1;try{process.kill(d,0),g=!0}catch{}g&&await cd(d)&&(console.error(`Another agentx daemon is already running (PID ${d}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{ld(i(process.cwd(),".env"))}catch{}await new Is(e.config).start()});function ld(e){if(!rd(e))return;let o=ad(e,"utf-8");for(let t of o.split(`
11
- `)){let n=t.trim();if(!n||n.startsWith("#"))continue;let s=n.indexOf("=");if(s<0)continue;let i=n.slice(0,s).trim();if(!i||process.env[i]!==void 0)continue;let r=n.slice(s+1).trim();(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))&&(r=r.slice(1,-1)),process.env[i]=r}}Ze.command("stop").description("stop the running daemon").action(async()=>{let{readFileSync:e,existsSync:o,unlinkSync:t}=await import("fs"),{resolve:n}=await import("path"),s=[n(process.cwd(),".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"];for(let r of s)if(o(r))try{let a=parseInt(e(r,"utf-8").trim(),10);process.kill(a,"SIGTERM"),await new Promise(c=>setTimeout(c,2e3));try{t(r)}catch{}console.log(O.green(`Daemon stopped (PID: ${a})`));return}catch{try{t(r)}catch{}}let{execSync:i}=await import("child_process");try{i("pkill -f 'node dist/cli.js daemon'",{stdio:"ignore"}),console.log(O.green("Daemon stopped"))}catch{console.log(O.yellow("No daemon process found"))}});Ze.command("status").alias("st").description("show daemon status, agents, crons, and mesh").option("-c, --config <path>","path to agentx.json").option("--json","output as JSON").action(async e=>{try{let o=_(e.config),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}/health`,r=await(await fetch(s,{signal:AbortSignal.timeout(3e3)})).json();if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(O.bold(` ${r.node.name}`)+O.dim(` (${r.node.id})`)),console.log(O.green(" Status: running")+O.dim(` \u2014 uptime ${dd(r.uptime)}`)),console.log(),console.log(O.bold(" Agents:"));for(let c of r.agents){let d=c.active>0?O.yellow(` [${c.active} active]`):"",g=c.errors>0?O.red(` (${c.errors} errors)`):"";console.log(` ${O.cyan(c.name)} ${O.dim(`(${c.tier})`)}${d}${g}`),console.log(O.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(O.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let d=c.enabled?O.green("\u25CF"):O.dim("\u25CB"),g=c.nextRun?O.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${d} ${c.id}${g}`)}}if(r.mesh?.length){console.log(),console.log(O.bold(" Mesh:"));for(let c of r.mesh){let d=c.healthy?O.green("\u25CF"):O.red("\u25CF"),g=c.skills?.length?O.dim(` (${c.skills.length} agents)`):"";console.log(` ${d} ${c.peer} ${O.dim(c.peerUrl)}${g}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError")console.log(O.red(" Daemon is not running")),console.log(O.dim(" Start with: agentx daemon start"));else try{let t=_(e.config),n=dn(t);if(console.log(),console.log(O.bold(` ${t.node.name}`)+O.dim(` (${t.node.id})`)),console.log(O.yellow(" Status: stopped")),console.log(O.dim(` ${Object.keys(t.agents).length} agents, ${Object.keys(t.crons).length} crons configured`)),n.length){console.log();for(let s of n)console.log(O.yellow(` \u26A0 ${s}`))}console.log()}catch(t){console.log(O.red(` ${t.message}`))}}});Ze.command("logs").description("tail daemon logs").option("-n, --lines <n>","number of lines","50").option("-f, --follow","follow log output",!1).action(async e=>{let{execSync:o,spawn:t}=await import("child_process"),n="/tmp/agentx-daemon.log",{existsSync:s}=await import("fs");if(!s(n)){console.log(O.yellow("No log file found at /tmp/agentx-daemon.log"));return}if(e.follow){let i=t("tail",["-f","-n",e.lines,n],{stdio:"inherit"});process.on("SIGINT",()=>{i.kill(),process.exit(0)})}else o(`tail -n ${e.lines} ${n}`,{stdio:"inherit"})});Ze.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(_(e.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(O.dim(` Connecting to ${n}...`)),console.log(O.dim(` Press Ctrl+C to stop
12
- `));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."))}});Ze.command("send <agent> <message...>").description("send a task to an agent via the daemon API").option("-c, --config <path>","path to agentx.json").option("--peer <peer>","send to a mesh peer's agent").option("--json","output raw JSON response").action(async(e,o,t)=>{let n=o.join(" ");try{let s=_(t.config),[i,r]=s.node.bind.split(":"),a=`http://${i||"127.0.0.1"}:${r}`,c,d;t.peer?(c=`${a}/mesh/task`,d={peer:t.peer,message:n,agent:e}):(c=`${a}/task`,d={agent:e,message:n}),console.log(O.dim(` Sending to ${t.peer?`${t.peer}/${e}`:e}...`));let l=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)})).json();t.json?console.log(JSON.stringify(l,null,2)):l.error?console.log(O.red(` Error: ${l.error}`)):(console.log(),console.log(l.content||l.response||"No response"),l.duration&&console.log(O.dim(`
14
- (${(l.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(O.red(` Failed: ${s.message}`)),console.log(O.dim(" Is the daemon running? Try: agentx daemon status"))}});Ze.command("deploy <host>").description("deploy agentx to a remote server via rsync").option("-i, --identity <key>","SSH identity file").option("-u, --user <user>","SSH user","root").option("-p, --path <path>","remote agentx path","~/agentx").option("--restart","restart remote daemon after deploy",!1).option("--skip-checks","skip build and test before deploy",!1).action(async(e,o)=>{let{execSync:t}=await import("child_process"),n=o.identity?`-e "ssh -i ${o.identity}"`:"",s=`${o.user}@${e}:${o.path}/dist/`;if(!o.skipChecks){try{console.log(O.dim(" Running tests...")),t("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(O.green(" \u2713 Tests passed"))}catch{console.log(O.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(O.dim(" Use --skip-checks to deploy anyway"));return}let{existsSync:i,statSync:r}=await import("fs"),{resolve:a}=await import("path"),c=a(process.cwd(),"dist/cli.js");if(!i(c)){console.log(O.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(c).mtimeMs>3e5&&(console.log(O.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),t("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(O.green(" \u2713 Build complete")))}console.log(O.dim(` Deploying to ${o.user}@${e}:${o.path}...`));try{if(t(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(O.green(" \u2713 Deploy complete")),o.restart){console.log(O.dim(" Restarting remote daemon..."));let i=o.identity?`ssh -i ${o.identity}`:"ssh";t(`${i} ${o.user}@${e} "pkill -f 'node dist/cli.js daemon' 2>/dev/null; sleep 2; cd ${o.path} && nohup node dist/cli.js daemon start > /tmp/agentx-daemon.log 2>&1 &"`,{stdio:"inherit"}),console.log(O.green(" Remote daemon restarted"))}}catch(i){console.log(O.red(` Deploy failed: ${i.message}`))}});Ze.action(async e=>{await new Is(e.config).start()});function dd(e){return e<60?`${Math.round(e)}s`:e<3600?`${Math.round(e/60)}m`:e<86400?`${Math.round(e/3600)}h ${Math.round(e%3600/60)}m`:`${Math.round(e/86400)}d ${Math.round(e%86400/3600)}h`}import{Command as gd}from"commander";import He from"chalk";import{existsSync as Mt,readFileSync as md,writeFileSync as ya,mkdirSync as wa}from"fs";import{hostname as ba}from"os";import{resolve as rt}from"path";var $a=new gd().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=rt(o,"agentx.json"),n=rt(o,".env"),s=rt(o,".agentx/sessions");if(console.log(),console.log(He.bold(" agentx init")),console.log(),Mt(t)&&!e.force){console.log(He.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[rt(o,"agentx.example.json"),rt(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(Mt(c)){r=md(c,"utf-8");break}r||(r=JSON.stringify({node:{id:ba().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:ba(),bind:"127.0.0.1:18800"},providers:{claude:{apiKey:"${ANTHROPIC_API_KEY}"}},agents:{assistant:{name:"Assistant",workspace:o,tier:"claude-code",model:"claude-sonnet-4-6",mentions:["@assistant","assistant"],maxConcurrent:2,systemPrompt:"You are a helpful assistant.",permissionMode:"default"}},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}}},null,2)),ya(t,r),console.log(He.green(" \u2713 Created agentx.json")),Mt(n)||(ya(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
15
- `)),console.log(He.green(" \u2713 Created .env template"))),Mt(s)||(wa(s,{recursive:!0}),console.log(He.green(" \u2713 Created .agentx/sessions/")));let a=rt(o,".claude");Mt(a)||(wa(a,{recursive:!0}),console.log(He.green(" \u2713 Created .claude/"))),console.log(),console.log(He.bold(" Next steps:")),console.log(` 1. Edit ${He.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${He.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${He.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${He.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as pd}from"commander";import Do from"chalk";import{spawn as va}from"child_process";import{existsSync as ud}from"fs";import{dirname as fd,resolve as hd}from"path";import{fileURLToPath as yd}from"url";pe();var xa=new pd().name("setup").description("open the web setup wizard to create or extend your AgentX install").option("--port <n>","dashboard port (default: from agentx.json, else 4202)").option("--no-open","don't try to open the browser").action(async e=>{let o=Kr(),t=e.port?parseInt(e.port,10):wd(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(Do.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(Do.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(Do.bold(` Opening ${n}`)),console.log(),await $d(n).catch(()=>!1))console.log(Do.dim(" Dashboard is already running.")),e.open!==!1&&ka(n);else{console.log(Do.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=bd(),r=va(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&ka(n),await new Promise(a=>r.on("exit",()=>a()))}});function wd(){try{return _().dashboard.port||4202}catch{return 4202}}function bd(){let e=hd(fd(yd(import.meta.url)),"cli.js");return ud(e)?e:process.argv[1]||e}async function $d(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}function ka(e){let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=va(o,[e],{stdio:"ignore",detached:!0});t.once("error",()=>{console.log(Do.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),t.unref()}catch{console.log(Do.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as kd}from"commander";import Se from"chalk";var Ft=new kd().name("token").description("scoped API tokens for external access (mesh peers, integrations)");Ft.command("create").description("mint a new token \u2014 prints the secret once, store it somewhere safe").requiredOption("--name <name>","human-readable label (e.g. 'Slack integration')").option("--scope <scopes>","comma-separated scopes (default: dashboard:read)","dashboard:read").option("--expires <days>","expire after N days (default: no expiry)").action(e=>{try{let o=new vn,t=String(e.scope).split(",").map(r=>r.trim()).filter(Boolean),n=e.expires?parseInt(e.expires,10):void 0;if(e.expires&&(!n||n<1))throw new Error("--expires must be a positive integer (days)");let{token:s,record:i}=o.create({name:e.name,scopes:t,expiresInDays:n});console.log(),console.log(Se.bold(" Token created.")),console.log(),console.log(` id: ${Se.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||Se.dim("never")}`),console.log(),console.log(Se.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${Se.green.bold(s)}`),console.log(),console.log(Se.dim(" Use it via the Authorization header:")),console.log(Se.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(o){console.log(Se.red(` ${o.message}`)),process.exit(1)}});Ft.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new vn().list();if(e.length===0){console.log(Se.dim(`
7
+ The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{cd(r,{recursive:!0,force:!0})}});at.command("start").description("start the installed desktop assistant").action(()=>{Tn(),xa(),console.log("Desktop assistant started.")});at.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{Tn(),await va(),console.log("Desktop assistant stopped.")});at.command("status").description("show the desktop login service status").action(()=>{Tn();try{console.log(ao("launchctl",["print",Mt()],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(Ds(rt())?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as bd}from"commander";import{open as $d}from"fs/promises";import{existsSync as Cn,mkdirSync as ud,readFileSync as Nn,writeFileSync as Sa}from"fs";import{homedir as fd}from"os";import{dirname as hd,resolve as _s}from"path";var Ps="/attach/",Ea="/guard/check";function Aa(e,o,t=""){return`curl -s --max-time 3 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${o}${e}${t}`}' 2>/dev/null || true`}function In(e,o,t){let n={hooks:[{type:"command",command:Aa(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function yd(e){return{SessionStart:[In("/attach/session-start",e,"")],UserPromptSubmit:[In("/attach/prompt",e)],Stop:[In("/attach/stop",e)],SessionEnd:[In("/attach/session-end",e)]}}function wd(e){let o=Aa("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function jn(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function Lt(){return _s(fd(),".claude/settings.json")}function Ft(e=process.cwd()){for(let o of[e,_s(e,"..")]){let t=_s(o,"agentx.json");if(Cn(t))try{let n=JSON.parse(Nn(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function Oa(e,o={}){let t=o.path??Lt(),n=o.withGuard!==!1,s={};if(Cn(t))try{s=JSON.parse(Nn(t,"utf-8"))}catch(g){throw new Error(`${t} is not valid JSON (${g?.message}) \u2014 refusing to overwrite it`)}let i=JSON.stringify(s),r=s.hooks??={},a=[];for(let[g,d]of Object.entries(yd(e))){let u=Array.isArray(r[g])?r[g].filter(f=>!jn(f,Ps)):[];r[g]=[...u,...d],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(d=>!jn(d,Ea)):[];r.PreToolUse=[...g,...wd(e)],c=!0}let l=JSON.stringify(s)!==i;return l&&(ud(hd(t),{recursive:!0}),Sa(t,`${JSON.stringify(s,null,2)}
8
+ `)),{path:t,changed:l,events:a,guardInstalled:c}}function Ta(e={}){let o=e.path??Lt();if(!Cn(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(Nn(o,"utf-8"))}catch(a){throw new Error(`${o} is not valid JSON (${a?.message}) \u2014 refusing to rewrite it`)}let n=JSON.stringify(t),s=t.hooks,i=[];if(s&&typeof s=="object"){for(let a of Object.keys(s)){if(!Array.isArray(s[a]))continue;let c=a==="PreToolUse"?Ea:Ps;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let l=s[a].filter(g=>!jn(g,c));l.length!==s[a].length&&i.push(a),l.length===0?delete s[a]:s[a]=l}Object.keys(s).length===0&&delete t.hooks}let r=JSON.stringify(t)!==n;return r&&Sa(o,`${JSON.stringify(t,null,2)}
9
+ `),{path:o,changed:r,events:i,guardInstalled:!1}}function Rn(e=Lt()){if(!Cn(e))return!1;try{return!!JSON.parse(Nn(e,"utf-8"))?.hooks?.Stop?.some?.(t=>jn(t,Ps))}catch{return!1}}var Dn=new bd("monitor").description("Register external CLI sessions and report ended runs to the briefing"),Ia=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Ft()}`;async function ja(e,o,t){let n=process.env.MESH_TOKEN,s=await fetch(e.replace(/\/$/,"")+"/monitor/"+o,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify(t),signal:AbortSignal.timeout(8e3)});if(!s.ok)throw new Error(`Monitor HTTP ${s.status}: ${(await s.text()).slice(0,300)}`)}Dn.command("register").requiredOption("--session <id>","Native session ID").requiredOption("--runtime <name>","claude, codex, gemini, opencode, or another CLI").requiredOption("--label <label>","Human-readable task label").option("--url <url>","Daemon URL",Ia).action(async e=>{try{await ja(e.url,"register",Sr.parse({id:e.session,runtime:e.runtime,label:e.label})),console.log("Session registered. Report each stopped run with agentx monitor ended.")}catch(o){console.error(o.message),process.exitCode=1}});Dn.command("ended").requiredOption("--session <id>","Registered session ID").requiredOption("--run <id>","Stable unique turn ID; reuse this ID when retrying delivery").requiredOption("--transcript <file>","Local transcript file; only the last 90 KB is submitted").option("--url <url>","Daemon URL",Ia).action(async e=>{try{let o=await $d(e.transcript,"r"),t;try{let n=await o.stat();if(!n.isFile())throw new Error("Transcript must be a regular file");let s=Math.min(n.size,9e4),i=Buffer.alloc(s),{bytesRead:r}=await o.read(i,0,s,Math.max(0,n.size-s));t=(n.size>s?`[Transcript truncated: last 90 KB only]
10
+ `:"")+i.subarray(0,r).toString("utf8")}finally{await o.close()}await ja(e.url,"ended",Er.parse({sessionId:e.session,runId:e.run,transcript:t})),console.log("Run queued for review.")}catch(o){console.error(o.message),process.exitCode=1}});import{Command as Gf}from"commander";import{Command as kd}from"commander";ge();import O from"chalk";import{existsSync as vd,readFileSync as xd}from"fs";async function Sd(e){try{let{execFileSync:o}=await import("child_process"),t=o("ps",["-p",String(e),"-o","command="],{encoding:"utf-8",timeout:2e3}).trim();return t?/\bnode\b/.test(t)||/agentx|agentix|cli\.js/.test(t):!1}catch{return!0}}var eo=new kd().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");eo.command("start").description("start the daemon (default if no subcommand)").option("-c, --config <path>","path to agentx.json").option("-d, --detach","run in background (detached)").option("--port <port>","override bind port").action(async e=>{if(e.detach){let{spawn:l}=await import("child_process"),{openSync:g,writeFileSync:d,existsSync:u}=await import("fs"),f=process.argv[1];(!f||!u(f))&&(console.error(O.red(` Cannot resolve agentx CLI entrypoint (process.argv[1]=${f||"?"}).`)),console.error(O.dim(" Try running without --detach to see the underlying error.")),process.exit(1));let p=[f,"daemon","start"];e.config&&p.push("-c",e.config),e.port&&p.push("--port",e.port);let w="/tmp/agentx-daemon.log",y;try{y=g(w,"a")}catch(b){console.error(O.red(` Failed to open ${w} for writing: ${b.message}`)),process.exit(1)}let k=l(process.execPath,p,{detached:!0,stdio:["ignore",y,y],cwd:process.cwd()});k.unref(),d("/tmp/agentx-daemon.pid",String(k.pid)),console.log(O.green(`Daemon started in background (PID: ${k.pid})`)),console.log(O.dim(` Logs: tail -f ${w}`)),console.log(O.dim(" Stop: agentx daemon stop")),await new Promise(b=>setTimeout(b,1e3));try{process.kill(k.pid,0)}catch{console.log(),console.log(O.yellow(` Daemon exited within 1s \u2014 check ${w} for the error:`)),console.log(O.dim(` tail -n 40 ${w}`))}return}let{readFileSync:o,writeFileSync:t,mkdirSync:n,existsSync:s}=await import("fs"),{resolve:i}=await import("path"),r=i(process.cwd(),".agentx");s(r)||n(r,{recursive:!0});let a=i(r,"daemon.pid");if(s(a)){let l=parseInt(o(a,"utf-8").trim(),10);if(l&&l!==process.pid){let g=!1;try{process.kill(l,0),g=!0}catch{}g&&await Sd(l)&&(console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{Ed(i(process.cwd(),".env"))}catch{}await new js(e.config).start()});function Ed(e){if(!vd(e))return;let o=xd(e,"utf-8");for(let t of o.split(`
11
+ `)){let n=t.trim();if(!n||n.startsWith("#"))continue;let s=n.indexOf("=");if(s<0)continue;let i=n.slice(0,s).trim();if(!i||process.env[i]!==void 0)continue;let r=n.slice(s+1).trim();(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))&&(r=r.slice(1,-1)),process.env[i]=r}}eo.command("stop").description("stop the running daemon").action(async()=>{let{readFileSync:e,existsSync:o,unlinkSync:t}=await import("fs"),{resolve:n}=await import("path"),s=[n(process.cwd(),".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"];for(let r of s)if(o(r))try{let a=parseInt(e(r,"utf-8").trim(),10);process.kill(a,"SIGTERM"),await new Promise(c=>setTimeout(c,2e3));try{t(r)}catch{}console.log(O.green(`Daemon stopped (PID: ${a})`));return}catch{try{t(r)}catch{}}let{execSync:i}=await import("child_process");try{i("pkill -f 'node dist/cli.js daemon'",{stdio:"ignore"}),console.log(O.green("Daemon stopped"))}catch{console.log(O.yellow("No daemon process found"))}});eo.command("status").alias("st").description("show daemon status, agents, crons, and mesh").option("-c, --config <path>","path to agentx.json").option("--json","output as JSON").action(async e=>{try{let o=_(e.config),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}/health`,r=await(await fetch(s,{signal:AbortSignal.timeout(3e3)})).json();if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(O.bold(` ${r.node.name}`)+O.dim(` (${r.node.id})`)),console.log(O.green(" Status: running")+O.dim(` \u2014 uptime ${Ad(r.uptime)}`)),console.log(),console.log(O.bold(" Agents:"));for(let c of r.agents){let l=c.active>0?O.yellow(` [${c.active} active]`):"",g=c.errors>0?O.red(` (${c.errors} errors)`):"";console.log(` ${O.cyan(c.name)} ${O.dim(`(${c.tier})`)}${l}${g}`),console.log(O.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(O.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let l=c.enabled?O.green("\u25CF"):O.dim("\u25CB"),g=c.nextRun?O.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${l} ${c.id}${g}`)}}if(r.mesh?.length){console.log(),console.log(O.bold(" Mesh:"));for(let c of r.mesh){let l=c.healthy?O.green("\u25CF"):O.red("\u25CF"),g=c.skills?.length?O.dim(` (${c.skills.length} agents)`):"";console.log(` ${l} ${c.peer} ${O.dim(c.peerUrl)}${g}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError")console.log(O.red(" Daemon is not running")),console.log(O.dim(" Start with: agentx daemon start"));else try{let t=_(e.config),n=mn(t);if(console.log(),console.log(O.bold(` ${t.node.name}`)+O.dim(` (${t.node.id})`)),console.log(O.yellow(" Status: stopped")),console.log(O.dim(` ${Object.keys(t.agents).length} agents, ${Object.keys(t.crons).length} crons configured`)),n.length){console.log();for(let s of n)console.log(O.yellow(` \u26A0 ${s}`))}console.log()}catch(t){console.log(O.red(` ${t.message}`))}}});eo.command("logs").description("tail daemon logs").option("-n, --lines <n>","number of lines","50").option("-f, --follow","follow log output",!1).action(async e=>{let{execSync:o,spawn:t}=await import("child_process"),n="/tmp/agentx-daemon.log",{existsSync:s}=await import("fs");if(!s(n)){console.log(O.yellow("No log file found at /tmp/agentx-daemon.log"));return}if(e.follow){let i=t("tail",["-f","-n",e.lines,n],{stdio:"inherit"});process.on("SIGINT",()=>{i.kill(),process.exit(0)})}else o(`tail -n ${e.lines} ${n}`,{stdio:"inherit"})});eo.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(_(e.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(O.dim(` Connecting to ${n}...`)),console.log(O.dim(` Press Ctrl+C to stop
12
+ `));try{let s=await fetch(n);if(!s.ok||!s.body){console.log(O.red(` Failed: ${s.status}`));return}let i=s.body.getReader(),r=new TextDecoder,a="";for(;;){let{done:c,value:l}=await i.read();if(c)break;a+=r.decode(l,{stream:!0});let g=a.split(`
13
+ `);a=g.pop()||"";for(let d of g)if(d.startsWith("data: "))try{let u=JSON.parse(d.slice(6)),f=new Date(u.time).toLocaleTimeString(),p=u.message?.replace(/^\[agentx\]\s*/,"")||"";p.includes("executing")?console.log(`${O.dim(f)} ${O.cyan("\u25B6")} ${p}`):p.includes("completed")?console.log(`${O.dim(f)} ${O.green("\u2713")} ${p}`):p.includes("error")||p.includes("Error")?console.log(`${O.dim(f)} ${O.red("\u2717")} ${p}`):p.includes("Routing")?console.log(`${O.dim(f)} ${O.yellow("\u2192")} ${p}`):p.includes("mention")?console.log(`${O.dim(f)} ${O.magenta("@")} ${p}`):p.includes("Skipping")?console.log(`${O.dim(f)} ${O.dim("\u2298")} ${O.dim(p)}`):console.log(`${O.dim(f)} ${p}`)}catch{}else d.startsWith("event: status")}}catch(s){console.log(O.red(` Connection failed: ${s.message}`)),console.log(O.dim(" Is the daemon running? Diagnostic order:")),console.log(O.dim(" 1) agentx daemon status # is the daemon up?")),console.log(O.dim(" 2) tail -n 60 /tmp/agentx-daemon.log # detach-mode crash log")),console.log(O.dim(" 3) journalctl -u agentx -n 60 # systemd-managed installs")),console.log(O.dim(" If the log file is missing, the daemon never started \u2014 re-run without --detach")),console.log(O.dim(" to see the error in the foreground."))}});eo.command("send <agent> <message...>").description("send a task to an agent via the daemon API").option("-c, --config <path>","path to agentx.json").option("--peer <peer>","send to a mesh peer's agent").option("--json","output raw JSON response").action(async(e,o,t)=>{let n=o.join(" ");try{let s=_(t.config),[i,r]=s.node.bind.split(":"),a=`http://${i||"127.0.0.1"}:${r}`,c,l;t.peer?(c=`${a}/mesh/task`,l={peer:t.peer,message:n,agent:e}):(c=`${a}/task`,l={agent:e,message:n}),console.log(O.dim(` Sending to ${t.peer?`${t.peer}/${e}`:e}...`));let d=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();t.json?console.log(JSON.stringify(d,null,2)):d.error?console.log(O.red(` Error: ${d.error}`)):(console.log(),console.log(d.content||d.response||"No response"),d.duration&&console.log(O.dim(`
14
+ (${(d.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(O.red(` Failed: ${s.message}`)),console.log(O.dim(" Is the daemon running? Try: agentx daemon status"))}});eo.command("deploy <host>").description("deploy agentx to a remote server via rsync").option("-i, --identity <key>","SSH identity file").option("-u, --user <user>","SSH user","root").option("-p, --path <path>","remote agentx path","~/agentx").option("--restart","restart remote daemon after deploy",!1).option("--skip-checks","skip build and test before deploy",!1).action(async(e,o)=>{let{execSync:t}=await import("child_process"),n=o.identity?`-e "ssh -i ${o.identity}"`:"",s=`${o.user}@${e}:${o.path}/dist/`;if(!o.skipChecks){try{console.log(O.dim(" Running tests...")),t("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(O.green(" \u2713 Tests passed"))}catch{console.log(O.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(O.dim(" Use --skip-checks to deploy anyway"));return}let{existsSync:i,statSync:r}=await import("fs"),{resolve:a}=await import("path"),c=a(process.cwd(),"dist/cli.js");if(!i(c)){console.log(O.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(c).mtimeMs>3e5&&(console.log(O.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),t("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(O.green(" \u2713 Build complete")))}console.log(O.dim(` Deploying to ${o.user}@${e}:${o.path}...`));try{if(t(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(O.green(" \u2713 Deploy complete")),o.restart){console.log(O.dim(" Restarting remote daemon..."));let i=o.identity?`ssh -i ${o.identity}`:"ssh";t(`${i} ${o.user}@${e} "pkill -f 'node dist/cli.js daemon' 2>/dev/null; sleep 2; cd ${o.path} && nohup node dist/cli.js daemon start > /tmp/agentx-daemon.log 2>&1 &"`,{stdio:"inherit"}),console.log(O.green(" Remote daemon restarted"))}}catch(i){console.log(O.red(` Deploy failed: ${i.message}`))}});eo.action(async e=>{await new js(e.config).start()});function Ad(e){return e<60?`${Math.round(e)}s`:e<3600?`${Math.round(e/60)}m`:e<86400?`${Math.round(e/3600)}h ${Math.round(e%3600/60)}m`:`${Math.round(e/86400)}d ${Math.round(e%86400/3600)}h`}import{Command as Od}from"commander";import He from"chalk";import{existsSync as Ut,readFileSync as Td,writeFileSync as Ca,mkdirSync as Na}from"fs";import{hostname as Ra}from"os";import{resolve as ct}from"path";var Da=new Od().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=ct(o,"agentx.json"),n=ct(o,".env"),s=ct(o,".agentx/sessions");if(console.log(),console.log(He.bold(" agentx init")),console.log(),Ut(t)&&!e.force){console.log(He.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[ct(o,"agentx.example.json"),ct(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(Ut(c)){r=Td(c,"utf-8");break}r||(r=JSON.stringify({node:{id:Ra().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:Ra(),bind:"127.0.0.1:18800"},providers:{claude:{apiKey:"${ANTHROPIC_API_KEY}"}},agents:{assistant:{name:"Assistant",workspace:o,tier:"claude-code",model:"claude-sonnet-4-6",mentions:["@assistant","assistant"],maxConcurrent:2,systemPrompt:"You are a helpful assistant.",permissionMode:"default"}},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}}},null,2)),Ca(t,r),console.log(He.green(" \u2713 Created agentx.json")),Ut(n)||(Ca(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
15
+ `)),console.log(He.green(" \u2713 Created .env template"))),Ut(s)||(Na(s,{recursive:!0}),console.log(He.green(" \u2713 Created .agentx/sessions/")));let a=ct(o,".claude");Ut(a)||(Na(a,{recursive:!0}),console.log(He.green(" \u2713 Created .claude/"))),console.log(),console.log(He.bold(" Next steps:")),console.log(` 1. Edit ${He.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${He.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${He.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${He.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as Id}from"commander";import _o from"chalk";import{spawn as Pa}from"child_process";import{existsSync as jd}from"fs";import{dirname as Cd,resolve as Nd}from"path";import{fileURLToPath as Rd}from"url";ge();var Ma=new Id().name("setup").description("open the web setup wizard to create or extend your AgentX install").option("--port <n>","dashboard port (default: from agentx.json, else 4202)").option("--no-open","don't try to open the browser").action(async e=>{let o=la(),t=e.port?parseInt(e.port,10):Dd(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(_o.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(_o.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(_o.bold(` Opening ${n}`)),console.log(),await Pd(n).catch(()=>!1))console.log(_o.dim(" Dashboard is already running.")),e.open!==!1&&_a(n);else{console.log(_o.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=_d(),r=Pa(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&_a(n),await new Promise(a=>r.on("exit",()=>a()))}});function Dd(){try{return _().dashboard.port||4202}catch{return 4202}}function _d(){let e=Nd(Cd(Rd(import.meta.url)),"cli.js");return jd(e)?e:process.argv[1]||e}async function Pd(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}function _a(e){let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=Pa(o,[e],{stdio:"ignore",detached:!0});t.once("error",()=>{console.log(_o.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),t.unref()}catch{console.log(_o.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as Md}from"commander";import Ee from"chalk";var qt=new Md().name("token").description("scoped API tokens for external access (mesh peers, integrations)");qt.command("create").description("mint a new token \u2014 prints the secret once, store it somewhere safe").requiredOption("--name <name>","human-readable label (e.g. 'Slack integration')").option("--scope <scopes>","comma-separated scopes (default: dashboard:read)","dashboard:read").option("--expires <days>","expire after N days (default: no expiry)").action(e=>{try{let o=new En,t=String(e.scope).split(",").map(r=>r.trim()).filter(Boolean),n=e.expires?parseInt(e.expires,10):void 0;if(e.expires&&(!n||n<1))throw new Error("--expires must be a positive integer (days)");let{token:s,record:i}=o.create({name:e.name,scopes:t,expiresInDays:n});console.log(),console.log(Ee.bold(" Token created.")),console.log(),console.log(` id: ${Ee.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||Ee.dim("never")}`),console.log(),console.log(Ee.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${Ee.green.bold(s)}`),console.log(),console.log(Ee.dim(" Use it via the Authorization header:")),console.log(Ee.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(o){console.log(Ee.red(` ${o.message}`)),process.exit(1)}});qt.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new En().list();if(e.length===0){console.log(Ee.dim(`
16
16
  No tokens issued.
17
- `));return}console.log();for(let o of e){let t=o.revokedAt?Se.red("revoked"):o.expiresAt&&Date.parse(o.expiresAt)<Date.now()?Se.red("expired"):Se.green("active");console.log(` ${Se.cyan(o.id)} ${t} ${o.name}`),console.log(Se.dim(` prefix: ${o.prefix}\u2026 scopes: ${o.scopes.join(", ")}`)),console.log(Se.dim(` created: ${o.createdAt}${o.expiresAt?` expires: ${o.expiresAt}`:""}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(Se.red(` ${e.message}`)),process.exit(1)}});Ft.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new vn().revoke(e);o||(console.log(Se.red(` Token ${e} not found.`)),process.exit(1)),console.log(Se.green(`
17
+ `));return}console.log();for(let o of e){let t=o.revokedAt?Ee.red("revoked"):o.expiresAt&&Date.parse(o.expiresAt)<Date.now()?Ee.red("expired"):Ee.green("active");console.log(` ${Ee.cyan(o.id)} ${t} ${o.name}`),console.log(Ee.dim(` prefix: ${o.prefix}\u2026 scopes: ${o.scopes.join(", ")}`)),console.log(Ee.dim(` created: ${o.createdAt}${o.expiresAt?` expires: ${o.expiresAt}`:""}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(Ee.red(` ${e.message}`)),process.exit(1)}});qt.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new En().revoke(e);o||(console.log(Ee.red(` Token ${e} not found.`)),process.exit(1)),console.log(Ee.green(`
18
18
  \u2713 Revoked ${e} (${o.name})
19
- `))}catch(o){console.log(Se.red(` ${o.message}`)),process.exit(1)}});pe();import{Command as oo}from"commander";import h from"chalk";import Te from"prompts";import{readFileSync as wo,writeFileSync as at,existsSync as ge,mkdirSync as eo,cpSync as _s,readdirSync as Ls}from"fs";import{resolve as J,join as yo,dirname as vd}from"path";import{fileURLToPath as xd}from"url";function ne(){let e=J(process.cwd(),"agentx.json");if(!ge(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(wo(e,"utf-8"))}function _e(e){return de(o=>{for(let t of Object.keys(o))delete o[t];Object.assign(o,e)}).then(o=>{if(!o.success){console.error(h.red(` Config save failed: ${o.error}`));return}o.reloaded?console.error(h.dim(" (daemon hot-reloaded)")):o.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(o.reloadSkipped)&&console.error(h.dim(` (daemon reload skipped: ${o.reloadSkipped})`))})}var _o=new oo().name("agent").description("manage agents \u2014 add, list, remove");_o.command("list").alias("ls").description("list configured agents").action(()=>{let e=ne();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=t.mentions?.join(", ")||"";console.log(` ${h.cyan(o)} \u2014 ${t.name} (${t.tier})`),console.log(h.dim(` workspace: ${t.workspace}`)),n&&console.log(h.dim(` mentions: ${n}`))}console.log()});_o.command("add").description("add a new agent interactively").action(async()=>{let e=ne(),o=await Te([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:d=>/^[a-z0-9-]+$/.test(d)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:J(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!o.id)return;let t=o.workspace.endsWith(o.id)?o.workspace:yo(o.workspace,o.id);eo(J(t,".claude/skills"),{recursive:!0});let n={name:o.name,workspace:t,tier:o.tier,model:o.model,mentions:o.mentions?.map(d=>d.trim()).filter(Boolean)||[],maxConcurrent:o.maxConcurrent,systemPrompt:o.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-G6KGWPHY.js"),i=s(o.id,n,"19900",(...d)=>{console.log(h.dim(` ${d.join(" ")}`))}),r=J(process.cwd(),"src/wiki/SKILL.md"),a=J(vd(xd(import.meta.url)),"../wiki/SKILL.md"),c=ge(r)?r:a;ge(c)&&(eo(J(t,".claude/skills/wiki"),{recursive:!0}),_s(c,J(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await _e(e),console.log(h.green(`
20
- Agent "${o.id}" added`)),console.log(h.dim(` Workspace: ${t}`)),console.log(h.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});_o.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=ne();if(!o.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete o.agents[e],await _e(o),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});_o.command("capability <id>").alias("caps").description("set agent capability flags (intents, maxDelegationDepth, contextReferences, contextStrategy)").option("--intents <csv>","comma-separated intent allow-list (set to '-' to clear)").option("--max-delegation-depth <n>","max distinct upstream agents on the same subject before refusal (0 disables)").option("--context-references <bool>","render the deterministic [Verified References] block (true|false)").option("--context-strategy <name>","per-agent override: layered | planner").option("--max-execution-minutes <n>","wall-clock cap on a single Claude Code call (1\u2013240)").option("--show","just print the current capability fields").action(async(e,o)=>{let t=ne(),n=t.agents?.[e];if(n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1)),o.show){console.log(),console.log(h.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):h.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":h.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||h.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(o.intents!==void 0&&(o.intents==="-"||o.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(o.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),o.maxDelegationDepth!==void 0){let i=parseInt(o.maxDelegationDepth,10);(!Number.isFinite(i)||i<0||i>50)&&(console.log(h.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=i,s.push(`maxDelegationDepth=${i}`)}if(o.contextReferences!==void 0){let i=String(o.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(i)||(console.log(h.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=i==="true"||i==="on"||i==="1",s.push(`contextReferences=${n.contextReferences}`)}if(o.contextStrategy!==void 0&&(o.contextStrategy==="-"||o.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(o.contextStrategy)?(n.contextStrategy=o.contextStrategy,s.push(`contextStrategy=${o.contextStrategy}`)):(console.log(h.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),o.maxExecutionMinutes!==void 0){let i=parseInt(o.maxExecutionMinutes,10);(!Number.isFinite(i)||i<1||i>240)&&(console.log(h.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(h.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await _e(t),console.log(h.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(h.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var Ut=new oo().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");Ut.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=ne().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(o.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(h.dim(`
19
+ `))}catch(o){console.log(Ee.red(` ${o.message}`)),process.exit(1)}});ge();import{Command as to}from"commander";import h from"chalk";import Ie from"prompts";import{readFileSync as bo,writeFileSync as lt,existsSync as me,mkdirSync as oo,cpSync as Ms,readdirSync as Fs}from"fs";import{resolve as G,join as wo,dirname as Ld}from"path";import{fileURLToPath as Fd}from"url";function se(){let e=G(process.cwd(),"agentx.json");if(!me(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(bo(e,"utf-8"))}function Pe(e){return ue(o=>{for(let t of Object.keys(o))delete o[t];Object.assign(o,e)}).then(o=>{if(!o.success){console.error(h.red(` Config save failed: ${o.error}`));return}o.reloaded?console.error(h.dim(" (daemon hot-reloaded)")):o.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(o.reloadSkipped)&&console.error(h.dim(` (daemon reload skipped: ${o.reloadSkipped})`))})}var Po=new to().name("agent").description("manage agents \u2014 add, list, remove");Po.command("list").alias("ls").description("list configured agents").action(()=>{let e=se();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=t.mentions?.join(", ")||"";console.log(` ${h.cyan(o)} \u2014 ${t.name} (${t.tier})`),console.log(h.dim(` workspace: ${t.workspace}`)),n&&console.log(h.dim(` mentions: ${n}`))}console.log()});Po.command("add").description("add a new agent interactively").action(async()=>{let e=se(),o=await Ie([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:l=>/^[a-z0-9-]+$/.test(l)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:G(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!o.id)return;let t=o.workspace.endsWith(o.id)?o.workspace:wo(o.workspace,o.id);oo(G(t,".claude/skills"),{recursive:!0});let n={name:o.name,workspace:t,tier:o.tier,model:o.model,mentions:o.mentions?.map(l=>l.trim()).filter(Boolean)||[],maxConcurrent:o.maxConcurrent,systemPrompt:o.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-G6KGWPHY.js"),i=s(o.id,n,"19900",(...l)=>{console.log(h.dim(` ${l.join(" ")}`))}),r=G(process.cwd(),"src/wiki/SKILL.md"),a=G(Ld(Fd(import.meta.url)),"../wiki/SKILL.md"),c=me(r)?r:a;me(c)&&(oo(G(t,".claude/skills/wiki"),{recursive:!0}),Ms(c,G(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await Pe(e),console.log(h.green(`
20
+ Agent "${o.id}" added`)),console.log(h.dim(` Workspace: ${t}`)),console.log(h.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});Po.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=se();if(!o.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete o.agents[e],await Pe(o),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});Po.command("capability <id>").alias("caps").description("set agent capability flags (intents, maxDelegationDepth, contextReferences, contextStrategy)").option("--intents <csv>","comma-separated intent allow-list (set to '-' to clear)").option("--max-delegation-depth <n>","max distinct upstream agents on the same subject before refusal (0 disables)").option("--context-references <bool>","render the deterministic [Verified References] block (true|false)").option("--context-strategy <name>","per-agent override: layered | planner").option("--max-execution-minutes <n>","wall-clock cap on a single Claude Code call (1\u2013240)").option("--show","just print the current capability fields").action(async(e,o)=>{let t=se(),n=t.agents?.[e];if(n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1)),o.show){console.log(),console.log(h.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):h.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":h.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||h.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(o.intents!==void 0&&(o.intents==="-"||o.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(o.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),o.maxDelegationDepth!==void 0){let i=parseInt(o.maxDelegationDepth,10);(!Number.isFinite(i)||i<0||i>50)&&(console.log(h.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=i,s.push(`maxDelegationDepth=${i}`)}if(o.contextReferences!==void 0){let i=String(o.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(i)||(console.log(h.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=i==="true"||i==="on"||i==="1",s.push(`contextReferences=${n.contextReferences}`)}if(o.contextStrategy!==void 0&&(o.contextStrategy==="-"||o.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(o.contextStrategy)?(n.contextStrategy=o.contextStrategy,s.push(`contextStrategy=${o.contextStrategy}`)):(console.log(h.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),o.maxExecutionMinutes!==void 0){let i=parseInt(o.maxExecutionMinutes,10);(!Number.isFinite(i)||i<1||i>240)&&(console.log(h.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(h.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await Pe(t),console.log(h.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(h.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var Wt=new to().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");Wt.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=se().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(o.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(h.dim(`
21
21
  ${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
22
- `));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,l]of Object.entries(c))typeof l=="string"&&/^[A-Z][A-Z0-9_]*$/.test(l)?a.push(process.env[l]?h.green(`${g}:${l}=set`):h.yellow(`${g}:${l}=UNSET`)):g==="auth"&&l==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof l=="string"&&a.push(h.dim(`sessionDir:${l}`));let d=Object.entries(i.metadata??{}).map(([g,l])=>`${g}=${l}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),d&&console.log(` ${h.dim(d)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});Ut.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=ne();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-SRTXHGSK.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Te({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Te({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),d=String(o.sessionDir||"").trim();if(!a&&!c&&!d&&n){let p=await Te({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});p.scheme==="tokenEnv"?a=((await Te({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():p.scheme==="keyring"?c="keyring":p.scheme==="sessionDir"&&(d=((await Te({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let p of String(o.metadata).split(",")){let[f,...u]=p.split("=");f&&(g[f.trim()]=u.join("=").trim())}else if(n){let p=await Te({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(p.metadata)for(let f of String(p.metadata).split(",")){let[u,...w]=f.split("=");u&&(g[u.trim()]=w.join("=").trim())}}let l={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),l.tokenEnv=a),c==="keyring"&&(l.auth="keyring"),d&&(l.sessionDir=d),Object.keys(l).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(p=>p.kind===i&&p.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:l,metadata:g,enabled:!0}),await _e(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Ut.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=ne(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(d=>d.kind===i&&(!r||d.label===r)||d.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await _e(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Ut.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=ne().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},d=[];for(let[g,l]of Object.entries(c))typeof l=="string"&&/^[A-Z][A-Z0-9_]*$/.test(l)&&!process.env[l]&&d.push(`${g}: env var ${l} is unset`);if(d.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of d)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});_o.addCommand(Ut);var Nn=new oo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Nn.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ne();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});Nn.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ne(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Te({type:"select",name:"channelType",message:"Channel type",choices:[{title:"Telegram \u2014 bot via BotFather token",value:"telegram"},{title:"WhatsApp \u2014 link via QR code (self-chat or contacts)",value:"whatsapp"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await Te([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await _e(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Te([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:t},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let i=[],r=s.addRoute;for(;r;){let a=await Te([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await _e(e),eo(J(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Te([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let i=[],r=s.addRoute;for(;r;){let a=await Te([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await _e(e),console.log(h.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(h.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(h.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(h.dim(` Secret token: ${s.webhookSecret}`)),console.log(h.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(h.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var ct=new oo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");ct.command("list").alias("ls").description("list cron jobs").action(()=>{let e=ne();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});ct.command("add").description("add a cron job").action(async()=>{let e=ne(),o=Object.keys(e.agents||{}),t=await Te([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:o.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!t.id||!t.schedule||(e.crons=e.crons||{},e.crons[t.id]={enabled:t.enabled,schedule:t.schedule,timezone:t.timezone,agent:t.agent,prompt:t.prompt,timeout:t.timeout,onError:["log"]},await _e(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});ct.command("enable <id>").description("enable a cron job").action(async e=>{let o=ne();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!0,await _e(o),console.log(h.green(` Cron "${e}" enabled`))});ct.command("disable <id>").description("disable a cron job").action(async e=>{let o=ne();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await _e(o),console.log(h.green(` Cron "${e}" disabled`))});var lt=new oo().name("mesh").description("manage mesh peers \u2014 add, list, remove");lt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=ne();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});lt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=ne(),o=await Te([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(h.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:o.url,name:o.name,...o.token?{token:o.token}:{}}),await _e(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});lt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=ne();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await _e(o),console.log(h.green(` Peer "${e}" removed`)))});lt.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let o=ne();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await _e(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});var Po=new oo().name("skill").description("manage skills \u2014 add to agent(s), list");Po.command("add <skillPath>").description("add a skill to agent(s)").option("-a, --agent <agents...>","target agent ID(s)").option("--all","add to all agents").action(async(e,o)=>{let t=ne(),n=J(e);if(!ge(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=ge(yo(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(o.all)i=Object.keys(t.agents||{});else if(o.agent)i=o.agent;else{let r=Object.keys(t.agents||{});i=(await Te({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=J(a.workspace,".claude/skills",s);eo(c,{recursive:!0}),ge(yo(n,"SKILL.md"))?_s(n,c,{recursive:!0}):n.endsWith(".md")&&_s(n,yo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Po.command("list").alias("ls").description("list skills per agent").action(()=>{let e=ne();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=J(t.workspace,".claude/skills"),s=ge(n)?Ls(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});Po.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[J(n,"src",e,"SKILL.md"),J(n,"skills",e,"SKILL.md")],i=s.find(k=>ge(k));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(h.dim(` ${k}`));return}let r=wo(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),d;try{d=_()}catch(k){console.log(h.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(d.agents||{}),l=o.agent?g.filter(([k])=>k===o.agent):g;if(l.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let p=0,f=0,u=0,w=0;for(let[k,b]of l){let x=b.workspace;if(!x||!ge(x)){console.log(` ${h.yellow("\u2717")} ${k.padEnd(22)} ${h.dim("(workspace missing: "+(x||"undefined")+")")}`),w++;continue}let A=J(x,".claude/skills",e),S=J(A,"SKILL.md");if(!ge(S)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${k.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}o.dryRun||(eo(A,{recursive:!0}),at(S,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),p++;continue}let v=wo(S,"utf-8");if(t("sha256").update(v).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${k.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),u++;continue}let C=(v.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||at(S,r),console.log(` ${h.yellow("\u21BB")} ${k.padEnd(22)} ${h.dim(`v${C} \u2192 v${c}`)}`),f++}console.log();let y=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${y} seed ${p}, ${y} update ${f}, ${u} already current, ${w} skipped.`)),o.dryRun&&(p>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Po.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:o}=await import("./loader-BOKE5M5S.js"),{auditAll:t}=await import("./audit-4245CX6P.js"),{loadReferences:n}=await import("./loader-4ZGTK7LD.js"),{loadRecipes:s}=await import("./recipes-7S4MC5OJ.js"),i=[];if(e.workspace){let f=ne().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(J(f.workspace))}else if(e.allWorkspaces){let p=ne();for(let f of Object.values(p.agents||{}))f?.workspace&&i.push(J(f.workspace))}else i.push(J(e.cwd));let r=J(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(p=>o(p)))).flat(),[d,g]=await Promise.all([n(r),s(r)]),l=t({skills:c,references:d,recipes:g});if(e.json)console.log(JSON.stringify(l.map(p=>({name:p.name,verdict:p.verdict,reasons:p.reasons,path:p.skill?.path})),null,2));else{let p={PASS:0,REVIEW:0,FAILING:0};for(let f of l)p[f.verdict]++;console.log();for(let f of l){let u=f.verdict==="PASS"?h.green("PASS "):f.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${u} ${h.bold(f.name)}${f.skill?.path?h.dim(` (${f.skill.path})`):""}`);for(let w of f.reasons)console.log(` ${h.dim("\xB7")} ${w}`)}console.log(),console.log(` ${h.green(`${p.PASS} PASS`)} ${h.yellow(`${p.REVIEW} REVIEW`)} ${h.red(`${p.FAILING} FAILING`)}`),console.log()}process.exit(l.some(p=>p.verdict==="FAILING")?1:0)});Po.command("suggest").description("rank an agent's skills against a task (suggests, never loads)").argument("<task>","the task, in the words it arrived in").option("--agent <id>","whose skills to rank").option("--min <p>","minimum P(any skill applies)","0.6").option("--json","emit the ranking as JSON").action(async(e,o)=>{let t=ne(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-BOKE5M5S.js"),{pickSkillForTask:a}=await import("./select-L4VIYSFJ.js"),c=await r(i.workspace);if(c.length===0){console.log(h.yellow(` ${s} has no skills`));return}let d=await a(c,e,{agent:s,minRelevant:Number(o.min)||.6});if(o.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:d.skill?.frontmatter.name??null,anyRelevant:d.anyRelevant,confidence:d.confidence,judged:d.judged,reason:d.reason,shortlist:d.shortlist},null,2));return}if(console.log(),d.skill?(console.log(` ${h.green("\u2192")} ${h.bold(d.skill.frontmatter.name)} ${h.dim(`\xB7 ${d.reason}`)}`),console.log(` ${h.dim(d.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${h.yellow("\xB7")} no skill for this ${h.dim(`\u2014 ${d.reason}`)}`),d.shortlist.length>1){console.log(h.dim(`
23
- 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 qt=new oo().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");qt.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=J(o.cwd),n=J(t,"references/example"),s=J(t,"references/recipes/example.yaml");ge(n)||(console.log(h.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=J(t,".agentx/references",e),r=J(t,".agentx/references/recipes");eo(i,{recursive:!0}),eo(r,{recursive:!0});let a=Ls(n).filter(l=>l.endsWith(".yaml")||l.endsWith(".yml")),c=0,d=0;for(let l of a){let p=yo(i,l);if(ge(p)&&!o.force){console.log(h.dim(` skip ${p} (exists; --force to overwrite)`)),d++;continue}let u=wo(yo(n,l),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);at(p,u),console.log(h.green(` + ${p}`)),c++}let g=yo(r,`${e}.yaml`);if(ge(g)&&!o.force)console.log(h.dim(` skip ${g} (exists; --force to overwrite)`)),d++;else if(ge(s)){let l=wo(s,"utf-8").replaceAll("example.",`${e}.`);at(g,l),console.log(h.green(` + ${g}`)),c++}console.log(),console.log(h.dim(` ${c} written, ${d} skipped. Edit the placeholders, then:`)),console.log(h.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(h.dim(" 2. agentx skill audit # verify references resolve")),console.log(h.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});qt.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.example.com)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-BOKE5M5S.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-D4VVRNAI.js"),i=J(o.cwd),r=o.from?String(o.from).split(",").map(w=>w.trim()).filter(Boolean):[e],a=await t(i),c=n(a,{namespace:e,filter:r,gitlabHost:o.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(h.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(h.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(h.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let d=Object.fromEntries(Object.entries(c.byKind).map(([w,y])=>[w,y.length]));console.log(` Discovered: ssh=${d.ssh} gitlab=${d.gitlab} paths=${d.path} contacts=${d.contact}`);let g=s(c,e),l=J(o.referencesCwd||o.cwd),p=J(l,".agentx/references",e);if(!o.write){console.log(),console.log(h.dim(` Dry-run \u2014 would write to ${p}/`));for(let[w,y]of Object.entries(g))console.log(h.cyan(`
22
+ `));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?h.green(`${g}:${d}=set`):h.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(h.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${h.dim(l)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});Wt.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=se();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-5V444ZFW.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Ie({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Ie({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),l=String(o.sessionDir||"").trim();if(!a&&!c&&!l&&n){let u=await Ie({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});u.scheme==="tokenEnv"?a=((await Ie({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():u.scheme==="keyring"?c="keyring":u.scheme==="sessionDir"&&(l=((await Ie({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let u of String(o.metadata).split(",")){let[f,...p]=u.split("=");f&&(g[f.trim()]=p.join("=").trim())}else if(n){let u=await Ie({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(u.metadata)for(let f of String(u.metadata).split(",")){let[p,...w]=f.split("=");p&&(g[p.trim()]=w.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(u=>u.kind===i&&u.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:d,metadata:g,enabled:!0}),await Pe(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Wt.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=se(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(l=>l.kind===i&&(!r||l.label===r)||l.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await Pe(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Wt.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=se().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});Po.addCommand(Wt);var _n=new to().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");_n.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=se();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});_n.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=se(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Ie({type:"select",name:"channelType",message:"Channel type",choices:[{title:"Telegram \u2014 bot via BotFather token",value:"telegram"},{title:"WhatsApp \u2014 link via QR code (self-chat or contacts)",value:"whatsapp"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await Ie([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await Pe(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Ie([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:t},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let i=[],r=s.addRoute;for(;r;){let a=await Ie([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await Pe(e),oo(G(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Ie([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let i=[],r=s.addRoute;for(;r;){let a=await Ie([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await Pe(e),console.log(h.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(h.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(h.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(h.dim(` Secret token: ${s.webhookSecret}`)),console.log(h.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(h.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var dt=new to().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");dt.command("list").alias("ls").description("list cron jobs").action(()=>{let e=se();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});dt.command("add").description("add a cron job").action(async()=>{let e=se(),o=Object.keys(e.agents||{}),t=await Ie([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:o.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!t.id||!t.schedule||(e.crons=e.crons||{},e.crons[t.id]={enabled:t.enabled,schedule:t.schedule,timezone:t.timezone,agent:t.agent,prompt:t.prompt,timeout:t.timeout,onError:["log"]},await Pe(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});dt.command("enable <id>").description("enable a cron job").action(async e=>{let o=se();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}if(o.crons[e].approval?.action==="create"){console.log(h.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}o.crons[e].enabled=!0,await Pe(o),console.log(h.green(` Cron "${e}" enabled`))});dt.command("disable <id>").description("disable a cron job").action(async e=>{let o=se();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Pe(o),console.log(h.green(` Cron "${e}" disabled`))});var gt=new to().name("mesh").description("manage mesh peers \u2014 add, list, remove");gt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=se();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});gt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=se(),o=await Ie([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(h.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:o.url,name:o.name,...o.token?{token:o.token}:{}}),await Pe(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});gt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=se();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Pe(o),console.log(h.green(` Peer "${e}" removed`)))});gt.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let o=se();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await Pe(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});var Mo=new to().name("skill").description("manage skills \u2014 add to agent(s), list");Mo.command("add <skillPath>").description("add a skill to agent(s)").option("-a, --agent <agents...>","target agent ID(s)").option("--all","add to all agents").action(async(e,o)=>{let t=se(),n=G(e);if(!me(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=me(wo(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(o.all)i=Object.keys(t.agents||{});else if(o.agent)i=o.agent;else{let r=Object.keys(t.agents||{});i=(await Ie({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=G(a.workspace,".claude/skills",s);oo(c,{recursive:!0}),me(wo(n,"SKILL.md"))?Ms(n,c,{recursive:!0}):n.endsWith(".md")&&Ms(n,wo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Mo.command("list").alias("ls").description("list skills per agent").action(()=>{let e=se();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=G(t.workspace,".claude/skills"),s=me(n)?Fs(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});Mo.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[G(n,"src",e,"SKILL.md"),G(n,"skills",e,"SKILL.md")],i=s.find(k=>me(k));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(h.dim(` ${k}`));return}let r=bo(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=_()}catch(k){console.log(h.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([k])=>k===o.agent):g;if(d.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,f=0,p=0,w=0;for(let[k,b]of d){let S=b.workspace;if(!S||!me(S)){console.log(` ${h.yellow("\u2717")} ${k.padEnd(22)} ${h.dim("(workspace missing: "+(S||"undefined")+")")}`),w++;continue}let A=G(S,".claude/skills",e),x=G(A,"SKILL.md");if(!me(x)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${k.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}o.dryRun||(oo(A,{recursive:!0}),lt(x,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let v=bo(x,"utf-8");if(t("sha256").update(v).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${k.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),p++;continue}let C=(v.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||lt(x,r),console.log(` ${h.yellow("\u21BB")} ${k.padEnd(22)} ${h.dim(`v${C} \u2192 v${c}`)}`),f++}console.log();let y=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${y} seed ${u}, ${y} update ${f}, ${p} already current, ${w} skipped.`)),o.dryRun&&(u>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Mo.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:o}=await import("./loader-BOKE5M5S.js"),{auditAll:t}=await import("./audit-4245CX6P.js"),{loadReferences:n}=await import("./loader-4ZGTK7LD.js"),{loadRecipes:s}=await import("./recipes-7S4MC5OJ.js"),i=[];if(e.workspace){let f=se().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(G(f.workspace))}else if(e.allWorkspaces){let u=se();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(G(f.workspace))}else i.push(G(e.cwd));let r=G(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>o(u)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=t({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(u=>({name:u.name,verdict:u.verdict,reasons:u.reasons,path:u.skill?.path})),null,2));else{let u={PASS:0,REVIEW:0,FAILING:0};for(let f of d)u[f.verdict]++;console.log();for(let f of d){let p=f.verdict==="PASS"?h.green("PASS "):f.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${p} ${h.bold(f.name)}${f.skill?.path?h.dim(` (${f.skill.path})`):""}`);for(let w of f.reasons)console.log(` ${h.dim("\xB7")} ${w}`)}console.log(),console.log(` ${h.green(`${u.PASS} PASS`)} ${h.yellow(`${u.REVIEW} REVIEW`)} ${h.red(`${u.FAILING} FAILING`)}`),console.log()}process.exit(d.some(u=>u.verdict==="FAILING")?1:0)});Mo.command("suggest").description("rank an agent's skills against a task (suggests, never loads)").argument("<task>","the task, in the words it arrived in").option("--agent <id>","whose skills to rank").option("--min <p>","minimum P(any skill applies)","0.6").option("--json","emit the ranking as JSON").action(async(e,o)=>{let t=se(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-BOKE5M5S.js"),{pickSkillForTask:a}=await import("./select-KPQWIC22.js"),c=await r(i.workspace);if(c.length===0){console.log(h.yellow(` ${s} has no skills`));return}let l=await a(c,e,{agent:s,minRelevant:Number(o.min)||.6});if(o.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:l.skill?.frontmatter.name??null,anyRelevant:l.anyRelevant,confidence:l.confidence,judged:l.judged,reason:l.reason,shortlist:l.shortlist},null,2));return}if(console.log(),l.skill?(console.log(` ${h.green("\u2192")} ${h.bold(l.skill.frontmatter.name)} ${h.dim(`\xB7 ${l.reason}`)}`),console.log(` ${h.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${h.yellow("\xB7")} no skill for this ${h.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(h.dim(`
23
+ shortlist (lexical -> judged)`));for(let g of l.shortlist.slice(0,6)){let d=g.p===void 0?" - ":g.p.toFixed(2);console.log(h.dim(` ${g.lexical.toFixed(2)} -> ${d} ${g.name}`))}}l.judged||console.log(h.dim(`
24
+ (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var Bt=new to().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Bt.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=G(o.cwd),n=G(t,"references/example"),s=G(t,"references/recipes/example.yaml");me(n)||(console.log(h.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=G(t,".agentx/references",e),r=G(t,".agentx/references/recipes");oo(i,{recursive:!0}),oo(r,{recursive:!0});let a=Fs(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let u=wo(i,d);if(me(u)&&!o.force){console.log(h.dim(` skip ${u} (exists; --force to overwrite)`)),l++;continue}let p=bo(wo(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);lt(u,p),console.log(h.green(` + ${u}`)),c++}let g=wo(r,`${e}.yaml`);if(me(g)&&!o.force)console.log(h.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(me(s)){let d=bo(s,"utf-8").replaceAll("example.",`${e}.`);lt(g,d),console.log(h.green(` + ${g}`)),c++}console.log(),console.log(h.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log(h.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(h.dim(" 2. agentx skill audit # verify references resolve")),console.log(h.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});Bt.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.example.com)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-BOKE5M5S.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-D4VVRNAI.js"),i=G(o.cwd),r=o.from?String(o.from).split(",").map(w=>w.trim()).filter(Boolean):[e],a=await t(i),c=n(a,{namespace:e,filter:r,gitlabHost:o.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(h.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(h.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(h.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([w,y])=>[w,y.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let g=s(c,e),d=G(o.referencesCwd||o.cwd),u=G(d,".agentx/references",e);if(!o.write){console.log(),console.log(h.dim(` Dry-run \u2014 would write to ${u}/`));for(let[w,y]of Object.entries(g))console.log(h.cyan(`
25
25
  --- ${w} ---`)),console.log(y.split(`
26
26
  `).slice(0,30).map(k=>` ${k}`).join(`
27
27
  `)),y.split(`
28
28
  `).length>30&&console.log(h.dim(` \u2026 (${y.split(`
29
- `).length-30} more lines truncated in preview)`));console.log(),console.log(h.dim(` Re-run with --write to commit these to ${p}/`)),console.log();return}eo(p,{recursive:!0});let f=0,u=0;for(let[w,y]of Object.entries(g)){let k=yo(p,w);if(ge(k)&&!o.force){console.log(h.dim(` skip ${k} (exists; --force to overwrite)`)),u++;continue}at(k,y),console.log(h.green(` + ${k}`)),f++}console.log(),console.log(h.dim(` ${f} written, ${u} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(h.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});qt.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:o}=await import("./loader-4ZGTK7LD.js"),t=await o(J(e.cwd)),n=[...t.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(h.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=t.sourceById.get(s.id);console.log(` ${h.cyan(s.id)} ${h.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(h.dim(` ${i}`))}console.log(),console.log(h.dim(` ${n.length} reference(s) loaded.`)),console.log()});var Ms=new oo().name("hook").description("manage hooks \u2014 add to agent workspace");Ms.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=ne().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=J(t.workspace,".claude/settings.json"),s=ge(n)?JSON.parse(wo(n,"utf-8")):{},i=await Te([{type:"select",name:"event",message:"Hook event",choices:[{title:"PreToolUse \u2014 before any tool runs",value:"PreToolUse"},{title:"PostToolUse \u2014 after any tool runs",value:"PostToolUse"},{title:"SessionStart \u2014 when session begins",value:"SessionStart"},{title:"Notification \u2014 on notifications",value:"Notification"},{title:"Stop \u2014 before session stops",value:"Stop"}]},{type:"select",name:"type",message:"Hook type",choices:[{title:"command \u2014 run a shell command",value:"command"},{title:"http \u2014 POST to a URL",value:"http"}]},{type:"text",name:"value",message:c=>c==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!i.event||!i.value)return;s.hooks=s.hooks||{},s.hooks[i.event]=s.hooks[i.event]||[];let a={hooks:[{type:i.type,...i.type==="command"?{command:i.value}:{url:i.value}}]};i.matcher&&(a.matcher=i.matcher),s.hooks[i.event].push(a),eo(J(t.workspace,".claude"),{recursive:!0}),at(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var Fs=new oo().name("migrate").description("import configuration from OpenClaw or other tools");Fs.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(e,o)=>{let t=[e,J(process.env.HOME||"",".openclaw/openclaw.json"),J(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of t)if(f&&ge(f)){n=f;break}if(!n){console.log(h.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(h.dim(` Reading: ${n}`));let s=JSON.parse(wo(n,"utf-8")),i=ge(J(process.cwd(),"agentx.json"))?ne():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},r=s.agents?.list||[],a=s.bindings||[],c={};for(let f of a)f.match?.channel==="telegram"&&(c[f.match.accountId]=f.agentId);r.find(f=>f.id==="main"||f.default)&&(c.default="main");let d=0;for(let f of r){if(f.workspace?.startsWith("/data"))continue;let u=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),w=f.groupChat?.mentionPatterns||[];if(w.some(y=>y===u)||w.push(u),i.agents[u]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:w,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},d++,!o.dryRun){eo(J(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-G6KGWPHY.js");y(u,i.agents[u])}}console.log(` ${h.green(d)} agents imported (workspaces set up with Claude Code best practices)`);let g=s.channels?.telegram?.accounts||{},l=0;for(let[f,u]of Object.entries(g)){if(!u.botToken)continue;let y=c[f]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[f]={token:u.botToken,agentBinding:y},i.channels.telegram.enabled=!0,l++}console.log(` ${h.green(l)} Telegram accounts imported`);let p=J(n,"../cron/jobs.json");if(ge(p)){let f=JSON.parse(wo(p,"utf-8")),u=0;for(let w of f.jobs||[]){let y=w.name||w.id,k=w.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[y]={enabled:w.enabled||!1,schedule:w.schedule?.expr||"0 9 * * *",timezone:w.schedule?.tz||"UTC",agent:k,prompt:w.payload?.message||"",timeout:w.payload?.timeoutSeconds||600,onError:["log"]},u++}console.log(` ${h.green(u)} cron jobs imported`)}o.dryRun?(console.log(h.yellow(`
30
- Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await _e(i),console.log(h.green(`
31
- Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var bo=new oo().name("config").description("validate and inspect configuration");bo.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async e=>{console.log();try{let o=_(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=dn(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=ge(J(r,".claude")),c=ge(J(r,"CLAUDE.md")),d=ge(J(r,".claude/settings.json")),g=ge(J(r,".claude/skills"))?Ls(J(r,".claude/skills")).filter(p=>!p.startsWith(".")).length:0,l=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",d?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${l.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});bo.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=_(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function Sd(e,o){if(o)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(t=>t.trim()).filter(Boolean):e}function Ps(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}bo.command("get <path>").description("read a config value by dot-path (e.g. agents.devops.model)").option("-c, --config <path>","path to agentx.json").option("--raw","show ${VAR} tokens instead of env-expanded values").option("--json","output as JSON (for scripting)").action(async(e,o)=>{let{readFileSync:t,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-KJ5GEMVV.js"),{expandEnvVars:r}=await import("./config-SRTXHGSK.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(h.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(t(a,"utf-8")),d=o.raw?c:r(c),g=i(d,e);o.json?console.log(JSON.stringify(g)):console.log(Ps(g))});bo.command("set <path> <value>").description("write a config value by dot-path; validates against schema and hot-reloads the daemon").option("-c, --config <path>","path to agentx.json").option("--string","treat the value as a literal string (skip JSON parsing)").option("--dry-run","validate and diff without writing").action(async(e,o,t)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:i}=await import("./config-mutator-KJ5GEMVV.js"),r=Sd(o,!!t.string),a=await n(d=>{s(d,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(h.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would become: ${Ps(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${Ps(c)}`)),a.reloaded?console.log(h.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(h.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});bo.command("unset <path>").description("remove a config value by dot-path (validates + hot-reloads)").option("-c, --config <path>","path to agentx.json").option("--dry-run","validate without writing").action(async(e,o)=>{let{applyConfigMutation:t,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-KJ5GEMVV.js"),i=await t(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:o.config,dryRun:!!o.dryRun});if(i.success||(console.log(h.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(h.dim(` (no-op) ${h.cyan(e)} was not set`));return}o.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would be removed`)):(console.log(h.green(` \u2713 ${h.cyan(e)} removed`)),i.reloaded&&console.log(h.dim(" Daemon hot-reloaded.")))});bo.command("governance").description("show resolved governance flags (read-only; flags read once at startup)").option("-c, --config <path>","path to agentx.json").option("--json","emit JSON").action(e=>{let o=!1,t=0,n;try{let l=_(e.config);o=!!l.business?.enabled,t=(l.business?.projects??[]).length}catch(l){n=l?.message??String(l)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(h.bold(" Governance flags")),console.log(),n&&(console.log(h.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let d=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${d(s)}${c?"":h.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?h.green("active"):r?h.yellow("env=true but business.enabled=false \u2192 inactive"):h.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(h.dim(` business.enabled ${o?h.green("true"):h.dim("false")}`)),console.log(h.dim(` business.projects[] ${t}`)),console.log(),console.log(h.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(h.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as Ed}from"commander";import $o from"chalk";import{resolve as ko}from"path";import{existsSync as Ad}from"fs";var lo=new Ed().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Lo(e){let o=ko(e,".agentx/db.sqlite");Ad(o)||(console.log($o.red(` No SQLite at ${o}`)),console.log($o.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=ir({path:o});return t||(console.log($o.red(` Could not open ${o}`)),console.log($o.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function Mo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log($o.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}lo.command("tasks").description("recent task_history rows (one per agent task)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by start day (UTC)").option("-s, --status <status>","ok | error").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=Lo(ko(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(t.push("status = @status"),n.status=e.status);let s=`
29
+ `).length-30} more lines truncated in preview)`));console.log(),console.log(h.dim(` Re-run with --write to commit these to ${u}/`)),console.log();return}oo(u,{recursive:!0});let f=0,p=0;for(let[w,y]of Object.entries(g)){let k=wo(u,w);if(me(k)&&!o.force){console.log(h.dim(` skip ${k} (exists; --force to overwrite)`)),p++;continue}lt(k,y),console.log(h.green(` + ${k}`)),f++}console.log(),console.log(h.dim(` ${f} written, ${p} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(h.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});Bt.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:o}=await import("./loader-4ZGTK7LD.js"),t=await o(G(e.cwd)),n=[...t.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(h.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=t.sourceById.get(s.id);console.log(` ${h.cyan(s.id)} ${h.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(h.dim(` ${i}`))}console.log(),console.log(h.dim(` ${n.length} reference(s) loaded.`)),console.log()});var Us=new to().name("hook").description("manage hooks \u2014 add to agent workspace");Us.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=se().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=G(t.workspace,".claude/settings.json"),s=me(n)?JSON.parse(bo(n,"utf-8")):{},i=await Ie([{type:"select",name:"event",message:"Hook event",choices:[{title:"PreToolUse \u2014 before any tool runs",value:"PreToolUse"},{title:"PostToolUse \u2014 after any tool runs",value:"PostToolUse"},{title:"SessionStart \u2014 when session begins",value:"SessionStart"},{title:"Notification \u2014 on notifications",value:"Notification"},{title:"Stop \u2014 before session stops",value:"Stop"}]},{type:"select",name:"type",message:"Hook type",choices:[{title:"command \u2014 run a shell command",value:"command"},{title:"http \u2014 POST to a URL",value:"http"}]},{type:"text",name:"value",message:c=>c==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!i.event||!i.value)return;s.hooks=s.hooks||{},s.hooks[i.event]=s.hooks[i.event]||[];let a={hooks:[{type:i.type,...i.type==="command"?{command:i.value}:{url:i.value}}]};i.matcher&&(a.matcher=i.matcher),s.hooks[i.event].push(a),oo(G(t.workspace,".claude"),{recursive:!0}),lt(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var qs=new to().name("migrate").description("import configuration from OpenClaw or other tools");qs.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(e,o)=>{let t=[e,G(process.env.HOME||"",".openclaw/openclaw.json"),G(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of t)if(f&&me(f)){n=f;break}if(!n){console.log(h.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(h.dim(` Reading: ${n}`));let s=JSON.parse(bo(n,"utf-8")),i=me(G(process.cwd(),"agentx.json"))?se():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},r=s.agents?.list||[],a=s.bindings||[],c={};for(let f of a)f.match?.channel==="telegram"&&(c[f.match.accountId]=f.agentId);r.find(f=>f.id==="main"||f.default)&&(c.default="main");let l=0;for(let f of r){if(f.workspace?.startsWith("/data"))continue;let p=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),w=f.groupChat?.mentionPatterns||[];if(w.some(y=>y===p)||w.push(p),i.agents[p]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:w,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!o.dryRun){oo(G(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-G6KGWPHY.js");y(p,i.agents[p])}}console.log(` ${h.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let g=s.channels?.telegram?.accounts||{},d=0;for(let[f,p]of Object.entries(g)){if(!p.botToken)continue;let y=c[f]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[f]={token:p.botToken,agentBinding:y},i.channels.telegram.enabled=!0,d++}console.log(` ${h.green(d)} Telegram accounts imported`);let u=G(n,"../cron/jobs.json");if(me(u)){let f=JSON.parse(bo(u,"utf-8")),p=0;for(let w of f.jobs||[]){let y=w.name||w.id,k=w.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[y]={enabled:w.enabled||!1,schedule:w.schedule?.expr||"0 9 * * *",timezone:w.schedule?.tz||"UTC",agent:k,prompt:w.payload?.message||"",timeout:w.payload?.timeoutSeconds||600,onError:["log"]},p++}console.log(` ${h.green(p)} cron jobs imported`)}o.dryRun?(console.log(h.yellow(`
30
+ Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await Pe(i),console.log(h.green(`
31
+ Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var $o=new to().name("config").description("validate and inspect configuration");$o.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async e=>{console.log();try{let o=_(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=mn(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=me(G(r,".claude")),c=me(G(r,"CLAUDE.md")),l=me(G(r,".claude/settings.json")),g=me(G(r,".claude/skills"))?Fs(G(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,d=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",l?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});$o.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=_(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function Ud(e,o){if(o)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(t=>t.trim()).filter(Boolean):e}function Ls(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}$o.command("get <path>").description("read a config value by dot-path (e.g. agents.devops.model)").option("-c, --config <path>","path to agentx.json").option("--raw","show ${VAR} tokens instead of env-expanded values").option("--json","output as JSON (for scripting)").action(async(e,o)=>{let{readFileSync:t,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-E6NQLFWR.js"),{expandEnvVars:r}=await import("./config-5V444ZFW.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(h.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(t(a,"utf-8")),l=o.raw?c:r(c),g=i(l,e);o.json?console.log(JSON.stringify(g)):console.log(Ls(g))});$o.command("set <path> <value>").description("write a config value by dot-path; validates against schema and hot-reloads the daemon").option("-c, --config <path>","path to agentx.json").option("--string","treat the value as a literal string (skip JSON parsing)").option("--dry-run","validate and diff without writing").action(async(e,o,t)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:i}=await import("./config-mutator-E6NQLFWR.js"),r=Ud(o,!!t.string),a=await n(l=>{s(l,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(h.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would become: ${Ls(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${Ls(c)}`)),a.reloaded?console.log(h.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(h.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});$o.command("unset <path>").description("remove a config value by dot-path (validates + hot-reloads)").option("-c, --config <path>","path to agentx.json").option("--dry-run","validate without writing").action(async(e,o)=>{let{applyConfigMutation:t,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-E6NQLFWR.js"),i=await t(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:o.config,dryRun:!!o.dryRun});if(i.success||(console.log(h.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(h.dim(` (no-op) ${h.cyan(e)} was not set`));return}o.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would be removed`)):(console.log(h.green(` \u2713 ${h.cyan(e)} removed`)),i.reloaded&&console.log(h.dim(" Daemon hot-reloaded.")))});$o.command("governance").description("show resolved governance flags (read-only; flags read once at startup)").option("-c, --config <path>","path to agentx.json").option("--json","emit JSON").action(e=>{let o=!1,t=0,n;try{let d=_(e.config);o=!!d.business?.enabled,t=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(h.bold(" Governance flags")),console.log(),n&&(console.log(h.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":h.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?h.green("active"):r?h.yellow("env=true but business.enabled=false \u2192 inactive"):h.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(h.dim(` business.enabled ${o?h.green("true"):h.dim("false")}`)),console.log(h.dim(` business.projects[] ${t}`)),console.log(),console.log(h.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(h.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as qd}from"commander";import ko from"chalk";import{resolve as vo}from"path";import{existsSync as Wd}from"fs";var co=new qd().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Lo(e){let o=vo(e,".agentx/db.sqlite");Wd(o)||(console.log(ko.red(` No SQLite at ${o}`)),console.log(ko.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=Qi({path:o});return t||(console.log(ko.red(` Could not open ${o}`)),console.log(ko.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function Fo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(ko.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}co.command("tasks").description("recent task_history rows (one per agent task)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by start day (UTC)").option("-s, --status <status>","ok | error").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=Lo(vo(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(t.push("status = @status"),n.status=e.status);let s=`
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)});Mo(i,!!e.json)});lo.command("rotations").description("session rotation events (stale | tier-2 | max-turns)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-r, --reason <r>","stale | tier-2 | max-turns").option("-n, --limit <n>","max rows","20").option("--summary","group by agent + reason").option("--json","emit JSON").action(e=>{let o=Lo(ko(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.reason&&(t.push("reason = @reason"),n.reason=e.reason);let s=t.length?"WHERE "+t.join(" AND "):"",i=e.summary?`
40
+ `,i=o.prepare(s).all({...n,limit:Number(e.limit)});Fo(i,!!e.json)});co.command("rotations").description("session rotation events (stale | tier-2 | max-turns)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-r, --reason <r>","stale | tier-2 | max-turns").option("-n, --limit <n>","max rows","20").option("--summary","group by agent + reason").option("--json","emit JSON").action(e=>{let o=Lo(vo(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.reason&&(t.push("reason = @reason"),n.reason=e.reason);let s=t.length?"WHERE "+t.join(" AND "):"",i=e.summary?`
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)});Mo(r,!!e.json)});lo.command("usage").description("token usage rolled up per (agent, model, day)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by day (UTC)").option("--json","emit JSON").action(e=>{let o=Lo(ko(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("day = @day"),n.day=e.day);let s=`
54
+ `,r=o.prepare(i).all({...n,limit:Number(e.limit)});Fo(r,!!e.json)});co.command("usage").description("token usage rolled up per (agent, model, day)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by day (UTC)").option("--json","emit JSON").action(e=>{let o=Lo(vo(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("day = @day"),n.day=e.day);let s=`
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);Mo(i,!!e.json)});lo.command("routes").description("inbound routing decisions captured by the pipeline trace").option("--cwd <cwd>","working directory",process.cwd()).option("-c, --channel <ch>","filter by channel (telegram, gitlab, github, ...)").option("-k, --kind <k>","match | drop").option("-n, --limit <n>","max rows","20").option("--summary","group by channel + kind + deciding stage").option("--json","emit JSON").action(e=>{let o=Lo(ko(e.cwd)),t=[],n={};e.channel&&(t.push("channel = @channel"),n.channel=e.channel),e.kind&&(t.push("kind = @kind"),n.kind=e.kind);let s=t.length?"WHERE "+t.join(" AND "):"",i=e.summary?`
61
+ `,i=o.prepare(s).all(n);Fo(i,!!e.json)});co.command("routes").description("inbound routing decisions captured by the pipeline trace").option("--cwd <cwd>","working directory",process.cwd()).option("-c, --channel <ch>","filter by channel (telegram, gitlab, github, ...)").option("-k, --kind <k>","match | drop").option("-n, --limit <n>","max rows","20").option("--summary","group by channel + kind + deciding stage").option("--json","emit JSON").action(e=>{let o=Lo(vo(e.cwd)),t=[],n={};e.channel&&(t.push("channel = @channel"),n.channel=e.channel),e.kind&&(t.push("kind = @kind"),n.kind=e.kind);let s=t.length?"WHERE "+t.join(" AND "):"",i=e.summary?`
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)});Mo(r,!!e.json)});lo.command("errors").description("failed tasks (status='error') with their error message").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=Lo(ko(e.cwd)),t=["status = 'error'"],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent);let s=`
74
+ `,r=o.prepare(i).all({...n,limit:Number(e.limit)});Fo(r,!!e.json)});co.command("errors").description("failed tasks (status='error') with their error message").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=Lo(vo(e.cwd)),t=["status = 'error'"],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent);let s=`
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)});Mo(i,!!e.json)});lo.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=Lo(ko(e.cwd)),n=o.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map(s=>({table:s.name,rows:o.prepare(`SELECT COUNT(*) AS c FROM ${s.name}`).get().c}));Mo(n,!!e.json)});lo.command("query <sql>").description("run an arbitrary read-only SQL query (escape hatch)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action((e,o)=>{let t=Lo(ko(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log($o.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log($o.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();Mo(n,!!o.json)}catch(n){console.log($o.red(` ${n.message}`)),process.exit(1)}});import{Command as Id}from"commander";import H from"chalk";import{mkdtempSync as jd}from"fs";import{tmpdir as Cd}from"os";import{resolve as Ea,join as Aa}from"path";import{existsSync as Nd}from"fs";import Rd from"better-sqlite3";function Sa(e,o,t,n=[]){let s=new Map;for(let c of o)s.set(c.id,c);let i=[];for(let c of t)i.push({kind:"decision",ts:c.decidedAt,decision:c});for(let c of n)i.push({kind:"resolution",ts:c.resolvedAt,resolution:c});i.sort((c,d)=>c.ts!==d.ts?c.ts-d.ts:c.kind===d.kind?0:c.kind==="decision"?-1:1);let r=[],a=0;for(let c of i){if(c.kind==="resolution"){try{e.recordResolution(c.resolution)}catch(u){r.push({eventId:c.resolution.decisionEventId,decidedBy:c.resolution.decisionDecidedBy,expected:{agentId:null,outcome:"resolved"},actual:{agentId:null,outcome:"resolution-failed"},reason:`recordResolution threw: ${u?.message??u}`})}continue}let d=c.decision,g=s.get(d.eventId);if(!g){r.push({eventId:d.eventId,decidedBy:d.decidedBy,expected:{agentId:d.agentId,outcome:d.outcome},actual:{agentId:null,outcome:"skipped"},reason:"decision references event not in snapshot"});continue}let l=Od(d),p={id:g.id,ts:g.ts,source:g.source,sourceEventId:g.sourceEventId,project:g.project,subject:g.subject,intent:g.intent,rawJson:g.rawJson},f=sr(e,p,l,()=>d.decidedAt);a+=1,(f.outcome!==d.outcome||f.agentId!==d.agentId)&&r.push({eventId:g.id,decidedBy:d.decidedBy,expected:{agentId:d.agentId,outcome:d.outcome},actual:{agentId:f.agentId,outcome:f.outcome},reason:Td(d,f)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function Od(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function Td(e,o){return e.outcome==="dispatched"&&o.outcome==="deduped"?"active-task-safety-now-fires (slot held by earlier decision)":e.outcome==="deduped"&&o.outcome==="halted"?"policy-returned-null (recorded as deduped means the live system hit active-task safety; playback policy returned null because deduped is illegal at the policy layer \u2014 investigate whether the in-flight decision is present in the snapshot)":e.agentId!==o.agentId?`agent-changed (recorded=${e.agentId} replayed=${o.agentId})`:e.outcome!==o.outcome?`outcome-changed (recorded=${e.outcome} replayed=${o.outcome})`:"unknown"}var vo=new Id().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function dt(e){let o=Ea(e.cwd??process.cwd()),t=Ea(o,e.path??".agentx/intent/ledger.sqlite");Nd(t)||(console.log(H.red(` No ledger at ${t}`)),console.log(H.dim(' Make sure the daemon has run with INTENT_LEDGER_MODE != "off". The file is created on first ledger write.')),process.exit(1));try{return new Rd(t,{readonly:!0})}catch(n){console.log(H.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(H.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Fo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(H.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}function Dd(e){let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!o)return null;let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function Rn(e){if(!e)return;let o=Dd(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(H.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}vo.command("stats").description("overview: events by source, decisions, divergences, in-flight count").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--since <duration>","limit to events newer than (e.g. 1h, 24h, 7d)").option("--json","emit JSON").action(e=>{let o=dt(e),t=Rn(e.since),n=t!==void 0?"WHERE ts >= @since":"",s=t!==void 0?"WHERE decided_at >= @since":"",i=n,r=o.prepare(`SELECT source, COUNT(*) as n FROM intent_events ${n} GROUP BY source ORDER BY n DESC`).all({since:t}),a=o.prepare(`SELECT COUNT(*) as n FROM intent_decisions ${s}`).get({since:t}).n,c=o.prepare(`SELECT outcome, COUNT(*) as n FROM intent_decisions ${s} GROUP BY outcome ORDER BY n DESC`).all({since:t}),d=o.prepare(`SELECT COUNT(*) as n FROM intent_divergences ${i}`).get({since:t}).n,g=o.prepare(`SELECT source, COUNT(*) as n FROM intent_divergences ${i} GROUP BY source ORDER BY n DESC`).all({since:t}),l=o.prepare(`
82
+ `,i=o.prepare(s).all({...n,limit:Number(e.limit)});Fo(i,!!e.json)});co.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=Lo(vo(e.cwd)),n=o.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map(s=>({table:s.name,rows:o.prepare(`SELECT COUNT(*) AS c FROM ${s.name}`).get().c}));Fo(n,!!e.json)});co.command("query <sql>").description("run an arbitrary read-only SQL query (escape hatch)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action((e,o)=>{let t=Lo(vo(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(ko.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(ko.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();Fo(n,!!o.json)}catch(n){console.log(ko.red(` ${n.message}`)),process.exit(1)}});import{Command as Gd}from"commander";import z from"chalk";import{mkdtempSync as Hd}from"fs";import{tmpdir as zd}from"os";import{resolve as Fa,join as Ua}from"path";import{existsSync as Yd}from"fs";import Vd from"better-sqlite3";function La(e,o,t,n=[]){let s=new Map;for(let c of o)s.set(c.id,c);let i=[];for(let c of t)i.push({kind:"decision",ts:c.decidedAt,decision:c});for(let c of n)i.push({kind:"resolution",ts:c.resolvedAt,resolution:c});i.sort((c,l)=>c.ts!==l.ts?c.ts-l.ts:c.kind===l.kind?0:c.kind==="decision"?-1:1);let r=[],a=0;for(let c of i){if(c.kind==="resolution"){try{e.recordResolution(c.resolution)}catch(p){r.push({eventId:c.resolution.decisionEventId,decidedBy:c.resolution.decisionDecidedBy,expected:{agentId:null,outcome:"resolved"},actual:{agentId:null,outcome:"resolution-failed"},reason:`recordResolution threw: ${p?.message??p}`})}continue}let l=c.decision,g=s.get(l.eventId);if(!g){r.push({eventId:l.eventId,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:null,outcome:"skipped"},reason:"decision references event not in snapshot"});continue}let d=Bd(l),u={id:g.id,ts:g.ts,source:g.source,sourceEventId:g.sourceEventId,project:g.project,subject:g.subject,intent:g.intent,rawJson:g.rawJson},f=cr(e,u,d,()=>l.decidedAt);a+=1,(f.outcome!==l.outcome||f.agentId!==l.agentId)&&r.push({eventId:g.id,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:f.agentId,outcome:f.outcome},reason:Jd(l,f)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function Bd(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function Jd(e,o){return e.outcome==="dispatched"&&o.outcome==="deduped"?"active-task-safety-now-fires (slot held by earlier decision)":e.outcome==="deduped"&&o.outcome==="halted"?"policy-returned-null (recorded as deduped means the live system hit active-task safety; playback policy returned null because deduped is illegal at the policy layer \u2014 investigate whether the in-flight decision is present in the snapshot)":e.agentId!==o.agentId?`agent-changed (recorded=${e.agentId} replayed=${o.agentId})`:e.outcome!==o.outcome?`outcome-changed (recorded=${e.outcome} replayed=${o.outcome})`:"unknown"}var xo=new Gd().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function mt(e){let o=Fa(e.cwd??process.cwd()),t=Fa(o,e.path??".agentx/intent/ledger.sqlite");Yd(t)||(console.log(z.red(` No ledger at ${t}`)),console.log(z.dim(' Make sure the daemon has run with INTENT_LEDGER_MODE != "off". The file is created on first ledger write.')),process.exit(1));try{return new Vd(t,{readonly:!0})}catch(n){console.log(z.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(z.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Uo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(z.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}function Kd(e){let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!o)return null;let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function Pn(e){if(!e)return;let o=Kd(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(z.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}xo.command("stats").description("overview: events by source, decisions, divergences, in-flight count").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--since <duration>","limit to events newer than (e.g. 1h, 24h, 7d)").option("--json","emit JSON").action(e=>{let o=mt(e),t=Pn(e.since),n=t!==void 0?"WHERE ts >= @since":"",s=t!==void 0?"WHERE decided_at >= @since":"",i=n,r=o.prepare(`SELECT source, COUNT(*) as n FROM intent_events ${n} GROUP BY source ORDER BY n DESC`).all({since:t}),a=o.prepare(`SELECT COUNT(*) as n FROM intent_decisions ${s}`).get({since:t}).n,c=o.prepare(`SELECT outcome, COUNT(*) as n FROM intent_decisions ${s} GROUP BY outcome ORDER BY n DESC`).all({since:t}),l=o.prepare(`SELECT COUNT(*) as n FROM intent_divergences ${i}`).get({since:t}).n,g=o.prepare(`SELECT source, COUNT(*) as n FROM intent_divergences ${i} GROUP BY source ORDER BY n DESC`).all({since:t}),d=o.prepare(`
83
83
  SELECT COUNT(*) as n FROM intent_decisions d
84
84
  LEFT JOIN intent_resolutions r
85
85
  ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
86
86
  WHERE d.outcome = 'dispatched' AND r.decision_event_id IS NULL
87
- `).get().n;if(e.json){console.log(JSON.stringify({since:t??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:d,divergencesBySource:g,inFlight:l},null,2));return}console.log(H.bold("Events by source")),Fo(r,!1),console.log(),console.log(H.bold(`Decisions: ${a}`)),Fo(c,!1),console.log(),console.log(H.bold(`Divergences: ${d}`)),Fo(g,!1),console.log(),console.log(H.bold(`In-flight (dispatched, no resolution): ${l}`))});vo.command("divergences").description("recent divergence rows (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source (telegram, gitlab, workflow, cron, mesh, github)").option("--since <duration>","limit to divergences newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=dt(e),t=Rn(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
87
+ `).get().n;if(e.json){console.log(JSON.stringify({since:t??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:l,divergencesBySource:g,inFlight:d},null,2));return}console.log(z.bold("Events by source")),Uo(r,!1),console.log(),console.log(z.bold(`Decisions: ${a}`)),Uo(c,!1),console.log(),console.log(z.bold(`Divergences: ${l}`)),Uo(g,!1),console.log(),console.log(z.bold(`In-flight (dispatched, no resolution): ${d}`))});xo.command("divergences").description("recent divergence rows (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source (telegram, gitlab, workflow, cron, mesh, github)").option("--since <duration>","limit to divergences newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=mt(e),t=Pn(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
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);Fo(r,!!e.json)});vo.command("active").description("currently in-flight dispatched decisions (no resolution yet)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=dt(e),t=["d.outcome = 'dispatched'","r.decision_event_id IS NULL"],n={limit:Number(e.limit)};e.source&&(t.push("e.source = @source"),n.source=e.source);let s=o.prepare(`
101
+ `).all(s);Uo(r,!!e.json)});xo.command("active").description("currently in-flight dispatched decisions (no resolution yet)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=mt(e),t=["d.outcome = 'dispatched'","r.decision_event_id IS NULL"],n={limit:Number(e.limit)};e.source&&(t.push("e.source = @source"),n.source=e.source);let s=o.prepare(`
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);Fo(s,!!e.json)});vo.command("events").description("recent events (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-p, --project <name>","filter by project").option("--since <duration>","limit to newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let o=dt(e),t=Rn(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),e.project&&(n.push("project = @project"),s.project=e.project),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
117
+ `).all(n);Uo(s,!!e.json)});xo.command("events").description("recent events (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-p, --project <name>","filter by project").option("--since <duration>","limit to newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let o=mt(e),t=Pn(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),e.project&&(n.push("project = @project"),s.project=e.project),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
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);Fo(r,!!e.json)});vo.command("lineage <eventOrSubject>").description("walk the dispatch chain on the same (project, subject) and print every decision + resolution").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--by-subject","treat the argument as `<project>:<subject>` instead of an event id").option("--json","emit JSON").action((e,o)=>{let t=dt(o),n=null,s=null;if(o.bySubject){let l=e.indexOf(":");l<0&&(console.log(H.red(' --by-subject expects "<project>:<subject>"')),process.exit(1)),n=e.slice(0,l),s=e.slice(l+1)}else{let l=t.prepare("SELECT project, subject FROM intent_events WHERE id = ?").get(e);l||(console.log(H.red(` no event with id ${e}`)),process.exit(1)),n=l.project,s=l.subject,(n===null||s===null)&&(console.log(H.yellow(` event ${e} has no (project, subject) \u2014 lineage requires both`)),n&&console.log(H.dim(` project: ${n}`)),s&&console.log(H.dim(` subject: ${s}`)),process.exit(1))}let i=t.prepare(`SELECT id, ts, source, COALESCE(intent, '-') AS intent, COALESCE(source_event_id, '-') AS source_event_id
129
- FROM intent_events WHERE project = ? AND subject = ? ORDER BY ts ASC`).all(n,s);if(i.length===0){console.log(H.dim(` (no events for ${n}:${s})`));return}let r=i.map(l=>l.id),a=r.map((l,p)=>`@id${p}`).join(", "),c=Object.fromEntries(r.map((l,p)=>[`id${p}`,l])),d=t.prepare(`
128
+ `).all(s);Uo(r,!!e.json)});xo.command("lineage <eventOrSubject>").description("walk the dispatch chain on the same (project, subject) and print every decision + resolution").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--by-subject","treat the argument as `<project>:<subject>` instead of an event id").option("--json","emit JSON").action((e,o)=>{let t=mt(o),n=null,s=null;if(o.bySubject){let d=e.indexOf(":");d<0&&(console.log(z.red(' --by-subject expects "<project>:<subject>"')),process.exit(1)),n=e.slice(0,d),s=e.slice(d+1)}else{let d=t.prepare("SELECT project, subject FROM intent_events WHERE id = ?").get(e);d||(console.log(z.red(` no event with id ${e}`)),process.exit(1)),n=d.project,s=d.subject,(n===null||s===null)&&(console.log(z.yellow(` event ${e} has no (project, subject) \u2014 lineage requires both`)),n&&console.log(z.dim(` project: ${n}`)),s&&console.log(z.dim(` subject: ${s}`)),process.exit(1))}let i=t.prepare(`SELECT id, ts, source, COALESCE(intent, '-') AS intent, COALESCE(source_event_id, '-') AS source_event_id
129
+ FROM intent_events WHERE project = ? AND subject = ? ORDER BY ts ASC`).all(n,s);if(i.length===0){console.log(z.dim(` (no events for ${n}:${s})`));return}let r=i.map(d=>d.id),a=r.map((d,u)=>`@id${u}`).join(", "),c=Object.fromEntries(r.map((d,u)=>[`id${u}`,d])),l=t.prepare(`
130
130
  SELECT d.event_id, d.decided_at, d.decided_by, d.agent_id, d.outcome, d.reason,
131
131
  r.resolved_at, r.status AS resolution_status, r.duration_ms, r.result_summary
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(p=>({event:p,decisions:d.filter(f=>f.event_id===p.id)}));console.log(JSON.stringify({project:n,subject:s,lineage:l},null,2));return}let g=new Set;for(let l of d)l.outcome==="dispatched"&&l.agent_id&&g.add(l.agent_id);console.log(),console.log(H.bold(` Lineage for ${H.cyan(n+":"+s)}`)),console.log(H.dim(` ${i.length} event(s), ${d.length} decision(s), ${g.size} distinct agent(s) dispatched`)),console.log();for(let l of i){let p=new Date(l.ts).toISOString().slice(0,19).replace("T"," ");console.log(` ${H.dim(p)} ${H.bold(l.id)} ${H.dim(`(${l.source}/${l.intent})`)}`);let f=d.filter(u=>u.event_id===l.id);if(f.length===0){console.log(H.dim(" (no decisions yet)"));continue}for(let u of f){let w=u.outcome==="dispatched"?H.green(u.outcome):u.outcome==="dropped"?H.dim(u.outcome):H.yellow(u.outcome),y=u.agent_id?H.cyan(u.agent_id):H.dim("-"),k=u.reason?H.dim(` \u2014 ${u.reason.slice(0,60)}`):"";if(console.log(` ${H.dim(u.decided_by)} \u2192 ${w} ${y}${k}`),u.resolution_status){let b=u.resolution_status==="ok"?H.green(u.resolution_status):H.red(u.resolution_status),x=u.duration_ms?`${(u.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${H.dim("resolved")} ${b} ${H.dim(x)}`)}else u.outcome==="dispatched"&&console.log(` ${H.yellow("(in-flight, no resolution)")}`)}}console.log()});vo.command("replay").description("replay the source ledger onto a fresh tmp ledger; report divergences").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--since <duration>","limit to events newer than (e.g. 1h, 24h, 7d)").option("-s, --source <name>","filter to one source").option("-n, --limit <n>","max events to replay (defaults to all)").option("--json","emit JSON").action(e=>{let o=dt(e),t=Rn(e.since),n=[],s={};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=e.limit?`LIMIT ${Number(e.limit)}`:"",r=o.prepare(`
137
+ `).all(c);if(o.json){let d=i.map(u=>({event:u,decisions:l.filter(f=>f.event_id===u.id)}));console.log(JSON.stringify({project:n,subject:s,lineage:d},null,2));return}let g=new Set;for(let d of l)d.outcome==="dispatched"&&d.agent_id&&g.add(d.agent_id);console.log(),console.log(z.bold(` Lineage for ${z.cyan(n+":"+s)}`)),console.log(z.dim(` ${i.length} event(s), ${l.length} decision(s), ${g.size} distinct agent(s) dispatched`)),console.log();for(let d of i){let u=new Date(d.ts).toISOString().slice(0,19).replace("T"," ");console.log(` ${z.dim(u)} ${z.bold(d.id)} ${z.dim(`(${d.source}/${d.intent})`)}`);let f=l.filter(p=>p.event_id===d.id);if(f.length===0){console.log(z.dim(" (no decisions yet)"));continue}for(let p of f){let w=p.outcome==="dispatched"?z.green(p.outcome):p.outcome==="dropped"?z.dim(p.outcome):z.yellow(p.outcome),y=p.agent_id?z.cyan(p.agent_id):z.dim("-"),k=p.reason?z.dim(` \u2014 ${p.reason.slice(0,60)}`):"";if(console.log(` ${z.dim(p.decided_by)} \u2192 ${w} ${y}${k}`),p.resolution_status){let b=p.resolution_status==="ok"?z.green(p.resolution_status):z.red(p.resolution_status),S=p.duration_ms?`${(p.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${z.dim("resolved")} ${b} ${z.dim(S)}`)}else p.outcome==="dispatched"&&console.log(` ${z.yellow("(in-flight, no resolution)")}`)}}console.log()});xo.command("replay").description("replay the source ledger onto a fresh tmp ledger; report divergences").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--since <duration>","limit to events newer than (e.g. 1h, 24h, 7d)").option("-s, --source <name>","filter to one source").option("-n, --limit <n>","max events to replay (defaults to all)").option("--json","emit JSON").action(e=>{let o=mt(e),t=Pn(e.since),n=[],s={};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=e.limit?`LIMIT ${Number(e.limit)}`:"",r=o.prepare(`
138
138
  SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
139
139
  FROM intent_events
140
140
  ${n.length?"WHERE "+n.join(" AND "):""}
141
141
  ORDER BY ts ASC
142
142
  ${i}
143
- `).all(s).map(u=>({id:u.id,ts:u.ts,source:u.source,sourceEventId:u.source_event_id,project:u.project,subject:u.subject,intent:u.intent,rawJson:u.raw_json}));if(r.length===0){console.log(H.dim(" (no events match filter)"));return}let a=new Set(r.map(u=>u.id)),c=r.map((u,w)=>`@id${w}`).join(", "),d=Object.fromEntries(r.map((u,w)=>[`id${w}`,u.id])),g=o.prepare(`
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(z.dim(" (no events match filter)"));return}let a=new Set(r.map(p=>p.id)),c=r.map((p,w)=>`@id${w}`).join(", "),l=Object.fromEntries(r.map((p,w)=>[`id${w}`,p.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(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(`
147
+ `).all(l).map(p=>({eventId:p.event_id,decidedAt:p.decided_at,decidedBy:p.decided_by,agentId:p.agent_id,outcome:p.outcome,reason:p.reason})),d=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(u=>({decisionEventId:u.decision_event_id,decisionDecidedBy:u.decision_decided_by,resolvedAt:u.resolved_at,status:u.status,durationMs:u.duration_ms,resultSummary:u.result_summary})),p=jd(Aa(Cd(),"agentx-ledger-replay-")),f=new Xi({path:Aa(p,"target.sqlite")});try{let u=Sa(f,r,g,l);if(e.json){console.log(JSON.stringify(u,null,2));return}console.log(H.bold(`Replayed ${u.eventsCount} events, ${u.decisionsCount} decisions, ${l.length} resolutions`)),u.divergences.length===0?console.log(H.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(H.red(` \u2717 ${u.divergences.length} divergences`)),Fo(u.divergences.map(w=>({event_id:w.eventId,decided_by:w.decidedBy,recorded:`${w.expected.outcome}/${w.expected.agentId??"-"}`,replayed:`${w.actual.outcome}/${w.actual.agentId??"-"}`,reason:w.reason.slice(0,80)})),!1))}finally{f.close()}});Li();Ml();Fl();Ul();Ll();Gi();Tt();import{Command as _d}from"commander";import U from"chalk";import{existsSync as Oa}from"fs";import{resolve as Us}from"path";import Pd from"better-sqlite3";var Pe=new _d().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),ze=".agentx/decisions/decisions.sqlite";function Ld(e){return Us(Us(e.cwd??process.cwd()),e.path??ze)}function no(e,o=!1){let t=Ld(e);Oa(t)||(console.log(U.red(` No decision store at ${t}`)),console.log(U.dim(' Set decisions.enabled and give a seat mode "shadow" (or export AGENTX_DECISION_SEAT_<SEAT>=shadow). The file is created on the first recorded call.')),process.exit(1));try{return new ln({path:t,readonly:!o})}catch(n){console.log(U.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(U.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function to(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(U.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(U.bold(s(t)));for(let i of e)console.log(s(t.map(r=>i[r])))}function qs(e){if(!e)return;let o=e.match(/^(\d+)([dhm])$/);if(o){let n=Number(o[1]),s=o[2]==="d"?864e5:o[2]==="h"?36e5:6e4;return Date.now()-n*s}let t=Date.parse(e);return Number.isNaN(t)?void 0:t}function Ws(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:qs(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}Pe.command("stats").description("per-seat call counts, failure rate, repair rate and latency").option("--path <file>","store path",ze).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let o=no(e),t=qs(e.since)??0,n=o.db.prepare(`SELECT seat, mode, backend, model, structure_mode AS structureMode,
151
+ `).all(l).map(p=>({decisionEventId:p.decision_event_id,decisionDecidedBy:p.decision_decided_by,resolvedAt:p.resolved_at,status:p.status,durationMs:p.duration_ms,resultSummary:p.result_summary})),u=Hd(Ua(zd(),"agentx-ledger-replay-")),f=new or({path:Ua(u,"target.sqlite")});try{let p=La(f,r,g,d);if(e.json){console.log(JSON.stringify(p,null,2));return}console.log(z.bold(`Replayed ${p.eventsCount} events, ${p.decisionsCount} decisions, ${d.length} resolutions`)),p.divergences.length===0?console.log(z.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(z.red(` \u2717 ${p.divergences.length} divergences`)),Uo(p.divergences.map(w=>({event_id:w.eventId,decided_by:w.decidedBy,recorded:`${w.expected.outcome}/${w.expected.agentId??"-"}`,replayed:`${w.actual.outcome}/${w.actual.agentId??"-"}`,reason:w.reason.slice(0,80)})),!1))}finally{f.close()}});Fi();ed();od();td();Zl();zi();jt();import{Command as Xd}from"commander";import U from"chalk";import{existsSync as qa}from"fs";import{resolve as Ws}from"path";import Qd from"better-sqlite3";var Le=new Xd().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),ze=".agentx/decisions/decisions.sqlite";function Zd(e){return Ws(Ws(e.cwd??process.cwd()),e.path??ze)}function so(e,o=!1){let t=Zd(e);qa(t)||(console.log(U.red(` No decision store at ${t}`)),console.log(U.dim(' Set decisions.enabled and give a seat mode "shadow" (or export AGENTX_DECISION_SEAT_<SEAT>=shadow). The file is created on the first recorded call.')),process.exit(1));try{return new gn({path:t,readonly:!o})}catch(n){console.log(U.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(U.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function no(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(U.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(U.bold(s(t)));for(let i of e)console.log(s(t.map(r=>i[r])))}function Bs(e){if(!e)return;let o=e.match(/^(\d+)([dhm])$/);if(o){let n=Number(o[1]),s=o[2]==="d"?864e5:o[2]==="h"?36e5:6e4;return Date.now()-n*s}let t=Date.parse(e);return Number.isNaN(t)?void 0:t}function Js(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:Bs(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}Le.command("stats").description("per-seat call counts, failure rate, repair rate and latency").option("--path <file>","store path",ze).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let o=so(e),t=Bs(e.since)??0,n=o.db.prepare(`SELECT seat, mode, backend, model, structure_mode AS structureMode,
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);to(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);no(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(U.bold(`
164
- policy`)),to(s,!1),console.log(U.dim(`
164
+ policy`)),no(s,!1),console.log(U.dim(`
165
165
  explored=1 means the policy wanted to skip and the expensive path ran anyway.
166
- Those are the only rows in the skip region that can ever be graded.`))),o.close()});Pe.command("calls").description("recent calls").option("--path <file>","store path",ze).option("--seat <seat>").option("--since <window>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=no(e),t=["ts >= ?"],n=[qs(e.since)??0];e.seat&&(t.push("seat = ?"),n.push(e.seat));let s=o.db.prepare(`SELECT id, datetime(ts/1000, 'unixepoch') AS at, seat, mode, backend, model,
166
+ Those are the only rows in the skip region that can ever be graded.`))),o.close()});Le.command("calls").description("recent calls").option("--path <file>","store path",ze).option("--seat <seat>").option("--since <window>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=so(e),t=["ts >= ?"],n=[Bs(e.since)??0];e.seat&&(t.push("seat = ?"),n.push(e.seat));let s=o.db.prepare(`SELECT id, datetime(ts/1000, 'unixepoch') AS at, seat, mode, backend, model,
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));to(s,e.json),o.close()});Pe.command("answers <callId>").description("every answer on one call, with its incumbent and label").option("--path <file>","store path",ze).option("--json").action((e,o)=>{let t=no(o),n=t.gradedRows({}).filter(s=>s.callId===e);if(n.length===0){console.log(U.dim(` (no answers for ${e} \u2014 check \`decisions calls\`)`)),t.close();return}to(n.map(s=>({question:s.question,type:s.type,predicted:s.predicted,confidence:s.confidence.toFixed(3),incumbent:s.incumbent??"",truth:s.truth??""})),o.json),t.close()});Pe.command("label <callId> <question> <value>").description("attach ground truth to one answer (append-only; newest wins)").option("--path <file>","store path",ze).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,o,t,n)=>{let s=no(n,!0);s.label(e,o,t,{kind:n.kind,labeledBy:n.by,note:n.note}),console.log(U.green(` labeled ${e}.${o} = ${t}`)),s.close()});Pe.command("unlabeled").description("lowest-confidence unlabeled answers first \u2014 the most informative to label").option("--path <file>","store path",ze).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=no(e),t=o.gradedRows({seat:e.seat}).filter(n=>n.truth===void 0).sort((n,s)=>n.confidence-s.confidence).slice(0,Number(e.limit));to(t.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),o.close()});Pe.command("backfill-labels").description("derive ground truth from what actually happened (monitor-prefilter seat)").option("--path <file>","store path",ze).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let o=no(e,!0),t=Us(process.cwd(),e.db);Oa(t)||(console.log(U.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new Pd(t,{readonly:!0});try{let s=mr(n,o);console.log(U.green(` wrote ${s} label(s)`)),s===0&&console.log(U.dim(` Rows whose outcome is genuinely ambiguous stay unlabeled on purpose \u2014
170
- label those by hand: agentx decisions unlabeled --seat monitor-prefilter`))}finally{n.close(),o.close()}});Pe.command("calibrate").description("is this seat's confidence worth anything? reliability, ECE, Brier, temperature").option("--path <file>","store path",ze).requiredOption("--seat <seat>").option("--question <name>").option("--backend <name>","grade one backend in isolation").option("--model <id>").option("--structure-mode <mode>","never pool verbalized and logprob rows").option("--since <window>").option("--explored","only rows the policy wanted to skip \u2014 the unbiased skip-region sample").option("--min-n <n>","refuse to report below this many labeled rows","100").option("--bins <n>","default 10","10").option("--json").action(e=>{let o=no(e),t=o.gradedRows(Ws(e)),n=qi(t,{minN:Number(e.minN),bins:Number(e.bins)});if(e.json){console.log(JSON.stringify(n,null,2)),o.close();return}if(console.log(U.bold(`
169
+ ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));no(s,e.json),o.close()});Le.command("answers <callId>").description("every answer on one call, with its incumbent and label").option("--path <file>","store path",ze).option("--json").action((e,o)=>{let t=so(o),n=t.gradedRows({}).filter(s=>s.callId===e);if(n.length===0){console.log(U.dim(` (no answers for ${e} \u2014 check \`decisions calls\`)`)),t.close();return}no(n.map(s=>({question:s.question,type:s.type,predicted:s.predicted,confidence:s.confidence.toFixed(3),incumbent:s.incumbent??"",truth:s.truth??""})),o.json),t.close()});Le.command("label <callId> <question> <value>").description("attach ground truth to one answer (append-only; newest wins)").option("--path <file>","store path",ze).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,o,t,n)=>{let s=so(n,!0);s.label(e,o,t,{kind:n.kind,labeledBy:n.by,note:n.note}),console.log(U.green(` labeled ${e}.${o} = ${t}`)),s.close()});Le.command("unlabeled").description("lowest-confidence unlabeled answers first \u2014 the most informative to label").option("--path <file>","store path",ze).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=so(e),t=o.gradedRows({seat:e.seat}).filter(n=>n.truth===void 0).sort((n,s)=>n.confidence-s.confidence).slice(0,Number(e.limit));no(t.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),o.close()});Le.command("backfill-labels").description("derive ground truth from what actually happened (monitor-prefilter seat)").option("--path <file>","store path",ze).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let o=so(e,!0),t=Ws(process.cwd(),e.db);qa(t)||(console.log(U.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new Qd(t,{readonly:!0});try{let s=xr(n,o);console.log(U.green(` wrote ${s} label(s)`)),s===0&&console.log(U.dim(` Rows whose outcome is genuinely ambiguous stay unlabeled on purpose \u2014
170
+ label those by hand: agentx decisions unlabeled --seat monitor-prefilter`))}finally{n.close(),o.close()}});Le.command("calibrate").description("is this seat's confidence worth anything? reliability, ECE, Brier, temperature").option("--path <file>","store path",ze).requiredOption("--seat <seat>").option("--question <name>").option("--backend <name>","grade one backend in isolation").option("--model <id>").option("--structure-mode <mode>","never pool verbalized and logprob rows").option("--since <window>").option("--explored","only rows the policy wanted to skip \u2014 the unbiased skip-region sample").option("--min-n <n>","refuse to report below this many labeled rows","100").option("--bins <n>","default 10","10").option("--json").action(e=>{let o=so(e),t=o.gradedRows(Js(e)),n=Bi(t,{minN:Number(e.minN),bins:Number(e.bins)});if(e.json){console.log(JSON.stringify(n,null,2)),o.close();return}if(console.log(U.bold(`
171
171
  ${e.seat}${e.question?`.${e.question}`:""}`)),console.log(` ${n.n} answers, ${n.nLabeled} labeled`+(n.agreement.n>0?`, ${n.agreement.n} with an incumbent (agree ${(n.agreement.rate*100).toFixed(1)}%, kappa ${n.agreement.kappa.toFixed(3)})`:"")),n.insufficient){console.log(U.yellow(`
172
172
  Not enough ground truth: ${n.nLabeled} labeled rows, need ${n.minN}.`)),console.log(U.dim(" An ECE on this little data is noise, and a noisy number on a dashboard gets acted on.")),console.log(U.dim(` Label the most informative rows: agentx decisions unlabeled --seat ${e.seat}`)),o.close();return}console.log(`
173
173
  accuracy ${(n.accuracy*100).toFixed(1)}%`),console.log(` ECE ${n.ece.toFixed(4)} `+U.dim(`[95% CI ${n.eceInterval.lo.toFixed(4)}\u2013${n.eceInterval.hi.toFixed(4)}]`)),console.log(` ECE (mass) ${n.eceEqualMass.toFixed(4)} ${U.dim("equal-mass bins")}`),console.log(` MCE ${n.mce.toFixed(4)} ${U.dim("worst single bin")}`),console.log(` Brier ${n.brier.toFixed(4)} ${U.dim("proper score, lower is better")}`),console.log(` log loss ${n.logLoss.toFixed(4)}`);let s=n.temperature;console.log(`
@@ -175,21 +175,21 @@ The AgentX daemon and a speech transcription backend must also be available. Run
175
175
  skip region ${i.length} answers (${(i.length/t.length*100).toFixed(1)}% of traffic), ${r.length} gradeable`),r.length===0&&console.log(U.yellow(` Nothing in the skip region has been graded. Everything below describes
176
176
  only the decisions this policy chose NOT to skip \u2014 it cannot tell you
177
177
  what skipping would cost. Raise decisions.seats.<seat>.explore.`))),console.log(U.bold(`
178
- reliability (equal-width bins)`)),to(n.bins.map(a=>({bin:`${a.lo.toFixed(2)}\u2013${a.hi.toFixed(2)}`,n:a.n,claimed:a.meanConfidence.toFixed(3),actual:a.accuracy.toFixed(3),gap:(a.accuracy-a.meanConfidence).toFixed(3)})),!1),o.close()});Pe.command("recalibrate").description("is one global temperature enough, or does calibration differ by group?").option("--path <file>","store path",ze).requiredOption("--seat <seat>").option("--question <name>").option("--since <window>").option("--by <names>","comma-separated covariates","agent,question").option("--folds <n>","cross-validation folds","5").option("--min-n <n>","default 100","100").option("--json").action(e=>{let o=no(e),t=o.gradedRows(Ws(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=Wi(t,{covariates:n},{folds:Number(e.folds),minN:Number(e.minN)});if(e.json){console.log(JSON.stringify(s,null,2)),o.close();return}if(s.insufficient){console.log(U.yellow(` ${s.n} labeled rows, need ${s.minN}.`)),o.close();return}console.log(U.bold(`
178
+ reliability (equal-width bins)`)),no(n.bins.map(a=>({bin:`${a.lo.toFixed(2)}\u2013${a.hi.toFixed(2)}`,n:a.n,claimed:a.meanConfidence.toFixed(3),actual:a.accuracy.toFixed(3),gap:(a.accuracy-a.meanConfidence).toFixed(3)})),!1),o.close()});Le.command("recalibrate").description("is one global temperature enough, or does calibration differ by group?").option("--path <file>","store path",ze).requiredOption("--seat <seat>").option("--question <name>").option("--since <window>").option("--by <names>","comma-separated covariates","agent,question").option("--folds <n>","cross-validation folds","5").option("--min-n <n>","default 100","100").option("--json").action(e=>{let o=so(e),t=o.gradedRows(Js(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=Ji(t,{covariates:n},{folds:Number(e.folds),minN:Number(e.minN)});if(e.json){console.log(JSON.stringify(s,null,2)),o.close();return}if(s.insufficient){console.log(U.yellow(` ${s.n} labeled rows, need ${s.minN}.`)),o.close();return}console.log(U.bold(`
179
179
  ${e.seat} \u2014 held-out comparison (${s.folds}-fold, n=${s.n})`)),console.log(U.dim(` Cross-validated, because more parameters always fit training data better.
180
- `)),to(s.scores.map(i=>({model:i.name,logLoss:i.logLoss.toFixed(4),brier:i.brier.toFixed(4),best:i.name===s.best?"<-":""})),!1),s.best==="covariate"?(console.log(U.green(`
180
+ `)),no(s.scores.map(i=>({model:i.name,logLoss:i.logLoss.toFixed(4),brier:i.brier.toFixed(4),best:i.name===s.best?"<-":""})),!1),s.best==="covariate"?(console.log(U.green(`
181
181
  Calibration differs by ${n.join("/")} \u2014 a single temperature averages groups`)),console.log(U.dim(" that need different corrections."))):s.best==="temperature"?console.log(U.dim(`
182
182
  One global temperature is enough. ${n.join("/")} carries no calibration signal here.`)):console.log(U.dim(`
183
- Neither correction beats the raw confidence out of sample. Leave it alone.`)),o.close()});Pe.command("coverage").description("accuracy at each threshold against the traffic it keeps \u2014 read this to pick one").option("--path <file>","store path",ze).requiredOption("--seat <seat>").option("--question <name>").option("--since <window>").option("--explored","only rows the policy wanted to skip").option("--steps <n>","default 20","20").option("--json").action(e=>{let o=no(e),t=o.gradedRows({...Ws(e),labeledOnly:!0}),n=Ui(t,Number(e.steps));if(n.length===0){console.log(U.yellow(` No labeled rows for seat "${e.seat}".`)),o.close();return}to(n.map(s=>({threshold:s.threshold.toFixed(2),coverage:`${(s.coverage*100).toFixed(1)}%`,accuracy:`${(s.accuracy*100).toFixed(1)}%`,n:s.n})),e.json),o.close()});Pe.command("consistency").description("does the question hold still? resample one recorded state N times").option("--path <file>","store path",ze).requiredOption("--seat <seat>").option("--backend <name>","default: the backend that recorded the row").option("--model <id>").option("--call <id>","a specific call id; default is the newest with stored state").option("-n, --samples <n>","default 15","15").option("--json").action(async e=>{Vo();let o=no(e),t=o.db.prepare(`SELECT id, backend, model, state_json, questions_json FROM decision_calls
183
+ Neither correction beats the raw confidence out of sample. Leave it alone.`)),o.close()});Le.command("coverage").description("accuracy at each threshold against the traffic it keeps \u2014 read this to pick one").option("--path <file>","store path",ze).requiredOption("--seat <seat>").option("--question <name>").option("--since <window>").option("--explored","only rows the policy wanted to skip").option("--steps <n>","default 20","20").option("--json").action(e=>{let o=so(e),t=o.gradedRows({...Js(e),labeledOnly:!0}),n=Wi(t,Number(e.steps));if(n.length===0){console.log(U.yellow(` No labeled rows for seat "${e.seat}".`)),o.close();return}no(n.map(s=>({threshold:s.threshold.toFixed(2),coverage:`${(s.coverage*100).toFixed(1)}%`,accuracy:`${(s.accuracy*100).toFixed(1)}%`,n:s.n})),e.json),o.close()});Le.command("consistency").description("does the question hold still? resample one recorded state N times").option("--path <file>","store path",ze).requiredOption("--seat <seat>").option("--backend <name>","default: the backend that recorded the row").option("--model <id>").option("--call <id>","a specific call id; default is the newest with stored state").option("-n, --samples <n>","default 15","15").option("--json").action(async e=>{Xo();let o=so(e),t=o.db.prepare(`SELECT id, backend, model, state_json, questions_json FROM decision_calls
184
184
  WHERE seat = ? AND state_json IS NOT NULL AND error IS NULL
185
185
  ${e.call?"AND id = ?":""}
186
- ORDER BY ts DESC LIMIT 1`).get(...e.call?[e.seat,e.call]:[e.seat]);if(!t){console.log(U.yellow(` No recorded call with stored state for seat "${e.seat}".`)),console.log(U.dim(" State is kept for the first `keepStateRows` per seat; see decisions.redactState.")),o.close();return}let n=e.backend??t.backend,s=e.model??(n===t.backend?t.model:void 0),i=await Bi(n,JSON.parse(t.state_json),JSON.parse(t.questions_json),{samples:Number(e.samples),model:s});if(e.json){console.log(JSON.stringify(i,null,2)),o.close();return}console.log(U.bold(`
186
+ ORDER BY ts DESC LIMIT 1`).get(...e.call?[e.seat,e.call]:[e.seat]);if(!t){console.log(U.yellow(` No recorded call with stored state for seat "${e.seat}".`)),console.log(U.dim(" State is kept for the first `keepStateRows` per seat; see decisions.redactState.")),o.close();return}let n=e.backend??t.backend,s=e.model??(n===t.backend?t.model:void 0),i=await Gi(n,JSON.parse(t.state_json),JSON.parse(t.questions_json),{samples:Number(e.samples),model:s});if(e.json){console.log(JSON.stringify(i,null,2)),o.close();return}console.log(U.bold(`
187
187
  ${e.seat} on ${i.backend} (${i.model})`)),console.log(U.dim(` ${i.samples} samples of call ${t.id}, ${i.totalMs}ms, ${i.usage.inputTokens.toLocaleString()} input tokens
188
- `)),to(i.questions.map(r=>({question:r.question,mean:r.mean.toFixed(4),stdev:r.stdev.toFixed(4),min:r.min.toFixed(3),max:r.max.toFixed(3),answers:r.distinctAnswers.join("/"),band:r.bands.join("/"),stable:r.crossesThreshold?U.red("NO"):"yes"})),!1),console.log(`
188
+ `)),no(i.questions.map(r=>({question:r.question,mean:r.mean.toFixed(4),stdev:r.stdev.toFixed(4),min:r.min.toFixed(3),max:r.max.toFixed(3),answers:r.distinctAnswers.join("/"),band:r.bands.join("/"),stable:r.crossesThreshold?U.red("NO"):"yes"})),!1),console.log(`
189
189
  mean stdev ${i.meanStdev.toFixed(4)}`),console.log(U.dim(" TypeSafe publish 0.0102 for jev across a 14-question rubric, as a reference.")),i.unstable.length>0?(console.log(U.red(`
190
190
  Unstable: ${i.unstable.join(", ")} \u2014 identical calls disagree about what to DO,`)),console.log(U.dim(` not merely by how much. Usually a compound question: one name, several questions.
191
191
  Split it, or narrow it to a single clause in the state's own vocabulary.`))):console.log(U.green(`
192
- Every question held its decision across all samples.`)),console.log(U.dim("\n Stability is not correctness. A question can hold perfectly still and be\n perfectly wrong \u2014 that is what `decisions calibrate` is for.")),o.close()});Pe.command("backends").description("registered decision backends and what they claim").action(()=>{Vo();let e=Pi().map(o=>{let t=hs(o).capabilities;return{backend:o,source:t.probabilitySource,calibrated:t.calibratedProbabilities?"yes":"no",maxOptions:t.maxChoiceOptions,maxStateChars:t.maxStateChars}});to(e,!1),console.log(U.dim(`
192
+ Every question held its decision across all samples.`)),console.log(U.dim("\n Stability is not correctness. A question can hold perfectly still and be\n perfectly wrong \u2014 that is what `decisions calibrate` is for.")),o.close()});Le.command("backends").description("registered decision backends and what they claim").action(()=>{Xo();let e=Li().map(o=>{let t=fs(o).capabilities;return{backend:o,source:t.probabilitySource,calibrated:t.calibratedProbabilities?"yes":"no",maxOptions:t.maxChoiceOptions,maxStateChars:t.maxStateChars}});no(e,!1),console.log(U.dim(`
193
193
  source where the numbers come from. "verbalized" means the model wrote them
194
194
  into its answer; "logits" means they were read off its next-token
195
195
  distribution. Logits are the model's actual posterior \u2014 verbalized
@@ -197,15 +197,15 @@ The AgentX daemon and a speech transcription backend must also be available. Run
197
197
  calibrated whether an answer given 0.8 is right about 80% of the time ON YOUR
198
198
  traffic. Reading real logits does not buy this: a posterior can be
199
199
  confidently wrong. It comes from a recalibrator fitted on your own
200
- labeled rows \u2014 see \`agentx decisions recalibrate\`.`))});Pe.command("ask").description("one-off smoke test against a backend (does not record)").requiredOption("--state <text>","the state to evaluate").option("--backend <name>","default mock","mock").option("--model <id>").option("--choice <labels>","comma-separated options for a choice question").option("--noul <question>","a yes/no question").action(async e=>{Vo();let o={};if(e.choice){let s={};for(let i of String(e.choice).split(",").map(r=>r.trim()))i&&(s[i]=null);o.answer=Yo(s,"Which option fits this state?")}e.noul&&(o.verdict=ao(String(e.noul))),Object.keys(o).length===0&&(console.log(U.red(" Give at least one of --choice or --noul.")),process.exit(1));let n=await hs(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as Md}from"commander";import I from"chalk";import{resolve as Ta}from"path";import{existsSync as Fd}from"fs";import Ud from"better-sqlite3";var Wt=new Md().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function Js(e){let o=Ta(e.cwd??process.cwd()),t=Ta(o,e.path??".agentx/db.sqlite");Fd(t)||(console.log(I.red(` No db at ${t}`)),console.log(I.dim(" The file is created on first SQLite write \u2014 start the daemon and run a task.")),process.exit(1));try{return new Ud(t,{readonly:!0})}catch(n){console.log(I.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(I.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function qd(e){let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!o)return null;let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function Wd(e){if(!e)return;let o=qd(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(I.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}function Bd(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s ago`:o<3600?`${Math.round(o/60)}m ago`:o<86400?`${Math.round(o/3600)}h ago`:`${Math.round(o/86400)}d ago`}function Bs(e){return e==="ok"?I.green:e==="error"||e==="timeout"?I.red:e==="in-flight"?I.yellow:I.dim}Wt.command("list").description("list recent traces (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--agent <id>","filter by agentId").option("--channel <name>","filter by channel (telegram|whatsapp|gitlab|...)").option("--chat <id>","filter by chatId").option("--workflow <runId>","filter by workflowRunId").option("--status <s>","filter by status (in-flight|ok|error|timeout)").option("--since <duration>","limit to traces newer than (e.g. 1h, 24h, 7d)").option("--limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=Js(e),t=rr(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:Wd(e.since),limit:parseInt(e.limit,10)||50});if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(I.dim(" (no traces)"));return}for(let n of t){let s=Bs(n.status)(n.status.padEnd(9)),i=n.durationMs!=null?`${(n.durationMs/1e3).toFixed(2)}s`:"\u2014",r=n.workflowRunId?I.cyan(` wf=${n.workflowRunId}`):"",a=n.inputTokens!=null?I.dim(` ${n.inputTokens}/${n.outputTokens??0} tok`):"";console.log(`${I.dim(n.taskId)} ${s} ${I.bold(n.agentId)}${I.dim(` ${n.channel??"\u2014"}:${n.chatId??"\u2014"}`)}${r} ${I.dim("\xB7")} ${i}${a} ${I.dim(Bd(n.startedAt))}`),n.error&&console.log(` ${I.red("error:")} ${n.error}`)}});Wt.command("show <taskId>").description("show one trace with its full ordered step log").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--json","emit JSON").action((e,o)=>{let t=Js(o),n=$s(t,e);if(n||(console.log(I.red(` No trace at ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}Jd(n.task,n.steps)});function Jd(e,o){let t=Bs(e.status)(e.status);if(console.log(I.bold(`Trace ${e.taskId}`)),console.log(` ${I.dim("agent")} ${e.agentId}`),console.log(` ${I.dim("channel")} ${e.channel??"\u2014"}:${e.chatId??"\u2014"}`),e.workflowRunId){let n=[e.workflowId,e.workflowNodeId].filter(Boolean).join("/");console.log(` ${I.dim("workflow")} ${I.cyan(e.workflowRunId)}${n?I.dim(` (${n})`):""}`)}if(e.intentEventId&&console.log(` ${I.dim("intent")} ${e.intentEventId} ${I.dim(`(${e.intentDecidedBy??"?"})`)}`),e.model&&console.log(` ${I.dim("model")} ${e.model}`),e.resumeSessionId&&console.log(` ${I.dim("resume")} ${e.resumeSessionId.slice(0,12)}\u2026`),e.finalSessionId&&console.log(` ${I.dim("final")} ${e.finalSessionId.slice(0,12)}\u2026`),console.log(` ${I.dim("status")} ${t}`),e.durationMs!=null&&console.log(` ${I.dim("duration")} ${(e.durationMs/1e3).toFixed(2)}s`),(e.inputTokens!=null||e.outputTokens!=null)&&console.log(` ${I.dim("tokens")} in=${e.inputTokens??0} out=${e.outputTokens??0} cache_read=${e.cacheReadTokens??0} cache_create=${e.cacheCreateTokens??0}`),e.error&&console.log(` ${I.red("error")} ${e.error}`),e.messagePreview&&console.log(` ${I.dim("message")} ${e.messagePreview}`),console.log(),o.length===0){console.log(I.dim(" (no recorded steps \u2014 task may have been on a non-streaming tier or completed before any tool call)"));return}console.log(I.bold(`Steps (${o.length}):`));for(let n of o){let s=n.status?Bs(n.status)(n.status):I.dim("\u2014"),i=n.action?I.cyan(n.action):"";if(console.log(` ${I.dim(`#${n.seq}`)} ${I.bold(n.name)}${i?" "+i:""} ${s}${n.ms!=null?I.dim(` ${n.ms}ms`):""}`),n.inputSummary){let r=n.inputSummary.split(`
200
+ labeled rows \u2014 see \`agentx decisions recalibrate\`.`))});Le.command("ask").description("one-off smoke test against a backend (does not record)").requiredOption("--state <text>","the state to evaluate").option("--backend <name>","default mock","mock").option("--model <id>").option("--choice <labels>","comma-separated options for a choice question").option("--noul <question>","a yes/no question").action(async e=>{Xo();let o={};if(e.choice){let s={};for(let i of String(e.choice).split(",").map(r=>r.trim()))i&&(s[i]=null);o.answer=Ko(s,"Which option fits this state?")}e.noul&&(o.verdict=ro(String(e.noul))),Object.keys(o).length===0&&(console.log(U.red(" Give at least one of --choice or --noul.")),process.exit(1));let n=await fs(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as eg}from"commander";import I from"chalk";import{resolve as Wa}from"path";import{existsSync as og}from"fs";import tg from"better-sqlite3";var Jt=new eg().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function Hs(e){let o=Wa(e.cwd??process.cwd()),t=Wa(o,e.path??".agentx/db.sqlite");og(t)||(console.log(I.red(` No db at ${t}`)),console.log(I.dim(" The file is created on first SQLite write \u2014 start the daemon and run a task.")),process.exit(1));try{return new tg(t,{readonly:!0})}catch(n){console.log(I.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(I.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function ng(e){let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!o)return null;let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function sg(e){if(!e)return;let o=ng(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(I.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}function ig(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s ago`:o<3600?`${Math.round(o/60)}m ago`:o<86400?`${Math.round(o/3600)}h ago`:`${Math.round(o/86400)}d ago`}function Gs(e){return e==="ok"?I.green:e==="error"||e==="timeout"?I.red:e==="in-flight"?I.yellow:I.dim}Jt.command("list").description("list recent traces (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--agent <id>","filter by agentId").option("--channel <name>","filter by channel (telegram|whatsapp|gitlab|...)").option("--chat <id>","filter by chatId").option("--workflow <runId>","filter by workflowRunId").option("--status <s>","filter by status (in-flight|ok|error|timeout)").option("--since <duration>","limit to traces newer than (e.g. 1h, 24h, 7d)").option("--limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=Hs(e),t=lr(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:sg(e.since),limit:parseInt(e.limit,10)||50});if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(I.dim(" (no traces)"));return}for(let n of t){let s=Gs(n.status)(n.status.padEnd(9)),i=n.durationMs!=null?`${(n.durationMs/1e3).toFixed(2)}s`:"\u2014",r=n.workflowRunId?I.cyan(` wf=${n.workflowRunId}`):"",a=n.inputTokens!=null?I.dim(` ${n.inputTokens}/${n.outputTokens??0} tok`):"";console.log(`${I.dim(n.taskId)} ${s} ${I.bold(n.agentId)}${I.dim(` ${n.channel??"\u2014"}:${n.chatId??"\u2014"}`)}${r} ${I.dim("\xB7")} ${i}${a} ${I.dim(ig(n.startedAt))}`),n.error&&console.log(` ${I.red("error:")} ${n.error}`)}});Jt.command("show <taskId>").description("show one trace with its full ordered step log").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--json","emit JSON").action((e,o)=>{let t=Hs(o),n=bs(t,e);if(n||(console.log(I.red(` No trace at ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}rg(n.task,n.steps)});function rg(e,o){let t=Gs(e.status)(e.status);if(console.log(I.bold(`Trace ${e.taskId}`)),console.log(` ${I.dim("agent")} ${e.agentId}`),console.log(` ${I.dim("channel")} ${e.channel??"\u2014"}:${e.chatId??"\u2014"}`),e.workflowRunId){let n=[e.workflowId,e.workflowNodeId].filter(Boolean).join("/");console.log(` ${I.dim("workflow")} ${I.cyan(e.workflowRunId)}${n?I.dim(` (${n})`):""}`)}if(e.intentEventId&&console.log(` ${I.dim("intent")} ${e.intentEventId} ${I.dim(`(${e.intentDecidedBy??"?"})`)}`),e.model&&console.log(` ${I.dim("model")} ${e.model}`),e.resumeSessionId&&console.log(` ${I.dim("resume")} ${e.resumeSessionId.slice(0,12)}\u2026`),e.finalSessionId&&console.log(` ${I.dim("final")} ${e.finalSessionId.slice(0,12)}\u2026`),console.log(` ${I.dim("status")} ${t}`),e.durationMs!=null&&console.log(` ${I.dim("duration")} ${(e.durationMs/1e3).toFixed(2)}s`),(e.inputTokens!=null||e.outputTokens!=null)&&console.log(` ${I.dim("tokens")} in=${e.inputTokens??0} out=${e.outputTokens??0} cache_read=${e.cacheReadTokens??0} cache_create=${e.cacheCreateTokens??0}`),e.error&&console.log(` ${I.red("error")} ${e.error}`),e.messagePreview&&console.log(` ${I.dim("message")} ${e.messagePreview}`),console.log(),o.length===0){console.log(I.dim(" (no recorded steps \u2014 task may have been on a non-streaming tier or completed before any tool call)"));return}console.log(I.bold(`Steps (${o.length}):`));for(let n of o){let s=n.status?Gs(n.status)(n.status):I.dim("\u2014"),i=n.action?I.cyan(n.action):"";if(console.log(` ${I.dim(`#${n.seq}`)} ${I.bold(n.name)}${i?" "+i:""} ${s}${n.ms!=null?I.dim(` ${n.ms}ms`):""}`),n.inputSummary){let r=n.inputSummary.split(`
201
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}`)}}Wt.command("replay <taskId>").description("re-run a recorded task against the current agent config (handoff item #11)").option("--cwd <dir>","project root",process.cwd()).option("--path <p>","sqlite db path (relative to --cwd)",".agentx/db.sqlite").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--diff","show original input + output vs new output side-by-side").option("--no-fresh","do NOT freshSession (default is fresh \u2014 required for clean replay)").action(async(e,o)=>{let t=Js(o),n=$s(t,e);n||(console.log(I.red(` task not found: ${e}`)),console.log(I.dim(" agentx trace list \u2014 see what's available")),process.exit(1));let s=n.task,i=s.originalMessage??s.messagePreview;i||(console.log(I.red(` task ${e} has no recorded input message \u2014 cannot replay`)),process.exit(1)),!s.originalMessage&&s.messagePreview!=null&&console.log(I.yellow(" \u26A0 pre-migration-v8 row: input message was capped at 200 chars; replay uses the preview")),console.log(),console.log(I.bold(` replay ${I.cyan(e)}`)),console.log(I.dim(` agent=${s.agentId} channel=${s.channel??"\u2014"} chatId=${s.chatId??"\u2014"}`)),console.log(I.dim(` original status=${s.status} duration=${s.durationMs??"?"}ms tokens=in:${s.inputTokens??0}/out:${s.outputTokens??0}`)),console.log();let a=String(o.daemon).replace(/\/+$/,""),c={agent:s.agentId,message:i,freshSession:o.fresh!==!1,context:{channel:s.channel??"api",chatId:`replay-${e.toLowerCase().slice(-8)}-${Date.now().toString(36)}`}},d=Date.now(),g;try{g=await fetch(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})}catch(f){console.log(I.red(` daemon unreachable at ${a}: ${f.message||f}`)),process.exit(1)}let l=await g.json().catch(()=>({})),p=Date.now()-d;if(g.ok||(console.log(I.red(` replay failed (${g.status}): ${l.error||"unknown error"}`)),process.exit(1)),o.diff){console.log(I.bold(" INPUT (replayed verbatim)")),console.log(),Dn(i),console.log(),console.log(I.bold(` ORIGINAL OUTPUT ${I.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?Dn(s.finalResponse):console.log(I.yellow(" (not captured \u2014 pre-migration-v8 row, or response was empty)")),console.log(),console.log(I.bold(` CURRENT OUTPUT ${I.dim(`status=${l.error?"error":"ok"} ${p}ms tokens=in:${l.usage?.inputTokens??0}/out:${l.usage?.outputTokens??0}`)}`)),console.log(),Dn(l.content??"(empty reply)"),l.error&&console.log(I.red(` error: ${l.error}`)),console.log();let f=(s.finalResponse??"").trim()===(l.content??"").trim();s.finalResponse&&(console.log(f?I.dim(" outputs are identical"):I.yellow(" outputs differ \u2014 read both blocks to see what changed")),console.log())}else console.log(I.green(` \u2713 replayed in ${p}ms`)),console.log(),Dn(l.content??"(empty reply)"),l.error&&console.log(I.red(`
207
- error: ${l.error}`)),console.log(),console.log(I.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function Dn(e){let o=e.split(`
208
- `),t=60,n=o.slice(0,t);for(let s of n)console.log(` ${I.dim("\u2502")} ${s}`);o.length>t&&console.log(` ${I.dim("\u2502")} ${I.dim(`\u2026+${o.length-t} more lines`)}`)}import{Command as Yd}from"commander";import ce from"chalk";import{existsSync as Vd,mkdirSync as Kd,writeFileSync as Xd}from"fs";import{resolve as Ca,join as ja,dirname as Qd}from"path";var Gd=`# AgentX destructive-action guardrails \u2014 global policy
206
+ `).length>8&&console.log(` ${I.dim("\u2026")}`)}n.error&&console.log(` ${I.red("error:")} ${n.error}`)}}Jt.command("replay <taskId>").description("re-run a recorded task against the current agent config (handoff item #11)").option("--cwd <dir>","project root",process.cwd()).option("--path <p>","sqlite db path (relative to --cwd)",".agentx/db.sqlite").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--diff","show original input + output vs new output side-by-side").option("--no-fresh","do NOT freshSession (default is fresh \u2014 required for clean replay)").action(async(e,o)=>{let t=Hs(o),n=bs(t,e);n||(console.log(I.red(` task not found: ${e}`)),console.log(I.dim(" agentx trace list \u2014 see what's available")),process.exit(1));let s=n.task,i=s.originalMessage??s.messagePreview;i||(console.log(I.red(` task ${e} has no recorded input message \u2014 cannot replay`)),process.exit(1)),!s.originalMessage&&s.messagePreview!=null&&console.log(I.yellow(" \u26A0 pre-migration-v8 row: input message was capped at 200 chars; replay uses the preview")),console.log(),console.log(I.bold(` replay ${I.cyan(e)}`)),console.log(I.dim(` agent=${s.agentId} channel=${s.channel??"\u2014"} chatId=${s.chatId??"\u2014"}`)),console.log(I.dim(` original status=${s.status} duration=${s.durationMs??"?"}ms tokens=in:${s.inputTokens??0}/out:${s.outputTokens??0}`)),console.log();let a=String(o.daemon).replace(/\/+$/,""),c={agent:s.agentId,message:i,freshSession:o.fresh!==!1,context:{channel:s.channel??"api",chatId:`replay-${e.toLowerCase().slice(-8)}-${Date.now().toString(36)}`}},l=Date.now(),g;try{g=await fetch(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})}catch(f){console.log(I.red(` daemon unreachable at ${a}: ${f.message||f}`)),process.exit(1)}let d=await g.json().catch(()=>({})),u=Date.now()-l;if(g.ok||(console.log(I.red(` replay failed (${g.status}): ${d.error||"unknown error"}`)),process.exit(1)),o.diff){console.log(I.bold(" INPUT (replayed verbatim)")),console.log(),Mn(i),console.log(),console.log(I.bold(` ORIGINAL OUTPUT ${I.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?Mn(s.finalResponse):console.log(I.yellow(" (not captured \u2014 pre-migration-v8 row, or response was empty)")),console.log(),console.log(I.bold(` CURRENT OUTPUT ${I.dim(`status=${d.error?"error":"ok"} ${u}ms tokens=in:${d.usage?.inputTokens??0}/out:${d.usage?.outputTokens??0}`)}`)),console.log(),Mn(d.content??"(empty reply)"),d.error&&console.log(I.red(` error: ${d.error}`)),console.log();let f=(s.finalResponse??"").trim()===(d.content??"").trim();s.finalResponse&&(console.log(f?I.dim(" outputs are identical"):I.yellow(" outputs differ \u2014 read both blocks to see what changed")),console.log())}else console.log(I.green(` \u2713 replayed in ${u}ms`)),console.log(),Mn(d.content??"(empty reply)"),d.error&&console.log(I.red(`
207
+ error: ${d.error}`)),console.log(),console.log(I.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function Mn(e){let o=e.split(`
208
+ `),t=60,n=o.slice(0,t);for(let s of n)console.log(` ${I.dim("\u2502")} ${s}`);o.length>t&&console.log(` ${I.dim("\u2502")} ${I.dim(`\u2026+${o.length-t} more lines`)}`)}import{Command as dg}from"commander";import le from"chalk";import{existsSync as gg,mkdirSync as mg,writeFileSync as pg}from"fs";import{resolve as Ga,join as Ja,dirname as ug}from"path";var ag=`# AgentX destructive-action guardrails \u2014 global policy
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
- `,Hd=`# Production protected resources.
234
+ `,cg=`# 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
- `,zd=`# Per-agent override for coder-agent. Top-level rules here are auto-scoped to
256
+ `,lg=`# 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
- `,Ia=[{relPath:"policy.yaml",content:Gd},{relPath:"environments/production.yaml",content:Hd},{relPath:"agents/coder-agent.yaml",content:zd}];var xo=new Yd().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function Gs(e){return e==="deny"?ce.red:e==="escalate"||e==="ask"?ce.yellow:e==="warn"?ce.magenta:ce.green}function _n(e){return e.root?Ca(e.root):jr()}xo.command("check").description("PreToolUse hook entrypoint: read a tool-call payload on stdin, emit a Claude Code decision").option("--agent <id>","agent id this workspace belongs to").option("--root <dir>","AgentX install root (holds .agentx/guardrails + .agentx/db.sqlite)").option("--env <name>","environment scope (e.g. production)").action(async e=>{await Ir({root:_n(e),agentId:e.agent,env:e.env}),process.exit(0)});xo.command("test <command>").description("dry-run a command through the policy engine and print the verdict").option("--agent <id>","evaluate as this agent").option("--env <name>","environment scope").option("--tool <name>","tool name","Bash").option("--cwd <dir>","workspace cwd for $VAR/.env resolution",process.cwd()).option("--root <dir>","AgentX install root (policy source)").option("--enforce","evaluate as if mode=enforce (show what WOULD block)").option("--json","emit JSON").action((e,o)=>{let t=_n(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=Tr({tool:o.tool,command:e,cwd:o.cwd,agentId:o.agent,env:o.env},{root:t,agentId:o.agent,env:o.env,modeOverride:n,noAudit:!0});if(o.json){console.log(JSON.stringify({verdict:s,mode:i,ms:r},null,2));return}Zd(s,i,r)});function Zd(e,o,t){let n=Gs(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":ce.dim(" (no rule matched)")}`),console.log(` enforced as ${Gs(e.effectiveAction)(e.effectiveAction)} ${ce.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${ce.cyan(e.ruleId)}${e.severity?ce.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${ce.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${ce.dim(`evaluated in ${t}ms`)}`),console.log()}xo.command("log").description("read the guardrail decision audit trail (newest first)").option("--root <dir>","AgentX install root (holds .agentx/db.sqlite)").option("--verdict <v>","filter by verdict (deny|escalate|warn|allow)").option("--agent <id>","filter by agent").option("--task <id>","filter by task id").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let o=Or({root:_n(e),verdict:e.verdict,agentId:e.agent,taskId:e.task,limit:parseInt(e.limit,10)||30});if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(ce.dim(" (no guardrail decisions recorded yet)"));return}for(let t of o){let n=new Date(t.ts).toISOString().replace("T"," ").slice(0,19),s=Gs(t.verdict),i=t.effective_action!==t.verdict?ce.dim(`->${t.effective_action}`):"";console.log(` ${ce.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${ce.cyan((t.agent_id??"?").padEnd(16))} ${ce.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(ce.dim(` target: ${t.resolved_target}`))}});xo.command("init").description("scaffold .agentx/guardrails/ with a starter policy + protected-resource example").option("--root <dir>","where to create .agentx/guardrails/",process.cwd()).option("--force","overwrite existing files").action(e=>{let o=ja(Ca(e.root),Er),t=0;for(let n of Ia){let s=ja(o,n.relPath);if(Vd(s)&&!e.force){console.log(ce.dim(` skip (exists) ${n.relPath}`));continue}Kd(Qd(s),{recursive:!0}),Xd(s,n.content),console.log(ce.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${ce.cyan(o)}`),console.log(ce.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(ce.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});xo.command("reload").description("signal the daemon to reload (note: guard policy is read live per tool call already)").option("--url <url>","daemon base url",process.env.AGENTX_DAEMON_URL||"http://localhost:19900").action(async e=>{try{let o=await fetch(`${String(e.url).replace(/\/$/,"")}/reload`,{method:"POST"});o.ok?console.log(ce.green(` daemon reloaded (${e.url})`)):console.log(ce.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(ce.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});xo.command("policy").description("print the resolved (merged) policy for an agent").option("--agent <id>","agent id").option("--root <dir>","AgentX install root").action(e=>{let o=Ar(_n(e),e.agent);console.log(JSON.stringify(o,null,2))});It();import{Command as eg}from"commander";import{execFile as og}from"child_process";import{promisify as tg}from"util";import{existsSync as ng}from"fs";import Ye from"chalk";Tt();var Jt="ui-element";function Pn(e){let o=(e.priorAttempts??[]).slice(-4);return{request:e.request,app:e.app,window:e.window??null,...o.length?{alreadyTried:o.map(t=>({control:Bt(t.tried,80),screenChanged:t.changed,note:t.note?Bt(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:Na(t.role),label:Bt(t.label,120),value:t.value?Bt(t.value,80):null,enabled:t.enabled}))}}function Ln(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${Na(t.role)}: ${Bt(n,80)}`}return{target:Yo(o,"Which control does the request refer to? If `alreadyTried` shows a control was clicked and the screen did not change, that one did not work \u2014 choose differently."),present:ao("The screen actually contains a control matching the request.",{true:"One of the listed controls is plainly the thing the request names, or is the obvious way to perform it.",false:"Nothing listed corresponds to the request \u2014 the right control is on another screen, behind a menu, not yet visible, or this application simply cannot do what was asked."})}}function Mn(e,o){let t=e.target,n=o.map(s=>({id:s.id,score:t.probabilities[String(s.id)]??0})).sort((s,i)=>i.score-s.score);return{id:Number(t.choice),confidence:t.confidence,present:e.present.noul,ranked:n}}function Na(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Bt(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}var Ra=tg(og),Da=new eg().name("point").description("point at the on-screen control matching a description (does not click)").argument("<request>",'what you mean, e.g. "the send button"').option("--max <n>","candidates to consider","40").option("--json","emit the decision as JSON instead of pointing").option("--min-present <p>","refuse below this P(control exists)","0.5").action(async(e,o)=>{ng($e)||(console.log(Ye.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await bn({max:Number(o.max)||40})}catch(l){console.log(Ye.red(` could not read the screen: ${l?.message??l}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(Ye.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let l=Dt(t,n[0].id);l&&(console.log(Ye.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+Ye.bold(n[0].label)),await Ra($e,["point","--x",String(l.x),"--y",String(l.y),"--w",String(l.width),"--h",String(l.height),"--label",n[0].label]));return}let s=await Qe(Jt,Pn({request:e,app:t.app,window:t.window,candidates:n}),Ln(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(Ye.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${Jt}.mode`)),process.exit(1));let i=Mn(s.answers,n),r=Dt(t,i.id),a=n.find(l=>l.id===i.id)?.label??"",c=t.ocrRects.has(i.id),d=Number(o.minPresent)||.5;if((i.present<d||!r)&&(console.log(Ye.yellow(` nothing on screen matches "${e}"`)+Ye.dim(` (P(exists)=${i.present.toFixed(2)} below ${d})`)),process.exit(2)),o.json){console.log(JSON.stringify({app:t.app,request:e,chosen:{...r,label:a,fromOCR:c},present:i.present,confidence:i.confidence,ranked:i.ranked.slice(0,5).map(l=>({...l,label:n.find(p=>p.id===l.id)?.label}))},null,2));return}let g=a;console.log(` ${Ye.green("\u2192")} ${Ye.bold(g)} `+Ye.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await Ra($e,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",g])});import{Command as Ig}from"commander";import Le from"chalk";import{execFile as sg}from"child_process";import{promisify as ig}from"util";import{existsSync as rg,readFileSync as Hs}from"fs";import{homedir as ag,tmpdir as cg}from"os";import{join as _a}from"path";var lg=ig(sg),Pa=12e5,dg="https://openrouter.ai/api/v1/chat/completions",gg=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function mg(e={kind:"window"},o=Pa){if(!rg($e))throw new Error("helper not built \u2014 run apps/mac-helper/build.sh");let n=["capture","--out",_a(cg(),`agentx-look-${Date.now()}.png`),"--max-pixels",String(o)];e.kind==="menubar"&&n.push("--menubar"),e.kind==="screen"&&n.push("--screen-full"),(e.kind==="screen"||e.kind==="menubar")&&e.index!==void 0&&n.push("--screen",String(e.index)),e.kind==="rect"&&n.push("--x",String(e.x),"--y",String(e.y),"--w",String(e.width),"--h",String(e.height));let s=await lg($e,n).then(a=>a.stdout,a=>{if(typeof a?.stdout=="string"&&a.stdout.trim().startsWith("{"))return a.stdout;throw a}),i=JSON.parse(s);if(!i.ok)throw new Error(i.error??"capture failed");let r=Hs(i.path).length;return{path:i.path,region:{x:i.region.x,y:i.region.y,width:i.region.w,height:i.region.h},bytes:r}}var pg=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
265
+ `,Ba=[{relPath:"policy.yaml",content:ag},{relPath:"environments/production.yaml",content:cg},{relPath:"agents/coder-agent.yaml",content:lg}];var So=new dg().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function zs(e){return e==="deny"?le.red:e==="escalate"||e==="ask"?le.yellow:e==="warn"?le.magenta:le.green}function Ln(e){return e.root?Ga(e.root):Hr()}So.command("check").description("PreToolUse hook entrypoint: read a tool-call payload on stdin, emit a Claude Code decision").option("--agent <id>","agent id this workspace belongs to").option("--root <dir>","AgentX install root (holds .agentx/guardrails + .agentx/db.sqlite)").option("--env <name>","environment scope (e.g. production)").action(async e=>{await Gr({root:Ln(e),agentId:e.agent,env:e.env}),process.exit(0)});So.command("test <command>").description("dry-run a command through the policy engine and print the verdict").option("--agent <id>","evaluate as this agent").option("--env <name>","environment scope").option("--tool <name>","tool name","Bash").option("--cwd <dir>","workspace cwd for $VAR/.env resolution",process.cwd()).option("--root <dir>","AgentX install root (policy source)").option("--enforce","evaluate as if mode=enforce (show what WOULD block)").option("--json","emit JSON").action((e,o)=>{let t=Ln(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=Jr({tool:o.tool,command:e,cwd:o.cwd,agentId:o.agent,env:o.env},{root:t,agentId:o.agent,env:o.env,modeOverride:n,noAudit:!0});if(o.json){console.log(JSON.stringify({verdict:s,mode:i,ms:r},null,2));return}fg(s,i,r)});function fg(e,o,t){let n=zs(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":le.dim(" (no rule matched)")}`),console.log(` enforced as ${zs(e.effectiveAction)(e.effectiveAction)} ${le.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${le.cyan(e.ruleId)}${e.severity?le.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${le.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${le.dim(`evaluated in ${t}ms`)}`),console.log()}So.command("log").description("read the guardrail decision audit trail (newest first)").option("--root <dir>","AgentX install root (holds .agentx/db.sqlite)").option("--verdict <v>","filter by verdict (deny|escalate|warn|allow)").option("--agent <id>","filter by agent").option("--task <id>","filter by task id").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let o=Zi({root:Ln(e),verdict:e.verdict,agentId:e.agent,taskId:e.task,limit:parseInt(e.limit,10)||30});if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(le.dim(" (no guardrail decisions recorded yet)"));return}for(let t of o){let n=new Date(t.ts).toISOString().replace("T"," ").slice(0,19),s=zs(t.verdict),i=t.effective_action!==t.verdict?le.dim(`->${t.effective_action}`):"";console.log(` ${le.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${le.cyan((t.agent_id??"?").padEnd(16))} ${le.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(le.dim(` target: ${t.resolved_target}`))}});So.command("init").description("scaffold .agentx/guardrails/ with a starter policy + protected-resource example").option("--root <dir>","where to create .agentx/guardrails/",process.cwd()).option("--force","overwrite existing files").action(e=>{let o=Ja(Ga(e.root),Wr),t=0;for(let n of Ba){let s=Ja(o,n.relPath);if(gg(s)&&!e.force){console.log(le.dim(` skip (exists) ${n.relPath}`));continue}mg(ug(s),{recursive:!0}),pg(s,n.content),console.log(le.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${le.cyan(o)}`),console.log(le.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(le.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});So.command("reload").description("signal the daemon to reload (note: guard policy is read live per tool call already)").option("--url <url>","daemon base url",process.env.AGENTX_DAEMON_URL||"http://localhost:19900").action(async e=>{try{let o=await fetch(`${String(e.url).replace(/\/$/,"")}/reload`,{method:"POST"});o.ok?console.log(le.green(` daemon reloaded (${e.url})`)):console.log(le.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(le.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});So.command("policy").description("print the resolved (merged) policy for an agent").option("--agent <id>","agent id").option("--root <dir>","AgentX install root").action(e=>{let o=Br(Ln(e),e.agent);console.log(JSON.stringify(o,null,2))});Ct();import{Command as hg}from"commander";import{execFile as yg}from"child_process";import{promisify as wg}from"util";import{existsSync as bg}from"fs";import Ye from"chalk";jt();var Ht="ui-element";function Fn(e){let o=(e.priorAttempts??[]).slice(-4);return{request:e.request,app:e.app,window:e.window??null,...o.length?{alreadyTried:o.map(t=>({control:Gt(t.tried,80),screenChanged:t.changed,note:t.note?Gt(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:Ha(t.role),label:Gt(t.label,120),value:t.value?Gt(t.value,80):null,enabled:t.enabled}))}}function Un(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${Ha(t.role)}: ${Gt(n,80)}`}return{target:Ko(o,"Which control does the request refer to? If `alreadyTried` shows a control was clicked and the screen did not change, that one did not work \u2014 choose differently."),present:ro("The screen actually contains a control matching the request.",{true:"One of the listed controls is plainly the thing the request names, or is the obvious way to perform it.",false:"Nothing listed corresponds to the request \u2014 the right control is on another screen, behind a menu, not yet visible, or this application simply cannot do what was asked."})}}function qn(e,o){let t=e.target,n=o.map(s=>({id:s.id,score:t.probabilities[String(s.id)]??0})).sort((s,i)=>i.score-s.score);return{id:Number(t.choice),confidence:t.confidence,present:e.present.noul,ranked:n}}function Ha(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Gt(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}var za=wg(yg),Ya=new hg().name("point").description("point at the on-screen control matching a description (does not click)").argument("<request>",'what you mean, e.g. "the send button"').option("--max <n>","candidates to consider","40").option("--json","emit the decision as JSON instead of pointing").option("--min-present <p>","refuse below this P(control exists)","0.5").action(async(e,o)=>{bg($e)||(console.log(Ye.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await vn({max:Number(o.max)||40})}catch(d){console.log(Ye.red(` could not read the screen: ${d?.message??d}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(Ye.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let d=Pt(t,n[0].id);d&&(console.log(Ye.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+Ye.bold(n[0].label)),await za($e,["point","--x",String(d.x),"--y",String(d.y),"--w",String(d.width),"--h",String(d.height),"--label",n[0].label]));return}let s=await Ze(Ht,Fn({request:e,app:t.app,window:t.window,candidates:n}),Un(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(Ye.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${Ht}.mode`)),process.exit(1));let i=qn(s.answers,n),r=Pt(t,i.id),a=n.find(d=>d.id===i.id)?.label??"",c=t.ocrRects.has(i.id),l=Number(o.minPresent)||.5;if((i.present<l||!r)&&(console.log(Ye.yellow(` nothing on screen matches "${e}"`)+Ye.dim(` (P(exists)=${i.present.toFixed(2)} below ${l})`)),process.exit(2)),o.json){console.log(JSON.stringify({app:t.app,request:e,chosen:{...r,label:a,fromOCR:c},present:i.present,confidence:i.confidence,ranked:i.ranked.slice(0,5).map(d=>({...d,label:n.find(u=>u.id===d.id)?.label}))},null,2));return}let g=a;console.log(` ${Ye.green("\u2192")} ${Ye.bold(g)} `+Ye.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await za($e,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",g])});import{Command as Gg}from"commander";import Fe from"chalk";import{execFile as $g}from"child_process";import{promisify as kg}from"util";import{existsSync as vg,readFileSync as Ys}from"fs";import{homedir as xg,tmpdir as Sg}from"os";import{join as Va}from"path";var Eg=kg($g),Ka=12e5,Ag="https://openrouter.ai/api/v1/chat/completions",Og=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function Tg(e={kind:"window"},o=Ka){if(!vg($e))throw new Error("helper not built \u2014 run apps/mac-helper/build.sh");let n=["capture","--out",Va(Sg(),`agentx-look-${Date.now()}.png`),"--max-pixels",String(o)];e.kind==="menubar"&&n.push("--menubar"),e.kind==="screen"&&n.push("--screen-full"),(e.kind==="screen"||e.kind==="menubar")&&e.index!==void 0&&n.push("--screen",String(e.index)),e.kind==="rect"&&n.push("--x",String(e.x),"--y",String(e.y),"--w",String(e.width),"--h",String(e.height));let s=await Eg($e,n).then(a=>a.stdout,a=>{if(typeof a?.stdout=="string"&&a.stdout.trim().startsWith("{"))return a.stdout;throw a}),i=JSON.parse(s);if(!i.ok)throw new Error(i.error??"capture failed");let r=Ys(i.path).length;return{path:i.path,region:{x:i.region.x,y:i.region.y,width:i.region.w,height:i.region.h},bytes:r}}var Ig=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
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 ug(e,o,t,n){let s=hg();if(!s)throw new Error("no OPENROUTER_API_KEY \u2014 looking at the screen needs a vision model (set it, or ~/.agentx/openrouter-key.txt)");let i=Hs(o.path).toString("base64"),r={model:t,max_tokens:700,messages:[{role:"user",content:[{type:"text",text:`Question: ${e}
273
+ Answer "unclear" when the deciding detail is not in frame, too small to read, or covered. "unclear" is a useful answer. A confident guess is not.`;async function jg(e,o,t,n){let s=Ng();if(!s)throw new Error("no OPENROUTER_API_KEY \u2014 looking at the screen needs a vision model (set it, or ~/.agentx/openrouter-key.txt)");let i=Ys(o.path).toString("base64"),r={model:t,max_tokens:700,messages:[{role:"user",content:[{type:"text",text:`Question: ${e}
274
274
 
275
- The image is the region ${fg(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:pg,tools:[{type:"function",function:{name:"report",description:"Report what is visible and how it bears on the question",parameters:{type:"object",properties:{observation:{type:"string",description:"What is visible in the image, factually, in one or two sentences."},evidence:{type:"string",description:"The specific visible detail that decides the question \u2014 where it is and what it looks like. Empty string if no such detail is visible."},reading:{type:"string",enum:["yes","no","unclear"],description:"Answer to the question, or unclear if the pixels do not settle it."}},required:["observation","evidence","reading"]}}}],tool_choice:{type:"function",function:{name:"report"}}},a=new AbortController,c=setTimeout(()=>a.abort(),n),d;try{d=await fetch(dg,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`,"HTTP-Referer":"https://github.com/acme/agentx","X-Title":"agentx"},body:JSON.stringify(r),signal:a.signal})}finally{clearTimeout(c)}if(!d.ok){let u=await d.text().catch(()=>"");throw new Error(`vision model ${d.status}: ${u.slice(0,300)}`)}let g=await d.json(),l=g?.choices?.[0]?.message?.tool_calls?.[0];if(!l?.function?.arguments)throw new Error("vision model returned no structured report");let p=JSON.parse(l.function.arguments),f=p.reading==="yes"||p.reading==="no"?p.reading:"unclear";return{observation:(p.observation??"").trim(),evidence:(p.evidence??"").trim(),reading:f,model:typeof g.model=="string"?g.model:t,usage:{inputTokens:g?.usage?.prompt_tokens??0,outputTokens:g?.usage?.completion_tokens??0}}}async function Fn(e,o={}){let t=Date.now(),n=await mg(o.region??{kind:"window"},o.maxPixels??Pa),s=await ug(e,n,o.model??gg,o.timeoutMs??45e3);return{question:e,observation:s.observation,evidence:s.evidence,reading:s.reading,shot:n,model:s.model,latencyMs:Date.now()-t,usage:s.usage}}function fg(e){let{x:o,y:t,width:n,height:s}=e.region;return t<=1&&s<=40?"the macOS menu bar at the top of the screen":`x=${Math.round(o)} y=${Math.round(t)} ${Math.round(n)}x${Math.round(s)} points`}var Gt;function hg(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(Gt!==void 0)return Gt??void 0;try{let e=Hs(_a(ag(),".agentx","openrouter-key.txt"),"utf-8").trim();Gt=e.length>0?e:null}catch{Gt=null}return Gt??void 0}import{execFile as yg}from"child_process";import{promisify as wg}from"util";var bg=wg(yg),$g=["screencapture"],kg=["Screen Studio","OBS","QuickTime Player","Zoom"];async function Ma(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await vg()),t}async function vg(){let e=await La($g);if(e.length)return{checked:"running screen-capture processes (pgrep)",found:`A screen capture is definitely in progress: ${e.join(", ")}. This process only exists while it is recording, so this settles the question on its own.`};let o=await La(kg);return o.length?{checked:"running screen-capture processes (pgrep)",found:`No standalone capture process. A recorder application IS open (${o.join(", ")}), but its process exists whether or not it is recording, so this neither confirms nor denies. macOS does not expose in-app recording state to this tool, and the menu bar indicator is about six points \u2014 measured as below what the vision models here resolve reliably. Unless something else settles it, this claim cannot be verified.`}:{checked:"running screen-capture processes (pgrep)",found:"No screen-capture process is running and no recorder application is open. Nothing that records the screen from outside an app is active."}}async function La(e){let o=[];for(let t of e)try{let{stdout:n}=await bg("pgrep",["-x",t]),s=n.trim().split(`
276
- `)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}It();Tt();var Fa="screen-state",Ua={observable:ao("The evidence gathered \u2014 the screenshot and the system checks together \u2014 is enough to settle the claim, either way.",{true:"Something in the evidence decides it. Either the observation names a specific visible detail that bears on the claim and was legible, or a system check directly establishes the claim true or false. A system check alone is sufficient: it does not need the image to agree with it, or the image to have shown anything at all.",false:"Nothing decides it. The deciding detail is not in frame, too small or blurred, or covered; the observation only describes context \u2014 which application is open, what the screen generally shows \u2014 without the detail itself; and no system check settles it either. Absence of evidence in a capture that could not have shown the evidence is not evidence of absence. This is also false when a check says the question is not answerable from a screenshot and the observation nonetheless claims to have seen it: that is a guess, however specific it sounds."}),holds:ao("The claim is true of the screen right now.",{true:"The visible evidence shows the claimed state is in effect: the indicator is present, the text is there, the element is visible and unobstructed, the action has plainly already happened.",false:"The visible evidence shows the claimed state is NOT in effect. An application being open, capable of the action, or offering it, is not the action having happened \u2014 a recorder on screen is not a recording, an unpressed button is not a pressed one, an offered dialog is not a chosen one. A system check that directly contradicts the observation outweighs it: the checks are deterministic readings of the machine, the observation is a model's reading of an image."})};function qa(e){return{claim:e.claim,capturedRegion:e.region,whatWasSeen:e.observation,decidingDetail:e.evidence||null,visionModelReading:e.reading,...e.treeNote?{accessibilityTree:e.treeNote}:{},...e.probes?.length?{systemChecks:e.probes}:{}}}function Wa(e){return{observable:e.observable.noul,holds:e.holds.noul}}var xg=.6,Sg=.7,Eg=.3;async function Ht(e,o={}){let[t,n]=await Promise.all([Fn(e,o),Ma(e).catch(()=>[])]),s=o.observableFloor??xg,i=await Qe(Fa,qa({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:Tg(t),treeNote:o.treeNote,probes:n}),Ua,{incumbent:{holds:t.reading==="yes"?1:0},features:{model:t.model,region:t.shot.region.height<=40?"menubar":"window"}});if(!i){let d=t.reading==="yes"?"confirmed":t.reading==="no"?"refuted":"unknown";return{claim:e,outcome:d,ok:d==="confirmed",observable:null,holds:null,calibrated:!1,reason:Og(d,t),sighting:t,probes:n}}let{observable:r,holds:a}=Wa(i.answers);if(r<s)return{claim:e,outcome:"unknown",ok:!1,observable:r,holds:a,calibrated:!0,reason:`Could not tell from the screenshot or the system checks (${Un(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=Sg?"confirmed":a<=Eg?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:Ag(c,a,t),sighting:t,probes:n}}function Ag(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${Un(o)}). ${n}`:e==="refuted"?`Not true (${Un(1-o)} it is false). ${n}`:`Inconclusive (${Un(o)}, between the thresholds). ${n}`}function Og(e,o){let t=o.evidence||o.observation||"no specific detail",n=" \u2014 uncalibrated, the screen-state seat is off";return e==="unknown"?`Could not tell${n}. ${t}`:`${e==="confirmed"?"Looks true":"Looks false"}${n}. ${t}`}function Tg(e){let o=e.shot.region;return o.y<=1&&o.height<=40?"the macOS menu bar":`a ${Math.round(o.width)}x${Math.round(o.height)} region of the screen`}var Un=e=>`${Math.round(e*100)}%`;var Ba=new Ig().name("look").description("look at the screen with a vision model \u2014 for state the tree and OCR cannot see").argument("<question>",'what you want to know, e.g. "is a dialog covering the page?"').option("--verify","treat the argument as a claim and judge it (exit 3 refuted, 4 unknown)").option("--menubar","capture the menu bar instead of the focused window").option("--screen","capture the whole screen instead of the focused window").option("--rect <x,y,w,h>","capture an explicit region").option("--model <id>","vision model to use").option("--json","emit the result as JSON").action(async(e,o)=>{let t={kind:"window"};if(o.menubar)t={kind:"menubar"};else if(o.screen)t={kind:"screen"};else if(o.rect){let n=String(o.rect).split(",").map(Number);(n.length!==4||n.some(Number.isNaN))&&(console.log(Le.red(" --rect wants x,y,w,h")),process.exit(1)),t={kind:"rect",x:n[0],y:n[1],width:n[2],height:n[3]}}try{if(o.verify){let s=await Ht(e,{region:t,model:o.model});if(o.json)console.log(JSON.stringify({claim:s.claim,outcome:s.outcome,ok:s.ok,observable:s.observable,holds:s.holds,calibrated:s.calibrated,reason:s.reason,evidence:s.sighting.evidence,probes:s.probes,observation:s.sighting.observation,shot:s.sighting.shot.path,model:s.sighting.model,latencyMs:s.sighting.latencyMs},null,2));else{let i=s.outcome==="confirmed"?Le.green("\u2713"):s.outcome==="refuted"?Le.red("\u2717"):Le.yellow("?");console.log(` ${i} ${Le.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(Le.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(Le.dim(` ${s.sighting.model} \xB7 ${s.sighting.latencyMs}ms \xB7 ${s.sighting.shot.path}`))}process.exit(s.outcome==="confirmed"?0:s.outcome==="refuted"?3:4)}let n=await Fn(e,{region:t,model:o.model});if(o.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${Le.bold(n.observation)}`),n.evidence&&console.log(Le.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${jg(n.reading)}`),console.log(Le.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(Le.red(` ${n?.message??n}`)),process.exit(1)}});function jg(e){return e==="yes"?Le.green(e):e==="no"?Le.red(e):Le.yellow(e)}It();import{Command as Rg}from"commander";import{execFile as Xa}from"child_process";import{promisify as Dg}from"util";import{existsSync as _g,readFileSync as Pg,writeFileSync as Qa,mkdirSync as Lg}from"fs";import{homedir as Mg}from"os";import{join as Fg,dirname as Ug}from"path";import je from"chalk";Tt();var zs="paste-transform";function Ja(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function Ga(e){let o={};for(let t of e)o[t.id]=t.criterion;return{worthChanging:ao("The text is in the wrong shape for where it is being pasted, and a mechanical reshaping would fix it.",{true:"The destination renders or stores formatted text, and the clipboard arrived in a shape that will not come out right: lines hard-wrapped mid-sentence going into prose, a link carrying campaign or tracking parameters, JSON collapsed onto one line, separate items going somewhere that renders a list, text padded with stray whitespace from a web page. The fix is mechanical and is what the person would have done by hand after pasting.",false:"The text is already in the right shape for this destination, OR its exact bytes carry meaning that reformatting would destroy \u2014 a credential, a command, a path, code, an identifier, a search query \u2014 OR the destination is a terminal, a password field, a URL bar or a code editor, where introduced formatting would corrupt what is pasted."}),shape:Yo(o,"What shape should this paste arrive in?")}}function Ha(e){let o=e.worthChanging,t=e.shape,n=Object.entries(t.probabilities??{}).map(([s,i])=>({id:s,p:Number(i)||0})).sort((s,i)=>i.p-s.p);return{worthChanging:o.noul,id:t.choice,confidence:t.confidence,ranked:n}}var Cg=new Set(["utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id","gclid","fbclid","mc_cid","mc_eid","igshid","ref_src","ref_url","s","si","spm","scid","twclid","yclid","_hsenc","_hsmi"]),Ng=e=>/^https?:\/\/\S+$/i.test(e.trim()),Ys=[{id:"asIs",criterion:"Paste it unchanged. The text is already in the right shape for where it is going, or it is something whose exact bytes matter \u2014 a password, a token, a command, code, an identifier.",label:"unchanged",apply:e=>e},{id:"unwrap",criterion:"Join lines that were hard-wrapped back into continuous paragraphs, keeping blank lines as paragraph breaks. For text copied out of a PDF, an email or a terminal, where every line ends at a fixed width mid-sentence.",label:"unwrap lines",apply:e=>{let o=e.split(`
275
+ The image is the region ${Cg(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:Ig,tools:[{type:"function",function:{name:"report",description:"Report what is visible and how it bears on the question",parameters:{type:"object",properties:{observation:{type:"string",description:"What is visible in the image, factually, in one or two sentences."},evidence:{type:"string",description:"The specific visible detail that decides the question \u2014 where it is and what it looks like. Empty string if no such detail is visible."},reading:{type:"string",enum:["yes","no","unclear"],description:"Answer to the question, or unclear if the pixels do not settle it."}},required:["observation","evidence","reading"]}}}],tool_choice:{type:"function",function:{name:"report"}}},a=new AbortController,c=setTimeout(()=>a.abort(),n),l;try{l=await fetch(Ag,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`,"HTTP-Referer":"https://github.com/acme/agentx","X-Title":"agentx"},body:JSON.stringify(r),signal:a.signal})}finally{clearTimeout(c)}if(!l.ok){let p=await l.text().catch(()=>"");throw new Error(`vision model ${l.status}: ${p.slice(0,300)}`)}let g=await l.json(),d=g?.choices?.[0]?.message?.tool_calls?.[0];if(!d?.function?.arguments)throw new Error("vision model returned no structured report");let u=JSON.parse(d.function.arguments),f=u.reading==="yes"||u.reading==="no"?u.reading:"unclear";return{observation:(u.observation??"").trim(),evidence:(u.evidence??"").trim(),reading:f,model:typeof g.model=="string"?g.model:t,usage:{inputTokens:g?.usage?.prompt_tokens??0,outputTokens:g?.usage?.completion_tokens??0}}}async function Wn(e,o={}){let t=Date.now(),n=await Tg(o.region??{kind:"window"},o.maxPixels??Ka),s=await jg(e,n,o.model??Og,o.timeoutMs??45e3);return{question:e,observation:s.observation,evidence:s.evidence,reading:s.reading,shot:n,model:s.model,latencyMs:Date.now()-t,usage:s.usage}}function Cg(e){let{x:o,y:t,width:n,height:s}=e.region;return t<=1&&s<=40?"the macOS menu bar at the top of the screen":`x=${Math.round(o)} y=${Math.round(t)} ${Math.round(n)}x${Math.round(s)} points`}var zt;function Ng(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(zt!==void 0)return zt??void 0;try{let e=Ys(Va(xg(),".agentx","openrouter-key.txt"),"utf-8").trim();zt=e.length>0?e:null}catch{zt=null}return zt??void 0}import{execFile as Rg}from"child_process";import{promisify as Dg}from"util";var _g=Dg(Rg),Pg=["screencapture"],Mg=["Screen Studio","OBS","QuickTime Player","Zoom"];async function Qa(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await Lg()),t}async function Lg(){let e=await Xa(Pg);if(e.length)return{checked:"running screen-capture processes (pgrep)",found:`A screen capture is definitely in progress: ${e.join(", ")}. This process only exists while it is recording, so this settles the question on its own.`};let o=await Xa(Mg);return o.length?{checked:"running screen-capture processes (pgrep)",found:`No standalone capture process. A recorder application IS open (${o.join(", ")}), but its process exists whether or not it is recording, so this neither confirms nor denies. macOS does not expose in-app recording state to this tool, and the menu bar indicator is about six points \u2014 measured as below what the vision models here resolve reliably. Unless something else settles it, this claim cannot be verified.`}:{checked:"running screen-capture processes (pgrep)",found:"No screen-capture process is running and no recorder application is open. Nothing that records the screen from outside an app is active."}}async function Xa(e){let o=[];for(let t of e)try{let{stdout:n}=await _g("pgrep",["-x",t]),s=n.trim().split(`
276
+ `)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}Ct();jt();var Za="screen-state",ec={observable:ro("The evidence gathered \u2014 the screenshot and the system checks together \u2014 is enough to settle the claim, either way.",{true:"Something in the evidence decides it. Either the observation names a specific visible detail that bears on the claim and was legible, or a system check directly establishes the claim true or false. A system check alone is sufficient: it does not need the image to agree with it, or the image to have shown anything at all.",false:"Nothing decides it. The deciding detail is not in frame, too small or blurred, or covered; the observation only describes context \u2014 which application is open, what the screen generally shows \u2014 without the detail itself; and no system check settles it either. Absence of evidence in a capture that could not have shown the evidence is not evidence of absence. This is also false when a check says the question is not answerable from a screenshot and the observation nonetheless claims to have seen it: that is a guess, however specific it sounds."}),holds:ro("The claim is true of the screen right now.",{true:"The visible evidence shows the claimed state is in effect: the indicator is present, the text is there, the element is visible and unobstructed, the action has plainly already happened.",false:"The visible evidence shows the claimed state is NOT in effect. An application being open, capable of the action, or offering it, is not the action having happened \u2014 a recorder on screen is not a recording, an unpressed button is not a pressed one, an offered dialog is not a chosen one. A system check that directly contradicts the observation outweighs it: the checks are deterministic readings of the machine, the observation is a model's reading of an image."})};function oc(e){return{claim:e.claim,capturedRegion:e.region,whatWasSeen:e.observation,decidingDetail:e.evidence||null,visionModelReading:e.reading,...e.treeNote?{accessibilityTree:e.treeNote}:{},...e.probes?.length?{systemChecks:e.probes}:{}}}function tc(e){return{observable:e.observable.noul,holds:e.holds.noul}}var Fg=.6,Ug=.7,qg=.3;async function Yt(e,o={}){let[t,n]=await Promise.all([Wn(e,o),Qa(e).catch(()=>[])]),s=o.observableFloor??Fg,i=await Ze(Za,oc({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:Jg(t),treeNote:o.treeNote,probes:n}),ec,{incumbent:{holds:t.reading==="yes"?1:0},features:{model:t.model,region:t.shot.region.height<=40?"menubar":"window"}});if(!i){let l=t.reading==="yes"?"confirmed":t.reading==="no"?"refuted":"unknown";return{claim:e,outcome:l,ok:l==="confirmed",observable:null,holds:null,calibrated:!1,reason:Bg(l,t),sighting:t,probes:n}}let{observable:r,holds:a}=tc(i.answers);if(r<s)return{claim:e,outcome:"unknown",ok:!1,observable:r,holds:a,calibrated:!0,reason:`Could not tell from the screenshot or the system checks (${Bn(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=Ug?"confirmed":a<=qg?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:Wg(c,a,t),sighting:t,probes:n}}function Wg(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${Bn(o)}). ${n}`:e==="refuted"?`Not true (${Bn(1-o)} it is false). ${n}`:`Inconclusive (${Bn(o)}, between the thresholds). ${n}`}function Bg(e,o){let t=o.evidence||o.observation||"no specific detail",n=" \u2014 uncalibrated, the screen-state seat is off";return e==="unknown"?`Could not tell${n}. ${t}`:`${e==="confirmed"?"Looks true":"Looks false"}${n}. ${t}`}function Jg(e){let o=e.shot.region;return o.y<=1&&o.height<=40?"the macOS menu bar":`a ${Math.round(o.width)}x${Math.round(o.height)} region of the screen`}var Bn=e=>`${Math.round(e*100)}%`;var nc=new Gg().name("look").description("look at the screen with a vision model \u2014 for state the tree and OCR cannot see").argument("<question>",'what you want to know, e.g. "is a dialog covering the page?"').option("--verify","treat the argument as a claim and judge it (exit 3 refuted, 4 unknown)").option("--menubar","capture the menu bar instead of the focused window").option("--screen","capture the whole screen instead of the focused window").option("--rect <x,y,w,h>","capture an explicit region").option("--model <id>","vision model to use").option("--json","emit the result as JSON").action(async(e,o)=>{let t={kind:"window"};if(o.menubar)t={kind:"menubar"};else if(o.screen)t={kind:"screen"};else if(o.rect){let n=String(o.rect).split(",").map(Number);(n.length!==4||n.some(Number.isNaN))&&(console.log(Fe.red(" --rect wants x,y,w,h")),process.exit(1)),t={kind:"rect",x:n[0],y:n[1],width:n[2],height:n[3]}}try{if(o.verify){let s=await Yt(e,{region:t,model:o.model});if(o.json)console.log(JSON.stringify({claim:s.claim,outcome:s.outcome,ok:s.ok,observable:s.observable,holds:s.holds,calibrated:s.calibrated,reason:s.reason,evidence:s.sighting.evidence,probes:s.probes,observation:s.sighting.observation,shot:s.sighting.shot.path,model:s.sighting.model,latencyMs:s.sighting.latencyMs},null,2));else{let i=s.outcome==="confirmed"?Fe.green("\u2713"):s.outcome==="refuted"?Fe.red("\u2717"):Fe.yellow("?");console.log(` ${i} ${Fe.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(Fe.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(Fe.dim(` ${s.sighting.model} \xB7 ${s.sighting.latencyMs}ms \xB7 ${s.sighting.shot.path}`))}process.exit(s.outcome==="confirmed"?0:s.outcome==="refuted"?3:4)}let n=await Wn(e,{region:t,model:o.model});if(o.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${Fe.bold(n.observation)}`),n.evidence&&console.log(Fe.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${Hg(n.reading)}`),console.log(Fe.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(Fe.red(` ${n?.message??n}`)),process.exit(1)}});function Hg(e){return e==="yes"?Fe.green(e):e==="no"?Fe.red(e):Fe.yellow(e)}Ct();import{Command as Vg}from"commander";import{execFile as gc}from"child_process";import{promisify as Kg}from"util";import{existsSync as Xg,readFileSync as Qg,writeFileSync as mc,mkdirSync as Zg}from"fs";import{homedir as em}from"os";import{join as om,dirname as tm}from"path";import Ce from"chalk";jt();var Vs="paste-transform";function sc(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function ic(e){let o={};for(let t of e)o[t.id]=t.criterion;return{worthChanging:ro("The text is in the wrong shape for where it is being pasted, and a mechanical reshaping would fix it.",{true:"The destination renders or stores formatted text, and the clipboard arrived in a shape that will not come out right: lines hard-wrapped mid-sentence going into prose, a link carrying campaign or tracking parameters, JSON collapsed onto one line, separate items going somewhere that renders a list, text padded with stray whitespace from a web page. The fix is mechanical and is what the person would have done by hand after pasting.",false:"The text is already in the right shape for this destination, OR its exact bytes carry meaning that reformatting would destroy \u2014 a credential, a command, a path, code, an identifier, a search query \u2014 OR the destination is a terminal, a password field, a URL bar or a code editor, where introduced formatting would corrupt what is pasted."}),shape:Ko(o,"What shape should this paste arrive in?")}}function rc(e){let o=e.worthChanging,t=e.shape,n=Object.entries(t.probabilities??{}).map(([s,i])=>({id:s,p:Number(i)||0})).sort((s,i)=>i.p-s.p);return{worthChanging:o.noul,id:t.choice,confidence:t.confidence,ranked:n}}var zg=new Set(["utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id","gclid","fbclid","mc_cid","mc_eid","igshid","ref_src","ref_url","s","si","spm","scid","twclid","yclid","_hsenc","_hsmi"]),Yg=e=>/^https?:\/\/\S+$/i.test(e.trim()),Ks=[{id:"asIs",criterion:"Paste it unchanged. The text is already in the right shape for where it is going, or it is something whose exact bytes matter \u2014 a password, a token, a command, code, an identifier.",label:"unchanged",apply:e=>e},{id:"unwrap",criterion:"Join lines that were hard-wrapped back into continuous paragraphs, keeping blank lines as paragraph breaks. For text copied out of a PDF, an email or a terminal, where every line ends at a fixed width mid-sentence.",label:"unwrap lines",apply:e=>{let o=e.split(`
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,37 +281,64 @@ The image is the region ${fg(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(!Ng(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])Cg.has(s.toLowerCase())&&(t.searchParams.delete(s),n++);return n===0?null:t.toString().replace(/\?$/,"")}catch{return null}}},{id:"slug",criterion:"Convert to a lowercase hyphenated slug. For a title or phrase going into a branch name, a filename or a URL path.",label:"slug",apply:e=>{let o=e.trim();if(o.includes(`
284
+ `)}},{id:"codeFence",criterion:"Wrap it in a fenced code block. For code, a command, a log line or structured output going somewhere that renders markdown.",label:"code block",apply:e=>e.trim().startsWith("```")?null:"```\n"+e.replace(/\n+$/,"")+"\n```"},{id:"prettyJson",criterion:"Re-indent it as readable JSON. Only for text that already parses as JSON.",label:"format JSON",apply:e=>{let o=e.trim();if(!/^[[{]/.test(o))return null;try{let t=JSON.parse(o),n=JSON.stringify(t,null,2);return n===o?null:n}catch{return null}}},{id:"cleanUrl",criterion:"Strip campaign and tracking parameters from the link, keeping the rest of it intact. For a URL copied out of a share sheet, a newsletter or a social post.",label:"clean the link",apply:e=>{let o=e.trim();if(!Yg(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])zg.has(s.toLowerCase())&&(t.searchParams.delete(s),n++);return n===0?null:t.toString().replace(/\?$/,"")}catch{return null}}},{id:"slug",criterion:"Convert to a lowercase hyphenated slug. For a title or phrase going into a branch name, a filename or a URL path.",label:"slug",apply:e=>{let o=e.trim();if(o.includes(`
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 za(e){let o=[];for(let t of Ys){let n=t.apply(e);n!==null&&(t.id!=="asIs"&&n===e||o.push({transform:t,result:n}))}return o}function Ya(e,o=320){if(e.length<=o)return e;let t=Math.floor(o*.7),n=o-t;return`${e.slice(0,t)}
286
+ `).trim();return o===e?null:o}}];function ac(e){let o=[];for(let t of Ks){let n=t.apply(e);n!==null&&(t.id!=="asIs"&&n===e||o.push({transform:t,result:n}))}return o}function cc(e,o=320){if(e.length<=o)return e;let t=Math.floor(o*.7),n=o-t;return`${e.slice(0,t)}
287
287
  \u2026[${e.length-o} more characters]\u2026
288
- ${e.slice(-n)}`}function Va(e){let o=e.trim();return o.includes(`
289
- `)||o.length>200?!1:/^(sk|pk|ghp|gho|ghs|glpat|xox[abps])[-_][A-Za-z0-9_-]{16,}$/.test(o)||/^[A-Za-z0-9+/]{40,}={0,2}$/.test(o)||/^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\./.test(o)||o.length>=20&&!/\s/.test(o)&&/[A-Z]/.test(o)&&/[a-z]/.test(o)&&/\d/.test(o)&&!/^https?:\/\//i.test(o)&&!/\.(com|org|net|io|ai|tn)$/i.test(o)}var Vs=Dg(Xa),Za=new Rg().name("paste").description("reshape the clipboard to fit where it is being pasted").option("--apply","write the result back to the clipboard").option("--paste","apply, then press cmd-V into the focused control").option("--as <id>",`force a transform (${Ys.map(e=>e.id).join(", ")})`).option("--min <p>","minimum P(worth changing) before transforming","0.45").option("--undo","restore the clipboard as it was before the last apply").option("--json","emit the decision as JSON").action(async e=>{if(e.undo){let c=Wg();c===null&&(console.log(je.yellow(" nothing to undo")),process.exit(2)),await oc(c),console.log(` ${je.green("\u2192")} clipboard restored`);return}let o=await Bg();if(o||(console.log(je.yellow(" clipboard is empty")),process.exit(2)),Va(o)){ec(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=za(o),n=await Jg();if(e.as){let c=t.find(d=>d.transform.id===e.as);c||(console.log(je.red(` "${e.as}" does not apply to this clipboard`)),console.log(je.dim(` available: ${t.map(d=>d.transform.id).join(", ")}`)),process.exit(1)),await gt(e,c.transform.id,c.result,o,"forced",1);return}if(t.length<2){await gt(e,"asIs",o,o,"nothing else applies",0);return}let s=await Qe(zs,Ja({preview:Ya(o),length:o.length,lineCount:o.split(`
290
- `).length,app:n.app,destination:n.role,destinationLabel:n.label}),Ga(t.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:t.length,chars:o.length}});if(!s){await gt(e,"asIs",o,o,`seat unavailable \u2014 set decisions.seats.${zs}.mode`,0);return}let i=Ha(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await gt(e,"asIs",o,o,`paste as copied (P(worth changing) ${i.worthChanging.toFixed(2)} below ${r})`,i.worthChanging);return}let a=t.find(c=>c.transform.id===i.id);if(!a){await gt(e,"asIs",o,o,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await gt(e,a.transform.id,a.result,o,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function gt(e,o,t,n,s,i){let r=t!==n;r&&(e.apply||e.paste)&&(qg(n),await oc(t)),ec(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await Vs($e,["key","--name","v","--mod","command"]).catch(a=>{console.log(je.red(` could not paste: ${a?.message??a}`))})}function ec(e,o){if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.changed){console.log(` ${je.dim("\u2192")} ${je.bold("unchanged")} ${je.dim(`\xB7 ${o.reason}`)}`);return}console.log(` ${je.green("\u2192")} ${je.bold(o.applied)} ${je.dim(`\xB7 ${o.reason}`)}`),console.log(je.dim(" \u2500\u2500\u2500 before \u2500\u2500\u2500")),console.log(je.dim(Ka(o.original))),console.log(je.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(Ka(o.result)),!e.apply&&!e.paste&&console.log(je.dim(`
291
- (dry run \u2014 pass --apply to write it back)`))}var Ka=(e,o=400)=>(e.length>o?`${e.slice(0,o)}\u2026`:e).split(`
288
+ ${e.slice(-n)}`}function lc(e){let o=e.trim();return o.includes(`
289
+ `)||o.length>200?!1:/^(sk|pk|ghp|gho|ghs|glpat|xox[abps])[-_][A-Za-z0-9_-]{16,}$/.test(o)||/^[A-Za-z0-9+/]{40,}={0,2}$/.test(o)||/^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\./.test(o)||o.length>=20&&!/\s/.test(o)&&/[A-Z]/.test(o)&&/[a-z]/.test(o)&&/\d/.test(o)&&!/^https?:\/\//i.test(o)&&!/\.(com|org|net|io|ai|tn)$/i.test(o)}var Xs=Kg(gc),pc=new Vg().name("paste").description("reshape the clipboard to fit where it is being pasted").option("--apply","write the result back to the clipboard").option("--paste","apply, then press cmd-V into the focused control").option("--as <id>",`force a transform (${Ks.map(e=>e.id).join(", ")})`).option("--min <p>","minimum P(worth changing) before transforming","0.45").option("--undo","restore the clipboard as it was before the last apply").option("--json","emit the decision as JSON").action(async e=>{if(e.undo){let c=sm();c===null&&(console.log(Ce.yellow(" nothing to undo")),process.exit(2)),await fc(c),console.log(` ${Ce.green("\u2192")} clipboard restored`);return}let o=await im();if(o||(console.log(Ce.yellow(" clipboard is empty")),process.exit(2)),lc(o)){uc(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=ac(o),n=await rm();if(e.as){let c=t.find(l=>l.transform.id===e.as);c||(console.log(Ce.red(` "${e.as}" does not apply to this clipboard`)),console.log(Ce.dim(` available: ${t.map(l=>l.transform.id).join(", ")}`)),process.exit(1)),await pt(e,c.transform.id,c.result,o,"forced",1);return}if(t.length<2){await pt(e,"asIs",o,o,"nothing else applies",0);return}let s=await Ze(Vs,sc({preview:cc(o),length:o.length,lineCount:o.split(`
290
+ `).length,app:n.app,destination:n.role,destinationLabel:n.label}),ic(t.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:t.length,chars:o.length}});if(!s){await pt(e,"asIs",o,o,`seat unavailable \u2014 set decisions.seats.${Vs}.mode`,0);return}let i=rc(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await pt(e,"asIs",o,o,`paste as copied (P(worth changing) ${i.worthChanging.toFixed(2)} below ${r})`,i.worthChanging);return}let a=t.find(c=>c.transform.id===i.id);if(!a){await pt(e,"asIs",o,o,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await pt(e,a.transform.id,a.result,o,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function pt(e,o,t,n,s,i){let r=t!==n;r&&(e.apply||e.paste)&&(nm(n),await fc(t)),uc(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await Xs($e,["key","--name","v","--mod","command"]).catch(a=>{console.log(Ce.red(` could not paste: ${a?.message??a}`))})}function uc(e,o){if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.changed){console.log(` ${Ce.dim("\u2192")} ${Ce.bold("unchanged")} ${Ce.dim(`\xB7 ${o.reason}`)}`);return}console.log(` ${Ce.green("\u2192")} ${Ce.bold(o.applied)} ${Ce.dim(`\xB7 ${o.reason}`)}`),console.log(Ce.dim(" \u2500\u2500\u2500 before \u2500\u2500\u2500")),console.log(Ce.dim(dc(o.original))),console.log(Ce.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(dc(o.result)),!e.apply&&!e.paste&&console.log(Ce.dim(`
291
+ (dry run \u2014 pass --apply to write it back)`))}var dc=(e,o=400)=>(e.length>o?`${e.slice(0,o)}\u2026`:e).split(`
292
292
  `).map(t=>` ${t}`).join(`
293
- `),qn=Fg(Mg(),".agentx","paste-undo.txt");function qg(e){try{Lg(Ug(qn),{recursive:!0}),Qa(qn,e,{mode:384})}catch{}}function Wg(){try{let e=Pg(qn,"utf-8");return Qa(qn,"",{mode:384}),e.length?e:null}catch{return null}}async function Bg(){let{stdout:e}=await Vs("pbpaste",[],{maxBuffer:16777216});return e}async function oc(e){await new Promise((o,t)=>{Xa("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function Jg(){if(!_g($e))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await Vs($e,["focused"]),o=JSON.parse(e);return o.ok===!1||!o.role?{app:"unknown",role:"an unknown control",label:null}:{app:o.app??"unknown",role:Gg(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function Gg(e,o){return{AXTextField:"a single-line text field",AXTextArea:"a multi-line text area",AXSearchField:"a search field",AXComboBox:"a combo box",AXSecureTextField:"a password field"}[e]??(o?"an editable control":`a ${e||"unknown"} control`)}import{Command as Hg}from"commander";import Ve from"chalk";var zg=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function Yg(e,o){return async({title:t,message:n,channel:s,chatId:i})=>{let r=t&&!n.startsWith(t)?`${t}
294
- ${n}`:n,a=await fetch(`${zg}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:s??e,chatId:i??o,text:r})});if(!a.ok)throw new Error(`daemon ${a.status}: ${(await a.text().catch(()=>"")).slice(0,200)}`)}}var tc=new Hg().name("notify").description("tell the operator something, holding it if they are in Focus").argument("[message]","what to say").option("--from <who>","who is speaking","agentx").option("--title <text>","notification title","Secretary").option("--priority <n>","1 (min) to 5 (max)","4").option("--urgent","deliver even during Focus").option("--channel <name>","delivery channel","ntfy").option("--chat-id <id>","channel address","default").option("--no-sound","do not play a sound on this machine").option("--status","show Focus state and anything being held").option("--flush","deliver everything held, as one message").option("--json","emit the result as JSON").action(async(e,o)=>{let t=new $r,n=wr(),s=o.sound===!1?!1:void 0;if(o.status){let r=t.list();if(o.json){console.log(JSON.stringify({focus:n,held:r},null,2));return}console.log(` ${n.active?Ve.yellow("\u25D0"):Ve.green("\u25CB")} ${br(n)} ${Ve.dim(`\xB7 ${n.reason}`)}`),console.log(` ${r.length} held`);for(let a of r.slice(0,8)){let c=new Date(a.at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(Ve.dim(` ${c} ${a.from}: ${a.message.slice(0,70)}`))}return}let i=Yg(o.channel,o.chatId);if(o.flush){let r=await vr(i,{queue:t,sound:s});console.log(r?Ve.green(` delivered ${r} held notification(s)`):Ve.dim(" nothing was held"));return}e?.trim()||(console.log(Ve.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let r=await kr({message:e.trim(),from:o.from,title:o.title,priority:Number(o.priority)||4,urgent:!!o.urgent,channel:o.channel,chatId:o.chatId},i,{queue:t,sound:s,focus:n});if(o.json){console.log(JSON.stringify(r,null,2));return}let a=r.delivered?Ve.green("\u2192"):Ve.yellow("\u23F8");console.log(` ${a} ${r.reason}`),r.held&&console.log(Ve.dim(" it will arrive with the others when Focus ends"))}catch(r){console.log(Ve.red(` ${r?.message??r}`)),s!==!1&&xr(),process.exit(1)}});It();Gi();Li();Tt();import{Command as Vg}from"commander";import{readFileSync as Kg}from"fs";var nc=new Vg().name("decide").description("ask a typed question about some state and get a calibrated answer back").option("--file <path>","spec JSON file (default: stdin)").option("--backend <name>","decision backend","typesafe").option("--seat <name>","seat name the answers are recorded under","adhoc").option("--no-record","answer without writing a row").option("--timeout <ms>","abandon the call after this long","20000").action(async e=>{let o;try{o=e.file?Kg(e.file,"utf8"):await Xg()}catch(r){Uo(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return Uo("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return Uo(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return Uo("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return Uo("spec needs at least one entry in `questions`");try{Fi(t.questions)}catch(r){return Uo(r?.message??String(r))}let n=t.seat||e.seat;Vo(),process.env[zi(n)]="active";let s=null;if(e.record!==!1)try{s=new ln({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
295
- `)}Hi({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await Qe(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return Uo(`the ${e.backend} backend did not answer \u2014 check the key and that the seat is reachable`);console.log(JSON.stringify({ok:!0,seat:n,callId:i.callId,answers:i.answers},null,2)),s?.close()});function Uo(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function Xg(){if(process.stdin.isTTY)return"";let e=[];for await(let o of process.stdin)e.push(Buffer.from(o));return Buffer.concat(e).toString("utf8")}It();import{Command as Em}from"commander";import{execFile as Am,spawn as fc}from"child_process";import{promisify as Om}from"util";import{existsSync as Tm,statSync as Im}from"fs";import{join as hc}from"path";import{tmpdir as jm}from"os";import X from"chalk";var Qg={id:"x-advanced-search",title:"X search: find anyone's best posts",appHint:"Opens X in Chrome; sign in before running the lesson.",start:{app:"Google Chrome",url:"https://x.com/home",ready:"Google Chrome is frontmost showing the signed-in x.com home page with its navigation sidebar"},steps:[{say:"Here's something about X search that almost nobody uses. It takes ten seconds and it changes what the site is good for."},{say:"Let's open search. This is it in the sidebar.",find:"the search and explore link in the sidebar",label:"Search",before:"Google Chrome is frontmost showing signed-in x.com with the search and explore sidebar link visible",click:!0,afterClickWaitMs:2600},{say:"Here's the box itself. Most people type a few words here and scroll. But it accepts commands, not just words.",find:"the search query input field where you type",label:"search field",before:"Google Chrome is frontmost showing x.com with the search query input visible",click:!0,afterClickWaitMs:900},{say:"Watch. From colon, then a username, limits it to that person. Then min underscore faves, colon, five hundred \u2014 only posts with at least five hundred likes.",before:"Google Chrome is frontmost on x.com and the empty search query input has keyboard focus",type:"from:naval min_faves:500",holdSeconds:1.8},{say:"And submit.",before:"Google Chrome is frontmost on x.com and the focused search input contains from:naval min_faves:500",key:"return",holdSeconds:3.2,verify:"the x.com page is displaying search results for the query from:naval min_faves:500, with at least one post visible"},{say:"There it is. That person's greatest hits \u2014 everything they wrote that actually landed. No scrolling through years of replies.",holdSeconds:2},{say:"Two more that pair well with it. Until colon, and since colon, with a date, pin it to a time period. Useful when you half remember something from a particular month."},{say:"And filter colon links, or filter colon media, narrows it to posts that shared something, which is usually where the substance is."},{say:"After you search, check the Latest tab. Top is ranked, Latest is chronological, and for research you almost always want chronological.",find:"the Latest tab",label:"Latest"},{say:"That's it. From colon someone, min underscore faves colon five hundred. It works on your own account too, which is a quick way to see what people actually responded to."}]},Zg={id:"x-bookmark-folders",title:"X bookmarks: turn the pile into folders",appHint:"Opens X in Chrome; sign in before running the lesson.",start:{app:"Google Chrome",url:"https://x.com/home",ready:"Google Chrome is frontmost showing the signed-in x.com home page with its navigation sidebar"},steps:[{say:"Most people's bookmarks on X are a single pile they never open again. There's a fix that takes a minute."},{say:"Bookmarks live here in the sidebar. By default everything you save lands in one list, in the order you saved it.",find:"the Bookmarks link in the sidebar",label:"Bookmarks",before:"Google Chrome is frontmost showing signed-in x.com with the Bookmarks sidebar link visible",click:!0,verify:"Google Chrome is showing the x.com Bookmarks page"},{say:"But bookmarks support folders. Open bookmarks and look for the add folder control, usually a small plus at the top right.",find:"the add folder button",label:"new folder"},{say:"The trick is what you name them. Not topics like design or tech, which you'll never search for. Name them after decisions you're going to make, like hiring, or pricing.",holdSeconds:2},{say:"Then when you save a post, hold the bookmark button instead of tapping it, and it asks which folder. That one gesture is the whole difference between a pile and a library."}]},em={id:"agentx-dashboard-tour",title:"AgentX: a tour of your agent team",appHint:"Start the demo first: docker compose -f docker-compose.demo.yml up -d",start:{app:"Google Chrome",url:"http://127.0.0.1:18931/live",cleanWindow:!0,ready:"The text laptop-paris is visible on the page"},steps:[{say:"This is AgentX: a team of AI agents running on your own machines. Everything here is real, except the model's replies, which are scripted for the demo."},{say:"Up top, three machines, one agent each, all online.",find:"the 3/3 machines count under Agents online",label:"3 machines online"},{say:"This machine is a laptop in Paris. Its agent, CX, talks to customers, and hands technical work to others.",find:"the laptop-paris machine name",label:"CX \xB7 laptop-paris"},{say:"And this is Builder, on a server in New York. When CX gets a code problem, it sends it here, across the mesh.",find:"the @builder Builder agent name in the vps-nyc section",label:"Builder \xB7 vps-nyc"},{say:"Operations shows what the whole team actually did.",find:"the Operations tab in the top navigation bar",label:"Operations",before:"The AgentX Live page is on screen with the Live tab selected",click:!0,verify:"The page shows the heading Mesh operations"},{say:"Machines online, work in progress, failures today, and jobs waiting for a person to review.",find:"the Nodes online summary",label:"The team at a glance"},{say:"Each lane is one kind of work. The demo's run landed here, as direct tasks.",find:"the Direct lane label in the What ran chart",label:"Direct tasks"},{say:"Workflows turn a job you repeat into steps you can review before they run.",find:"the Workflows tab in the top navigation bar",label:"Workflows",before:"The AgentX page with the heading Mesh operations is on screen",click:!0,verify:"The page shows a Workflows list that includes Draft the demo shop report"},{say:"This one drafts a report for the demo shop. It's saved switched off, so nothing runs until you say so.",find:"the Draft the demo shop report workflow title",label:"A saved workflow"},{say:"And on every page, you can ask an agent about what you're looking at.",find:"the Ask an agent about this page input",label:"Ask an agent"},{say:"That's the tour. Your machines, the work they did, and the jobs you can hand them."}]},Ks=[Qg,Zg,em];pe();pe();import Ke from"chalk";import{execFile as om}from"child_process";import{promisify as tm}from"util";import{createInterface as nm}from"readline";var sc=tm(om);function sm(e){e.type==="step"?console.log(`${Ke.cyan(` ${e.n}. ${e.action}`)}${e.target?Ke.dim(` "${e.target}"`):""} ${e.say}`):e.type==="changed"?console.log(Ke.dim(` ${e.changed?"screen changed":"no change"}`)):e.type==="acted"?console.log(e.error?Ke.red(` failed: ${e.error}`):Ke.dim(" done it")):e.type==="replanned"?console.log(Ke.yellow(` screen changed, looking again: ${e.reason}`)):e.type==="door"?console.log(Ke.cyan(` you: ${e.text}`)):e.type==="error"?console.log(Ke.red(` error: ${e.error}`)):e.type==="end"&&console.log(Ke.dim(` \xB7 ended (${e.reason})`))}async function im(e,o){let t=Date.now()+o;for(let n=0;Date.now()<t;n++){n&&n%10===0&&await sc("open",["-a",e]).catch(()=>{});try{let s=(await Es()).app;if(s.toLowerCase()===e.replace(/\.app$/i,"").toLowerCase())return s}catch{}await new Promise(s=>setTimeout(s,500))}return null}async function ic(e,o){let t=_(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=["teach","watch","act"].includes(o.mode??"")?o.mode:"teach",i;if(o.app&&(await sc("open",["-a",o.app]),i=await im(o.app,15e3)??void 0,!i))throw new Error(`${o.app} did not come to the front`);let r=hn(n,t.agents,!1),a=$n(n,t.agents[n]),c=new Fr({goal:e,app:i,mode:s,speaker:r,actionsAllowed:a.allowActions,maxSteps:Number(o.steps)||void 0},{readScreen:Es,presence:new kn(a,$e,n),speech:new ot,model:tt({system:Mr(r.persona,"Anis")}),act:Jr});c.on(sm),console.log(Ke.bold(`
296
- ${a.name} teaches: ${e}`)+Ke.dim(` (${s}${s==="act"&&!a.allowActions?", actions not allowed":""}; type to cut in, "stop" to end)
297
- `));let d=nm({input:process.stdin});d.on("line",g=>{g.trim()&&c.door(g)}),process.once("SIGINT",()=>c.stop("interrupted")),await c.run(),d.close()}pe();import so from"chalk";import{execFile as hm}from"child_process";import{copyFileSync as ym,existsSync as Xs}from"fs";import{homedir as wm}from"os";import{join as pc,resolve as bm}from"path";import{promisify as $m}from"util";var We={w:1e3,h:640},rc=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],ac=["rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","cloud","heart"],rm=["none","semi","solid","fill","pattern"],am=["s","m","l","xl"],cm=["draw","sans","serif","mono"];function cc(){return[`You plan a simple, good-looking illustration for a tldraw canvas ${We.w} wide and ${We.h} tall (x right, y down, origin top-left).`,"Reply with JSON Lines only: one element per line, no prose, no code fences, at most 14 lines. Draw back to front: big background shapes first, details and text last, arrows at the end.",'Shape: {"id":"sea","say":"First, the sea.","geo":"rectangle","x":0,"y":420,"w":1000,"h":220,"color":"blue","fill":"fill","label":""}','Text: {"id":"title","say":"And a title.","text":"Sidi Bou Said","x":330,"y":40,"size":"xl","color":"black","font":"draw"}',`Arrow: {"id":"a1","say":"That's the sun.","arrow":["sun-note","sun"],"label":"","color":"black"}`,"An arrow joins two DIFFERENT earlier elements. To label something, first add a small text element beside it (e.g. id sun-note, a few words), then an arrow from that text to the thing.",`geo is one of: ${ac.join(", ")}.`,`color is one of: ${rc.join(", ")}. fill is fill (strong colour), solid (pale tint), semi, none or pattern; prefer fill for the main shapes. size is s, m, l or xl. font is draw, sans, serif or mono.`,"Keep everything inside the canvas. Use 3 to 5 colours that go together. Give text room: an xl word is about 40 px tall and 28 px wide per letter.","say is a short caption, at most 8 words, in the voice of someone drawing it live. Caption only the steps worth narrating (about one in three) and leave say empty on the rest: captioned steps pause so they can be read, the others draw straight through."].join(`
298
- `)}function zt(e,o,t){return typeof e=="string"&&o.includes(e)?e:t}function Wn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}var Bn=(e,o,t)=>Math.min(t,Math.max(o,e));function lc(e,o){let t=e.trim().replace(/,$/,"");if(!t.startsWith("{"))return null;let n;try{n=JSON.parse(t)}catch{return null}let s=typeof n.id=="string"&&n.id?n.id.slice(0,40):null;if(!s||o.has(s))return null;let i=typeof n.say=="string"?n.say.slice(0,80):"",r=zt(n.color,rc,"black");if(Array.isArray(n.arrow)){let[d,g]=n.arrow;return typeof d!="string"||typeof g!="string"||!o.has(d)||!o.has(g)||d===g?null:{kind:"arrow",id:s,say:i,from:d,to:g,label:typeof n.label=="string"?n.label.slice(0,40):"",color:r}}let a=Wn(n.x),c=Wn(n.y);if(a===null||c===null)return null;if(typeof n.text=="string"&&n.text)return{kind:"text",id:s,say:i,text:n.text.slice(0,60),x:Bn(a,0,We.w-20),y:Bn(c,0,We.h-20),size:zt(n.size,am,"l"),color:r,font:zt(n.font,cm,"draw")};if(typeof n.geo=="string"){let d=Wn(n.w),g=Wn(n.h);if(d===null||g===null||d<4||g<4)return null;let l=Bn(a,0,We.w-4),p=Bn(c,0,We.h-4);return{kind:"geo",id:s,say:i,geo:zt(n.geo,ac,"rectangle"),x:l,y:p,w:Math.min(d,We.w-l),h:Math.min(g,We.h-p),color:r,fill:zt(n.fill,rm,"solid"),label:typeof n.label=="string"?n.label.slice(0,40):""}}return null}var Jn=class{buf="";push(o){this.buf+=o;let t=this.buf.split(`
299
- `);return this.buf=t.pop()??"",t}flush(){let o=this.buf;return this.buf="",o.trim()?[o]:[]}};var lm=500,dm=e=>`
300
- editor.zoomToBounds({ x: 0, y: 0, w: ${We.w}, h: ${We.h} }, { inset: ${e}, immediate: true })
301
- const o = editor.pageToScreen({ x: 0, y: 0 }), e = editor.pageToScreen({ x: ${We.w}, y: 0 })
293
+ `),Jn=om(em(),".agentx","paste-undo.txt");function nm(e){try{Zg(tm(Jn),{recursive:!0}),mc(Jn,e,{mode:384})}catch{}}function sm(){try{let e=Qg(Jn,"utf-8");return mc(Jn,"",{mode:384}),e.length?e:null}catch{return null}}async function im(){let{stdout:e}=await Xs("pbpaste",[],{maxBuffer:16777216});return e}async function fc(e){await new Promise((o,t)=>{gc("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function rm(){if(!Xg($e))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await Xs($e,["focused"]),o=JSON.parse(e);return o.ok===!1||!o.role?{app:"unknown",role:"an unknown control",label:null}:{app:o.app??"unknown",role:am(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function am(e,o){return{AXTextField:"a single-line text field",AXTextArea:"a multi-line text area",AXSearchField:"a search field",AXComboBox:"a combo box",AXSecureTextField:"a password field"}[e]??(o?"an editable control":`a ${e||"unknown"} control`)}import{Command as cm}from"commander";import Ve from"chalk";ge();var lm=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function dm(e,o){return async({title:t,message:n,channel:s,chatId:i})=>{let r=t&&!n.startsWith(t)?`${t}
294
+ ${n}`:n,a=await fetch(`${lm}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:s??e,chatId:i??o,text:r})});if(!a.ok)throw new Error(`daemon ${a.status}: ${(await a.text().catch(()=>"")).slice(0,200)}`)}}function gm(e){let o;try{o=_(e.config).notifications.local}catch{o=void 0}let t=bn(o);return e.sound||(t.sound=!1),e.banner||(t.banner=!1),Mr(t)}var hc=new cm().name("notify").description("tell the operator something, holding it if they are in Focus").argument("[message]","what to say").option("--from <who>","who is speaking","agentx").option("--title <text>","notification title","AgentX").option("--priority <n>","1 (min) to 5 (max)","4").option("--urgent","deliver even during Focus").option("--channel <name>","delivery channel","ntfy").option("--chat-id <id>","channel address","default").option("--no-sound","do not play a sound on this machine").option("--no-banner","do not show a banner on this machine").option("-c, --config <path>","agentx.json to read local settings from (default: ./agentx.json)").option("--status","show Focus state and anything being held").option("--flush","deliver everything held, as one message").option("--json","emit the result as JSON").action(async(e,o)=>{let t=new Cr,n=Ir(),s=gm(o);if(o.status){let r=t.list();if(o.json){console.log(JSON.stringify({focus:n,held:r},null,2));return}console.log(` ${n.active?Ve.yellow("\u25D0"):Ve.green("\u25CB")} ${jr(n)} ${Ve.dim(`\xB7 ${n.reason}`)}`),console.log(` ${r.length} held`);for(let a of r.slice(0,8)){let c=new Date(a.at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(Ve.dim(` ${c} ${a.from}: ${a.message.slice(0,70)}`))}return}let i=dm(o.channel,o.chatId);if(o.flush){let r=await Ur(i,{queue:t,alert:s});console.log(r?Ve.green(` delivered ${r} held notification(s)`):Ve.dim(" nothing was held"));return}e?.trim()||(console.log(Ve.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let r=await Fr({message:e.trim(),from:o.from,title:o.title,priority:Number(o.priority)||4,urgent:!!o.urgent,channel:o.channel,chatId:o.chatId},i,{queue:t,alert:s,focus:n});if(o.json){console.log(JSON.stringify(r,null,2));return}let a=r.delivered?Ve.green("\u2192"):Ve.yellow("\u23F8");console.log(` ${a} ${r.reason}`),r.held&&console.log(Ve.dim(" it will arrive with the others when Focus ends"))}catch(r){console.log(Ve.red(` ${r?.message??r}`)),await s(o.title,e.trim()),process.exit(1)}});Ct();zi();Fi();jt();import{Command as mm}from"commander";import{readFileSync as pm}from"fs";var yc=new mm().name("decide").description("ask a typed question about some state and get a calibrated answer back").option("--file <path>","spec JSON file (default: stdin)").option("--backend <name>","decision backend","typesafe").option("--seat <name>","seat name the answers are recorded under","adhoc").option("--no-record","answer without writing a row").option("--timeout <ms>","abandon the call after this long","20000").action(async e=>{let o;try{o=e.file?pm(e.file,"utf8"):await um()}catch(r){qo(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return qo("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return qo(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return qo("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return qo("spec needs at least one entry in `questions`");try{qi(t.questions)}catch(r){return qo(r?.message??String(r))}let n=t.seat||e.seat;Xo(),process.env[Vi(n)]="active";let s=null;if(e.record!==!1)try{s=new gn({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
295
+ `)}Yi({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await Ze(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return qo(`the ${e.backend} backend did not answer \u2014 check the key and that the seat is reachable`);console.log(JSON.stringify({ok:!0,seat:n,callId:i.callId,answers:i.answers},null,2)),s?.close()});function qo(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function um(){if(process.stdin.isTTY)return"";let e=[];for await(let o of process.stdin)e.push(Buffer.from(o));return Buffer.concat(e).toString("utf8")}Ct();import{Command as Gm}from"commander";import{execFile as Hm,spawn as Nc}from"child_process";import{promisify as zm}from"util";import{existsSync as Ym,statSync as Vm}from"fs";import{join as Rc}from"path";import{tmpdir as Km}from"os";import X from"chalk";var fm={id:"x-advanced-search",title:"X search: find anyone's best posts",appHint:"Opens X in Chrome; sign in before running the lesson.",start:{app:"Google Chrome",url:"https://x.com/home",ready:"Google Chrome is frontmost showing the signed-in x.com home page with its navigation sidebar"},steps:[{say:"Here's something about X search that almost nobody uses. It takes ten seconds and it changes what the site is good for."},{say:"Let's open search. This is it in the sidebar.",find:"the search and explore link in the sidebar",label:"Search",before:"Google Chrome is frontmost showing signed-in x.com with the search and explore sidebar link visible",click:!0,afterClickWaitMs:2600},{say:"Here's the box itself. Most people type a few words here and scroll. But it accepts commands, not just words.",find:"the search query input field where you type",label:"search field",before:"Google Chrome is frontmost showing x.com with the search query input visible",click:!0,afterClickWaitMs:900},{say:"Watch. From colon, then a username, limits it to that person. Then min underscore faves, colon, five hundred \u2014 only posts with at least five hundred likes.",before:"Google Chrome is frontmost on x.com and the empty search query input has keyboard focus",type:"from:naval min_faves:500",holdSeconds:1.8},{say:"And submit.",before:"Google Chrome is frontmost on x.com and the focused search input contains from:naval min_faves:500",key:"return",holdSeconds:3.2,verify:"the x.com page is displaying search results for the query from:naval min_faves:500, with at least one post visible"},{say:"There it is. That person's greatest hits \u2014 everything they wrote that actually landed. No scrolling through years of replies.",holdSeconds:2},{say:"Two more that pair well with it. Until colon, and since colon, with a date, pin it to a time period. Useful when you half remember something from a particular month."},{say:"And filter colon links, or filter colon media, narrows it to posts that shared something, which is usually where the substance is."},{say:"After you search, check the Latest tab. Top is ranked, Latest is chronological, and for research you almost always want chronological.",find:"the Latest tab",label:"Latest"},{say:"That's it. From colon someone, min underscore faves colon five hundred. It works on your own account too, which is a quick way to see what people actually responded to."}]},hm={id:"x-bookmark-folders",title:"X bookmarks: turn the pile into folders",appHint:"Opens X in Chrome; sign in before running the lesson.",start:{app:"Google Chrome",url:"https://x.com/home",ready:"Google Chrome is frontmost showing the signed-in x.com home page with its navigation sidebar"},steps:[{say:"Most people's bookmarks on X are a single pile they never open again. There's a fix that takes a minute."},{say:"Bookmarks live here in the sidebar. By default everything you save lands in one list, in the order you saved it.",find:"the Bookmarks link in the sidebar",label:"Bookmarks",before:"Google Chrome is frontmost showing signed-in x.com with the Bookmarks sidebar link visible",click:!0,verify:"Google Chrome is showing the x.com Bookmarks page"},{say:"But bookmarks support folders. Open bookmarks and look for the add folder control, usually a small plus at the top right.",find:"the add folder button",label:"new folder"},{say:"The trick is what you name them. Not topics like design or tech, which you'll never search for. Name them after decisions you're going to make, like hiring, or pricing.",holdSeconds:2},{say:"Then when you save a post, hold the bookmark button instead of tapping it, and it asks which folder. That one gesture is the whole difference between a pile and a library."}]},ym={id:"agentx-dashboard-tour",title:"AgentX: a tour of your agent team",appHint:"Start the demo first: docker compose -f docker-compose.demo.yml up -d",start:{app:"Google Chrome",url:"http://127.0.0.1:18931/live",cleanWindow:!0,ready:"The text laptop-paris is visible on the page"},steps:[{say:"This is AgentX: a team of AI agents running on your own machines. Everything here is real, except the model's replies, which are scripted for the demo."},{say:"Up top, three machines, one agent each, all online.",find:"the 3/3 machines count under Agents online",label:"3 machines online"},{say:"This machine is a laptop in Paris. Its agent, CX, talks to customers, and hands technical work to others.",find:"the laptop-paris machine name",label:"CX \xB7 laptop-paris"},{say:"And this is Builder, on a server in New York. When CX gets a code problem, it sends it here, across the mesh.",find:"the @builder Builder agent name in the vps-nyc section",label:"Builder \xB7 vps-nyc"},{say:"Operations shows what the whole team actually did.",find:"the Operations tab in the top navigation bar",label:"Operations",before:"The AgentX Live page is on screen with the Live tab selected",click:!0,verify:"The page shows the heading Mesh operations"},{say:"Machines online, work in progress, failures today, and jobs waiting for a person to review.",find:"the Nodes online summary",label:"The team at a glance"},{say:"Each lane is one kind of work. The demo's run landed here, as direct tasks.",find:"the Direct lane label in the What ran chart",label:"Direct tasks"},{say:"Workflows turn a job you repeat into steps you can review before they run.",find:"the Workflows tab in the top navigation bar",label:"Workflows",before:"The AgentX page with the heading Mesh operations is on screen",click:!0,verify:"The page shows a Workflows list that includes Draft the demo shop report"},{say:"This one drafts a report for the demo shop. It's saved switched off, so nothing runs until you say so.",find:"the Draft the demo shop report workflow title",label:"A saved workflow"},{say:"And on every page, you can ask an agent about what you're looking at.",find:"the Ask an agent about this page input",label:"Ask an agent"},{say:"That's the tour. Your machines, the work they did, and the jobs you can hand them."}]},Qs=[fm,hm,ym];ge();ge();import Ke from"chalk";import{execFile as wm}from"child_process";import{promisify as bm}from"util";import{createInterface as $m}from"readline";var wc=bm(wm);function km(e){e.type==="step"?console.log(`${Ke.cyan(` ${e.n}. ${e.action}`)}${e.target?Ke.dim(` "${e.target}"`):""} ${e.say}`):e.type==="changed"?console.log(Ke.dim(` ${e.changed?"screen changed":"no change"}`)):e.type==="acted"?console.log(e.error?Ke.red(` failed: ${e.error}`):Ke.dim(" done it")):e.type==="replanned"?console.log(Ke.yellow(` screen changed, looking again: ${e.reason}`)):e.type==="door"?console.log(Ke.cyan(` you: ${e.text}`)):e.type==="error"?console.log(Ke.red(` error: ${e.error}`)):e.type==="end"&&console.log(Ke.dim(` \xB7 ended (${e.reason})`))}async function vm(e,o){let t=Date.now()+o;for(let n=0;Date.now()<t;n++){n&&n%10===0&&await wc("open",["-a",e]).catch(()=>{});try{let s=(await As()).app;if(s.toLowerCase()===e.replace(/\.app$/i,"").toLowerCase())return s}catch{}await new Promise(s=>setTimeout(s,500))}return null}async function bc(e,o){let t=_(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=["teach","watch","act"].includes(o.mode??"")?o.mode:"teach",i;if(o.app&&(await wc("open",["-a",o.app]),i=await vm(o.app,15e3)??void 0,!i))throw new Error(`${o.app} did not come to the front`);let r=kn(n,t.agents,!1),a=t.voice.listener??Zr,c=xn(n,t.agents[n]),l=new ta({goal:e,app:i,mode:s,speaker:r,actionsAllowed:c.allowActions,maxSteps:Number(o.steps)||void 0,listener:a},{readScreen:As,presence:new Sn(c,$e,n),speech:new st,model:it({system:oa(r.persona,a)}),act:na});l.on(km),console.log(Ke.bold(`
296
+ ${c.name} teaches: ${e}`)+Ke.dim(` (${s}${s==="act"&&!c.allowActions?", actions not allowed":""}; type to cut in, "stop" to end)
297
+ `));let g=$m({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close()}ge();import Xe from"chalk";import{execFile as Pm}from"child_process";import{existsSync as oi,writeFileSync as Mm}from"fs";import{homedir as Lm}from"os";import{join as jc,resolve as Fm}from"path";import{promisify as Um}from"util";var Me={w:1e3,h:640},Zs=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],vc=["rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","cloud","heart"],$c=["none","semi","solid","fill","pattern"],ei=180,xc=48,xm=["s","m","l","xl"],Sm=["draw","sans","serif","mono"];function Sc(){return[`You are an illustrator drawing on a tldraw canvas ${Me.w} wide and ${Me.h} tall (x right, y down, origin top-left).`,`Reply with JSON Lines only: one element per line, no prose, no code fences. Scale the number of elements to the brief: a quick sketch needs 10 to 20, a finished, ambitious piece up to ${ei}. Draw back to front: background first, then midground, foreground, details, text last, arrows at the very end.`,'Palette (optional, first line): {"palette":{"blue":"#1f5fa6","white":"#f7f3ea"},"say":"Choosing a palette."} remaps any of the colour names to a hex value for this drawing; every later element uses the names.','Shape: {"id":"sea","say":"First, the sea.","geo":"rectangle","x":0,"y":420,"w":1000,"h":220,"color":"blue","fill":"fill","label":"","opacity":1}',`Path: {"id":"dome","say":"","path":[[400,200],[410,170],[440,150],[470,170],[480,200],[400,200]],"color":"white","fill":"fill","opacity":1} is a free outline of 3 to ${xc} points, closed and filled, for any silhouette a box can't make: domes, arches, hills, foliage, stairs, shadows, reflections. Straight edges stay straight; give curves enough points. With fill none it is an open stroke: a railing, a grille bar, a crack, a horizon line.`,'Text: {"id":"title","say":"And a title.","text":"Sidi Bou Said","x":330,"y":40,"size":"xl","color":"black","font":"serif"}',`Arrow: {"id":"a1","say":"That's the sun.","arrow":["sun-note","sun"],"label":"","color":"black"}`,"An arrow joins two DIFFERENT earlier elements. To label something, first add a small text element beside it, then an arrow from that text to the thing.",`geo is one of: ${vc.join(", ")}.`,`color is one of: ${Zs.join(", ")}. fill is fill (strong colour), solid (pale tint), semi, none or pattern. opacity is 0.1 to 1: use it for shadows, haze and atmospheric depth. size is s, m, l or xl. font is draw (hand-lettered), sans, serif or mono.`,"Keep everything inside the canvas. Give text room: an xl word is about 40 px tall and 28 px wide per letter.","say is a short caption, at most 8 words, in the voice of someone drawing it live. Caption only the steps worth narrating (about one in five) and leave say empty on the rest: captioned steps pause so they can be read, the others draw straight through."].join(`
298
+ `)}function ut(e,o,t){return typeof e=="string"&&o.includes(e)?e:t}function Wo(e){return typeof e=="number"&&Number.isFinite(e)?e:null}var Bo=(e,o,t)=>Math.min(t,Math.max(o,e)),kc=e=>Bo(Wo(e)??1,.1,1),Em=/^#[0-9a-f]{6}$/i;function Am(e){if(!e||typeof e!="object")return null;let o={};for(let[t,n]of Object.entries(e))Zs.includes(t)&&typeof n=="string"&&Em.test(n)&&(o[t]=n);return Object.keys(o).length?o:null}function Om(e){if(!Array.isArray(e))return null;let o=[];for(let t of e.slice(0,xc)){if(!Array.isArray(t))return null;let n=Wo(t[0]),s=Wo(t[1]);if(n===null||s===null)return null;o.push([Bo(n,0,Me.w),Bo(s,0,Me.h)])}return o.length>=2?o:null}function Ec(e,o){let t=e.trim().replace(/,$/,"");if(!t.startsWith("{"))return null;let n;try{n=JSON.parse(t)}catch{return null}if("palette"in n){let l=Am(n.palette);return!l||o.has("palette")?null:{kind:"palette",id:"palette",say:typeof n.say=="string"?n.say.slice(0,80):"",colors:l}}let s=typeof n.id=="string"&&n.id?n.id.slice(0,40):null;if(!s||o.has(s))return null;let i=typeof n.say=="string"?n.say.slice(0,80):"",r=ut(n.color,Zs,"black");if(Array.isArray(n.arrow)){let[l,g]=n.arrow;return typeof l!="string"||typeof g!="string"||!o.has(l)||!o.has(g)||l===g?null:{kind:"arrow",id:s,say:i,from:l,to:g,label:typeof n.label=="string"?n.label.slice(0,40):"",color:r}}if("path"in n){let l=Om(n.path),g=ut(n.fill,$c,"fill");return!l||g!=="none"&&l.length<3?null:{kind:"path",id:s,say:i,pts:l,color:r,fill:g,opacity:kc(n.opacity)}}let a=Wo(n.x),c=Wo(n.y);if(a===null||c===null)return null;if(typeof n.text=="string"&&n.text)return{kind:"text",id:s,say:i,text:n.text.slice(0,60),x:Bo(a,0,Me.w-20),y:Bo(c,0,Me.h-20),size:ut(n.size,xm,"l"),color:r,font:ut(n.font,Sm,"draw")};if(typeof n.geo=="string"){let l=Wo(n.w),g=Wo(n.h);if(l===null||g===null||l<4||g<4)return null;let d=Bo(a,0,Me.w-4),u=Bo(c,0,Me.h-4);return{kind:"geo",id:s,say:i,geo:ut(n.geo,vc,"rectangle"),x:d,y:u,w:Math.min(l,Me.w-d),h:Math.min(g,Me.h-u),color:r,fill:ut(n.fill,$c,"solid"),label:typeof n.label=="string"?n.label.slice(0,40):"",opacity:kc(n.opacity)}}return null}var Gn=class{buf="";push(o){this.buf+=o;let t=this.buf.split(`
299
+ `);return this.buf=t.pop()??"",t}flush(){let o=this.buf;return this.buf="",o.trim()?[o]:[]}};var Tm=500,Im=e=>`
300
+ editor.zoomToBounds({ x: 0, y: 0, w: ${Me.w}, h: ${Me.h} }, { inset: ${e}, immediate: true })
301
+ const o = editor.pageToScreen({ x: 0, y: 0 }), e = editor.pageToScreen({ x: ${Me.w}, y: 0 })
302
302
  const chrome = window.outerHeight - window.innerHeight
303
- return { ox: window.screenX + o.x, oy: window.screenY + chrome + o.y, scale: (e.x - o.x) / ${We.w} }`;function dc(e,o,t,n=0,s=0){return{x:e.ox+o*e.scale,y:e.oy+t*e.scale,width:n*e.scale,height:s*e.scale}}function gc(e){let o={s:18,m:24,l:32,xl:44}[e.size]??32;return{x:e.x,y:e.y,w:e.text.length*o*.6,h:o*1.3}}function gm(e,o){let t=s=>JSON.stringify(`${o}-${s}`),n=`const { createShapeId, toRichText } = await import('tldraw')
303
+ return { ox: window.screenX + o.x, oy: window.screenY + chrome + o.y, scale: (e.x - o.x) / ${Me.w} }`;function Ac(e,o,t,n=0,s=0){return{x:e.ox+o*e.scale,y:e.oy+t*e.scale,width:n*e.scale,height:s*e.scale}}function Oc(e){let o={s:18,m:24,l:32,xl:44}[e.size]??32;return{x:e.x,y:e.y,w:e.text.length*o*.6,h:o*1.3}}function jm(e){let o=e.map(i=>i[0]),t=e.map(i=>i[1]),n=Math.min(...o),s=Math.min(...t);return{x:n,y:s,w:Math.max(...o)-n,h:Math.max(...t)-s}}function Tc(e){return`const hex = ${JSON.stringify(e.colors)}
304
+ const tint = (h, t) => '#' + [1, 3, 5].map((i) => Math.round(parseInt(h.slice(i, i + 2), 16) * (1 - t) + 255 * t).toString(16).padStart(2, '0')).join('')
305
+ const th = editor.getTheme('default')
306
+ const colors = structuredClone(th.colors)
307
+ for (const mode of Object.keys(colors)) for (const [name, v] of Object.entries(hex)) {
308
+ if (colors[mode][name]) Object.assign(colors[mode][name], { solid: v, fill: v, pattern: v, linedFill: tint(v, 0.25), semi: tint(v, 0.75), noteFill: v })
309
+ }
310
+ editor.updateTheme({ ...th, colors })
311
+ return true`}function Cm(e,o){if(e.kind==="palette")return Tc(e);let t=s=>JSON.stringify(`${o}-${s}`),n=`const { createShapeId, toRichText } = await import('tldraw')
304
312
  const el = ${JSON.stringify(e)}
305
- const frames = 10, wait = () => new Promise((r) => setTimeout(r, ${Math.round(lm/10)}))
313
+ const frames = 10, wait = () => new Promise((r) => setTimeout(r, ${Math.round(Tm/10)}))
306
314
  const ease = (t) => 1 - Math.pow(1 - t, 3)`;return e.kind==="geo"?`${n}
307
315
  const id = createShapeId(${t(e.id)})
308
- editor.createShape({ id, type: 'geo', x: el.x, y: el.y, props: { geo: el.geo, w: 1, h: 1, color: el.color, fill: el.fill } })
316
+ editor.createShape({ id, type: 'geo', x: el.x, y: el.y, opacity: el.opacity, props: { geo: el.geo, w: 1, h: 1, color: el.color, fill: el.fill, dash: 'solid', size: 's' } })
309
317
  for (let i = 1; i <= frames; i++) {
310
318
  const t = ease(i / frames)
311
319
  editor.updateShape({ id, type: 'geo', props: { w: Math.max(1, el.w * t), h: Math.max(1, el.h * t) } })
312
320
  await wait()
313
321
  }
314
322
  if (el.label) editor.updateShape({ id, type: 'geo', props: { richText: toRichText(el.label) } })
323
+ return id`:e.kind==="path"?`${n}
324
+ const { compressLegacySegments } = await import('tldraw')
325
+ const id = createShapeId(${t(e.id)})
326
+ const closed = el.fill !== 'none'
327
+ const pts = closed ? [...el.pts, el.pts[0]] : el.pts
328
+ const dense = []
329
+ for (let i = 0; i < pts.length - 1; i++) {
330
+ const [ax, ay] = pts[i], [bx, by] = pts[i + 1]
331
+ const n = Math.max(1, Math.ceil(Math.hypot(bx - ax, by - ay) / 3))
332
+ for (let k = 0; k < n; k++) dense.push({ x: ax + (bx - ax) * k / n, y: ay + (by - ay) * k / n, z: 0.5 })
333
+ }
334
+ dense.push({ x: pts[pts.length - 1][0], y: pts[pts.length - 1][1], z: 0.5 })
335
+ const seg = (upTo) => compressLegacySegments([{ type: 'free', points: dense.slice(0, Math.max(2, upTo)) }])
336
+ editor.createShape({ id, type: 'draw', x: 0, y: 0, opacity: el.opacity, props: { segments: seg(2), isComplete: false, isClosed: false, color: el.color, fill: 'none', dash: 'solid', size: 's' } })
337
+ for (let i = 1; i <= frames; i++) {
338
+ editor.updateShape({ id, type: 'draw', props: { segments: seg(Math.ceil(dense.length * ease(i / frames))) } })
339
+ await wait()
340
+ }
341
+ editor.updateShape({ id, type: 'draw', props: { segments: seg(dense.length), isComplete: true, isClosed: closed, fill: el.fill } })
315
342
  return id`:e.kind==="text"?`${n}
316
343
  const id = createShapeId(${t(e.id)})
317
344
  editor.createShape({ id, type: 'text', x: el.x, y: el.y, props: { richText: toRichText(''), size: el.size, color: el.color, font: el.font } })
@@ -323,70 +350,70 @@ return id`:`${n}
323
350
  const arrow = helpers.createArrowBetweenShapes(createShapeId(${t(e.from)}), createShapeId(${t(e.to)}), el.label ? { richText: toRichText(el.label) } : {})
324
351
  const aid = typeof arrow === 'string' ? arrow : arrow?.id
325
352
  if (aid) editor.updateShape({ id: aid, type: 'arrow', props: { color: el.color } })
326
- return aid ?? null`}function mm(e,o){if(e.kind==="geo")return[qo(e.x,e.y),qo(e.x+e.w,e.y+e.h)];if(e.kind==="text"){let s=gc(e);return[qo(s.x,s.y+s.h/2),qo(s.x+s.w,s.y+s.h/2)]}let t=o.get(e.from),n=o.get(e.to);return[qo(t.x+t.w/2,t.y+t.h/2),qo(n.x+n.w/2,n.y+n.h/2)]}var qo=(e,o)=>({x:e,y:o,w:0,h:0});async function mc(e,o,t,n=()=>{}){let s=o.sleep??(v=>new Promise($=>setTimeout($,v))),i=o.now??Date.now,r=t.stepMs??1500,a=t.runTag??i().toString(36),c=i(),d=await o.api.exec(t.docId,dm(60)),g=new Set,l=new Map,p=[],f=!1,u=0,w=null,y=null,k=null,b=()=>{k?.(),k=null},x=v=>{let $=lc(v,g);if(!$){v.trim()&&n({type:"skipped",line:v.slice(0,120)});return}g.add($.id),w??=i()-c,p.push($),n({type:"planned",n:g.size,el:$,atMs:i()-c}),b()},A=(async()=>{let v=new Jn;try{for await(let $ of o.model.reply(`Draw: ${e}`,t.signal))v.push($).forEach(x);v.flush().forEach(x)}catch($){y=$?.message??String($)}finally{u=i()-c,f=!0,b()}})(),S=0;for(;!t.signal?.aborted;){let v=p.shift();if(!v){if(f)break;await new Promise(D=>{k=D});continue}if(v.kind==="arrow"&&!(l.has(v.from)&&l.has(v.to))){n({type:"error",error:`${v.id}: an end was not drawn`});continue}let $=i(),[C,j]=mm(v,l);v.say&&o.presence.say(v.say),o.presence.moveTo(dc(d,C.x,C.y)),await s(250),o.presence.moveTo(dc(d,j.x,j.y));try{await o.api.exec(t.docId,gm(v,a))}catch(D){n({type:"error",error:`${v.id}: ${D?.message??D}`});continue}l.set(v.id,v.kind==="geo"?v:v.kind==="text"?gc(v):qo(0,0)),S++,n({type:"drawn",n:S,el:v,ms:i()-$});let T=(v.say?r:0)-(i()-$);T>0&&await s(T)}return await A,y&&n({type:"error",error:`plan: ${y}`}),o.presence.park(),{steps:S,totalMs:i()-c,firstLineMs:w,planMs:u}}import{readFileSync as pm}from"fs";import{homedir as um}from"os";import{join as fm}from"path";var Yt=fm(um(),"Library","Application Support","tldraw","server.json"),Gn=class{constructor(o=Yt,t=fetch){this.serverJson=o;this.fetchFn=t}server(){let o;try{o=pm(this.serverJson,"utf8")}catch{throw new Error("tldraw offline is not running (no server.json)")}let{port:t,token:n}=JSON.parse(o);return{port:t,token:n}}async post(o,t){let{port:n,token:s}=this.server(),i=await this.fetchFn(`http://localhost:${n}${o}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${s}`},body:JSON.stringify(t)}),r=await i.json();if(!i.ok||r.success===!1)throw new Error(`tldraw ${o}: ${r.error??i.status}`);return r.result}createDoc(o,t){return this.post("/api/docs/create",{name:o,...t?{directory:t}:{}})}exec(o,t){return this.post(`/api/doc/${o}/exec`,{code:t})}search(o){return this.post("/api/search",{code:o})}};var km=$m(hm),vm="claude-sonnet-5";function xm(e){e.type==="planned"?console.log(so.dim(` planned ${e.n}: ${e.el.kind} ${e.el.id} at ${(e.atMs/1e3).toFixed(1)} s`)):e.type==="drawn"?console.log(`${so.cyan(` ${e.n}. ${e.el.kind} ${e.el.id}`)} ${e.el.say}${so.dim(` (${(e.ms/1e3).toFixed(1)} s)`)}`):e.type==="skipped"?console.log(so.yellow(` skipped: ${e.line}`)):console.log(so.red(` error: ${e.error}`))}async function Sm(){if(!Xs(Yt)){await km("open",["-a","tldraw offline"]);for(let e=0;e<40&&!Xs(Yt);e++)await new Promise(o=>setTimeout(o,500));if(!Xs(Yt))throw new Error("tldraw offline did not start")}}async function uc(e,o){let t=_(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=o.model||vm,i=bm(o.out||pc(wm(),"Documents")),r=$n(n,t.agents[n]),a=tt({system:cc(),model:s}),c=new kn(r,$e,n),d=new Gn;try{await Sm();let g=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),l=await d.createDoc(`agentx-draw-${g}`,i);await new Promise(y=>setTimeout(y,800)),console.log(so.bold(`
327
- ${r.name} draws: ${e}`)+so.dim(` (${s}, ${l.filePath})
328
- `));let p=new AbortController;process.once("SIGINT",()=>p.abort());let f=await mc(e,{api:d,presence:c,model:a},{docId:l.id,signal:p.signal},xm);await d.exec(l.id,"await helpers.saveDoc(); return true");let u=await d.search(`return await api.getScreenshot(${JSON.stringify(l.id)}, { size: 'full' })`),w=l.filePath?l.filePath.replace(/\.tldraw$/,".jpg"):pc(i,`agentx-draw-${g}.jpg`);ym(u.filePath,w),console.log(so.bold(`
329
- ${f.steps} steps in ${(f.totalMs/1e3).toFixed(1)} s`)+so.dim(` (first shape planned at ${f.firstLineMs===null?"\u2013":(f.firstLineMs/1e3).toFixed(1)} s, plan done at ${(f.planMs/1e3).toFixed(1)} s)`)),console.log(so.dim(` ${l.filePath}
353
+ return aid ?? null`}function Nm(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.floor(s.length/2)];return[lo(s[0][0],s[0][1]),lo(i[0],i[1])]}if(e.kind==="geo")return[lo(e.x,e.y),lo(e.x+e.w,e.y+e.h)];if(e.kind==="text"){let s=Oc(e);return[lo(s.x,s.y+s.h/2),lo(s.x+s.w,s.y+s.h/2)]}let t=o.get(e.from),n=o.get(e.to);return[lo(t.x+t.w/2,t.y+t.h/2),lo(n.x+n.w/2,n.y+n.h/2)]}var lo=(e,o)=>({x:e,y:o,w:0,h:0});async function Ic(e,o,t,n=()=>{}){let s=o.sleep??(v=>new Promise($=>setTimeout($,v))),i=o.now??Date.now,r=t.stepMs??1500,a=t.runTag??i().toString(36),c=i(),l=await o.api.exec(t.docId,Im(60)),g=new Set,d=new Map,u=[],f=!1,p=0,w=null,y=null,k=null,b=()=>{k?.(),k=null},S=v=>{if(g.size>=ei)return;let $=Ec(v,g);if(!$){v.trim()&&n({type:"skipped",line:v.slice(0,120)});return}g.add($.id),w??=i()-c,u.push($),n({type:"planned",n:g.size,el:$,atMs:i()-c}),b()},A=(async()=>{let v=new Gn;try{for await(let $ of o.model.reply(`Draw: ${e}`,t.signal))v.push($).forEach(S);v.flush().forEach(S)}catch($){y=$?.message??String($)}finally{p=i()-c,f=!0,b()}})(),x=0;for(;!t.signal?.aborted;){let v=u.shift();if(!v){if(f)break;await new Promise(D=>{k=D});continue}if(v.kind==="arrow"&&!(d.has(v.from)&&d.has(v.to))){n({type:"error",error:`${v.id}: an end was not drawn`});continue}let $=i();if(v.kind==="palette"){v.say&&o.presence.say(v.say);try{await o.api.exec(t.docId,Tc(v))}catch(D){n({type:"error",error:`palette: ${D?.message??D}`});continue}x++,n({type:"drawn",n:x,el:v,ms:i()-$});continue}let[C,j]=Nm(v,d);v.say&&o.presence.say(v.say),o.presence.moveTo(Ac(l,C.x,C.y)),await s(250),o.presence.moveTo(Ac(l,j.x,j.y));try{await o.api.exec(t.docId,Cm(v,a))}catch(D){n({type:"error",error:`${v.id}: ${D?.message??D}`});continue}d.set(v.id,v.kind==="geo"?v:v.kind==="text"?Oc(v):v.kind==="path"?jm(v.pts):lo(0,0)),x++,n({type:"drawn",n:x,el:v,ms:i()-$});let T=(v.say?r:0)-(i()-$);T>0&&await s(T)}return await A,y&&n({type:"error",error:`plan: ${y}`}),o.presence.park(),{steps:x,totalMs:i()-c,firstLineMs:w,planMs:p}}import{readFileSync as Rm}from"fs";import{homedir as Dm}from"os";import{join as _m}from"path";var Vt=_m(Dm(),"Library","Application Support","tldraw","server.json"),Hn=class{constructor(o=Vt,t=fetch){this.serverJson=o;this.fetchFn=t}server(){let o;try{o=Rm(this.serverJson,"utf8")}catch{throw new Error("tldraw offline is not running (no server.json)")}let{port:t,token:n}=JSON.parse(o);return{port:t,token:n}}async post(o,t){let{port:n,token:s}=this.server(),i=await this.fetchFn(`http://localhost:${n}${o}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${s}`},body:JSON.stringify(t)}),r=await i.json();if(!i.ok||r.success===!1)throw new Error(`tldraw ${o}: ${r.error??i.status}`);return r.result}createDoc(o,t){return this.post("/api/docs/create",{name:o,...t?{directory:t}:{}})}exec(o,t){return this.post(`/api/doc/${o}/exec`,{code:t})}search(o){return this.post("/api/search",{code:o})}};var qm=Um(Pm),Wm="claude-sonnet-5";function Bm(e){e.type==="planned"?console.log(Xe.dim(` planned ${e.n}: ${e.el.kind} ${e.el.id} at ${(e.atMs/1e3).toFixed(1)} s`)):e.type==="drawn"?console.log(`${Xe.cyan(` ${e.n}. ${e.el.kind} ${e.el.id}`)} ${e.el.say}${Xe.dim(` (${(e.ms/1e3).toFixed(1)} s)`)}`):e.type==="skipped"?console.log(Xe.yellow(` skipped: ${e.line}`)):console.log(Xe.red(` error: ${e.error}`))}async function Jm(){if(!oi(Vt)){await qm("open",["-a","tldraw offline"]);for(let e=0;e<40&&!oi(Vt);e++)await new Promise(o=>setTimeout(o,500));if(!oi(Vt))throw new Error("tldraw offline did not start")}}async function Cc(e,o){let t=_(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=o.model||Wm,i=Fm(o.out||jc(Lm(),"Documents")),r=xn(n,t.agents[n]),a=it({system:Sc(),model:s}),c=new Sn(r,$e,n),l=new Hn;try{await Jm();let g=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),d=await l.createDoc(`agentx-draw-${g}`,i);await new Promise(k=>setTimeout(k,800)),console.log(Xe.bold(`
354
+ ${r.name} draws: ${e}`)+Xe.dim(` (${s}, ${d.filePath})
355
+ `));let u=new AbortController;process.once("SIGINT",()=>u.abort());let f=await Ic(e,{api:l,presence:c,model:a},{docId:d.id,signal:u.signal},Bm);await l.exec(d.id,"await helpers.saveDoc(); return true");let p=await l.exec(d.id,"const r = await editor.toImageDataUrl([...editor.getCurrentPageShapeIds()], { format: 'png', scale: 2, background: true }); return r.url"),w=d.filePath?d.filePath.replace(/\.tldraw$/,".png"):jc(i,`agentx-draw-${g}.png`);Mm(w,Buffer.from(p.slice(p.indexOf(",")+1),"base64")),console.log(Xe.bold(`
356
+ ${f.steps} steps in ${(f.totalMs/1e3).toFixed(1)} s`)+Xe.dim(` (first shape planned at ${f.firstLineMs===null?"\u2013":(f.firstLineMs/1e3).toFixed(1)} s, plan done at ${(f.planMs/1e3).toFixed(1)} s)`));let y=a.lastUsage;y&&console.log(Xe.dim(` tokens: ${y.inputTokens} in, ${y.outputTokens} out, ${y.cacheReadTokens} cache read, ${y.cacheWriteTokens} cache write; cost ${y.costUsd===null?"not reported":`$${y.costUsd.toFixed(4)}`}`)),console.log(Xe.dim(` ${d.filePath}
330
357
  ${w}
331
- `))}finally{a.close(),c.close()}}var Zs=Om(Am),yc=new Em().name("teach").description("walk through something on screen, speaking and pointing as it goes").argument("[lesson]","lesson id (omit to list)").option("--voice <voice>",`system voice name, "${ho}" for the OS default, or ElevenLabs voice id (overrides the agent's)`).option("--agent <id>","speak in this agent's voice (default: AGENTX_VOICE_AGENT or node.defaultAgent)").option("--no-speak","point only, print the narration").option("--no-hud","skip the on-screen callout").option("--record","record the screen (screencapture) around the lesson").option("--record-dir <path>","where to write the recording").option("--live <goal>","no lesson: the agent reads the screen and teaches this, step by step").option("--mode <mode>","with --live: teach (you do each step), watch (you drive, it coaches) act (it does it, if allowed) or draw (plans a tldraw offline illustration in one model turn and draws it)").option("--app <name>","with --live: open this app first").option("-c, --config <path>","with --live: agentx.json to read the agent from").option("--steps <n>","with --live: most steps before it stops (default 12)").option("--model <id>","with --mode draw: the planning model (default claude-sonnet-5)").option("--out <dir>","with --mode draw: where the .tldraw file and the picture go (default ~/Documents)").action(async(e,o)=>{if(o.live)try{o.mode==="draw"?await uc(String(o.live),o):await ic(String(o.live),o),process.exit(0)}catch(g){console.log(X.red(` ${g?.message??g}`)),process.exit(1)}if(!e){console.log(X.bold(`
358
+ `))}finally{a.close(),c.close()}}var ni=zm(Hm),Dc=new Gm().name("teach").description("walk through something on screen, speaking and pointing as it goes").argument("[lesson]","lesson id (omit to list)").option("--voice <voice>",`system voice name, "${yo}" for the OS default, or ElevenLabs voice id (overrides the agent's)`).option("--agent <id>","speak in this agent's voice (default: AGENTX_VOICE_AGENT or node.defaultAgent)").option("--no-speak","point only, print the narration").option("--no-hud","skip the on-screen callout").option("--record","record the screen (screencapture) around the lesson").option("--record-dir <path>","where to write the recording").option("--live <goal>","no lesson: the agent reads the screen and teaches this, step by step").option("--mode <mode>","with --live: teach (you do each step), watch (you drive, it coaches) act (it does it, if allowed) or draw (plans a tldraw offline illustration in one model turn and draws it)").option("--app <name>","with --live: open this app first").option("-c, --config <path>","with --live: agentx.json to read the agent from").option("--steps <n>","with --live: most steps before it stops (default 12)").option("--model <id>","with --mode draw: the planning model (default claude-sonnet-5)").option("--out <dir>","with --mode draw: where the .tldraw file and the picture go (default ~/Documents)").action(async(e,o)=>{if(o.live)try{o.mode==="draw"?await Cc(String(o.live),o):await bc(String(o.live),o),process.exit(0)}catch(g){console.log(X.red(` ${g?.message??g}`)),process.exit(1)}if(!e){console.log(X.bold(`
332
359
  lessons
333
- `));for(let g of Ks)console.log(` ${X.cyan(g.id.padEnd(22))} ${g.title}`),console.log(` ${" ".repeat(22)} ${X.dim(g.appHint)}
334
- `);return}let t=Ks.find(g=>g.id===e);t||(console.log(X.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),Tm($e)||(console.log(X.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let n=o.speak===!1?void 0:Rm(o.voice,o.agent);console.log(X.bold(`
360
+ `));for(let g of Qs)console.log(` ${X.cyan(g.id.padEnd(22))} ${g.title}`),console.log(` ${" ".repeat(22)} ${X.dim(g.appHint)}
361
+ `);return}let t=Qs.find(g=>g.id===e);t||(console.log(X.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),Ym($e)||(console.log(X.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let n=o.speak===!1?void 0:Zm(o.voice,o.agent);console.log(X.bold(`
335
362
  ${t.title}`)),console.log(X.dim(` ${t.appHint}
336
- `));try{t.start&&(await Zs("/usr/bin/open",Cm(t.start)),await So(2e3),await Hn(t.start.ready))}catch(g){console.log(X.red(` setup stopped: ${g?.message??g}`)),process.exitCode=3;return}let s=null,i=null;o.record&&(i=hc(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(X.dim(` recording \u2192 ${i}`)),s=fc("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await So(2e3));let r=o.hud===!1?null:fc($e,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(g,l,p,f)=>{try{r?.stdin?.write(JSON.stringify({title:g,body:l,state:p,avoid:f})+`
337
- `)}catch{}},c=[],d=!1;try{for(let[g,l]of t.steps.entries()){if(console.log(` ${X.dim(String(g+1).padStart(2))} ${l.say}`),a(`Step ${g+1} of ${t.steps.length}`,l.say,"talking"),l.click||l.type||l.key){if(!l.before)throw new Error(`Step ${g+1} needs a before claim`);await Hn(l.before)}let p=o.speak===!1?Promise.resolve():_m(l.say,n),f=l.find?await Nm(l.find,c):null;if(l.find&&!f)throw c.push({tried:l.find,changed:!1,note:"not found on screen"}),await p,new Error(`Could not find "${l.find}"; stopped before acting`);if(await p,f&&(a(`Step ${g+1} of ${t.steps.length}`,l.say,"pointing",{x:f.x,y:f.y,w:f.width,h:f.height}),await Zs($e,["point","--x",String(f.x),"--y",String(f.y),"--w",String(f.width),"--h",String(f.height),"--label",l.label??l.find??"","--hold",String(l.click||l.type?.5:l.holdSeconds??2.6)]),l.click)){let{error:u,changed:w}=await Qs(["click"]);if(u)throw new Error(u);c.push({tried:l.label??l.find??"control",changed:w!==!1,note:u??void 0}),w===!1&&console.log(X.yellow(" \xB7 clicked, but the screen did not change")),await So(l.afterClickWaitMs??1500)}if(l.type){await Hn(l.before),a(`Step ${g+1} of ${t.steps.length}`,l.type,"typing");let{error:u}=await Qs(["type","--text",l.type]);if(u)throw console.log(X.red(` \u2717 ${u}`)),a("Blocked",u,"waiting"),c.push({tried:`type into ${l.label??"the field"}`,changed:!1,note:u}),new Error(u)}if(l.key){await Hn(l.before),a(`Step ${g+1} of ${t.steps.length}`,`\u21B5 ${l.key}`,"typing");let{error:u}=await Qs(["key","--name",l.key]);if(u)throw console.log(X.red(` \u2717 ${u}`)),a("Blocked",u,"waiting"),c.push({tried:`press ${l.key}`,changed:!1,note:u}),new Error(u)}if(!f&&!l.type&&!l.key?await So((l.holdSeconds??1.2)*1e3):l.holdSeconds&&await So(l.holdSeconds*1e3),l.verify){a(`Step ${g+1} of ${t.steps.length}`,"Checking that worked\u2026","waiting");let u;try{u=await Ht(l.verify)}catch(w){u=null,console.log(X.yellow(` ? could not check: ${w?.message??w}`))}if(!u&&!l.verifyOptional)throw new Error(`Could not verify: ${l.verify}`);if(u){let w=u.outcome==="confirmed"?X.green("\u2713"):u.outcome==="refuted"?X.red("\u2717"):X.yellow("?");if(console.log(` ${w} ${X.dim(u.reason)}`),!u.ok&&!l.verifyOptional){a("Stopped",`That did not work: ${l.verify}`,"waiting"),console.log(X.red(`
338
- stopping: could not confirm \u2014 ${l.verify}`)),console.log(X.dim(` ${u.reason}`)),console.log(X.dim(` screenshot: ${u.sighting.shot.path}`)),await So(2500);try{r?.stdin?.end()}catch{}d=!0;break}}}}}catch(g){d=!0,console.log(X.red(` stopping: ${g?.message??g}`)),a("Stopped",String(g?.message??g),"waiting")}finally{if(d)try{r?.stdin?.end()}catch{}}if(!d){a("Done",t.title,"done"),await So(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await So(2500);try{let{size:g}=Im(i);console.log(X.green(` recorded ${(g/1048576).toFixed(1)} MB \u2192 ${i}`))}catch{console.log(X.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(d){console.log(X.red(` lesson stopped before the end.
363
+ `));try{t.start&&(await ni("/usr/bin/open",Xm(t.start)),await Eo(2e3),await zn(t.start.ready))}catch(g){console.log(X.red(` setup stopped: ${g?.message??g}`)),process.exitCode=3;return}let s=null,i=null;o.record&&(i=Rc(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(X.dim(` recording \u2192 ${i}`)),s=Nc("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await Eo(2e3));let r=o.hud===!1?null:Nc($e,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(g,d,u,f)=>{try{r?.stdin?.write(JSON.stringify({title:g,body:d,state:u,avoid:f})+`
364
+ `)}catch{}},c=[],l=!1;try{for(let[g,d]of t.steps.entries()){if(console.log(` ${X.dim(String(g+1).padStart(2))} ${d.say}`),a(`Step ${g+1} of ${t.steps.length}`,d.say,"talking"),d.click||d.type||d.key){if(!d.before)throw new Error(`Step ${g+1} needs a before claim`);await zn(d.before)}let u=o.speak===!1?Promise.resolve():op(d.say,n),f=d.find?await Qm(d.find,c):null;if(d.find&&!f)throw c.push({tried:d.find,changed:!1,note:"not found on screen"}),await u,new Error(`Could not find "${d.find}"; stopped before acting`);if(await u,f&&(a(`Step ${g+1} of ${t.steps.length}`,d.say,"pointing",{x:f.x,y:f.y,w:f.width,h:f.height}),await ni($e,["point","--x",String(f.x),"--y",String(f.y),"--w",String(f.width),"--h",String(f.height),"--label",d.label??d.find??"","--hold",String(d.click||d.type?.5:d.holdSeconds??2.6)]),d.click)){let{error:p,changed:w}=await ti(["click"]);if(p)throw new Error(p);c.push({tried:d.label??d.find??"control",changed:w!==!1,note:p??void 0}),w===!1&&console.log(X.yellow(" \xB7 clicked, but the screen did not change")),await Eo(d.afterClickWaitMs??1500)}if(d.type){await zn(d.before),a(`Step ${g+1} of ${t.steps.length}`,d.type,"typing");let{error:p}=await ti(["type","--text",d.type]);if(p)throw console.log(X.red(` \u2717 ${p}`)),a("Blocked",p,"waiting"),c.push({tried:`type into ${d.label??"the field"}`,changed:!1,note:p}),new Error(p)}if(d.key){await zn(d.before),a(`Step ${g+1} of ${t.steps.length}`,`\u21B5 ${d.key}`,"typing");let{error:p}=await ti(["key","--name",d.key]);if(p)throw console.log(X.red(` \u2717 ${p}`)),a("Blocked",p,"waiting"),c.push({tried:`press ${d.key}`,changed:!1,note:p}),new Error(p)}if(!f&&!d.type&&!d.key?await Eo((d.holdSeconds??1.2)*1e3):d.holdSeconds&&await Eo(d.holdSeconds*1e3),d.verify){a(`Step ${g+1} of ${t.steps.length}`,"Checking that worked\u2026","waiting");let p;try{p=await Yt(d.verify)}catch(w){p=null,console.log(X.yellow(` ? could not check: ${w?.message??w}`))}if(!p&&!d.verifyOptional)throw new Error(`Could not verify: ${d.verify}`);if(p){let w=p.outcome==="confirmed"?X.green("\u2713"):p.outcome==="refuted"?X.red("\u2717"):X.yellow("?");if(console.log(` ${w} ${X.dim(p.reason)}`),!p.ok&&!d.verifyOptional){a("Stopped",`That did not work: ${d.verify}`,"waiting"),console.log(X.red(`
365
+ stopping: could not confirm \u2014 ${d.verify}`)),console.log(X.dim(` ${p.reason}`)),console.log(X.dim(` screenshot: ${p.sighting.shot.path}`)),await Eo(2500);try{r?.stdin?.end()}catch{}l=!0;break}}}}}catch(g){l=!0,console.log(X.red(` stopping: ${g?.message??g}`)),a("Stopped",String(g?.message??g),"waiting")}finally{if(l)try{r?.stdin?.end()}catch{}}if(!l){a("Done",t.title,"done"),await Eo(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await Eo(2500);try{let{size:g}=Vm(i);console.log(X.green(` recorded ${(g/1048576).toFixed(1)} MB \u2192 ${i}`))}catch{console.log(X.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(l){console.log(X.red(` lesson stopped before the end.
339
366
  `)),process.exitCode=3;return}console.log(X.green(`
340
367
  done.
341
- `))});function Cm(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${hc(jm(),"agentx-teach-chrome")}`,"--no-first-run","--no-default-browser-check","--window-position=0,200","--window-size=1440,680",`--app=${e.url}`]:["-a",e.app,e.url]}async function Hn(e){let o=await Ht(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function Qs(e){try{let{stdout:o}=await Zs($e,e),t=JSON.parse(o||"{}");return t.ok===!1?{error:String(t.error??"refused")}:{error:null,changed:t.changed}}catch(o){try{let t=JSON.parse(o?.stdout||"{}");if(t.error)return{error:String(t.error)}}catch{}return{error:o?.message??"failed"}}}async function Nm(e,o=[]){try{let t=await bn({max:45});if(t.candidates.length<2)return null;let n=await Qe(Jt,Pn({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),Ln(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=Mn(n.answers,t.candidates);return s.present<.5?null:Dt(t,s.id)}catch{return null}}function Rm(e,o){if(e?.trim().toLowerCase()===ho)return{provider:"system",elevenlabs:Rt(),system:null,fallback:!0};let t=e?fn(e,Nt()):null;if(t)return{provider:"system",elevenlabs:Rt(),system:t.id,fallback:!0};if(e)return{provider:"elevenlabs",elevenlabs:e,system:null,fallback:!0};try{let n=_(),s=o||process.env.AGENTX_VOICE_AGENT||n.node.defaultAgent;return s&&!n.agents[s]&&console.log(X.yellow(` no agent "${s}" in agentx.json \u2014 using the default voice`)),s&&n.agents[s]?Dr(Nr(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:Rt(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(X.dim(` no agent voice (${String(n?.message??n).split(`
342
- `)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:Rt(),system:null,fallback:!0}}}var Dm=new ot;async function _m(e,o){o&&await Dm.say({voice:o,text:e})}var So=e=>new Promise(o=>setTimeout(o,e));pe();import{Command as wc}from"commander";import Me from"chalk";import{createInterface as bc}from"readline";var Pm=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function mt(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(Pm()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function Lm(e){e.type==="line"?console.log(`${Me.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(Me.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(Me.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(Me.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(Me.dim(" \xB7 hushed")):e.type==="error"?console.log(Me.red(` error: ${e.error}`)):e.type==="end"&&console.log(Me.dim(` \xB7 ended (${e.reason})`))}function $c(e){if(!e.length)return"no hand-overs measured";let o=[...e].sort((n,s)=>n-s);return`gap between speakers: median ${o[Math.floor(o.length/2)]} ms, max ${o.at(-1)} ms over ${e.length} hand-overs`}async function Mm(e,o,t){let n=_(t.config),s=n.agents,i;if(e.some(l=>!s[l])){let l=await mt("GET","/mesh").then(p=>Array.isArray(p.data)?p.data:[]).catch(()=>[]);i=new Pr(()=>n,()=>l),i.usePool(await _r(Cr()))}let r=e.map(l=>s[l]?hn(l,s,!0):i?.speaker(l,!0)),a=e.filter((l,p)=>!r[p]);if(a.length)throw new Error(`Unknown agent: ${a.join(", ")}`);let c=Date.now(),d=new Lr({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new ot,model:(l,p)=>tt({system:p})});d.on(Lm),d.on(l=>{l.type==="line"&&l.turn===0&&console.log(Me.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=bc({input:process.stdin});g.on("line",l=>{l.trim()&&d.door(l)}),process.once("SIGINT",()=>d.stop("interrupted")),await d.run(),g.close(),console.log(Me.dim(` ${$c(d.gaps)}`))}async function Fm(e,o,t){let n=await mt("POST","/talk",{agents:e,topic:o,context:t.context,maxTurns:Number(t.turns)||void 0});if(n.status>=300)throw new Error(n.data.error||`HTTP ${n.status}`);let s=bc({input:process.stdin});s.on("line",a=>{a.trim()&&mt("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void mt("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await mt("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${Me.bold(c[i].name)}: ${c[i].text}`);if(r=a.gaps??r,!a.active)break;await new Promise(d=>setTimeout(d,400))}s.close(),console.log(Me.dim(` ${$c(r)}`))}var kc=new wc().name("talk").description('two agents, local or on a mesh peer, talk a topic through out loud; type to cut in, "stop" to end').argument("<agentA>").argument("<agentB>").argument("<topic...>").option("--context <text>","a few lines of context both agents should know").option("--turns <n>","most lines before they wrap up (default 10)").option("--local","run the talk in this process instead of the daemon").option("-c, --config <path>","agentx.json for --local (default: the usual lookup)").action(async(e,o,t,n)=>{let s=t.join(" ");try{await(n.local?Mm:Fm)([e,o],s,n),process.exit(0)}catch(i){console.error(Me.red(` ${i?.message??i}`)),process.exit(1)}}),vc=new wc().name("narrate").description("switch spoken task narration on or off for an agent or one task").argument("<target>","agent id, or task id with --task").argument("<state>","on | off | default").option("--task","the target is a task id").action(async(e,o,t)=>{let n=o==="on"?!0:o==="off"?!1:o==="default"?null:void 0;n===void 0&&(console.error(Me.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await mt("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(Me.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});pe();import{Command as Um}from"commander";import Ee from"chalk";import{existsSync as qm,readFileSync as Wm,writeFileSync as Bm}from"fs";import{resolve as xc}from"path";var zn=new Um().name("voice").description("list installed system voices and pick each agent's voice");function Jm(e){let o=e?[e]:[xc(process.cwd(),"agentx.json"),xc(process.cwd(),".agentx/config.json")],t=o.find(n=>qm(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function Gm(e,o,t,n,s){let{provider:i,gender:r}=n,a=n.lang?.toLowerCase().split(/[-_]/)[0],c=e?.agents?.[o];if(!c)throw new Error(`No agent "${o}" in agentx.json`);if(i&&i!=="system"&&i!=="elevenlabs")throw new Error("--provider must be system or elevenlabs");if(r&&!["female","male","neutral"].includes(r))throw new Error("--gender must be female, male or neutral");if(a&&!t)throw new Error("--lang needs a voice");if(!t&&!i&&!r)throw new Error("Give a voice, a --provider, a --gender, or a mix");let d={...c.voice??{}};i&&(d.provider=i),r&&(d.gender=r);let g=d.provider??e?.voice?.provider??"system",l=[i&&`provider ${i}`,r&&`gender ${r}`],p=w=>{if(!a){d.system=w;return}let y=typeof d.system=="string"?{[String(e?.voice?.locale??"en").toLowerCase().split(/[-_]/)[0]]:d.system}:{...d.system??{}};d.system={...y,[a]:w}},f=a?` for ${a}`:"";if(t){let w=t.trim().toLowerCase()===ho,y=w?null:fn(t,s,a??e?.voice?.locale),k=y?`system voice ${vs(y)}`:"the OS default voice";if((y||w)&&g==="system")p(w?ho:t),l.push(`${k}${f}`);else if(g==="elevenlabs"&&!y&&!w&&!a)d.elevenlabsVoiceId=t,l.push(`ElevenLabs voice ${t}`);else if(y||w)p(w?ho:t),l.push(`fallback ${k}${f}`);else throw new Error(`"${t}" is not an installed system voice. Run \`agentx voice list\`, or add --provider elevenlabs for an ElevenLabs voice id.`)}let u=l.filter(Boolean).join(", ");return{raw:{...e,agents:{...e.agents,[o]:{...c,voice:d}}},summary:u}}zn.command("list").alias("ls").description("installed system voices, best first, and which agent uses which").option("--all","every language, not only the configured one").option("-c, --config <path>","agentx.json to read").action(e=>{let o=Nt(),t;try{t=_(e.config)}catch{}let n=t?.voice.locale??"en",s=new Map,i=t?Rr(t.agents,t.voice,o):new Map;if(t)for(let[r,a]of Object.entries(t.agents)){let c=i.get(r),d=Object.values(xs(r,a.voice?.system,a.voice?.gender,t.voice,o));for(let g of new Set([c,...d]))g&&s.set(g.id,[...s.get(g.id)??[],r])}if(!o.length)console.log(Ee.yellow(`
368
+ `))});function Xm(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${Rc(Km(),"agentx-teach-chrome")}`,"--no-first-run","--no-default-browser-check","--window-position=0,200","--window-size=1440,680",`--app=${e.url}`]:["-a",e.app,e.url]}async function zn(e){let o=await Yt(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function ti(e){try{let{stdout:o}=await ni($e,e),t=JSON.parse(o||"{}");return t.ok===!1?{error:String(t.error??"refused")}:{error:null,changed:t.changed}}catch(o){try{let t=JSON.parse(o?.stdout||"{}");if(t.error)return{error:String(t.error)}}catch{}return{error:o?.message??"failed"}}}async function Qm(e,o=[]){try{let t=await vn({max:45});if(t.candidates.length<2)return null;let n=await Ze(Ht,Fn({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),Un(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=qn(n.answers,t.candidates);return s.present<.5?null:Pt(t,s.id)}catch{return null}}function Zm(e,o){if(e?.trim().toLowerCase()===yo)return{provider:"system",elevenlabs:_t(),system:null,fallback:!0};let t=e?$n(e,Dt()):null;if(t)return{provider:"system",elevenlabs:_t(),system:t.id,fallback:!0};if(e)return{provider:"elevenlabs",elevenlabs:e,system:null,fallback:!0};try{let n=_(),s=o||process.env.AGENTX_VOICE_AGENT||n.node.defaultAgent;return s&&!n.agents[s]&&console.log(X.yellow(` no agent "${s}" in agentx.json \u2014 using the default voice`)),s&&n.agents[s]?Kr(Yr(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:_t(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(X.dim(` no agent voice (${String(n?.message??n).split(`
369
+ `)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:_t(),system:null,fallback:!0}}}var ep=new st;async function op(e,o){o&&await ep.say({voice:o,text:e})}var Eo=e=>new Promise(o=>setTimeout(o,e));ge();import{Command as _c}from"commander";import Ue from"chalk";import{createInterface as Pc}from"readline";var tp=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function ft(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(tp()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function np(e){e.type==="line"?console.log(`${Ue.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(Ue.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(Ue.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(Ue.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(Ue.dim(" \xB7 hushed")):e.type==="error"?console.log(Ue.red(` error: ${e.error}`)):e.type==="end"&&console.log(Ue.dim(` \xB7 ended (${e.reason})`))}function Mc(e){if(!e.length)return"no hand-overs measured";let o=[...e].sort((n,s)=>n-s);return`gap between speakers: median ${o[Math.floor(o.length/2)]} ms, max ${o.at(-1)} ms over ${e.length} hand-overs`}async function sp(e,o,t){let n=_(t.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await ft("GET","/mesh").then(u=>Array.isArray(u.data)?u.data:[]).catch(()=>[]);i=new Qr(()=>n,()=>d),i.usePool(await Xr(zr()))}let r=e.map(d=>s[d]?kn(d,s,!0):i?.speaker(d,!0)),a=e.filter((d,u)=>!r[u]);if(a.length)throw new Error(`Unknown agent: ${a.join(", ")}`);let c=Date.now(),l=new ea({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new st,listener:n.voice.listener,model:(d,u)=>it({system:u})});l.on(np),l.on(d=>{d.type==="line"&&d.turn===0&&console.log(Ue.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=Pc({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close(),console.log(Ue.dim(` ${Mc(l.gaps)}`))}async function ip(e,o,t){let n=await ft("POST","/talk",{agents:e,topic:o,context:t.context,maxTurns:Number(t.turns)||void 0});if(n.status>=300)throw new Error(n.data.error||`HTTP ${n.status}`);let s=Pc({input:process.stdin});s.on("line",a=>{a.trim()&&ft("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void ft("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await ft("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${Ue.bold(c[i].name)}: ${c[i].text}`);if(r=a.gaps??r,!a.active)break;await new Promise(l=>setTimeout(l,400))}s.close(),console.log(Ue.dim(` ${Mc(r)}`))}var Lc=new _c().name("talk").description('two agents, local or on a mesh peer, talk a topic through out loud; type to cut in, "stop" to end').argument("<agentA>").argument("<agentB>").argument("<topic...>").option("--context <text>","a few lines of context both agents should know").option("--turns <n>","most lines before they wrap up (default 10)").option("--local","run the talk in this process instead of the daemon").option("-c, --config <path>","agentx.json for --local (default: the usual lookup)").action(async(e,o,t,n)=>{let s=t.join(" ");try{await(n.local?sp:ip)([e,o],s,n),process.exit(0)}catch(i){console.error(Ue.red(` ${i?.message??i}`)),process.exit(1)}}),Fc=new _c().name("narrate").description("switch spoken task narration on or off for an agent or one task").argument("<target>","agent id, or task id with --task").argument("<state>","on | off | default").option("--task","the target is a task id").action(async(e,o,t)=>{let n=o==="on"?!0:o==="off"?!1:o==="default"?null:void 0;n===void 0&&(console.error(Ue.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await ft("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(Ue.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});ge();import{Command as rp}from"commander";import Ae from"chalk";import{existsSync as ap,readFileSync as cp,writeFileSync as lp}from"fs";import{resolve as Uc}from"path";var Yn=new rp().name("voice").description("list installed system voices and pick each agent's voice");function dp(e){let o=e?[e]:[Uc(process.cwd(),"agentx.json"),Uc(process.cwd(),".agentx/config.json")],t=o.find(n=>ap(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function gp(e,o,t,n,s){let{provider:i,gender:r}=n,a=n.lang?.toLowerCase().split(/[-_]/)[0],c=e?.agents?.[o];if(!c)throw new Error(`No agent "${o}" in agentx.json`);if(i&&i!=="system"&&i!=="elevenlabs")throw new Error("--provider must be system or elevenlabs");if(r&&!["female","male","neutral"].includes(r))throw new Error("--gender must be female, male or neutral");if(a&&!t)throw new Error("--lang needs a voice");if(!t&&!i&&!r)throw new Error("Give a voice, a --provider, a --gender, or a mix");let l={...c.voice??{}};i&&(l.provider=i),r&&(l.gender=r);let g=l.provider??e?.voice?.provider??"system",d=[i&&`provider ${i}`,r&&`gender ${r}`],u=w=>{if(!a){l.system=w;return}let y=typeof l.system=="string"?{[String(e?.voice?.locale??"en").toLowerCase().split(/[-_]/)[0]]:l.system}:{...l.system??{}};l.system={...y,[a]:w}},f=a?` for ${a}`:"";if(t){let w=t.trim().toLowerCase()===yo,y=w?null:$n(t,s,a??e?.voice?.locale),k=y?`system voice ${Ss(y)}`:"the OS default voice";if((y||w)&&g==="system")u(w?yo:t),d.push(`${k}${f}`);else if(g==="elevenlabs"&&!y&&!w&&!a)l.elevenlabsVoiceId=t,d.push(`ElevenLabs voice ${t}`);else if(y||w)u(w?yo:t),d.push(`fallback ${k}${f}`);else throw new Error(`"${t}" is not an installed system voice. Run \`agentx voice list\`, or add --provider elevenlabs for an ElevenLabs voice id.`)}let p=d.filter(Boolean).join(", ");return{raw:{...e,agents:{...e.agents,[o]:{...c,voice:l}}},summary:p}}Yn.command("list").alias("ls").description("installed system voices, best first, and which agent uses which").option("--all","every language, not only the configured one").option("-c, --config <path>","agentx.json to read").action(e=>{let o=Dt(),t;try{t=_(e.config)}catch{}let n=t?.voice.locale??"en",s=new Map,i=t?Vr(t.agents,t.voice,o):new Map;if(t)for(let[r,a]of Object.entries(t.agents)){let c=i.get(r),l=Object.values(Es(r,a.voice?.system,a.voice?.gender,t.voice,o));for(let g of new Set([c,...l]))g&&s.set(g.id,[...s.get(g.id)??[],r])}if(!o.length)console.log(Ae.yellow(`
343
370
  No system voices found (system voices need macOS).
344
- `));else{let r=e.all?ks(o,""):ks(o,n);console.log(Ee.bold(`
371
+ `));else{let r=e.all?xs(o,""):xs(o,n);console.log(Ae.bold(`
345
372
  System voices${e.all?"":` (${n})`}, best first
346
- `));for(let a of r){let c=a.siri?Ee.magenta("siri"):a.quality==="standard"?Ee.dim("standard"):Ee.green(a.quality),d=s.get(a.id)?.join(", ");console.log(` ${(a.siri?`siri:${a.name.toLowerCase()}`:a.name).padEnd(12)} ${a.locale.padEnd(6)} ${c.padEnd(18)} ${Ee.dim((a.gender??"").padEnd(7))} ${d?Ee.cyan(d):""}`)}o.some(a=>a.quality!=="standard")||(console.log(Ee.dim(`
347
- More natural voices are free: System Settings \u2192 Accessibility \u2192 Spoken Content \u2192`)),console.log(Ee.dim(" System Voice \u2192 Manage Voices, then download a Premium or Enhanced voice.")))}if(t){console.log(Ee.bold(`
373
+ `));for(let a of r){let c=a.siri?Ae.magenta("siri"):a.quality==="standard"?Ae.dim("standard"):Ae.green(a.quality),l=s.get(a.id)?.join(", ");console.log(` ${(a.siri?`siri:${a.name.toLowerCase()}`:a.name).padEnd(12)} ${a.locale.padEnd(6)} ${c.padEnd(18)} ${Ae.dim((a.gender??"").padEnd(7))} ${l?Ae.cyan(l):""}`)}o.some(a=>a.quality!=="standard")||(console.log(Ae.dim(`
374
+ More natural voices are free: System Settings \u2192 Accessibility \u2192 Spoken Content \u2192`)),console.log(Ae.dim(" System Voice \u2192 Manage Voices, then download a Premium or Enhanced voice.")))}if(t){console.log(Ae.bold(`
348
375
  Agents
349
- `));for(let[r,a]of Object.entries(t.agents)){let c=a.voice?.provider??t.voice.provider,d=p=>p?vs(p):Ee.dim("system default"),g=Object.entries(xs(r,a.voice?.system,a.voice?.gender,t.voice,o)).filter(([,p])=>(p?.id??null)!==(i.get(r)?.id??null)).map(([p,f])=>`${Ee.dim(`${p}:`)} ${d(f)}`).join(Ee.dim(" \xB7 ")),l=c==="elevenlabs"?`elevenlabs ${a.voice?.elevenlabsVoiceId??Ee.dim("(default voice)")}`:`system ${d(i.get(r))}${g?Ee.dim(" \xB7 ")+g:""}`;console.log(` ${r.padEnd(24)} ${l}${a.voice?.gender?Ee.dim(` (${a.voice.gender})`):""}`)}}console.log()});zn.command("set <agent> [voice]").description(`pick an agent's voice: a system voice name, a Siri voice as siri:<name>, "${ho}" for the OS default, or an ElevenLabs id with --provider elevenlabs`).option("--provider <provider>","system or elevenlabs").option("--lang <lang>","use this voice for lines in one language only: en, fr, ar").option("--gender <gender>","female, male or neutral; an assigned voice matches it").option("-c, --config <path>","agentx.json to change").action((e,o,t)=>{try{let n=Jm(t.config),{raw:s,summary:i}=Gm(JSON.parse(Wm(n,"utf8")),e,o,t,Nt());Bm(n,JSON.stringify(s,null,2)+`
350
- `),console.log(Ee.green(` ${e}: ${i}`)),console.log(Ee.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(Ee.red(` ${n.message}`)),process.exit(1)}});import{Command as Hm}from"commander";import M from"chalk";var Wo=new Hm().name("attach").description("wear an agentx agent identity in this Claude Code session"),ei=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Lt()}`;function oi(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function ti(e,o,t){let n=await fetch(`${e}${o}`,{method:t?"POST":"GET",headers:{"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0}),s=await n.text(),i=null;try{i=s?JSON.parse(s):null}catch{}if(!n.ok)throw new Error(i?.error||s||`HTTP ${n.status}`);return i}function ni(e){let o=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(o)?`daemon not reachable \u2014 start it with ${M.cyan("agentx daemon start")}`:o}function Sc(e){return e==="auto"?M.yellow:e==="manual"?M.gray:M.green}function zm(e,o=!1){let t=e.agentIds.length?e.agentIds.join(", "):M.gray("(not bound)"),n=e.pending?M.yellow(`${e.pending} pending`):M.gray("empty"),s=o?M.cyan(" \u2190 this session"):"";console.log(` ${M.bold(t)} ${Sc(e.mode)(e.mode)} ${n} ${M.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${M.gray(e.cwd)}`)}Wo.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${ws.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",ei).action(async(e,o)=>{let t=oi(o.session);t||(console.error(M.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${M.cyan("--session <id>")} (list them with ${M.cyan("agentx attach list")}).`),process.exit(1)),Qi(o.mode)||(console.error(M.red(`Invalid mode "${o.mode}". Expected one of: ${ws.join(", ")}`)),process.exit(1)),jn()||(console.error(M.yellow("Attach hooks are not installed yet.")),console.error(`Run ${M.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{let n=await ti(o.url,"/attach/bind",{sessionId:t,agentId:e,mode:o.mode,cwd:process.cwd()});console.log(`${M.green("\u2713")} This session is now wearing ${M.bold(e)} (${Sc(o.mode)(o.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(M.yellow(` ${s} message(s) already queued for it.`)),console.log(M.gray(o.mode==="auto"?" Queued messages will be answered automatically at the end of each turn.":o.mode==="notify"?" You'll be told when messages arrive; run /inbox to answer them.":" Nothing will interrupt you; run /inbox to check for messages."))}catch(n){console.error(M.red(`Bind failed: ${ni(n)}`)),process.exit(1)}});Wo.command("detach").description("stop wearing an identity in this session (queued work falls back to spawned agents)").option("--agent <id>","release only this identity (default: all)").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",ei).action(async e=>{let o=oi(e.session);o||(console.error(M.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await ti(e.url,"/attach/detach",{sessionId:o,agentId:e.agent}),console.log(`${M.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(t){console.error(M.red(`Detach failed: ${ni(t)}`)),process.exit(1)}});Wo.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",ei).option("--json","raw JSON output").action(async e=>{let o=oi();try{let n=(await ti(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:jn(),sessions:n},null,2));return}console.log(),console.log(jn()?`${M.green("\u2713")} Attach hooks installed ${M.gray(Pt())}`:`${M.yellow("!")} Attach hooks not installed \u2014 run ${M.cyan("agentx attach install")}`),console.log();let s=n.filter(r=>r.agentIds.length>0);if(s.length===0)console.log(M.gray(" No session is wearing an identity right now."));else for(let r of s)zm(r,r.sessionId===o);let i=n.length-s.length;i>0&&console.log(M.gray(`
351
- ${i} registered session(s) with no binding.`)),console.log()}catch(t){console.error(M.red(`Could not read attach state: ${ni(t)}`)),process.exit(1)}});Wo.command("install").description("wire the attach hooks into ~/.claude/settings.json (one time, all sessions)").option("--port <n>","daemon port the hooks should call (default: node.bind in agentx.json)").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--no-guard","skip the PreToolUse guard hook (not recommended)").action(e=>{try{let o=String(e.port||Lt()),t=pa(o,{path:e.path,withGuard:e.guard});console.log(t.changed?`${M.green("\u2713")} Installed attach hooks in ${M.gray(t.path)}`:`${M.green("\u2713")} Attach hooks already up to date in ${M.gray(t.path)}`),console.log(M.gray(` Events: ${t.events.join(", ")} \u2192 127.0.0.1:${o}`)),t.guardInstalled?(console.log(M.gray(" PreToolUse guard installed at user scope.")),console.log(M.gray(` (An attached session runs under your permissions, not the agent's workspace
376
+ `));for(let[r,a]of Object.entries(t.agents)){let c=a.voice?.provider??t.voice.provider,l=u=>u?Ss(u):Ae.dim("system default"),g=Object.entries(Es(r,a.voice?.system,a.voice?.gender,t.voice,o)).filter(([,u])=>(u?.id??null)!==(i.get(r)?.id??null)).map(([u,f])=>`${Ae.dim(`${u}:`)} ${l(f)}`).join(Ae.dim(" \xB7 ")),d=c==="elevenlabs"?`elevenlabs ${a.voice?.elevenlabsVoiceId??Ae.dim("(default voice)")}`:`system ${l(i.get(r))}${g?Ae.dim(" \xB7 ")+g:""}`;console.log(` ${r.padEnd(24)} ${d}${a.voice?.gender?Ae.dim(` (${a.voice.gender})`):""}`)}}console.log()});Yn.command("set <agent> [voice]").description(`pick an agent's voice: a system voice name, a Siri voice as siri:<name>, "${yo}" for the OS default, or an ElevenLabs id with --provider elevenlabs`).option("--provider <provider>","system or elevenlabs").option("--lang <lang>","use this voice for lines in one language only: en, fr, ar").option("--gender <gender>","female, male or neutral; an assigned voice matches it").option("-c, --config <path>","agentx.json to change").action((e,o,t)=>{try{let n=dp(t.config),{raw:s,summary:i}=gp(JSON.parse(cp(n,"utf8")),e,o,t,Dt());lp(n,JSON.stringify(s,null,2)+`
377
+ `),console.log(Ae.green(` ${e}: ${i}`)),console.log(Ae.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(Ae.red(` ${n.message}`)),process.exit(1)}});import{Command as mp}from"commander";import L from"chalk";var Jo=new mp().name("attach").description("wear an agentx agent identity in this Claude Code session"),si=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Ft()}`;function ii(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function ri(e,o,t){let n=await fetch(`${e}${o}`,{method:t?"POST":"GET",headers:{"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0}),s=await n.text(),i=null;try{i=s?JSON.parse(s):null}catch{}if(!n.ok)throw new Error(i?.error||s||`HTTP ${n.status}`);return i}function ai(e){let o=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(o)?`daemon not reachable \u2014 start it with ${L.cyan("agentx daemon start")}`:o}function qc(e){return e==="auto"?L.yellow:e==="manual"?L.gray:L.green}function pp(e,o=!1){let t=e.agentIds.length?e.agentIds.join(", "):L.gray("(not bound)"),n=e.pending?L.yellow(`${e.pending} pending`):L.gray("empty"),s=o?L.cyan(" \u2190 this session"):"";console.log(` ${L.bold(t)} ${qc(e.mode)(e.mode)} ${n} ${L.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${L.gray(e.cwd)}`)}Jo.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${ys.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",si).action(async(e,o)=>{let t=ii(o.session);t||(console.error(L.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${L.cyan("--session <id>")} (list them with ${L.cyan("agentx attach list")}).`),process.exit(1)),tr(o.mode)||(console.error(L.red(`Invalid mode "${o.mode}". Expected one of: ${ys.join(", ")}`)),process.exit(1)),Rn()||(console.error(L.yellow("Attach hooks are not installed yet.")),console.error(`Run ${L.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{let n=await ri(o.url,"/attach/bind",{sessionId:t,agentId:e,mode:o.mode,cwd:process.cwd()});console.log(`${L.green("\u2713")} This session is now wearing ${L.bold(e)} (${qc(o.mode)(o.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(L.yellow(` ${s} message(s) already queued for it.`)),console.log(L.gray(o.mode==="auto"?" Queued messages will be answered automatically at the end of each turn.":o.mode==="notify"?" You'll be told when messages arrive; run /inbox to answer them.":" Nothing will interrupt you; run /inbox to check for messages."))}catch(n){console.error(L.red(`Bind failed: ${ai(n)}`)),process.exit(1)}});Jo.command("detach").description("stop wearing an identity in this session (queued work falls back to spawned agents)").option("--agent <id>","release only this identity (default: all)").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",si).action(async e=>{let o=ii(e.session);o||(console.error(L.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await ri(e.url,"/attach/detach",{sessionId:o,agentId:e.agent}),console.log(`${L.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(t){console.error(L.red(`Detach failed: ${ai(t)}`)),process.exit(1)}});Jo.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",si).option("--json","raw JSON output").action(async e=>{let o=ii();try{let n=(await ri(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:Rn(),sessions:n},null,2));return}console.log(),console.log(Rn()?`${L.green("\u2713")} Attach hooks installed ${L.gray(Lt())}`:`${L.yellow("!")} Attach hooks not installed \u2014 run ${L.cyan("agentx attach install")}`),console.log();let s=n.filter(r=>r.agentIds.length>0);if(s.length===0)console.log(L.gray(" No session is wearing an identity right now."));else for(let r of s)pp(r,r.sessionId===o);let i=n.length-s.length;i>0&&console.log(L.gray(`
378
+ ${i} registered session(s) with no binding.`)),console.log()}catch(t){console.error(L.red(`Could not read attach state: ${ai(t)}`)),process.exit(1)}});Jo.command("install").description("wire the attach hooks into ~/.claude/settings.json (one time, all sessions)").option("--port <n>","daemon port the hooks should call (default: node.bind in agentx.json)").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--no-guard","skip the PreToolUse guard hook (not recommended)").action(e=>{try{let o=String(e.port||Ft()),t=Oa(o,{path:e.path,withGuard:e.guard});console.log(t.changed?`${L.green("\u2713")} Installed attach hooks in ${L.gray(t.path)}`:`${L.green("\u2713")} Attach hooks already up to date in ${L.gray(t.path)}`),console.log(L.gray(` Events: ${t.events.join(", ")} \u2192 127.0.0.1:${o}`)),t.guardInstalled?(console.log(L.gray(" PreToolUse guard installed at user scope.")),console.log(L.gray(` (An attached session runs under your permissions, not the agent's workspace
352
379
  settings \u2014 without this an attached production identity would be less
353
- guarded than a spawned one.)`))):console.log(M.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${M.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(M.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Wo.command("uninstall").description("remove the attach hooks from ~/.claude/settings.json").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--remove-guard","also remove the PreToolUse guard hook").action(e=>{try{let o=ua({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${M.green("\u2713")} Removed attach hooks from ${M.gray(o.path)} (${o.events.join(", ")})`:`${M.gray("Nothing to remove.")}`),e.removeGuard||console.log(M.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(M.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});pe();import{Command as Ym}from"commander";import ue from"chalk";var Yn=new Ym().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Ac(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=_(e.config);o||(o=n.dashboard?.daemonUrl||""),t||(t=n.dashboard?.token||"")}catch{}return o||(o="http://localhost:18800"),{baseUrl:o.replace(/\/+$/,""),token:t}}function Oc(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function Ec(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s`:o<3600?`${Math.round(o/60)}m`:o<86400?`${Math.round(o/3600)}h`:`${Math.round(o/86400)}d`}function Vm(e){return e==="busy"?ue.magenta:e==="warm-hot"?ue.green:e==="warm-cold"?ue.cyan:e==="idle"?ue.yellow:e==="dead"?ue.red:ue.dim}Yn.command("list").description("list every live persistent claude process").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("--json","emit JSON").action(async e=>{let{baseUrl:o,token:t}=Ac(e),n;try{n=await fetch(`${o}/api/processes`,{headers:Oc(t)})}catch(r){console.log(ue.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(ue.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(ue.red(` HTTP ${n.status} from ${o}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(ue.dim(" (no processes)"));return}for(let r of i){let a=Vm(r.state)(r.state.padEnd(9)),c=Ec(r.spawnedAt),d=r.lastTurnAt?Ec(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?ue.dim(`last_in=${r.lastInputTokens} tok`):"",l=r.claudeSessionId?ue.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):ue.dim("sess=\u2014"),p=r.pendingTaskId?ue.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${ue.bold(r.key.agentId)}${ue.dim(":"+r.key.channel+":"+r.key.chatId)} ${ue.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${d} ${l} ${g} ${p}`),r.deadReason&&console.log(` ${ue.red("dead:")} ${r.deadReason}`)}});Yn.command("kill <agentId> <channel> <chatId>").description("force-kill one persistent process (the next dispatch will spawn fresh)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("-r, --reason <reason>","kill reason (recorded on the dead-process snapshot)","operator-cli").action(async(e,o,t,n)=>{let{baseUrl:s,token:i}=Ac(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Oc(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(ue.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(ue.dim(" daemon has no persistent-process registry"));return}if(!r.ok){let a=`HTTP ${r.status}`;try{let c=await r.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(ue.red(` ${a}`)),process.exit(1)}console.log(ue.green(` killed ${e}:${o}:${t}`))});import{Command as Km}from"commander";import Ce from"chalk";import{existsSync as si,rmSync as Xm}from"fs";import{resolve as ii}from"path";var pt=new Km().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");pt.command("add <agentId>").description("build or refresh an agent's lexical index from one or more globs").argument("<globs...>","glob patterns relative to cwd (e.g. './docs/**/*.md')").option("-v, --verbose","log each indexed file").action(async(e,o,t)=>{o.length===0&&(console.log(Ce.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await tr(e,o,{verbose:n}),r=Date.now()-s;console.log(Ce.green(` \u2713 indexed ${i.docs} doc(s) for ${Ce.bold(e)} in ${r}ms`)),console.log(Ce.dim(` \u2192 ${i.path}`))});pt.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=ii(e.cwd,".agentx","rag");if(!si(o)){console.log(Ce.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>si(ii(o,s,"index.json")));if(n.length===0){console.log(Ce.dim(" (no indexes)"));return}for(let s of n.sort()){let i=bs(s);console.log(` ${Ce.bold(s)} ${i.docs} doc(s) ${Ce.dim(i.path)}`)}});pt.command("search <agentId> <query>").description("query an agent's index \u2014 useful for debugging recall before the agent calls rag.lexical").option("-k, --k <n>","top-k results","5").option("--json","emit JSON").action((e,o,t)=>{let n=parseInt(t.k,10)||5,s=nr(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=bs(e);i.exists?console.log(Ce.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Ce.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Ce.bold(i.title)} ${Ce.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Ce.dim(i.path)}`),console.log(` ${Ce.dim(i.snippet.slice(0,200))}`)});pt.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=ii(process.cwd(),".agentx","rag",e);if(!si(o)){console.log(Ce.dim(` no index for ${e} \u2014 nothing to clear`));return}Xm(o,{recursive:!0,force:!0}),console.log(Ce.green(` \u2713 cleared index for ${e}`))});pe();import{Command as Qm}from"commander";import K from"chalk";import ut from"prompts";var Bo=new Qm().name("backlog").description("manage the local backlog used by business workSource=backlog");function Vt(e){let o=_(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new Gr(n)}}function Zm(e){return e?K.cyan(`${e.type}:${e.project}#${e.iid}`):K.dim("manual")}function ep(e){return{todo:K.gray("todo"),doing:K.yellow("doing"),blocked:K.red("blocked"),done:K.green("done")}[e]}Bo.command("list",{isDefault:!0}).description("list backlog items").option("--status <status>","filter by status (todo|doing|blocked|done)").option("--assignee <agent>","filter by assignee").option("--source <type>","filter by source.type (gitlab|github|manual)").option("-c, --config <path>","config path").action(async e=>{let{store:o}=Vt(e.config),t=o.list();if(e.status&&(t=t.filter(n=>n.status===e.status)),e.assignee&&(t=t.filter(n=>n.assignee===e.assignee)),e.source&&(t=t.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!t.length){console.log(K.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?K.magenta(`@${n.assignee}`):K.dim("unassigned");console.log(` ${ep(n.status).padEnd(7)} ${Zm(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(K.dim(` ${n.source.url}`))}console.log(),console.log(K.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});Bo.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,o,t)=>{let n=Vt(t.config);n.store.findById(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(K.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=Hr([o],i.source,n.config),a=await Os(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(K.dim(" sync:"),...c));console.log(a.ok?K.dim(` synced -> ${a.url??i.source.type}`):K.yellow(` sync failed: ${a.error}`))}});Bo.command("done <id>").description("mark an item as done; closes the upstream issue if linked").option("--note <text>","comment to post upstream").option("--close","also close the upstream issue (default: only labels change)",!1).option("-c, --config <path>","config path").action(async(e,o)=>{let t=Vt(o.config);t.store.findById(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(K.green(` done: ${s.title}`)),s.source){let i=await Os(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(K.dim(" sync:"),...r));console.log(i.ok?K.dim(` synced -> ${i.url??s.source.type}`):K.yellow(` sync failed: ${i.error}`))}});Bo.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,o)=>{let{store:t}=Vt(o.config);t.remove(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1)),console.log(K.green(` removed ${e}`))});Bo.command("import").description("import open issues from gitlab/github into the backlog (interactive)").option("--source <type>","source type (gitlab|github)").option("--project <id>","project id (group/repo for gitlab, owner/repo for github)").option("--assignee <agent>","assign all imported items to this agentId").option("-c, --config <path>","config path").action(async e=>{let o=Vt(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(K.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let y=[t&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await ut({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!t&&(console.error(K.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(K.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?tp(o.config):np(o.config);y.length?(i=(await ut({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...y.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await ut({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await ut({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await ut({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(K.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await sp(o.config,i,a):await ip(o.config,i,a);if(!c.length){console.log(K.yellow(" no open issues matched"));return}console.log(K.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let d=i,g=new Set(o.store.list().map(y=>y.id)),l=c.map(y=>{let k=As({type:s,project:d,iid:y.iid,url:y.url}),b=g.has(k),x=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${x}${b?K.dim(" (already imported)"):""}`,value:y,disabled:b}}),f=(await ut({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:l,min:1})).selected||[];if(!f.length){console.log(K.dim(" nothing selected"));return}let u=f.map(y=>{let k={type:s,host:s==="gitlab"?op(o.config):void 0,project:d,iid:y.iid,url:y.url};return{id:As(k),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),w=o.store.addMany(u);console.log(K.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(K.dim(` ${y.id} \u2014 ${y.title}`))});function op(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function tp(e){let o=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&o.add(n.project);let t=e.business?.workSource;if(t?.type==="gitlab")for(let n of t.projects??[])o.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&o.add(n.id);return[...o].sort()}function np(e){let o=new Set;for(let t of e.channels.github?.routes??[])t.repo&&t.repo!=="*"&&o.add(t.repo);return[...o].sort()}async function sp(e,o,t){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});t&&s.set("search",t);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(o)}/issues?${s}`,{headers:{"PRIVATE-TOKEN":n.token}});if(!i.ok)throw new Error(`GitLab ${i.status}: ${await i.text().catch(()=>"")}`);let r=await i.json();return Array.isArray(r)?r.map(a=>({iid:a.iid,title:a.title,description:a.description||void 0,labels:Array.isArray(a.labels)?a.labels.map(c=>typeof c=="string"?c:c.name):[],milestone:a.milestone?.title||void 0,assignee:a.assignee?.username||a.assignees?.[0]?.username||void 0,url:a.web_url})):[]}async function ip(e,o,t){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(t){let c=`repo:${o} is:issue is:open ${t}`;i=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let d=await fetch(i,{headers:s});if(!d.ok)throw new Error(`GitHub ${d.status}: ${await d.text().catch(()=>"")}`);return((await d.json()).items??[]).map(Tc)}i=`https://api.github.com/repos/${o}/issues?state=open&per_page=100&sort=updated&direction=desc`;let r=await fetch(i,{headers:s});if(!r.ok)throw new Error(`GitHub ${r.status}: ${await r.text().catch(()=>"")}`);let a=await r.json();return Array.isArray(a)?a.filter(c=>!c.pull_request).map(Tc):[]}function Tc(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(o=>typeof o=="string"?o:o.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as cp}from"commander";import z from"chalk";import{existsSync as lp,readFileSync as dp}from"fs";import{resolve as gp}from"path";import mp from"prompts";pe();import rp from"cronstrue";var ri={sun:0,sunday:0,mon:1,monday:1,tue:2,tuesday:2,tues:2,wed:3,wednesday:3,thu:4,thursday:4,thurs:4,fri:5,friday:5,sat:6,saturday:6},Vn={morning:{h:9,m:0},afternoon:{h:14,m:0},evening:{h:18,m:0},night:{h:22,m:0},noon:{h:12,m:0},midnight:{h:0,m:0}};function io(e){try{return rp.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function ap(e){if(/\b(noon|midday)\b/.test(e))return Vn.noon;if(/\bmidnight\b/.test(e))return Vn.midnight;let o=e.match(/\b(?:at|by|@)\s*(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/);if(o){let t=parseInt(o[1],10),n=o[2]?parseInt(o[2],10):0,s=o[3];return s==="pm"&&t<12&&(t+=12),s==="am"&&t===12&&(t=0),t>23||n>59?null:{h:t,m:n}}return null}function ai(e){let o=e.trim().toLowerCase();if(!o)return null;let t;if(t=o.match(/\bevery\s+(\d+)\s*(minutes|mins|m)\b/)){let l=parseInt(t[1],10);return l<1||l>59?null:{cron:`*/${l} * * * *`,human:io(`*/${l} * * * *`),matched:t[0]}}if(/\bevery\s+minute\b/.test(o))return{cron:"* * * * *",human:io("* * * * *"),matched:"every minute"};if(t=o.match(/\bevery\s+(\d+)\s*(hours|hrs|h)\b/)){let l=parseInt(t[1],10);return l<1||l>23?null:{cron:`0 */${l} * * *`,human:io(`0 */${l} * * *`),matched:t[0]}}if(/\b(every hour|hourly)\b/.test(o))return{cron:"0 * * * *",human:io("0 * * * *"),matched:"every hour"};let n=ap(o),s=null;for(let[l,p]of Object.entries(Vn))if(!(l==="noon"||l==="midnight")&&new RegExp(`\\b(every\\s+)?${l}s?\\b`).test(o)){s=p;break}let i=n||s,r=o.match(/\b(first|1st|2nd|3rd|last|(\d+)(?:st|nd|rd|th)?)\s+(day\s+)?of\s+(every|each|the)\s+month\b/);if(r){let l=r[1],p=1;if(l==="last"||(/^\d+(st|nd|rd|th)?$/.test(l)?p=parseInt(l,10):l==="first"||l==="1st"?p=1:l==="2nd"?p=2:l==="3rd"&&(p=3),p<1||p>31))return null;let f=i||{h:9,m:0},u=`${f.m} ${f.h} ${p} * *`;return{cron:u,human:io(u),matched:r[0]}}let a=[],c=Object.keys(ri).join("|"),d=new RegExp(`\\b(?:every|on|each|by)\\s+((?:${c})s?(?:\\s*(?:,|and|&)\\s*(?:${c})s?)*)\\b`),g=o.match(d);if(g){let l=g[1];for(let p of Object.keys(ri))if(new RegExp(`\\b${p}s?\\b`).test(l)){let f=ri[p];a.includes(f)||a.push(f)}}if(a.length){let l=i||{h:9,m:0};a.sort((u,w)=>u-w);let p=a.join(","),f=`${l.m} ${l.h} * * ${p}`;return{cron:f,human:io(f),matched:`on ${p}`}}if(/\b(weekday|workday|business day)s?\b/.test(o)){let l=i||{h:9,m:0},p=`${l.m} ${l.h} * * 1-5`;return{cron:p,human:io(p),matched:"weekdays"}}if(/\bweekends?\b/.test(o)){let l=i||{h:9,m:0},p=`${l.m} ${l.h} * * 0,6`;return{cron:p,human:io(p),matched:"weekends"}}if(/\b(every day|daily|each day)\b/.test(o)||s){let l=i||{h:9,m:0},p=`${l.m} ${l.h} * * *`;return{cron:p,human:io(p),matched:s&&Object.entries(Vn).find(([,f])=>f===s)?.[0]||"daily"}}if(n){let l=`${n.m} ${n.h} * * *`;return{cron:l,human:io(l),matched:`at ${n.h}:${String(n.m).padStart(2,"0")}`}}return null}function Ic(e,o){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"job"}-${o}`}function jc(e){let o=e||gp(process.cwd(),"agentx.json");return lp(o)||(console.log(z.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(dp(o,"utf-8"))}function pp(e){return e?e.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o==="log"||o==="notify"||o==="disable"):["log"]}async function up(e,o){if(!e)return;if(e==="me"){let n=o?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(z.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await mp([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let t=e.split(":");if(t.length>=2)return{channel:t[0],chatId:t[1],accountId:t[2]};console.log(z.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var Eo=new cp().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');Eo.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>","IANA timezone (default: Africa/Tunis)","Africa/Tunis").option("--timeout <seconds>","max run time","600").option("--model <model>","override model").option("--disabled","create but leave disabled").option("--dry-run","print what would be written without writing").action(async(e,o)=>{if(!e){Eo.help();return}o.agent||(console.log(z.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(z.red(' --do "<prompt>" is required')),process.exit(1));let t=ai(e);t||(console.log(z.red(` Couldn't parse: "${e}"`)),console.log(z.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(z.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(z.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=jc(o.config),s=Mi(n);n.agents?.[o.agent]||(console.log(z.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(z.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=pp(o.onError),r=await up(o.notify,s);r&&!i.includes("notify")&&i.push("notify");let a=o.id||Ic(t.matched,o.agent),c={enabled:!o.disabled,schedule:t.cron,timezone:o.timezone,agent:o.agent,prompt:o.do,timeout:parseInt(o.timeout,10),onError:i};o.model&&(c.model=o.model),r&&(c.notify=r);let d=await de(l=>be(l,`crons.${a}`,c),{configPath:o.config,dryRun:!!o.dryRun});d.success||(console.log(z.red(` \u2717 ${d.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(z.green(` \u2713 ${g} cron ${z.cyan(a)}`)),console.log(z.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(z.dim(` Agent: ${o.agent}`)),r&&console.log(z.dim(` Notify: ${r.channel} ${r.chatId}`)),i.length&&console.log(z.dim(` On error: ${i.join(", ")}`)),!o.dryRun&&d.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});Eo.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async e=>{let t=jc(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(z.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.enabled?z.green("\u25CF"):z.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}console.log(` ${r} ${z.cyan(s.padEnd(32))} ${z.dim(i.schedule.padEnd(14))} ${z.dim("\u2192")} ${i.agent}`),console.log(z.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(z.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`))}console.log()});for(let[e,o]of[["on",!0],["off",!1]])Eo.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await de(s=>{if(!Ro(s,`crons.${t}`))throw new Error(`cron "${t}" not found`);be(s,`crons.${t}.enabled`,o)});n.success||(console.log(z.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(z.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});Eo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await de(t=>{if(!Ro(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);ar(t,`crons.${e}`)});o.success||(console.log(z.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(z.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});Eo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=ai(o);t||(console.log(z.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(z.green(` "${o}"`)),console.log(z.dim(` \u2192 ${t.cron}`)),console.log(z.dim(` \u2192 ${t.human}`))});import{Command as Lp}from"commander";import ft from"chalk";import Z from"chalk";import Xt from"prompts";import{readFileSync as fp,writeFileSync as hp,existsSync as yp}from"fs";import{resolve as Cc}from"path";var wp=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function bp(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function ci(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Nc(e=".env"){let o=Cc(e);if(!yp(o))return[];let t=fp(o,"utf-8"),n=[];for(let s of t.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let i=s.match(wp);i?n.push({kind:"kv",key:i[1],value:bp(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function $p(e){return e.map(o=>o.kind==="kv"?`${o.key}=${ci(o.value)}`:o.raw).join(`
380
+ guarded than a spawned one.)`))):console.log(L.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${L.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(L.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Jo.command("uninstall").description("remove the attach hooks from ~/.claude/settings.json").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--remove-guard","also remove the PreToolUse guard hook").action(e=>{try{let o=Ta({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${L.green("\u2713")} Removed attach hooks from ${L.gray(o.path)} (${o.events.join(", ")})`:`${L.gray("Nothing to remove.")}`),e.removeGuard||console.log(L.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(L.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});ge();import{Command as up}from"commander";import fe from"chalk";var Vn=new up().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Bc(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=_(e.config);o||(o=n.dashboard?.daemonUrl||""),t||(t=n.dashboard?.token||"")}catch{}return o||(o="http://localhost:18800"),{baseUrl:o.replace(/\/+$/,""),token:t}}function Jc(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function Wc(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s`:o<3600?`${Math.round(o/60)}m`:o<86400?`${Math.round(o/3600)}h`:`${Math.round(o/86400)}d`}function fp(e){return e==="busy"?fe.magenta:e==="warm-hot"?fe.green:e==="warm-cold"?fe.cyan:e==="idle"?fe.yellow:e==="dead"?fe.red:fe.dim}Vn.command("list").description("list every live persistent claude process").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("--json","emit JSON").action(async e=>{let{baseUrl:o,token:t}=Bc(e),n;try{n=await fetch(`${o}/api/processes`,{headers:Jc(t)})}catch(r){console.log(fe.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(fe.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(fe.red(` HTTP ${n.status} from ${o}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(fe.dim(" (no processes)"));return}for(let r of i){let a=fp(r.state)(r.state.padEnd(9)),c=Wc(r.spawnedAt),l=r.lastTurnAt?Wc(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?fe.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?fe.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):fe.dim("sess=\u2014"),u=r.pendingTaskId?fe.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${fe.bold(r.key.agentId)}${fe.dim(":"+r.key.channel+":"+r.key.chatId)} ${fe.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${u}`),r.deadReason&&console.log(` ${fe.red("dead:")} ${r.deadReason}`)}});Vn.command("kill <agentId> <channel> <chatId>").description("force-kill one persistent process (the next dispatch will spawn fresh)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("-r, --reason <reason>","kill reason (recorded on the dead-process snapshot)","operator-cli").action(async(e,o,t,n)=>{let{baseUrl:s,token:i}=Bc(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Jc(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(fe.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(fe.dim(" daemon has no persistent-process registry"));return}if(!r.ok){let a=`HTTP ${r.status}`;try{let c=await r.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(fe.red(` ${a}`)),process.exit(1)}console.log(fe.green(` killed ${e}:${o}:${t}`))});import{Command as hp}from"commander";import Ne from"chalk";import{existsSync as ci,rmSync as yp}from"fs";import{resolve as li}from"path";var ht=new hp().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");ht.command("add <agentId>").description("build or refresh an agent's lexical index from one or more globs").argument("<globs...>","glob patterns relative to cwd (e.g. './docs/**/*.md')").option("-v, --verbose","log each indexed file").action(async(e,o,t)=>{o.length===0&&(console.log(Ne.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await rr(e,o,{verbose:n}),r=Date.now()-s;console.log(Ne.green(` \u2713 indexed ${i.docs} doc(s) for ${Ne.bold(e)} in ${r}ms`)),console.log(Ne.dim(` \u2192 ${i.path}`))});ht.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=li(e.cwd,".agentx","rag");if(!ci(o)){console.log(Ne.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>ci(li(o,s,"index.json")));if(n.length===0){console.log(Ne.dim(" (no indexes)"));return}for(let s of n.sort()){let i=ws(s);console.log(` ${Ne.bold(s)} ${i.docs} doc(s) ${Ne.dim(i.path)}`)}});ht.command("search <agentId> <query>").description("query an agent's index \u2014 useful for debugging recall before the agent calls rag.lexical").option("-k, --k <n>","top-k results","5").option("--json","emit JSON").action((e,o,t)=>{let n=parseInt(t.k,10)||5,s=ar(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=ws(e);i.exists?console.log(Ne.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Ne.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Ne.bold(i.title)} ${Ne.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Ne.dim(i.path)}`),console.log(` ${Ne.dim(i.snippet.slice(0,200))}`)});ht.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=li(process.cwd(),".agentx","rag",e);if(!ci(o)){console.log(Ne.dim(` no index for ${e} \u2014 nothing to clear`));return}yp(o,{recursive:!0,force:!0}),console.log(Ne.green(` \u2713 cleared index for ${e}`))});ge();import{Command as wp}from"commander";import K from"chalk";import yt from"prompts";var Go=new wp().name("backlog").description("manage the local backlog used by business workSource=backlog");function Kt(e){let o=_(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new sa(n)}}function bp(e){return e?K.cyan(`${e.type}:${e.project}#${e.iid}`):K.dim("manual")}function $p(e){return{todo:K.gray("todo"),doing:K.yellow("doing"),blocked:K.red("blocked"),done:K.green("done")}[e]}Go.command("list",{isDefault:!0}).description("list backlog items").option("--status <status>","filter by status (todo|doing|blocked|done)").option("--assignee <agent>","filter by assignee").option("--source <type>","filter by source.type (gitlab|github|manual)").option("-c, --config <path>","config path").action(async e=>{let{store:o}=Kt(e.config),t=o.list();if(e.status&&(t=t.filter(n=>n.status===e.status)),e.assignee&&(t=t.filter(n=>n.assignee===e.assignee)),e.source&&(t=t.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!t.length){console.log(K.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?K.magenta(`@${n.assignee}`):K.dim("unassigned");console.log(` ${$p(n.status).padEnd(7)} ${bp(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(K.dim(` ${n.source.url}`))}console.log(),console.log(K.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});Go.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,o,t)=>{let n=Kt(t.config);n.store.findById(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(K.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=ia([o],i.source,n.config),a=await Ts(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(K.dim(" sync:"),...c));console.log(a.ok?K.dim(` synced -> ${a.url??i.source.type}`):K.yellow(` sync failed: ${a.error}`))}});Go.command("done <id>").description("mark an item as done; closes the upstream issue if linked").option("--note <text>","comment to post upstream").option("--close","also close the upstream issue (default: only labels change)",!1).option("-c, --config <path>","config path").action(async(e,o)=>{let t=Kt(o.config);t.store.findById(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(K.green(` done: ${s.title}`)),s.source){let i=await Ts(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(K.dim(" sync:"),...r));console.log(i.ok?K.dim(` synced -> ${i.url??s.source.type}`):K.yellow(` sync failed: ${i.error}`))}});Go.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,o)=>{let{store:t}=Kt(o.config);t.remove(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1)),console.log(K.green(` removed ${e}`))});Go.command("import").description("import open issues from gitlab/github into the backlog (interactive)").option("--source <type>","source type (gitlab|github)").option("--project <id>","project id (group/repo for gitlab, owner/repo for github)").option("--assignee <agent>","assign all imported items to this agentId").option("-c, --config <path>","config path").action(async e=>{let o=Kt(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(K.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let y=[t&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await yt({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!t&&(console.error(K.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(K.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?vp(o.config):xp(o.config);y.length?(i=(await yt({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...y.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await yt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await yt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await yt({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(K.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await Sp(o.config,i,a):await Ep(o.config,i,a);if(!c.length){console.log(K.yellow(" no open issues matched"));return}console.log(K.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(o.store.list().map(y=>y.id)),d=c.map(y=>{let k=Os({type:s,project:l,iid:y.iid,url:y.url}),b=g.has(k),S=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${S}${b?K.dim(" (already imported)"):""}`,value:y,disabled:b}}),f=(await yt({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!f.length){console.log(K.dim(" nothing selected"));return}let p=f.map(y=>{let k={type:s,host:s==="gitlab"?kp(o.config):void 0,project:l,iid:y.iid,url:y.url};return{id:Os(k),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),w=o.store.addMany(p);console.log(K.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(K.dim(` ${y.id} \u2014 ${y.title}`))});function kp(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function vp(e){let o=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&o.add(n.project);let t=e.business?.workSource;if(t?.type==="gitlab")for(let n of t.projects??[])o.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&o.add(n.id);return[...o].sort()}function xp(e){let o=new Set;for(let t of e.channels.github?.routes??[])t.repo&&t.repo!=="*"&&o.add(t.repo);return[...o].sort()}async function Sp(e,o,t){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});t&&s.set("search",t);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(o)}/issues?${s}`,{headers:{"PRIVATE-TOKEN":n.token}});if(!i.ok)throw new Error(`GitLab ${i.status}: ${await i.text().catch(()=>"")}`);let r=await i.json();return Array.isArray(r)?r.map(a=>({iid:a.iid,title:a.title,description:a.description||void 0,labels:Array.isArray(a.labels)?a.labels.map(c=>typeof c=="string"?c:c.name):[],milestone:a.milestone?.title||void 0,assignee:a.assignee?.username||a.assignees?.[0]?.username||void 0,url:a.web_url})):[]}async function Ep(e,o,t){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(t){let c=`repo:${o} is:issue is:open ${t}`;i=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let l=await fetch(i,{headers:s});if(!l.ok)throw new Error(`GitHub ${l.status}: ${await l.text().catch(()=>"")}`);return((await l.json()).items??[]).map(Gc)}i=`https://api.github.com/repos/${o}/issues?state=open&per_page=100&sort=updated&direction=desc`;let r=await fetch(i,{headers:s});if(!r.ok)throw new Error(`GitHub ${r.status}: ${await r.text().catch(()=>"")}`);let a=await r.json();return Array.isArray(a)?a.filter(c=>!c.pull_request).map(Gc):[]}function Gc(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(o=>typeof o=="string"?o:o.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as Ap}from"commander";import q from"chalk";import{existsSync as Op,readFileSync as Tp}from"fs";import{resolve as Ip}from"path";import jp from"prompts";ge();function Hc(e){let o=e||Ip(process.cwd(),"agentx.json");return Op(o)||(console.log(q.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Tp(o,"utf-8"))}async function Cp(e,o){if(!e)return;if(e==="me"){let n=o?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(q.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await jp([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let t=e.split(":");if(t.length>=2)return{channel:t[0],chatId:t[1],accountId:t[2]};console.log(q.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var go=new Ap().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');go.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>",`IANA timezone (default: ${ks})`,ks).option("--timeout <seconds>","max run time","600").option("--model <model>","override model").option("--disabled","create but leave disabled").option("--dry-run","print what would be written without writing").action(async(e,o)=>{if(!e){go.help();return}o.agent||(console.log(q.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(q.red(' --do "<prompt>" is required')),process.exit(1));let t=$s(e);t||(console.log(q.red(` Couldn't parse: "${e}"`)),console.log(q.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(q.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(q.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=Hc(o.config),s=Ui(n);n.agents?.[o.agent]||(console.log(q.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(q.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await Cp(o.notify,s),r=o.id||pr(t.matched,o.agent),a=fr({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:ur(o.onError),enabled:!o.disabled}),c=a.onError,l=await ue(d=>Se(d,`crons.${r}`,a),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(q.red(` \u2717 ${l.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(q.green(` \u2713 ${g} cron ${q.cyan(r)}`)),console.log(q.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(q.dim(` Agent: ${o.agent}`)),i&&console.log(q.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(q.dim(` On error: ${c.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(q.dim(" Daemon hot-reloaded."))});go.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async e=>{let t=Hc(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(q.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?q.yellow("\u25D0"):i.enabled?q.green("\u25CF"):q.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${q.cyan(s.padEnd(32))} ${q.dim(i.schedule.padEnd(14))} ${q.dim("\u2192")} ${i.agent}`),console.log(q.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(q.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(q.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=yr(hr(i.schedule,c),c);console.log(q.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(q.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,o]of[["on",!0],["off",!1]])go.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await $r(t,o);n.success||(console.log(q.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(q.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(q.dim(" Daemon hot-reloaded."))});go.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await ue(t=>{if(!nt(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);dr(t,`crons.${e}`)});o.success||(console.log(q.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(q.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(q.dim(" Daemon hot-reloaded."))});for(let[e,o,t]of[["approve",wr,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",br,"reject an agent's pending create/delete request (drops the request)"]])go.command(`${e} <id>`).description(t).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await o(n,{configPath:s.config});i.success||(console.log(q.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(q.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(q.dim(" Daemon hot-reloaded."))});go.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=$s(o);t||(console.log(q.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(q.green(` "${o}"`)),console.log(q.dim(` \u2192 ${t.cron}`)),console.log(q.dim(` \u2192 ${t.human}`))});import{Command as eu}from"commander";import wt from"chalk";import Z from"chalk";import Qt from"prompts";import{readFileSync as Np,writeFileSync as Rp,existsSync as Dp}from"fs";import{resolve as zc}from"path";var _p=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Pp(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function di(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Yc(e=".env"){let o=zc(e);if(!Dp(o))return[];let t=Np(o,"utf-8"),n=[];for(let s of t.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let i=s.match(_p);i?n.push({kind:"kv",key:i[1],value:Pp(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Mp(e){return e.map(o=>o.kind==="kv"?`${o.key}=${di(o.value)}`:o.raw).join(`
354
381
  `)+`
355
- `}function Kt(e,o,t=".env"){let n=Cc(t),s=Nc(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${ci(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${ci(o)}`})),hp(n,$p(s))}function li(e,o=".env"){return Nc(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var Rc="https://t.me/BotFather";async function kp(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function vp(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function Dc(e={}){console.log(),console.log(Z.bold(" Connect Telegram")),console.log(),console.log(Z.dim(` 1. Open ${Rc}`)),console.log(Z.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Z.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await Xt({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),x=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(x,[Rc],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Xt({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(Z.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await kp(t.trim());n||(console.log(Z.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Z.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(Z.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),d=Object.keys(c.agents||{});d.length===0&&(console.log(Z.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Xt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:d.map(x=>({title:x,value:x})),initial:0})).agent),g||(console.log(Z.red(" Aborted")),process.exit(1));let l=c.channels?.telegram?.accounts||{},p=e.account||g;l[p]&&l[p].agentBinding!==g&&(p=(await Xt({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(Z.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Kt(f,t.trim()),process.env[f]=t.trim();let u=await de(b=>{be(b,"channels.telegram.enabled",!0),be(b,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:g});let x=Ro(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;x.includes(A)||(x.push(A),be(b,`agents.${g}.mentions`,x))},{configPath:e.configPath});if(u.success||(console.log(Z.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(Z.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(Z.dim(` Token stored in .env as ${f}`)),console.log(Z.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(Z.dim(" Daemon hot-reloaded.")):console.log(Z.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await Xt({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(Z.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Z.dim(" Waiting up to 90s..."));let y=await vp(t.trim(),9e4);if(!y){console.log(Z.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Z.dim(" agentx config set notifications.destination.channel telegram")),console.log(Z.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Z.dim(` agentx config set notifications.destination.accountId ${p}`));return}let k=await de(b=>{be(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:p})},{configPath:e.configPath});if(!k.success){console.log(Z.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(Z.green(" \u2713 Default --notify target set")),console.log(Z.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Z.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(Z.dim(" Daemon hot-reloaded."))}import fe from"chalk";import di from"prompts";import{existsSync as mi,mkdirSync as xp,readdirSync as Sp,readFileSync as _c}from"fs";import{resolve as gi}from"path";var Ep=".agentx/whatsapp-sessions";function Ap(){let e=gi(process.cwd(),".agentx/daemon.pid");if(!mi(e))return!1;try{let o=parseInt(_c(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Op(e){if(!mi(e))return!1;try{return Sp(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Tp(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(fe.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(fe.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;xp(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},d=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return d.ev.on("creds.update",r),await new Promise(g=>{let p=setTimeout(()=>{o(fe.yellow(" Timed out waiting for scan (2min)."));try{d.end(void 0)}catch{}g(!1)},12e4);d.ev.on("connection.update",async f=>{if(f.qr){o(fe.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:u}=await import("qrcode-terminal");u.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(p),o(fe.green(" \u2713 Paired"));try{d.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),o(fe.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Pc(e={}){if(console.log(),console.log(fe.bold(" Connect WhatsApp")),console.log(),Ap()){console.log(fe.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(fe.dim(" agentx daemon stop")),console.log();let{cont:d}=await di({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});d||(console.log(fe.red(" Aborted")),process.exit(1))}let o=e.configPath||gi(process.cwd(),"agentx.json");mi(o)||(console.log(fe.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(_c(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Ep,s=gi(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(fe.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await di({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(fe.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Op(s)&&a){let{keep:d}=await di({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!d,d&&console.log(fe.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Tp(s,g=>console.log(g))||(console.log(fe.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await de(d=>{be(d,"channels.whatsapp.enabled",!0),be(d,"channels.whatsapp.sessionDir",n),be(d,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(fe.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(fe.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(fe.dim(` Session: ${n}`)),console.log(fe.dim(" Start the daemon to begin receiving:")),console.log(fe.dim(" agentx daemon start")),console.log(fe.dim(" Add routes later with:")),console.log(fe.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Ip}from"crypto";import ke from"chalk";import Lc from"prompts";var Kn="agentx-mesh:",Xn="//join/";function jp(e){return Buffer.from(e,"utf-8").toString("base64url")}function Cp(e){return Buffer.from(e,"base64url").toString("utf-8")}function Np(e){return`${Kn}${Xn}${jp(JSON.stringify(e))}`}function Rp(e){if(!e.startsWith(`${Kn}${Xn}`))throw new Error(`Not a mesh invite link \u2014 expected ${Kn}${Xn}\u2026`);let o=e.slice(Kn.length+Xn.length),t=JSON.parse(Cp(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function Dp(){return Ip(32).toString("hex")}function _p(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Pp(e){return e?.node?.name||e?.node?.id||"node"}async function Mc(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(ke.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=li("MESH_TOKEN");r||(r=Dp(),Kt("MESH_TOKEN",r),console.log(ke.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||_p(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:l}=await Lc({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});l||(console.log(ke.red(" Aborted")),process.exit(1)),a=l}let d=await de(l=>{be(l,"mesh.enabled",!0)},{configPath:e.configPath});d.success||(console.log(ke.red(` \u2717 ${d.error}`)),process.exit(1));let g=Np({url:a,token:r,name:Pp(i),version:1});console.log(),console.log(ke.bold(" Mesh invite")),console.log(),console.log(` ${ke.cyan(g)}`),console.log(),console.log(ke.dim(" Run on the other node:")),console.log(ke.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(ke.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Fc(e,o={}){let t;try{t=Rp(e)}catch(i){console.log(ke.red(` \u2717 ${i.message}`)),process.exit(1)}let n=li("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Lc({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(ke.red(" Aborted (keeping existing .env)")),process.exit(1))}Kt("MESH_TOKEN",t.token);let s=await de(i=>{be(i,"mesh.enabled",!0);let r=Ro(i,"mesh.peers")||[],a=r.findIndex(d=>d.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),be(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(ke.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(ke.green(" \u2713 Joined mesh")),console.log(ke.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(ke.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(ke.dim(" Daemon hot-reloaded.")):console.log(ke.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(ke.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(ke.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(ke.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var ht=new Lp().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");ht.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await Dc({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});ht.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Pc({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Uc=ht.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Uc.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Mc({url:e.url,configPath:e.config})});Uc.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await Fc(e,{configPath:o.config})});ht.action(()=>{console.log(),console.log(ft.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${ft.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${ft.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${ft.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${ft.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(ft.dim(" GitLab connect is the next slice.")),console.log()});pe();import{Command as Mp}from"commander";import le from"chalk";var Qt=new Mp().name("usage").description("token usage analysis and reporting");Qt.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=_(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(le.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(le.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${le.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${le.red(String(s.totalErrors))}`),console.log(),console.log(le.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let d=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${le.cyan(a)}: ${d} tokens (${c.tasks} tasks) ${le.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(le.red(" Daemon not running. Start with: agentx daemon start")):console.log(le.red(` ${e.message}`))}});Qt.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(le.red(` Script not found: ${s}`)),console.log(le.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(le.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(le.red(" Analysis failed. Is Python 3 installed?"))}});Qt.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:o}=await import("./surface-usage-UREILT2E.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-LAACUZWW.js"),r=await i(),a=new Set(n.filter(l=>l.kind==="cli").map(l=>l.name)),c=[],d=(l,p)=>{for(let f of l.commands??[]){let u=p?`${p} ${f.name()}`:f.name();c.push(u),d(f,u)}};d(r,"");let g=c.filter(l=>!a.has(l)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(le.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let l of g)console.log(` ${le.dim("\xB7")} ${l}`);console.log(),console.log(le.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(le.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(le.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(le.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(le.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(le.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=le.dim(`${i.days}d`);console.log(` ${le.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(le.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Fp}from"commander";import he from"chalk";import{resolve as Up}from"path";pe();var Ao=new Fp().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Ao.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{Yi(Up(process.cwd(),".env"))}catch{}let o=qp(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-HLTVSSGW.js");t(o)}catch(o){console.log(he.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(he.dim(o.stack)),process.exit(1)}});function qp(e,o){try{let t=_();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(he.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(he.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
356
- `)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:o||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}Ao.command("list").description("list configured boards").action(()=>{try{let e=_();if(!e.boards?.length){console.log(he.dim(`
382
+ `}function Xt(e,o,t=".env"){let n=zc(t),s=Yc(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${di(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${di(o)}`})),Rp(n,Mp(s))}function gi(e,o=".env"){return Yc(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var Vc="https://t.me/BotFather";async function Lp(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function Fp(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function Kc(e={}){console.log(),console.log(Z.bold(" Connect Telegram")),console.log(),console.log(Z.dim(` 1. Open ${Vc}`)),console.log(Z.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Z.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await Qt({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),S=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(S,[Vc],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Qt({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(Z.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Lp(t.trim());n||(console.log(Z.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Z.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(Z.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(Z.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Qt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(S=>({title:S,value:S})),initial:0})).agent),g||(console.log(Z.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Qt({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(Z.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Xt(f,t.trim()),process.env[f]=t.trim();let p=await ue(b=>{Se(b,"channels.telegram.enabled",!0),Se(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let S=nt(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;S.includes(A)||(S.push(A),Se(b,`agents.${g}.mentions`,S))},{configPath:e.configPath});if(p.success||(console.log(Z.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(Z.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(Z.dim(` Token stored in .env as ${f}`)),console.log(Z.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(Z.dim(" Daemon hot-reloaded.")):console.log(Z.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await Qt({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(Z.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Z.dim(" Waiting up to 90s..."));let y=await Fp(t.trim(),9e4);if(!y){console.log(Z.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Z.dim(" agentx config set notifications.destination.channel telegram")),console.log(Z.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Z.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await ue(b=>{Se(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(Z.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(Z.green(" \u2713 Default --notify target set")),console.log(Z.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Z.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(Z.dim(" Daemon hot-reloaded."))}import he from"chalk";import mi from"prompts";import{existsSync as ui,mkdirSync as Up,readdirSync as qp,readFileSync as Xc}from"fs";import{resolve as pi}from"path";var Wp=".agentx/whatsapp-sessions";function Bp(){let e=pi(process.cwd(),".agentx/daemon.pid");if(!ui(e))return!1;try{let o=parseInt(Xc(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Jp(e){if(!ui(e))return!1;try{return qp(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Gp(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(he.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(he.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;Up(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(he.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(he.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(he.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(he.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Qc(e={}){if(console.log(),console.log(he.bold(" Connect WhatsApp")),console.log(),Bp()){console.log(he.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(he.dim(" agentx daemon stop")),console.log();let{cont:l}=await mi({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(he.red(" Aborted")),process.exit(1))}let o=e.configPath||pi(process.cwd(),"agentx.json");ui(o)||(console.log(he.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Xc(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Wp,s=pi(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(he.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await mi({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(he.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Jp(s)&&a){let{keep:l}=await mi({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(he.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Gp(s,g=>console.log(g))||(console.log(he.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ue(l=>{Se(l,"channels.whatsapp.enabled",!0),Se(l,"channels.whatsapp.sessionDir",n),Se(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(he.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(he.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(he.dim(` Session: ${n}`)),console.log(he.dim(" Start the daemon to begin receiving:")),console.log(he.dim(" agentx daemon start")),console.log(he.dim(" Add routes later with:")),console.log(he.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Hp}from"crypto";import ke from"chalk";import Zc from"prompts";var Kn="agentx-mesh:",Xn="//join/";function zp(e){return Buffer.from(e,"utf-8").toString("base64url")}function Yp(e){return Buffer.from(e,"base64url").toString("utf-8")}function Vp(e){return`${Kn}${Xn}${zp(JSON.stringify(e))}`}function Kp(e){if(!e.startsWith(`${Kn}${Xn}`))throw new Error(`Not a mesh invite link \u2014 expected ${Kn}${Xn}\u2026`);let o=e.slice(Kn.length+Xn.length),t=JSON.parse(Yp(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function Xp(){return Hp(32).toString("hex")}function Qp(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Zp(e){return e?.node?.name||e?.node?.id||"node"}async function el(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(ke.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=gi("MESH_TOKEN");r||(r=Xp(),Xt("MESH_TOKEN",r),console.log(ke.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Qp(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Zc({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(ke.red(" Aborted")),process.exit(1)),a=d}let l=await ue(d=>{Se(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(ke.red(` \u2717 ${l.error}`)),process.exit(1));let g=Vp({url:a,token:r,name:Zp(i),version:1});console.log(),console.log(ke.bold(" Mesh invite")),console.log(),console.log(` ${ke.cyan(g)}`),console.log(),console.log(ke.dim(" Run on the other node:")),console.log(ke.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(ke.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function ol(e,o={}){let t;try{t=Kp(e)}catch(i){console.log(ke.red(` \u2717 ${i.message}`)),process.exit(1)}let n=gi("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Zc({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(ke.red(" Aborted (keeping existing .env)")),process.exit(1))}Xt("MESH_TOKEN",t.token);let s=await ue(i=>{Se(i,"mesh.enabled",!0);let r=nt(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Se(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(ke.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(ke.green(" \u2713 Joined mesh")),console.log(ke.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(ke.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(ke.dim(" Daemon hot-reloaded.")):console.log(ke.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(ke.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(ke.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(ke.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var bt=new eu().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");bt.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await Kc({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});bt.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Qc({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var tl=bt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");tl.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await el({url:e.url,configPath:e.config})});tl.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await ol(e,{configPath:o.config})});bt.action(()=>{console.log(),console.log(wt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${wt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${wt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${wt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${wt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(wt.dim(" GitLab connect is the next slice.")),console.log()});ge();import{Command as ou}from"commander";import de from"chalk";var Zt=new ou().name("usage").description("token usage analysis and reporting");Zt.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=_(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(de.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(de.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${de.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${de.red(String(s.totalErrors))}`),console.log(),console.log(de.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${de.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${de.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(de.red(" Daemon not running. Start with: agentx daemon start")):console.log(de.red(` ${e.message}`))}});Zt.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(de.red(` Script not found: ${s}`)),console.log(de.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(de.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(de.red(" Analysis failed. Is Python 3 installed?"))}});Zt.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:o}=await import("./surface-usage-UREILT2E.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-HGI5C2MP.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(de.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${de.dim("\xB7")} ${d}`);console.log(),console.log(de.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(de.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(de.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(de.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(de.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(de.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=de.dim(`${i.days}d`);console.log(` ${de.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(de.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as tu}from"commander";import ye from"chalk";import{resolve as nu}from"path";ge();var Ao=new tu().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Ao.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{Ki(nu(process.cwd(),".env"))}catch{}let o=su(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-OYGL7Z7X.js");t(o)}catch(o){console.log(ye.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(ye.dim(o.stack)),process.exit(1)}});function su(e,o){try{let t=_();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(ye.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(ye.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
383
+ `)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:o||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}Ao.command("list").description("list configured boards").action(()=>{try{let e=_();if(!e.boards?.length){console.log(ye.dim(`
357
384
  No boards configured.
358
- `));return}console.log();for(let o of e.boards){console.log(` ${he.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(he.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(he.dim(` primary label: ${o.primaryToolLabel}`)),console.log(he.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(he.red(` ${e.message}`)),process.exit(1)}});Ao.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,o)=>{try{Zt(t=>{if(Array.isArray(t.boards)||(t.boards=[]),t.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(o.projects).split(",").map(i=>i.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:o.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(o.days,10)||30,closedWindowDays:parseInt(o.closedDays,10)||30};return o.label&&(s.primaryToolLabel=o.label),t.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(t){console.log(he.red(` ${t.message}`)),process.exit(1)}});Ao.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,o)=>{try{Zt(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(o.name&&(s.name=o.name,i.push(`name="${o.name}"`)),o.projects){let r=String(o.projects).split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:r},i.push(`projects=${r.length}`)}if(o.label!==void 0&&(o.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=o.label,i.push(`label="${o.label}"`))),o.days&&(s.timeRangeDays=parseInt(o.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),o.closedDays&&(s.closedWindowDays=parseInt(o.closedDays,10)||s.closedWindowDays,i.push(`closed-days=${s.closedWindowDays}`)),i.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${i.join(", ")})`})}catch(t){console.log(he.red(` ${t.message}`)),process.exit(1)}});var pi=Ao.command("column").description("manage a board's columns (add / remove / edit / list)");pi.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(_l("fs").readFileSync("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!t)throw new Error(`board "${e}" not found`);let n=t.columns||[];if(n.length===0){console.log(he.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let i=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${he.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${he.dim(i)}`)}}catch(o){console.log(he.red(` ${o.message}`)),process.exit(1)}});pi.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,o,t)=>{try{Zt(n=>{let i=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!i)throw new Error(`board "${e}" not found`);if(i.columns=i.columns||[],i.columns.find(a=>a.id===o))throw new Error(`column "${o}" already exists on board "${e}"`);let r={id:o,title:t.title,kind:t.kind,scopedPrefix:t.scopedPrefix};if(t.kind==="scoped-label"){if(!t.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=t.scoped}if(t.kind==="label"){if(!t.label)throw new Error("--label required for kind=label");r.mapsToLabel=t.label}return t.accent&&(r.accent=t.accent),i.columns.push(r),`column "${o}" added to board "${e}"`})}catch(n){console.log(he.red(` ${n.message}`)),process.exit(1)}});pi.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{Zt(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(r=>r.id!==o),s.columns.length===i)throw new Error(`column "${o}" not found`);return`column "${o}" removed from board "${e}"`})}catch(t){console.log(he.red(` ${t.message}`)),process.exit(1)}});Ao.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Zt(o=>{if(!Array.isArray(o.boards)||o.boards.length===0)throw new Error("no boards configured");let t=o.boards.length;if(o.boards=o.boards.filter(n=>n.id!==e),o.boards.length===t)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(o){console.log(he.red(` ${o.message}`)),process.exit(1)}});function Zt(e){let{summary:o,backupPath:t}=nt(n=>e(n));console.log(he.green(`
385
+ `));return}console.log();for(let o of e.boards){console.log(` ${ye.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(ye.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(ye.dim(` primary label: ${o.primaryToolLabel}`)),console.log(ye.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(ye.red(` ${e.message}`)),process.exit(1)}});Ao.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,o)=>{try{en(t=>{if(Array.isArray(t.boards)||(t.boards=[]),t.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(o.projects).split(",").map(i=>i.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:o.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(o.days,10)||30,closedWindowDays:parseInt(o.closedDays,10)||30};return o.label&&(s.primaryToolLabel=o.label),t.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(t){console.log(ye.red(` ${t.message}`)),process.exit(1)}});Ao.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,o)=>{try{en(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(o.name&&(s.name=o.name,i.push(`name="${o.name}"`)),o.projects){let r=String(o.projects).split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:r},i.push(`projects=${r.length}`)}if(o.label!==void 0&&(o.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=o.label,i.push(`label="${o.label}"`))),o.days&&(s.timeRangeDays=parseInt(o.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),o.closedDays&&(s.closedWindowDays=parseInt(o.closedDays,10)||s.closedWindowDays,i.push(`closed-days=${s.closedWindowDays}`)),i.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${i.join(", ")})`})}catch(t){console.log(ye.red(` ${t.message}`)),process.exit(1)}});var fi=Ao.command("column").description("manage a board's columns (add / remove / edit / list)");fi.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(Xl("fs").readFileSync("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!t)throw new Error(`board "${e}" not found`);let n=t.columns||[];if(n.length===0){console.log(ye.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let i=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${ye.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${ye.dim(i)}`)}}catch(o){console.log(ye.red(` ${o.message}`)),process.exit(1)}});fi.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,o,t)=>{try{en(n=>{let i=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!i)throw new Error(`board "${e}" not found`);if(i.columns=i.columns||[],i.columns.find(a=>a.id===o))throw new Error(`column "${o}" already exists on board "${e}"`);let r={id:o,title:t.title,kind:t.kind,scopedPrefix:t.scopedPrefix};if(t.kind==="scoped-label"){if(!t.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=t.scoped}if(t.kind==="label"){if(!t.label)throw new Error("--label required for kind=label");r.mapsToLabel=t.label}return t.accent&&(r.accent=t.accent),i.columns.push(r),`column "${o}" added to board "${e}"`})}catch(n){console.log(ye.red(` ${n.message}`)),process.exit(1)}});fi.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{en(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(r=>r.id!==o),s.columns.length===i)throw new Error(`column "${o}" not found`);return`column "${o}" removed from board "${e}"`})}catch(t){console.log(ye.red(` ${t.message}`)),process.exit(1)}});Ao.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{en(o=>{if(!Array.isArray(o.boards)||o.boards.length===0)throw new Error("no boards configured");let t=o.boards.length;if(o.boards=o.boards.filter(n=>n.id!==e),o.boards.length===t)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(o){console.log(ye.red(` ${o.message}`)),process.exit(1)}});function en(e){let{summary:o,backupPath:t}=Do(n=>e(n));console.log(ye.green(`
359
386
  \u2713 ${o}
360
- `)),t&&console.log(he.dim(` Backup: ${t}`)),console.log(he.dim(` Restart the dashboard to pick up the change if not auto-reloading.
361
- `))}import{Command as Wp}from"commander";import m from"chalk";import{resolve as q,relative as qc,dirname as Wc}from"path";import{execSync as Jo}from"child_process";import{writeFileSync as Go,mkdirSync as go,readFileSync as en,readdirSync as Bp,renameSync as Qn,rmSync as Jp,existsSync as Je}from"fs";function ve(e,o){return new ys(on(e),void 0,o||"graph")}function on(e){return e||q(process.cwd(),".agentx/wiki")}function fi(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var ee=new Wp().name("wiki").description("wiki knowledge base management");ee.command("status").description("show wiki status per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").action(e=>{let o=e.mode,t=ve(e.dir,o),n=t.summary(),i=t.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${fi(o)}]`)),console.log(),console.log(` Total raw entries: ${i}`),console.log(` Agents: ${n.length}`),console.log();for(let a of n){let c=a.unabsorbed>0?m.yellow(`${a.unabsorbed} unabsorbed`):m.green("up to date");if(console.log(` ${m.cyan(a.agentId)}`),console.log(` Entries: ${a.totalEntries} Articles: ${a.totalArticles} ${c}`),a.articles.length>0){for(let d of a.articles.slice(0,3))console.log(m.dim(` - ${d.title} [${(d.tags||[]).slice(0,3).join(", ")}]`));a.articles.length>3&&console.log(m.dim(` ... and ${a.articles.length-3} more`))}console.log()}let r=n.reduce((a,c)=>a+c.unabsorbed,0);r>0&&(console.log(m.dim(` ${r} raw entries on disk. Absorb is deprecated \u2014 see 'agentx wiki absorb --help'.`)),console.log())});ee.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(e=>{let o=ve(e.dir,e.mode),t=e.agent?[e.agent]:o.listAgents(),n=0;console.log();for(let s of t){let r=o.getAgentWiki(s).lint();if(n+=r.length,r.length===0)console.log(` ${m.cyan(s)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(s)}: ${m.yellow(`${r.length} issues`)}`);for(let a of r){let c=a.type==="broken-link"?"x":a.type==="orphan"?"?":"!";console.log(` [${c}] ${m.dim(a.type)} ${a.article}: ${a.message}`)}}}console.log(),n===0&&console.log(m.green(" All agent wikis are healthy")),console.log()});ee.command("absorb").description("compile unabsorbed entries into typed per-agent wiki articles (Farzapedia-faithful)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","absorb only this agent").option("--dry-run","preview without running").option("--no-facts","skip the system-of-record lookups").option("--max <n>","max entries per agent","10").option("--since <date>","only entries dated on or after YYYY-MM-DD").action(async e=>{let o=e.mode,t=ve(e.dir,o),n=e.agent?[e.agent]:t.listAgents(),s=parseInt(e.max),i=(()=>{try{let p=q(process.cwd(),".agentx/graph");return Je(p)?new uo({baseDir:p}):null}catch{return null}})(),r=new Map;if(i)try{let p=i.loadIndex();for(let[f,u]of Object.entries(p.entries))r.set(f,u.path)}catch{}let a,c=p=>{let f=p.meta?.intentPath;if(Array.isArray(f)&&f.every(y=>typeof y=="string")&&f.length>0)return f;if(!i||r.size===0)return;let u=String(p.meta?.sender??""),w=i.fingerprint({text:p.content,channel:p.source,sender:u});return r.get(w)},d=(p,f)=>{let u=new Map;for(let y of p){let k=f.find(S=>S.id===y);if(!k)continue;let b=c(k);if(!b?.length)continue;let x=b.join("/"),A=u.get(x);A?A.n++:u.set(x,{path:b,n:1})}if(u.size===0)return;let w;for(let y of u.values())(!w||y.n>w.n)&&(w=y);return w?.path},g=0,l=0;for(let p of n){let f=typeof e.since=="string"?e.since.trim():"",u=t.getUnabsorbedEntries(p).filter($=>!f||($.date??"")>=f).slice(0,s);if(u.length===0){console.log(` ${m.cyan(p)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(p)}: ${u.length} entries to absorb`));for(let $ of u.slice(0,3))console.log(m.dim(` [${$.date} via ${$.source}] ${$.content.slice(0,80)}...`));if(u.length>3&&console.log(m.dim(` ... and ${u.length-3} more`)),e.dryRun)continue;let w=t.getAgentWiki(p),y=w.rebuildIndex(),k=w.getWorldview()||t.getSharedStore().getWorldview()||"",b=u.map($=>`--- ENTRY ${$.id} [${$.date} ${$.agentId} via ${$.source}] ---
387
+ `)),t&&console.log(ye.dim(` Backup: ${t}`)),console.log(ye.dim(` Restart the dashboard to pick up the change if not auto-reloading.
388
+ `))}import{Command as iu}from"commander";import m from"chalk";import{resolve as W,relative as nl,dirname as sl}from"path";import{execSync as Ho}from"child_process";import{writeFileSync as zo,mkdirSync as mo,readFileSync as on,readdirSync as ru,renameSync as Qn,rmSync as au,existsSync as Je}from"fs";function ve(e,o){return new hs(tn(e),void 0,o||"graph")}function tn(e){return e||W(process.cwd(),".agentx/wiki")}function yi(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var ee=new iu().name("wiki").description("wiki knowledge base management");ee.command("status").description("show wiki status per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").action(e=>{let o=e.mode,t=ve(e.dir,o),n=t.summary(),i=t.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${yi(o)}]`)),console.log(),console.log(` Total raw entries: ${i}`),console.log(` Agents: ${n.length}`),console.log();for(let a of n){let c=a.unabsorbed>0?m.yellow(`${a.unabsorbed} unabsorbed`):m.green("up to date");if(console.log(` ${m.cyan(a.agentId)}`),console.log(` Entries: ${a.totalEntries} Articles: ${a.totalArticles} ${c}`),a.articles.length>0){for(let l of a.articles.slice(0,3))console.log(m.dim(` - ${l.title} [${(l.tags||[]).slice(0,3).join(", ")}]`));a.articles.length>3&&console.log(m.dim(` ... and ${a.articles.length-3} more`))}console.log()}let r=n.reduce((a,c)=>a+c.unabsorbed,0);r>0&&(console.log(m.dim(` ${r} raw entries on disk. Absorb is deprecated \u2014 see 'agentx wiki absorb --help'.`)),console.log())});ee.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(e=>{let o=ve(e.dir,e.mode),t=e.agent?[e.agent]:o.listAgents(),n=0;console.log();for(let s of t){let r=o.getAgentWiki(s).lint();if(n+=r.length,r.length===0)console.log(` ${m.cyan(s)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(s)}: ${m.yellow(`${r.length} issues`)}`);for(let a of r){let c=a.type==="broken-link"?"x":a.type==="orphan"?"?":"!";console.log(` [${c}] ${m.dim(a.type)} ${a.article}: ${a.message}`)}}}console.log(),n===0&&console.log(m.green(" All agent wikis are healthy")),console.log()});ee.command("absorb").description("compile unabsorbed entries into typed per-agent wiki articles (Farzapedia-faithful)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","absorb only this agent").option("--dry-run","preview without running").option("--no-facts","skip the system-of-record lookups").option("--max <n>","max entries per agent","10").option("--since <date>","only entries dated on or after YYYY-MM-DD").action(async e=>{let o=e.mode,t=ve(e.dir,o),n=e.agent?[e.agent]:t.listAgents(),s=parseInt(e.max),i=(()=>{try{let u=W(process.cwd(),".agentx/graph");return Je(u)?new fo({baseDir:u}):null}catch{return null}})(),r=new Map;if(i)try{let u=i.loadIndex();for(let[f,p]of Object.entries(u.entries))r.set(f,p.path)}catch{}let a,c=u=>{let f=u.meta?.intentPath;if(Array.isArray(f)&&f.every(y=>typeof y=="string")&&f.length>0)return f;if(!i||r.size===0)return;let p=String(u.meta?.sender??""),w=i.fingerprint({text:u.content,channel:u.source,sender:p});return r.get(w)},l=(u,f)=>{let p=new Map;for(let y of u){let k=f.find(x=>x.id===y);if(!k)continue;let b=c(k);if(!b?.length)continue;let S=b.join("/"),A=p.get(S);A?A.n++:p.set(S,{path:b,n:1})}if(p.size===0)return;let w;for(let y of p.values())(!w||y.n>w.n)&&(w=y);return w?.path},g=0,d=0;for(let u of n){let f=typeof e.since=="string"?e.since.trim():"",p=t.getUnabsorbedEntries(u).filter($=>!f||($.date??"")>=f).slice(0,s);if(p.length===0){console.log(` ${m.cyan(u)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(u)}: ${p.length} entries to absorb`));for(let $ of p.slice(0,3))console.log(m.dim(` [${$.date} via ${$.source}] ${$.content.slice(0,80)}...`));if(p.length>3&&console.log(m.dim(` ... and ${p.length-3} more`)),e.dryRun)continue;let w=t.getAgentWiki(u),y=w.rebuildIndex(),k=w.getWorldview()||t.getSharedStore().getWorldview()||"",b=p.map($=>`--- ENTRY ${$.id} [${$.date} ${$.agentId} via ${$.source}] ---
362
389
  ${$.content}
363
390
  --- END ENTRY ---`).join(`
364
391
 
365
- `),x="";if(e.facts!==!1){let{extractHints:$,resolveFacts:C,mergeRecords:j,renderFactsBlock:T,installPrompts:D,defaultSources:W,recordsFromEntries:L}=await import("./facts-YVEJOM7O.js");if(!a){let B=new Set;for(let xe of t.listAgents())for(let ye of t.getAgentWiki(xe).listArticles(xe))ye.meta.type==="person"&&B.add(ye.meta.title);a=[...B]}let G=$(u.map(B=>({context:B.sourceContext,content:B.content,sender:typeof B.meta?.sender=="string"?B.meta.sender:void 0})),{known:a}),ae=L(u);if(G.length>0||ae.length>0){let B=W(),{records:xe,results:ye}=G.length>0?await C(G,{sources:B}):{records:[],results:[]},P=j([...ae,...xe]);x=T(P);let qe=[...ae.length>0?[`entries:${ae.length}`]:[],...ye.filter(we=>we.records.length>0).map(we=>`${we.source}:${we.records.length}`)];console.log(m.dim(` Facts: ${G.length} entities \u2192 ${P.length} resolved${qe.length?` (${qe.join(" ")})`:""}`));for(let we of D(ye,B))console.log(m.yellow(` ! ${we.source} ${we.kind} \u2014 would supply ${we.provides.join(", ")}`)),console.log(m.dim(` ${we.hint}`))}}let A=fr(o,p,k,y.articles,b,u.length,x);console.log(m.dim(` Mode: ${fi(o)}`));let S=q(w.baseDir,"_tmp");go(S,{recursive:!0});let v=q(S,"absorb-prompt.txt");Go(v,A),console.log(m.dim(" Compiling with Claude..."));try{let $;try{$=Jo(`cat '${v}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Ko({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(P){if($=P.stdout||"",!$)throw P}let C=$;try{let P=JSON.parse($);C=P.result||P.content||"",C||(console.log(m.dim(` Claude envelope keys: ${Object.keys(P).join(", ")}`)),console.log(m.dim(` is_error: ${P.is_error}, stop_reason: ${P.stop_reason}`)))}catch{}let j,T=[],D=C.indexOf("{"),W=C.indexOf("["),L=D>=0&&(W<0||D<W)?D:W;if(L===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(C.slice(0,500)));continue}let G=C[L],ae=G==="{"?"}":"]",B=0,xe=-1;for(let P=L;P<C.length;P++)if(C[P]===G)B++;else if(C[P]===ae&&(B--,B===0)){xe=P+1;break}if(xe===-1){console.log(m.red(" Unbalanced JSON"));continue}let ye=C.slice(L,xe);try{let P=JSON.parse(ye);Array.isArray(P)?j=P:(j=P.articles||[],T=P.gaps||[])}catch(P){console.log(m.red(` JSON parse error: ${P.message}`)),console.log(m.dim(` First 300 chars: ${ye.slice(0,300)}`));continue}for(let P of j){let qe=new Date().toISOString().slice(0,10),we=d(P.sources||[],u);w.writeArticle(P.path,{title:P.title,type:P.type,related:Array.isArray(P.related)?P.related:void 0,tags:P.tags||[],owner:p,access:"public",created:qe,lastUpdated:qe,sources:P.sources||[],graphPath:we},P.content,p);let Co=P.type?m.magenta(`[${P.type}]`)+" ":"",N=Array.isArray(P.related)&&P.related.length?` \u2192 ${P.related.slice(0,3).join(", ")}${P.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${Co}${P.path}: ${P.title}${m.dim(N)}`);let me=(P.tags||[]).slice(0,4).join(", ");me&&console.log(m.dim(` tags: ${me}`)),we?.length&&(console.log(m.dim(` graphPath: ${we.join(" \u203A ")}`)),l++),g++}if(T.length>0){console.log(),console.log(m.yellow(` Gaps detected (${T.length} missing pieces):`));for(let P of T)console.log(m.yellow(` ? ${P}`));try{let{QuestionStore:P}=await import("./questions-4B4KSPXG.js"),qe=new P(on(e.dir)).add(T.map(we=>({kind:"article",agentId:p,path:"",subject:String(we).slice(0,120),question:`No article yet for: ${String(we).slice(0,160)}`})));qe.added>0&&console.log(m.dim(` queued ${qe.added} for follow-up (agentx wiki questions)`))}catch{}}w.rebuildIndex()}catch($){console.log(m.red(` Absorb failed: ${$.message?.slice(0,200)}`)),$.stderr&&console.log(m.dim(String($.stderr).slice(0,300))),$.stdout&&console.log(m.dim("stdout: "+String($.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let p=g>0?Math.round(l/g*100):0;console.log(m.dim(` ${l}/${g} carry graphPath (${p}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});ee.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--commit","write articles and ledger (default: dry-run)",!1).action(async e=>{let o=Gp(e.since),t=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=t.find(a=>!n.includes(a));s&&(console.log(m.red(` Invalid memory type "${s}". Valid: ${n.join(", ")}`)),process.exit(1)),e.commit&&!e.via&&!e.model&&(console.log(m.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1)),console.log(),console.log(m.bold(" Memory \u2192 Wiki Promotion")),console.log();let i=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-LEOPEOEG.js"),{default:c}=await import("better-sqlite3"),d=q(process.cwd(),".agentx/db.sqlite");if(!Je(d))console.log(m.yellow(` --reviews: no ${d}`));else{let g=new c(d,{readonly:!0});try{let l=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(o??6048e5));i=a(l,{kinds:String(e.reviewKinds).split(",").map(u=>u.trim()).filter(Boolean)});let p=i.filter(u=>(u.occurrences??1)>1).length;console.log(m.dim(` ${l.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${p} seen in more than one session`));let f=i[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.memory.description.slice(0,84)}`))}finally{g.close()}}}let r=await hr({extraCandidates:i,wikiDir:e.dir?q(e.dir):void 0,memoryRoot:e.memoryDir?q(e.memoryDir):void 0,sinceMs:o,agentFilter:e.agent,types:t,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,log:a=>console.log(m.dim(` ${a}`))});if(r.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.clusters){let c=a.candidates[0],d=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${d} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${c.memory.description}`))}if(console.log(),r.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to promote")),console.log();return}for(let a of r.written){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",d=a.related?.length?` \u2192 ${a.related.slice(0,3).join(", ")}${a.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${c}${a.path}: ${a.title}${m.dim(d)}`),console.log(m.dim(` from: ${a.stamps.join(", ")}`))}for(let a of r.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(m.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(m.dim(` ! ${a}`));for(let a of r.errors)console.log(m.red(` x ${a}`));console.log(),console.log(r.errors.length?m.red(` ${r.written.length} promoted, ${r.errors.length} error(s)`):m.green(` ${r.written.length} promoted, ${r.skipped.length} skipped`)),console.log(),r.errors.length&&process.exit(1)});function Gp(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());o||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}ee.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",q(process.cwd(),".agentx/task-history")).option("--n <n>","number of messages to sample (newest first)","10").option("--out <path>","markdown output file (default: stdout)").option("--selector-model <m>","agentic selector model","haiku").option("--synth-model <m>","agentic synthesis model","sonnet").action(async e=>{let{agenticQuery:o}=await import("./query-ZSUBNWOL.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=ve(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let d=a.getAgentWiki(c),g=parseInt(e.n),l=i(e.history,c);if(!s(l)){console.log(m.yellow(` no task-history at ${l}`));return}let p=[],f=t(l).sort().reverse();for(let y of f){let k=r(l,y),b=[];try{b=t(k).filter(x=>x.endsWith(".json")).sort().reverse()}catch{continue}for(let x of b){if(p.length>=g)break;try{let A=JSON.parse(n(r(k,x),"utf-8")),S=A.message||A.task?.message;typeof S=="string"&&S.trim().length>10&&p.push({id:A.id||x.replace(".json",""),message:S.trim(),ts:A.at||A.timestamp||y})}catch{}}if(p.length>=g)break}if(p.length===0){console.log(m.yellow(` no task messages found under ${l}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${p.length} messages from ${c}`)),console.log(m.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(m.dim(` NEW: agenticQuery() catalog+wikilink walk (selector=${e.selectorModel}, synth=${e.synthModel})`)),console.log();let u=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${p.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let y=0;y<p.length;y++){let k=p[y];process.stdout.write(m.dim(` [${y+1}/${p.length}] querying... `));let x=d.findRelevant(k.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
366
- `)||"_(none returned)_",A;try{let S=await o(k.message,d,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(S.status!=="ok")A=`_(status: ${S.status}${S.error?" \u2014 "+S.error:""})_`;else{let v=S.citations.map($=>`\`${$.title}\` [${$.type||"?"}]`).join(", ");A=`**Answer:**
392
+ `),S="";if(e.facts!==!1){let{extractHints:$,resolveFacts:C,mergeRecords:j,renderFactsBlock:T,installPrompts:D,defaultSources:B,recordsFromEntries:M}=await import("./facts-YVEJOM7O.js");if(!a){let J=new Set;for(let xe of t.listAgents())for(let we of t.getAgentWiki(xe).listArticles(xe))we.meta.type==="person"&&J.add(we.meta.title);a=[...J]}let H=$(p.map(J=>({context:J.sourceContext,content:J.content,sender:typeof J.meta?.sender=="string"?J.meta.sender:void 0})),{known:a}),ce=M(p);if(H.length>0||ce.length>0){let J=B(),{records:xe,results:we}=H.length>0?await C(H,{sources:J}):{records:[],results:[]},P=j([...ce,...xe]);S=T(P);let Be=[...ce.length>0?[`entries:${ce.length}`]:[],...we.filter(be=>be.records.length>0).map(be=>`${be.source}:${be.records.length}`)];console.log(m.dim(` Facts: ${H.length} entities \u2192 ${P.length} resolved${Be.length?` (${Be.join(" ")})`:""}`));for(let be of D(we,J))console.log(m.yellow(` ! ${be.source} ${be.kind} \u2014 would supply ${be.provides.join(", ")}`)),console.log(m.dim(` ${be.hint}`))}}let A=Ar(o,u,k,y.articles,b,p.length,S);console.log(m.dim(` Mode: ${yi(o)}`));let x=W(w.baseDir,"_tmp");mo(x,{recursive:!0});let v=W(x,"absorb-prompt.txt");zo(v,A),console.log(m.dim(" Compiling with Claude..."));try{let $;try{$=Ho(`cat '${v}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Qo({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(P){if($=P.stdout||"",!$)throw P}let C=$;try{let P=JSON.parse($);C=P.result||P.content||"",C||(console.log(m.dim(` Claude envelope keys: ${Object.keys(P).join(", ")}`)),console.log(m.dim(` is_error: ${P.is_error}, stop_reason: ${P.stop_reason}`)))}catch{}let j,T=[],D=C.indexOf("{"),B=C.indexOf("["),M=D>=0&&(B<0||D<B)?D:B;if(M===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(C.slice(0,500)));continue}let H=C[M],ce=H==="{"?"}":"]",J=0,xe=-1;for(let P=M;P<C.length;P++)if(C[P]===H)J++;else if(C[P]===ce&&(J--,J===0)){xe=P+1;break}if(xe===-1){console.log(m.red(" Unbalanced JSON"));continue}let we=C.slice(M,xe);try{let P=JSON.parse(we);Array.isArray(P)?j=P:(j=P.articles||[],T=P.gaps||[])}catch(P){console.log(m.red(` JSON parse error: ${P.message}`)),console.log(m.dim(` First 300 chars: ${we.slice(0,300)}`));continue}for(let P of j){let Be=new Date().toISOString().slice(0,10),be=l(P.sources||[],p);w.writeArticle(P.path,{title:P.title,type:P.type,related:Array.isArray(P.related)?P.related:void 0,tags:P.tags||[],owner:u,access:"public",created:Be,lastUpdated:Be,sources:P.sources||[],graphPath:be},P.content,u);let No=P.type?m.magenta(`[${P.type}]`)+" ":"",N=Array.isArray(P.related)&&P.related.length?` \u2192 ${P.related.slice(0,3).join(", ")}${P.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${No}${P.path}: ${P.title}${m.dim(N)}`);let pe=(P.tags||[]).slice(0,4).join(", ");pe&&console.log(m.dim(` tags: ${pe}`)),be?.length&&(console.log(m.dim(` graphPath: ${be.join(" \u203A ")}`)),d++),g++}if(T.length>0){console.log(),console.log(m.yellow(` Gaps detected (${T.length} missing pieces):`));for(let P of T)console.log(m.yellow(` ? ${P}`));try{let{QuestionStore:P}=await import("./questions-4B4KSPXG.js"),Be=new P(tn(e.dir)).add(T.map(be=>({kind:"article",agentId:u,path:"",subject:String(be).slice(0,120),question:`No article yet for: ${String(be).slice(0,160)}`})));Be.added>0&&console.log(m.dim(` queued ${Be.added} for follow-up (agentx wiki questions)`))}catch{}}w.rebuildIndex()}catch($){console.log(m.red(` Absorb failed: ${$.message?.slice(0,200)}`)),$.stderr&&console.log(m.dim(String($.stderr).slice(0,300))),$.stdout&&console.log(m.dim("stdout: "+String($.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let u=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${u}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});ee.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--commit","write articles and ledger (default: dry-run)",!1).action(async e=>{let o=cu(e.since),t=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=t.find(a=>!n.includes(a));s&&(console.log(m.red(` Invalid memory type "${s}". Valid: ${n.join(", ")}`)),process.exit(1)),e.commit&&!e.via&&!e.model&&(console.log(m.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1)),console.log(),console.log(m.bold(" Memory \u2192 Wiki Promotion")),console.log();let i=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-BFAWNDOR.js"),{default:c}=await import("better-sqlite3"),l=W(process.cwd(),".agentx/db.sqlite");if(!Je(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(o??6048e5));i=a(d,{kinds:String(e.reviewKinds).split(",").map(p=>p.trim()).filter(Boolean)});let u=i.filter(p=>(p.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${u} seen in more than one session`));let f=i[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.memory.description.slice(0,84)}`))}finally{g.close()}}}let r=await Or({extraCandidates:i,wikiDir:e.dir?W(e.dir):void 0,memoryRoot:e.memoryDir?W(e.memoryDir):void 0,sinceMs:o,agentFilter:e.agent,types:t,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,log:a=>console.log(m.dim(` ${a}`))});if(r.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.clusters){let c=a.candidates[0],l=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${l} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${c.memory.description}`))}if(console.log(),r.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to promote")),console.log();return}for(let a of r.written){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=a.related?.length?` \u2192 ${a.related.slice(0,3).join(", ")}${a.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${c}${a.path}: ${a.title}${m.dim(l)}`),console.log(m.dim(` from: ${a.stamps.join(", ")}`))}for(let a of r.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(m.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(m.dim(` ! ${a}`));for(let a of r.errors)console.log(m.red(` x ${a}`));console.log(),console.log(r.errors.length?m.red(` ${r.written.length} promoted, ${r.errors.length} error(s)`):m.green(` ${r.written.length} promoted, ${r.skipped.length} skipped`)),console.log(),r.errors.length&&process.exit(1)});function cu(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());o||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}ee.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",W(process.cwd(),".agentx/task-history")).option("--n <n>","number of messages to sample (newest first)","10").option("--out <path>","markdown output file (default: stdout)").option("--selector-model <m>","agentic selector model","haiku").option("--synth-model <m>","agentic synthesis model","sonnet").action(async e=>{let{agenticQuery:o}=await import("./query-6EMTLCHQ.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=ve(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),g=parseInt(e.n),d=i(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let u=[],f=t(d).sort().reverse();for(let y of f){let k=r(d,y),b=[];try{b=t(k).filter(S=>S.endsWith(".json")).sort().reverse()}catch{continue}for(let S of b){if(u.length>=g)break;try{let A=JSON.parse(n(r(k,S),"utf-8")),x=A.message||A.task?.message;typeof x=="string"&&x.trim().length>10&&u.push({id:A.id||S.replace(".json",""),message:x.trim(),ts:A.at||A.timestamp||y})}catch{}}if(u.length>=g)break}if(u.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${u.length} messages from ${c}`)),console.log(m.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(m.dim(` NEW: agenticQuery() catalog+wikilink walk (selector=${e.selectorModel}, synth=${e.synthModel})`)),console.log();let p=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${u.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let y=0;y<u.length;y++){let k=u[y];process.stdout.write(m.dim(` [${y+1}/${u.length}] querying... `));let S=l.findRelevant(k.message,c,3).map(x=>`- **${x.meta.title}** [${x.meta.type||"?"}] (${x.path})`).join(`
393
+ `)||"_(none returned)_",A;try{let x=await o(k.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(x.status!=="ok")A=`_(status: ${x.status}${x.error?" \u2014 "+x.error:""})_`;else{let v=x.citations.map($=>`\`${$.title}\` [${$.type||"?"}]`).join(", ");A=`**Answer:**
367
394
 
368
- ${S.answer}
395
+ ${x.answer}
369
396
 
370
- **Citations:** ${v}`}}catch(S){A=`_(error: ${S.message})_`}console.log(m.dim("done")),u.push(`## ${y+1}. ${k.id}`,"",`> ${k.message.replace(/\n/g," ").slice(0,400)}${k.message.length>400?"\u2026":""}`,"","### OLD \u2014 BM25 preload (top 3)","",x,"","### NEW \u2014 agentic query","",A,"","| Path | Rating 0\u20132 | Notes |","|---|---|---|","| OLD | | |","| NEW | | |","")}let w=u.join(`
371
- `);e.out?((await import("fs")).writeFileSync(e.out,w),console.log(),console.log(m.green(` Wrote ${w.length} bytes to ${e.out}`))):(console.log(),console.log(w))});ee.command("interview").description("interactive interview session \u2014 Q&A with an LLM synthesizer, produces one typed wiki article").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to write to (required)").option("--topic <text>","what to interview about (e.g. 'Globex deployment procedure')").option("--type <t>","article type hint (person|project|place|concept|event|decision|pattern)").option("--model <m>","synthesis model","sonnet").option("--no-commit","show the draft but don't write").option("--answers <path>","non-interactive: one answer per line (same order as questions); last line = save|edit|scrap").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{WIKI_ARTICLE_TYPES:n}=await import("./types-OIFU3KSQ.js"),s=e.answers?en(e.answers,"utf-8").split(/\r?\n/).filter(N=>N.length>0):null,i=0;if(!e.agent){console.log(m.red(" --agent <id> is required. The article will be owned by this agent."));return}let r=ve(e.dir),a;try{a=r.getAgentWiki(e.agent)}catch(N){console.log(m.red(` can't open wiki for agent "${e.agent}": ${N.message}`));return}let c=s?null:o.createInterface({input:process.stdin,output:process.stdout}),d=async N=>{if(s){let me=s[i++]??"";return process.stdout.write(N+m.dim(`[scripted] ${me.slice(0,80)}${me.length>80?"\u2026":""}`)+`
372
- `),me.trim()}return(await c.question(N)).trim()};console.log(),console.log(m.bold(" Wiki Interview")),console.log(m.dim(" One article per session. Empty answer = skip field. /done = stop & synthesize. /abort = quit.")),console.log();let g=e.topic||"";if(!g&&(g=await d(m.cyan(" Topic? ")+m.dim("(a person, a procedure, a past event, \u2026) ")),!g||g==="/abort")){c?.close();return}let l=(e.type||"").toLowerCase(),p=new Set(n);if(!p.has(l)){console.log(m.dim(` Types: ${n.join(" | ")}`));let N=await d(m.cyan(" Type? "));if(N==="/abort"){c?.close();return}p.has(N)?l=N:(console.log(m.yellow(` "${N}" isn't a valid type. Falling back to "concept".`)),l="concept")}let f={person:["Full name (and any aliases / Telegram handle / GitLab username)?","Role or title?","Which org or team are they part of (use the article title if you have one)?","Key responsibilities in OUR work?","Preferred channel to reach them (Telegram, email, in-person, \u2026)?","Who do they report to? (skip if none)","Notable decisions, events, or patterns they're involved in?","Anything quirky we should remember (timezone, working hours, style)?"],project:["One-line description \u2014 what is this project?","Who owns it? (person article title)","Tech stack or key tools involved?","Current status (active / paused / archived)?","Repo / URL / path on disk?","Two or three key decisions made so far?","Any open blockers, risks, or known issues?","Related projects or patterns?"],place:["Kind \u2014 office / server / environment / domain / URL?","Address \u2014 URL, IP, hostname, or physical location?","Owner (person or team)?","How to access it (SSH host, login, VPN, \u2026)?","What lives there (services, people, data)?","Known quirks (timezone, uptime, access restrictions)?"],concept:["Define it in one sentence \u2014 what does this term mean in OUR work?","Where did we first adopt it (origin story, date)?","Two or three concrete examples from our team?","What does it replace or extend (older concept, related concept)?","Common misunderstandings to avoid?"],event:["Date (YYYY-MM-DD)?","One-line summary \u2014 what happened?","Who was involved?","Timeline \u2014 key moments (start \u2192 resolution)?","Impact \u2014 what broke, what got delivered, who was affected?","Resolution / outcome?","Follow-ups or lessons captured?"],decision:["Context \u2014 what was the situation forcing a choice?","Options that were considered?","Chosen option \u2014 and one-sentence why?","Alternatives rejected \u2014 and one-sentence why not?","Who decided, and when (date)?","Is this reversible, and what would trigger a revisit?"],pattern:["Trigger \u2014 when should someone follow this pattern?","Inputs required (what do you need before starting)?","Steps in order \u2014 keep it tight, one line per step?","Expected output \u2014 how do you know it worked?","Common failure modes?","Related patterns, decisions, or runbooks?"]},u=f[l]||f.concept;console.log(),console.log(m.bold(` Topic: ${m.cyan(g)} \xB7 Type: ${m.magenta(l)}`)),console.log(m.dim(` ${u.length} questions. Skip with empty answer. /done to stop early.`)),console.log();let w=[],y=!1;for(let N=0;N<u.length;N++){let me=u[N],Ge=await d(` ${m.dim(`[${N+1}/${u.length}]`)} ${me}
373
- ${m.green(">")} `);if(Ge==="/abort"){y=!0;break}if(Ge==="/done")break;Ge!=="/skip"&&Ge&&w.push({q:me,a:Ge})}if(!y){let N=await d(`
397
+ **Citations:** ${v}`}}catch(x){A=`_(error: ${x.message})_`}console.log(m.dim("done")),p.push(`## ${y+1}. ${k.id}`,"",`> ${k.message.replace(/\n/g," ").slice(0,400)}${k.message.length>400?"\u2026":""}`,"","### OLD \u2014 BM25 preload (top 3)","",S,"","### NEW \u2014 agentic query","",A,"","| Path | Rating 0\u20132 | Notes |","|---|---|---|","| OLD | | |","| NEW | | |","")}let w=p.join(`
398
+ `);e.out?((await import("fs")).writeFileSync(e.out,w),console.log(),console.log(m.green(` Wrote ${w.length} bytes to ${e.out}`))):(console.log(),console.log(w))});ee.command("interview").description("interactive interview session \u2014 Q&A with an LLM synthesizer, produces one typed wiki article").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to write to (required)").option("--topic <text>","what to interview about (e.g. 'Globex deployment procedure')").option("--type <t>","article type hint (person|project|place|concept|event|decision|pattern)").option("--model <m>","synthesis model","sonnet").option("--no-commit","show the draft but don't write").option("--answers <path>","non-interactive: one answer per line (same order as questions); last line = save|edit|scrap").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{WIKI_ARTICLE_TYPES:n}=await import("./types-OIFU3KSQ.js"),s=e.answers?on(e.answers,"utf-8").split(/\r?\n/).filter(N=>N.length>0):null,i=0;if(!e.agent){console.log(m.red(" --agent <id> is required. The article will be owned by this agent."));return}let r=ve(e.dir),a;try{a=r.getAgentWiki(e.agent)}catch(N){console.log(m.red(` can't open wiki for agent "${e.agent}": ${N.message}`));return}let c=s?null:o.createInterface({input:process.stdin,output:process.stdout}),l=async N=>{if(s){let pe=s[i++]??"";return process.stdout.write(N+m.dim(`[scripted] ${pe.slice(0,80)}${pe.length>80?"\u2026":""}`)+`
399
+ `),pe.trim()}return(await c.question(N)).trim()};console.log(),console.log(m.bold(" Wiki Interview")),console.log(m.dim(" One article per session. Empty answer = skip field. /done = stop & synthesize. /abort = quit.")),console.log();let g=e.topic||"";if(!g&&(g=await l(m.cyan(" Topic? ")+m.dim("(a person, a procedure, a past event, \u2026) ")),!g||g==="/abort")){c?.close();return}let d=(e.type||"").toLowerCase(),u=new Set(n);if(!u.has(d)){console.log(m.dim(` Types: ${n.join(" | ")}`));let N=await l(m.cyan(" Type? "));if(N==="/abort"){c?.close();return}u.has(N)?d=N:(console.log(m.yellow(` "${N}" isn't a valid type. Falling back to "concept".`)),d="concept")}let f={person:["Full name (and any aliases / Telegram handle / GitLab username)?","Role or title?","Which org or team are they part of (use the article title if you have one)?","Key responsibilities in OUR work?","Preferred channel to reach them (Telegram, email, in-person, \u2026)?","Who do they report to? (skip if none)","Notable decisions, events, or patterns they're involved in?","Anything quirky we should remember (timezone, working hours, style)?"],project:["One-line description \u2014 what is this project?","Who owns it? (person article title)","Tech stack or key tools involved?","Current status (active / paused / archived)?","Repo / URL / path on disk?","Two or three key decisions made so far?","Any open blockers, risks, or known issues?","Related projects or patterns?"],place:["Kind \u2014 office / server / environment / domain / URL?","Address \u2014 URL, IP, hostname, or physical location?","Owner (person or team)?","How to access it (SSH host, login, VPN, \u2026)?","What lives there (services, people, data)?","Known quirks (timezone, uptime, access restrictions)?"],concept:["Define it in one sentence \u2014 what does this term mean in OUR work?","Where did we first adopt it (origin story, date)?","Two or three concrete examples from our team?","What does it replace or extend (older concept, related concept)?","Common misunderstandings to avoid?"],event:["Date (YYYY-MM-DD)?","One-line summary \u2014 what happened?","Who was involved?","Timeline \u2014 key moments (start \u2192 resolution)?","Impact \u2014 what broke, what got delivered, who was affected?","Resolution / outcome?","Follow-ups or lessons captured?"],decision:["Context \u2014 what was the situation forcing a choice?","Options that were considered?","Chosen option \u2014 and one-sentence why?","Alternatives rejected \u2014 and one-sentence why not?","Who decided, and when (date)?","Is this reversible, and what would trigger a revisit?"],pattern:["Trigger \u2014 when should someone follow this pattern?","Inputs required (what do you need before starting)?","Steps in order \u2014 keep it tight, one line per step?","Expected output \u2014 how do you know it worked?","Common failure modes?","Related patterns, decisions, or runbooks?"]},p=f[d]||f.concept;console.log(),console.log(m.bold(` Topic: ${m.cyan(g)} \xB7 Type: ${m.magenta(d)}`)),console.log(m.dim(` ${p.length} questions. Skip with empty answer. /done to stop early.`)),console.log();let w=[],y=!1;for(let N=0;N<p.length;N++){let pe=p[N],Ge=await l(` ${m.dim(`[${N+1}/${p.length}]`)} ${pe}
400
+ ${m.green(">")} `);if(Ge==="/abort"){y=!0;break}if(Ge==="/done")break;Ge!=="/skip"&&Ge&&w.push({q:pe,a:Ge})}if(!y){let N=await l(`
374
401
  ${m.dim("Anything else worth capturing?")}
375
402
  ${m.green(">")} `);N&&N!=="/abort"&&N!=="/done"&&w.push({q:"Anything else worth capturing?",a:N})}if(y||w.length===0){console.log(m.yellow(`
376
403
  Nothing captured. Exiting.`)),c?.close();return}let b=a.listArticles(e.agent).slice(0,40).map(N=>`- ${N.meta.title} [${N.meta.type||"?"}]`).join(`
377
- `),x=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${g}`,`**Type:** ${l}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...w.map(N=>`
404
+ `),S=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${g}`,`**Type:** ${d}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...w.map(N=>`
378
405
  Q: ${N.q}
379
- A: ${N.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",b||"(none yet)","","## Output rules","- Output EXACTLY one markdown file: frontmatter (---) + body. No code fences, no preamble.","- Frontmatter fields in this exact order: title, type, related, tags, owner, access, created, last_updated, sources.",' - `title`: "\u2026"',` - \`type\`: ${l}`,' - `related`: ["Article Title", \u2026] (titles that exist in the catalog above; drop if none)'," - `tags`: 2-4 specific tags, lowercase-kebab \u2014 no dates unless type=event",` - \`owner\`: ${e.agent}`," - `access`: public (unless the content is sensitive)",` - \`created\`: ${new Date().toISOString().slice(0,10)}`,` - \`last_updated\`: ${new Date().toISOString().slice(0,10)}`,` - \`sources\`: ["interview-${new Date().toISOString().slice(0,10)}"]`,"- Body: 20-80 lines, Wikipedia-style, organized by theme (not by question), synthesized (not verbatim Q&A).","- Use [[Title]] inline every time you reference something that has an article in the catalog.","- Do NOT invent facts. If the transcript didn't cover something, skip that sub-topic."].join(`
380
- `),A=q(a.baseDir,"_tmp");go(A,{recursive:!0});let S=q(A,`interview-${t().slice(0,8)}.txt`);Go(S,x),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let v="";try{let N=`cat '${S}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,me=Jo(N,{env:Ko({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Ge=JSON.parse(me);v=String(Ge.result||Ge.content||"")}catch{v=me}}catch(N){console.log(m.red(` synthesis failed: ${N.message?.slice(0,200)}`)),c?.close();return}v=v.trim();let $=v.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);$&&(v=$[1].trim());let C=v.indexOf("---");C>0&&(v=v.slice(C));let j=v.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!j){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(v.slice(0,600)),c?.close();return}let T={};for(let N of j[1].split(`
381
- `)){let me=N.match(/^(\w+):\s*(.+)$/);me&&(T[me[1]]=me[2].trim().replace(/^"(.*)"$/,"$1"))}let D=j[2],W=T.title||g,L=W.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),ae=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[l]||l+"s"}/${L}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${ae}`)),console.log(),console.log(v),console.log();let B=await d(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),B==="scrap"||B==="/abort"){console.log(m.dim(" Discarded."));return}if(!e.commit){console.log(m.dim(" --no-commit: not writing.")),console.log(m.dim(` Draft kept at ${S} (prompt only; no article file)`));return}let xe=D,ye={title:W,type:T.type||l,related:T.related?T.related.replace(/^\[|\]$/g,"").split(",").map(N=>N.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:T.tags?T.tags.replace(/^\[|\]$/g,"").split(",").map(N=>N.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:T.access||"public",created:T.created||new Date().toISOString().slice(0,10),lastUpdated:T.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(B==="edit"){let N=process.env.EDITOR||"vi",me=q(A,`draft-${t().slice(0,8)}.md`);Go(me,v);try{Jo(`${N} '${me}'`,{stdio:"inherit"});let us=en(me,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(us){let po={};for(let Ot of us[1].split(`
382
- `)){let fs=Ot.match(/^(\w+):\s*(.+)$/);fs&&(po[fs[1]]=fs[2].trim().replace(/^"(.*)"$/,"$1"))}xe=us[2],ye={...ye,title:po.title||ye.title,type:po.type||ye.type,access:po.access||ye.access,related:po.related?po.related.replace(/^\[|\]$/g,"").split(",").map(Ot=>Ot.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ye.related,tags:po.tags?po.tags.replace(/^\[|\]$/g,"").split(",").map(Ot=>Ot.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ye.tags}}}catch(Ge){console.log(m.red(` editor failed: ${Ge.message}`));return}}if(!a.writeArticle(ae,ye,xe,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${ae} saved.`));let qe=a.extractWikilinks(xe),we=new Map;for(let N of a.listArticles(e.agent))we.set(N.meta.title.toLowerCase(),!0);let Co=qe.filter(N=>!we.has(N.toLowerCase()));if(Co.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let N of Co.slice(0,8))console.log(m.dim(` - ${N}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});ee.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{agenticQuery:n}=await import("./query-ZSUBNWOL.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=ve(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(f){console.log(m.red(` can't open wiki for agent "${e.agent}": ${f.message}`));return}let r=null;if(e.script){let u=en(e.script,"utf-8").split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);r=[];for(let w of u){let y=w.split(/\r?\n/).filter(x=>x.trim());if(y.length<2)continue;let k=y[0].replace(/^Q:\s*/i,"").trim(),b=y.slice(1).join(" ").trim();k&&b&&r.push({q:k,verdict:b})}}let a=r?null:o.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",d=Math.min(parseInt(e.rounds)||20,r?.length??999),g=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${d} \xB7 ${g?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let l=[],p=0;for(let f=0;f<d;f++){let u,w;if(r){let G=r[f];if(!G)break;u=G.q,w=G.verdict,console.log(m.cyan(` [${f+1}] Q: `)+u)}else{if(u=await c(m.cyan(` [${f+1}] Q: `)),!u||u==="/done"||u==="/abort")break;w=""}process.stdout.write(m.dim(" querying... "));let y;try{y=await n(u,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(G){console.log(m.red(`failed: ${G.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),y.status!=="ok")console.log(m.yellow(` (status: ${y.status}${y.error?" \u2014 "+y.error:""})`));else{let G=y.citations.map(ae=>`${ae.title} [${ae.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
383
- `)),console.log(m.dim(" citations: "+G))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let k={q:u,answer:y.answer,citations:y.citations,verdict:w},b=w.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!b){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),l.push(k);continue}let x=b[1].toLowerCase(),A=(b[2]||"").trim();if(l.push(k),x==="/ok"||x==="/skip")continue;if(!A){console.log(m.yellow(` ${x} without note \u2014 skipping.`));continue}let S=y.citations[0];if(!S){console.log(m.yellow(" no cited article to patch."));continue}let v=i.readArticle(S.path);if(!v){console.log(m.red(` can't read ${S.path} to patch.`));continue}console.log(m.dim(` patching ${S.title} (${S.path})...`));let $=zp(v.content,x,A,v.meta.title,v.meta.type),C=q(i.baseDir,"_tmp");go(C,{recursive:!0});let j=q(C,`quiz-patch-${t().slice(0,8)}.txt`);Go(j,$);let T="";try{let G=`cat '${j}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,ae=Jo(G,{env:Ko({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let xe=JSON.parse(ae);T=String(xe.result||xe.content||"")}catch{T=ae}let B=T.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);B&&(T=B[1].trim()),T=T.trim()}catch(G){console.log(m.red(` patch failed: ${G.message?.slice(0,120)}`));continue}if(!T||T.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let D=v.content.split(`
384
- `).length,W=T.split(`
385
- `).length;if(console.log(m.dim(` diff: ${D} \u2192 ${W} lines (${W-D>=0?"+":""}${W-D})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),k.patched=S.path+" (dry)";continue}if(!i.writeArticle(S.path,{...v.meta,lastUpdated:new Date().toISOString().slice(0,10)},T,e.agent)){console.log(m.red(" write failed (permission?)"));continue}p++,k.patched=S.path,console.log(m.green(` \u2713 patched ${S.path}`))}if(a&&a.close(),p>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${l.length} rounds, ${p} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${l.length} rounds \xB7 ${p} patches_`,""];for(let u=0;u<l.length;u++){let w=l[u];f.push(`## ${u+1}. Q: ${w.q}`,"",`**A:** ${w.answer}`,"",`**Citations:** ${w.citations.map(y=>`\`${y.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${w.verdict}\``+(w.patched?` \u2192 patched \`${w.patched}\``:""),"")}Go(e.out,f.join(`
386
- `)),console.log(m.dim(` Transcript written to ${e.out}`))}});ee.command("edit <agent> <titleOrPath>").description("open an article in $EDITOR (resolves by title or path), rebuild catalog on exit").option("--dir <path>","wiki directory").option("--editor <cmd>","override $EDITOR for this run").action((e,o,t)=>{let n=ve(t.dir),s;try{s=n.getAgentWiki(e)}catch(d){console.log(m.red(` can't open wiki for agent "${e}": ${d.message}`));return}let i=Gc(s,o,e);if(!i){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`)),console.log(m.dim(` Tip: ${m.green("agentx wiki status")} lists agents; ${m.green(`agentx wiki search "term" --agent ${e}`)} finds by content.`));return}let r=q(s.baseDir,i),a=t.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${i} in ${a}...`));try{Jo(`${a} '${r}'`,{stdio:"inherit"})}catch(d){console.log(m.red(` editor exited with error: ${d.message?.slice(0,150)}`));return}let c=s.readArticle(i);if(c){let d=new Set,g=s.extractWikilinks(c.content).filter(f=>d.has(f)?!1:(d.add(f),!0)),l=c.meta.related||[];(g.some(f=>!l.includes(f))||l.some(f=>!g.includes(f)))&&(s.writeArticle(i,{...c.meta,related:g.length?g:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.content,e),console.log(m.dim(` (synced frontmatter.related from body: ${g.length} wikilink${g.length===1?"":"s"})`)))}try{s.rebuildIndex(),console.log(m.green(` \u2713 ${i} saved. Catalog rebuilt.`))}catch(d){console.log(m.yellow(` saved, but catalog rebuild failed: ${d.message?.slice(0,100)}`))}});ee.command("patch <agent> <titleOrPath> <instruction>").description("LLM-patch an article from a free-form instruction; shows diff + confirms before writing").option("--dir <path>","wiki directory").option("--patch-model <m>","patch model","sonnet").option("--yes","skip confirmation and write immediately").option("--no-commit","show the patched body but don't write").action(async(e,o,t,n)=>{let s=await import("node:readline/promises"),{randomUUID:i}=await import("node:crypto"),r=ve(n.dir),a;try{a=r.getAgentWiki(e)}catch(S){console.log(m.red(` can't open wiki for agent "${e}": ${S.message}`));return}let c=Gc(a,o,e);if(!c){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`));return}let d=a.readArticle(c);if(!d){console.log(m.red(` can't read ${c}.`));return}let g=Hp(d.content,d.meta.title,d.meta.type,t),l=q(a.baseDir,"_tmp");go(l,{recursive:!0});let p=q(l,`patch-${i().slice(0,8)}.txt`);Go(p,g),console.log(),console.log(m.dim(` Target: ${d.meta.title} (${c})`)),console.log(m.dim(` Patching with ${n.patchModel}...`));let f="";try{let S=`cat '${p}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,v=Jo(S,{env:Ko({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let C=JSON.parse(v);f=String(C.result||C.content||"")}catch{f=v}let $=f.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);$&&(f=$[1].trim()),f=f.trim()}catch(S){console.log(m.red(` patch failed: ${S.message?.slice(0,150)}`));return}if(!f||f.length<20){console.log(m.yellow(" patch returned nothing usable."));return}let u=d.content.split(`
406
+ A: ${N.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",b||"(none yet)","","## Output rules","- Output EXACTLY one markdown file: frontmatter (---) + body. No code fences, no preamble.","- Frontmatter fields in this exact order: title, type, related, tags, owner, access, created, last_updated, sources.",' - `title`: "\u2026"',` - \`type\`: ${d}`,' - `related`: ["Article Title", \u2026] (titles that exist in the catalog above; drop if none)'," - `tags`: 2-4 specific tags, lowercase-kebab \u2014 no dates unless type=event",` - \`owner\`: ${e.agent}`," - `access`: public (unless the content is sensitive)",` - \`created\`: ${new Date().toISOString().slice(0,10)}`,` - \`last_updated\`: ${new Date().toISOString().slice(0,10)}`,` - \`sources\`: ["interview-${new Date().toISOString().slice(0,10)}"]`,"- Body: 20-80 lines, Wikipedia-style, organized by theme (not by question), synthesized (not verbatim Q&A).","- Use [[Title]] inline every time you reference something that has an article in the catalog.","- Do NOT invent facts. If the transcript didn't cover something, skip that sub-topic."].join(`
407
+ `),A=W(a.baseDir,"_tmp");mo(A,{recursive:!0});let x=W(A,`interview-${t().slice(0,8)}.txt`);zo(x,S),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let v="";try{let N=`cat '${x}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,pe=Ho(N,{env:Qo({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Ge=JSON.parse(pe);v=String(Ge.result||Ge.content||"")}catch{v=pe}}catch(N){console.log(m.red(` synthesis failed: ${N.message?.slice(0,200)}`)),c?.close();return}v=v.trim();let $=v.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);$&&(v=$[1].trim());let C=v.indexOf("---");C>0&&(v=v.slice(C));let j=v.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!j){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(v.slice(0,600)),c?.close();return}let T={};for(let N of j[1].split(`
408
+ `)){let pe=N.match(/^(\w+):\s*(.+)$/);pe&&(T[pe[1]]=pe[2].trim().replace(/^"(.*)"$/,"$1"))}let D=j[2],B=T.title||g,M=B.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),ce=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${M}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${ce}`)),console.log(),console.log(v),console.log();let J=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),J==="scrap"||J==="/abort"){console.log(m.dim(" Discarded."));return}if(!e.commit){console.log(m.dim(" --no-commit: not writing.")),console.log(m.dim(` Draft kept at ${x} (prompt only; no article file)`));return}let xe=D,we={title:B,type:T.type||d,related:T.related?T.related.replace(/^\[|\]$/g,"").split(",").map(N=>N.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:T.tags?T.tags.replace(/^\[|\]$/g,"").split(",").map(N=>N.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:T.access||"public",created:T.created||new Date().toISOString().slice(0,10),lastUpdated:T.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(J==="edit"){let N=process.env.EDITOR||"vi",pe=W(A,`draft-${t().slice(0,8)}.md`);zo(pe,v);try{Ho(`${N} '${pe}'`,{stdio:"inherit"});let ps=on(pe,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(ps){let uo={};for(let It of ps[1].split(`
409
+ `)){let us=It.match(/^(\w+):\s*(.+)$/);us&&(uo[us[1]]=us[2].trim().replace(/^"(.*)"$/,"$1"))}xe=ps[2],we={...we,title:uo.title||we.title,type:uo.type||we.type,access:uo.access||we.access,related:uo.related?uo.related.replace(/^\[|\]$/g,"").split(",").map(It=>It.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):we.related,tags:uo.tags?uo.tags.replace(/^\[|\]$/g,"").split(",").map(It=>It.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):we.tags}}}catch(Ge){console.log(m.red(` editor failed: ${Ge.message}`));return}}if(!a.writeArticle(ce,we,xe,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${ce} saved.`));let Be=a.extractWikilinks(xe),be=new Map;for(let N of a.listArticles(e.agent))be.set(N.meta.title.toLowerCase(),!0);let No=Be.filter(N=>!be.has(N.toLowerCase()));if(No.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let N of No.slice(0,8))console.log(m.dim(` - ${N}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});ee.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{agenticQuery:n}=await import("./query-6EMTLCHQ.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=ve(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(f){console.log(m.red(` can't open wiki for agent "${e.agent}": ${f.message}`));return}let r=null;if(e.script){let p=on(e.script,"utf-8").split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);r=[];for(let w of p){let y=w.split(/\r?\n/).filter(S=>S.trim());if(y.length<2)continue;let k=y[0].replace(/^Q:\s*/i,"").trim(),b=y.slice(1).join(" ").trim();k&&b&&r.push({q:k,verdict:b})}}let a=r?null:o.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",l=Math.min(parseInt(e.rounds)||20,r?.length??999),g=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${l} \xB7 ${g?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let d=[],u=0;for(let f=0;f<l;f++){let p,w;if(r){let H=r[f];if(!H)break;p=H.q,w=H.verdict,console.log(m.cyan(` [${f+1}] Q: `)+p)}else{if(p=await c(m.cyan(` [${f+1}] Q: `)),!p||p==="/done"||p==="/abort")break;w=""}process.stdout.write(m.dim(" querying... "));let y;try{y=await n(p,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(H){console.log(m.red(`failed: ${H.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),y.status!=="ok")console.log(m.yellow(` (status: ${y.status}${y.error?" \u2014 "+y.error:""})`));else{let H=y.citations.map(ce=>`${ce.title} [${ce.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
410
+ `)),console.log(m.dim(" citations: "+H))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let k={q:p,answer:y.answer,citations:y.citations,verdict:w},b=w.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!b){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(k);continue}let S=b[1].toLowerCase(),A=(b[2]||"").trim();if(d.push(k),S==="/ok"||S==="/skip")continue;if(!A){console.log(m.yellow(` ${S} without note \u2014 skipping.`));continue}let x=y.citations[0];if(!x){console.log(m.yellow(" no cited article to patch."));continue}let v=i.readArticle(x.path);if(!v){console.log(m.red(` can't read ${x.path} to patch.`));continue}console.log(m.dim(` patching ${x.title} (${x.path})...`));let $=du(v.content,S,A,v.meta.title,v.meta.type),C=W(i.baseDir,"_tmp");mo(C,{recursive:!0});let j=W(C,`quiz-patch-${t().slice(0,8)}.txt`);zo(j,$);let T="";try{let H=`cat '${j}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,ce=Ho(H,{env:Qo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let xe=JSON.parse(ce);T=String(xe.result||xe.content||"")}catch{T=ce}let J=T.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);J&&(T=J[1].trim()),T=T.trim()}catch(H){console.log(m.red(` patch failed: ${H.message?.slice(0,120)}`));continue}if(!T||T.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let D=v.content.split(`
411
+ `).length,B=T.split(`
412
+ `).length;if(console.log(m.dim(` diff: ${D} \u2192 ${B} lines (${B-D>=0?"+":""}${B-D})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),k.patched=x.path+" (dry)";continue}if(!i.writeArticle(x.path,{...v.meta,lastUpdated:new Date().toISOString().slice(0,10)},T,e.agent)){console.log(m.red(" write failed (permission?)"));continue}u++,k.patched=x.path,console.log(m.green(` \u2713 patched ${x.path}`))}if(a&&a.close(),u>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${d.length} rounds, ${u} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${u} patches_`,""];for(let p=0;p<d.length;p++){let w=d[p];f.push(`## ${p+1}. Q: ${w.q}`,"",`**A:** ${w.answer}`,"",`**Citations:** ${w.citations.map(y=>`\`${y.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${w.verdict}\``+(w.patched?` \u2192 patched \`${w.patched}\``:""),"")}zo(e.out,f.join(`
413
+ `)),console.log(m.dim(` Transcript written to ${e.out}`))}});ee.command("edit <agent> <titleOrPath>").description("open an article in $EDITOR (resolves by title or path), rebuild catalog on exit").option("--dir <path>","wiki directory").option("--editor <cmd>","override $EDITOR for this run").action((e,o,t)=>{let n=ve(t.dir),s;try{s=n.getAgentWiki(e)}catch(l){console.log(m.red(` can't open wiki for agent "${e}": ${l.message}`));return}let i=al(s,o,e);if(!i){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`)),console.log(m.dim(` Tip: ${m.green("agentx wiki status")} lists agents; ${m.green(`agentx wiki search "term" --agent ${e}`)} finds by content.`));return}let r=W(s.baseDir,i),a=t.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${i} in ${a}...`));try{Ho(`${a} '${r}'`,{stdio:"inherit"})}catch(l){console.log(m.red(` editor exited with error: ${l.message?.slice(0,150)}`));return}let c=s.readArticle(i);if(c){let l=new Set,g=s.extractWikilinks(c.content).filter(f=>l.has(f)?!1:(l.add(f),!0)),d=c.meta.related||[];(g.some(f=>!d.includes(f))||d.some(f=>!g.includes(f)))&&(s.writeArticle(i,{...c.meta,related:g.length?g:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.content,e),console.log(m.dim(` (synced frontmatter.related from body: ${g.length} wikilink${g.length===1?"":"s"})`)))}try{s.rebuildIndex(),console.log(m.green(` \u2713 ${i} saved. Catalog rebuilt.`))}catch(l){console.log(m.yellow(` saved, but catalog rebuild failed: ${l.message?.slice(0,100)}`))}});ee.command("patch <agent> <titleOrPath> <instruction>").description("LLM-patch an article from a free-form instruction; shows diff + confirms before writing").option("--dir <path>","wiki directory").option("--patch-model <m>","patch model","sonnet").option("--yes","skip confirmation and write immediately").option("--no-commit","show the patched body but don't write").action(async(e,o,t,n)=>{let s=await import("node:readline/promises"),{randomUUID:i}=await import("node:crypto"),r=ve(n.dir),a;try{a=r.getAgentWiki(e)}catch(x){console.log(m.red(` can't open wiki for agent "${e}": ${x.message}`));return}let c=al(a,o,e);if(!c){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`));return}let l=a.readArticle(c);if(!l){console.log(m.red(` can't read ${c}.`));return}let g=lu(l.content,l.meta.title,l.meta.type,t),d=W(a.baseDir,"_tmp");mo(d,{recursive:!0});let u=W(d,`patch-${i().slice(0,8)}.txt`);zo(u,g),console.log(),console.log(m.dim(` Target: ${l.meta.title} (${c})`)),console.log(m.dim(` Patching with ${n.patchModel}...`));let f="";try{let x=`cat '${u}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,v=Ho(x,{env:Qo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let C=JSON.parse(v);f=String(C.result||C.content||"")}catch{f=v}let $=f.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);$&&(f=$[1].trim()),f=f.trim()}catch(x){console.log(m.red(` patch failed: ${x.message?.slice(0,150)}`));return}if(!f||f.length<20){console.log(m.yellow(" patch returned nothing usable."));return}let p=l.content.split(`
387
414
  `).length,w=f.split(`
388
- `).length;if(console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${u} \u2192 ${w} lines (${w-u>=0?"+":""}${w-u})`)),console.log(),console.log(f),console.log(),!n.commit){console.log(m.dim(" --no-commit: preview only, not written."));return}let y=!!n.yes;if(!y){let S=s.createInterface({input:process.stdin,output:process.stdout}),v=(await S.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();S.close(),y=v==="y"||v==="yes"}if(!y){console.log(m.dim(" aborted."));return}let k=new Set,b=a.extractWikilinks(f).filter(S=>k.has(S)?!1:(k.add(S),!0));if(!a.writeArticle(c,{...d.meta,related:b.length?b:void 0,lastUpdated:new Date().toISOString().slice(0,10)},f,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex();let A=(d.meta.related||[]).filter(S=>!b.includes(S));A.length&&console.log(m.dim(` (pruned stale related: ${A.slice(0,3).join(", ")}${A.length>3?", \u2026":""})`)),console.log(m.green(` \u2713 ${c} patched.`))});function Gc(e,o,t){let n=o.trim(),s=e.listArticles(t),i=n.toLowerCase(),r=s.find(d=>d.meta.title.toLowerCase()===i);if(r)return r.path;if(n.includes("/")||n.endsWith(".md")){let d=n.endsWith(".md")?n:`${n}.md`,g=s.find(l=>l.path===d||l.path===n);if(g)return g.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(d=>{let g=d.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return g===a||g.includes(a)||d.path.toLowerCase().includes(a)});return c?c.path:null}function Hp(e,o,t,n){return["You are editing a single wiki article to incorporate an operator instruction.","",`## Article: "${o}" (type: ${t||"untyped"})`,"","<article-body>",e,"</article-body>","","## Operator instruction",n,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the instruction requires changing them.","- Make the MINIMUM edit that satisfies the instruction \u2014 don't rewrite untouched sections.","- If the instruction is ambiguous or can't be applied, return the original body unchanged."].join(`
389
- `)}function zp(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
415
+ `).length;if(console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${p} \u2192 ${w} lines (${w-p>=0?"+":""}${w-p})`)),console.log(),console.log(f),console.log(),!n.commit){console.log(m.dim(" --no-commit: preview only, not written."));return}let y=!!n.yes;if(!y){let x=s.createInterface({input:process.stdin,output:process.stdout}),v=(await x.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();x.close(),y=v==="y"||v==="yes"}if(!y){console.log(m.dim(" aborted."));return}let k=new Set,b=a.extractWikilinks(f).filter(x=>k.has(x)?!1:(k.add(x),!0));if(!a.writeArticle(c,{...l.meta,related:b.length?b:void 0,lastUpdated:new Date().toISOString().slice(0,10)},f,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex();let A=(l.meta.related||[]).filter(x=>!b.includes(x));A.length&&console.log(m.dim(` (pruned stale related: ${A.slice(0,3).join(", ")}${A.length>3?", \u2026":""})`)),console.log(m.green(` \u2713 ${c} patched.`))});function al(e,o,t){let n=o.trim(),s=e.listArticles(t),i=n.toLowerCase(),r=s.find(l=>l.meta.title.toLowerCase()===i);if(r)return r.path;if(n.includes("/")||n.endsWith(".md")){let l=n.endsWith(".md")?n:`${n}.md`,g=s.find(d=>d.path===l||d.path===n);if(g)return g.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(l=>{let g=l.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return g===a||g.includes(a)||l.path.toLowerCase().includes(a)});return c?c.path:null}function lu(e,o,t,n){return["You are editing a single wiki article to incorporate an operator instruction.","",`## Article: "${o}" (type: ${t||"untyped"})`,"","<article-body>",e,"</article-body>","","## Operator instruction",n,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the instruction requires changing them.","- Make the MINIMUM edit that satisfies the instruction \u2014 don't rewrite untouched sections.","- If the instruction is ambiguous or can't be applied, return the original body unchanged."].join(`
416
+ `)}function du(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
390
417
 
391
418
  ${t}
392
419
 
@@ -399,8 +426,8 @@ Incorporate it into the most relevant existing section, or create a short new se
399
426
  ${t}
400
427
 
401
428
  Add it as a Markdown link in the most relevant section, or append a "## References" section at the end if none exists. If it looks like a URL, use it as-is; otherwise treat it as a wikilink target and use [[${t}]].`};return["You are editing a single wiki article to incorporate operator feedback.","",`## Article: "${n}" (type: ${s||"untyped"})`,"","<article-body>",e,"</article-body>","","## Edit instruction",i[o]||`Make a minimal edit per: ${t}`,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the edit requires changing them.","- If no meaningful edit can be made from the operator's feedback, return the original body unchanged."].join(`
402
- `)}ee.command("prune").description("collapse legacy flat/unified mode dirs into graph/ (dedup by title; losers archived)").option("--dir <path>","wiki directory").option("--agent <id>","prune only this agent's wiki").option("--commit","execute moves + archives (default: dry-run)").action(async e=>{let o=ve(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=!!e.commit,s=e.dir?q(e.dir):q(process.cwd(),".agentx/wiki"),i="graph",r=["flat","unified"];console.log(),console.log(m.bold(n?" Pruning (commit)":" Pruning (dry-run)")),console.log(m.dim(` Canonical: ${i}/ \xB7 Legacy to collapse: ${r.join("/, ")}/`));let a=0,c=0,d=0,g=0;for(let l of t){let p=q(s,"agents",l);if(!Je(p))continue;let f=q(p,i),u=r.map(b=>({mode:b,dir:q(p,b)})).filter(b=>Je(b.dir));if(u.length===0)continue;let w=new Map;ui(f,b=>{let x=qc(f,b);if(x.startsWith("_")||x.startsWith("raw/")||x.includes("_tmp/"))return;let A=Bc(en(b,"utf-8"));A?.meta.title&&w.set(A.meta.title.trim().toLowerCase(),{relPath:x,type:A.meta.type,lastUpdated:A.meta.lastUpdated||""})});let y=[];for(let b of u)ui(b.dir,x=>{let A=qc(b.dir,x);if(A.startsWith("_")||A.startsWith("raw/")||A.includes("_tmp/"))return;let S=Bc(en(x,"utf-8"));S?.meta.title&&y.push({mode:b.mode,relPath:A,absPath:x,title:S.meta.title.trim(),type:S.meta.type,lastUpdated:S.meta.lastUpdated||""})});if(a+=y.length,y.length===0)continue;console.log();let k=u.map(b=>b.mode).join("+");console.log(m.bold(` ${m.cyan(l)}: ${y.length} legacy article(s) across ${k}`));for(let b of y){let x=b.title.toLowerCase(),A=w.get(x),S;A?!A.type&&b.type||!!A.type==!!b.type&&b.lastUpdated&&A.lastUpdated&&b.lastUpdated>A.lastUpdated?S="upgrade":S="archive":S="promote";let v=b.type?m.magenta(`[${b.type}]`):m.yellow("[untyped]"),$=S==="promote"?m.green("\u2192 promote "):S==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),C=b.relPath.length>46?b.relPath.slice(0,43)+"...":b.relPath.padEnd(46);if(console.log(` ${$} ${v} ${m.dim(b.mode+"/")}${C}`),S==="upgrade"&&console.log(m.dim(` (replaces ${A.relPath}, old version kept under _versions/)`)),!n){S==="promote"?c++:S==="upgrade"?d++:g++;continue}try{if(S==="promote"){let j=q(f,b.relPath);Je(j)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${b.relPath}`)),Jc(p,b),g++):(go(Wc(j),{recursive:!0}),Qn(b.absPath,j),w.set(x,{relPath:b.relPath,type:b.type,lastUpdated:b.lastUpdated}),c++)}else if(S==="upgrade"){let j=q(f,A.relPath);if(Je(j)){let T=q(p,"_versions",A.relPath.replace(/\.md$/,""));go(T,{recursive:!0});let D=new Date().toISOString().replace(/[:.]/g,"-");Qn(j,q(T,`${D}.md`))}go(Wc(j),{recursive:!0}),Qn(b.absPath,j),w.set(x,{relPath:A.relPath,type:b.type,lastUpdated:b.lastUpdated}),d++}else Jc(p,b),g++}catch(j){console.log(m.red(` ! ${S} failed: ${j.message?.slice(0,120)}`))}}if(n){for(let b of u)try{Jp(b.dir,{recursive:!0,force:!0})}catch{}try{o.getAgentWiki(l).rebuildIndex()}catch(b){console.log(m.dim(` (catalog rebuild skipped: ${b.message?.slice(0,80)})`))}}}console.log(),console.log(m.dim(` Legacy scanned: ${a}`)),n?(console.log(m.green(` Promoted: ${c} \xB7 Upgraded canonical: ${d} \xB7 Archived: ${g}`)),console.log(m.dim(" Archived losers preserved under <agent>/_versions/. Legacy mode dirs deleted."))):(console.log(m.dim(` Would: promote ${c} \xB7 upgrade ${d} \xB7 archive ${g}`)),console.log(m.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function ui(e,o){if(Je(e))for(let t of Bp(e,{withFileTypes:!0})){let n=q(e,t.name);t.isDirectory()?ui(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function Bc(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
403
- `)){let s=n.match(/^(\w+):\s*(.+)$/);if(!s)continue;let i=s[1]==="last_updated"?"lastUpdated":s[1];t[i]=s[2].trim().replace(/^"(.*)"$/,"$1")}return{meta:t}}function Jc(e,o){let t=q(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));go(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");Qn(o.absPath,q(t,`${n}.md`))}ee.command("migrate").description("backfill type + related on legacy articles (one-shot)").option("--dir <path>","wiki directory").option("--agent <id>","migrate only this agent's articles").option("--commit","write changes (default: dry-run, reports what would change)").option("--batch <n>","articles per LLM call","10").option("--max <n>","cap articles this run (for spot-checks)").option("--model <m>","classifier model","sonnet").action(async e=>{let o=ve(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=Math.max(1,parseInt(e.batch)||10),s=e.max?parseInt(e.max):1/0,i=!!e.commit;console.log(),console.log(m.bold(i?" Migrating (commit)":" Migrating (dry-run)")),console.log(m.dim(` Batch size: ${n} \xB7 Model: ${e.model}`)),console.log();let r=0,a=0,c=0;for(let d of t){let g=o.getAgentWiki(d),l=g.listArticles(d),p=l.filter(k=>!k.meta.type);if(r+=l.length,a+=p.length,p.length===0){console.log(` ${m.cyan(d)}: ${m.green("all typed")} (${l.length} articles)`);continue}let f=Math.max(0,s-c),u=Math.min(p.length,f);if(u===0){console.log(m.dim(` ${d}: skipped (--max reached)`));continue}console.log(),console.log(m.bold(` ${m.cyan(d)}: ${u}/${p.length} untyped articles`));let w=g.baseDir,y=q(w,"_tmp");go(y,{recursive:!0});for(let k=0;k<u;k+=n){let b=p.slice(k,Math.min(k+n,u)),x=Vp(b),A=q(y,"migrate-prompt.txt");Go(A,x);let S;try{let v=`cat '${A}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,$=Jo(v,{env:Ko({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),C=JSON.parse($),T=String(C.result||C.content||"").match(/\[[\s\S]*\]/);if(!T)throw new Error("no JSON array in classifier response");S=JSON.parse(T[0])}catch(v){console.log(m.red(` LLM classify failed: ${v.message?.slice(0,150)}`));continue}for(let v of b){let $=S.find(L=>L.path===v.path),C=Yp($?.type);if(!$||!C){console.log(m.yellow(` ? ${v.path}: unclassified${$?` (got "${$.type}")`:""}`));continue}let j=g.extractWikilinks(v.content),T={...v.meta,type:C.type,related:j.length?j:void 0,lastUpdated:new Date().toISOString().slice(0,10)},D=j.length?m.dim(` \u2192 ${j.slice(0,3).join(", ")}${j.length>3?", \u2026":""}`):"",W=C.alias?m.dim(` (from "${C.alias}")`):"";console.log(` ${m.green("+")} ${m.magenta("["+C.type+"]")}${W} ${v.path}${D}`),i&&(g.writeArticle(v.path,T,v.content,d),c++)}}i&&g.rebuildIndex()}console.log(),console.log(m.dim(` Scanned ${r} articles; ${a} needed migration`)),console.log(i?m.green(` Applied ${c} patches.`):m.dim(" Dry-run \u2014 add --commit to write changes.")),console.log()});function Yp(e){if(!e)return null;let o=String(e).trim().toLowerCase().replace(/^[\s"'`]+|[\s"'`]+$/g,"");if(!o)return null;let n={person:"person",project:"project",place:"place",concept:"concept",event:"event",decision:"decision",pattern:"pattern",people:"person",projects:"project",places:"place",concepts:"concept",events:"event",decisions:"decision",patterns:"pattern",agent:"project",bot:"project",service:"project",product:"project",tool:"project",repo:"project",repository:"project",app:"project",application:"project",team:"project",organization:"project",company:"project",issue:"event",mr:"event","merge-request":"event",merge_request:"event",ticket:"event",incident:"event",deploy:"event",deployment:"event",launch:"event",release:"event",process:"pattern",procedure:"pattern",workflow:"pattern",runbook:"pattern",recipe:"pattern",template:"pattern",sop:"pattern",infrastructure:"place",infra:"place",server:"place",environment:"place",env:"place",location:"place",host:"place",decisionrecord:"decision",adr:"decision","decision-record":"decision"}[o];return n?n===o?{type:n}:{type:n,alias:o}:null}function Vp(e){let o=e.map((t,n)=>{let s=t.content.replace(/\s+/g," ").slice(0,400),i=(t.meta.tags||[]).slice(0,8).join(", ");return`${n+1}. path: "${t.path}"
429
+ `)}ee.command("prune").description("collapse legacy flat/unified mode dirs into graph/ (dedup by title; losers archived)").option("--dir <path>","wiki directory").option("--agent <id>","prune only this agent's wiki").option("--commit","execute moves + archives (default: dry-run)").action(async e=>{let o=ve(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=!!e.commit,s=e.dir?W(e.dir):W(process.cwd(),".agentx/wiki"),i="graph",r=["flat","unified"];console.log(),console.log(m.bold(n?" Pruning (commit)":" Pruning (dry-run)")),console.log(m.dim(` Canonical: ${i}/ \xB7 Legacy to collapse: ${r.join("/, ")}/`));let a=0,c=0,l=0,g=0;for(let d of t){let u=W(s,"agents",d);if(!Je(u))continue;let f=W(u,i),p=r.map(b=>({mode:b,dir:W(u,b)})).filter(b=>Je(b.dir));if(p.length===0)continue;let w=new Map;hi(f,b=>{let S=nl(f,b);if(S.startsWith("_")||S.startsWith("raw/")||S.includes("_tmp/"))return;let A=il(on(b,"utf-8"));A?.meta.title&&w.set(A.meta.title.trim().toLowerCase(),{relPath:S,type:A.meta.type,lastUpdated:A.meta.lastUpdated||""})});let y=[];for(let b of p)hi(b.dir,S=>{let A=nl(b.dir,S);if(A.startsWith("_")||A.startsWith("raw/")||A.includes("_tmp/"))return;let x=il(on(S,"utf-8"));x?.meta.title&&y.push({mode:b.mode,relPath:A,absPath:S,title:x.meta.title.trim(),type:x.meta.type,lastUpdated:x.meta.lastUpdated||""})});if(a+=y.length,y.length===0)continue;console.log();let k=p.map(b=>b.mode).join("+");console.log(m.bold(` ${m.cyan(d)}: ${y.length} legacy article(s) across ${k}`));for(let b of y){let S=b.title.toLowerCase(),A=w.get(S),x;A?!A.type&&b.type||!!A.type==!!b.type&&b.lastUpdated&&A.lastUpdated&&b.lastUpdated>A.lastUpdated?x="upgrade":x="archive":x="promote";let v=b.type?m.magenta(`[${b.type}]`):m.yellow("[untyped]"),$=x==="promote"?m.green("\u2192 promote "):x==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),C=b.relPath.length>46?b.relPath.slice(0,43)+"...":b.relPath.padEnd(46);if(console.log(` ${$} ${v} ${m.dim(b.mode+"/")}${C}`),x==="upgrade"&&console.log(m.dim(` (replaces ${A.relPath}, old version kept under _versions/)`)),!n){x==="promote"?c++:x==="upgrade"?l++:g++;continue}try{if(x==="promote"){let j=W(f,b.relPath);Je(j)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${b.relPath}`)),rl(u,b),g++):(mo(sl(j),{recursive:!0}),Qn(b.absPath,j),w.set(S,{relPath:b.relPath,type:b.type,lastUpdated:b.lastUpdated}),c++)}else if(x==="upgrade"){let j=W(f,A.relPath);if(Je(j)){let T=W(u,"_versions",A.relPath.replace(/\.md$/,""));mo(T,{recursive:!0});let D=new Date().toISOString().replace(/[:.]/g,"-");Qn(j,W(T,`${D}.md`))}mo(sl(j),{recursive:!0}),Qn(b.absPath,j),w.set(S,{relPath:A.relPath,type:b.type,lastUpdated:b.lastUpdated}),l++}else rl(u,b),g++}catch(j){console.log(m.red(` ! ${x} failed: ${j.message?.slice(0,120)}`))}}if(n){for(let b of p)try{au(b.dir,{recursive:!0,force:!0})}catch{}try{o.getAgentWiki(d).rebuildIndex()}catch(b){console.log(m.dim(` (catalog rebuild skipped: ${b.message?.slice(0,80)})`))}}}console.log(),console.log(m.dim(` Legacy scanned: ${a}`)),n?(console.log(m.green(` Promoted: ${c} \xB7 Upgraded canonical: ${l} \xB7 Archived: ${g}`)),console.log(m.dim(" Archived losers preserved under <agent>/_versions/. Legacy mode dirs deleted."))):(console.log(m.dim(` Would: promote ${c} \xB7 upgrade ${l} \xB7 archive ${g}`)),console.log(m.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function hi(e,o){if(Je(e))for(let t of ru(e,{withFileTypes:!0})){let n=W(e,t.name);t.isDirectory()?hi(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function il(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
430
+ `)){let s=n.match(/^(\w+):\s*(.+)$/);if(!s)continue;let i=s[1]==="last_updated"?"lastUpdated":s[1];t[i]=s[2].trim().replace(/^"(.*)"$/,"$1")}return{meta:t}}function rl(e,o){let t=W(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));mo(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");Qn(o.absPath,W(t,`${n}.md`))}ee.command("migrate").description("backfill type + related on legacy articles (one-shot)").option("--dir <path>","wiki directory").option("--agent <id>","migrate only this agent's articles").option("--commit","write changes (default: dry-run, reports what would change)").option("--batch <n>","articles per LLM call","10").option("--max <n>","cap articles this run (for spot-checks)").option("--model <m>","classifier model","sonnet").action(async e=>{let o=ve(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=Math.max(1,parseInt(e.batch)||10),s=e.max?parseInt(e.max):1/0,i=!!e.commit;console.log(),console.log(m.bold(i?" Migrating (commit)":" Migrating (dry-run)")),console.log(m.dim(` Batch size: ${n} \xB7 Model: ${e.model}`)),console.log();let r=0,a=0,c=0;for(let l of t){let g=o.getAgentWiki(l),d=g.listArticles(l),u=d.filter(k=>!k.meta.type);if(r+=d.length,a+=u.length,u.length===0){console.log(` ${m.cyan(l)}: ${m.green("all typed")} (${d.length} articles)`);continue}let f=Math.max(0,s-c),p=Math.min(u.length,f);if(p===0){console.log(m.dim(` ${l}: skipped (--max reached)`));continue}console.log(),console.log(m.bold(` ${m.cyan(l)}: ${p}/${u.length} untyped articles`));let w=g.baseDir,y=W(w,"_tmp");mo(y,{recursive:!0});for(let k=0;k<p;k+=n){let b=u.slice(k,Math.min(k+n,p)),S=mu(b),A=W(y,"migrate-prompt.txt");zo(A,S);let x;try{let v=`cat '${A}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,$=Ho(v,{env:Qo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),C=JSON.parse($),T=String(C.result||C.content||"").match(/\[[\s\S]*\]/);if(!T)throw new Error("no JSON array in classifier response");x=JSON.parse(T[0])}catch(v){console.log(m.red(` LLM classify failed: ${v.message?.slice(0,150)}`));continue}for(let v of b){let $=x.find(M=>M.path===v.path),C=gu($?.type);if(!$||!C){console.log(m.yellow(` ? ${v.path}: unclassified${$?` (got "${$.type}")`:""}`));continue}let j=g.extractWikilinks(v.content),T={...v.meta,type:C.type,related:j.length?j:void 0,lastUpdated:new Date().toISOString().slice(0,10)},D=j.length?m.dim(` \u2192 ${j.slice(0,3).join(", ")}${j.length>3?", \u2026":""}`):"",B=C.alias?m.dim(` (from "${C.alias}")`):"";console.log(` ${m.green("+")} ${m.magenta("["+C.type+"]")}${B} ${v.path}${D}`),i&&(g.writeArticle(v.path,T,v.content,l),c++)}}i&&g.rebuildIndex()}console.log(),console.log(m.dim(` Scanned ${r} articles; ${a} needed migration`)),console.log(i?m.green(` Applied ${c} patches.`):m.dim(" Dry-run \u2014 add --commit to write changes.")),console.log()});function gu(e){if(!e)return null;let o=String(e).trim().toLowerCase().replace(/^[\s"'`]+|[\s"'`]+$/g,"");if(!o)return null;let n={person:"person",project:"project",place:"place",concept:"concept",event:"event",decision:"decision",pattern:"pattern",people:"person",projects:"project",places:"place",concepts:"concept",events:"event",decisions:"decision",patterns:"pattern",agent:"project",bot:"project",service:"project",product:"project",tool:"project",repo:"project",repository:"project",app:"project",application:"project",team:"project",organization:"project",company:"project",issue:"event",mr:"event","merge-request":"event",merge_request:"event",ticket:"event",incident:"event",deploy:"event",deployment:"event",launch:"event",release:"event",process:"pattern",procedure:"pattern",workflow:"pattern",runbook:"pattern",recipe:"pattern",template:"pattern",sop:"pattern",infrastructure:"place",infra:"place",server:"place",environment:"place",env:"place",location:"place",host:"place",decisionrecord:"decision",adr:"decision","decision-record":"decision"}[o];return n?n===o?{type:n}:{type:n,alias:o}:null}function mu(e){let o=e.map((t,n)=>{let s=t.content.replace(/\s+/g," ").slice(0,400),i=(t.meta.tags||[]).slice(0,8).join(", ");return`${n+1}. path: "${t.path}"
404
431
  title: "${t.meta.title}"
405
432
  tags: [${i}]
406
433
  body: ${s}${t.content.length>400?"\u2026":""}`}).join(`
@@ -440,45 +467,48 @@ Output (JSON array, one entry per input article, same order):
440
467
  [
441
468
  {"path": "path/to/article.md", "type": "project"},
442
469
  ...
443
- ]`}ee.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=ve(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});ee.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let o=e.dir||q(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-SRTXHGSK.js");n=(s().mesh?.peers||[]).map(r=>r.url)}catch{}console.log(),console.log(m.bold(" AgentX Wiki Server")),console.log(),console.log(` ${m.green(">")} http://localhost:${t}`),e.agent?console.log(` Agent: ${m.cyan(e.agent)}`):console.log(` Mode: ${m.cyan("Hub")} (all agents)`),n.length>0&&console.log(` Mesh: ${m.cyan(n.length+" peer(s)")} \u2014 ${n.join(", ")}`),console.log(m.dim(` Wiki: ${o}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),oa(o,t,e.agent,n,e.mode)});ee.command("grade").description("grade absorbed articles with the article-quality seat").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","grade only this agent's wiki").option("--limit <n>","articles to grade","20").option("--min <n>","only show articles scoring below this","3").option("--fields","also check the required fields for each article's type").option("--type <t>","grade only articles of this type (person, place, project, \u2026)").option("--json").action(async e=>{let{articleQualityQuestionsFor:o,articleQualityState:t,gradeArticle:n,ARTICLE_QUALITY_SEAT:s}=await import("./article-quality-44ONVGLN.js"),{fieldQuestions:i,reportFields:r}=await import("./article-fields-L4D2BOGY.js"),{askSeat:a}=await import("./seat-XB4EGUKJ.js"),c=ve(e.dir,e.mode),d=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),l=parseFloat(e.min),p=[];e:for(let y of d){let k=c.getAgentWiki(y);for(let b of k.listArticles(y)){if(p.length>=g)break e;let x=k.readArticle(b.path);if(!x||e.type&&x.meta.type!==e.type)continue;let A={...o(x.meta.type),...e.fields?i(x.meta.type):{}},S=await a(s,t({path:b.path,title:x.meta.title,type:x.meta.type,tags:x.meta.tags,body:x.content}),A,{links:[{kind:"article",id:b.path}],features:{agent:y,type:x.meta.type??"?"}});if(!S){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let v=n(S.answers),$=e.fields?r(x.meta.type,S.answers):null;v.completeness>=l&&!($&&!$.fit)||p.push({agent:y,type:x.meta.type??"?",score:v.completeness.toFixed(2),standsAlone:v.standsAlone.toFixed(2),gap:v.biggestGap,...$?{missing:$.missingCritical.join(",")||"-",cov:`${Math.round($.coverage*100)}%`}:{},title:x.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(" no articles below the threshold"));return}p.sort((y,k)=>parseFloat(y.score)-parseFloat(k.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],u=f.map(y=>Math.max(y.length,...p.map(k=>String(k[y]).length))),w=y=>y.map((k,b)=>String(k).padEnd(u[b])).join(" ");console.log(),console.log(m.bold(w(f)));for(let y of p)console.log(w(f.map(k=>y[k])));if(e.fields){let y=p.filter(k=>k.missing!=="-").length;console.log(m.dim(`
444
- ${p.length} article(s) flagged; ${y} missing a required field.`)),console.log(m.dim(" 'missing' is the actionable column \u2014 a named field beats a score."))}else console.log(m.dim(`
445
- ${p.length} article(s) below ${l}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});ee.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,o)=>{let{agenticQuery:t}=await import("./query-ZSUBNWOL.js"),n=ve(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let d=n.getAgentWiki(c),g=q(d.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(m.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(m.dim(" Citations:"));for(let c of a.citations){let d=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${d} (${c.path})`))}console.log()}if(o.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(d=>!a.candidates.some(g=>g.path===d.path));console.log(m.dim(` followed: ${c.map(d=>`${d.title}@h${d.hop}`).join(" | ")}`))}console.log()}});ee.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,o)=>{let t=ve(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=await t.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});ee.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let o=ve(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=q(process.cwd(),".agentx/graph");if(!Je(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new uo({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[l,p]of Object.entries(i.entries))r.set(l,p.path);if(r.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,d=0,g=0;for(let l of t){let p=o.getAgentWiki(l),f=p.listArticles(l),u=o.getSharedStore().listEntries(),w=new Map(u.map(x=>[x.id,x])),y=0,k=0,b=0;for(let x of f){if(a++,x.meta.graphPath?.length||!x.meta.sources?.length)continue;y++,c++;let A=new Map;for(let v of x.meta.sources){let $=w.get(v);if(!$)continue;let C=String($.meta?.sender??""),j=s.fingerprint({text:$.content,channel:$.source,sender:C}),T=r.get(j);if(!T?.length)continue;let D=T.join("/"),W=A.get(D);W?W.n++:A.set(D,{path:T,n:1})}if(A.size===0)continue;k++,d++;let S;for(let v of A.values())(!S||v.n>S.n)&&(S=v);S&&(e.dryRun||(p.writeArticle(x.path,{...x.meta,graphPath:S.path},x.content,l),b++,g++))}console.log(` ${m.cyan(l)}: ${m.bold(f.length)} articles \xB7 ${y} eligible \xB7 ${k} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${d} matched (${Math.round(d/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});ee.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let t=ve(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-SRTXHGSK.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(m.red(" No --peer specified and no daemon config found")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(n.length===0){console.log(m.dim(" No mesh peers configured"));return}let s=new Set(t.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(m.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(m.red(` HTTP ${a.status}`));continue}let c=await a.json(),d=c.entries||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${d.length} entries`));let l=0;for(let p of d)s.has(p.id)||(e.dryRun||(t.addEntry({id:p.id,date:p.date,agentId:p.agentId,source:`${p.source}@${g}`,sourceContext:p.sourceContext,content:p.content}),s.add(p.id)),l++);l>0?console.log(m.green(` ${l} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=l;try{let p=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(p.ok){let f=await p.json();for(let u of f.agents||[])u.totalEntries>0&&console.log(m.dim(` ${u.agentId}: ${u.totalEntries} entries, ${u.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});ee.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let o=e.dir||q(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let d=new ys(o,void 0,c),l=d.getAgentWiki(t).rebuildIndex(),p=d.getAgentEntries(t),f=d.getUnabsorbedEntries(t),u=new Set,w=0,y=new Set;for(let b of l.articles){for(let x of b.tags||[])u.add(x);w+=b.tags?.length||0;for(let x of b.sources||[])y.add(x)}let k=new Set(l.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:fi(c),articles:l.articles.length,entries:p.length,unabsorbed:f.length,uniqueTags:u.size,avgTags:l.articles.length>0?(w/l.articles.length).toFixed(1):"0",dirs:k.size,coverage:y.size,articleList:l.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,d]of r){let g=s.map(l=>d(l).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,d)=>{let g=Math.max(...s.map(p=>p[c])),l=s.filter(p=>p[c]===g).map(p=>p.label);g>0&&console.log(m.dim(` Best ${d}: ${l.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});ee.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,o)=>{let t=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");Je(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?q(process.cwd(),e):q(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=q(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),d=c("tar",a,{stdio:"inherit"});d.status!==0&&(console.log(m.red(` tar exited with ${d.status}`)),process.exit(d.status||1));let{statSync:g}=await import("fs"),l=Je(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Kp(l)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});ee.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-L4D2BOGY.js"),{askSeat:a}=await import("./seat-XB4EGUKJ.js"),{QuestionStore:c}=await import("./questions-4B4KSPXG.js"),d=ve(e.dir,e.mode),g=[],l=e.agent?[e.agent]:d.listAgents(),p=parseInt(e.limit),f=0,u=[];e:for(let v of l){let $=d.getAgentWiki(v);for(let C of $.listArticles(v)){if(f>=p)break e;let j=$.readArticle(C.path);if(!j||e.type&&j.meta.type!==e.type)continue;f++;let T=await a(r,n({title:j.meta.title,type:j.meta.type,body:j.content}),o(j.meta.type),{links:[{kind:"article",id:C.path}],features:{agent:v,type:j.meta.type??"?"}});if(!T){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let D=t(j.meta.type,T.answers);for(let W of s(D,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&W.needsHuman||(e.ask&&W.needsHuman&&g.push({kind:"field",agentId:v,path:C.path,subject:j.meta.title,field:W.field,tier:W.tier,question:`${j.meta.title} (${j.meta.type??"?"}) \u2014 ${W.label}?`}),u.push({tier:W.tier,need:W.field,how:W.needsHuman?m.yellow("ask"):W.sources.join("/"),uncertain:W.uncertain?"?":"",agent:v,article:j.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&g.length>0&&(w=new c(on(e.dir)).add(g)),e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],k=v=>String(v).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(v=>Math.max(v.length,...u.map($=>k($[v]).length))),x=(v,$)=>String(v)+" ".repeat(Math.max(0,b[$]-k(v).length));console.log(),console.log(m.bold(y.map((v,$)=>x(v,$)).join(" ")));for(let v of u)console.log(y.map(($,C)=>x(v[$],C)).join(" "));let A=u.filter(v=>v.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${u.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${A} can be closed by a lookup; ${u.length-A} need a person.`));let S=u[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${i[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${w.added} question(s) for a person (${w.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&w.added>0){let{TIER_RANK:v}=await import("./article-fields-L4D2BOGY.js"),$=v[e.notifyTier]??v.pillar,C=g.filter(j=>(v[j.tier??"furniture"]??9)<=$);if(C.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:j}=await import("./config-SRTXHGSK.js"),T=j(),D=T?.notifications?.destination;if(!D?.channel||!D?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let W=C.slice(0,10).map(B=>`\u2022 ${B.question}`).join(`
446
- `),L=C.length>10?`
447
- \u2026and ${C.length-10} more`:"",G=`${C.length} wiki gap(s) need you (${e.notifyTier}+):
448
- ${W}${L}
449
-
450
- agentx wiki questions`,ae=T?.daemon?.port??T?.port??18800;try{let B=await fetch(`http://127.0.0.1:${ae}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:D.channel,chatId:D.chatId,accountId:D.accountId,text:G})});console.log(B.ok?m.cyan(` Pushed ${C.length} question(s) to ${D.channel}.`):m.yellow(` Push failed (${B.status}) \u2014 questions are still queued.`))}catch(B){console.log(m.yellow(` Push failed (${String(B?.message??B).slice(0,80)}) \u2014 questions are still queued.`))}}}}});ee.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-L4D2BOGY.js"),{askSeat:r}=await import("./seat-XB4EGUKJ.js"),{resolveFacts:a,mergeRecords:c,installPrompts:d,defaultSources:g,recordsFromEntries:l}=await import("./facts-YVEJOM7O.js"),{backfillArticle:p}=await import("./backfill-MTD2B62I.js"),f=ve(e.dir,e.mode),u=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=g(),k=c(l(f.getSharedStore().listEntries())),b=new Map(k.map(T=>[T.name.toLowerCase().trim(),T])),x=0,A=0,S=[],v=!1;e:for(let T of u){let D=f.getAgentWiki(T);for(let W of D.listArticles(T)){if(x>=w)break e;if(W.meta.type!=="person")continue;let L=D.readArticle(W.path);if(!L)continue;x++;let G=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),o(L.meta.type),{links:[{kind:"article",id:W.path}],features:{agent:T,op:"backfill"}});if(!G){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let B=t(L.meta.type,G.answers).missing.filter(N=>i.includes(N));if(B.length===0)continue;let{records:xe,results:ye}=await a([{name:L.meta.title,type:"person"}],{sources:y}),P=b.get(L.meta.title.toLowerCase().trim());if(!v){for(let N of d(ye,y))console.log(m.yellow(` ! ${N.source} ${N.kind} \u2014 would supply ${N.provides.join(", ")}`)),console.log(m.dim(` ${N.hint}`));v=!0}let qe=c([...P?[{name:P.name,source:"entries",fields:Object.fromEntries(Object.entries(P.fields).map(([N,me])=>[N,me.value]))}]:[],...xe]);if(qe.length===0)continue;let{content:we,edits:Co}=p(L.content,qe[0],B);if(Co.length!==0){for(let N of Co)S.push({agent:T,article:L.meta.title.slice(0,32),field:N.field,action:N.replaced?"replace":"add",got:`${N.value.split(";").length} value(s)`});e.apply&&(D.writeArticle(W.path,L.meta,we,T)?A++:console.log(m.red(` could not write ${W.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${x} person article(s) considered \u2014 nothing to backfill`));return}let $=["agent","article","field","action","got"],C=$.map(T=>Math.max(T.length,...S.map(D=>String(D[T]).length))),j=T=>T.map((D,W)=>String(D).padEnd(C[W])).join(" ");console.log(),console.log(m.bold(j($)));for(let T of S)console.log(j($.map(D=>T[D])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${A} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${x} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});ee.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:o}=await import("./questions-4B4KSPXG.js"),{TIER_RANK:t}=await import("./article-fields-L4D2BOGY.js"),n=new o(on(e.dir)).list(e.status);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(m.green(` no ${e.status} questions`));return}n.sort((s,i)=>(t[s.tier??"furniture"]??9)-(t[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});ee.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,o,t)=>{let{QuestionStore:n}=await import("./questions-4B4KSPXG.js"),{patchIdentityField:s}=await import("./backfill-MTD2B62I.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-L4D2BOGY.js"),r=new n(on(t.dir));if(t.dismiss){let f=r.resolve(e,"dismissed");console.log(f?m.dim(` dismissed: ${f.question}`):m.red(` no question matching "${e}"`));return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let a=r.resolve(e,"answered",o);if(!a){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${a.question}`)),a.kind!=="field"||!a.field||!a.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[a.field]){console.log(m.dim(` recorded against ${a.path}. "${a.field}" has no fixed slot, so nothing was rewritten.`));return}let d=ve(t.dir,t.mode).getAgentWiki(a.agentId),g=d.readArticle(a.path);if(!g){console.log(m.yellow(` article gone: ${a.path}`));return}let l=s(g.content,a.field,`${o} (answered by operator)`);if(!l){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=d.writeArticle(a.path,g.meta,l.content,a.agentId);console.log(p?m.green(` wrote ${a.field} into ${a.path} (prior version kept)`):m.red(` could not write ${a.path}`))});ee.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:o,entryTriageQuestions:t,triageState:n,triage:s}=await import("./entry-triage-LK34TSQD.js"),{askSeat:i}=await import("./seat-XB4EGUKJ.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:d,sweepPolicies:g}=await import("./triage-backtest-JNO7RKX7.js"),{calibrationReport:l}=await import("./calibration-ILS5OI44.js"),f=ve(e.dir,"graph").getSharedStore(),u=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:y,backlog:k}=r(u,w),b=a(y,L=>L.absorbed,parseInt(e.n)),x={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},A=[],S=0,v=Date.now();if(e.load){let{readFileSync:L}=await import("fs");A.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${k} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let G=await i(o,n(L),t,{features:{source:L.source??"",absorbed:L.absorbed}});if(!G){S++;continue}let ae=G.answers;A.push({entry:L,verdict:s(G.answers,x),citeWorthy:ae.citeWorthy?.noul})}if(A.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let $=c(A,{minType:x.minTypeConfidence,minWorth:x.minWorth,minDurability:x.minDurability}),C=d(A,"seat","seat"),j=l(C,{minN:50}),T=((Date.now()-v)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:$,calibration:j,failures:S,elapsed:T},null,2));return}let D=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${$.n} (${$.positives} kept by absorb, ${$.negatives} passed over)`),console.log(` recall ${D($.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${D($.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${D($.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${$.lostPositives>0?m.yellow(`lost ${$.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in j)||!j.insufficient)&&console.log(` ECE ${j.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),$.lostPositives>0){let L=$.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let W=$.positiveMeans;if(console.log(m.dim(` positives avg: worth ${W.worth.toFixed(2)} \xB7 durability ${W.durability.toFixed(2)} \xB7 typeConf ${W.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${T}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let L=parseFloat(e.minRecall),{best:G,points:ae}=g(A,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${ae.length} policies, recall floor ${D(L)})`)),G)console.log(` best: ${G.requireTyped?`typed & type>=${G.minType}`:"type gate OFF"} worth>=${G.minWorth} durability>=${G.minDurability}`),console.log(` recall ${D(G.recall)} \xB7 filtered ${D(G.filtered)} \xB7 precision ${D(G.precision)} \xB7 lost ${G.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${D(L)} recall \u2014 not even keeping everything typed.`));let B=ae.slice().sort((xe,ye)=>ye.recall-xe.recall)[0];B&&console.log(m.dim(` Best recall available: ${D(B.recall)} at ${B.requireTyped?`type>=${B.minType}`:"type gate OFF"} worth>=${B.minWorth} dur>=${B.minDurability}, filtering ${D(B.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});ee.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,o)=>{let t=q(process.cwd(),e);Je(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");Je(n)&&!o.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=q(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function Kp(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}ql();import{Command as Xp}from"commander";import R from"chalk";import{resolve as Zn}from"path";import{existsSync as Qp}from"fs";pe();var yt=new Xp().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");yt.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let o=_();if(!o.graph?.enabled){console.log(R.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(R.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(R.red(` agent "${t}" not in config`));return}let n=(e.daemonUrl||o.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new uo({baseDir:Zn(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(R.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(R.bold(` Graph review \u2014 ${r.length} pending`)),console.log(R.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let d=0,g=0,l=0,p=0;for(let u=0;u<r.length;u++){let w=r[u],y=gn(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${u+1}/${r.length}] ${R.cyan(w.msgHash.slice(0,8))} ${R.dim(y)} ... `);let k=Zp(w,a,c),b=null;try{b=await eu(n,t,k,o.dashboard?.token)}catch(S){p++,console.log(R.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){p++,console.log(R.red("ERR no decision"));continue}let x=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(x==="approve")if(console.log(R.green("APPROVE")+" "+R.dim(A)),e.dryRun)d++;else try{ou(i,w,a,c,t),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:t,reviewReason:A}),d++}catch(S){console.log(R.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),p++}else x==="reject"?(console.log(R.red("REJECT")+" "+R.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:t,reviewReason:A}),g++):(console.log(R.yellow("SKIP")+" "+R.dim(A||x)),l++)}console.log();let f=e.dryRun?"would":"did";console.log(R.dim(` Summary: ${f} approve ${d}, ${f} reject ${g}, ${l} skipped, ${p} errors.`)),e.dryRun&&(d>0||g>0)&&console.log(R.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});yt.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let o=_();if(!o.graph){console.log(R.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=Zn(process.cwd(),o.graph.baseDir);if(!Qp(t)){console.log(R.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-V4WN2VVM.js"),s=new uo({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(R.dim(" "),...a)});console.log(),console.log(R.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(R.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(R.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(R.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});yt.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let o=_();if(!o.graph?.enabled){console.log(R.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let t=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new uo({baseDir:Zn(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map($=>$.id));console.log(),console.log(R.bold(` graph pull \u2190 ${t}`));let d,g,l;try{let $=await fetch(`${t}/graph/schema`,{headers:s});if(!$.ok)throw new Error(`schema HTTP ${$.status}`);d=(await $.json()).schema;let j=await fetch(`${t}/graph/nodes`,{headers:s});if(!j.ok)throw new Error(`nodes HTTP ${j.status}`);g=(await j.json()).nodes||[];let T=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!T.ok)throw new Error(`classifications HTTP ${T.status}`);l=(await T.json()).classifications||[]}catch($){console.log(R.red(` fetch failed: ${$.message}`));return}let p=r.levels.map($=>$.id).join(","),f=d?.levels?.map($=>$.id).join(","),u=p===f;u?console.log(R.dim(` schema matches (${r.levels.length} levels)`)):(console.log(R.yellow(" \u26A0 schema levels differ:")),console.log(R.dim(` local: ${p}`)),console.log(R.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(R.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(d)):console.log(R.yellow(" keeping local schema; node import may fail if levels disagree")));let w=u?r:d,y=new Map;w.levels.forEach(($,C)=>y.set($.id,C));let k=[...g].sort(($,C)=>(y.get($.level)??99)-(y.get(C.level)??99)),b=0,x=0,A=0;for(let $ of k){if(c.has($.id)){x++;continue}if(e.dryRun){b++,c.add($.id);continue}try{i.addNode({...$,createdBy:$.createdBy?`${$.createdBy} (sync)`:`sync:${t}`}),c.add($.id),b++}catch(C){A++,console.log(R.yellow(` skip node ${$.id}: ${C.message?.slice(0,100)}`))}}console.log(R.dim(` nodes: +${b} added \xB7 ${x} already-present \xB7 ${A} failed`));let S=0,v=0;for(let $ of l)if(!(!$.msgHash||!Array.isArray($.path))){if(i.getFingerprint($.msgHash)){v++;continue}if(e.dryRun){S++;continue}i.setFingerprint($.msgHash,{path:$.path,leaf:$.leaf||{}}),S++}console.log(R.dim(` fingerprints: +${S} cached \xB7 ${v} already-present`)),console.log(),e.dryRun?console.log(R.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(R.green(` \u2713 pulled from ${t}`)),console.log()});function Zp(e,o,t){let n={};for(let r of t)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=o.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
470
+ ]`}ee.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=ve(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});ee.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let o=e.dir||W(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-5V444ZFW.js");n=(s().mesh?.peers||[]).map(r=>r.url)}catch{}console.log(),console.log(m.bold(" AgentX Wiki Server")),console.log(),console.log(` ${m.green(">")} http://localhost:${t}`),e.agent?console.log(` Agent: ${m.cyan(e.agent)}`):console.log(` Mode: ${m.cyan("Hub")} (all agents)`),n.length>0&&console.log(` Mesh: ${m.cyan(n.length+" peer(s)")} \u2014 ${n.join(", ")}`),console.log(m.dim(` Wiki: ${o}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),fa(o,t,e.agent,n,e.mode)});ee.command("grade").description("grade absorbed articles with the article-quality seat").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","grade only this agent's wiki").option("--limit <n>","articles to grade","20").option("--min <n>","only show articles scoring below this","3").option("--fields","also check the required fields for each article's type").option("--type <t>","grade only articles of this type (person, place, project, \u2026)").option("--json").action(async e=>{let{articleQualityQuestionsFor:o,articleQualityState:t,gradeArticle:n,ARTICLE_QUALITY_SEAT:s}=await import("./article-quality-44ONVGLN.js"),{fieldQuestions:i,reportFields:r}=await import("./article-fields-L4D2BOGY.js"),{askSeat:a}=await import("./seat-3WT3VJC2.js"),c=ve(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),u=[];e:for(let y of l){let k=c.getAgentWiki(y);for(let b of k.listArticles(y)){if(u.length>=g)break e;let S=k.readArticle(b.path);if(!S||e.type&&S.meta.type!==e.type)continue;let A={...o(S.meta.type),...e.fields?i(S.meta.type):{}},x=await a(s,t({path:b.path,title:S.meta.title,type:S.meta.type,tags:S.meta.tags,body:S.content}),A,{links:[{kind:"article",id:b.path}],features:{agent:y,type:S.meta.type??"?"}});if(!x){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let v=n(x.answers),$=e.fields?r(S.meta.type,x.answers):null;v.completeness>=d&&!($&&!$.fit)||u.push({agent:y,type:S.meta.type??"?",score:v.completeness.toFixed(2),standsAlone:v.standsAlone.toFixed(2),gap:v.biggestGap,...$?{missing:$.missingCritical.join(",")||"-",cov:`${Math.round($.coverage*100)}%`}:{},title:S.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(" no articles below the threshold"));return}u.sort((y,k)=>parseFloat(y.score)-parseFloat(k.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],p=f.map(y=>Math.max(y.length,...u.map(k=>String(k[y]).length))),w=y=>y.map((k,b)=>String(k).padEnd(p[b])).join(" ");console.log(),console.log(m.bold(w(f)));for(let y of u)console.log(w(f.map(k=>y[k])));if(e.fields){let y=u.filter(k=>k.missing!=="-").length;console.log(m.dim(`
471
+ ${u.length} article(s) flagged; ${y} missing a required field.`)),console.log(m.dim(" 'missing' is the actionable column \u2014 a named field beats a score."))}else console.log(m.dim(`
472
+ ${u.length} article(s) below ${d}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});ee.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,o)=>{let{agenticQuery:t}=await import("./query-6EMTLCHQ.js"),n=ve(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=W(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(m.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(m.dim(" Citations:"));for(let c of a.citations){let l=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${l} (${c.path})`))}console.log()}if(o.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(l=>!a.candidates.some(g=>g.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});ee.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,o)=>{let t=ve(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=await t.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});ee.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let o=ve(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=W(process.cwd(),".agentx/graph");if(!Je(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new fo({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,u]of Object.entries(i.entries))r.set(d,u.path);if(r.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,l=0,g=0;for(let d of t){let u=o.getAgentWiki(d),f=u.listArticles(d),p=o.getSharedStore().listEntries(),w=new Map(p.map(S=>[S.id,S])),y=0,k=0,b=0;for(let S of f){if(a++,S.meta.graphPath?.length||!S.meta.sources?.length)continue;y++,c++;let A=new Map;for(let v of S.meta.sources){let $=w.get(v);if(!$)continue;let C=String($.meta?.sender??""),j=s.fingerprint({text:$.content,channel:$.source,sender:C}),T=r.get(j);if(!T?.length)continue;let D=T.join("/"),B=A.get(D);B?B.n++:A.set(D,{path:T,n:1})}if(A.size===0)continue;k++,l++;let x;for(let v of A.values())(!x||v.n>x.n)&&(x=v);x&&(e.dryRun||(u.writeArticle(S.path,{...S.meta,graphPath:x.path},S.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${y} eligible \xB7 ${k} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});ee.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let t=ve(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-5V444ZFW.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(m.red(" No --peer specified and no daemon config found")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(n.length===0){console.log(m.dim(" No mesh peers configured"));return}let s=new Set(t.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(m.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(m.red(` HTTP ${a.status}`));continue}let c=await a.json(),l=c.entries||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${l.length} entries`));let d=0;for(let u of l)s.has(u.id)||(e.dryRun||(t.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${g}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),d++);d>0?console.log(m.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=d;try{let u=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(u.ok){let f=await u.json();for(let p of f.agents||[])p.totalEntries>0&&console.log(m.dim(` ${p.agentId}: ${p.totalEntries} entries, ${p.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});ee.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let o=e.dir||W(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let l=new hs(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),u=l.getAgentEntries(t),f=l.getUnabsorbedEntries(t),p=new Set,w=0,y=new Set;for(let b of d.articles){for(let S of b.tags||[])p.add(S);w+=b.tags?.length||0;for(let S of b.sources||[])y.add(S)}let k=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:yi(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(w/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:y.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,l]of r){let g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(u=>u[c])),d=s.filter(u=>u[c]===g).map(u=>u.label);g>0&&console.log(m.dim(` Best ${l}: ${d.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});ee.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,o)=>{let t=o.dir?W(process.cwd(),o.dir):W(process.cwd(),".agentx/wiki");Je(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?W(process.cwd(),e):W(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=W(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:g}=await import("fs"),d=Je(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${pu(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});ee.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-L4D2BOGY.js"),{askSeat:a}=await import("./seat-3WT3VJC2.js"),{QuestionStore:c}=await import("./questions-4B4KSPXG.js"),l=ve(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let v of d){let $=l.getAgentWiki(v);for(let C of $.listArticles(v)){if(f>=u)break e;let j=$.readArticle(C.path);if(!j||e.type&&j.meta.type!==e.type)continue;f++;let T=await a(r,n({title:j.meta.title,type:j.meta.type,body:j.content}),o(j.meta.type),{links:[{kind:"article",id:C.path}],features:{agent:v,type:j.meta.type??"?"}});if(!T){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let D=t(j.meta.type,T.answers);for(let B of s(D,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:v,path:C.path,subject:j.meta.title,field:B.field,tier:B.tier,question:`${j.meta.title} (${j.meta.type??"?"}) \u2014 ${B.label}?`}),p.push({tier:B.tier,need:B.field,how:B.needsHuman?m.yellow("ask"):B.sources.join("/"),uncertain:B.uncertain?"?":"",agent:v,article:j.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&g.length>0&&(w=new c(tn(e.dir)).add(g)),e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],k=v=>String(v).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(v=>Math.max(v.length,...p.map($=>k($[v]).length))),S=(v,$)=>String(v)+" ".repeat(Math.max(0,b[$]-k(v).length));console.log(),console.log(m.bold(y.map((v,$)=>S(v,$)).join(" ")));for(let v of p)console.log(y.map(($,C)=>S(v[$],C)).join(" "));let A=p.filter(v=>v.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${p.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${A} can be closed by a lookup; ${p.length-A} need a person.`));let x=p[0]?.tier;if(x&&console.log(m.dim(` Start at ${x} \u2014 ${i[x]}.`)),e.ask&&(console.log(m.cyan(` Queued ${w.added} question(s) for a person (${w.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&w.added>0){let{TIER_RANK:v}=await import("./article-fields-L4D2BOGY.js"),$=v[e.notifyTier]??v.pillar,C=g.filter(j=>(v[j.tier??"furniture"]??9)<=$);if(C.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:j}=await import("./config-5V444ZFW.js"),T=j(),D=T?.notifications?.destination;if(!D?.channel||!D?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let B=C.slice(0,10).map(J=>`\u2022 ${J.question}`).join(`
473
+ `),M=C.length>10?`
474
+ \u2026and ${C.length-10} more`:"",H=`${C.length} wiki gap(s) need you (${e.notifyTier}+):
475
+ ${B}${M}
476
+
477
+ agentx wiki questions`,ce=T?.daemon?.port??T?.port??18800;try{let J=await fetch(`http://127.0.0.1:${ce}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:D.channel,chatId:D.chatId,accountId:D.accountId,text:H})});console.log(J.ok?m.cyan(` Pushed ${C.length} question(s) to ${D.channel}.`):m.yellow(` Push failed (${J.status}) \u2014 questions are still queued.`))}catch(J){console.log(m.yellow(` Push failed (${String(J?.message??J).slice(0,80)}) \u2014 questions are still queued.`))}}}}});ee.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-L4D2BOGY.js"),{askSeat:r}=await import("./seat-3WT3VJC2.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-YVEJOM7O.js"),{backfillArticle:u}=await import("./backfill-MTD2B62I.js"),f=ve(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(T=>[T.name.toLowerCase().trim(),T])),S=0,A=0,x=[],v=!1;e:for(let T of p){let D=f.getAgentWiki(T);for(let B of D.listArticles(T)){if(S>=w)break e;if(B.meta.type!=="person")continue;let M=D.readArticle(B.path);if(!M)continue;S++;let H=await r(s,n({title:M.meta.title,type:M.meta.type,body:M.content}),o(M.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:T,op:"backfill"}});if(!H){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=t(M.meta.type,H.answers).missing.filter(N=>i.includes(N));if(J.length===0)continue;let{records:xe,results:we}=await a([{name:M.meta.title,type:"person"}],{sources:y}),P=b.get(M.meta.title.toLowerCase().trim());if(!v){for(let N of l(we,y))console.log(m.yellow(` ! ${N.source} ${N.kind} \u2014 would supply ${N.provides.join(", ")}`)),console.log(m.dim(` ${N.hint}`));v=!0}let Be=c([...P?[{name:P.name,source:"entries",fields:Object.fromEntries(Object.entries(P.fields).map(([N,pe])=>[N,pe.value]))}]:[],...xe]);if(Be.length===0)continue;let{content:be,edits:No}=u(M.content,Be[0],J);if(No.length!==0){for(let N of No)x.push({agent:T,article:M.meta.title.slice(0,32),field:N.field,action:N.replaced?"replace":"add",got:`${N.value.split(";").length} value(s)`});e.apply&&(D.writeArticle(B.path,M.meta,be,T)?A++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(x,null,2));return}if(x.length===0){console.log(m.green(` ${S} person article(s) considered \u2014 nothing to backfill`));return}let $=["agent","article","field","action","got"],C=$.map(T=>Math.max(T.length,...x.map(D=>String(D[T]).length))),j=T=>T.map((D,B)=>String(D).padEnd(C[B])).join(" ");console.log(),console.log(m.bold(j($)));for(let T of x)console.log(j($.map(D=>T[D])));console.log(),e.apply?(console.log(m.green(` ${x.length} field(s) written across ${A} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${x.length} field(s) would be written across ${S} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});ee.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:o}=await import("./questions-4B4KSPXG.js"),{TIER_RANK:t}=await import("./article-fields-L4D2BOGY.js"),n=new o(tn(e.dir)).list(e.status);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(m.green(` no ${e.status} questions`));return}n.sort((s,i)=>(t[s.tier??"furniture"]??9)-(t[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});ee.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,o,t)=>{let{QuestionStore:n}=await import("./questions-4B4KSPXG.js"),{patchIdentityField:s}=await import("./backfill-MTD2B62I.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-L4D2BOGY.js"),r=new n(tn(t.dir));if(t.dismiss){let f=r.resolve(e,"dismissed");console.log(f?m.dim(` dismissed: ${f.question}`):m.red(` no question matching "${e}"`));return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let a=r.resolve(e,"answered",o);if(!a){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${a.question}`)),a.kind!=="field"||!a.field||!a.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[a.field]){console.log(m.dim(` recorded against ${a.path}. "${a.field}" has no fixed slot, so nothing was rewritten.`));return}let l=ve(t.dir,t.mode).getAgentWiki(a.agentId),g=l.readArticle(a.path);if(!g){console.log(m.yellow(` article gone: ${a.path}`));return}let d=s(g.content,a.field,`${o} (answered by operator)`);if(!d){console.log(m.dim(" already present \u2014 nothing to write."));return}let u=l.writeArticle(a.path,g.meta,d.content,a.agentId);console.log(u?m.green(` wrote ${a.field} into ${a.path} (prior version kept)`):m.red(` could not write ${a.path}`))});ee.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:o,entryTriageQuestions:t,triageState:n,triage:s}=await import("./entry-triage-LK34TSQD.js"),{askSeat:i}=await import("./seat-3WT3VJC2.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-JNO7RKX7.js"),{calibrationReport:d}=await import("./calibration-ILS5OI44.js"),f=ve(e.dir,"graph").getSharedStore(),p=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(M=>M.id)),{labeled:y,backlog:k}=r(p,w),b=a(y,M=>M.absorbed,parseInt(e.n)),S={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},A=[],x=0,v=Date.now();if(e.load){let{readFileSync:M}=await import("fs");A.push(...JSON.parse(M(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${k} in backlog) \u2014 grading ${b.length}`));for(let M of e.load?[]:b){let H=await i(o,n(M),t,{features:{source:M.source??"",absorbed:M.absorbed}});if(!H){x++;continue}let ce=H.answers;A.push({entry:M,verdict:s(H.answers,S),citeWorthy:ce.citeWorthy?.noul})}if(A.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:M}=await import("fs");M(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let $=c(A,{minType:S.minTypeConfidence,minWorth:S.minWorth,minDurability:S.minDurability}),C=l(A,"seat","seat"),j=d(C,{minN:50}),T=((Date.now()-v)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:$,calibration:j,failures:x,elapsed:T},null,2));return}let D=M=>`${(M*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${$.n} (${$.positives} kept by absorb, ${$.negatives} passed over)`),console.log(` recall ${D($.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${D($.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${D($.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${$.lostPositives>0?m.yellow(`lost ${$.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in j)||!j.insufficient)&&console.log(` ECE ${j.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),$.lostPositives>0){let M=$.droppedBy;console.log(m.dim(` dropped by: type ${M.type} \xB7 worth ${M.worth} \xB7 durability ${M.durability} (a positive can fail several)`))}let B=$.positiveMeans;if(console.log(m.dim(` positives avg: worth ${B.worth.toFixed(2)} \xB7 durability ${B.durability.toFixed(2)} \xB7 typeConf ${B.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${T}s, ${x} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let M=parseFloat(e.minRecall),{best:H,points:ce}=g(A,{minRecall:M});if(console.log(),console.log(m.bold(` threshold sweep (${ce.length} policies, recall floor ${D(M)})`)),H)console.log(` best: ${H.requireTyped?`typed & type>=${H.minType}`:"type gate OFF"} worth>=${H.minWorth} durability>=${H.minDurability}`),console.log(` recall ${D(H.recall)} \xB7 filtered ${D(H.filtered)} \xB7 precision ${D(H.precision)} \xB7 lost ${H.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${D(M)} recall \u2014 not even keeping everything typed.`));let J=ce.slice().sort((xe,we)=>we.recall-xe.recall)[0];J&&console.log(m.dim(` Best recall available: ${D(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${D(J.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});ee.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,o)=>{let t=W(process.cwd(),e);Je(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?W(process.cwd(),o.dir):W(process.cwd(),".agentx/wiki");Je(n)&&!o.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=W(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function pu(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}nd();import{Command as uu}from"commander";import R from"chalk";import{resolve as Zn}from"path";import{existsSync as fu}from"fs";ge();var $t=new uu().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");$t.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let o=_();if(!o.graph?.enabled){console.log(R.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(R.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(R.red(` agent "${t}" not in config`));return}let n=(e.daemonUrl||o.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new fo({baseDir:Zn(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(R.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(R.bold(` Graph review \u2014 ${r.length} pending`)),console.log(R.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,u=0;for(let p=0;p<r.length;p++){let w=r[p],y=pn(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${R.cyan(w.msgHash.slice(0,8))} ${R.dim(y)} ... `);let k=hu(w,a,c),b=null;try{b=await yu(n,t,k,o.dashboard?.token)}catch(x){u++,console.log(R.red(`ERR ${x.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(R.red("ERR no decision"));continue}let S=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(S==="approve")if(console.log(R.green("APPROVE")+" "+R.dim(A)),e.dryRun)l++;else try{wu(i,w,a,c,t),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:t,reviewReason:A}),l++}catch(x){console.log(R.yellow(` (commit failed, staying pending: ${x.message?.slice(0,100)})`)),u++}else S==="reject"?(console.log(R.red("REJECT")+" "+R.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:t,reviewReason:A}),g++):(console.log(R.yellow("SKIP")+" "+R.dim(A||S)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(R.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${u} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(R.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});$t.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let o=_();if(!o.graph){console.log(R.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=Zn(process.cwd(),o.graph.baseDir);if(!fu(t)){console.log(R.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-V4WN2VVM.js"),s=new fo({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(R.dim(" "),...a)});console.log(),console.log(R.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(R.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(R.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(R.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});$t.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let o=_();if(!o.graph?.enabled){console.log(R.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let t=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new fo({baseDir:Zn(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map($=>$.id));console.log(),console.log(R.bold(` graph pull \u2190 ${t}`));let l,g,d;try{let $=await fetch(`${t}/graph/schema`,{headers:s});if(!$.ok)throw new Error(`schema HTTP ${$.status}`);l=(await $.json()).schema;let j=await fetch(`${t}/graph/nodes`,{headers:s});if(!j.ok)throw new Error(`nodes HTTP ${j.status}`);g=(await j.json()).nodes||[];let T=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!T.ok)throw new Error(`classifications HTTP ${T.status}`);d=(await T.json()).classifications||[]}catch($){console.log(R.red(` fetch failed: ${$.message}`));return}let u=r.levels.map($=>$.id).join(","),f=l?.levels?.map($=>$.id).join(","),p=u===f;p?console.log(R.dim(` schema matches (${r.levels.length} levels)`)):(console.log(R.yellow(" \u26A0 schema levels differ:")),console.log(R.dim(` local: ${u}`)),console.log(R.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(R.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(R.yellow(" keeping local schema; node import may fail if levels disagree")));let w=p?r:l,y=new Map;w.levels.forEach(($,C)=>y.set($.id,C));let k=[...g].sort(($,C)=>(y.get($.level)??99)-(y.get(C.level)??99)),b=0,S=0,A=0;for(let $ of k){if(c.has($.id)){S++;continue}if(e.dryRun){b++,c.add($.id);continue}try{i.addNode({...$,createdBy:$.createdBy?`${$.createdBy} (sync)`:`sync:${t}`}),c.add($.id),b++}catch(C){A++,console.log(R.yellow(` skip node ${$.id}: ${C.message?.slice(0,100)}`))}}console.log(R.dim(` nodes: +${b} added \xB7 ${S} already-present \xB7 ${A} failed`));let x=0,v=0;for(let $ of d)if(!(!$.msgHash||!Array.isArray($.path))){if(i.getFingerprint($.msgHash)){v++;continue}if(e.dryRun){x++;continue}i.setFingerprint($.msgHash,{path:$.path,leaf:$.leaf||{}}),x++}console.log(R.dim(` fingerprints: +${x} cached \xB7 ${v} already-present`)),console.log(),e.dryRun?console.log(R.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(R.green(` \u2713 pulled from ${t}`)),console.log()});function hu(e,o,t){let n={};for(let r of t)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=o.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
451
478
  `),i=JSON.stringify(e.proposedAxes||{},null,2);return["You are reviewing a pending intent classification. Decide whether it is reasonable.","","--- MESSAGE (first 500 chars) ---",(e.preview||"").slice(0,500),`channel: ${e.channel||"?"} \xB7 sender: ${e.sender||"?"}`,"","--- PROPOSED PATH ---",e.path.join(" \u203A "),"","--- PROPOSED AXES (per new node) ---",i,"","--- CURRENT NODES BY LEVEL (first 10 per level) ---",s,"","--- YOUR JOB ---","Decide one of:"," approve \u2014 the path is right and the axes make sense for the message"," reject \u2014 the path is wrong (e.g. the message is NOT about the proposed org/topic, or the axes are bogus)"," skip \u2014 you can't confidently decide; leave it for a human","",'BEFORE you decide, you MAY call `agentx wiki query` (via Bash) to check institutional context \u2014 e.g. "is there an article for this project" or "who is this person". This is optional; don\'t call it for obvious cases.',"","Bias toward reject over approve when uncertain. A wrong approval pollutes the graph; a wrong rejection just keeps the entry pending.","","Return EXACTLY one JSON object on one line, no prose, no fences:",' {"decision":"approve"|"reject"|"skip","reason":"one sentence"}'].join(`
452
- `)}async function eu(e,o,t,n){let s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);let i=new AbortController,r=setTimeout(()=>i.abort(),12e4);try{let a=await fetch(`${e}/task`,{method:"POST",headers:s,body:JSON.stringify({agent:o,message:t,context:{channel:"a2a",sender:"graph-review"}}),signal:i.signal});if(!a.ok)throw new Error(`daemon /task HTTP ${a.status}`);let c=await a.json();if(c?.error)throw new Error(String(c.error));return Ji((c?.content||"").toString())}finally{clearTimeout(r)}}function ou(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function hi(){let e=_();if(!e.graph?.baseDir)return console.log(R.red(" graph.baseDir is not configured")),null;let o=Zn(process.cwd(),e.graph.baseDir);return{store:new uo({baseDir:o}),baseDir:o}}var yi=yt.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");yi.command("next").alias("list").description("what to check next, spread across the confidence range").option("--n <n>","how many","10").option("--strategy <s>","stratified | uncertain","stratified").option("--json").action(async e=>{let o=hi();if(!o)return;let{ReviewStore:t,buildQueue:n}=await import("./review-store-B4YE3EFK.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,new Set(i.keys()),{n:parseInt(e.n),strategy:e.strategy});if(e.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(R.green(" nothing left unreviewed"));return}let a=o.store.loadNodes().nodes;console.log();for(let c of r){let d=typeof c.confidence=="number"?c.confidence.toFixed(2):R.dim("cache");console.log(` ${R.cyan(c.msgHash.slice(0,8))} ${d.padStart(5)} ${R.bold(gn(c.path,a)||c.path.join(" \u203A "))}`),c.preview&&console.log(R.dim(` ${String(c.preview).replace(/\s+/g," ").slice(0,96)}`))}console.log(),console.log(R.dim(` ${r.length} to check (${e.strategy}).`)),console.log(R.dim(" agentx graph label mark <hash> correct|wrong|unsure [--path a/b/c]"))});yi.command("mark <hash> <verdict>").description("record a verdict: correct | wrong | unsure").option("--path <p>","for `wrong`: the path it should have been, slash-separated").option("--note <t>","why, when it is worth remembering").option("--by <who>","reviewer","operator").action(async(e,o,t)=>{if(!["correct","wrong","unsure"].includes(o)){console.log(R.red(" verdict must be correct | wrong | unsure"));return}let n=hi();if(!n)return;let{ReviewStore:s}=await import("./review-store-B4YE3EFK.js"),r=n.store.listAllClassifications().filter(d=>d.msgHash===e||d.msgHash.startsWith(e));if(r.length===0){console.log(R.red(` no classification matching "${e}"`));return}if(r.length>1){console.log(R.red(` "${e}" matches ${r.length} rows \u2014 use more characters`));return}new s(n.baseDir).record({msgHash:r[0].msgHash,verdict:o,correctPath:t.path?String(t.path).split("/").filter(Boolean):void 0,note:t.note,reviewer:t.by});let c=n.store.loadNodes().nodes;console.log(R.green(` ${o}: ${gn(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(R.dim(` should have been: ${t.path}`))});yi.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=hi();if(!o)return;let{ReviewStore:t,labelStats:n}=await import("./review-store-B4YE3EFK.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,i);if(e.json){console.log(JSON.stringify(r,null,2));return}let a=c=>`${(c*100).toFixed(1)}%`;if(console.log(),console.log(` classifications ${r.classifications}`),console.log(` reviewed ${r.reviewed} (${r.correct} correct \xB7 ${r.wrong} wrong \xB7 ${r.unsure} unsure)`),r.correct+r.wrong>0&&console.log(` accuracy ${a(r.accuracy)}`),console.log(` calibratable ${r.calibratable} ${R.dim("reviewed rows that carry a confidence")}`),r.byBin.length>0){console.log(),console.log(R.bold(" reliability \u2014 confidence vs how often it was right"));for(let c of r.byBin){let d=Math.abs(parseFloat(c.bin.split("-")[0])+.05-c.accuracy),g=c.n>=5&&d>.15?R.yellow(" \u2190 miscalibrated"):"";console.log(` ${c.bin} n=${String(c.n).padStart(3)} right ${a(c.accuracy).padStart(6)}${g}`)}}console.log(),r.calibratable<100?console.log(R.dim(` ${100-r.calibratable} more labelled rows before a calibration report means anything.`)):console.log(R.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as au}from"commander";import Y from"chalk";import{Command as zc}from"commander";import se from"chalk";import{existsSync as tu}from"fs";import{resolve as nu}from"path";import su from"better-sqlite3";function iu(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(o){let n=Number(o[1]),s=o[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(se.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function ru(e){let o=nu(process.cwd(),e);return tu(o)||(console.log(se.red(` No db at ${o}`)),process.exit(1)),new su(o,{readonly:!0})}var Yc=new zc().name("extract").description("mine recurring user activity into procedure drafts (dry-run by default)").option("--path <path>","SQLite db path",".agentx/db.sqlite").option("--since <duration>","activity window, e.g. 24h, 7d, or ms epoch","7d").option("--agent <id>","only mine one agent's activity").option("--min-occurrences <n>","recurrences before a pattern becomes a draft",String(Ct)).option("--max <n>","max clusters distilled per run",String(un)).option("--via <agentId>","route the LLM call through a running agent \u2014 uses the agent's own session").option("--model <model>","direct Anthropic API model \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--commit","write drafts and persist recurrence counts",!1).action(async e=>{e.commit&&!e.via&&!e.model&&(console.log(se.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=ru(e.path),t=await yr(o,{since:iu(e.since),agentId:e.agent,sessions:new Ki(process.cwd()),minOccurrences:Number(e.minOccurrences)||Ct,max:Number(e.max)||un,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(se.dim(` ${n}`))});console.log(),console.log(` ${t.episodes} episode(s) \u2192 ${t.clusters} cluster(s), ${t.ready.length} at threshold`);for(let n of t.ready)console.log(` ${se.cyan(n.key)} ${se.bold(`\xD7${n.count}`)} ${se.dim(n.status)}`),n.sampleMessage&&console.log(se.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(se.dim(`
453
- near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(se.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(se.green(` \u2713 draft written: ${n.id}`)+se.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(se.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(se.yellow(` \u26A0 ${n}`));t.dryRun?console.log(se.dim(`
454
- dry run only; pass --commit --via <agentId> to write drafts`)):t.drafted.length&&console.log(se.dim(`
455
- review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),Hc={hourly:"0 * * * *",daily:"0 3 * * *"},Vc=new zc().name("watch").description("set the extraction cadence: registers the cron + config the daemon runs on").option("--hourly","extract every hour").option("--daily","extract daily at 03:00").option("--cron <expr>","custom 5-field cron expression").option("--on-task","also count patterns live after each completed task").option("--off","disable scheduled extraction").option("--via <agentId>","agent that runs the extraction (LLM distillation goes through its session)").option("--min-occurrences <n>","recurrences before a pattern becomes a draft",String(Ct)).option("--timezone <tz>","IANA timezone","Africa/Tunis").option("-c, --config <path>","path to agentx.json").option("--dry-run","print what would be written without writing").action(async e=>{let o=e.off?void 0:e.cron??(e.hourly?Hc.hourly:e.daily?Hc.daily:void 0);!e.off&&!o&&!e.onTask&&(console.log(se.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(se.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let t=Number(e.minOccurrences)||Ct,n={enabled:!e.off,onTaskCompletion:!e.off&&!!e.onTask,minOccurrences:t,via:e.off?void 0:e.via},s=["Run this shell command EXACTLY as written. Do NOT substitute, rewrite, shorten, or fall back to alternative commands. If it exits non-zero, report the verbatim exit code and stderr and STOP.","",`1) cd ${process.cwd()} && node dist/cli.js procedure extract --since 7d --max ${un} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
456
- `),i=await de(a=>{be(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&be(a,"crons.procedure-extract.enabled",!1):o&&be(a,"crons.procedure-extract",{enabled:!0,schedule:o,timezone:e.timezone,agent:e.via,prompt:s,timeout:900,onError:"log"})},{configPath:e.config,dryRun:!!e.dryRun});i.success||(console.log(se.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(se.green(` \u2713 ${r} procedure extraction: off`)):(console.log(se.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(se.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(se.dim(" on-task counting: enabled")),console.log(se.dim(` threshold: ${t} occurrences`))),console.log(se.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var Xe=new au().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");Xe.addCommand(Yc);Xe.addCommand(Vc);Xe.command("list").description("list procedures with their trigger line").option("--drafts","list unreviewed drafts instead",!1).option("--all","list active procedures and drafts",!1).action(e=>{let o=new fo,t=[...e.drafts?[]:o.list(),...e.drafts||e.all?o.listDrafts():[]];if(!t.length){console.log(Y.dim(e.drafts?" no procedure drafts. Mine some with: agentx procedure extract":" no procedures yet. Try: agentx procedure extract \xB7 or: agentx procedure add"));return}console.log();for(let n of t){let s=n.meta.status==="active"?Y.green(n.meta.status):n.meta.status==="draft"?Y.yellow(n.meta.status):Y.dim(n.meta.status);console.log(` ${Y.cyan(n.meta.id)} ${Y.bold(n.meta.title)} ${s}`),console.log(` ${Y.dim("trigger:")} ${n.meta.trigger}`),n.meta.source&&console.log(` ${Y.dim("source:")} ${Y.dim(n.meta.source)}`),n.meta.kpis?.length&&console.log(` ${Y.dim("kpis:")} ${n.meta.kpis.join(", ")}`)}console.log(),console.log(Y.dim(` ${t.length} procedure${t.length===1?"":"s"}.`))});Xe.command("add").description("add a new procedure (non-interactive; pass all fields as flags)").requiredOption("--id <id>","procedure id (lower-kebab, e.g. deploy-peer)").requiredOption("--title <t>","human-readable title").requiredOption("--trigger <t>","when this procedure applies (one sentence)").option("--input <i...>","required input (repeatable)",(e,o=[])=>[...o,e]).option("--expected <t>","expected output / success criterion").option("--kpi <k...>","KPI (repeatable)",(e,o=[])=>[...o,e]).option("--owner <id>","owning agent or person").option("--tag <t...>","tag (repeatable)",(e,o=[])=>[...o,e]).option("--related <r...>","related procedure id or wiki article title (repeatable)",(e,o=[])=>[...o,e]).option("--steps <md>","markdown body \u2014 usually numbered steps").action(e=>{let o=new fo,t=e.steps?String(e.steps):`## Steps
479
+ `)}async function yu(e,o,t,n){let s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);let i=new AbortController,r=setTimeout(()=>i.abort(),12e4);try{let a=await fetch(`${e}/task`,{method:"POST",headers:s,body:JSON.stringify({agent:o,message:t,context:{channel:"a2a",sender:"graph-review"}}),signal:i.signal});if(!a.ok)throw new Error(`daemon /task HTTP ${a.status}`);let c=await a.json();if(c?.error)throw new Error(String(c.error));return Hi((c?.content||"").toString())}finally{clearTimeout(r)}}function wu(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function wi(){let e=_();if(!e.graph?.baseDir)return console.log(R.red(" graph.baseDir is not configured")),null;let o=Zn(process.cwd(),e.graph.baseDir);return{store:new fo({baseDir:o}),baseDir:o}}var bi=$t.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");bi.command("next").alias("list").description("what to check next, spread across the confidence range").option("--n <n>","how many","10").option("--strategy <s>","stratified | uncertain","stratified").option("--json").action(async e=>{let o=wi();if(!o)return;let{ReviewStore:t,buildQueue:n}=await import("./review-store-B4YE3EFK.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,new Set(i.keys()),{n:parseInt(e.n),strategy:e.strategy});if(e.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(R.green(" nothing left unreviewed"));return}let a=o.store.loadNodes().nodes;console.log();for(let c of r){let l=typeof c.confidence=="number"?c.confidence.toFixed(2):R.dim("cache");console.log(` ${R.cyan(c.msgHash.slice(0,8))} ${l.padStart(5)} ${R.bold(pn(c.path,a)||c.path.join(" \u203A "))}`),c.preview&&console.log(R.dim(` ${String(c.preview).replace(/\s+/g," ").slice(0,96)}`))}console.log(),console.log(R.dim(` ${r.length} to check (${e.strategy}).`)),console.log(R.dim(" agentx graph label mark <hash> correct|wrong|unsure [--path a/b/c]"))});bi.command("mark <hash> <verdict>").description("record a verdict: correct | wrong | unsure").option("--path <p>","for `wrong`: the path it should have been, slash-separated").option("--note <t>","why, when it is worth remembering").option("--by <who>","reviewer","operator").action(async(e,o,t)=>{if(!["correct","wrong","unsure"].includes(o)){console.log(R.red(" verdict must be correct | wrong | unsure"));return}let n=wi();if(!n)return;let{ReviewStore:s}=await import("./review-store-B4YE3EFK.js"),r=n.store.listAllClassifications().filter(l=>l.msgHash===e||l.msgHash.startsWith(e));if(r.length===0){console.log(R.red(` no classification matching "${e}"`));return}if(r.length>1){console.log(R.red(` "${e}" matches ${r.length} rows \u2014 use more characters`));return}new s(n.baseDir).record({msgHash:r[0].msgHash,verdict:o,correctPath:t.path?String(t.path).split("/").filter(Boolean):void 0,note:t.note,reviewer:t.by});let c=n.store.loadNodes().nodes;console.log(R.green(` ${o}: ${pn(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(R.dim(` should have been: ${t.path}`))});bi.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=wi();if(!o)return;let{ReviewStore:t,labelStats:n}=await import("./review-store-B4YE3EFK.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,i);if(e.json){console.log(JSON.stringify(r,null,2));return}let a=c=>`${(c*100).toFixed(1)}%`;if(console.log(),console.log(` classifications ${r.classifications}`),console.log(` reviewed ${r.reviewed} (${r.correct} correct \xB7 ${r.wrong} wrong \xB7 ${r.unsure} unsure)`),r.correct+r.wrong>0&&console.log(` accuracy ${a(r.accuracy)}`),console.log(` calibratable ${r.calibratable} ${R.dim("reviewed rows that carry a confidence")}`),r.byBin.length>0){console.log(),console.log(R.bold(" reliability \u2014 confidence vs how often it was right"));for(let c of r.byBin){let l=Math.abs(parseFloat(c.bin.split("-")[0])+.05-c.accuracy),g=c.n>=5&&l>.15?R.yellow(" \u2190 miscalibrated"):"";console.log(` ${c.bin} n=${String(c.n).padStart(3)} right ${a(c.accuracy).padStart(6)}${g}`)}}console.log(),r.calibratable<100?console.log(R.dim(` ${100-r.calibratable} more labelled rows before a calibration report means anything.`)):console.log(R.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as Su}from"commander";import Y from"chalk";import{Command as ll}from"commander";import ie from"chalk";import{existsSync as bu}from"fs";import{resolve as $u}from"path";import ku from"better-sqlite3";function vu(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(o){let n=Number(o[1]),s=o[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(ie.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function xu(e){let o=$u(process.cwd(),e);return bu(o)||(console.log(ie.red(` No db at ${o}`)),process.exit(1)),new ku(o,{readonly:!0})}var dl=new ll().name("extract").description("mine recurring user activity into procedure drafts (dry-run by default)").option("--path <path>","SQLite db path",".agentx/db.sqlite").option("--since <duration>","activity window, e.g. 24h, 7d, or ms epoch","7d").option("--agent <id>","only mine one agent's activity").option("--min-occurrences <n>","recurrences before a pattern becomes a draft",String(Rt)).option("--max <n>","max clusters distilled per run",String(hn)).option("--via <agentId>","route the LLM call through a running agent \u2014 uses the agent's own session").option("--model <model>","direct Anthropic API model \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--commit","write drafts and persist recurrence counts",!1).action(async e=>{e.commit&&!e.via&&!e.model&&(console.log(ie.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=xu(e.path),t=await Tr(o,{since:vu(e.since),agentId:e.agent,sessions:new er(process.cwd()),minOccurrences:Number(e.minOccurrences)||Rt,max:Number(e.max)||hn,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(ie.dim(` ${n}`))});console.log(),console.log(` ${t.episodes} episode(s) \u2192 ${t.clusters} cluster(s), ${t.ready.length} at threshold`);for(let n of t.ready)console.log(` ${ie.cyan(n.key)} ${ie.bold(`\xD7${n.count}`)} ${ie.dim(n.status)}`),n.sampleMessage&&console.log(ie.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(ie.dim(`
480
+ near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(ie.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(ie.green(` \u2713 draft written: ${n.id}`)+ie.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(ie.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(ie.yellow(` \u26A0 ${n}`));t.dryRun?console.log(ie.dim(`
481
+ dry run only; pass --commit --via <agentId> to write drafts`)):t.drafted.length&&console.log(ie.dim(`
482
+ review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),cl={hourly:"0 * * * *",daily:"0 3 * * *"},gl=new ll().name("watch").description("set the extraction cadence: registers the cron + config the daemon runs on").option("--hourly","extract every hour").option("--daily","extract daily at 03:00").option("--cron <expr>","custom 5-field cron expression").option("--on-task","also count patterns live after each completed task").option("--off","disable scheduled extraction").option("--via <agentId>","agent that runs the extraction (LLM distillation goes through its session)").option("--min-occurrences <n>","recurrences before a pattern becomes a draft",String(Rt)).option("--timezone <tz>","IANA timezone (default: this machine's)",Intl.DateTimeFormat().resolvedOptions().timeZone).option("-c, --config <path>","path to agentx.json").option("--dry-run","print what would be written without writing").action(async e=>{let o=e.off?void 0:e.cron??(e.hourly?cl.hourly:e.daily?cl.daily:void 0);!e.off&&!o&&!e.onTask&&(console.log(ie.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(ie.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let t=Number(e.minOccurrences)||Rt,n={enabled:!e.off,onTaskCompletion:!e.off&&!!e.onTask,minOccurrences:t,via:e.off?void 0:e.via},s=["Run this shell command EXACTLY as written. Do NOT substitute, rewrite, shorten, or fall back to alternative commands. If it exits non-zero, report the verbatim exit code and stderr and STOP.","",`1) cd ${process.cwd()} && node dist/cli.js procedure extract --since 7d --max ${hn} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
483
+ `),i=await ue(a=>{Se(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&Se(a,"crons.procedure-extract.enabled",!1):o&&Se(a,"crons.procedure-extract",{enabled:!0,schedule:o,timezone:e.timezone,agent:e.via,prompt:s,timeout:900,onError:"log"})},{configPath:e.config,dryRun:!!e.dryRun});i.success||(console.log(ie.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(ie.green(` \u2713 ${r} procedure extraction: off`)):(console.log(ie.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(ie.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(ie.dim(" on-task counting: enabled")),console.log(ie.dim(` threshold: ${t} occurrences`))),console.log(ie.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var Qe=new Su().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");Qe.addCommand(dl);Qe.addCommand(gl);Qe.command("list").description("list procedures with their trigger line").option("--drafts","list unreviewed drafts instead",!1).option("--all","list active procedures and drafts",!1).action(e=>{let o=new ho,t=[...e.drafts?[]:o.list(),...e.drafts||e.all?o.listDrafts():[]];if(!t.length){console.log(Y.dim(e.drafts?" no procedure drafts. Mine some with: agentx procedure extract":" no procedures yet. Try: agentx procedure extract \xB7 or: agentx procedure add"));return}console.log();for(let n of t){let s=n.meta.status==="active"?Y.green(n.meta.status):n.meta.status==="draft"?Y.yellow(n.meta.status):Y.dim(n.meta.status);console.log(` ${Y.cyan(n.meta.id)} ${Y.bold(n.meta.title)} ${s}`),console.log(` ${Y.dim("trigger:")} ${n.meta.trigger}`),n.meta.source&&console.log(` ${Y.dim("source:")} ${Y.dim(n.meta.source)}`),n.meta.kpis?.length&&console.log(` ${Y.dim("kpis:")} ${n.meta.kpis.join(", ")}`)}console.log(),console.log(Y.dim(` ${t.length} procedure${t.length===1?"":"s"}.`))});Qe.command("add").description("add a new procedure (non-interactive; pass all fields as flags)").requiredOption("--id <id>","procedure id (lower-kebab, e.g. deploy-peer)").requiredOption("--title <t>","human-readable title").requiredOption("--trigger <t>","when this procedure applies (one sentence)").option("--input <i...>","required input (repeatable)",(e,o=[])=>[...o,e]).option("--expected <t>","expected output / success criterion").option("--kpi <k...>","KPI (repeatable)",(e,o=[])=>[...o,e]).option("--owner <id>","owning agent or person").option("--tag <t...>","tag (repeatable)",(e,o=[])=>[...o,e]).option("--related <r...>","related procedure id or wiki article title (repeatable)",(e,o=[])=>[...o,e]).option("--steps <md>","markdown body \u2014 usually numbered steps").action(e=>{let o=new ho,t=e.steps?String(e.steps):`## Steps
457
484
 
458
485
  1. (fill in)
459
486
 
460
487
  ## Notes
461
488
 
462
- `;try{let n=o.add({id:e.id,title:e.title,trigger:e.trigger,inputs:e.input||[],expected:e.expected,kpis:e.kpi||[],owner:e.owner,tags:e.tag||[],related:e.related||[]},t);console.log(Y.green(` \u2713 procedure added: ${n.meta.id}`)),console.log(Y.dim(` ${o.baseDir}/${n.path}`))}catch(n){console.log(Y.red(` add failed: ${n.message}`)),process.exit(1)}});Xe.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new fo,t=o.get(e)??o.getDraft(e);t||(console.log(Y.yellow(` no procedure matches "${e}". Try: agentx procedure list --all`)),process.exit(1)),console.log(),console.log(Y.bold(` ${t.meta.title}`)+Y.dim(` (${t.meta.id}, ${t.meta.status})`)),console.log(Y.dim(` trigger: ${t.meta.trigger}`)),t.meta.inputs?.length&&console.log(Y.dim(` inputs: ${t.meta.inputs.join(", ")}`)),t.meta.expected&&console.log(Y.dim(` expected: ${t.meta.expected}`)),t.meta.kpis?.length&&console.log(Y.dim(` kpis: ${t.meta.kpis.join(", ")}`)),t.meta.owner&&console.log(Y.dim(` owner: ${t.meta.owner}`)),t.meta.source&&console.log(Y.dim(` source: ${t.meta.source}`)),t.meta.related?.length&&console.log(Y.dim(` related: ${t.meta.related.join(", ")}`)),console.log(),console.log(t.body),console.log()});Xe.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new fo;try{let t=o.promoteDraft(e);console.log(Y.green(` \u2713 promoted: ${t.meta.id}`)),console.log(Y.dim(` agents will now follow it when a task matches: "${t.meta.trigger}"`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Xe.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new fo;try{o.rejectDraft(e),console.log(Y.green(` \u2713 rejected: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Xe.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new fo;try{o.deprecate(e),console.log(Y.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Xe.command("match <text>").description("find active procedures matching a task description").option("--limit <n>","max matches","3").option("--min-score <s>","minimum score 0..1","0.2").action((e,o)=>{let t=new fo,n=cr(e,t.list(),{limit:Number(o.limit)||3,minScore:Number(o.minScore)||.2});if(!n.length){console.log(Y.dim(" no matching procedures"));return}for(let s of n)console.log(` ${Y.cyan(s.procedure.meta.id)} ${Y.bold(s.score.toFixed(2))} ${Y.dim(s.reasons.join(", "))}`),console.log(Y.dim(` ${s.procedure.meta.trigger}`))});import{Command as du}from"commander";import E from"chalk";import{resolve as bt,basename as gu}from"path";import{existsSync as wi,readFileSync as bi,writeFileSync as es}from"fs";import rv from"better-sqlite3";import{readFileSync as cu}from"fs";import{resolve as wt,dirname as Kc}from"path";import{fileURLToPath as lu}from"url";var tn=[{name:"linear",title:"Linear",description:"Trigger \u2192 Agent \u2192 End. Smallest workflow that runs."},{name:"branching",title:"Branching",description:"Classify, then route on the result via a branch node."},{name:"extract",title:"Structured extraction",description:"Pull typed fields from free-form text via extract.structured."},{name:"retry",title:"Retry + fallback",description:"Per-node retry policy with a branch fallback path."}];function Xc(e){let o=Kc(lu(import.meta.url)),t=process.argv[1]?Kc(process.argv[1]):"",n=[wt(o,`${e}.yaml`),wt(o,"workflows/templates",`${e}.yaml`),wt(o,"..","workflows/templates",`${e}.yaml`),wt(o,"../..","workflows/templates",`${e}.yaml`),t?wt(t,"workflows/templates",`${e}.yaml`):"",t?wt(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return cu(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
489
+ `;try{let n=o.add({id:e.id,title:e.title,trigger:e.trigger,inputs:e.input||[],expected:e.expected,kpis:e.kpi||[],owner:e.owner,tags:e.tag||[],related:e.related||[]},t);console.log(Y.green(` \u2713 procedure added: ${n.meta.id}`)),console.log(Y.dim(` ${o.baseDir}/${n.path}`))}catch(n){console.log(Y.red(` add failed: ${n.message}`)),process.exit(1)}});Qe.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new ho,t=o.get(e)??o.getDraft(e);t||(console.log(Y.yellow(` no procedure matches "${e}". Try: agentx procedure list --all`)),process.exit(1)),console.log(),console.log(Y.bold(` ${t.meta.title}`)+Y.dim(` (${t.meta.id}, ${t.meta.status})`)),console.log(Y.dim(` trigger: ${t.meta.trigger}`)),t.meta.inputs?.length&&console.log(Y.dim(` inputs: ${t.meta.inputs.join(", ")}`)),t.meta.expected&&console.log(Y.dim(` expected: ${t.meta.expected}`)),t.meta.kpis?.length&&console.log(Y.dim(` kpis: ${t.meta.kpis.join(", ")}`)),t.meta.owner&&console.log(Y.dim(` owner: ${t.meta.owner}`)),t.meta.source&&console.log(Y.dim(` source: ${t.meta.source}`)),t.meta.related?.length&&console.log(Y.dim(` related: ${t.meta.related.join(", ")}`)),console.log(),console.log(t.body),console.log()});Qe.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new ho;try{let t=o.promoteDraft(e);console.log(Y.green(` \u2713 promoted: ${t.meta.id}`)),console.log(Y.dim(` agents will now follow it when a task matches: "${t.meta.trigger}"`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Qe.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new ho;try{o.rejectDraft(e),console.log(Y.green(` \u2713 rejected: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Qe.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new ho;try{o.deprecate(e),console.log(Y.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});Qe.command("match <text>").description("find active procedures matching a task description").option("--limit <n>","max matches","3").option("--min-score <s>","minimum score 0..1","0.2").action((e,o)=>{let t=new ho,n=gr(e,t.list(),{limit:Number(o.limit)||3,minScore:Number(o.minScore)||.2});if(!n.length){console.log(Y.dim(" no matching procedures"));return}for(let s of n)console.log(` ${Y.cyan(s.procedure.meta.id)} ${Y.bold(s.score.toFixed(2))} ${Y.dim(s.reasons.join(", "))}`),console.log(Y.dim(` ${s.procedure.meta.trigger}`))});import{Command as Ou}from"commander";import E from"chalk";import{resolve as vt,basename as Tu}from"path";import{existsSync as $i,readFileSync as ki,writeFileSync as es}from"fs";import Ev from"better-sqlite3";import{readFileSync as Eu}from"fs";import{resolve as kt,dirname as ml}from"path";import{fileURLToPath as Au}from"url";var nn=[{name:"linear",title:"Linear",description:"Trigger \u2192 Agent \u2192 End. Smallest workflow that runs."},{name:"branching",title:"Branching",description:"Classify, then route on the result via a branch node."},{name:"extract",title:"Structured extraction",description:"Pull typed fields from free-form text via extract.structured."},{name:"retry",title:"Retry + fallback",description:"Per-node retry policy with a branch fallback path."}];function pl(e){let o=ml(Au(import.meta.url)),t=process.argv[1]?ml(process.argv[1]):"",n=[kt(o,`${e}.yaml`),kt(o,"workflows/templates",`${e}.yaml`),kt(o,"..","workflows/templates",`${e}.yaml`),kt(o,"../..","workflows/templates",`${e}.yaml`),t?kt(t,"workflows/templates",`${e}.yaml`):"",t?kt(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return Eu(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
463
490
  ${n.join(`
464
- `)}`)}var Fe=new du().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Fe.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new No().list();if(!o.length){console.log(E.dim(" no workflows yet. Add one by writing .agentx/workflows/<id>.json"));return}console.log();for(let t of o){let s=t.nodes.find(a=>a.type.startsWith("trigger."))?.config??{},i=[s.filter?.project,s.filter?.repo,s.filter?.chat].filter(Boolean).join(" / "),r=t.state==="active"?E.green("dispatch: active"):E.yellow(`dispatch: ${t.state}`);console.log(` ${E.cyan(t.id)} ${E.bold(t.title)} ${E.dim(`v${t.version} \xB7`)} ${r} ${E.dim(`\xB7 review: ${t.status}`)}`),console.log(` ${E.dim("trigger:")} ${s.source??"?"}${i?` ${E.dim(i)}`:""}`),console.log(` ${E.dim("nodes: ")} ${t.nodes.length} (${t.nodes.map(a=>a.type).join(", ")})`)}console.log(),console.log(E.dim(` ${o.length} workflow${o.length===1?"":"s"}.`))});Fe.command("show <id>").description("show a single workflow's full definition").option("--format <fmt>","output format: json (default) or yaml","json").action((e,o)=>{let n=new No().get(e);n||(console.log(E.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=o.format.toLowerCase();s==="yaml"||s==="yml"?console.log(Zi(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(E.red(` unknown format "${o.format}" \u2014 use json or yaml`)),process.exit(1))});Fe.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=bt(process.cwd(),e);wi(i)||(console.log(E.red(` file not found: ${i}`)),process.exit(1));try{let r=bi(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?Zo(r,{filePath:e}):JSON.parse(r),d=Qo.safeParse(c);if(!d.success){console.log(E.red(` \u2717 ${i}`));for(let l of d.error.issues)console.log(` ${l.path.join(".")||"<root>"}: ${l.message}`);process.exit(1)}let g=mn(d.data);if(g.length){console.log(E.yellow(` ! ${i} (lint)`));for(let l of g)console.log(` ${l}`);process.exit(1)}console.log(E.green(` \u2713 ${d.data.id} \u2014 valid`))}catch(r){let a=r instanceof pn?r.message:`parse error: ${r?.message??r}`;console.log(E.red(` ${a}`)),process.exit(1)}return}let t=new No().validateAll(),n=0,s=0;for(let i of t)if(i.isValid)console.log(E.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(E.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(E.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});Fe.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${tn.map(e=>e.name).join(" | ")})`,"linear").option("--agent <id>","fill the agent placeholder with this agent id","default").option("--reviewer <id>","fill the reviewer placeholder for human-in-the-loop templates","alice").option("--title <text>","workflow title","").option("--json","scaffold as .json instead of .yaml",!1).option("--force","overwrite an existing workflow with the same id",!1).action((e,o)=>{let t=String(o.template||"linear");tn.some(a=>a.name===t)||(console.log(E.red(` unknown template "${o.template}"`)),console.log(E.dim(` available: ${tn.map(a=>a.name).join(", ")}`)),process.exit(1)),/^[a-z0-9][a-z0-9_-]*$/.test(e)||(console.log(E.red(` workflow id must be lower-kebab (got "${e}")`)),process.exit(1));let n=new No;!o.force&&n.get(e)&&(console.log(E.red(` workflow "${e}" already exists. Use --force to overwrite or pick a new id.`)),process.exit(1));let s=Xc(t);s=s.replace(/__ID__/g,e).replace(/__TITLE__/g,o.title?String(o.title):`${t} workflow ${e}`).replace(/__AGENT__/g,String(o.agent)).replace(/__REVIEWER__/g,String(o.reviewer));try{let a=Zo(s,{filePath:`${e}.yaml`}),c=Qo.safeParse(a);if(!c.success){console.log(E.red(` template "${t}" failed schema validation after substitution:`));for(let d of c.error.issues)console.log(` ${d.path.join(".")||"<root>"}: ${d.message}`);process.exit(1)}}catch(a){console.log(E.red(` template parse failed: ${a?.message??a}`)),process.exit(1)}let i=o.json?"json":"yaml",r=bt(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=Zo(s,{filePath:`${e}.yaml`}),c=Qo.parse(a);es(r,JSON.stringify(c,null,2)+`
465
- `)}else es(r,s);console.log(),console.log(E.green(` \u2713 scaffolded ${r}`)),console.log(E.dim(` template: ${t}`)),console.log(),console.log(E.dim(" Next:")),console.log(E.dim(` 1. edit ${r}`)),console.log(E.dim(` 2. agentx workflow validate ${r}`)),console.log(E.dim(` 3. agentx workflow run ${e} --watch`)),console.log()});Fe.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of tn)console.log(` ${E.cyan(e.name.padEnd(20))} ${E.bold(e.title)}`),console.log(` ${" ".repeat(20)} ${E.dim(e.description)}`);console.log(),console.log(E.dim(" Use: agentx workflow init <id> --template <name>")),console.log()});Fe.command("add <file>").description("import a YAML/JSON workflow file into .agentx/workflows and hot-reload").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--no-reload","skip the POST /reload after writing").action(async(e,o)=>{let t=bt(process.cwd(),e);wi(t)||(console.log(E.red(` file not found: ${t}`)),process.exit(1));let n=bi(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?Zo(n,{filePath:e}):JSON.parse(n)}catch(p){let f=p instanceof pn?p.message:`parse error: ${p?.message??p}`;console.log(E.red(` ${f}`)),process.exit(1)}let r=Qo.safeParse(i);if(!r.success){console.log(E.red(" \u2717 schema:"));for(let p of r.error.issues)console.log(` ${p.path.join(".")||"<root>"}: ${p.message}`);process.exit(1)}let a=mn(r.data);if(a.length){console.log(E.red(" \u2717 lint:"));for(let p of a)console.log(` ${p}`);process.exit(1)}let c=new No,d=s?gu(e).match(/\.yml$/i)?"yml":"yaml":"json",g=bt(c.baseDir,`${r.data.id}.${d}`);if(es(g,s?n:JSON.stringify(r.data,null,2)+`
466
- `),console.log(E.green(` \u2713 ${r.data.id} \u2192 ${g}`)),o.reload===!1){console.log(E.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let l=`${String(o.daemon).replace(/\/$/,"")}/reload`;try{let p=await fetch(l,{method:"POST"});p.ok?console.log(E.dim(" \u2713 daemon reloaded")):console.log(E.dim(` daemon /reload returned ${p.status} \u2014 restart manually if needed`))}catch{console.log(E.dim(` daemon not reachable at ${o.daemon} \u2014 start it or restart to pick up the new workflow`))}});Fe.command("runs [id]").description("list recent runs (optionally filtered to a single workflow)").option("--limit <n>","max runs to show","20").option("--node <id>",'home-node id for this daemon (defaults to WF_NODE_ID env or "local")').action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local",n=new jt({nodeId:t}).list({workflowId:e,limit:Number(o.limit)});if(!n.length){console.log(E.dim(` no runs yet${e?` for "${e}"`:""}.`));return}console.log();for(let s of n){let i=s.history.at(-1),r=s.pending[0]??(s.status==="completed"?"\u2205":"\u2014"),a=s.status==="running"?E.cyan:s.status==="failed"?E.red:E.green;console.log(` ${E.dim(s.id.slice(0,8))} ${E.bold(s.workflowId)} ${a(r)} ${E.dim(s.status)}`),console.log(` ${E.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${E.dim("home: ")} ${s.homeNode}`),console.log(` ${E.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${E.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(E.dim(` ${n.length} run${n.length===1?"":"s"}.`))});Fe.command("run <id-or-file>").description("manually trigger a workflow by id, or load + register + run a YAML/JSON file").option("--input <json>","JSON object merged into the trigger event payload").option("--force","fire even if the trigger isn't `trigger.manual` (uses a synthesized event)",!1).option("--watch","tail per-step traces while the run executes",!1).option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").action(async(e,o)=>{let t={};if(o.input)try{t=JSON.parse(o.input)}catch{console.log(E.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=bt(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&wi(s)){let c=bi(s,"utf-8"),d=/\.(ya?ml)$/i.test(e),g;try{g=d?Zo(c,{filePath:e}):JSON.parse(c)}catch(b){let x=b instanceof pn?b.message:`parse error: ${b?.message??b}`;console.log(E.red(` ${x}`)),process.exit(1)}let l=Qo.safeParse(g);if(!l.success){console.log(E.red(" \u2717 schema:"));for(let b of l.error.issues)console.log(` ${b.path.join(".")||"<root>"}: ${b.message}`);process.exit(1)}let p=mn(l.data);if(p.length){console.log(E.red(" \u2717 lint:"));for(let b of p)console.log(` ${b}`);process.exit(1)}let f=new No,u=l.data.id.startsWith("_adhoc-")?l.data.id:`_adhoc-${l.data.id}-${Date.now().toString(36)}`,w=d?"yaml":"json",y=bt(f.baseDir,`${u}.${w}`),k=d?c.replace(new RegExp(`^id:\\s*${l.data.id}\\b`,"m"),`id: ${u}`):JSON.stringify({...l.data,id:u},null,2)+`
467
- `;es(y,k),n=u,console.log(E.dim(` ad-hoc registered as "${u}" \u2192 ${y}`));try{await fetch(`${String(o.daemon).replace(/\/$/,"")}/reload`,{method:"POST"})}catch{}}let r=`${String(o.daemon).replace(/\/$/,"")}/workflows/${encodeURIComponent(n)}/run`,a;try{let c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:t,force:!!o.force})});if(!c.ok){let g=await c.text();console.log(E.red(` run failed (${c.status}): ${g.slice(0,300)}`)),c.status===409&&console.log(E.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let d=await c.json();a=d.runId,console.log(E.green(` \u2713 run started: ${a||"(unknown id)"}${d.force?E.dim(` (forced, source=${d.source})`):""}`))}catch(c){console.log(E.red(` request to daemon failed: ${c.message}`)),process.exit(1)}o.watch&&a&&await mu({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function mu(e){let o=new Set,t=new Map,n=Date.now(),s=15*60*1e3;for(;Date.now()-n<s;){let i=[];try{let r=await fetch(`${e.daemonUrl}/traces?workflowRunId=${encodeURIComponent(e.runId)}&limit=200`);r.ok&&(i=(await r.json()).traces||[])}catch{}for(let r of i){if(!r.taskId||o.has(r.taskId)||(o.add(r.taskId),t.set(r.taskId,r),e.quiet))continue;let a=r.status||"running",c=a==="ok"?E.green:a==="error"?E.red:E.cyan,d=r.totalTokens!=null?E.dim(`${r.totalTokens}t`):"",g=r.durationMs!=null?E.dim(`${r.durationMs}ms`):"";console.log(` ${c(a.padEnd(5))} ${E.bold(r.nodeId||r.label||"(node)")} ${d} ${g}`),r.error&&console.log(` ${E.red(String(r.error).slice(0,200))}`)}try{let r=await fetch(`${e.daemonUrl}/api/workflows/runs/${encodeURIComponent(e.runId)}`);if(r.ok){let c=(await r.json()).run;if(c&&c.status&&c.status!=="running")return e.quiet||(console.log(),console.log(` ${E.dim("run finished:")} ${c.status}`),console.log(E.dim(` full traces: ${e.daemonUrl}/traces?workflowRunId=${e.runId}`))),Array.from(t.values())}}catch{}await new Promise(r=>setTimeout(r,500))}return e.quiet||console.log(E.yellow(" watch timed out after 15min. Run is still active \u2014 check /traces")),Array.from(t.values())}Fe.command("trace <id>").description("pretty-print a task's execution trace (taskId or runId)").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output",!1).action(async(e,o)=>{let t=String(o.daemon).replace(/\/$/,"");try{let i=await fetch(`${t}/traces/${encodeURIComponent(e)}`);if(i.ok){let r=await i.json();if(o.json){console.log(JSON.stringify(r,null,2));return}Qc(r);return}}catch{}let n;try{let i=await fetch(`${t}/traces?workflowRunId=${encodeURIComponent(e)}&limit=200`);i.ok||(console.log(E.red(` /traces returned ${i.status}`)),process.exit(1)),n=await i.json()}catch(i){console.log(E.red(` daemon request failed: ${i.message}`)),process.exit(1)}let s=n.traces||[];if(s.length===0){console.log(E.yellow(` no traces for "${e}"`)),console.log(E.dim(" (sqlite must be opened \u2014 check 'agentx doctor' if the daemon logged 'sqlite: not opened')"));return}if(o.json){console.log(JSON.stringify(s,null,2));return}console.log(),console.log(E.bold(` ${s.length} step${s.length===1?"":"s"} for run ${e}:`)),console.log();for(let i of s)Qc(i)});function Qc(e){let o=e.status||"ok",t=o==="ok"?E.green:o==="error"?E.red:E.cyan,n=e.totalTokens!=null?`${e.totalTokens}t`:"\u2014",s=e.durationMs!=null?`${e.durationMs}ms`:"\u2014",i=e.model||"\u2014";console.log(` ${t(o.padEnd(5))} ${E.bold(String(e.nodeId||e.label||"(node)"))}`),console.log(` ${E.dim("taskId:")} ${e.taskId||"\u2014"}`),console.log(` ${E.dim("model:")} ${i}`),console.log(` ${E.dim("tokens:")} ${n} ${E.dim("duration:")} ${s}`),e.error&&console.log(` ${E.dim("error:")} ${E.red(String(e.error).slice(0,300))}`),console.log()}Fe.command("pause <runId>").description("pause an active run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new jt({nodeId:t}).setStatus(e,"paused")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 paused ${e}`))});Fe.command("resume <runId>").description("resume a paused run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new jt({nodeId:t}).setStatus(e,"running")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 resumed ${e}`))});Fe.command("cancel <runId>").description("cancel an active run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new jt({nodeId:t}).setStatus(e,"canceled")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 canceled ${e}`))});import{Command as Zc}from"commander";import oe from"chalk";import Ho from"prompts";import{readFileSync as pu,existsSync as uu}from"fs";import{resolve as fu}from"path";var nn=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],$i=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),el={gitlab:"GitLab \u2192 Settings \u2192 Webhooks (tick Push/Issue/Pipeline events)",github:"GitHub \u2192 Repo Settings \u2192 Webhooks",sentry:"Sentry \u2192 Project Settings \u2192 Alerts \u2192 Webhooks",stripe:"Stripe Dashboard \u2192 Developers \u2192 Webhooks",vercel:"Vercel \u2192 Project Settings \u2192 Webhooks",odoo:"Odoo \u2192 Settings \u2192 Technical \u2192 Automation \u2192 Webhooks (or your installed `webhook` module)",hubspot:"HubSpot \u2192 Settings \u2192 Integrations \u2192 Private Apps \u2192 Webhooks subscription",discord:"Discord channel \u2192 Integrations \u2192 Webhooks (inbound-only, no on:* events)",slack:"Slack Outgoing Webhooks / Events API (inbound-only, no on:* events)",custom:"Any service that POSTs JSON \u2014 Linear, Calendly, Notion, etc. (inbound-only)"};function ol(){let e=fu(process.cwd(),"agentx.json");if(!uu(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(pu(e,"utf-8"))}function hu(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?oe.yellow("\u26A0 no signing secret"):oe.green("\u2713 active"):oe.dim("disabled")}function yu(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=$i.has(e.source)?oe.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${oe.cyan(e.id)} ${hu(e)}`),console.log(` ${oe.dim(e.source)} \u2192 ${oe.bold(e.agentId)}${n}`),console.log(` POST ${oe.dim(t)}`),e.secretEnv&&console.log(` secret: ${oe.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${oe.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${oe.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${oe.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var mo=new Zc().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");mo.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=ol(),t=Array.isArray(o.webhooks)?o.webhooks:[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(oe.dim(`
491
+ `)}`)}var qe=new Ou().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");qe.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new Ro().list();if(!o.length){console.log(E.dim(" no workflows yet. Add one by writing .agentx/workflows/<id>.json"));return}console.log();for(let t of o){let s=t.nodes.find(a=>a.type.startsWith("trigger."))?.config??{},i=[s.filter?.project,s.filter?.repo,s.filter?.chat].filter(Boolean).join(" / "),r=t.state==="active"?E.green("dispatch: active"):E.yellow(`dispatch: ${t.state}`);console.log(` ${E.cyan(t.id)} ${E.bold(t.title)} ${E.dim(`v${t.version} \xB7`)} ${r} ${E.dim(`\xB7 review: ${t.status}`)}`),console.log(` ${E.dim("trigger:")} ${s.source??"?"}${i?` ${E.dim(i)}`:""}`),console.log(` ${E.dim("nodes: ")} ${t.nodes.length} (${t.nodes.map(a=>a.type).join(", ")})`)}console.log(),console.log(E.dim(` ${o.length} workflow${o.length===1?"":"s"}.`))});qe.command("show <id>").description("show a single workflow's full definition").option("--format <fmt>","output format: json (default) or yaml","json").action((e,o)=>{let n=new Ro().get(e);n||(console.log(E.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=o.format.toLowerCase();s==="yaml"||s==="yml"?console.log(nr(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(E.red(` unknown format "${o.format}" \u2014 use json or yaml`)),process.exit(1))});qe.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=vt(process.cwd(),e);$i(i)||(console.log(E.red(` file not found: ${i}`)),process.exit(1));try{let r=ki(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?ot(r,{filePath:e}):JSON.parse(r),l=et.safeParse(c);if(!l.success){console.log(E.red(` \u2717 ${i}`));for(let d of l.error.issues)console.log(` ${d.path.join(".")||"<root>"}: ${d.message}`);process.exit(1)}let g=un(l.data);if(g.length){console.log(E.yellow(` ! ${i} (lint)`));for(let d of g)console.log(` ${d}`);process.exit(1)}console.log(E.green(` \u2713 ${l.data.id} \u2014 valid`))}catch(r){let a=r instanceof fn?r.message:`parse error: ${r?.message??r}`;console.log(E.red(` ${a}`)),process.exit(1)}return}let t=new Ro().validateAll(),n=0,s=0;for(let i of t)if(i.isValid)console.log(E.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(E.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(E.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});qe.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${nn.map(e=>e.name).join(" | ")})`,"linear").option("--agent <id>","fill the agent placeholder with this agent id","default").option("--reviewer <id>","fill the reviewer placeholder for human-in-the-loop templates","alice").option("--title <text>","workflow title","").option("--json","scaffold as .json instead of .yaml",!1).option("--force","overwrite an existing workflow with the same id",!1).action((e,o)=>{let t=String(o.template||"linear");nn.some(a=>a.name===t)||(console.log(E.red(` unknown template "${o.template}"`)),console.log(E.dim(` available: ${nn.map(a=>a.name).join(", ")}`)),process.exit(1)),/^[a-z0-9][a-z0-9_-]*$/.test(e)||(console.log(E.red(` workflow id must be lower-kebab (got "${e}")`)),process.exit(1));let n=new Ro;!o.force&&n.get(e)&&(console.log(E.red(` workflow "${e}" already exists. Use --force to overwrite or pick a new id.`)),process.exit(1));let s=pl(t);s=s.replace(/__ID__/g,e).replace(/__TITLE__/g,o.title?String(o.title):`${t} workflow ${e}`).replace(/__AGENT__/g,String(o.agent)).replace(/__REVIEWER__/g,String(o.reviewer));try{let a=ot(s,{filePath:`${e}.yaml`}),c=et.safeParse(a);if(!c.success){console.log(E.red(` template "${t}" failed schema validation after substitution:`));for(let l of c.error.issues)console.log(` ${l.path.join(".")||"<root>"}: ${l.message}`);process.exit(1)}}catch(a){console.log(E.red(` template parse failed: ${a?.message??a}`)),process.exit(1)}let i=o.json?"json":"yaml",r=vt(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=ot(s,{filePath:`${e}.yaml`}),c=et.parse(a);es(r,JSON.stringify(c,null,2)+`
492
+ `)}else es(r,s);console.log(),console.log(E.green(` \u2713 scaffolded ${r}`)),console.log(E.dim(` template: ${t}`)),console.log(),console.log(E.dim(" Next:")),console.log(E.dim(` 1. edit ${r}`)),console.log(E.dim(` 2. agentx workflow validate ${r}`)),console.log(E.dim(` 3. agentx workflow run ${e} --watch`)),console.log()});qe.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of nn)console.log(` ${E.cyan(e.name.padEnd(20))} ${E.bold(e.title)}`),console.log(` ${" ".repeat(20)} ${E.dim(e.description)}`);console.log(),console.log(E.dim(" Use: agentx workflow init <id> --template <name>")),console.log()});qe.command("add <file>").description("import a YAML/JSON workflow file into .agentx/workflows and hot-reload").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--no-reload","skip the POST /reload after writing").action(async(e,o)=>{let t=vt(process.cwd(),e);$i(t)||(console.log(E.red(` file not found: ${t}`)),process.exit(1));let n=ki(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?ot(n,{filePath:e}):JSON.parse(n)}catch(u){let f=u instanceof fn?u.message:`parse error: ${u?.message??u}`;console.log(E.red(` ${f}`)),process.exit(1)}let r=et.safeParse(i);if(!r.success){console.log(E.red(" \u2717 schema:"));for(let u of r.error.issues)console.log(` ${u.path.join(".")||"<root>"}: ${u.message}`);process.exit(1)}let a=un(r.data);if(a.length){console.log(E.red(" \u2717 lint:"));for(let u of a)console.log(` ${u}`);process.exit(1)}let c=new Ro,l=s?Tu(e).match(/\.yml$/i)?"yml":"yaml":"json",g=vt(c.baseDir,`${r.data.id}.${l}`);if(es(g,s?n:JSON.stringify(r.data,null,2)+`
493
+ `),console.log(E.green(` \u2713 ${r.data.id} \u2192 ${g}`)),o.reload===!1){console.log(E.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let d=`${String(o.daemon).replace(/\/$/,"")}/reload`;try{let u=await fetch(d,{method:"POST"});u.ok?console.log(E.dim(" \u2713 daemon reloaded")):console.log(E.dim(` daemon /reload returned ${u.status} \u2014 restart manually if needed`))}catch{console.log(E.dim(` daemon not reachable at ${o.daemon} \u2014 start it or restart to pick up the new workflow`))}});qe.command("runs [id]").description("list recent runs (optionally filtered to a single workflow)").option("--limit <n>","max runs to show","20").option("--node <id>",'home-node id for this daemon (defaults to WF_NODE_ID env or "local")').action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local",n=new Nt({nodeId:t}).list({workflowId:e,limit:Number(o.limit)});if(!n.length){console.log(E.dim(` no runs yet${e?` for "${e}"`:""}.`));return}console.log();for(let s of n){let i=s.history.at(-1),r=s.pending[0]??(s.status==="completed"?"\u2205":"\u2014"),a=s.status==="running"?E.cyan:s.status==="failed"?E.red:E.green;console.log(` ${E.dim(s.id.slice(0,8))} ${E.bold(s.workflowId)} ${a(r)} ${E.dim(s.status)}`),console.log(` ${E.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${E.dim("home: ")} ${s.homeNode}`),console.log(` ${E.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${E.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(E.dim(` ${n.length} run${n.length===1?"":"s"}.`))});qe.command("run <id-or-file>").description("manually trigger a workflow by id, or load + register + run a YAML/JSON file").option("--input <json>","JSON object merged into the trigger event payload").option("--force","fire even if the trigger isn't `trigger.manual` (uses a synthesized event)",!1).option("--watch","tail per-step traces while the run executes",!1).option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").action(async(e,o)=>{let t={};if(o.input)try{t=JSON.parse(o.input)}catch{console.log(E.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=vt(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&$i(s)){let c=ki(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),g;try{g=l?ot(c,{filePath:e}):JSON.parse(c)}catch(b){let S=b instanceof fn?b.message:`parse error: ${b?.message??b}`;console.log(E.red(` ${S}`)),process.exit(1)}let d=et.safeParse(g);if(!d.success){console.log(E.red(" \u2717 schema:"));for(let b of d.error.issues)console.log(` ${b.path.join(".")||"<root>"}: ${b.message}`);process.exit(1)}let u=un(d.data);if(u.length){console.log(E.red(" \u2717 lint:"));for(let b of u)console.log(` ${b}`);process.exit(1)}let f=new Ro,p=d.data.id.startsWith("_adhoc-")?d.data.id:`_adhoc-${d.data.id}-${Date.now().toString(36)}`,w=l?"yaml":"json",y=vt(f.baseDir,`${p}.${w}`),k=l?c.replace(new RegExp(`^id:\\s*${d.data.id}\\b`,"m"),`id: ${p}`):JSON.stringify({...d.data,id:p},null,2)+`
494
+ `;es(y,k),n=p,console.log(E.dim(` ad-hoc registered as "${p}" \u2192 ${y}`));try{await fetch(`${String(o.daemon).replace(/\/$/,"")}/reload`,{method:"POST"})}catch{}}let r=`${String(o.daemon).replace(/\/$/,"")}/workflows/${encodeURIComponent(n)}/run`,a;try{let c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:t,force:!!o.force})});if(!c.ok){let g=await c.text();console.log(E.red(` run failed (${c.status}): ${g.slice(0,300)}`)),c.status===409&&console.log(E.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let l=await c.json();a=l.runId,console.log(E.green(` \u2713 run started: ${a||"(unknown id)"}${l.force?E.dim(` (forced, source=${l.source})`):""}`))}catch(c){console.log(E.red(` request to daemon failed: ${c.message}`)),process.exit(1)}o.watch&&a&&await Iu({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function Iu(e){let o=new Set,t=new Map,n=Date.now(),s=15*60*1e3;for(;Date.now()-n<s;){let i=[];try{let r=await fetch(`${e.daemonUrl}/traces?workflowRunId=${encodeURIComponent(e.runId)}&limit=200`);r.ok&&(i=(await r.json()).traces||[])}catch{}for(let r of i){if(!r.taskId||o.has(r.taskId)||(o.add(r.taskId),t.set(r.taskId,r),e.quiet))continue;let a=r.status||"running",c=a==="ok"?E.green:a==="error"?E.red:E.cyan,l=r.totalTokens!=null?E.dim(`${r.totalTokens}t`):"",g=r.durationMs!=null?E.dim(`${r.durationMs}ms`):"";console.log(` ${c(a.padEnd(5))} ${E.bold(r.nodeId||r.label||"(node)")} ${l} ${g}`),r.error&&console.log(` ${E.red(String(r.error).slice(0,200))}`)}try{let r=await fetch(`${e.daemonUrl}/api/workflows/runs/${encodeURIComponent(e.runId)}`);if(r.ok){let c=(await r.json()).run;if(c&&c.status&&c.status!=="running")return e.quiet||(console.log(),console.log(` ${E.dim("run finished:")} ${c.status}`),console.log(E.dim(` full traces: ${e.daemonUrl}/traces?workflowRunId=${e.runId}`))),Array.from(t.values())}}catch{}await new Promise(r=>setTimeout(r,500))}return e.quiet||console.log(E.yellow(" watch timed out after 15min. Run is still active \u2014 check /traces")),Array.from(t.values())}qe.command("trace <id>").description("pretty-print a task's execution trace (taskId or runId)").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output",!1).action(async(e,o)=>{let t=String(o.daemon).replace(/\/$/,"");try{let i=await fetch(`${t}/traces/${encodeURIComponent(e)}`);if(i.ok){let r=await i.json();if(o.json){console.log(JSON.stringify(r,null,2));return}ul(r);return}}catch{}let n;try{let i=await fetch(`${t}/traces?workflowRunId=${encodeURIComponent(e)}&limit=200`);i.ok||(console.log(E.red(` /traces returned ${i.status}`)),process.exit(1)),n=await i.json()}catch(i){console.log(E.red(` daemon request failed: ${i.message}`)),process.exit(1)}let s=n.traces||[];if(s.length===0){console.log(E.yellow(` no traces for "${e}"`)),console.log(E.dim(" (sqlite must be opened \u2014 check 'agentx doctor' if the daemon logged 'sqlite: not opened')"));return}if(o.json){console.log(JSON.stringify(s,null,2));return}console.log(),console.log(E.bold(` ${s.length} step${s.length===1?"":"s"} for run ${e}:`)),console.log();for(let i of s)ul(i)});function ul(e){let o=e.status||"ok",t=o==="ok"?E.green:o==="error"?E.red:E.cyan,n=e.totalTokens!=null?`${e.totalTokens}t`:"\u2014",s=e.durationMs!=null?`${e.durationMs}ms`:"\u2014",i=e.model||"\u2014";console.log(` ${t(o.padEnd(5))} ${E.bold(String(e.nodeId||e.label||"(node)"))}`),console.log(` ${E.dim("taskId:")} ${e.taskId||"\u2014"}`),console.log(` ${E.dim("model:")} ${i}`),console.log(` ${E.dim("tokens:")} ${n} ${E.dim("duration:")} ${s}`),e.error&&console.log(` ${E.dim("error:")} ${E.red(String(e.error).slice(0,300))}`),console.log()}qe.command("pause <runId>").description("pause an active run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new Nt({nodeId:t}).setStatus(e,"paused")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 paused ${e}`))});qe.command("resume <runId>").description("resume a paused run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new Nt({nodeId:t}).setStatus(e,"running")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 resumed ${e}`))});qe.command("cancel <runId>").description("cancel an active run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new Nt({nodeId:t}).setStatus(e,"canceled")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 canceled ${e}`))});import{Command as fl}from"commander";import oe from"chalk";import Yo from"prompts";import{readFileSync as ju,existsSync as Cu}from"fs";import{resolve as Nu}from"path";var sn=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],vi=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),hl={gitlab:"GitLab \u2192 Settings \u2192 Webhooks (tick Push/Issue/Pipeline events)",github:"GitHub \u2192 Repo Settings \u2192 Webhooks",sentry:"Sentry \u2192 Project Settings \u2192 Alerts \u2192 Webhooks",stripe:"Stripe Dashboard \u2192 Developers \u2192 Webhooks",vercel:"Vercel \u2192 Project Settings \u2192 Webhooks",odoo:"Odoo \u2192 Settings \u2192 Technical \u2192 Automation \u2192 Webhooks (or your installed `webhook` module)",hubspot:"HubSpot \u2192 Settings \u2192 Integrations \u2192 Private Apps \u2192 Webhooks subscription",discord:"Discord channel \u2192 Integrations \u2192 Webhooks (inbound-only, no on:* events)",slack:"Slack Outgoing Webhooks / Events API (inbound-only, no on:* events)",custom:"Any service that POSTs JSON \u2014 Linear, Calendly, Notion, etc. (inbound-only)"};function yl(){let e=Nu(process.cwd(),"agentx.json");if(!Cu(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(ju(e,"utf-8"))}function Ru(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?oe.yellow("\u26A0 no signing secret"):oe.green("\u2713 active"):oe.dim("disabled")}function Du(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=vi.has(e.source)?oe.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${oe.cyan(e.id)} ${Ru(e)}`),console.log(` ${oe.dim(e.source)} \u2192 ${oe.bold(e.agentId)}${n}`),console.log(` POST ${oe.dim(t)}`),e.secretEnv&&console.log(` secret: ${oe.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${oe.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${oe.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${oe.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var po=new fl().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");po.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=yl(),t=Array.isArray(o.webhooks)?o.webhooks:[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(oe.dim(`
468
495
  No webhooks registered. Add one with: agentx webhook add
469
- `));return}console.log();for(let n of t)yu(n)});mo.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${nn.join(", ")}`).option("--agent <agentId>","agent that receives the webhook").option("--secret-env <name>","env var holding the signing secret (recommended)").option("--description <text>","free-text description").option("--node <peer>","forward to a mesh peer (skips local agent check; validates against mesh.peers)").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=ol(),n=Object.keys(t.agents||{}),s=(t.mesh?.peers||[]).map(f=>f.name).filter(Boolean),i=String(o.node||"").trim();if(!n.length&&!i)throw new Error("No local agents configured. Add one with: agentx agent add \u2014 or use --node <peer> to forward to a mesh peer.");let r=(e||"").trim(),a=String(o.source||"").trim(),c=String(o.agent||"").trim(),d=String(o.secretEnv||"").trim(),g=String(o.description||"").trim(),l=o.prompt!==!1;if(!r&&l&&(r=((await Ho({type:"text",name:"id",message:"Webhook id (lowercase, e.g. globex-gitlab)",validate:u=>/^[a-z0-9][a-z0-9_-]*$/.test(u)||"Use lowercase letters, digits, -, _"})).id||"").trim()),!r)throw new Error("Webhook id is required.");if(!/^[a-z0-9][a-z0-9_-]*$/.test(r))throw new Error("Webhook id must be lowercase (letters, digits, -, _).");if(!a&&l&&(a=(await Ho({type:"select",name:"source",message:"Source",choices:nn.map(u=>({title:`${u}${$i.has(u)?" \u2713 wired":""}`,value:u,description:el[u]}))})).source),!nn.includes(a))throw new Error(`Source must be one of: ${nn.join(", ")}`);if(!c&&l&&(i?c=((await Ho({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await Ho({type:"select",name:"agentId",message:"Agent",choices:n.map(u=>({title:u,value:u}))})).agentId),!c)throw new Error("Agent is required.");if(i){if(!s.includes(i))throw new Error(`Mesh peer "${i}" not found in mesh.peers. Add the peer first or omit --node.`)}else if(!t.agents?.[c])throw new Error(`Unknown agent "${c}". Add it locally, or use --node <peer> to forward to a mesh peer.`);!d&&l&&a!=="custom"&&(d=((await Ho({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&l&&(g=((await Ho({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let p=await de(f=>{if(f.webhooks=Array.isArray(f.webhooks)?f.webhooks:[],f.webhooks.find(w=>w.id===r))throw new Error(`Webhook "${r}" already exists.`);let u={id:r,source:a,agentId:c,enabled:!0};d&&(u.secretEnv=d),g&&(u.description=g),i&&(u.node=i),f.webhooks.push(u)});if(!p.success)throw new Error(p.error);console.log(oe.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),p.reloaded&&console.log(oe.dim(" daemon hot-reloaded")),!d&&a!=="custom"&&console.log(oe.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});mo.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await Ho({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await de(n=>{let s=(n.webhooks||[]).length;if(n.webhooks=(n.webhooks||[]).filter(i=>i.id!==e),n.webhooks.length===s)throw new Error(`Webhook "${e}" not found.`)});if(!t.success)throw new Error(t.error);console.log(oe.green(`\u2713 removed webhook "${e}"`))});function tl(e){return async o=>{let t=await de(n=>{let s=(n.webhooks||[]).find(i=>i.id===o);if(!s)throw new Error(`Webhook "${o}" not found.`);s.enabled=e});if(!t.success)throw new Error(t.error);console.log(oe.green(`\u2713 ${e?"enabled":"disabled"} webhook "${o}"`))}}mo.command("enable <id>").description("enable a webhook entry").action(tl(!0));mo.command("disable <id>").description("disable a webhook entry").action(tl(!1));var os=new Zc().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");os.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await de(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);i.triggers=i.triggers&&typeof i.triggers=="object"?i.triggers:{},i.triggers[o]=t});if(!n.success)throw new Error(n.error);console.log(oe.green(`\u2713 ${e}: ${o} \u2192 ${t}`))});os.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await de(n=>{let s=(n.webhooks||[]).find(i=>i.id===e);if(!s)throw new Error(`Webhook "${e}" not found.`);s.triggers&&typeof s.triggers=="object"&&delete s.triggers[o]});if(!t.success)throw new Error(t.error);console.log(oe.green(`\u2713 removed trigger ${o} from "${e}"`))});os.command("default <id> <workflowId>").description("set the default workflow when no event-type matches (use '-' to clear)").action(async(e,o)=>{let t=o==="-"||o==="",n=await de(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);t?delete i.defaultWorkflow:i.defaultWorkflow=o});if(!n.success)throw new Error(n.error);console.log(oe.green(`\u2713 ${e}: defaultWorkflow ${t?"cleared":`\u2192 ${o}`}`))});mo.addCommand(os);mo.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=nn.map(t=>({source:t,wired:$i.has(t),hint:el[t]}));if(e.json){console.log(JSON.stringify(o,null,2));return}console.log();for(let t of o){let n=t.wired?oe.green("\u2713 wired"):oe.dim("inbound-only");console.log(` ${oe.cyan(t.source.padEnd(8))} ${n} ${oe.dim(t.hint)}`)}console.log(),console.log(oe.dim(" Wired sources emit on:<source>-* hook events that workflows can subscribe to via trigger.hook.")),console.log(oe.dim(" Use 'custom' for any service not in the list (Odoo, HubSpot, Linear, Calendly, etc.).")),console.log()});import{Command as wu}from"commander";import te from"chalk";pe();function $t(e){let{summary:o,backupPath:t}=nt(n=>e(n));console.log(te.green(`
496
+ `));return}console.log();for(let n of t)Du(n)});po.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${sn.join(", ")}`).option("--agent <agentId>","agent that receives the webhook").option("--secret-env <name>","env var holding the signing secret (recommended)").option("--description <text>","free-text description").option("--node <peer>","forward to a mesh peer (skips local agent check; validates against mesh.peers)").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=yl(),n=Object.keys(t.agents||{}),s=(t.mesh?.peers||[]).map(f=>f.name).filter(Boolean),i=String(o.node||"").trim();if(!n.length&&!i)throw new Error("No local agents configured. Add one with: agentx agent add \u2014 or use --node <peer> to forward to a mesh peer.");let r=(e||"").trim(),a=String(o.source||"").trim(),c=String(o.agent||"").trim(),l=String(o.secretEnv||"").trim(),g=String(o.description||"").trim(),d=o.prompt!==!1;if(!r&&d&&(r=((await Yo({type:"text",name:"id",message:"Webhook id (lowercase, e.g. globex-gitlab)",validate:p=>/^[a-z0-9][a-z0-9_-]*$/.test(p)||"Use lowercase letters, digits, -, _"})).id||"").trim()),!r)throw new Error("Webhook id is required.");if(!/^[a-z0-9][a-z0-9_-]*$/.test(r))throw new Error("Webhook id must be lowercase (letters, digits, -, _).");if(!a&&d&&(a=(await Yo({type:"select",name:"source",message:"Source",choices:sn.map(p=>({title:`${p}${vi.has(p)?" \u2713 wired":""}`,value:p,description:hl[p]}))})).source),!sn.includes(a))throw new Error(`Source must be one of: ${sn.join(", ")}`);if(!c&&d&&(i?c=((await Yo({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await Yo({type:"select",name:"agentId",message:"Agent",choices:n.map(p=>({title:p,value:p}))})).agentId),!c)throw new Error("Agent is required.");if(i){if(!s.includes(i))throw new Error(`Mesh peer "${i}" not found in mesh.peers. Add the peer first or omit --node.`)}else if(!t.agents?.[c])throw new Error(`Unknown agent "${c}". Add it locally, or use --node <peer> to forward to a mesh peer.`);!l&&d&&a!=="custom"&&(l=((await Yo({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&d&&(g=((await Yo({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let u=await ue(f=>{if(f.webhooks=Array.isArray(f.webhooks)?f.webhooks:[],f.webhooks.find(w=>w.id===r))throw new Error(`Webhook "${r}" already exists.`);let p={id:r,source:a,agentId:c,enabled:!0};l&&(p.secretEnv=l),g&&(p.description=g),i&&(p.node=i),f.webhooks.push(p)});if(!u.success)throw new Error(u.error);console.log(oe.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),u.reloaded&&console.log(oe.dim(" daemon hot-reloaded")),!l&&a!=="custom"&&console.log(oe.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});po.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await Yo({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await ue(n=>{let s=(n.webhooks||[]).length;if(n.webhooks=(n.webhooks||[]).filter(i=>i.id!==e),n.webhooks.length===s)throw new Error(`Webhook "${e}" not found.`)});if(!t.success)throw new Error(t.error);console.log(oe.green(`\u2713 removed webhook "${e}"`))});function wl(e){return async o=>{let t=await ue(n=>{let s=(n.webhooks||[]).find(i=>i.id===o);if(!s)throw new Error(`Webhook "${o}" not found.`);s.enabled=e});if(!t.success)throw new Error(t.error);console.log(oe.green(`\u2713 ${e?"enabled":"disabled"} webhook "${o}"`))}}po.command("enable <id>").description("enable a webhook entry").action(wl(!0));po.command("disable <id>").description("disable a webhook entry").action(wl(!1));var os=new fl().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");os.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await ue(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);i.triggers=i.triggers&&typeof i.triggers=="object"?i.triggers:{},i.triggers[o]=t});if(!n.success)throw new Error(n.error);console.log(oe.green(`\u2713 ${e}: ${o} \u2192 ${t}`))});os.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await ue(n=>{let s=(n.webhooks||[]).find(i=>i.id===e);if(!s)throw new Error(`Webhook "${e}" not found.`);s.triggers&&typeof s.triggers=="object"&&delete s.triggers[o]});if(!t.success)throw new Error(t.error);console.log(oe.green(`\u2713 removed trigger ${o} from "${e}"`))});os.command("default <id> <workflowId>").description("set the default workflow when no event-type matches (use '-' to clear)").action(async(e,o)=>{let t=o==="-"||o==="",n=await ue(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);t?delete i.defaultWorkflow:i.defaultWorkflow=o});if(!n.success)throw new Error(n.error);console.log(oe.green(`\u2713 ${e}: defaultWorkflow ${t?"cleared":`\u2192 ${o}`}`))});po.addCommand(os);po.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=sn.map(t=>({source:t,wired:vi.has(t),hint:hl[t]}));if(e.json){console.log(JSON.stringify(o,null,2));return}console.log();for(let t of o){let n=t.wired?oe.green("\u2713 wired"):oe.dim("inbound-only");console.log(` ${oe.cyan(t.source.padEnd(8))} ${n} ${oe.dim(t.hint)}`)}console.log(),console.log(oe.dim(" Wired sources emit on:<source>-* hook events that workflows can subscribe to via trigger.hook.")),console.log(oe.dim(" Use 'custom' for any service not in the list (Odoo, HubSpot, Linear, Calendly, etc.).")),console.log()});import{Command as _u}from"commander";import te from"chalk";ge();function xt(e){let{summary:o,backupPath:t}=Do(n=>e(n));console.log(te.green(`
470
497
  \u2713 ${o}`)),t&&console.log(te.dim(` Backup: ${t}`)),console.log(te.dim(` Restart the daemon (or POST /reload) for the change to take effect.
471
- `))}function ts(){try{return _().business||{}}catch{return{}}}var kt=new wu().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");kt.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=ts();if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o||!o.enabled){console.log(),console.log(te.yellow(" business block not enabled (or missing).")),console.log(te.dim(" Add a `business` key to agentx.json to opt in.")),console.log();return}let t=o.orgChart||{},n=o.projects||[],s=o.contactMap||[];console.log(),console.log(te.bold(" Org chart"));let i=Object.entries(t);if(i.length===0)console.log(te.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?te.dim(` \u2192 reports to ${a.reportsTo}`):"",d=a.schedule?te.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${te.cyan(r)} ${a.role}${c}${d}`)}if(console.log(),console.log(te.bold(` Projects (${n.length})`)),n.length===0)console.log(te.dim(" (empty)"));else for(let r of n){let a=r.pm?te.dim(` \xB7 pm=${r.pm}`):"",c=r.client?te.dim(` \xB7 client=${r.client}`):"";console.log(` ${te.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(te.bold(` Contact map (${s.length})`)),s.length===0)console.log(te.dim(" (empty)"));else for(let r of s){let a=r.chatId?`chatId=${r.chatId}`:r.username?`username=${r.username}`:r.senderId?`senderId=${r.senderId}`:"?",c=r.channel?`${r.channel}/`:"";console.log(` ${te.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?te.dim(` (${r.displayName})`):""}`)}console.log()});var ki=kt.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");ki.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=ts(),t=Object.entries(o.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(t),null,2));return}if(t.length===0){console.log(te.dim(" no entries"));return}for(let[n,s]of t)console.log(` ${te.cyan(n)} ${s.role}${s.reportsTo?te.dim(` \u2192 ${s.reportsTo}`):""}`)});ki.command("add <agentId>").description("add or update an orgChart entry for an agent").requiredOption("--role <role>","role title (e.g. 'PM', 'Coder', 'DevOps')").option("--reports-to <agentId>","manager's agentId").option("--start <hh:mm>","schedule start","09:00").option("--end <hh:mm>","schedule end","17:00").option("--days <csv>","working days (mon,tue,wed,thu,fri)","mon,tue,wed,thu,fri").option("--utilization <0..1>","target utilization","0.8").action((e,o)=>{let t=String(o.days).split(",").map(n=>n.trim()).filter(Boolean);$t(n=>(n.business=n.business||{},n.business.orgChart=n.business.orgChart||{},n.business.orgChart[e]={role:o.role,...o.reportsTo?{reportsTo:o.reportsTo}:{},schedule:{days:t,start:o.start,end:o.end},utilizationTarget:parseFloat(o.utilization)||.8},`orgChart entry "${e}" upserted (role=${o.role}${o.reportsTo?`, reports to ${o.reportsTo}`:""})`))});ki.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{$t(o=>{if(!o.business?.orgChart||!(e in o.business.orgChart))throw new Error(`no orgChart entry for "${e}"`);return delete o.business.orgChart[e],`orgChart entry "${e}" removed`})});var vi=kt.command("project").description("manage business.projects \u2014 id, pm, client");vi.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=ts().projects||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(te.dim(" no projects"));return}for(let n of t)console.log(` ${te.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});vi.command("add <id>").description("add or update a project entry").option("--pm <agentId>","PM responsible for this project (drives PM gate)").option("--client <name>","client this project belongs to (drives activity-graph attribution)").action((e,o)=>{$t(t=>{t.business=t.business||{},t.business.projects=t.business.projects||[];let n=t.business.projects.findIndex(i=>i.id===e),s={id:e,...o.pm?{pm:o.pm}:{},...o.client?{client:o.client}:{}};return n>=0?t.business.projects[n]={...t.business.projects[n],...s}:t.business.projects.push(s),n>=0?`project "${e}" updated`:`project "${e}" added`})});vi.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{$t(o=>{let t=o.business?.projects||[],n=t.length;if(o.business.projects=t.filter(s=>s.id!==e),o.business.projects.length===n)throw new Error(`no project "${e}"`);return`project "${e}" removed`})});var xi=kt.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");xi.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let t=ts().contactMap||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(te.dim(" no entries"));return}for(let n of t){let s=n.chatId?`chatId=${n.chatId}`:n.username?`username=${n.username}`:n.senderId?`senderId=${n.senderId}`:"?";console.log(` ${n.channel?n.channel+"/":""}${te.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});xi.command("add").description("add a contactMap entry").requiredOption("--client <name>","client this contact belongs to").option("--channel <name>","telegram | whatsapp | slack | discord").option("--chat-id <id>","native chat id (e.g. -100\u2026, JID)").option("--username <handle>","sender username/handle").option("--sender-id <id>","numeric sender id (when username is unstable)").option("--project <id>","project this traffic should attribute to").option("--display-name <name>","display-name override for the initiator pill").action(e=>{!e.chatId&&!e.username&&!e.senderId&&(console.log(te.red(" one of --chat-id / --username / --sender-id is required")),process.exit(1)),$t(o=>{o.business=o.business||{},o.business.contactMap=o.business.contactMap||[];let t={client:e.client};e.channel&&(t.channel=e.channel),e.chatId&&(t.chatId=e.chatId),e.username&&(t.username=e.username),e.senderId&&(t.senderId=e.senderId),e.project&&(t.project=e.project),e.displayName&&(t.displayName=e.displayName),o.business.contactMap.push(t);let n=e.chatId||e.username||e.senderId;return`contact ${e.channel?e.channel+"/":""}${n} \u2192 ${e.client}${e.project?"/"+e.project:""} added`})});xi.command("remove").alias("rm").description("remove a contactMap entry by matching field(s)").option("--channel <name>").option("--chat-id <id>").option("--username <handle>").option("--sender-id <id>").action(e=>{$t(o=>{let t=o.business?.contactMap||[],n=t.length;if(o.business.contactMap=t.filter(s=>!!(e.channel&&s.channel!==e.channel||e.chatId&&s.chatId!==e.chatId||e.username&&s.username!==e.username||e.senderId&&s.senderId!==e.senderId)),o.business.contactMap.length===n)throw new Error("no matching contact entry");return`${n-o.business.contactMap.length} contact entry/entries removed`})});import{Command as bu}from"commander";import Ne from"chalk";pe();var $u={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function Si(e){let o=$u[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function ns(){let o=_().business?.standup?.plansDir||".agentx/plans";return new zr(o)}var vt=new bu().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");vt.command("set <tier>").description("write a plan for today | week | month (priorities-as-bullets)").option("-p, --priority <text...>","bullet line \u2014 repeat for multiple priorities").option("-m, --markdown <md>","raw markdown body (overrides --priority)").option("-f, --file <path>","read markdown from a file").action(async(e,o)=>{let t=Si(e),n=ns(),s;if(o.file){let{readFileSync:a}=await import("fs");s=a(o.file,"utf-8")}else o.markdown?s=o.markdown:o.priority?.length?s=o.priority.map(a=>`- ${a}`).join(`
472
- `):(console.error(Ne.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(t,s);console.log(Ne.green(` \u2713 ${t} plan saved \u2192 ${i.path}`));let r=Ts(s);if(r.length){console.log(Ne.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(Ne.dim(` \u2022 ${a}`))}});vt.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=ns();if(e){let n=Si(e),s=o.read(n);if(!s){console.log(Ne.dim(` No ${n} plan set.`));return}nl(s.tier,s.date,s.content);return}let t=o.resolve();if(!t){console.log(Ne.yellow(" No plan set at any tier.")),console.log(Ne.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(Ne.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}nl(t.tier,t.date,t.content)});vt.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=ns().list(parseInt(e.limit,10)||20);if(!t.length){console.log(Ne.dim(" No plans yet."));return}for(let n of t)console.log(` ${Ne.cyan(n.tier.padEnd(5))} ${Ne.bold(n.date.padEnd(11))} ${Ne.dim(n.path)}`)});vt.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=Si(e),n=ns().read(o);if(!n){console.log(Ne.dim(` No ${o} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(Ne.green(` \u2713 ${o} plan cleared (${n.path})`))});function nl(e,o,t){console.log(Ne.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
473
- `))console.log(` ${s}`);console.log();let n=Ts(t);n.length&&console.log(Ne.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as ku}from"commander";import Be from"chalk";pe();function vu(){try{return _().notifications||{}}catch{return{}}}function ss(e){let{summary:o,backupPath:t}=nt(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(Be.green(`
474
- \u2713 ${o}`)),t&&console.log(Be.dim(` Backup: ${t}`)),console.log(Be.dim(` Restart the daemon (or POST /reload) for the change to take effect.
475
- `))}var xt=new ku().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");xt.command("show").description("print current notifications config").option("--json","JSON output").action(e=>{let o=vu();if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.destination){let n=o.destination.accountId?` \xB7 account=${o.destination.accountId}`:"";console.log(` destination ${Be.cyan(o.destination.channel+":"+o.destination.chatId)}${Be.dim(n)}`)}else console.log(` destination ${Be.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${Be.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?Be.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?Be.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":Be.dim("off")}`),console.log()});xt.command("route").description("set the destination channel/chatId for notifications").requiredOption("--channel <name>","telegram | whatsapp | slack | discord").requiredOption("--chat-id <id>","native chat id (e.g. -100\u2026, JID, channel id)").option("--account-id <id>","channel account id when the channel is multi-account (telegram with multiple bots)").option("--clear","clear the destination instead of setting it").action(e=>{if(e.clear){ss(o=>(delete o.destination,"notifications destination cleared"));return}ss(o=>(o.destination={channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}},`notifications destination \u2192 ${e.channel}:${e.chatId}${e.accountId?` (account=${e.accountId})`:""}`))});xt.command("event <name> <state>").description("toggle an event: name in {taskComplete, taskError, taskQueued}; state in {on, off}").action((e,o)=>{let t=["taskComplete","taskError","taskQueued"];t.includes(e)||(console.log(Be.red(` unknown event "${e}". Pick from: ${t.join(", ")}`)),process.exit(1));let n=o.toLowerCase();["on","off","true","false","1","0"].includes(n)||(console.log(Be.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";ss(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});xt.command("threshold <seconds>").description("set the long-task threshold in seconds (0 disables long-task pings)").action(e=>{let o=parseInt(e,10);(!Number.isFinite(o)||o<0)&&(console.log(Be.red(" threshold must be a non-negative integer")),process.exit(1)),ss(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});import{Command as xu}from"commander";import Oo from"chalk";import{readdirSync as Ei,statSync as sl,unlinkSync as Su,rmSync as Eu,existsSync as il}from"fs";import{resolve as rl,join as al}from"path";var cl=[{dir:".agentx/sessions",label:"Per-day session JSON"},{dir:".agentx/drift",label:"Drift snapshots",recursive:!0},{dir:".agentx/router",label:"Router-decision logs",recursive:!0},{dir:".agentx/patterns",label:"Self-improving pattern store",recursive:!0}];function Ai(e,o){if(!il(e))return[];let t=[];for(let n of Ei(e,{withFileTypes:!0})){let s=al(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...Ai(s,!0))}return t}var rs=new xu().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");rs.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of cl){let t=rl(process.cwd(),o.dir),n=Ai(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=sl(a);s+=c.size,(i===null||c.mtimeMs<i)&&(i=c.mtimeMs)}catch{}e+=s;let r=i!==null?`${Math.round((Date.now()-i)/864e5)}d`:"\u2014";console.log(` ${Oo.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${is(s).padStart(10)} oldest=${r}`)}console.log(Oo.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${is(e).padStart(10)} total`)),console.log(),console.log(Oo.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});rs.command("prune").description("delete files older than --days from each retention target").option("--days <n>","max age in days; everything older is deleted","30").option("--dry-run","list candidates, don't delete").option("--target <name>","limit to one target dir (e.g. .agentx/sessions)").action(e=>{let o=parseInt(e.days,10);(!Number.isFinite(o)||o<1)&&(console.log(Oo.red(" --days must be a positive integer")),process.exit(1));let t=Date.now()-o*864e5,n=e.target,s=0,i=0;console.log(),console.log(Oo.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?Oo.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of cl){if(n&&r.dir!==n)continue;let a=rl(process.cwd(),r.dir),c=Ai(a,!!r.recursive),d=0,g=0;for(let p of c)try{let f=sl(p);if(f.mtimeMs<t&&(g+=f.size,d++,!e.dryRun))try{Su(p)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{ll(a)}catch{}let l=e.dryRun?"would remove":"removed";console.log(` ${Oo.cyan(r.dir.padEnd(22))} ${l} ${String(d).padStart(5)} files (${is(g)})`),s+=d,i+=g}console.log(),console.log(Oo.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${is(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function ll(e){if(il(e))for(let o of Ei(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=al(e,o.name);ll(t);try{Ei(t).length===0&&Eu(t,{recursive:!1})}catch{}}}function is(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}import{Command as Au}from"commander";import F from"chalk";var To=new Au().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");To.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new et().list();if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(),console.log(F.dim(" No actions yet. Add one with `agentx actions add` or `agentx actions create`.")),console.log();return}console.log();for(let n of t){let s=n.inputs?.length?F.dim(` (${n.inputs.length} input${n.inputs.length===1?"":"s"})`):"",i=n.kind==="shell"?`shell: ${n.command.slice(0,50)}`:`${n.method} ${n.url.slice(0,50)}`;console.log(` ${F.cyan(n.id.padEnd(24))} ${n.title}${s}`),console.log(` ${" ".repeat(24)} ${F.dim(i)}`)}console.log()});To.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new et().get(e);if(n||(console.log(F.red(` no action "${e}"`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),console.log(F.bold(` ${n.title}`)),n.description&&console.log(F.dim(` ${n.description}`)),console.log(),console.log(` id ${n.id}`),console.log(` kind ${n.kind}`),console.log(` timeout ${n.timeoutMs}ms`),n.kind==="shell"?(console.log(` command ${n.command}`),n.cwd&&console.log(` cwd ${n.cwd}`),n.env&&console.log(` env ${JSON.stringify(n.env)}`)):(console.log(` ${n.method.padEnd(9)} ${n.url}`),n.headers&&console.log(` headers ${JSON.stringify(n.headers)}`),n.body&&console.log(` body ${n.body.slice(0,200)}`)),n.inputs.length){console.log(),console.log(F.bold(" Inputs:"));for(let s of n.inputs){let i=s.required?F.red("*"):" ",r=s.defaultValue!==void 0?F.dim(` default=${JSON.stringify(s.defaultValue)}`):"",a=s.description?F.dim(` \u2014 ${s.description}`):"";console.log(` ${i} ${F.cyan(s.name)} (${s.type})${r}${a}`)}}console.log()});To.command("add <id>").description("add (or replace) an action non-interactively").requiredOption("--title <text>").requiredOption("--kind <kind>","shell | http").option("--description <text>").option("--command <text>","[shell] templated shell command").option("--cwd <path>","[shell] working directory").option("--url <url>","[http] URL").option("--method <m>","[http] GET|POST|PUT|PATCH|DELETE","POST").option("--headers <json>","[http] headers as JSON object").option("--body <text>","[http] body template").option("--inputs <csv>","comma-separated list of name:type[!] (e.g. amount:number!,note:string)").option("--timeout <ms>","timeout in ms (default 30000)","30000").action((e,o)=>{let t=Ou(o.inputs),n={id:e,title:o.title,description:o.description,inputs:t,timeoutMs:parseInt(o.timeout,10)||3e4,kind:o.kind};if(o.kind==="shell")o.command||(console.log(F.red(" --command required for kind=shell")),process.exit(1)),n.command=o.command,o.cwd&&(n.cwd=o.cwd);else if(o.kind==="http"){if(o.url||(console.log(F.red(" --url required for kind=http")),process.exit(1)),n.url=o.url,n.method=o.method,o.headers)try{n.headers=JSON.parse(o.headers)}catch{console.log(F.red(" --headers must be valid JSON")),process.exit(1)}o.body&&(n.body=o.body)}else console.log(F.red(" --kind must be shell|http")),process.exit(1);let s=er.safeParse(n);if(!s.success){console.log(F.red(" validation failed:"));for(let a of s.error.issues)console.log(F.red(` ${a.path.join(".")}: ${a.message}`));process.exit(1)}let r=new et().save(s.data);console.log(F.green(`
498
+ `))}function ts(){try{return _().business||{}}catch{return{}}}var St=new _u().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");St.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=ts();if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o||!o.enabled){console.log(),console.log(te.yellow(" business block not enabled (or missing).")),console.log(te.dim(" Add a `business` key to agentx.json to opt in.")),console.log();return}let t=o.orgChart||{},n=o.projects||[],s=o.contactMap||[];console.log(),console.log(te.bold(" Org chart"));let i=Object.entries(t);if(i.length===0)console.log(te.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?te.dim(` \u2192 reports to ${a.reportsTo}`):"",l=a.schedule?te.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${te.cyan(r)} ${a.role}${c}${l}`)}if(console.log(),console.log(te.bold(` Projects (${n.length})`)),n.length===0)console.log(te.dim(" (empty)"));else for(let r of n){let a=r.pm?te.dim(` \xB7 pm=${r.pm}`):"",c=r.client?te.dim(` \xB7 client=${r.client}`):"";console.log(` ${te.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(te.bold(` Contact map (${s.length})`)),s.length===0)console.log(te.dim(" (empty)"));else for(let r of s){let a=r.chatId?`chatId=${r.chatId}`:r.username?`username=${r.username}`:r.senderId?`senderId=${r.senderId}`:"?",c=r.channel?`${r.channel}/`:"";console.log(` ${te.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?te.dim(` (${r.displayName})`):""}`)}console.log()});var xi=St.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");xi.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=ts(),t=Object.entries(o.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(t),null,2));return}if(t.length===0){console.log(te.dim(" no entries"));return}for(let[n,s]of t)console.log(` ${te.cyan(n)} ${s.role}${s.reportsTo?te.dim(` \u2192 ${s.reportsTo}`):""}`)});xi.command("add <agentId>").description("add or update an orgChart entry for an agent").requiredOption("--role <role>","role title (e.g. 'PM', 'Coder', 'DevOps')").option("--reports-to <agentId>","manager's agentId").option("--start <hh:mm>","schedule start","09:00").option("--end <hh:mm>","schedule end","17:00").option("--days <csv>","working days (mon,tue,wed,thu,fri)","mon,tue,wed,thu,fri").option("--utilization <0..1>","target utilization","0.8").action((e,o)=>{let t=String(o.days).split(",").map(n=>n.trim()).filter(Boolean);xt(n=>(n.business=n.business||{},n.business.orgChart=n.business.orgChart||{},n.business.orgChart[e]={role:o.role,...o.reportsTo?{reportsTo:o.reportsTo}:{},schedule:{days:t,start:o.start,end:o.end},utilizationTarget:parseFloat(o.utilization)||.8},`orgChart entry "${e}" upserted (role=${o.role}${o.reportsTo?`, reports to ${o.reportsTo}`:""})`))});xi.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{xt(o=>{if(!o.business?.orgChart||!(e in o.business.orgChart))throw new Error(`no orgChart entry for "${e}"`);return delete o.business.orgChart[e],`orgChart entry "${e}" removed`})});var Si=St.command("project").description("manage business.projects \u2014 id, pm, client");Si.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=ts().projects||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(te.dim(" no projects"));return}for(let n of t)console.log(` ${te.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});Si.command("add <id>").description("add or update a project entry").option("--pm <agentId>","PM responsible for this project (drives PM gate)").option("--client <name>","client this project belongs to (drives activity-graph attribution)").action((e,o)=>{xt(t=>{t.business=t.business||{},t.business.projects=t.business.projects||[];let n=t.business.projects.findIndex(i=>i.id===e),s={id:e,...o.pm?{pm:o.pm}:{},...o.client?{client:o.client}:{}};return n>=0?t.business.projects[n]={...t.business.projects[n],...s}:t.business.projects.push(s),n>=0?`project "${e}" updated`:`project "${e}" added`})});Si.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{xt(o=>{let t=o.business?.projects||[],n=t.length;if(o.business.projects=t.filter(s=>s.id!==e),o.business.projects.length===n)throw new Error(`no project "${e}"`);return`project "${e}" removed`})});var Ei=St.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");Ei.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let t=ts().contactMap||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(te.dim(" no entries"));return}for(let n of t){let s=n.chatId?`chatId=${n.chatId}`:n.username?`username=${n.username}`:n.senderId?`senderId=${n.senderId}`:"?";console.log(` ${n.channel?n.channel+"/":""}${te.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});Ei.command("add").description("add a contactMap entry").requiredOption("--client <name>","client this contact belongs to").option("--channel <name>","telegram | whatsapp | slack | discord").option("--chat-id <id>","native chat id (e.g. -100\u2026, JID)").option("--username <handle>","sender username/handle").option("--sender-id <id>","numeric sender id (when username is unstable)").option("--project <id>","project this traffic should attribute to").option("--display-name <name>","display-name override for the initiator pill").action(e=>{!e.chatId&&!e.username&&!e.senderId&&(console.log(te.red(" one of --chat-id / --username / --sender-id is required")),process.exit(1)),xt(o=>{o.business=o.business||{},o.business.contactMap=o.business.contactMap||[];let t={client:e.client};e.channel&&(t.channel=e.channel),e.chatId&&(t.chatId=e.chatId),e.username&&(t.username=e.username),e.senderId&&(t.senderId=e.senderId),e.project&&(t.project=e.project),e.displayName&&(t.displayName=e.displayName),o.business.contactMap.push(t);let n=e.chatId||e.username||e.senderId;return`contact ${e.channel?e.channel+"/":""}${n} \u2192 ${e.client}${e.project?"/"+e.project:""} added`})});Ei.command("remove").alias("rm").description("remove a contactMap entry by matching field(s)").option("--channel <name>").option("--chat-id <id>").option("--username <handle>").option("--sender-id <id>").action(e=>{xt(o=>{let t=o.business?.contactMap||[],n=t.length;if(o.business.contactMap=t.filter(s=>!!(e.channel&&s.channel!==e.channel||e.chatId&&s.chatId!==e.chatId||e.username&&s.username!==e.username||e.senderId&&s.senderId!==e.senderId)),o.business.contactMap.length===n)throw new Error("no matching contact entry");return`${n-o.business.contactMap.length} contact entry/entries removed`})});import{Command as Pu}from"commander";import Re from"chalk";ge();var Mu={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function Ai(e){let o=Mu[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function ns(){let o=_().business?.standup?.plansDir||".agentx/plans";return new ra(o)}var Et=new Pu().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");Et.command("set <tier>").description("write a plan for today | week | month (priorities-as-bullets)").option("-p, --priority <text...>","bullet line \u2014 repeat for multiple priorities").option("-m, --markdown <md>","raw markdown body (overrides --priority)").option("-f, --file <path>","read markdown from a file").action(async(e,o)=>{let t=Ai(e),n=ns(),s;if(o.file){let{readFileSync:a}=await import("fs");s=a(o.file,"utf-8")}else o.markdown?s=o.markdown:o.priority?.length?s=o.priority.map(a=>`- ${a}`).join(`
499
+ `):(console.error(Re.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(t,s);console.log(Re.green(` \u2713 ${t} plan saved \u2192 ${i.path}`));let r=Is(s);if(r.length){console.log(Re.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(Re.dim(` \u2022 ${a}`))}});Et.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=ns();if(e){let n=Ai(e),s=o.read(n);if(!s){console.log(Re.dim(` No ${n} plan set.`));return}bl(s.tier,s.date,s.content);return}let t=o.resolve();if(!t){console.log(Re.yellow(" No plan set at any tier.")),console.log(Re.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(Re.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}bl(t.tier,t.date,t.content)});Et.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=ns().list(parseInt(e.limit,10)||20);if(!t.length){console.log(Re.dim(" No plans yet."));return}for(let n of t)console.log(` ${Re.cyan(n.tier.padEnd(5))} ${Re.bold(n.date.padEnd(11))} ${Re.dim(n.path)}`)});Et.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=Ai(e),n=ns().read(o);if(!n){console.log(Re.dim(` No ${o} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(Re.green(` \u2713 ${o} plan cleared (${n.path})`))});function bl(e,o,t){console.log(Re.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
500
+ `))console.log(` ${s}`);console.log();let n=Is(t);n.length&&console.log(Re.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as Lu}from"commander";import ne from"chalk";ge();function Fu(){try{return _().notifications||{}}catch{return{}}}function Uu(){try{return _().channels?.ntfy}catch{return}}function rn(e){let{summary:o,backupPath:t}=Do(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(ne.green(`
501
+ \u2713 ${o}`)),t&&console.log(ne.dim(` Backup: ${t}`)),console.log(ne.dim(` Restart the daemon (or POST /reload) for the change to take effect.
502
+ `))}var Oo=new Lu().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");Oo.command("show").description("print current notifications config").option("--json","JSON output").action(e=>{let o=Fu();if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.destination){let i=o.destination.accountId?` \xB7 account=${o.destination.accountId}`:"";console.log(` destination ${ne.cyan(o.destination.channel+":"+o.destination.chatId)}${ne.dim(i)}`)}else console.log(` destination ${ne.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${ne.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?ne.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?ne.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":ne.dim("off")}`);let n=bn(o.local);console.log(` local.banner ${n.banner?"on":ne.dim("off")}`),console.log(` local.sound ${n.sound?`${n.soundName} at ${n.volume}`:ne.dim("off")}`),console.log(` local.icon ${n.icon??ne.dim("AgentX logo")}`);let s=Cs(Uu());console.log(` ntfy ${s.enabled?"on":ne.dim("off")} ${ne.dim(`${s.server} \xB7 topic ${s.topicSet?"set":"unset"} \xB7 token ${s.tokenSet?"set":"unset"}`)}`),console.log()});Oo.command("route").description("set the destination channel/chatId for notifications").requiredOption("--channel <name>","telegram | whatsapp | slack | discord").requiredOption("--chat-id <id>","native chat id (e.g. -100\u2026, JID, channel id)").option("--account-id <id>","channel account id when the channel is multi-account (telegram with multiple bots)").option("--clear","clear the destination instead of setting it").action(e=>{if(e.clear){rn(o=>(delete o.destination,"notifications destination cleared"));return}rn(o=>(o.destination={channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}},`notifications destination \u2192 ${e.channel}:${e.chatId}${e.accountId?` (account=${e.accountId})`:""}`))});Oo.command("event <name> <state>").description("toggle an event: name in {taskComplete, taskError, taskQueued}; state in {on, off}").action((e,o)=>{let t=["taskComplete","taskError","taskQueued"];t.includes(e)||(console.log(ne.red(` unknown event "${e}". Pick from: ${t.join(", ")}`)),process.exit(1));let n=o.toLowerCase();["on","off","true","false","1","0"].includes(n)||(console.log(ne.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";rn(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});Oo.command("threshold <seconds>").description("set the long-task threshold in seconds (0 disables long-task pings)").action(e=>{let o=parseInt(e,10);(!Number.isFinite(o)||o<0)&&(console.log(ne.red(" threshold must be a non-negative integer")),process.exit(1)),rn(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});Oo.command("local").description("set what `agentx notify` does on this Mac: banner, sound, sound name, volume, banner icon").option("--banner <state>","on | off").option("--sound <state>","on | off").option("--sound-name <name>","a macOS system sound, e.g. Glass, Ping, Tink").option("--volume <n>","0 to 1").option("--icon <path>",'image for the banner icon (.png, .jpg, .icns); "" for the AgentX logo').action(e=>{let o=(n,s)=>{let i=s.toLowerCase();if(["on","true","1"].includes(i))return!0;if(["off","false","0"].includes(i))return!1;console.log(ne.red(` ${n} must be on|off`)),process.exit(1)},t={};e.banner!==void 0&&(t.banner=o("--banner",e.banner)),e.sound!==void 0&&(t.sound=o("--sound",e.sound)),e.soundName!==void 0&&(t.soundName=e.soundName),e.volume!==void 0&&(t.volume=e.volume),e.icon!==void 0&&(t.icon=e.icon),Object.keys(t).length===0&&(console.log(ne.red(" nothing to change \u2014 pass --banner, --sound, --sound-name, --volume or --icon")),process.exit(1));try{rn(n=>(n.local=Lr(n.local,t),`notifications.local = ${JSON.stringify(n.local)}`)),e.icon!==void 0&&console.log(ne.dim(` Run agentx desktop install to put the new icon on the helper.
503
+ `))}catch(n){console.log(ne.red(` ${n?.message??n}`)),process.exit(1)}});Oo.command("ntfy").description("set up phone push through ntfy: server, topic, token, on/off").option("--server <url>","ntfy server (default https://ntfy.sh)").option("--topic <topic>",'topic to publish to; a secret on ntfy.sh \u2014 "${NTFY_TOPIC}" reads it from .env').option("--token <token>",'access token for a protected topic; "${NTFY_TOKEN}" reads it from .env; "" removes it').option("--enable","turn the channel on").option("--disable","turn the channel off").action(e=>{let o={};e.server!==void 0&&(o.server=e.server),e.topic!==void 0&&(o.topic=e.topic),e.token!==void 0&&(o.token=e.token),e.enable&&(o.enabled=!0),e.disable&&(o.enabled=!1),Object.keys(o).length===0&&(console.log(ne.red(" nothing to change \u2014 pass --server, --topic, --token, --enable or --disable")),process.exit(1));try{let{summary:t,backupPath:n}=Do(s=>{s.channels=s.channels||{},s.channels.ntfy=ua(s.channels.ntfy,o);let i=Cs(s.channels.ntfy);return`channels.ntfy ${i.enabled?"on":"off"} \xB7 ${i.server} \xB7 topic ${i.topicSet?"set":"unset"} \xB7 token ${i.tokenSet?"set":"unset"}`});console.log(ne.green(`
504
+ \u2713 ${t}`)),n&&console.log(ne.dim(` Backup: ${n}`)),console.log(ne.dim(` Restart the daemon for a channel change to take effect.
505
+ `))}catch(t){console.log(ne.red(` ${t?.message??t}`)),process.exit(1)}});import{Command as qu}from"commander";import To from"chalk";import{readdirSync as Oi,statSync as $l,unlinkSync as Wu,rmSync as Bu,existsSync as kl}from"fs";import{resolve as vl,join as xl}from"path";var Sl=[{dir:".agentx/sessions",label:"Per-day session JSON"},{dir:".agentx/drift",label:"Drift snapshots",recursive:!0},{dir:".agentx/router",label:"Router-decision logs",recursive:!0},{dir:".agentx/patterns",label:"Self-improving pattern store",recursive:!0}];function Ti(e,o){if(!kl(e))return[];let t=[];for(let n of Oi(e,{withFileTypes:!0})){let s=xl(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...Ti(s,!0))}return t}var is=new qu().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");is.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of Sl){let t=vl(process.cwd(),o.dir),n=Ti(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=$l(a);s+=c.size,(i===null||c.mtimeMs<i)&&(i=c.mtimeMs)}catch{}e+=s;let r=i!==null?`${Math.round((Date.now()-i)/864e5)}d`:"\u2014";console.log(` ${To.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${ss(s).padStart(10)} oldest=${r}`)}console.log(To.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${ss(e).padStart(10)} total`)),console.log(),console.log(To.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});is.command("prune").description("delete files older than --days from each retention target").option("--days <n>","max age in days; everything older is deleted","30").option("--dry-run","list candidates, don't delete").option("--target <name>","limit to one target dir (e.g. .agentx/sessions)").action(e=>{let o=parseInt(e.days,10);(!Number.isFinite(o)||o<1)&&(console.log(To.red(" --days must be a positive integer")),process.exit(1));let t=Date.now()-o*864e5,n=e.target,s=0,i=0;console.log(),console.log(To.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?To.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of Sl){if(n&&r.dir!==n)continue;let a=vl(process.cwd(),r.dir),c=Ti(a,!!r.recursive),l=0,g=0;for(let u of c)try{let f=$l(u);if(f.mtimeMs<t&&(g+=f.size,l++,!e.dryRun))try{Wu(u)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{El(a)}catch{}let d=e.dryRun?"would remove":"removed";console.log(` ${To.cyan(r.dir.padEnd(22))} ${d} ${String(l).padStart(5)} files (${ss(g)})`),s+=l,i+=g}console.log(),console.log(To.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${ss(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function El(e){if(kl(e))for(let o of Oi(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=xl(e,o.name);El(t);try{Oi(t).length===0&&Bu(t,{recursive:!1})}catch{}}}function ss(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}import{Command as Ju}from"commander";import F from"chalk";var Io=new Ju().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");Io.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new tt().list();if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(),console.log(F.dim(" No actions yet. Add one with `agentx actions add` or `agentx actions create`.")),console.log();return}console.log();for(let n of t){let s=n.inputs?.length?F.dim(` (${n.inputs.length} input${n.inputs.length===1?"":"s"})`):"",i=n.kind==="shell"?`shell: ${n.command.slice(0,50)}`:`${n.method} ${n.url.slice(0,50)}`;console.log(` ${F.cyan(n.id.padEnd(24))} ${n.title}${s}`),console.log(` ${" ".repeat(24)} ${F.dim(i)}`)}console.log()});Io.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new tt().get(e);if(n||(console.log(F.red(` no action "${e}"`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),console.log(F.bold(` ${n.title}`)),n.description&&console.log(F.dim(` ${n.description}`)),console.log(),console.log(` id ${n.id}`),console.log(` kind ${n.kind}`),console.log(` timeout ${n.timeoutMs}ms`),n.kind==="shell"?(console.log(` command ${n.command}`),n.cwd&&console.log(` cwd ${n.cwd}`),n.env&&console.log(` env ${JSON.stringify(n.env)}`)):(console.log(` ${n.method.padEnd(9)} ${n.url}`),n.headers&&console.log(` headers ${JSON.stringify(n.headers)}`),n.body&&console.log(` body ${n.body.slice(0,200)}`)),n.inputs.length){console.log(),console.log(F.bold(" Inputs:"));for(let s of n.inputs){let i=s.required?F.red("*"):" ",r=s.defaultValue!==void 0?F.dim(` default=${JSON.stringify(s.defaultValue)}`):"",a=s.description?F.dim(` \u2014 ${s.description}`):"";console.log(` ${i} ${F.cyan(s.name)} (${s.type})${r}${a}`)}}console.log()});Io.command("add <id>").description("add (or replace) an action non-interactively").requiredOption("--title <text>").requiredOption("--kind <kind>","shell | http").option("--description <text>").option("--command <text>","[shell] templated shell command").option("--cwd <path>","[shell] working directory").option("--url <url>","[http] URL").option("--method <m>","[http] GET|POST|PUT|PATCH|DELETE","POST").option("--headers <json>","[http] headers as JSON object").option("--body <text>","[http] body template").option("--inputs <csv>","comma-separated list of name:type[!] (e.g. amount:number!,note:string)").option("--timeout <ms>","timeout in ms (default 30000)","30000").action((e,o)=>{let t=Gu(o.inputs),n={id:e,title:o.title,description:o.description,inputs:t,timeoutMs:parseInt(o.timeout,10)||3e4,kind:o.kind};if(o.kind==="shell")o.command||(console.log(F.red(" --command required for kind=shell")),process.exit(1)),n.command=o.command,o.cwd&&(n.cwd=o.cwd);else if(o.kind==="http"){if(o.url||(console.log(F.red(" --url required for kind=http")),process.exit(1)),n.url=o.url,n.method=o.method,o.headers)try{n.headers=JSON.parse(o.headers)}catch{console.log(F.red(" --headers must be valid JSON")),process.exit(1)}o.body&&(n.body=o.body)}else console.log(F.red(" --kind must be shell|http")),process.exit(1);let s=sr.safeParse(n);if(!s.success){console.log(F.red(" validation failed:"));for(let a of s.error.issues)console.log(F.red(` ${a.path.join(".")}: ${a.message}`));process.exit(1)}let r=new tt().save(s.data);console.log(F.green(`
476
506
  \u2713 action "${r.id}" saved (${r.kind}).`)),console.log(F.dim(` Test: agentx actions run ${r.id}
477
- `))});To.command("remove <id>").alias("rm").description("delete an action").action(e=>{new et().delete(e)||(console.log(F.red(` no action "${e}"`)),process.exit(1)),console.log(F.green(` \u2713 action "${e}" removed`))});To.command("run <id>").description("invoke an action and print its output").option("--input <kv...>","input as key=value (repeat for each)").option("--json","JSON output (full ActionRunResult)").action(async(e,o)=>{let n=new et().get(e);n||(console.log(F.red(` no action "${e}"`)),process.exit(1));let s={};for(let i of o.input||[]){let r=i.indexOf("=");r<0&&(console.log(F.red(` --input "${i}" must be key=value`)),process.exit(1)),s[i.slice(0,r)]=i.slice(r+1)}try{let i=await or(n,s);if(o.json){console.log(JSON.stringify(i,null,2));return}console.log(),console.log(` ${i.ok?F.green("\u2713 ok"):F.red("\u2717 failed")} status=${i.status} ${i.durationMs}ms`),console.log(),i.output&&(console.log(F.dim(" --- output ---")),console.log(i.output)),i.errors&&(console.log(F.dim(" --- errors ---")),console.log(F.red(i.errors))),console.log(),i.ok||process.exit(1)}catch(i){console.log(F.red(` ${i.message}`)),process.exit(1)}});To.command("builtin [name]").description("list registered built-in actions, or run one with --input").option("--input <json>","JSON input matching the action's inputSchema").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output (omit chrome)").option("--schema","show the action's input/output schema instead of running it").action(async(e,o)=>{let t=String(o.daemon).replace(/\/+$/,"");if(!e){try{let s=await fetch(`${t}/api/actions/builtin`);s.ok||(console.log(F.red(` list failed (${s.status}): ${(await s.text()).slice(0,200)}`)),process.exit(1));let r=(await s.json()).actions||[];if(o.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(F.dim(" No built-in actions registered. Daemon may not be running, or registerAllBuiltins() didn't fire at boot."));return}console.log(),console.log(F.bold(" Built-in typed actions")),console.log(F.dim(" Invoke: agentx actions builtin <name> --input '<json>'")),console.log();for(let a of r){let c=a.timeoutMs?F.dim(` (timeout=${Math.round(a.timeoutMs/1e3)}s)`):"";console.log(` ${F.cyan(a.name.padEnd(22))} ${a.description||""}${c}`)}console.log()}catch(s){console.log(F.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}return}if(o.schema){try{let r=((await(await fetch(`${t}/api/actions/builtin`)).json()).actions||[]).find(a=>a.name===e);if(r||(console.log(F.red(` unknown action: ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(F.bold(` ${r.name}`)),r.description&&console.log(F.dim(` ${r.description}`)),console.log(),console.log(F.dim(" --- input schema ---")),console.log(JSON.stringify(r.inputSchema??{},null,2)),r.outputSchema&&(console.log(),console.log(F.dim(" --- output schema ---")),console.log(JSON.stringify(r.outputSchema,null,2))),console.log()}catch(s){console.log(F.red(` schema fetch failed: ${s.message||s}`)),process.exit(1)}return}let n={};if(o.input)try{n=JSON.parse(o.input)}catch(s){console.log(F.red(` --input must be valid JSON: ${s.message}`)),process.exit(1)}try{let s=await fetch(`${t}/api/actions/builtin/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json().catch(()=>({}));if(s.ok||(o.json&&(console.log(JSON.stringify(i,null,2)),process.exit(1)),console.log(F.red(` action failed (${s.status}): ${i.error||JSON.stringify(i).slice(0,300)}`)),process.exit(1)),o.json){console.log(JSON.stringify(i,null,2));return}console.log(JSON.stringify(i,null,2))}catch(s){console.log(F.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}});function Ou(e){if(!e)return[];let o=[];for(let t of e.split(",").map(n=>n.trim()).filter(Boolean)){let n=t.endsWith("!"),s=n?t.slice(0,-1):t,i=s.indexOf(":"),r=i>=0?s.slice(0,i):s,a=i>=0?s.slice(i+1):"string";o.push({name:r,type:a,required:n})}return o}pe();import{Command as Tu}from"commander";import Q from"chalk";var dl=new Tu().name("watch").description("stream live daemon events \u2014 workflow runs, user tasks, signals, mesh health").option("-c, --config <path>","daemon config file").option("-t, --type <kinds>","comma-separated event kinds (run,task,signal,mesh,channel,status)").option("-w, --workflow <id>","only events for this workflow id").option("-a, --actor <id>","only task events involving this actor id").option("-r, --run <id>","only events for this run id").option("--channel <name>","only channel events on this channel (telegram/whatsapp/\u2026)").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let r=_(e.config);o||(o=r.dashboard?.daemonUrl||""),t||(t=r.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n=[];typeof e.type=="string"&&n.push(`type=${encodeURIComponent(e.type)}`),typeof e.workflow=="string"&&n.push(`workflow=${encodeURIComponent(e.workflow)}`),typeof e.actor=="string"&&n.push(`actor=${encodeURIComponent(e.actor)}`),typeof e.run=="string"&&n.push(`run=${encodeURIComponent(e.run)}`),typeof e.channel=="string"&&n.push(`channel=${encodeURIComponent(e.channel)}`);let s=`${o.replace(/\/+$/,"")}/events${n.length?`?${n.join("&")}`:""}`;console.log(Q.dim(` connecting to ${s}`));let i={Accept:"text/event-stream"};t&&(i.Authorization=`Bearer ${t}`);try{let r=await fetch(s,{headers:i});(!r.ok||!r.body)&&(console.error(Q.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(Q.green(" connected \u2014 Ctrl-C to stop")),console.log("");let a=r.body.getReader(),c=new TextDecoder,d="";for(;;){let{done:g,value:l}=await a.read();if(g)break;d+=c.decode(l,{stream:!0});let p;for(;(p=d.indexOf(`
507
+ `))});Io.command("remove <id>").alias("rm").description("delete an action").action(e=>{new tt().delete(e)||(console.log(F.red(` no action "${e}"`)),process.exit(1)),console.log(F.green(` \u2713 action "${e}" removed`))});Io.command("run <id>").description("invoke an action and print its output").option("--input <kv...>","input as key=value (repeat for each)").option("--json","JSON output (full ActionRunResult)").action(async(e,o)=>{let n=new tt().get(e);n||(console.log(F.red(` no action "${e}"`)),process.exit(1));let s={};for(let i of o.input||[]){let r=i.indexOf("=");r<0&&(console.log(F.red(` --input "${i}" must be key=value`)),process.exit(1)),s[i.slice(0,r)]=i.slice(r+1)}try{let i=await ir(n,s);if(o.json){console.log(JSON.stringify(i,null,2));return}console.log(),console.log(` ${i.ok?F.green("\u2713 ok"):F.red("\u2717 failed")} status=${i.status} ${i.durationMs}ms`),console.log(),i.output&&(console.log(F.dim(" --- output ---")),console.log(i.output)),i.errors&&(console.log(F.dim(" --- errors ---")),console.log(F.red(i.errors))),console.log(),i.ok||process.exit(1)}catch(i){console.log(F.red(` ${i.message}`)),process.exit(1)}});Io.command("builtin [name]").description("list registered built-in actions, or run one with --input").option("--input <json>","JSON input matching the action's inputSchema").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output (omit chrome)").option("--schema","show the action's input/output schema instead of running it").action(async(e,o)=>{let t=String(o.daemon).replace(/\/+$/,"");if(!e){try{let s=await fetch(`${t}/api/actions/builtin`);s.ok||(console.log(F.red(` list failed (${s.status}): ${(await s.text()).slice(0,200)}`)),process.exit(1));let r=(await s.json()).actions||[];if(o.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(F.dim(" No built-in actions registered. Daemon may not be running, or registerAllBuiltins() didn't fire at boot."));return}console.log(),console.log(F.bold(" Built-in typed actions")),console.log(F.dim(" Invoke: agentx actions builtin <name> --input '<json>'")),console.log();for(let a of r){let c=a.timeoutMs?F.dim(` (timeout=${Math.round(a.timeoutMs/1e3)}s)`):"";console.log(` ${F.cyan(a.name.padEnd(22))} ${a.description||""}${c}`)}console.log()}catch(s){console.log(F.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}return}if(o.schema){try{let r=((await(await fetch(`${t}/api/actions/builtin`)).json()).actions||[]).find(a=>a.name===e);if(r||(console.log(F.red(` unknown action: ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(F.bold(` ${r.name}`)),r.description&&console.log(F.dim(` ${r.description}`)),console.log(),console.log(F.dim(" --- input schema ---")),console.log(JSON.stringify(r.inputSchema??{},null,2)),r.outputSchema&&(console.log(),console.log(F.dim(" --- output schema ---")),console.log(JSON.stringify(r.outputSchema,null,2))),console.log()}catch(s){console.log(F.red(` schema fetch failed: ${s.message||s}`)),process.exit(1)}return}let n={};if(o.input)try{n=JSON.parse(o.input)}catch(s){console.log(F.red(` --input must be valid JSON: ${s.message}`)),process.exit(1)}try{let s=await fetch(`${t}/api/actions/builtin/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json().catch(()=>({}));if(s.ok||(o.json&&(console.log(JSON.stringify(i,null,2)),process.exit(1)),console.log(F.red(` action failed (${s.status}): ${i.error||JSON.stringify(i).slice(0,300)}`)),process.exit(1)),o.json){console.log(JSON.stringify(i,null,2));return}console.log(JSON.stringify(i,null,2))}catch(s){console.log(F.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}});function Gu(e){if(!e)return[];let o=[];for(let t of e.split(",").map(n=>n.trim()).filter(Boolean)){let n=t.endsWith("!"),s=n?t.slice(0,-1):t,i=s.indexOf(":"),r=i>=0?s.slice(0,i):s,a=i>=0?s.slice(i+1):"string";o.push({name:r,type:a,required:n})}return o}ge();import{Command as Hu}from"commander";import Q from"chalk";var Al=new Hu().name("watch").description("stream live daemon events \u2014 workflow runs, user tasks, signals, mesh health").option("-c, --config <path>","daemon config file").option("-t, --type <kinds>","comma-separated event kinds (run,task,signal,mesh,channel,status)").option("-w, --workflow <id>","only events for this workflow id").option("-a, --actor <id>","only task events involving this actor id").option("-r, --run <id>","only events for this run id").option("--channel <name>","only channel events on this channel (telegram/whatsapp/\u2026)").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let r=_(e.config);o||(o=r.dashboard?.daemonUrl||""),t||(t=r.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n=[];typeof e.type=="string"&&n.push(`type=${encodeURIComponent(e.type)}`),typeof e.workflow=="string"&&n.push(`workflow=${encodeURIComponent(e.workflow)}`),typeof e.actor=="string"&&n.push(`actor=${encodeURIComponent(e.actor)}`),typeof e.run=="string"&&n.push(`run=${encodeURIComponent(e.run)}`),typeof e.channel=="string"&&n.push(`channel=${encodeURIComponent(e.channel)}`);let s=`${o.replace(/\/+$/,"")}/events${n.length?`?${n.join("&")}`:""}`;console.log(Q.dim(` connecting to ${s}`));let i={Accept:"text/event-stream"};t&&(i.Authorization=`Bearer ${t}`);try{let r=await fetch(s,{headers:i});(!r.ok||!r.body)&&(console.error(Q.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(Q.green(" connected \u2014 Ctrl-C to stop")),console.log("");let a=r.body.getReader(),c=new TextDecoder,l="";for(;;){let{done:g,value:d}=await a.read();if(g)break;l+=c.decode(d,{stream:!0});let u;for(;(u=l.indexOf(`
478
508
 
479
- `))>=0;){let f=d.slice(0,p);d=d.slice(p+2),Iu(f)}}}catch(r){console.error(Q.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function Iu(e){let o="message",t="";for(let i of e.split(`
480
- `))i.startsWith("event: ")?o=i.slice(7):i.startsWith("data: ")&&(t=i.slice(6));if(!t)return;let n={};try{n=JSON.parse(t)}catch{console.log(`${o}: ${t}`);return}let s=n.at?Q.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=Q.cyan(n.phase?.padEnd(9)??"run"),r=Q.bold(n.workflowId??""),a=Q.dim((n.runId??"").slice(0,8)),c=n.nodeId?Q.yellow(n.nodeId):"",d=n.note?Q.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${d}`);break}case"task":{let i=Q.magenta(`task.${n.phase}`.padEnd(14)),r=Q.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?Q.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${Q.cyan(a)} ${c}`);break}case"signal":{let i=Q.green("signal".padEnd(9)),r=Q.bold(n.name),a=Q.dim(`(${n.scope})`),c=n.workflowId?Q.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=Q.blue("mesh".padEnd(9)),r=Q.bold(n.peer),a=n.healthy?Q.green("\u2713 healthy"):Q.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${Q.dim(n.delta??"")}`);break}case"channel":{let i=Q.yellow("channel".padEnd(9)),r=n.direction==="in"?Q.cyan("\u2190"):Q.magenta("\u2192"),a=Q.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?Q.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(Q.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${o} ${JSON.stringify(n)}`)}}import{Command as Cu}from"commander";import as from"chalk";import{spawn as Nu}from"node:child_process";import{execFileSync as ju}from"node:child_process";function gl(e=()=>ju("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let o;try{o=e().trim()}catch(n){return{ok:!1,reason:n?.code==="ENOENT"?"OpenCode is not installed or is not on PATH.":`Could not run opencode --version: ${n?.message||String(n)}`}}let t=o.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return t?Number(t[1])<2?{ok:!1,reason:`OpenCode ${o} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:o}:{ok:!1,reason:`Could not recognize the OpenCode version: ${o||"empty output"}`}}var ml=new Cu().name("tui").description("open the AgentX console in OpenCode").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","daemon mesh bearer token for remote nodes").option("--agent <id>","AgentX agent to use as the OpenCode model").option("--legacy","open the built-in Ink terminal UI").option("--poll <ms>","legacy UI snapshot poll interval in ms","3000").action(async e=>{process.stdout.isTTY||(console.error(as.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-6BGTH2TT.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:gl();if(n?.ok){let{fetchAgents:d}=await import("./client-6BGTH2TT.js"),g=await d(t);if(!g.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let l=e.agent||g[0].id;if(!g.some(y=>y.id===l))throw new Error(`Unknown AgentX agent: ${l}`);let p={};try{p=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(y=>[y.id,{name:`AgentX ${y.name||y.id}`}])),u={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...p,model:`agentx/${l}`,providers:{...p.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:f}}})};console.error(as.dim(`Opening ${n.version} with AgentX model ${l}.`));let w=Nu("opencode",["--standalone"],{stdio:"inherit",env:u});await new Promise((y,k)=>{w.once("error",k),w.once("exit",b=>b===0?y():k(new Error(`OpenCode exited with code ${b??"unknown"}`)))});return}n&&!n.ok&&(console.error(as.yellow(n.reason)),console.error(as.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-HSRGG5VA.js"),{render:i}=await import("ink"),r=(await import("react")).default,a=Math.max(500,Number(e.poll)||3e3);await i(r.createElement(s,{conn:t,pollMs:a})).waitUntilExit()});import{Command as Ru}from"commander";import V from"chalk";import{randomUUID as fl}from"crypto";import{createInterface as Du}from"node:readline/promises";import _u from"ora";import cs from"chalk";function pl(e){console.error(),console.error(cs.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(cs.dim(` ${e.why}`)),console.error(),console.error(` Use ${cs.cyan(e.instead)} instead.`),e.note&&console.error(cs.dim(` ${e.note}`)),console.error()}var ul={why:"No recorded use on any node since 2026-07-03.",instead:"agentx attach <agent>",note:"Wears the identity in the Claude Code session you already have open \u2014 see docs/reference/attach.md"};var hl=new Ru().name("chat").description("[deprecated \u2014 see agentx attach] interactive chat with a daemon-registered agent").argument("[agent]","agent id to talk to (with or without leading @)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").option("--channel <name>","logical channel name passed in context","chat-cli").option("--chat-id <id>","resume an existing chatId (otherwise a fresh one is generated)").action(async(e,o)=>{pl({what:"agentx chat",...ul});let t=ta({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${fl().slice(0,12)}`,r=[];try{r=await xn(t)}catch(g){console.error(V.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(V.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(V.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(V.red(` unknown agent: @${n}`)),console.error(V.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(V.dim(` no agent given \u2014 defaulting to @${n}`))),process.stdout.isTTY&&process.stdin.isTTY){let{render:g}=await import("ink"),{ChatApp:l}=await import("./ChatApp-4FOU6Q3S.js"),p=(await import("react")).default;await g(p.createElement(l,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}Lu(t.baseUrl,n,i,s);let a=Du({input:process.stdin,output:process.stdout}),c=!1,d=!1;for(a.on("close",()=>{if(c){d=!0;return}console.log(V.dim(`
481
- bye`)),process.exit(0)});;){let g;try{g=(await a.question(V.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(V.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${fl().slice(0,12)}`,console.log(V.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let u=await xn(t);for(let w of u){let y=w.id===n?V.green("\u25CF"):V.dim("\u25CB");console.log(` ${y} @${w.id} ${V.dim(w.tier)} ${w.model??""}`)}}catch(u){console.error(V.red(` failed to list agents: ${u?.message||u}`))}continue}if(g.startsWith("/agent ")){let u=g.slice(7).replace(/^@/,"").trim();if(!u){console.log(V.red(" usage: /agent <id>"));continue}try{if(!(await xn(t)).find(y=>y.id===u)){console.log(V.red(` unknown agent: @${u}`));continue}n=u,console.log(V.dim(` now talking to @${n}`))}catch(w){console.error(V.red(` failed to switch agent: ${w?.message||w}`))}continue}if(g.startsWith("/")){console.log(V.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(V.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let l=_u({text:`@${n}\u2026`,color:"cyan"}).start(),p=Date.now(),f=Pu(n);try{let u=await na(t,n,g,{channel:s,chatId:i,onText:y=>{l.stop(),f.text(y)},onThinking:()=>{},onTool:y=>{l.stop(),f.tool(y)}});l.stop();let w=Math.round((Date.now()-p)/100)/10;u.error?f.finishError(u.error):f.finish(w,u.usage)}catch(u){l.stop(),f.finishError(u?.message||String(u))}finally{c=!1}if(d){console.log(V.dim(" bye"));return}}});function Pu(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${V.green(`@${e}`)}
509
+ `))>=0;){let f=l.slice(0,u);l=l.slice(u+2),zu(f)}}}catch(r){console.error(Q.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function zu(e){let o="message",t="";for(let i of e.split(`
510
+ `))i.startsWith("event: ")?o=i.slice(7):i.startsWith("data: ")&&(t=i.slice(6));if(!t)return;let n={};try{n=JSON.parse(t)}catch{console.log(`${o}: ${t}`);return}let s=n.at?Q.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=Q.cyan(n.phase?.padEnd(9)??"run"),r=Q.bold(n.workflowId??""),a=Q.dim((n.runId??"").slice(0,8)),c=n.nodeId?Q.yellow(n.nodeId):"",l=n.note?Q.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=Q.magenta(`task.${n.phase}`.padEnd(14)),r=Q.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?Q.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${Q.cyan(a)} ${c}`);break}case"signal":{let i=Q.green("signal".padEnd(9)),r=Q.bold(n.name),a=Q.dim(`(${n.scope})`),c=n.workflowId?Q.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=Q.blue("mesh".padEnd(9)),r=Q.bold(n.peer),a=n.healthy?Q.green("\u2713 healthy"):Q.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${Q.dim(n.delta??"")}`);break}case"channel":{let i=Q.yellow("channel".padEnd(9)),r=n.direction==="in"?Q.cyan("\u2190"):Q.magenta("\u2192"),a=Q.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?Q.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(Q.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${o} ${JSON.stringify(n)}`)}}import{Command as Vu}from"commander";import rs from"chalk";import{spawn as Ku}from"node:child_process";import{execFileSync as Yu}from"node:child_process";function Ol(e=()=>Yu("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let o;try{o=e().trim()}catch(n){return{ok:!1,reason:n?.code==="ENOENT"?"OpenCode is not installed or is not on PATH.":`Could not run opencode --version: ${n?.message||String(n)}`}}let t=o.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return t?Number(t[1])<2?{ok:!1,reason:`OpenCode ${o} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:o}:{ok:!1,reason:`Could not recognize the OpenCode version: ${o||"empty output"}`}}var Tl=new Vu().name("tui").description("open the AgentX console in OpenCode").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","daemon mesh bearer token for remote nodes").option("--agent <id>","AgentX agent to use as the OpenCode model").option("--legacy","open the built-in Ink terminal UI").option("--poll <ms>","legacy UI snapshot poll interval in ms","3000").action(async e=>{process.stdout.isTTY||(console.error(rs.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-NTC667CA.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:Ol();if(n?.ok){let{fetchAgents:l}=await import("./client-NTC667CA.js"),g=await l(t);if(!g.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let d=e.agent||g[0].id;if(!g.some(y=>y.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let u={};try{u=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(y=>[y.id,{name:`AgentX ${y.name||y.id}`}])),p={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...u,model:`agentx/${d}`,providers:{...u.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:f}}})};console.error(rs.dim(`Opening ${n.version} with AgentX model ${d}.`));let w=Ku("opencode",["--standalone"],{stdio:"inherit",env:p});await new Promise((y,k)=>{w.once("error",k),w.once("exit",b=>b===0?y():k(new Error(`OpenCode exited with code ${b??"unknown"}`)))});return}n&&!n.ok&&(console.error(rs.yellow(n.reason)),console.error(rs.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-QTUGMHG7.js"),{render:i}=await import("ink"),r=(await import("react")).default,a=Math.max(500,Number(e.poll)||3e3);await i(r.createElement(s,{conn:t,pollMs:a})).waitUntilExit()});import{Command as Xu}from"commander";import V from"chalk";import{randomUUID as Cl}from"crypto";import{createInterface as Qu}from"node:readline/promises";import Zu from"ora";import as from"chalk";function Il(e){console.error(),console.error(as.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(as.dim(` ${e.why}`)),console.error(),console.error(` Use ${as.cyan(e.instead)} instead.`),e.note&&console.error(as.dim(` ${e.note}`)),console.error()}var jl={why:"No recorded use on any node since 2026-07-03.",instead:"agentx attach <agent>",note:"Wears the identity in the Claude Code session you already have open \u2014 see docs/reference/attach.md"};var Nl=new Xu().name("chat").description("[deprecated \u2014 see agentx attach] interactive chat with a daemon-registered agent").argument("[agent]","agent id to talk to (with or without leading @)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").option("--channel <name>","logical channel name passed in context","chat-cli").option("--chat-id <id>","resume an existing chatId (otherwise a fresh one is generated)").action(async(e,o)=>{Il({what:"agentx chat",...jl});let t=ha({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${Cl().slice(0,12)}`,r=[];try{r=await An(t)}catch(g){console.error(V.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(V.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(V.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(V.red(` unknown agent: @${n}`)),console.error(V.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(V.dim(` no agent given \u2014 defaulting to @${n}`))),process.stdout.isTTY&&process.stdin.isTTY){let{render:g}=await import("ink"),{ChatApp:d}=await import("./ChatApp-634FDG3W.js"),u=(await import("react")).default;await g(u.createElement(d,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}of(t.baseUrl,n,i,s);let a=Qu({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(V.dim(`
511
+ bye`)),process.exit(0)});;){let g;try{g=(await a.question(V.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(V.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${Cl().slice(0,12)}`,console.log(V.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let p=await An(t);for(let w of p){let y=w.id===n?V.green("\u25CF"):V.dim("\u25CB");console.log(` ${y} @${w.id} ${V.dim(w.tier)} ${w.model??""}`)}}catch(p){console.error(V.red(` failed to list agents: ${p?.message||p}`))}continue}if(g.startsWith("/agent ")){let p=g.slice(7).replace(/^@/,"").trim();if(!p){console.log(V.red(" usage: /agent <id>"));continue}try{if(!(await An(t)).find(y=>y.id===p)){console.log(V.red(` unknown agent: @${p}`));continue}n=p,console.log(V.dim(` now talking to @${n}`))}catch(w){console.error(V.red(` failed to switch agent: ${w?.message||w}`))}continue}if(g.startsWith("/")){console.log(V.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(V.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=Zu({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),f=ef(n);try{let p=await ya(t,n,g,{channel:s,chatId:i,onText:y=>{d.stop(),f.text(y)},onThinking:()=>{},onTool:y=>{d.stop(),f.tool(y)}});d.stop();let w=Math.round((Date.now()-u)/100)/10;p.error?f.finishError(p.error):f.finish(w,p.usage)}catch(p){d.stop(),f.finishError(p?.message||String(p))}finally{c=!1}if(l){console.log(V.dim(" bye"));return}}});function ef(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${V.green(`@${e}`)}
482
512
  `),o=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)t&&a!==`
483
513
  `&&(process.stdout.write(" "),t=!1),process.stdout.write(a),a===`
484
514
  `&&(t=!0)}},tool(r){if(i(),r.status==="start"&&r.name){let a=r.id||`${r.name}:${s.size}`;if(s.has(a))return;s.add(a),t||(process.stdout.write(`
@@ -493,17 +523,17 @@ agentx wiki questions`,ae=T?.daemon?.port??T?.port??18800;try{let B=await fetch(
493
523
  `))},finishError(r){o&&!t&&process.stdout.write(`
494
524
  `),process.stdout.write(V.red(` \u2717 ${r}
495
525
 
496
- `))}}}function Lu(e,o,t,n){console.log(),console.log(V.bold(" agentx chat")),console.log(V.dim(` daemon: ${e} \xB7 channel: ${n} \xB7 chatId: ${t}`)),console.log(V.dim(` agent: @${o} \xB7 /exit to quit \xB7 /agent <id> to switch`)),console.log()}import{Command as Mu}from"commander";import Re from"chalk";import{readFileSync as Fu}from"fs";var ls=["user","feedback","project","reference"],zo=new Mu().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");zo.command("add").description("add a memory for an agent").requiredOption("--agent <id>","agent id").requiredOption("--type <type>","one of: user, feedback, project, reference").requiredOption("--name <slug>","short slug, unique per agent (e.g. deep-backend)").requiredOption("--description <line>","one-line hook shown in MEMORY.md").option("--body <text>","memory body (markdown); repeat --body or use --file").option("--file <path>","read body from a file (use '-' for stdin)").action(async e=>{if(!ls.includes(e.type)){console.error(Re.red(` --type must be one of: ${ls.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await Uu();else try{o=Fu(e.file,"utf-8")}catch(s){console.error(Re.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(Re.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new Xo().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(Re.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});zo.command("list").description("list memories for an agent").requiredOption("--agent <id>","agent id").option("--type <type>","filter by memory type").action(e=>{let t=new Xo().list(e.agent);if(e.type){if(!ls.includes(e.type)){console.error(Re.red(` --type must be one of: ${ls.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.length){console.log(Re.dim(` no memories for agent "${e.agent}"${e.type?` of type "${e.type}"`:""}`));return}console.log();let n=null;for(let s of t)s.type!==n&&(console.log(Re.bold(` ${s.type}`)),n=s.type),console.log(` ${Re.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(Re.dim(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});zo.command("show").description("print the full body of a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{let n=new Xo().get(o.agent,e);if(!n){console.error(Re.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Re.bold(`${n.type}/${n.name}`)+Re.dim(` (${n.description})`)),console.log(Re.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});zo.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new Xo().remove(o.agent,e)){console.error(Re.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Re.green(` \u2713 memory "${e}" removed`))});zo.command("index").description("print the MEMORY.md index content an agent sees in its prompt").requiredOption("--agent <id>","agent id").action(e=>{let t=new Xo().indexMarkdown(e.agent);if(!t){console.log(Re.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});async function Uu(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}Pl();import Oi from"chalk";import{Command as qu}from"commander";import{resolve as Wu}from"path";var yl=new qu().name("serve").description("run agentx as an MCP server for AI editors (Claude Code, Cursor, Windsurf, etc.)").option("--stdio","use stdio transport (default)",!0).option("-c, --cwd <cwd>","working directory",process.cwd()).action(async e=>{try{process.chdir(Wu(e.cwd)),e.stdio!==!1?await dr():(ro.error("Only stdio transport is currently supported."),ro.info(`Usage: ${Oi.green("agentx serve --stdio")} or configure in your MCP client.`),ro.break(),ro.info("Add to Claude Code:"),ro.info(Oi.dim(" claude mcp add agentx -- npx agentx serve --stdio")),ro.break(),ro.info("Add to Cursor/MCP config:"),ro.info(Oi.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){Yr(o)}});import{Command as Bu}from"commander";import ie from"chalk";import{spawn as Ti}from"child_process";import{mkdirSync as Ju,writeFileSync as ms,readFileSync as Gu,readdirSync as Hu,rmSync as bl,openSync as $l,existsSync as ds}from"fs";import{resolve as zu,join as De}from"path";import{randomBytes as Yu}from"crypto";var wl={id:"demo-report",version:2,title:"Draft the demo shop report",description:"Scripted documentation example. Review and enable before running.",status:"draft",state:"disabled",nodes:[{id:"start",type:"trigger.manual",config:{},position:{x:80,y:180}},{id:"report",type:"agent",config:{agentId:"cx",prompt:"Prepare the demo shop report."},position:{x:380,y:180}},{id:"done",type:"end",config:{status:"completed"},position:{x:680,y:180}}],edges:[{from:"start",to:"report"},{from:"report",to:"done"}]};var kl="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",Vu="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function Ku(e,o){return[{dir:De(e,"node-a"),id:"demo-laptop",name:"laptop-paris",port:o,agentId:"cx",agentName:"CX",persona:"You are CX, the customer-facing coordinator. You triage inbound issues and delegate technical work to @builder on the vps node.",script:{steps:[{match:"USER: Build the demo report workflow",reply:"Here is a scripted example: start it manually, ask CX for a report, then finish. It is saved disabled so you can review it before running.\n\n```json\n"+JSON.stringify(wl,null,2)+"\n```",delayMs:300,chunkMs:2},{match:"Prepare the demo shop report",reply:"Demo shop report: checkout checks passed, MR !47 is ready for review, and CX has drafted the customer update. This is a scripted example.",delayMs:500},{match:"checkout is broken",thinking:"Checkout failure + red CI \u2014 this is a build problem, not a support question. @builder on vps-nyc owns demo/shop.",reply:"Checkout failure traced to the red pipeline on demo/shop. This needs a code fix \u2014 delegating to @builder on the vps-nyc node over the mesh. I'll report back on this thread.",delayMs:900},{match:"Builder reports",thinking:"Fix confirmed and pipeline green \u2014 close the loop with the customer.",reply:"Resolved \u2705 \u2014 builder patched checkout.test.ts (Node 22 crypto import), MR !47 merged, pipeline green. Customer thread updated. Every hop of this run is in the ledger: `agentx ledger`.",delayMs:800}],fallback:{reply:"Demo mode \u2014 I answer from a script. Try the scripted scenario, or run `agentx setup` to connect a real model."}}},{dir:De(e,"node-b"),id:"demo-vps",name:"vps-nyc",port:o+1,agentId:"builder",agentName:"Builder",persona:"You are Builder, the engineering agent on the vps node. You fix code, open MRs, and report results tersely.",script:{steps:[{match:"checkout\\.test\\.ts|CI is red",thinking:"Reproducing on Node 22\u2026 crypto.webcrypto import moved. Patching the test setup, rerunning the suite.",reply:"Fixed. checkout.test.ts assumed the legacy crypto.webcrypto import \u2014 patched for Node 22, suite green locally. Opened MR !47 on demo/shop; pipeline is green. Handing back to @cx.",delayMs:1400,chunkMs:40}],fallback:{reply:"Builder here (demo script). Send me a failing pipeline."}}},{dir:De(e,"node-c"),id:"demo-pi",name:"pi-office",port:o+2,agentId:"scout",agentName:"Scout",persona:"You are Scout, the monitoring agent on the office Raspberry Pi. You watch schedules and report status.",script:{fallback:{reply:"Scout here (demo script) \u2014 all monitors green on pi-office."},steps:[]}}]}function Xu(e,o,t){let n=De(e.dir,"workspaces",e.agentId);Ju(n,{recursive:!0}),ms(De(n,"CLAUDE.md"),`# ${e.agentName}
526
+ `))}}}function of(e,o,t,n){console.log(),console.log(V.bold(" agentx chat")),console.log(V.dim(` daemon: ${e} \xB7 channel: ${n} \xB7 chatId: ${t}`)),console.log(V.dim(` agent: @${o} \xB7 /exit to quit \xB7 /agent <id> to switch`)),console.log()}import{Command as tf}from"commander";import De from"chalk";import{readFileSync as nf}from"fs";var cs=["user","feedback","project","reference"],Vo=new tf().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");Vo.command("add").description("add a memory for an agent").requiredOption("--agent <id>","agent id").requiredOption("--type <type>","one of: user, feedback, project, reference").requiredOption("--name <slug>","short slug, unique per agent (e.g. deep-backend)").requiredOption("--description <line>","one-line hook shown in MEMORY.md").option("--body <text>","memory body (markdown); repeat --body or use --file").option("--file <path>","read body from a file (use '-' for stdin)").action(async e=>{if(!cs.includes(e.type)){console.error(De.red(` --type must be one of: ${cs.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await sf();else try{o=nf(e.file,"utf-8")}catch(s){console.error(De.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(De.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new Zo().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(De.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});Vo.command("list").description("list memories for an agent").requiredOption("--agent <id>","agent id").option("--type <type>","filter by memory type").action(e=>{let t=new Zo().list(e.agent);if(e.type){if(!cs.includes(e.type)){console.error(De.red(` --type must be one of: ${cs.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.length){console.log(De.dim(` no memories for agent "${e.agent}"${e.type?` of type "${e.type}"`:""}`));return}console.log();let n=null;for(let s of t)s.type!==n&&(console.log(De.bold(` ${s.type}`)),n=s.type),console.log(` ${De.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(De.dim(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});Vo.command("show").description("print the full body of a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{let n=new Zo().get(o.agent,e);if(!n){console.error(De.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(De.bold(`${n.type}/${n.name}`)+De.dim(` (${n.description})`)),console.log(De.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});Vo.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new Zo().remove(o.agent,e)){console.error(De.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(De.green(` \u2713 memory "${e}" removed`))});Vo.command("index").description("print the MEMORY.md index content an agent sees in its prompt").requiredOption("--agent <id>","agent id").action(e=>{let t=new Zo().indexMarkdown(e.agent);if(!t){console.log(De.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});async function sf(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}Ql();import Ii from"chalk";import{Command as rf}from"commander";import{resolve as af}from"path";var Rl=new rf().name("serve").description("run agentx as an MCP server for AI editors (Claude Code, Cursor, Windsurf, etc.)").option("--stdio","use stdio transport (default)",!0).option("-c, --cwd <cwd>","working directory",process.cwd()).action(async e=>{try{process.chdir(af(e.cwd)),e.stdio!==!1?await kr():(io.error("Only stdio transport is currently supported."),io.info(`Usage: ${Ii.green("agentx serve --stdio")} or configure in your MCP client.`),io.break(),io.info("Add to Claude Code:"),io.info(Ii.dim(" claude mcp add agentx -- npx agentx serve --stdio")),io.break(),io.info("Add to Cursor/MCP config:"),io.info(Ii.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){aa(o)}});import{Command as cf}from"commander";import re from"chalk";import{spawn as ji}from"child_process";import{mkdirSync as lf,writeFileSync as gs,readFileSync as df,readdirSync as gf,rmSync as _l,openSync as Pl,existsSync as ls}from"fs";import{resolve as mf,join as _e}from"path";import{randomBytes as pf}from"crypto";var Dl={id:"demo-report",version:2,title:"Draft the demo shop report",description:"Scripted documentation example. Review and enable before running.",status:"draft",state:"disabled",nodes:[{id:"start",type:"trigger.manual",config:{},position:{x:80,y:180}},{id:"report",type:"agent",config:{agentId:"cx",prompt:"Prepare the demo shop report."},position:{x:380,y:180}},{id:"done",type:"end",config:{status:"completed"},position:{x:680,y:180}}],edges:[{from:"start",to:"report"},{from:"report",to:"done"}]};var Ml="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",uf="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function ff(e,o){return[{dir:_e(e,"node-a"),id:"demo-laptop",name:"laptop-paris",port:o,agentId:"cx",agentName:"CX",persona:"You are CX, the customer-facing coordinator. You triage inbound issues and delegate technical work to @builder on the vps node.",script:{steps:[{match:"USER: Build the demo report workflow",reply:"Here is a scripted example: start it manually, ask CX for a report, then finish. It is saved disabled so you can review it before running.\n\n```json\n"+JSON.stringify(Dl,null,2)+"\n```",delayMs:300,chunkMs:2},{match:"Prepare the demo shop report",reply:"Demo shop report: checkout checks passed, MR !47 is ready for review, and CX has drafted the customer update. This is a scripted example.",delayMs:500},{match:"checkout is broken",thinking:"Checkout failure + red CI \u2014 this is a build problem, not a support question. @builder on vps-nyc owns demo/shop.",reply:"Checkout failure traced to the red pipeline on demo/shop. This needs a code fix \u2014 delegating to @builder on the vps-nyc node over the mesh. I'll report back on this thread.",delayMs:900},{match:"Builder reports",thinking:"Fix confirmed and pipeline green \u2014 close the loop with the customer.",reply:"Resolved \u2705 \u2014 builder patched checkout.test.ts (Node 22 crypto import), MR !47 merged, pipeline green. Customer thread updated. Every hop of this run is in the ledger: `agentx ledger`.",delayMs:800}],fallback:{reply:"Demo mode \u2014 I answer from a script. Try the scripted scenario, or run `agentx setup` to connect a real model."}}},{dir:_e(e,"node-b"),id:"demo-vps",name:"vps-nyc",port:o+1,agentId:"builder",agentName:"Builder",persona:"You are Builder, the engineering agent on the vps node. You fix code, open MRs, and report results tersely.",script:{steps:[{match:"checkout\\.test\\.ts|CI is red",thinking:"Reproducing on Node 22\u2026 crypto.webcrypto import moved. Patching the test setup, rerunning the suite.",reply:"Fixed. checkout.test.ts assumed the legacy crypto.webcrypto import \u2014 patched for Node 22, suite green locally. Opened MR !47 on demo/shop; pipeline is green. Handing back to @cx.",delayMs:1400,chunkMs:40}],fallback:{reply:"Builder here (demo script). Send me a failing pipeline."}}},{dir:_e(e,"node-c"),id:"demo-pi",name:"pi-office",port:o+2,agentId:"scout",agentName:"Scout",persona:"You are Scout, the monitoring agent on the office Raspberry Pi. You watch schedules and report status.",script:{fallback:{reply:"Scout here (demo script) \u2014 all monitors green on pi-office."},steps:[]}}]}function hf(e,o,t){let n=_e(e.dir,"workspaces",e.agentId);lf(n,{recursive:!0}),gs(_e(n,"CLAUDE.md"),`# ${e.agentName}
497
527
 
498
528
  ${e.persona}
499
- `),ms(De(e.dir,"demo-script.json"),JSON.stringify(e.script,null,2));let s=o.filter(r=>r.id!==e.id).map(r=>({name:r.name,url:`http://127.0.0.1:${r.port}`,token:t})),i={node:{id:e.id,name:e.name,bind:`127.0.0.1:${e.port}`,defaultAgent:e.agentId},dashboard:{enabled:!0,port:e.port+10,bind:"127.0.0.1",daemonUrl:`http://127.0.0.1:${e.port}`},providers:{demo:{apiKey:"demo-mode"}},agents:{[e.agentId]:{name:e.agentName,description:e.persona,workspace:"./workspaces/"+e.agentId,tier:"orchestrator",provider:"demo",mentions:[`@${e.agentId}`,e.agentId],maxConcurrent:2,systemPrompt:e.persona}},mesh:{enabled:!0,peers:s,discovery:"static",healthCheck:{interval:3,timeout:5}},workflows:{enabled:!0}};ms(De(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function Ii(e,o,t){let n=Date.now();for(;Date.now()-n<t;){try{if(await o())return}catch{}await new Promise(s=>setTimeout(s,500))}throw new Error(`Timed out waiting for ${e} (${Math.round(t/1e3)}s)`)}async function ji(e,o,t){let n=await fetch(`http://127.0.0.1:${e}${o}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),s=await n.json().catch(()=>({}));if(!n.ok||s.error)throw new Error(s.error||`${o} HTTP ${n.status}`);return s}function gs(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
529
+ `),gs(_e(e.dir,"demo-script.json"),JSON.stringify(e.script,null,2));let s=o.filter(r=>r.id!==e.id).map(r=>({name:r.name,url:`http://127.0.0.1:${r.port}`,token:t})),i={node:{id:e.id,name:e.name,bind:`127.0.0.1:${e.port}`,defaultAgent:e.agentId},dashboard:{enabled:!0,port:e.port+10,bind:"127.0.0.1",daemonUrl:`http://127.0.0.1:${e.port}`},providers:{demo:{apiKey:"demo-mode"}},agents:{[e.agentId]:{name:e.agentName,description:e.persona,workspace:"./workspaces/"+e.agentId,tier:"orchestrator",provider:"demo",mentions:[`@${e.agentId}`,e.agentId],maxConcurrent:2,systemPrompt:e.persona}},mesh:{enabled:!0,peers:s,discovery:"static",healthCheck:{interval:3,timeout:5}},workflows:{enabled:!0}};gs(_e(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function Ci(e,o,t){let n=Date.now();for(;Date.now()-n<t;){try{if(await o())return}catch{}await new Promise(s=>setTimeout(s,500))}throw new Error(`Timed out waiting for ${e} (${Math.round(t/1e3)}s)`)}async function Ni(e,o,t){let n=await fetch(`http://127.0.0.1:${e}${o}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),s=await n.json().catch(()=>({}));if(!n.ok||s.error)throw new Error(s.error||`${o} HTTP ${n.status}`);return s}function ds(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
500
530
  `).join(`
501
- `)}`)}var vl=new Bu().name("demo").description("zero-key demo: three daemons, a real A2A mesh, a scripted scenario").option("--base-port <port>","first of three consecutive loopback ports","18921").option("--once","play the scenario once and exit (default: keep daemons up until Ctrl-C)").option("--keep","keep the .agentx-demo directory on exit").option("--no-open","don't open the dashboard in a browser").option("--reuse","resume an existing .agentx-demo instead of starting fresh (implies --keep)").option("--bind <host>","dashboard bind address","127.0.0.1").action(async e=>{let o=parseInt(e.basePort,10),t=zu(process.cwd(),".agentx-demo"),n=Ku(t,o),s=De(t,"mesh-token"),i=!!e.reuse&&ds(s)&&ds(De(n[0].dir,"agentx.json")),r=i?Gu(s,"utf8").trim():Yu(24).toString("hex"),a=e.keep||e.reuse,c=[],d=process.argv[1];if((!d||!ds(d))&&(console.error(ie.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!i){if(ds(t))for(let f of Hu(t))bl(De(t,f),{recursive:!0,force:!0});for(let f of n)Xu(f,n,r);ms(s,r+`
502
- `,{mode:384})}console.log(),console.log(ie.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(ie.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(ie.dim(" Run `agentx setup` to wire real agents.\n"));let g=!1,l=f=>{if(!g){g=!0;for(let u of c)try{u.kill("SIGTERM")}catch{}setTimeout(()=>{if(!a)try{bl(t,{recursive:!0,force:!0})}catch{}process.exit(f)},800)}};process.on("SIGINT",()=>l(0)),process.on("SIGTERM",()=>l(0));let p={...process.env};delete p.ANTHROPIC_API_KEY,delete p.ANTHROPIC_API_KEY_OLD,delete p.OPENAI_API_KEY,delete p.DEEPSEEK_API_KEY;try{for(let y of n){let k=$l(De(y.dir,"daemon.log"),"a"),b=Ti(process.execPath,[d,"daemon","start","-c",De(y.dir,"agentx.json")],{cwd:y.dir,env:{...p,MESH_TOKEN:r,AGENTX_DEMO_SCRIPT:De(y.dir,"demo-script.json")},stdio:["ignore",k,k]});c.push(b),console.log(ie.dim(` \u25B8 ${y.name} starting on 127.0.0.1:${y.port} (log: ${De(y.dir,"daemon.log")})`))}for(let y of n)await Ii(`${y.name} /health`,async()=>(await fetch(`http://127.0.0.1:${y.port}/health`)).ok,3e4);console.log(ie.green(" \u2713 three daemons up"));let f=n[0].port+10;{let y=$l(De(n[0].dir,"board.log"),"a"),k=Ti(process.execPath,[d,"board","serve","--bind",e.bind],{cwd:n[0].dir,env:{...p,MESH_TOKEN:r},stdio:["ignore",y,y]});c.push(k)}await Ii("dashboard /live",async()=>(await fetch(`http://127.0.0.1:${f}/live`)).ok,3e4),console.log(ie.green(" \u2713 dashboard up")),await Ii("mesh discovery (laptop sees both peers)",async()=>((await(await fetch(`http://127.0.0.1:${n[0].port}/health`)).json()).mesh||[]).filter(x=>x.healthy&&x.skills?.length).length>=2,3e4),console.log(ie.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let u=`http://127.0.0.1:${f}/live`;if(console.log(),console.log(` Dashboard: ${ie.cyan(u)} (all three nodes via the mesh)`),console.log(ie.dim(` Daemon APIs: ${n.map(y=>`127.0.0.1:${y.port}`).join(" \xB7 ")}`)),e.open!==!1){let y=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{Ti(y,[u],{stdio:"ignore",detached:!0}).unref()}catch{}}let w=async()=>{console.log(),console.log(ie.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),gs("You \u2192 @cx (laptop-paris)",kl,ie.cyan);let y=await ji(n[0].port,"/task",{agent:"cx",message:kl});gs("@cx (laptop-paris)",y.content||"(no content)",ie.green),console.log(),console.log(ie.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let k=await ji(n[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:Vu}),b=typeof k.messageId=="string"?k.messageId:k.content||"(no reply)";gs("@builder (vps-nyc)",b,ie.yellow);let x=await ji(n[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${b}`});gs("@cx (laptop-paris)",x.content||"(no content)",ie.green),console.log(),console.log(ie.dim(` Inspect the run: ${u} \xB7 ledger rows on each node record every dispatch`)),console.log(ie.dim(` Worth your time? A star helps others find it: ${ie.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(i?console.log(ie.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await w(),e.once){console.log(),console.log(ie.dim(" --once: shutting down.")),l(0);return}console.log(),console.log(ie.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{w().catch(y=>console.error(ie.red(` Replay failed: ${y.message}`)))}),process.stdin.resume()}catch(f){console.error(),console.error(ie.red(` Demo failed: ${f.message}`)),console.error(ie.dim(` Node logs: ${n.map(u=>De(u.dir,"daemon.log")).join(", ")}`)),l(1)}});import{Command as Qu}from"commander";import{randomUUID as Zu}from"crypto";import{readFileSync as ef}from"fs";import{resolve as of}from"path";pe();var Sl=new Qu().name("exec").description("run one task through an agent and exit \u2014 for scripts and benchmarks").argument("[message]","the task (default: read from stdin)").requiredOption("-a, --agent <id>","agent id from the config").option("-c, --config <path>","config file (default: ./agentx.json)").option("-m, --model <model>","override the agent's model for this task").option("--timeout <minutes>","upper bound on the task's run time").option("--setup-workspace","write the managed workspace files first, as daemon boot does").option("--json","print one JSON result object instead of the reply text").action(async(e,o)=>{let t=(e??ef(0,"utf8")).trim();t||xl("no task given (pass it as an argument or on stdin)");let n=_(o.config?of(o.config):void 0),s=n.agents[o.agent];s||xl(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`);let i=(...d)=>console.error("[agentx exec]",...d);if(o.setupWorkspace){let d=n.node.bind.split(":")[1]||"19900";Vi(o.agent,s,d,i)}let r=new lr(n,i),a=Date.now(),c=await r.execute({agentId:o.agent,message:t,model:o.model,timeoutMinutes:o.timeout?Number(o.timeout):void 0,context:{channel:"exec",chatId:`exec-${Zu()}`,sender:"cli"}});o.json?process.stdout.write(JSON.stringify({content:c.content,error:c.error,errorKind:c.errorKind,usage:c.usage,numTurns:c.numTurns,billedModel:c.billedModel,durationMs:Date.now()-a})+`
531
+ `)}`)}var Ll=new cf().name("demo").description("zero-key demo: three daemons, a real A2A mesh, a scripted scenario").option("--base-port <port>","first of three consecutive loopback ports","18921").option("--once","play the scenario once and exit (default: keep daemons up until Ctrl-C)").option("--keep","keep the .agentx-demo directory on exit").option("--no-open","don't open the dashboard in a browser").option("--reuse","resume an existing .agentx-demo instead of starting fresh (implies --keep)").option("--bind <host>","dashboard bind address","127.0.0.1").action(async e=>{let o=parseInt(e.basePort,10),t=mf(process.cwd(),".agentx-demo"),n=ff(t,o),s=_e(t,"mesh-token"),i=!!e.reuse&&ls(s)&&ls(_e(n[0].dir,"agentx.json")),r=i?df(s,"utf8").trim():pf(24).toString("hex"),a=e.keep||e.reuse,c=[],l=process.argv[1];if((!l||!ls(l))&&(console.error(re.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!i){if(ls(t))for(let f of gf(t))_l(_e(t,f),{recursive:!0,force:!0});for(let f of n)hf(f,n,r);gs(s,r+`
532
+ `,{mode:384})}console.log(),console.log(re.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(re.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(re.dim(" Run `agentx setup` to wire real agents.\n"));let g=!1,d=f=>{if(!g){g=!0;for(let p of c)try{p.kill("SIGTERM")}catch{}setTimeout(()=>{if(!a)try{_l(t,{recursive:!0,force:!0})}catch{}process.exit(f)},800)}};process.on("SIGINT",()=>d(0)),process.on("SIGTERM",()=>d(0));let u={...process.env};delete u.ANTHROPIC_API_KEY,delete u.ANTHROPIC_API_KEY_OLD,delete u.OPENAI_API_KEY,delete u.DEEPSEEK_API_KEY;try{for(let y of n){let k=Pl(_e(y.dir,"daemon.log"),"a"),b=ji(process.execPath,[l,"daemon","start","-c",_e(y.dir,"agentx.json")],{cwd:y.dir,env:{...u,MESH_TOKEN:r,AGENTX_DEMO_SCRIPT:_e(y.dir,"demo-script.json")},stdio:["ignore",k,k]});c.push(b),console.log(re.dim(` \u25B8 ${y.name} starting on 127.0.0.1:${y.port} (log: ${_e(y.dir,"daemon.log")})`))}for(let y of n)await Ci(`${y.name} /health`,async()=>(await fetch(`http://127.0.0.1:${y.port}/health`)).ok,3e4);console.log(re.green(" \u2713 three daemons up"));let f=n[0].port+10;{let y=Pl(_e(n[0].dir,"board.log"),"a"),k=ji(process.execPath,[l,"board","serve","--bind",e.bind],{cwd:n[0].dir,env:{...u,MESH_TOKEN:r},stdio:["ignore",y,y]});c.push(k)}await Ci("dashboard /live",async()=>(await fetch(`http://127.0.0.1:${f}/live`)).ok,3e4),console.log(re.green(" \u2713 dashboard up")),await Ci("mesh discovery (laptop sees both peers)",async()=>((await(await fetch(`http://127.0.0.1:${n[0].port}/health`)).json()).mesh||[]).filter(S=>S.healthy&&S.skills?.length).length>=2,3e4),console.log(re.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let p=`http://127.0.0.1:${f}/live`;if(console.log(),console.log(` Dashboard: ${re.cyan(p)} (all three nodes via the mesh)`),console.log(re.dim(` Daemon APIs: ${n.map(y=>`127.0.0.1:${y.port}`).join(" \xB7 ")}`)),e.open!==!1){let y=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{ji(y,[p],{stdio:"ignore",detached:!0}).unref()}catch{}}let w=async()=>{console.log(),console.log(re.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),ds("You \u2192 @cx (laptop-paris)",Ml,re.cyan);let y=await Ni(n[0].port,"/task",{agent:"cx",message:Ml});ds("@cx (laptop-paris)",y.content||"(no content)",re.green),console.log(),console.log(re.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let k=await Ni(n[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:uf}),b=typeof k.messageId=="string"?k.messageId:k.content||"(no reply)";ds("@builder (vps-nyc)",b,re.yellow);let S=await Ni(n[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${b}`});ds("@cx (laptop-paris)",S.content||"(no content)",re.green),console.log(),console.log(re.dim(` Inspect the run: ${p} \xB7 ledger rows on each node record every dispatch`)),console.log(re.dim(` Worth your time? A star helps others find it: ${re.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(i?console.log(re.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await w(),e.once){console.log(),console.log(re.dim(" --once: shutting down.")),d(0);return}console.log(),console.log(re.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{w().catch(y=>console.error(re.red(` Replay failed: ${y.message}`)))}),process.stdin.resume()}catch(f){console.error(),console.error(re.red(` Demo failed: ${f.message}`)),console.error(re.dim(` Node logs: ${n.map(p=>_e(p.dir,"daemon.log")).join(", ")}`)),d(1)}});import{Command as yf}from"commander";import{randomUUID as wf}from"crypto";import{readFileSync as bf}from"fs";import{resolve as $f}from"path";ge();var Ul=new yf().name("exec").description("run one task through an agent and exit \u2014 for scripts and benchmarks").argument("[message]","the task (default: read from stdin)").requiredOption("-a, --agent <id>","agent id from the config").option("-c, --config <path>","config file (default: ./agentx.json)").option("-m, --model <model>","override the agent's model for this task").option("--timeout <minutes>","upper bound on the task's run time").option("--setup-workspace","write the managed workspace files first, as daemon boot does").option("--json","print one JSON result object instead of the reply text").action(async(e,o)=>{let t=(e??bf(0,"utf8")).trim();t||Fl("no task given (pass it as an argument or on stdin)");let n=_(o.config?$f(o.config):void 0),s=n.agents[o.agent];s||Fl(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`);let i=(...l)=>console.error("[agentx exec]",...l);if(o.setupWorkspace){let l=n.node.bind.split(":")[1]||"19900";Xi(o.agent,s,l,i)}let r=new mr(n,i),a=Date.now(),c=await r.execute({agentId:o.agent,message:t,model:o.model,timeoutMinutes:o.timeout?Number(o.timeout):void 0,context:{channel:"exec",chatId:`exec-${wf()}`,sender:"cli"}});o.json?process.stdout.write(JSON.stringify({content:c.content,error:c.error,errorKind:c.errorKind,usage:c.usage,numTurns:c.numTurns,billedModel:c.billedModel,durationMs:Date.now()-a})+`
503
533
  `):c.error?console.error(c.error):process.stdout.write(c.content+`
504
- `),process.exit(c.error?1:0)});function xl(e){console.error(`agentx exec: ${e}`),process.exit(1)}pe();import{Command as tf}from"commander";import Ae from"chalk";var Io=new tf().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Io.command("list-chats").description("list chats observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").option("--group","groups only").option("--dm","DMs only").action(async e=>{try{let t=(await sn("/whatsapp/chats")).chats??[];if(e.group&&(t=t.filter(n=>n.isGroup)),e.dm&&(t=t.filter(n=>!n.isGroup)),e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Ae.dim(" no chats cached yet"));return}console.log(),console.log(Ae.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?Ae.cyan("group"):Ae.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Ae.dim(n.jid.padEnd(40))} ${Ae.dim(i)}`)}console.log()}catch(o){St(o)}});Io.command("list-contacts").description("list contacts observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").action(async e=>{try{let t=(await sn("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Ae.dim(" no contacts cached yet"));return}console.log(),console.log(Ae.bold(` ${t.length} contact${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=(n.name||n.pushName||n.phone||n.jid).padEnd(30),i=n.phone?`+${n.phone}`.padEnd(16):"\u2014".padEnd(16);console.log(` ${s} ${Ae.dim(i)} ${Ae.dim(n.jid)}`)}console.log()}catch(o){St(o)}});Io.command("ingest-all").description("run a full ingest sweep against the configured allowlist (writes raw wiki entries)").option("--dry-run","compute entries without writing them \u2014 review before enabling").option("--agent <id>","owner agent for the entries (defaults to channels.whatsapp.defaultAgent)").option("--force","bypass the channels.whatsapp.ingest.enabled guard").action(async e=>{try{let o={dryRun:!!e.dryRun,force:!!e.force};e.agent&&(o.agent=e.agent);let t=await Ni("/whatsapp/ingest",o);Ci(t,!!e.dryRun)}catch(o){St(o)}});Io.command("ingest-contact <jid>").description("ingest one contact (skips scope allowlist for this JID only)").option("--dry-run","compute entries without writing them").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e,onlyKind:"contact"};o.agent&&(t.agent=o.agent);let n=await Ni("/whatsapp/ingest",t);Ci(n,!!o.dryRun)}catch(t){St(t)}});Io.command("ingest-chat <jid>").description("ingest one chat (DM or group) including message window if `--messages` is set").option("--dry-run","compute entries without writing them").option("--messages","include the bounded message window for this chat (overrides config mode)").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e};o.agent&&(t.agent=o.agent),o.messages&&(t.forceMode="messages");let n=await Ni("/whatsapp/ingest",t);Ci(n,!!o.dryRun)}catch(t){St(t)}});Io.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await sn("/whatsapp/state"),o=await sn("/whatsapp/chats"),t=await sn("/whatsapp/contacts");console.log(),console.log(Ae.bold(" WhatsApp status")),console.log(),console.log(` connection: ${e.connection||"\u2014"}`),console.log(` cached chats: ${o.chats?.length??0}`),console.log(` cached contacts: ${t.contacts?.length??0}`),console.log()}catch(e){St(e)}});function Ci(e,o){if(console.log(),console.log(Ae.bold(o?" Ingest (dry-run)":" Ingest report")),console.log(),console.log(` scanned: contacts=${e.scannedContacts}, groups=${e.scannedGroups}`),console.log(` wrote: contacts=${e.wroteContacts}, groups=${e.wroteGroups}, dm-windows=${e.wroteDmWindows}, group-windows=${e.wroteGroupWindows}`),e.skippedUnchanged&&console.log(` skipped: ${e.skippedUnchanged} unchanged`),e.errors?.length){console.log(Ae.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(Ae.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(Ae.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(Ae.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Ae.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function El(){try{let e=_(),[o,t]=e.node.bind.split(":");return`http://${o||"127.0.0.1"}:${t||"19900"}`}catch{return"http://127.0.0.1:19900"}}async function sn(e){let o=await fetch(`${El()}${e}`,{signal:AbortSignal.timeout(1e4)}),t=await o.json().catch(()=>({}));if(!o.ok)throw new Error(t.error||`HTTP ${o.status}`);return t}async function Ni(e,o){let t=await fetch(`${El()}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(6e5)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error(n.error||`HTTP ${t.status}`);return n}function St(e){console.error(Ae.red(` ${e.message||e}`)),process.exit(1)}pe();import{Command as nf}from"commander";import re from"chalk";import{existsSync as sf,mkdirSync as Al,writeFileSync as rn}from"fs";import{join as Et,resolve as rf}from"path";var an=new nf().name("plugin").description("manage agentx plugins (Move B)");an.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=_().plugins??[];if(console.log(),o.length===0){console.log(re.dim(" No plugins configured.")),console.log(re.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(re.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${re.cyan(t)}`);console.log(),console.log(re.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(re.red(` ${e.message}`)),process.exitCode=1}});an.command("init <name>").description("scaffold a new plugin package (npm-publishable, with manifest + setup hook)").option("--cwd <cwd>","directory to create the package under",process.cwd()).option("--description <text>","short package description").option("--force","overwrite an existing directory").action((e,o)=>{/^(@[a-z0-9-]+\/)?[a-z0-9][a-z0-9._-]*$/i.test(e)||(console.log(re.red(` invalid package name "${e}". Use lowercase letters, digits, hyphens; optional @scope/ prefix.`)),process.exit(1));let t=e.startsWith("@")?e.split("/")[1]:e,n=rf(o.cwd,t);sf(n)&&!o.force&&(console.log(re.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),Al(n,{recursive:!0}),Al(Et(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;rn(Et(n,"package.json"),df(e,s)),rn(Et(n,"tsconfig.json"),gf()),rn(Et(n,"src/index.ts"),mf(e)),rn(Et(n,"README.md"),pf(e,s)),rn(Et(n,".gitignore"),uf()),console.log(),console.log(re.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(re.bold(" Next steps:")),console.log(re.dim(` cd ${t}`)),console.log(re.dim(" pnpm install")),console.log(re.dim(" pnpm build")),console.log(re.dim(" pnpm link --global # for local testing")),console.log(re.dim(" # then in your agentx project:")),console.log(re.dim(` pnpm link --global ${e}`)),console.log(re.dim(` agentx config set plugins[0] "${e}"`)),console.log(re.dim(" agentx plugin doctor")),console.log()});an.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let o=_().plugins??[];if(console.log(),o.length===0){console.log(re.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await af(n);s.kind==="ok"?console.log(` ${re.green("\u2713")} ${re.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${re.red("\u2717")} ${re.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(re.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(re.red(` ${e.message}`)),process.exitCode=1}});async function af(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=cf(o);if(!lf(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=Sr.safeParse(t.manifest);return n.success?{kind:"ok",manifestName:n.data.name,manifestVersion:n.data.version}:{kind:"fail",reason:`manifest invalid: ${n.error.issues.map(i=>i.message).join("; ")}`}}function cf(e){if(e==null||typeof e!="object")return e;let o=e;if(o.default&&typeof o.default=="object"){let t=o.default;if(t.manifest&&typeof t.setup=="function")return t;if(t.default&&typeof t.default=="object"){let n=t.default;if(n.manifest&&typeof n.setup=="function")return n}}return o.manifest&&typeof o.setup=="function"?o:o.default??o}function lf(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function df(e,o){return JSON.stringify({name:e,version:"0.1.0",description:o,main:"dist/index.js",types:"dist/index.d.ts",files:["dist"],scripts:{build:"tsc",prepublishOnly:"pnpm build"},keywords:["agentx","agentx-plugin"],license:"MIT",devDependencies:{typescript:"^5.4.0","@types/node":"^20.0.0"}},null,2)+`
505
- `}function gf(){return JSON.stringify({compilerOptions:{target:"es2020",module:"commonjs",lib:["es2020"],declaration:!0,outDir:"dist",strict:!0,esModuleInterop:!0,skipLibCheck:!0,moduleResolution:"node"},include:["src/**/*.ts"]},null,2)+`
506
- `}function mf(e){return`// ${e} \u2014 AgentX plugin
534
+ `),process.exit(c.error?1:0)});function Fl(e){console.error(`agentx exec: ${e}`),process.exit(1)}ge();import{Command as kf}from"commander";import Oe from"chalk";var jo=new kf().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");jo.command("list-chats").description("list chats observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").option("--group","groups only").option("--dm","DMs only").action(async e=>{try{let t=(await an("/whatsapp/chats")).chats??[];if(e.group&&(t=t.filter(n=>n.isGroup)),e.dm&&(t=t.filter(n=>!n.isGroup)),e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Oe.dim(" no chats cached yet"));return}console.log(),console.log(Oe.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?Oe.cyan("group"):Oe.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Oe.dim(n.jid.padEnd(40))} ${Oe.dim(i)}`)}console.log()}catch(o){At(o)}});jo.command("list-contacts").description("list contacts observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").action(async e=>{try{let t=(await an("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Oe.dim(" no contacts cached yet"));return}console.log(),console.log(Oe.bold(` ${t.length} contact${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=(n.name||n.pushName||n.phone||n.jid).padEnd(30),i=n.phone?`+${n.phone}`.padEnd(16):"\u2014".padEnd(16);console.log(` ${s} ${Oe.dim(i)} ${Oe.dim(n.jid)}`)}console.log()}catch(o){At(o)}});jo.command("ingest-all").description("run a full ingest sweep against the configured allowlist (writes raw wiki entries)").option("--dry-run","compute entries without writing them \u2014 review before enabling").option("--agent <id>","owner agent for the entries (defaults to channels.whatsapp.defaultAgent)").option("--force","bypass the channels.whatsapp.ingest.enabled guard").action(async e=>{try{let o={dryRun:!!e.dryRun,force:!!e.force};e.agent&&(o.agent=e.agent);let t=await Di("/whatsapp/ingest",o);Ri(t,!!e.dryRun)}catch(o){At(o)}});jo.command("ingest-contact <jid>").description("ingest one contact (skips scope allowlist for this JID only)").option("--dry-run","compute entries without writing them").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e,onlyKind:"contact"};o.agent&&(t.agent=o.agent);let n=await Di("/whatsapp/ingest",t);Ri(n,!!o.dryRun)}catch(t){At(t)}});jo.command("ingest-chat <jid>").description("ingest one chat (DM or group) including message window if `--messages` is set").option("--dry-run","compute entries without writing them").option("--messages","include the bounded message window for this chat (overrides config mode)").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e};o.agent&&(t.agent=o.agent),o.messages&&(t.forceMode="messages");let n=await Di("/whatsapp/ingest",t);Ri(n,!!o.dryRun)}catch(t){At(t)}});jo.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await an("/whatsapp/state"),o=await an("/whatsapp/chats"),t=await an("/whatsapp/contacts");console.log(),console.log(Oe.bold(" WhatsApp status")),console.log(),console.log(` connection: ${e.connection||"\u2014"}`),console.log(` cached chats: ${o.chats?.length??0}`),console.log(` cached contacts: ${t.contacts?.length??0}`),console.log()}catch(e){At(e)}});function Ri(e,o){if(console.log(),console.log(Oe.bold(o?" Ingest (dry-run)":" Ingest report")),console.log(),console.log(` scanned: contacts=${e.scannedContacts}, groups=${e.scannedGroups}`),console.log(` wrote: contacts=${e.wroteContacts}, groups=${e.wroteGroups}, dm-windows=${e.wroteDmWindows}, group-windows=${e.wroteGroupWindows}`),e.skippedUnchanged&&console.log(` skipped: ${e.skippedUnchanged} unchanged`),e.errors?.length){console.log(Oe.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(Oe.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(Oe.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(Oe.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Oe.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function ql(){try{let e=_(),[o,t]=e.node.bind.split(":");return`http://${o||"127.0.0.1"}:${t||"19900"}`}catch{return"http://127.0.0.1:19900"}}async function an(e){let o=await fetch(`${ql()}${e}`,{signal:AbortSignal.timeout(1e4)}),t=await o.json().catch(()=>({}));if(!o.ok)throw new Error(t.error||`HTTP ${o.status}`);return t}async function Di(e,o){let t=await fetch(`${ql()}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(6e5)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error(n.error||`HTTP ${t.status}`);return n}function At(e){console.error(Oe.red(` ${e.message||e}`)),process.exit(1)}ge();import{Command as vf}from"commander";import ae from"chalk";import{existsSync as xf,mkdirSync as Wl,writeFileSync as cn}from"fs";import{join as Ot,resolve as Sf}from"path";var ln=new vf().name("plugin").description("manage agentx plugins (Move B)");ln.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=_().plugins??[];if(console.log(),o.length===0){console.log(ae.dim(" No plugins configured.")),console.log(ae.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(ae.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${ae.cyan(t)}`);console.log(),console.log(ae.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(ae.red(` ${e.message}`)),process.exitCode=1}});ln.command("init <name>").description("scaffold a new plugin package (npm-publishable, with manifest + setup hook)").option("--cwd <cwd>","directory to create the package under",process.cwd()).option("--description <text>","short package description").option("--force","overwrite an existing directory").action((e,o)=>{/^(@[a-z0-9-]+\/)?[a-z0-9][a-z0-9._-]*$/i.test(e)||(console.log(ae.red(` invalid package name "${e}". Use lowercase letters, digits, hyphens; optional @scope/ prefix.`)),process.exit(1));let t=e.startsWith("@")?e.split("/")[1]:e,n=Sf(o.cwd,t);xf(n)&&!o.force&&(console.log(ae.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),Wl(n,{recursive:!0}),Wl(Ot(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;cn(Ot(n,"package.json"),Tf(e,s)),cn(Ot(n,"tsconfig.json"),If()),cn(Ot(n,"src/index.ts"),jf(e)),cn(Ot(n,"README.md"),Cf(e,s)),cn(Ot(n,".gitignore"),Nf()),console.log(),console.log(ae.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(ae.bold(" Next steps:")),console.log(ae.dim(` cd ${t}`)),console.log(ae.dim(" pnpm install")),console.log(ae.dim(" pnpm build")),console.log(ae.dim(" pnpm link --global # for local testing")),console.log(ae.dim(" # then in your agentx project:")),console.log(ae.dim(` pnpm link --global ${e}`)),console.log(ae.dim(` agentx config set plugins[0] "${e}"`)),console.log(ae.dim(" agentx plugin doctor")),console.log()});ln.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let o=_().plugins??[];if(console.log(),o.length===0){console.log(ae.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await Ef(n);s.kind==="ok"?console.log(` ${ae.green("\u2713")} ${ae.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${ae.red("\u2717")} ${ae.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(ae.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(ae.red(` ${e.message}`)),process.exitCode=1}});async function Ef(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=Af(o);if(!Of(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=qr.safeParse(t.manifest);return n.success?{kind:"ok",manifestName:n.data.name,manifestVersion:n.data.version}:{kind:"fail",reason:`manifest invalid: ${n.error.issues.map(i=>i.message).join("; ")}`}}function Af(e){if(e==null||typeof e!="object")return e;let o=e;if(o.default&&typeof o.default=="object"){let t=o.default;if(t.manifest&&typeof t.setup=="function")return t;if(t.default&&typeof t.default=="object"){let n=t.default;if(n.manifest&&typeof n.setup=="function")return n}}return o.manifest&&typeof o.setup=="function"?o:o.default??o}function Of(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function Tf(e,o){return JSON.stringify({name:e,version:"0.1.0",description:o,main:"dist/index.js",types:"dist/index.d.ts",files:["dist"],scripts:{build:"tsc",prepublishOnly:"pnpm build"},keywords:["agentx","agentx-plugin"],license:"MIT",devDependencies:{typescript:"^5.4.0","@types/node":"^20.0.0"}},null,2)+`
535
+ `}function If(){return JSON.stringify({compilerOptions:{target:"es2020",module:"commonjs",lib:["es2020"],declaration:!0,outDir:"dist",strict:!0,esModuleInterop:!0,skipLibCheck:!0,moduleResolution:"node"},include:["src/**/*.ts"]},null,2)+`
536
+ `}function jf(e){return`// ${e} \u2014 AgentX plugin
507
537
  //
508
538
  // A plugin's default export is { manifest, setup }. The daemon calls
509
539
  // setup(ctx) once at boot. ctx.on() subscribes to the bus; ctx.addChannel()
@@ -539,7 +569,7 @@ const plugin = {
539
569
  }
540
570
 
541
571
  export default plugin
542
- `}function pf(e,o){return`# ${e}
572
+ `}function Cf(e,o){return`# ${e}
543
573
 
544
574
  ${o}
545
575
 
@@ -566,19 +596,19 @@ agentx plugin doctor
566
596
  \`\`\`
567
597
 
568
598
  Restart the daemon to activate.
569
- `}function uf(){return`node_modules/
599
+ `}function Nf(){return`node_modules/
570
600
  dist/
571
601
  *.log
572
602
  .env
573
- `}import{Command as ff}from"commander";import Oe from"chalk";import{writeFileSync as hf,mkdirSync as yf,existsSync as ps,readFileSync as Ol,appendFileSync as Tl}from"fs";import{resolve as At,dirname as Cl}from"path";import{homedir as Di}from"os";var Nl=new ff().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:o}=await import("./program-LAACUZWW.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=$f(t);break;case"bash":s=Ef(t);break;case"fish":s=Af(t);break;default:console.error(Oe.red(`unsupported shell: ${n}`)),console.error(Oe.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?At(String(e.output)):wf(n);yf(Cl(i),{recursive:!0}),hf(i,s),console.log(Oe.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),bf(n,i,!!e.yes)});function wf(e){let o=Di();switch(e){case"zsh":return At(o,".zsh","completions","_agentx");case"bash":return At(o,".bash_completion.d","agentx.bash");case"fish":return At(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function bf(e,o,t){if(e==="zsh"){let n=At(Di(),".zshrc"),s=Cl(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=ps(n)?Ol(n,"utf-8"):"",c=!a.includes(s),d=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!d){console.log(Oe.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&ps(n)){let g=["","# agentx completion"];c&&g.push(i),d&&g.push(r),Tl(n,g.join(`
603
+ `}import{Command as Rf}from"commander";import Te from"chalk";import{writeFileSync as Df,mkdirSync as _f,existsSync as ms,readFileSync as Bl,appendFileSync as Jl}from"fs";import{resolve as Tt,dirname as zl}from"path";import{homedir as Pi}from"os";var Yl=new Rf().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:o}=await import("./program-HGI5C2MP.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Lf(t);break;case"bash":s=Bf(t);break;case"fish":s=Jf(t);break;default:console.error(Te.red(`unsupported shell: ${n}`)),console.error(Te.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?Tt(String(e.output)):Pf(n);_f(zl(i),{recursive:!0}),Df(i,s),console.log(Te.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Mf(n,i,!!e.yes)});function Pf(e){let o=Pi();switch(e){case"zsh":return Tt(o,".zsh","completions","_agentx");case"bash":return Tt(o,".bash_completion.d","agentx.bash");case"fish":return Tt(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Mf(e,o,t){if(e==="zsh"){let n=Tt(Pi(),".zshrc"),s=zl(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=ms(n)?Bl(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Te.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&ms(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Jl(n,g.join(`
574
604
  `)+`
575
- `),console.log(Oe.green("\u2713 Patched ~/.zshrc")),console.log(Oe.dim("Reload your shell: exec zsh"));return}console.log(Oe.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Oe.cyan(` ${i}`)),d&&console.log(Oe.cyan(` ${r}`)),console.log(),console.log(Oe.dim("Then reload: exec zsh")),console.log(Oe.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=At(Di(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((ps(n)?Ol(n,"utf-8"):"").includes(o)){console.log(Oe.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&ps(n)){Tl(n,`
605
+ `),console.log(Te.green("\u2713 Patched ~/.zshrc")),console.log(Te.dim("Reload your shell: exec zsh"));return}console.log(Te.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Te.cyan(` ${i}`)),l&&console.log(Te.cyan(` ${r}`)),console.log(),console.log(Te.dim("Then reload: exec zsh")),console.log(Te.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Tt(Pi(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((ms(n)?Bl(n,"utf-8"):"").includes(o)){console.log(Te.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&ms(n)){Jl(n,`
576
606
  # agentx completion
577
607
  ${s}
578
- `),console.log(Oe.green("\u2713 Patched ~/.bashrc")),console.log(Oe.dim("Reload your shell: exec bash"));return}console.log(Oe.dim("Add this to ~/.bashrc:")),console.log(Oe.cyan(` ${s}`)),console.log(),console.log(Oe.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(Oe.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function Ue(e){return e._name||e.name()||""}function jo(e){return e.commands.filter(o=>{let t=Ue(o);return!(!t||t==="help")})}function cn(e){return e.options.filter(o=>!o.hidden)}function $f(e){let o=[];return o.push("#compdef agentx"),o.push(""),Rl(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
579
- `)}function Il(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function Rl(e,o,t){let n=jo(e),i=cn(e).map(xf).filter(c=>!!c),r=Il(o);if(t.push(`${r}() {`),t.push(" local -a commands"),t.push(" local -a options"),t.push(" "),i.length===0&&n.length===0){t.push(" return 0"),t.push("}"),t.push("");return}let a=[];for(let c of i)a.push(c);if(n.length>0){let c=n.map(Sf).join(" ");a.push(` "1: :_values 'command' ${c}"`),a.push(' "*::arg:->args"')}t.push(" _arguments -C \\");for(let c=0;c<a.length;c++){let d=c===a.length-1;t.push(`${a[c]}${d?"":" \\"}`)}if(n.length>0){t.push(""),t.push(" case $state in"),t.push(" (args)"),t.push(" case $line[1] in");for(let c of n){let d=Il([...o,Ue(c)]);t.push(` (${Ue(c)}) ${d} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)Rl(c,[...o,Ue(c)],t)}function kf(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function vf(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function xf(e){let o=e.short||void 0,t=e.long||void 0;if(!o&&!t)return null;let n=kf(e.description||"");return o&&t?` "(${t} ${o})"{${t},${o}}"[${n}]"`:` "${t||o}[${n}]"`}function Sf(e){let o=vf(e.description()||"");return`'${Ue(e)}[${o}]'`}function Ef(e){let o=jo(e),t=[];t.push("# bash completion for agentx"),t.push("_agentx_complete() {"),t.push(" local cur prev words cword"),t.push(" COMPREPLY=()"),t.push(' cur="${COMP_WORDS[COMP_CWORD]}"'),t.push(' prev="${COMP_WORDS[COMP_CWORD-1]}"'),t.push(""),t.push(` local top="${o.map(Ue).join(" ")}"`),t.push(""),t.push(" if [[ $COMP_CWORD -eq 1 ]]; then"),t.push(' COMPREPLY=( $(compgen -W "$top" -- "$cur") )'),t.push(" return 0"),t.push(" fi"),t.push(""),t.push(' local cmd="${COMP_WORDS[1]}"'),t.push(' local sub2="${COMP_WORDS[2]:-}"'),t.push(' case "$cmd" in');for(let n of o){let s=jo(n).map(Ue),i=jl(n);if(t.push(` ${Ue(n)})`),s.length>0){t.push(" if [[ $COMP_CWORD -eq 2 ]]; then"),t.push(` COMPREPLY=( $(compgen -W "${s.join(" ")} ${i}" -- "$cur") )`),t.push(" return 0"),t.push(" fi"),t.push(' case "$sub2" in');for(let r of jo(n)){let a=jl(r);t.push(` ${Ue(r)})`),t.push(` COMPREPLY=( $(compgen -W "${a}" -- "$cur") )`),t.push(" return 0"),t.push(" ;;")}t.push(" esac")}else t.push(` COMPREPLY=( $(compgen -W "${i}" -- "$cur") )`);t.push(" ;;")}return t.push(" esac"),t.push("}"),t.push(""),t.push("complete -F _agentx_complete agentx"),t.push(""),t.join(`
580
- `)}function jl(e){let o=[];for(let t of cn(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function Af(e){let o=[];o.push("# fish completion for agentx"),o.push(""),o.push("complete -c agentx -f"),o.push(""),o.push("# top-level commands");for(let t of jo(e)){let n=_i(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${Ue(t)}" -d "${n}"`)}o.push("");for(let t of cn(e)){let n=Ri(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of jo(e)){let n=Ue(t);o.push(`# ${n}`);for(let s of cn(t)){let i=Ri(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of jo(t)){let i=_i(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${jo(t).map(Ue).join(" ")}" -a "${Ue(s)}" -d "${i}"`);for(let r of cn(s)){let a=Ri(r,[`__fish_seen_subcommand_from ${Ue(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
581
- `)}function _i(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Ri(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=_i(e.description||""),r=["complete -c agentx",o.map(a=>`-n "${a}"`).join(" ")];return t&&r.push(`-s ${t}`),n&&r.push(`-l ${n}`),r.push(`-d "${s}"`),r.join(" ")}async function tS(){let e=await Vr(),o=new Of().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");o.hook("preAction",(t,n)=>{let s=Zr(n);ea(s)&&Qr("cli",s)});for(let t of[xa,$a,ht,it,Ze,Xr,_o,Nn,Eo,Wo,Cn,ml,xo,Da,Ba,Za,tc,nc,yc,kc,vc,zn,Qt,yl,Ft,bo,Nl])o.addCommand(t);for(let t of Dl)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Dl.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Tf(t,74," "),""].join(`
582
- `)}),o}var Dl=[ee,yt,zo,Xe,qt,pt,Fe,mo,Ao,Bo,kt,vt,vo,Pe,Wt,Yn,dl,lo,lt,sa,Po,an,Ms,To,ct,Fs,rs,xt,Io,vl,Sl,hl];function Tf(e,o,t){let n=[],s="";for(let i of e)s&&s.length+i.length+2>o&&(n.push(t+s),s=""),s+=(s?", ":"")+i;return s&&n.push(t+s),n.join(`
583
- `)}export{tS as a};
584
- //# sourceMappingURL=chunk-2IYOKDVI.js.map
608
+ `),console.log(Te.green("\u2713 Patched ~/.bashrc")),console.log(Te.dim("Reload your shell: exec bash"));return}console.log(Te.dim("Add this to ~/.bashrc:")),console.log(Te.cyan(` ${s}`)),console.log(),console.log(Te.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(Te.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function We(e){return e._name||e.name()||""}function Co(e){return e.commands.filter(o=>{let t=We(o);return!(!t||t==="help")})}function dn(e){return e.options.filter(o=>!o.hidden)}function Lf(e){let o=[];return o.push("#compdef agentx"),o.push(""),Vl(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
609
+ `)}function Gl(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function Vl(e,o,t){let n=Co(e),i=dn(e).map(qf).filter(c=>!!c),r=Gl(o);if(t.push(`${r}() {`),t.push(" local -a commands"),t.push(" local -a options"),t.push(" "),i.length===0&&n.length===0){t.push(" return 0"),t.push("}"),t.push("");return}let a=[];for(let c of i)a.push(c);if(n.length>0){let c=n.map(Wf).join(" ");a.push(` "1: :_values 'command' ${c}"`),a.push(' "*::arg:->args"')}t.push(" _arguments -C \\");for(let c=0;c<a.length;c++){let l=c===a.length-1;t.push(`${a[c]}${l?"":" \\"}`)}if(n.length>0){t.push(""),t.push(" case $state in"),t.push(" (args)"),t.push(" case $line[1] in");for(let c of n){let l=Gl([...o,We(c)]);t.push(` (${We(c)}) ${l} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)Vl(c,[...o,We(c)],t)}function Ff(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Uf(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function qf(e){let o=e.short||void 0,t=e.long||void 0;if(!o&&!t)return null;let n=Ff(e.description||"");return o&&t?` "(${t} ${o})"{${t},${o}}"[${n}]"`:` "${t||o}[${n}]"`}function Wf(e){let o=Uf(e.description()||"");return`'${We(e)}[${o}]'`}function Bf(e){let o=Co(e),t=[];t.push("# bash completion for agentx"),t.push("_agentx_complete() {"),t.push(" local cur prev words cword"),t.push(" COMPREPLY=()"),t.push(' cur="${COMP_WORDS[COMP_CWORD]}"'),t.push(' prev="${COMP_WORDS[COMP_CWORD-1]}"'),t.push(""),t.push(` local top="${o.map(We).join(" ")}"`),t.push(""),t.push(" if [[ $COMP_CWORD -eq 1 ]]; then"),t.push(' COMPREPLY=( $(compgen -W "$top" -- "$cur") )'),t.push(" return 0"),t.push(" fi"),t.push(""),t.push(' local cmd="${COMP_WORDS[1]}"'),t.push(' local sub2="${COMP_WORDS[2]:-}"'),t.push(' case "$cmd" in');for(let n of o){let s=Co(n).map(We),i=Hl(n);if(t.push(` ${We(n)})`),s.length>0){t.push(" if [[ $COMP_CWORD -eq 2 ]]; then"),t.push(` COMPREPLY=( $(compgen -W "${s.join(" ")} ${i}" -- "$cur") )`),t.push(" return 0"),t.push(" fi"),t.push(' case "$sub2" in');for(let r of Co(n)){let a=Hl(r);t.push(` ${We(r)})`),t.push(` COMPREPLY=( $(compgen -W "${a}" -- "$cur") )`),t.push(" return 0"),t.push(" ;;")}t.push(" esac")}else t.push(` COMPREPLY=( $(compgen -W "${i}" -- "$cur") )`);t.push(" ;;")}return t.push(" esac"),t.push("}"),t.push(""),t.push("complete -F _agentx_complete agentx"),t.push(""),t.join(`
610
+ `)}function Hl(e){let o=[];for(let t of dn(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function Jf(e){let o=[];o.push("# fish completion for agentx"),o.push(""),o.push("complete -c agentx -f"),o.push(""),o.push("# top-level commands");for(let t of Co(e)){let n=Mi(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${We(t)}" -d "${n}"`)}o.push("");for(let t of dn(e)){let n=_i(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of Co(e)){let n=We(t);o.push(`# ${n}`);for(let s of dn(t)){let i=_i(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of Co(t)){let i=Mi(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${Co(t).map(We).join(" ")}" -a "${We(s)}" -d "${i}"`);for(let r of dn(s)){let a=_i(r,[`__fish_seen_subcommand_from ${We(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
611
+ `)}function Mi(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function _i(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=Mi(e.description||""),r=["complete -c agentx",o.map(a=>`-n "${a}"`).join(" ")];return t&&r.push(`-s ${t}`),n&&r.push(`-l ${n}`),r.push(`-d "${s}"`),r.join(" ")}async function xS(){let e=await ca(),o=new Gf().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");o.hook("preAction",(t,n)=>{let s=ma(n);pa(s)&&ga("cli",s)});for(let t of[Ma,Da,bt,at,eo,da,Po,_n,go,Jo,Dn,Tl,So,Ya,nc,pc,hc,yc,Dc,Lc,Fc,Yn,Zt,Rl,qt,$o,Yl])o.addCommand(t);for(let t of Kl)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Kl.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Hf(t,74," "),""].join(`
612
+ `)}),o}var Kl=[ee,$t,Vo,Qe,Bt,ht,qe,po,Ao,Go,St,Et,xo,Le,Jt,Vn,Al,co,gt,wa,Mo,ln,Us,Io,dt,qs,is,Oo,jo,Ll,Ul,Nl];function Hf(e,o,t){let n=[],s="";for(let i of e)s&&s.length+i.length+2>o&&(n.push(t+s),s=""),s+=(s?", ":"")+i;return s&&n.push(t+s),n.join(`
613
+ `)}export{xS as a};
614
+ //# sourceMappingURL=chunk-Q3Q6FTFY.js.map