agentix-cli 0.69.0 → 0.69.2
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.
- package/dist/{agent-VQIC7O5T.js → agent-P2UO35ZW.js} +2 -2
- package/dist/{board-dashboard-ZPJHXX3U.js → board-dashboard-3WVKEGRZ.js} +6 -5
- package/dist/{board-dashboard-ZPJHXX3U.js.map → board-dashboard-3WVKEGRZ.js.map} +1 -1
- package/dist/{chunk-ART666G6.js → chunk-2V7IQUEA.js} +2 -2
- package/dist/{chunk-PNWNVOEZ.js → chunk-4DRNEOOW.js} +2 -2
- package/dist/{chunk-NVJHA63C.js → chunk-4UMYRIEI.js} +10 -10
- package/dist/chunk-4UMYRIEI.js.map +1 -0
- package/dist/{chunk-HEJOWP7O.js → chunk-56AQBWEJ.js} +2 -2
- package/dist/{chunk-JHWBCDD2.js → chunk-A5ZCMRB3.js} +12 -9
- package/dist/chunk-A5ZCMRB3.js.map +1 -0
- package/dist/{chunk-BYKF3UTL.js → chunk-AIV547JW.js} +2 -2
- package/dist/chunk-ILEC3IAV.js +3 -0
- package/dist/chunk-ILEC3IAV.js.map +1 -0
- package/dist/{chunk-B65FS265.js → chunk-JSF2THM4.js} +2 -2
- package/dist/chunk-KA2UIZXG.js +3 -0
- package/dist/chunk-KA2UIZXG.js.map +1 -0
- package/dist/chunk-KXR6GVL7.js +5 -0
- package/dist/chunk-KXR6GVL7.js.map +1 -0
- package/dist/{chunk-QDRAKJSY.js → chunk-L2K4N3DA.js} +4 -4
- package/dist/chunk-M6HJDSLS.js +109 -0
- package/dist/chunk-M6HJDSLS.js.map +1 -0
- package/dist/{chunk-4NXIJEYU.js → chunk-U3XQ7USK.js} +9 -9
- package/dist/{chunk-4NXIJEYU.js.map → chunk-U3XQ7USK.js.map} +1 -1
- package/dist/{chunk-S4ASFOJU.js → chunk-VXDM7JAT.js} +2 -2
- package/dist/{chunk-5AMQFDLE.js → chunk-X4FD5OBK.js} +63 -63
- package/dist/{chunk-5AMQFDLE.js.map → chunk-X4FD5OBK.js.map} +1 -1
- package/dist/{chunk-NEC4RXFT.js → chunk-XMW422NO.js} +2 -2
- package/dist/{chunk-LPWPFEIE.js → chunk-YBLITM6C.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/fact-proposals-LZWS5KFO.js +2 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +1 -1
- package/dist/ledger-CH7R756S.js +2 -0
- package/dist/{migrate-v2-5VGHWPBW.js → migrate-v2-KOMPDC6U.js} +2 -2
- package/dist/{program-6PFRDQFT.js → program-GUBHJFZS.js} +2 -2
- package/dist/{promote-XRKH73IB.js → promote-7FMPZKXN.js} +2 -2
- package/dist/questions-ZATLU5AW.js +2 -0
- package/dist/{registry-KP3C4EZ4.js → registry-MUMQPZDM.js} +2 -2
- package/dist/{rotation-memo-store-X63HYIMV.js → rotation-memo-store-A4YW6FSK.js} +2 -2
- package/dist/{schedule-tool-ZVKBZOVG.js → schedule-tool-BY72YNNU.js} +2 -2
- package/dist/{scheduler-5NBO3J2G.js → scheduler-XWYFGG2S.js} +2 -2
- package/dist/{tool-ZENVUVBO.js → tool-ZUGNQZGI.js} +2 -2
- package/dist/{wiki-W6WI6HL3.js → wiki-LLL7VWRJ.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-AU6FFC4I.js +0 -5
- package/dist/chunk-AU6FFC4I.js.map +0 -1
- package/dist/chunk-CUZWGTXT.js +0 -109
- package/dist/chunk-CUZWGTXT.js.map +0 -1
- package/dist/chunk-JHWBCDD2.js.map +0 -1
- package/dist/chunk-NVJHA63C.js.map +0 -1
- package/dist/chunk-ST6KPQOY.js +0 -3
- package/dist/chunk-ST6KPQOY.js.map +0 -1
- package/dist/chunk-ZXR6GNEK.js +0 -3
- package/dist/chunk-ZXR6GNEK.js.map +0 -1
- package/dist/fact-proposals-ERRQXV2J.js +0 -2
- package/dist/ledger-DHYRP4TN.js +0 -2
- package/dist/questions-QGITDLJY.js +0 -2
- /package/dist/{agent-VQIC7O5T.js.map → agent-P2UO35ZW.js.map} +0 -0
- /package/dist/{chunk-ART666G6.js.map → chunk-2V7IQUEA.js.map} +0 -0
- /package/dist/{chunk-PNWNVOEZ.js.map → chunk-4DRNEOOW.js.map} +0 -0
- /package/dist/{chunk-HEJOWP7O.js.map → chunk-56AQBWEJ.js.map} +0 -0
- /package/dist/{chunk-BYKF3UTL.js.map → chunk-AIV547JW.js.map} +0 -0
- /package/dist/{chunk-B65FS265.js.map → chunk-JSF2THM4.js.map} +0 -0
- /package/dist/{chunk-QDRAKJSY.js.map → chunk-L2K4N3DA.js.map} +0 -0
- /package/dist/{chunk-S4ASFOJU.js.map → chunk-VXDM7JAT.js.map} +0 -0
- /package/dist/{chunk-NEC4RXFT.js.map → chunk-XMW422NO.js.map} +0 -0
- /package/dist/{chunk-LPWPFEIE.js.map → chunk-YBLITM6C.js.map} +0 -0
- /package/dist/{fact-proposals-ERRQXV2J.js.map → fact-proposals-LZWS5KFO.js.map} +0 -0
- /package/dist/{ledger-DHYRP4TN.js.map → ledger-CH7R756S.js.map} +0 -0
- /package/dist/{migrate-v2-5VGHWPBW.js.map → migrate-v2-KOMPDC6U.js.map} +0 -0
- /package/dist/{program-6PFRDQFT.js.map → program-GUBHJFZS.js.map} +0 -0
- /package/dist/{promote-XRKH73IB.js.map → promote-7FMPZKXN.js.map} +0 -0
- /package/dist/{questions-QGITDLJY.js.map → questions-ZATLU5AW.js.map} +0 -0
- /package/dist/{registry-KP3C4EZ4.js.map → registry-MUMQPZDM.js.map} +0 -0
- /package/dist/{rotation-memo-store-X63HYIMV.js.map → rotation-memo-store-A4YW6FSK.js.map} +0 -0
- /package/dist/{schedule-tool-ZVKBZOVG.js.map → schedule-tool-BY72YNNU.js.map} +0 -0
- /package/dist/{scheduler-5NBO3J2G.js.map → scheduler-XWYFGG2S.js.map} +0 -0
- /package/dist/{tool-ZENVUVBO.js.map → tool-ZUGNQZGI.js.map} +0 -0
- /package/dist/{wiki-W6WI6HL3.js.map → wiki-LLL7VWRJ.js.map} +0 -0
|
@@ -1,42 +1,42 @@
|
|
|
1
|
-
import{a as Gc,b as Zn,g as zc}from"./chunk-G3SOCQII.js";import{a as Mc,c as Lc}from"./chunk-APKKQGTG.js";import{a as ct,b as Rc,f as _c,g as Dc,h as Pc,i as Qn,j as Fc,k as Uc,l as hi,m as Jc,o as Hc}from"./chunk-
|
|
1
|
+
import{a as Gc,b as Zn,g as zc}from"./chunk-G3SOCQII.js";import{a as Mc,c as Lc}from"./chunk-APKKQGTG.js";import{a as ct,b as Rc,f as _c,g as Dc,h as Pc,i as Qn,j as Fc,k as Uc,l as hi,m as Jc,o as Hc}from"./chunk-56AQBWEJ.js";import{a as qc,c as Wc,d as Bc}from"./chunk-Z3IP66SL.js";import{a as ni,b as ma}from"./chunk-RKPAVWXF.js";import{a as ho}from"./chunk-GV7S5BAX.js";import{e as oa}from"./chunk-GSX4NK2N.js";import{c as na}from"./chunk-SZDACK6O.js";import{$ as Cc,A as ri,B as cc,C as lc,D as dc,E as gc,F as mc,G as pc,H as wc,I as bc,J as wo,K as Yn,L as di,M as $c,N as kc,O as vc,P as xc,Q as bo,R as $o,S as Sc,T as Ec,U as Re,V as Vn,W as an,X as gi,Y as Ac,Z as Tc,_ as ui,a as $a,aa as Kn,b as ka,ba as ko,ca as Xn,da as fi,ea as Nc,h as Un,i as Ea,j as nn,k as qn,l as Oa,m as Ta,n as Ia,o as Ca,p as Ba,q as Ja,r as Hn,s as ii,t as Va,u as ec,v as nc,w as sc,x as ic,y as rc,z as ac}from"./chunk-U3XQ7USK.js";import{A as Qa,B as Za,Ma as at,N as sn,Oa as Ic,P as ai,Q as Gn,R as uc,ba as Et,ca as fc,da as ci,fa as li,ha as hc,ia as yc,ja as rn,m as St,na as zn,q as Ka,t as Xa,va as jc,wa as mi,xa as Oc,ya as pi}from"./chunk-JSF2THM4.js";import{a as Wn,b as Bn,c as Na,d as Ra,e as _a,g as Da,h as Pa,j as Ma,k as La,l as Fa,m as Ua,p as Jn,r as qa,s as Wa}from"./chunk-BYJ3A55Y.js";import{a as va,d as xa,e as Sa}from"./chunk-F2DEKA2Q.js";import{a as Aa,p as ja}from"./chunk-2V7IQUEA.js";import{a as Ha,b as Ga,c as za,d as Ya}from"./chunk-2D3RYIDU.js";import{a as tc,b as oc}from"./chunk-L53FTKEP.js";import{B as xt,H as da,S as ga,h as Vr,q as Kr,v as ei,w as ea}from"./chunk-L2K4N3DA.js";import{b as mo,g as uo,h as Ln,i as Fn,j as fo,k as ta,l as Ht,m as on}from"./chunk-4UMYRIEI.js";import{a as Yr}from"./chunk-N6EWZGIX.js";import{e as aa,f as oi,k as ca}from"./chunk-WP6KLXTP.js";import{b as po}from"./chunk-DP7RTNDM.js";import{a as si,e as pa,f as ua,h as fa,i as ha,k as ya,l as wa,m as ba}from"./chunk-XMW422NO.js";import{f as sa,g as ia,h as ti}from"./chunk-76Z4VHDX.js";import{a as Qr,k as ra}from"./chunk-A5ZCMRB3.js";import{b as ye,c as Te,d as yo,e as la}from"./chunk-APKAW7LU.js";import{a as Zs,b as Xr}from"./chunk-GQ76J72O.js";import{j as Zr}from"./chunk-X5C5W3E4.js";import{h as zr}from"./chunk-DWADWDMU.js";import{a as Qs}from"./chunk-VXDM7JAT.js";import{b as vt,d as Mn}from"./chunk-M6HJDSLS.js";import{b as go,d as Gr}from"./chunk-2GIDVZ4H.js";import{a as Xs,b as Cr,c as em,d as Dn,e as Nr,f as Ur,g as nm,h as qr,i as sm,m as lo,n as Br,o as Jr,s as Hr,v as rt,w as tn}from"./chunk-VOS2IW4V.js";import{a as Wr,b as im}from"./chunk-FX3D7YON.js";import{a as ft,b as co,e as Mr,f as en}from"./chunk-72SZI2UW.js";import{a as ut,b as Zg}from"./chunk-7I7IEX4S.js";import{m as Rr,n as _r,p as Dr,q as tm,v as Pr,w as I,x as Pn,z as ae}from"./chunk-N5NPJ6DJ.js";import{g as Lr,k as Fr,l as om}from"./chunk-RGDKHYY2.js";import{Command as rm}from"commander";var Yc=new rm().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 ka({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()});ae();import{Command as am}from"commander";import{execFileSync as Xe}from"node:child_process";import{cpSync as Vc,existsSync as bi,mkdirSync as yi,mkdtempSync as cm,readdirSync as lm,rmSync as Kc,writeFileSync as Xc}from"node:fs";import{dirname as Qc,join as De}from"node:path";import{homedir as es,release as dm,tmpdir as gm}from"node:os";import{setTimeout as mm}from"node:timers/promises";function ts(){let e=Na(process.platform,process.arch,dm());if(e)throw new Error(e)}function os(){let e=De(es(),"Library/LaunchAgents"),t=[];try{t=lm(e).filter(Da)}catch{}let o=t.flatMap(n=>{let s=De(e,n);try{return[{file:s,plist:Xe("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Pa(e,o)}function cn(e){return`gui/${process.getuid()}/${e.label}`}async function wi(e){try{Xe("launchctl",["bootout",cn(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{Xe("launchctl",["print",cn(e)],{stdio:"pipe"})}catch{return}await mm(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Zc(e){if(!bi(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{Xe("launchctl",["print",cn(e)],{stdio:"pipe"})}catch{t=!1}t||Xe("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),Xe("launchctl",["kickstart",cn(e)],{stdio:"pipe"})}function pm(){let e=Ua();if(e&&bi(De(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var vo=new am("desktop").description("install and control the macOS desktop assistant");vo.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{ts();let t=I(),o=Ra(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=pm(),r=De(es(),"Applications"),{keep:a,remove:c}=os();if(console.log(`Desktop assistant \u2192 ${De(r,Wn)}
|
|
2
2
|
Computer-use helper \u2192 ${De(r,Bn)}
|
|
3
3
|
Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
|
|
4
4
|
Daemon \u2192 ${s}
|
|
5
5
|
Starts at login \u2192 ${a.file}${c.map(d=>`
|
|
6
|
-
Removes duplicate login item \u2192 ${d.file}`).join("")}`),e.dryRun)return;try{Xe("xcrun",["--find","swiftc"],{stdio:"pipe"})}catch{throw new Error("Apple command-line tools are required. Run xcode-select --install, finish installation, then retry.")}let l=null;try{l=Xe("/bin/sh",["-c","command -v ffmpeg"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{}!l&&!process.env.AGENTX_VOICE_PATH&&console.warn("ffmpeg was not found. Local Whisper transcription needs it: install ffmpeg (for example brew install ffmpeg), then rerun this install.");let g=cm(De(gm(),"agentx-desktop-"));try{for(let p of["mac-helper","mac-voice"]){Vc(De(i,"apps",p),De(g,p),{recursive:!0,filter:
|
|
6
|
+
Removes duplicate login item \u2192 ${d.file}`).join("")}`),e.dryRun)return;try{Xe("xcrun",["--find","swiftc"],{stdio:"pipe"})}catch{throw new Error("Apple command-line tools are required. Run xcode-select --install, finish installation, then retry.")}let l=null;try{l=Xe("/bin/sh",["-c","command -v ffmpeg"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{}!l&&!process.env.AGENTX_VOICE_PATH&&console.warn("ffmpeg was not found. Local Whisper transcription needs it: install ffmpeg (for example brew install ffmpeg), then rerun this install.");let g=cm(De(gm(),"agentx-desktop-"));try{for(let p of["mac-helper","mac-voice"]){Vc(De(i,"apps",p),De(g,p),{recursive:!0,filter:y=>!y.split("/").includes("build")});let w=p==="mac-helper"?La(t.notifications.local.icon):[];Xe("/bin/bash",[De(g,p,"build.sh"),...w],{stdio:"inherit"})}let d=De(es(),"Library/Logs/agentx-desktop.err.log"),u=Ma({label:a.label,executable:De(r,Wn,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:n,url:s,helper:Fa(es()),cli:De(i,"dist/cli.js"),node:process.execPath,log:d,path:_a(l,process.env.AGENTX_VOICE_PATH)}),f=De(g,"desktop.plist");Xc(f,u,{mode:384}),Xe("plutil",["-lint",f],{stdio:"pipe"}),await wi(a);for(let p of c)p.label!==a.label&&await wi(p),Kc(p.file,{force:!0});yi(r,{recursive:!0});for(let[p,w,y]of[["mac-voice","AgentX Voice.app",Wn],["mac-helper",Bn,Bn]])Vc(De(g,p,"build",w),De(r,y),{recursive:!0});yi(Qc(a.file),{recursive:!0}),yi(Qc(d),{recursive:!0}),Xc(a.file,u,{mode:384}),Zc(a),console.log(`Desktop assistant is running. Hold Option\u2013Space to speak; Command\u2013Option\u2013V for smart paste.
|
|
7
7
|
Allow Microphone for the app and Accessibility / Screen Recording for the helper when macOS asks.
|
|
8
8
|
The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{Kc(g,{recursive:!0,force:!0})}});vo.command("start").description("start the installed desktop assistant").action(()=>{ts(),Zc(os().keep),console.log("Desktop assistant started.")});vo.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{ts(),await wi(os().keep),console.log("Desktop assistant stopped.")});vo.command("status").description("show the desktop login service status").action(()=>{ts();let{keep:e}=os();try{console.log(Xe("launchctl",["print",cn(e)],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(bi(e.file)?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as bm}from"commander";import{open as $m}from"fs/promises";import{existsSync as is,mkdirSync as um,readFileSync as rs,writeFileSync as el}from"fs";import{homedir as fm}from"os";import{dirname as hm,resolve as $i}from"path";var ki="/attach/",tl="/guard/check";function ol(e,t,o=""){return`curl -s --max-time 3 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${t}${e}${o}`}' 2>/dev/null || true`}function ns(e,t,o){let n={hooks:[{type:"command",command:ol(e,t),timeout:10}]};return o!==void 0&&(n.matcher=o),n}function ym(e){return{SessionStart:[ns("/attach/session-start",e,"")],UserPromptSubmit:[ns("/attach/prompt",e)],Stop:[ns("/attach/stop",e)],SessionEnd:[ns("/attach/session-end",e)]}}function wm(e){let t=ol("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:t,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:t,timeout:10}]}]}function ss(e,t){return Array.isArray(e?.hooks)&&e.hooks.some(o=>typeof o?.command=="string"&&o.command.includes(t))}function ln(){return $i(fm(),".claude/settings.json")}function Gt(e=process.cwd()){for(let t of[e,$i(e,"..")]){let o=$i(t,"agentx.json");if(is(o))try{let n=JSON.parse(rs(o,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function nl(e,t={}){let o=t.path??ln(),n=t.withGuard!==!1,s={};if(is(o))try{s=JSON.parse(rs(o,"utf-8"))}catch(g){throw new Error(`${o} 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(ym(e))){let u=Array.isArray(r[g])?r[g].filter(f=>!ss(f,ki)):[];r[g]=[...u,...d],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(d=>!ss(d,tl)):[];r.PreToolUse=[...g,...wm(e)],c=!0}let l=JSON.stringify(s)!==i;return l&&(um(hm(o),{recursive:!0}),el(o,`${JSON.stringify(s,null,2)}
|
|
9
9
|
`)),{path:o,changed:l,events:a,guardInstalled:c}}function sl(e={}){let t=e.path??ln();if(!is(t))return{path:t,changed:!1,events:[],guardInstalled:!1};let o;try{o=JSON.parse(rs(t,"utf-8"))}catch(a){throw new Error(`${t} is not valid JSON (${a?.message}) \u2014 refusing to rewrite it`)}let n=JSON.stringify(o),s=o.hooks,i=[];if(s&&typeof s=="object"){for(let a of Object.keys(s)){if(!Array.isArray(s[a]))continue;let c=a==="PreToolUse"?tl:ki;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let l=s[a].filter(g=>!ss(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 o.hooks}let r=JSON.stringify(o)!==n;return r&&el(t,`${JSON.stringify(o,null,2)}
|
|
10
10
|
`),{path:t,changed:r,events:i,guardInstalled:!1}}function dn(e=ln()){if(!is(e))return!1;try{return!!JSON.parse(rs(e,"utf-8"))?.hooks?.Stop?.some?.(o=>ss(o,ki))}catch{return!1}}var as=new bm("monitor").description("Register external CLI sessions and report ended runs to the briefing"),il=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Gt()}`;async function rl(e,t,o){let n=process.env.MESH_TOKEN,s=await fetch(e.replace(/\/$/,"")+"/monitor/"+t,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify(o),signal:AbortSignal.timeout(8e3)});if(!s.ok)throw new Error(`Monitor HTTP ${s.status}: ${(await s.text()).slice(0,300)}`)}as.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",il).action(async e=>{try{await rl(e.url,"register",xa.parse({id:e.session,runtime:e.runtime,label:e.label})),console.log("Session registered. Report each stopped run with agentx monitor ended.")}catch(t){console.error(t.message),process.exitCode=1}});as.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",il).action(async e=>{try{let t=await $m(e.transcript,"r"),o;try{let n=await t.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 t.read(i,0,s,Math.max(0,n.size-s));o=(n.size>s?`[Transcript truncated: last 90 KB only]
|
|
11
|
-
`:"")+i.subarray(0,r).toString("utf8")}finally{await t.close()}await rl(e.url,"ended",Sa.parse({sessionId:e.session,runId:e.run,transcript:o})),console.log("Run queued for review.")}catch(t){console.error(t.message),process.exitCode=1}});import{Command as xw}from"commander";import{Command as Tm}from"commander";ae();import j from"chalk";import{existsSync as Im,readFileSync as Cm}from"fs";ae();import{Command as km}from"commander";import oe from"chalk";import{spawn as cl}from"child_process";import{existsSync as vm,readFileSync as xm,unlinkSync as Sm}from"fs";import{resolve as vi}from"path";var xi=e=>new Promise(t=>setTimeout(t,e));function Si(e){try{return process.kill(e,0),!0}catch{return!1}}async function xo(e){try{let t=await fetch(e,{signal:AbortSignal.timeout(3e3)});return t.ok?await t.json():null}catch{return null}}async function Em(e){let t=await xo(`${e}/daemon/restart`);if(typeof t?.inflight?.total=="number")return t.inflight.total;let o=await xo(`${e}/health`);return o?typeof o.inflight?.total=="number"?o.inflight.total:Array.isArray(o.agents)?o.agents.reduce((n,s)=>n+(Number(s.active)||0),0):null:null}function Am(e){for(let t of[vi(e,".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"])try{let o=parseInt(xm(t,"utf-8").trim(),10);if(Number.isFinite(o)&&Si(o))return o}catch{}return null}function jm(e){return new Promise(t=>{let o=cl(e[0],e.slice(1),{stdio:"inherit"});o.on("error",()=>t(127)),o.on("exit",n=>t(n??1))})}var ll=new km("restart").description("restart the daemon through launchd, systemd or a plain stop + start; --when-idle waits for running tasks first").option("-c, --config <path>","path to agentx.json").option("--when-idle","wait until no task is running before restarting").option("--timeout <minutes>","how long --when-idle waits","30").option("--abort-on-timeout","with --when-idle: give up instead of restarting when the wait runs out").option("--interval <seconds>","how often --when-idle checks","5").option("--reload-service","also re-read the service's settings file (launchd plist / systemd unit)").option("--dry-run","show what would run, without restarting").action(async e=>{let t=I(e.config),[o,n]=t.node.bind.split(":"),s=parseInt(n||"18800",10),i=`http://${!o||o==="0.0.0.0"?"127.0.0.1":o}:${s}`,r=await xo(`${i}/health`);r||(console.log(oe.red(` The daemon is not answering on ${i}; nothing to restart.`)),console.log(oe.dim(" Start it with: agentx daemon start --detach (or through its service)")),process.exit(1));let a=await xo(`${i}/daemon/restart`),c=a?.pid??cc(s)??Am(process.cwd()),l=a?.service??(c?rc(c):{kind:"none"}),g=a?.cwd??process.cwd(),d=e.config??a?.configPath,u=process.getuid?.()===0,f=sc(l,{isRoot:u,reloadService:!!e.reloadService,plistPath:l.kind==="launchd"&&e.reloadService?ac(l):null,interactive:!!process.stdin.isTTY});if(console.log(),console.log(` Daemon ${oe.bold(r.node?.name||r.node?.id||i)}${c?oe.dim(` (PID ${c})`):""}`),console.log(` Run by: ${ic(l)}`),f.ok||(console.log(oe.red(` ${f.reason}`)),console.log(oe.dim(` Restart it by hand: ${f.manual}`)),process.exit(1)),l.kind==="none"&&!c&&(console.log(oe.red(" Can't find the daemon's process, so it can't be stopped safely.")),console.log(oe.dim(" Run `agentx daemon stop`, then `agentx daemon start --detach`, from the directory holding agentx.json.")),process.exit(1)),e.dryRun){console.log(oe.dim(" Would run:"));for(let v of f.steps)console.log(oe.dim(` ${al(v,c)}`));console.log();return}if(e.whenIdle){let v=Number(e.timeout),A=Math.max(1,Number(e.interval)||5);(!Number.isFinite(v)||v<0)&&(console.log(oe.red(" --timeout must be a number of minutes")),process.exit(1));let S,x=await nc({read:()=>Em(i),intervalMs:A*1e3,timeoutMs:v*6e4,onCheck
|
|
11
|
+
`:"")+i.subarray(0,r).toString("utf8")}finally{await t.close()}await rl(e.url,"ended",Sa.parse({sessionId:e.session,runId:e.run,transcript:o})),console.log("Run queued for review.")}catch(t){console.error(t.message),process.exitCode=1}});import{Command as xw}from"commander";import{Command as Tm}from"commander";ae();import j from"chalk";import{existsSync as Im,readFileSync as Cm}from"fs";ae();import{Command as km}from"commander";import oe from"chalk";import{spawn as cl}from"child_process";import{existsSync as vm,readFileSync as xm,unlinkSync as Sm}from"fs";import{resolve as vi}from"path";var xi=e=>new Promise(t=>setTimeout(t,e));function Si(e){try{return process.kill(e,0),!0}catch{return!1}}async function xo(e){try{let t=await fetch(e,{signal:AbortSignal.timeout(3e3)});return t.ok?await t.json():null}catch{return null}}async function Em(e){let t=await xo(`${e}/daemon/restart`);if(typeof t?.inflight?.total=="number")return t.inflight.total;let o=await xo(`${e}/health`);return o?typeof o.inflight?.total=="number"?o.inflight.total:Array.isArray(o.agents)?o.agents.reduce((n,s)=>n+(Number(s.active)||0),0):null:null}function Am(e){for(let t of[vi(e,".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"])try{let o=parseInt(xm(t,"utf-8").trim(),10);if(Number.isFinite(o)&&Si(o))return o}catch{}return null}function jm(e){return new Promise(t=>{let o=cl(e[0],e.slice(1),{stdio:"inherit"});o.on("error",()=>t(127)),o.on("exit",n=>t(n??1))})}var ll=new km("restart").description("restart the daemon through launchd, systemd or a plain stop + start; --when-idle waits for running tasks first").option("-c, --config <path>","path to agentx.json").option("--when-idle","wait until no task is running before restarting").option("--timeout <minutes>","how long --when-idle waits","30").option("--abort-on-timeout","with --when-idle: give up instead of restarting when the wait runs out").option("--interval <seconds>","how often --when-idle checks","5").option("--reload-service","also re-read the service's settings file (launchd plist / systemd unit)").option("--dry-run","show what would run, without restarting").action(async e=>{let t=I(e.config),[o,n]=t.node.bind.split(":"),s=parseInt(n||"18800",10),i=`http://${!o||o==="0.0.0.0"?"127.0.0.1":o}:${s}`,r=await xo(`${i}/health`);r||(console.log(oe.red(` The daemon is not answering on ${i}; nothing to restart.`)),console.log(oe.dim(" Start it with: agentx daemon start --detach (or through its service)")),process.exit(1));let a=await xo(`${i}/daemon/restart`),c=a?.pid??cc(s)??Am(process.cwd()),l=a?.service??(c?rc(c):{kind:"none"}),g=a?.cwd??process.cwd(),d=e.config??a?.configPath,u=process.getuid?.()===0,f=sc(l,{isRoot:u,reloadService:!!e.reloadService,plistPath:l.kind==="launchd"&&e.reloadService?ac(l):null,interactive:!!process.stdin.isTTY});if(console.log(),console.log(` Daemon ${oe.bold(r.node?.name||r.node?.id||i)}${c?oe.dim(` (PID ${c})`):""}`),console.log(` Run by: ${ic(l)}`),f.ok||(console.log(oe.red(` ${f.reason}`)),console.log(oe.dim(` Restart it by hand: ${f.manual}`)),process.exit(1)),l.kind==="none"&&!c&&(console.log(oe.red(" Can't find the daemon's process, so it can't be stopped safely.")),console.log(oe.dim(" Run `agentx daemon stop`, then `agentx daemon start --detach`, from the directory holding agentx.json.")),process.exit(1)),e.dryRun){console.log(oe.dim(" Would run:"));for(let v of f.steps)console.log(oe.dim(` ${al(v,c)}`));console.log();return}if(e.whenIdle){let v=Number(e.timeout),A=Math.max(1,Number(e.interval)||5);(!Number.isFinite(v)||v<0)&&(console.log(oe.red(" --timeout must be a number of minutes")),process.exit(1));let S,x=await nc({read:()=>Em(i),intervalMs:A*1e3,timeoutMs:v*6e4,onCheck:k=>{k!==S&&k!==null&&k>0&&console.log(oe.dim(` Waiting: ${k} task(s) running...`)),S=k}});if(x.outcome==="unreachable"&&(console.log(oe.red(" The daemon stopped answering while waiting. Not restarting it.")),console.log(oe.dim(" Check with: agentx daemon status")),process.exit(1)),x.outcome==="timeout"){let k=x.inflight??"some";e.abortOnTimeout&&(console.log(oe.yellow(` Still ${k} task(s) running after ${v} min. Not restarting (--abort-on-timeout).`)),process.exit(1)),console.log(oe.yellow(` Still ${k} task(s) running after ${v} min. Restarting anyway:`)),console.log(oe.yellow(" they get the usual time to finish, and anything cut off is picked up again after the restart."))}else console.log(oe.green(` No tasks running${x.waitedMs>=1e3?` (waited ${Math.round(x.waitedMs/1e3)}s)`:""}.`))}let p=vi(g,".agentx");try{oc(p,{by:"agentx daemon restart",pid:process.pid,at:new Date().toISOString()})}catch{}let w=Date.now(),y=parseInt(process.env.AGENTX_DRAIN_TIMEOUT_MS||"300000",10)+6e4;console.log(oe.dim(" Restarting..."));for(let v of f.steps){if(await Om(v,{pid:c,daemonCwd:g,configPath:d,drainLimitMs:y,service:l})||v.kind==="exec"&&v.mayFail)continue;let S=v===f.steps[0];try{S&&Sm(vi(p,tc))}catch{}console.log(oe.red(` Step failed: ${al(v,c)}`)),console.log(S?oe.dim(` The daemon is still running. Restart it with: ${f.manual}`):oe.red(` The daemon may be down. Start it with: ${f.manual}`)),process.exit(1)}let $=12e4,b=Date.now();for(;Date.now()-b<$;){let v=await xo(`${i}/health`);if(v&&typeof v.uptime=="number"&&v.uptime*1e3<=Date.now()-w+2e3){let A=await xo(`${i}/daemon/restart`);console.log(oe.green(` Daemon is back${A?.pid?` (PID ${A.pid})`:""} after ${Math.round((Date.now()-w)/1e3)}s.`)),console.log();return}await xi(1e3)}console.log(oe.red(` The daemon did not come back within ${$/6e4} min.`)),console.log(oe.dim(` Start it with: ${f.manual}`)),console.log(oe.dim(" Then check the log: agentx daemon logs")),process.exit(1)});function al(e,t){switch(e.kind){case"exec":return e.argv.join(" ");case"sigterm":return`kill -TERM ${t??"<pid>"} (the daemon finishes running tasks, then exits)`;case"wait-exit":return"wait for the old daemon to exit";case"wait-unloaded":return"wait until launchd has unloaded the job";case"start-detached":return"agentx daemon start --detach"}}async function Om(e,t){switch(e.kind){case"exec":return await jm(e.argv)===0;case"sigterm":if(!t.pid)return!1;try{return process.kill(t.pid,"SIGTERM"),!0}catch{return!1}case"wait-exit":{if(!t.pid)return!0;let o=Date.now(),n=!1;for(;Si(t.pid)&&Date.now()-o<t.drainLimitMs;)!n&&Date.now()-o>3e3&&(console.log(oe.dim(" Waiting for the old daemon to finish its tasks and exit...")),n=!0),await xi(500);return Si(t.pid)?(console.log(oe.yellow(` The old daemon (PID ${t.pid}) is still finishing tasks; not starting a second one.`)),!1):!0}case"wait-unloaded":{if(t.service.kind!=="launchd")return!0;let o=Date.now();for(;ri(t.service)&&Date.now()-o<3e4;)await xi(500);return!ri(t.service)}case"start-detached":{let o=process.argv[1];if(!o||!vm(o))return!1;let n=[o,"daemon","start","--detach",...t.configPath?["-c",t.configPath]:[]];return new Promise(s=>{let i=cl(process.execPath,n,{cwd:t.daemonCwd,stdio:"inherit"});i.on("error",()=>s(!1)),i.on("exit",r=>s(r===0))})}}}async function Nm(e){try{let{execFileSync:t}=await import("child_process"),o=t("ps",["-p",String(e),"-o","command="],{encoding:"utf-8",timeout:2e3}).trim();return o?/\bnode\b/.test(o)||/agentx|agentix|cli\.js/.test(o):!1}catch{return!0}}var Qe=new Tm().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");Qe.command("start").description("start the daemon (default if no subcommand)").option("-c, --config <path>","path to agentx.json").option("-d, --detach","run in background (detached)").option("--port <port>","override bind port").action(async e=>{if(e.detach){let{spawn:l}=await import("child_process"),{openSync:g,writeFileSync:d,existsSync:u}=await import("fs"),f=process.argv[1];(!f||!u(f))&&(console.error(j.red(` Cannot resolve agentx CLI entrypoint (process.argv[1]=${f||"?"}).`)),console.error(j.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(j.red(` Failed to open ${w} for writing: ${b.message}`)),process.exit(1)}let $=l(process.execPath,p,{detached:!0,stdio:["ignore",y,y],cwd:process.cwd()});$.unref(),d("/tmp/agentx-daemon.pid",String($.pid)),console.log(j.green(`Daemon started in background (PID: ${$.pid})`)),console.log(j.dim(` Logs: tail -f ${w}`)),console.log(j.dim(" Stop: agentx daemon stop")),await new Promise(b=>setTimeout(b,1e3));try{process.kill($.pid,0)}catch{console.log(),console.log(j.yellow(` Daemon exited within 1s \u2014 check ${w} for the error:`)),console.log(j.dim(` tail -n 40 ${w}`))}return}let{readFileSync:t,writeFileSync:o,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(t(a,"utf-8").trim(),10);if(l&&l!==process.pid){let g=!1;try{process.kill(l,0),g=!0}catch{}g&&await Nm(l)&&(console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0))}}o(a,String(process.pid));try{Rm(i(process.cwd(),".env"))}catch{}await new fi(e.config).start()});function Rm(e){if(!Im(e))return;let t=Cm(e,"utf-8");for(let o of t.split(`
|
|
12
12
|
`)){let n=o.trim();if(!n||n.startsWith("#"))continue;let s=n.indexOf("=");if(s<0)continue;let i=n.slice(0,s).trim();if(!i||process.env[i]!==void 0)continue;let r=n.slice(s+1).trim();(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))&&(r=r.slice(1,-1)),process.env[i]=r}}Qe.command("stop").description("stop the running daemon").action(async()=>{let{readFileSync:e,existsSync:t,unlinkSync:o}=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(t(r))try{let a=parseInt(e(r,"utf-8").trim(),10);try{let{writeShutdownRequest:d}=await import("./shutdown-ZAF7RW25.js");d(n(process.cwd(),".agentx"),{by:"agentx daemon stop",pid:process.pid,at:new Date().toISOString()})}catch{}process.kill(a,"SIGTERM");let c=parseInt(process.env.AGENTX_DRAIN_TIMEOUT_MS||"300000",10)+6e4,l=Date.now(),g=!1;for(;dl(a)&&Date.now()-l<c;)!g&&Date.now()-l>3e3&&(console.log(j.dim(` Waiting for in-flight tasks to finish (up to ${Math.round(c/6e4)} min)...`)),g=!0),await new Promise(d=>setTimeout(d,500));if(dl(a)){console.log(j.yellow(`Daemon (PID: ${a}) is still finishing tasks. Check again with: agentx daemon status`));return}try{o(r)}catch{}console.log(j.green(`Daemon stopped (PID: ${a})`));return}catch{try{o(r)}catch{}}let{execSync:i}=await import("child_process");try{i("pkill -f 'node dist/cli.js daemon'",{stdio:"ignore"}),console.log(j.green("Daemon stopped"))}catch{console.log(j.yellow("No daemon process found"))}});Qe.addCommand(ll);Qe.command("status").alias("st").description("show daemon status, agents, crons, and mesh").option("-c, --config <path>","path to agentx.json").option("--json","output as JSON").action(async e=>{try{let t=I(e.config),[o,n]=t.node.bind.split(":"),s=`http://${o||"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(j.bold(` ${r.node.name}`)+j.dim(` (${r.node.id})`)),console.log(j.green(" Status: running")+j.dim(` \u2014 uptime ${_m(r.uptime)}`)),console.log(),console.log(j.bold(" Agents:"));for(let c of r.agents){let l=c.active>0?j.yellow(` [${c.active} active]`):"",g=c.errors>0?j.red(` (${c.errors} errors)`):"";console.log(` ${j.cyan(c.name)} ${j.dim(`(${c.tier})`)}${l}${g}`),console.log(j.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(j.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let l=c.enabled?j.green("\u25CF"):j.dim("\u25CB"),g=c.nextRun?j.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${l} ${c.id}${g}`)}}if(r.mesh?.length){console.log(),console.log(j.bold(" Mesh:"));for(let c of r.mesh){let l=c.healthy?j.green("\u25CF"):j.red("\u25CF"),g=c.skills?.length?j.dim(` (${c.skills.length} agents)`):"";console.log(` ${l} ${c.peer} ${j.dim(c.peerUrl)}${g}`)}}console.log()}catch(t){if(t.cause?.code==="ECONNREFUSED"||t.name==="TimeoutError")console.log(j.red(" Daemon is not running")),console.log(j.dim(" Start with: agentx daemon start"));else try{let o=I(e.config),n=Pn(o);if(console.log(),console.log(j.bold(` ${o.node.name}`)+j.dim(` (${o.node.id})`)),console.log(j.yellow(" Status: stopped")),console.log(j.dim(` ${Object.keys(o.agents).length} agents, ${Object.keys(o.crons).length} crons configured`)),n.length){console.log();for(let s of n)console.log(j.yellow(` \u26A0 ${s}`))}console.log()}catch(o){console.log(j.red(` ${o.message}`))}}});Qe.command("logs").description("tail daemon logs").option("-n, --lines <n>","number of lines","50").option("-f, --follow","follow log output",!1).action(async e=>{let{execSync:t,spawn:o}=await import("child_process"),n="/tmp/agentx-daemon.log",{existsSync:s}=await import("fs");if(!s(n)){console.log(j.yellow("No log file found at /tmp/agentx-daemon.log"));return}if(e.follow){let i=o("tail",["-f","-n",e.lines,n],{stdio:"inherit"});process.on("SIGINT",()=>{i.kill(),process.exit(0)})}else t(`tail -n ${e.lines} ${n}`,{stdio:"inherit"})});Qe.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(I(e.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(j.dim(` Connecting to ${n}...`)),console.log(j.dim(` Press Ctrl+C to stop
|
|
13
13
|
`));try{let s=await fetch(n);if(!s.ok||!s.body){console.log(j.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(`
|
|
14
14
|
`);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(`${j.dim(f)} ${j.cyan("\u25B6")} ${p}`):p.includes("completed")?console.log(`${j.dim(f)} ${j.green("\u2713")} ${p}`):p.includes("error")||p.includes("Error")?console.log(`${j.dim(f)} ${j.red("\u2717")} ${p}`):p.includes("Routing")?console.log(`${j.dim(f)} ${j.yellow("\u2192")} ${p}`):p.includes("mention")?console.log(`${j.dim(f)} ${j.magenta("@")} ${p}`):p.includes("Skipping")?console.log(`${j.dim(f)} ${j.dim("\u2298")} ${j.dim(p)}`):console.log(`${j.dim(f)} ${p}`)}catch{}else d.startsWith("event: status")}}catch(s){console.log(j.red(` Connection failed: ${s.message}`)),console.log(j.dim(" Is the daemon running? Diagnostic order:")),console.log(j.dim(" 1) agentx daemon status # is the daemon up?")),console.log(j.dim(" 2) tail -n 60 /tmp/agentx-daemon.log # detach-mode crash log")),console.log(j.dim(" 3) journalctl -u agentx -n 60 # systemd-managed installs")),console.log(j.dim(" If the log file is missing, the daemon never started \u2014 re-run without --detach")),console.log(j.dim(" to see the error in the foreground."))}});Qe.command("send <agent> <message...>").description("send a task to an agent via the daemon API").option("-c, --config <path>","path to agentx.json").option("--peer <peer>","send to a mesh peer's agent").option("--json","output raw JSON response").action(async(e,t,o)=>{let n=t.join(" ");try{let s=I(o.config),[i,r]=s.node.bind.split(":"),a=`http://${i||"127.0.0.1"}:${r}`,c,l;o.peer?(c=`${a}/mesh/task`,l={peer:o.peer,message:n,agent:e}):(c=`${a}/task`,l={agent:e,message:n}),console.log(j.dim(` Sending to ${o.peer?`${o.peer}/${e}`:e}...`));let d=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();o.json?console.log(JSON.stringify(d,null,2)):d.error?console.log(j.red(` Error: ${d.error}`)):(console.log(),console.log(d.content||d.response||"No response"),d.duration&&console.log(j.dim(`
|
|
15
15
|
(${(d.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(j.red(` Failed: ${s.message}`)),console.log(j.dim(" Is the daemon running? Try: agentx daemon status"))}});Qe.command("deploy <host>").description("deploy agentx to a remote server via rsync").option("-i, --identity <key>","SSH identity file").option("-u, --user <user>","SSH user","root").option("-p, --path <path>","remote agentx path","~/agentx").option("--restart","restart remote daemon after deploy",!1).option("--skip-checks","skip build and test before deploy",!1).action(async(e,t)=>{let{execSync:o}=await import("child_process"),n=t.identity?`-e "ssh -i ${t.identity}"`:"",s=`${t.user}@${e}:${t.path}/dist/`;if(!t.skipChecks){try{console.log(j.dim(" Running tests...")),o("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(j.green(" \u2713 Tests passed"))}catch{console.log(j.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(j.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(j.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(c).mtimeMs>3e5&&(console.log(j.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),o("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(j.green(" \u2713 Build complete")))}console.log(j.dim(` Deploying to ${t.user}@${e}:${t.path}...`));try{if(o(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(j.green(" \u2713 Deploy complete")),t.restart){console.log(j.dim(" Restarting remote daemon once no task is running..."));let i=t.identity?`ssh -i ${t.identity}`:"ssh";o(`${i} -t ${t.user}@${e} "cd ${t.path} && node dist/cli.js daemon restart --when-idle"`,{stdio:"inherit"}),console.log(j.green(" Remote daemon restarted"))}}catch(i){console.log(j.red(` Deploy failed: ${i.message}`))}});Qe.action(async e=>{await new fi(e.config).start()});function _m(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`}function dl(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}import{Command as Dm}from"commander";import Ze from"chalk";import{existsSync as gn,readFileSync as Pm,writeFileSync as gl,mkdirSync as ml}from"fs";import{hostname as pl}from"os";import{resolve as So}from"path";var ul=new Dm().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let t=process.cwd(),o=So(t,"agentx.json"),n=So(t,".env"),s=So(t,".agentx/sessions");if(console.log(),console.log(Ze.bold(" agentx init")),console.log(),gn(o)&&!e.force){console.log(Ze.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[So(t,"agentx.example.json"),So(t,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(gn(c)){r=Pm(c,"utf-8");break}r||(r=JSON.stringify({node:{id:pl().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:pl(),bind:"127.0.0.1:18800"},providers:{claude:{apiKey:"${ANTHROPIC_API_KEY}"}},agents:{assistant:{name:"Assistant",workspace:t,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)),gl(o,r),console.log(Ze.green(" \u2713 Created agentx.json")),gn(n)||(gl(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
|
|
16
|
-
`)),console.log(Ze.green(" \u2713 Created .env template"))),gn(s)||(ml(s,{recursive:!0}),console.log(Ze.green(" \u2713 Created .agentx/sessions/")));let a=So(t,".claude");gn(a)||(ml(a,{recursive:!0}),console.log(Ze.green(" \u2713 Created .claude/"))),console.log(),console.log(Ze.bold(" Next steps:")),console.log(` 1. Edit ${Ze.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${Ze.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${Ze.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${Ze.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as Mm}from"commander";import zt from"chalk";import{spawn as hl}from"child_process";import{existsSync as Lm}from"fs";import{dirname as Fm,resolve as Um}from"path";import{fileURLToPath as qm}from"url";ae();var yl=new Mm().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 t=Rc(),o=e.port?parseInt(e.port,10):Wm(),n=`http://127.0.0.1:${o}/setup`;if(console.log(),t.configExists?console.log(zt.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(zt.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(zt.bold(` Opening ${n}`)),console.log(),await Jm(n).catch(()=>!1))console.log(zt.dim(" Dashboard is already running.")),e.open!==!1&&fl(n);else{console.log(zt.dim(` Starting dashboard server on port ${o} (Ctrl-C to quit)\u2026`));let i=Bm(),r=hl(process.execPath,[i,"board","serve","--port",String(o)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&fl(n),await new Promise(a=>r.on("exit",()=>a()))}});function Wm(){try{return I().dashboard.port||4202}catch{return 4202}}function Bm(){let e=Um(Fm(qm(import.meta.url)),"cli.js");return Lm(e)?e:process.argv[1]||e}async function Jm(e){try{let t=await fetch(e,{method:"GET"});return t.ok||t.status===302}catch{return!1}}function fl(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let o=hl(t,[e],{stdio:"ignore",detached:!0});o.once("error",()=>{console.log(zt.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),o.unref()}catch{console.log(zt.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as Hm}from"commander";import
|
|
16
|
+
`)),console.log(Ze.green(" \u2713 Created .env template"))),gn(s)||(ml(s,{recursive:!0}),console.log(Ze.green(" \u2713 Created .agentx/sessions/")));let a=So(t,".claude");gn(a)||(ml(a,{recursive:!0}),console.log(Ze.green(" \u2713 Created .claude/"))),console.log(),console.log(Ze.bold(" Next steps:")),console.log(` 1. Edit ${Ze.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${Ze.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${Ze.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${Ze.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as Mm}from"commander";import zt from"chalk";import{spawn as hl}from"child_process";import{existsSync as Lm}from"fs";import{dirname as Fm,resolve as Um}from"path";import{fileURLToPath as qm}from"url";ae();var yl=new Mm().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 t=Rc(),o=e.port?parseInt(e.port,10):Wm(),n=`http://127.0.0.1:${o}/setup`;if(console.log(),t.configExists?console.log(zt.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(zt.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(zt.bold(` Opening ${n}`)),console.log(),await Jm(n).catch(()=>!1))console.log(zt.dim(" Dashboard is already running.")),e.open!==!1&&fl(n);else{console.log(zt.dim(` Starting dashboard server on port ${o} (Ctrl-C to quit)\u2026`));let i=Bm(),r=hl(process.execPath,[i,"board","serve","--port",String(o)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&fl(n),await new Promise(a=>r.on("exit",()=>a()))}});function Wm(){try{return I().dashboard.port||4202}catch{return 4202}}function Bm(){let e=Um(Fm(qm(import.meta.url)),"cli.js");return Lm(e)?e:process.argv[1]||e}async function Jm(e){try{let t=await fetch(e,{method:"GET"});return t.ok||t.status===302}catch{return!1}}function fl(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let o=hl(t,[e],{stdio:"ignore",detached:!0});o.once("error",()=>{console.log(zt.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),o.unref()}catch{console.log(zt.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as Hm}from"commander";import Ie from"chalk";var mn=new Hm().name("token").description("scoped API tokens for external access (mesh peers, integrations)");mn.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 t=new St,o=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}=t.create({name:e.name,scopes:o,expiresInDays:n});console.log(),console.log(Ie.bold(" Token created.")),console.log(),console.log(` id: ${Ie.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||Ie.dim("never")}`),console.log(),console.log(Ie.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${Ie.green.bold(s)}`),console.log(),console.log(Ie.dim(" Use it via the Authorization header:")),console.log(Ie.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(t){console.log(Ie.red(` ${t.message}`)),process.exit(1)}});mn.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new St().list();if(e.length===0){console.log(Ie.dim(`
|
|
17
17
|
No tokens issued.
|
|
18
|
-
`));return}console.log();for(let t of e){let o=t.revokedAt?
|
|
18
|
+
`));return}console.log();for(let t of e){let o=t.revokedAt?Ie.red("revoked"):t.expiresAt&&Date.parse(t.expiresAt)<Date.now()?Ie.red("expired"):Ie.green("active");console.log(` ${Ie.cyan(t.id)} ${o} ${t.name}`),console.log(Ie.dim(` prefix: ${t.prefix}\u2026 scopes: ${t.scopes.join(", ")}`)),console.log(Ie.dim(` created: ${t.createdAt}${t.expiresAt?` expires: ${t.expiresAt}`:""}${t.lastUsedAt?` last used: ${t.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(Ie.red(` ${e.message}`)),process.exit(1)}});mn.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let t=new St().revoke(e);t||(console.log(Ie.red(` Token ${e} not found.`)),process.exit(1)),console.log(Ie.green(`
|
|
19
19
|
\u2713 Revoked ${e} (${t.name})
|
|
20
|
-
`))}catch(t){console.log(
|
|
21
|
-
`));let o=(e.url?String(e.url):Ym()).replace(/\/+$/,"");if(!/^https?:\/\/[^/]+$/.test(o))throw new Error(`--url must be an origin like https://host.example.ts.net, got: ${o}`);let{token:n,record:s}=new St().create({name:String(e.name),scopes:["app"]}),{code:i}=new Pc().create({token:n,tokenId:s.id,name:s.name}),r=`${o}/app/pair#token=${n}`,{default:a}=await import("qrcode-terminal");console.log(),a.generate(r,{small:!0},c=>console.log(c));for(let c of zm({code:i,origin:o,deviceId:s.id,deviceName:s.name}))console.log(c);!wl("agentx.json")&&!wl(".agentx/config.json")&&console.log(
|
|
20
|
+
`))}catch(t){console.log(Ie.red(` ${t.message}`)),process.exit(1)}});import{Command as Gm}from"commander";import Ee from"chalk";import{execFileSync as bl}from"child_process";import{existsSync as wl}from"fs";ae();var Eo=new Gm().name("app").description("pair phones with the AgentX phone app and manage paired devices");Eo.command("pair").description("pair a phone \u2014 prints a QR code to scan and a one-time code to type in the installed app").option("--name <name>","name for this phone (shown in `agentx app devices`)","Phone").option("--url <origin>","address the phone opens, e.g. https://my-mac.tailnet-name.ts.net (default: this machine's Tailscale name)").action(async e=>{try{let t=Km(Xm(),Ei());if(t.length>0)throw new Error([`tailscale serve publishes the whole dashboard, not only the phone app: ${t.join(", ")}`," Anyone on your tailnet can open it without a key. Serve only the app paths instead:"," tailscale serve reset",` tailscale serve --bg --set-path /app http://127.0.0.1:${Ei()}/app`,` tailscale serve --bg --set-path /api/app http://127.0.0.1:${Ei()}/api/app`].join(`
|
|
21
|
+
`));let o=(e.url?String(e.url):Ym()).replace(/\/+$/,"");if(!/^https?:\/\/[^/]+$/.test(o))throw new Error(`--url must be an origin like https://host.example.ts.net, got: ${o}`);let{token:n,record:s}=new St().create({name:String(e.name),scopes:["app"]}),{code:i}=new Pc().create({token:n,tokenId:s.id,name:s.name}),r=`${o}/app/pair#token=${n}`,{default:a}=await import("qrcode-terminal");console.log(),a.generate(r,{small:!0},c=>console.log(c));for(let c of zm({code:i,origin:o,deviceId:s.id,deviceName:s.name}))console.log(c);!wl("agentx.json")&&!wl(".agentx/config.json")&&console.log(Ee.yellow(" \u26A0 No agentx.json here. The dashboard only accepts phones paired from the folder that holds agentx.json.")),console.log()}catch(t){console.log(Ee.red(` ${t.message}`)),process.exit(1)}});Eo.command("devices").description("list paired phones").action(()=>{let e=new St().list().filter(t=>t.scopes.includes("app"));if(e.length===0){console.log(Ee.dim("\n No paired phones. Run `agentx app pair`.\n"));return}console.log();for(let t of e){let o=t.revokedAt?Ee.red("revoked"):Ee.green("active");console.log(` ${Ee.cyan(t.id)} ${o} ${t.name}`),console.log(Ee.dim(` paired: ${t.createdAt}${t.lastUsedAt?` last used: ${t.lastUsedAt}`:""}`))}console.log()});Eo.command("revoke <id>").description("unpair a phone immediately").action(e=>{let t=new St,o=t.list().find(n=>n.id===e&&n.scopes.includes("app"));o||(console.log(Ee.red(` No paired phone with id ${e}. See \`agentx app devices\`.`)),process.exit(1)),t.revoke(e),console.log(Ee.green(`
|
|
22
22
|
\u2713 Unpaired ${e} (${o.name})
|
|
23
|
-
`))});Eo.command("push-keys").description("create the key pair that lets this computer send notifications to paired phones").option("--force","replace existing keys (every phone must turn notifications on again)").action(async e=>{let t=Ha;try{t=I().channels.push.keysFile}catch{}let o=Ga(t),n=za(o);if(n&&!e.force){console.log(
|
|
24
|
-
\u2713 Keys already exist in ${o} (created ${n.createdAt}).`)),console.log(
|
|
25
|
-
`));return}let{default:s}=await import("web-push");Ya(o,s.generateVAPIDKeys()),console.log(
|
|
26
|
-
\u2713 Saved new push keys to ${o}`)),console.log(
|
|
27
|
-
`))});function zm(e){let t=Math.round(_c/6e4),o=[` Pairing code: ${
|
|
28
|
-
Agent "${t.id}" added`)),console.log(
|
|
23
|
+
`))});Eo.command("push-keys").description("create the key pair that lets this computer send notifications to paired phones").option("--force","replace existing keys (every phone must turn notifications on again)").action(async e=>{let t=Ha;try{t=I().channels.push.keysFile}catch{}let o=Ga(t),n=za(o);if(n&&!e.force){console.log(Ee.green(`
|
|
24
|
+
\u2713 Keys already exist in ${o} (created ${n.createdAt}).`)),console.log(Ee.dim(` Replacing them cuts off every phone; pass --force if you really mean to.
|
|
25
|
+
`));return}let{default:s}=await import("web-push");Ya(o,s.generateVAPIDKeys()),console.log(Ee.green(`
|
|
26
|
+
\u2713 Saved new push keys to ${o}`)),console.log(Ee.dim(" Keep this file private. It is readable only by you, and agentx.json never contains it.")),n&&console.log(Ee.yellow(" \u26A0 Old keys replaced: open Alerts on each phone and turn notifications on again.")),console.log(Ee.dim(` Restart the daemon so it picks up the keys.
|
|
27
|
+
`))});function zm(e){let t=Math.round(_c/6e4),o=[` Pairing code: ${Ee.bold.cyan(Dc(e.code))}`,Ee.dim(` Open the app from the phone's home screen and type this code. It works once, for ${t} minutes.`)," Or scan the QR code with the phone's camera and open the link.",` Device ${Ee.cyan(e.deviceId)} (${e.deviceName}) paired to ${e.origin}.`,Ee.yellow(" \u26A0 Anyone who scans the QR code or types the code can use the app. Clear the terminal when done.")];return e.origin.startsWith("https://")||o.push(Ee.yellow(` \u26A0 ${e.origin} is not HTTPS: the phone can't install the app or keep the session from there.`)),o}function Ym(){let e;try{e=JSON.parse(bl("tailscale",["status","--json"],{encoding:"utf-8",timeout:5e3}))}catch{throw new Error("Could not read this machine's Tailscale name. Is Tailscale running? Or pass --url https://<address>.")}let t=String(e?.Self?.DNSName||"").replace(/\.$/,"");if(!t)throw new Error("Tailscale has no MagicDNS name for this machine. Pass --url https://<address>.");return`https://${t}`}var Vm=new Set(["/app","/api/app"]);function Km(e,t){let o=[e,...Object.values(e?.Foreground??{})],n=[];for(let s of o)for(let[i,r]of Object.entries(s?.Web??{}))for(let[a,c]of Object.entries(r?.Handlers??{})){let l=String(c?.Proxy??"").match(/^(?:https?:\/\/)?(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)/),g=a.replace(/\/+$/,"")||"/";l&&Number(l[1])===t&&!Vm.has(g)&&n.push(`${i}${a}`)}return n}function Xm(){try{return JSON.parse(bl("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function Ei(){try{return I().dashboard.port||4202}catch{return 4202}}ae();import{Command as dt}from"commander";import h from"chalk";import _e from"prompts";import{readFileSync as jt,writeFileSync as Ao,existsSync as fe,mkdirSync as lt,cpSync as Ai,readdirSync as Oi}from"fs";import{resolve as H,join as At,dirname as Qm}from"path";import{fileURLToPath as Zm}from"url";function ce(){let e=H(process.cwd(),"agentx.json");if(!fe(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(jt(e,"utf-8"))}function Ue(e){return ye(t=>{for(let o of Object.keys(t))delete t[o];Object.assign(t,e)}).then(t=>{if(!t.success){console.error(h.red(` Config save failed: ${t.error}`));return}t.reloaded?console.error(h.dim(" (daemon hot-reloaded)")):t.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(t.reloadSkipped)&&console.error(h.dim(` (daemon reload skipped: ${t.reloadSkipped})`))})}var Yt=new dt().name("agent").description("manage agents \u2014 add, list, remove");Yt.command("list").alias("ls").description("list configured agents").action(()=>{let e=ce();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=o.mentions?.join(", ")||"";console.log(` ${h.cyan(t)} \u2014 ${o.name} (${o.tier})`),console.log(h.dim(` workspace: ${o.workspace}`)),n&&console.log(h.dim(` mentions: ${n}`))}console.log()});Yt.command("add").description("add a new agent interactively").action(async()=>{let e=ce(),t=await _e([{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:H(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(!t.id)return;let o=t.workspace.endsWith(t.id)?t.workspace:At(t.workspace,t.id);lt(H(o,".claude/skills"),{recursive:!0});let n={name:t.name,workspace:o,tier:t.tier,model:t.model,mentions:t.mentions?.map(l=>l.trim()).filter(Boolean)||[],maxConcurrent:t.maxConcurrent,systemPrompt:t.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-42ARC42I.js"),i=s(t.id,n,"19900",(...l)=>{console.log(h.dim(` ${l.join(" ")}`))}),r=H(process.cwd(),"src/wiki/SKILL.md"),a=H(Qm(Zm(import.meta.url)),"../wiki/SKILL.md"),c=fe(r)?r:a;fe(c)&&(lt(H(o,".claude/skills/wiki"),{recursive:!0}),Ai(c,H(o,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[t.id]=n,await Ue(e),console.log(h.green(`
|
|
28
|
+
Agent "${t.id}" added`)),console.log(h.dim(` Workspace: ${o}`)),console.log(h.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});Yt.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let t=ce();if(!t.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete t.agents[e],await Ue(t),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});Yt.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,t)=>{let o=ce(),n=o.agents?.[e];if(n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1)),t.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(t.intents!==void 0&&(t.intents==="-"||t.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(t.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),t.maxDelegationDepth!==void 0){let i=parseInt(t.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(t.contextReferences!==void 0){let i=String(t.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(t.contextStrategy!==void 0&&(t.contextStrategy==="-"||t.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(t.contextStrategy)?(n.contextStrategy=t.contextStrategy,s.push(`contextStrategy=${t.contextStrategy}`)):(console.log(h.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),t.maxExecutionMinutes!==void 0){let i=parseInt(t.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 Ue(o),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 pn=new dt().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");pn.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,t)=>{let n=ce().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(t.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(h.dim(`
|
|
29
29
|
${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
|
|
30
|
-
`));return}console.log(),console.log(y.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]?y.green(`${g}:${d}=set`):y.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(y.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(y.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${r?y.cyan(i.kind.padEnd(14)):y.dim(i.kind.padEnd(14))} ${y.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${y.dim(l)}`),r||console.log(` ${y.dim("(disabled)")}`)}console.log()});pn.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,t)=>{let o=ce();o.agents?.[e]||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let n=t.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-VV4X7PEK.js"),i=String(t.kind||"").trim();!i&&n&&(i=((await _e({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(y.red(" --kind is required")),process.exit(1));let r=String(t.label||"").trim();!r&&n&&(r=((await _e({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(y.red(" --label is required")),process.exit(1));let a=String(t.tokenEnv||"").trim(),c=String(t.auth||"").trim(),l=String(t.sessionDir||"").trim();if(!a&&!c&&!l&&n){let u=await _e({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 _e({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 _e({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(t.metadata)for(let u of String(t.metadata).split(",")){let[f,...p]=u.split("=");f&&(g[f.trim()]=p.join("=").trim())}else if(n){let u=await _e({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(y.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(y.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),o.agents[e].integrations=o.agents[e].integrations??[],o.agents[e].integrations.find(u=>u.kind===i&&u.label===r)&&(console.log(y.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),o.agents[e].integrations.push({kind:i,label:r,credentials:d,metadata:g,enabled:!0}),await Ue(o),console.log(y.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(y.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});pn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,t)=>{let o=ce(),n=o.agents?.[e];n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=t.includes(":")?t.split(":",2):[t,""],a=s.findIndex(l=>l.kind===i&&(!r||l.label===r)||l.label===t);a===-1&&(console.log(y.red(` No integration matched "${t}"`)),process.exit(1));let c=s.splice(a,1)[0];await Ue(o),console.log(y.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});pn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,t)=>{let n=ce().agents?.[e];n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=t?s.filter(a=>a.kind===t||a.label===t||`${a.kind}:${a.label}`===t):s;if(!i.length){console.log(y.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(` ${y.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${y.dim(g)}`)}else console.log(` ${y.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});Yt.addCommand(pn);var cs=new dt().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");cs.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ce();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log(y.bold(" Telegram:"));for(let[s,i]of Object.entries(t.accounts||{}))console.log(` ${y.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(y.dim(" Telegram: disabled"));let o=e.channels?.whatsapp;if(o?.enabled){console.log(y.bold(" WhatsApp:")),console.log(` default agent: ${o.defaultAgent||"(none)"}`),console.log(` session: ${o.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of o.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(y.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(y.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(y.dim(" GitLab: disabled"));console.log()});cs.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ce(),t=Object.keys(e.agents||{});if(!t.length){console.log(y.red(" No agents configured. Run: agentx agent add"));return}let o=t.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await _e({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 _e([{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:o}]);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(y.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(y.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 Ue(e),console.log(y.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await _e([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:o},{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 _e([{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:o},{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 Ue(e),lt(H(process.cwd(),s.sessionDir),{recursive:!0}),console.log(y.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(y.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await _e([{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 _e([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{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 Ue(e),console.log(y.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(y.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(y.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(y.dim(` Secret token: ${s.webhookSecret}`)),console.log(y.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(y.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var jo=new dt().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");jo.command("list").alias("ls").description("list cron jobs").action(()=>{let e=ce();console.log();for(let[t,o]of Object.entries(e.crons||{})){let n=o.enabled?y.green("\u25CF"):y.dim("\u25CB");console.log(` ${n} ${y.cyan(t)} \u2014 ${o.schedule} (${o.timezone})`),console.log(y.dim(` agent: ${o.agent} | timeout: ${o.timeout}s`))}Object.keys(e.crons||{}).length||console.log(y.dim(" No cron jobs configured")),console.log()});jo.command("add").description("add a cron job").action(async()=>{let e=ce(),t=Object.keys(e.agents||{}),o=await _e([{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:t.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}]);!o.id||!o.schedule||(e.crons=e.crons||{},e.crons[o.id]={enabled:o.enabled,schedule:o.schedule,timezone:o.timezone,agent:o.agent,prompt:o.prompt,timeout:o.timeout,onError:["log"]},await Ue(e),console.log(y.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});jo.command("enable <id>").description("enable a cron job").action(async e=>{let t=ce();if(!t.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}if(t.crons[e].approval?.action==="create"){console.log(y.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}t.crons[e].enabled=!0,await Ue(t),console.log(y.green(` Cron "${e}" enabled`))});jo.command("disable <id>").description("disable a cron job").action(async e=>{let t=ce();if(!t.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await Ue(t),console.log(y.green(` Cron "${e}" disabled`))});var Vt=new dt().name("mesh").description("manage mesh peers \u2014 add, list, remove");Vt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=ce();if(console.log(),!e.mesh?.enabled)console.log(y.dim(" Mesh: disabled"));else{console.log(y.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let o=y.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();o=y.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${y.cyan(t.name)} ${y.dim(t.url)} ${o}`)}}console.log()});Vt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=ce(),t=await _e([{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(!(!t.name||!t.url)){try{let n=await(await fetch(`${t.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(y.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(y.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:t.url,name:t.name,...t.token?{token:t.token}:{}}),await Ue(e),console.log(y.green(` Peer "${t.name}" added`)),console.log()}});Vt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=ce();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await Ue(t),console.log(y.green(` Peer "${e}" removed`)))});Vt.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 t=ce();if(t.mesh=t.mesh||{},t.mesh.healthCheck=t.mesh.healthCheck||{},e.show){console.log(` interval ${t.mesh.healthCheck.interval??60}s`),console.log(` timeout ${t.mesh.healthCheck.timeout??10}s`);return}let o=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(y.red(" --interval must be 5..3600 seconds")),process.exit(1)),t.mesh.healthCheck.interval=n,o.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(y.red(" --timeout must be 1..60 seconds")),process.exit(1)),t.mesh.healthCheck.timeout=n,o.push(`timeout=${n}s`)}o.length===0&&(console.log(y.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await Ue(t),console.log(y.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log(y.dim(" Restart the daemon for the new cadence to take effect."))});Vt.command("announce <text...>").description("send a short note to every machine in the mesh (shown in event feeds)").option("--by <name>","who the note is from (an agent id or a person's name)").option("--node <url>","daemon to publish on (default: dashboard.daemonUrl, else this machine on port 18800)").option("--token <token>","mesh token, needed only when --node is another machine (default: MESH_TOKEN)").action(async(e,t)=>{let o=t.node||"";if(!o)try{o=I().dashboard?.daemonUrl||""}catch{}o=(o||"http://localhost:18800").replace(/\/+$/,"");let n=t.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let i=await fetch(`${o}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...t.by?{by:t.by}:{}}),signal:AbortSignal.timeout(1e4)}),r=await i.json().catch(()=>({}));i.ok||(console.log(y.red(` Announcement refused (${i.status}): ${r.error||"unknown error"}`)),process.exit(1)),console.log(y.green(` \u2713 Announced from ${r.event?.node??"this machine"}`)+y.dim(` (event ${r.event?.id??"?"})`))}catch(i){console.log(y.red(` Could not reach the daemon at ${o}: ${i?.message||i}`)),process.exit(1)}});var Kt=new dt().name("skill").description("manage skills \u2014 add to agent(s), list");Kt.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,t)=>{let o=ce(),n=H(e);if(!fe(n)){console.log(y.red(` Skill not found: ${n}`));return}let s=fe(At(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(t.all)i=Object.keys(o.agents||{});else if(t.agent)i=t.agent;else{let r=Object.keys(o.agents||{});i=(await _e({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${o.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=o.agents[r];if(!a){console.log(y.yellow(` Agent "${r}" not found, skipping`));continue}let c=H(a.workspace,".claude/skills",s);lt(c,{recursive:!0}),fe(At(n,"SKILL.md"))?Ai(n,c,{recursive:!0}):n.endsWith(".md")&&Ai(n,At(c,"SKILL.md")),console.log(y.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Kt.command("list").alias("ls").description("list skills per agent").action(()=>{let e=ce();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=H(o.workspace,".claude/skills"),s=fe(n)?Oi(n).filter(i=>!i.startsWith(".")):[];console.log(` ${y.cyan(t)}: ${s.length?s.join(", "):y.dim("(none)")}`)}console.log()});Kt.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,t)=>{let{createHash:o}=await import("node:crypto"),n=process.cwd(),s=t.source?[t.source]:[H(n,"src",e,"SKILL.md"),H(n,"skills",e,"SKILL.md")],i=s.find(k=>fe(k));if(!i){console.log(y.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(y.dim(` ${k}`));return}let r=jt(i,"utf-8"),a=o("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=I()}catch(k){console.log(y.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(l.agents||{}),d=t.agent?g.filter(([k])=>k===t.agent):g;if(d.length===0){console.log(y.yellow(t.agent?` Agent "${t.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(y.bold(` Skill sync \u2014 ${e}`)),console.log(y.dim(` Source: ${i}`)),console.log(y.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(y.dim(` Mode: ${t.dryRun?"dry-run":"commit"}${t.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 v=b.workspace;if(!v||!fe(v)){console.log(` ${y.yellow("\u2717")} ${k.padEnd(22)} ${y.dim("(workspace missing: "+(v||"undefined")+")")}`),w++;continue}let A=H(v,".claude/skills",e),S=H(A,"SKILL.md");if(!fe(S)){if(!t.allWorkspaces){console.log(` ${y.dim("\xB7")} ${k.padEnd(22)} ${y.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}t.dryRun||(lt(A,{recursive:!0}),Ao(S,r)),console.log(` ${y.green("+")} ${k.padEnd(22)} ${y.dim("\u2192 seeded v"+c)}`),u++;continue}let x=jt(S,"utf-8");if(o("sha256").update(x).digest("hex").slice(0,12)===a){console.log(` ${y.dim("=")} ${k.padEnd(22)} ${y.dim("up to date (v"+c+")")}`),p++;continue}let R=(x.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();t.dryRun||Ao(S,r),console.log(` ${y.yellow("\u21BB")} ${k.padEnd(22)} ${y.dim(`v${R} \u2192 v${c}`)}`),f++}console.log();let h=t.dryRun?"would":"did";console.log(y.dim(` Summary: ${h} seed ${u}, ${h} update ${f}, ${p} already current, ${w} skipped.`)),t.dryRun&&(u>0||f>0)&&console.log(y.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Kt.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:t}=await import("./loader-EVHZ2R73.js"),{auditAll:o}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),i=[];if(e.workspace){let f=ce().agents?.[e.workspace];f||(console.log(y.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(H(f.workspace))}else if(e.allWorkspaces){let u=ce();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(H(f.workspace))}else i.push(H(e.cwd));let r=H(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>t(u)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=o({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"?y.green("PASS "):f.verdict==="REVIEW"?y.yellow("REVIEW "):y.red("FAILING");console.log(` ${p} ${y.bold(f.name)}${f.skill?.path?y.dim(` (${f.skill.path})`):""}`);for(let w of f.reasons)console.log(` ${y.dim("\xB7")} ${w}`)}console.log(),console.log(` ${y.green(`${u.PASS} PASS`)} ${y.yellow(`${u.REVIEW} REVIEW`)} ${y.red(`${u.FAILING} FAILING`)}`),console.log()}process.exit(d.some(u=>u.verdict==="FAILING")?1:0)});Kt.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,t)=>{let o=ce(),n=Object.entries(o.agents||{}),[s,i]=t.agent?n.find(([g])=>g===t.agent)??[]:n[0]??[];i||(console.log(y.red(` no such agent${t.agent?` "${t.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-EVHZ2R73.js"),{pickSkillForTask:a}=await import("./select-WOUZIR3Y.js"),c=await r(i.workspace);if(c.length===0){console.log(y.yellow(` ${s} has no skills`));return}let l=await a(c,e,{agent:s,minRelevant:Number(t.min)||.6});if(t.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(` ${y.green("\u2192")} ${y.bold(l.skill.frontmatter.name)} ${y.dim(`\xB7 ${l.reason}`)}`),console.log(` ${y.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${y.yellow("\xB7")} no skill for this ${y.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(y.dim(`
|
|
31
|
-
shortlist (lexical -> judged)`));for(let g of l.shortlist.slice(0,6)){let d=g.p===void 0?" - ":g.p.toFixed(2);console.log(
|
|
32
|
-
(lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var un=new dt().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");un.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,t)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(
|
|
33
|
-
--- ${w} ---`)),console.log(
|
|
34
|
-
`).slice(0,30).map(
|
|
35
|
-
`)),
|
|
36
|
-
`).length>30&&console.log(
|
|
37
|
-
`).length-30} more lines truncated in preview)`));console.log(),console.log(
|
|
38
|
-
Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await Ue(i),console.log(
|
|
39
|
-
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Ot=new dt().name("config").description("validate and inspect configuration");Ot.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 t=I(e.config);console.log(
|
|
30
|
+
`));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()});pn.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,t)=>{let o=ce();o.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=t.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-VV4X7PEK.js"),i=String(t.kind||"").trim();!i&&n&&(i=((await _e({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(t.label||"").trim();!r&&n&&(r=((await _e({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(t.tokenEnv||"").trim(),c=String(t.auth||"").trim(),l=String(t.sessionDir||"").trim();if(!a&&!c&&!l&&n){let u=await _e({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 _e({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 _e({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(t.metadata)for(let u of String(t.metadata).split(",")){let[f,...p]=u.split("=");f&&(g[f.trim()]=p.join("=").trim())}else if(n){let u=await _e({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)),o.agents[e].integrations=o.agents[e].integrations??[],o.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)),o.agents[e].integrations.push({kind:i,label:r,credentials:d,metadata:g,enabled:!0}),await Ue(o),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`))});pn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,t)=>{let o=ce(),n=o.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=t.includes(":")?t.split(":",2):[t,""],a=s.findIndex(l=>l.kind===i&&(!r||l.label===r)||l.label===t);a===-1&&(console.log(h.red(` No integration matched "${t}"`)),process.exit(1));let c=s.splice(a,1)[0];await Ue(o),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});pn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,t)=>{let n=ce().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=t?s.filter(a=>a.kind===t||a.label===t||`${a.kind}:${a.label}`===t):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)});Yt.addCommand(pn);var cs=new dt().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");cs.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ce();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(t.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let o=e.channels?.whatsapp;if(o?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${o.defaultAgent||"(none)"}`),console.log(` session: ${o.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of o.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()});cs.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ce(),t=Object.keys(e.agents||{});if(!t.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let o=t.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await _e({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 _e([{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:o}]);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 Ue(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await _e([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:o},{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 _e([{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:o},{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 Ue(e),lt(H(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 _e([{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 _e([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{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 Ue(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 jo=new dt().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");jo.command("list").alias("ls").description("list cron jobs").action(()=>{let e=ce();console.log();for(let[t,o]of Object.entries(e.crons||{})){let n=o.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(t)} \u2014 ${o.schedule} (${o.timezone})`),console.log(h.dim(` agent: ${o.agent} | timeout: ${o.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});jo.command("add").description("add a cron job").action(async()=>{let e=ce(),t=Object.keys(e.agents||{}),o=await _e([{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:t.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}]);!o.id||!o.schedule||(e.crons=e.crons||{},e.crons[o.id]={enabled:o.enabled,schedule:o.schedule,timezone:o.timezone,agent:o.agent,prompt:o.prompt,timeout:o.timeout,onError:["log"]},await Ue(e),console.log(h.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});jo.command("enable <id>").description("enable a cron job").action(async e=>{let t=ce();if(!t.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}if(t.crons[e].approval?.action==="create"){console.log(h.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}t.crons[e].enabled=!0,await Ue(t),console.log(h.green(` Cron "${e}" enabled`))});jo.command("disable <id>").description("disable a cron job").action(async e=>{let t=ce();if(!t.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await Ue(t),console.log(h.green(` Cron "${e}" disabled`))});var Vt=new dt().name("mesh").description("manage mesh peers \u2014 add, list, remove");Vt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=ce();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let o=h.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();o=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(t.name)} ${h.dim(t.url)} ${o}`)}}console.log()});Vt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=ce(),t=await _e([{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(!(!t.name||!t.url)){try{let n=await(await fetch(`${t.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:t.url,name:t.name,...t.token?{token:t.token}:{}}),await Ue(e),console.log(h.green(` Peer "${t.name}" added`)),console.log()}});Vt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=ce();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await Ue(t),console.log(h.green(` Peer "${e}" removed`)))});Vt.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 t=ce();if(t.mesh=t.mesh||{},t.mesh.healthCheck=t.mesh.healthCheck||{},e.show){console.log(` interval ${t.mesh.healthCheck.interval??60}s`),console.log(` timeout ${t.mesh.healthCheck.timeout??10}s`);return}let o=[];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)),t.mesh.healthCheck.interval=n,o.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)),t.mesh.healthCheck.timeout=n,o.push(`timeout=${n}s`)}o.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await Ue(t),console.log(h.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});Vt.command("announce <text...>").description("send a short note to every machine in the mesh (shown in event feeds)").option("--by <name>","who the note is from (an agent id or a person's name)").option("--node <url>","daemon to publish on (default: dashboard.daemonUrl, else this machine on port 18800)").option("--token <token>","mesh token, needed only when --node is another machine (default: MESH_TOKEN)").action(async(e,t)=>{let o=t.node||"";if(!o)try{o=I().dashboard?.daemonUrl||""}catch{}o=(o||"http://localhost:18800").replace(/\/+$/,"");let n=t.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let i=await fetch(`${o}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...t.by?{by:t.by}:{}}),signal:AbortSignal.timeout(1e4)}),r=await i.json().catch(()=>({}));i.ok||(console.log(h.red(` Announcement refused (${i.status}): ${r.error||"unknown error"}`)),process.exit(1)),console.log(h.green(` \u2713 Announced from ${r.event?.node??"this machine"}`)+h.dim(` (event ${r.event?.id??"?"})`))}catch(i){console.log(h.red(` Could not reach the daemon at ${o}: ${i?.message||i}`)),process.exit(1)}});var Kt=new dt().name("skill").description("manage skills \u2014 add to agent(s), list");Kt.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,t)=>{let o=ce(),n=H(e);if(!fe(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=fe(At(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(t.all)i=Object.keys(o.agents||{});else if(t.agent)i=t.agent;else{let r=Object.keys(o.agents||{});i=(await _e({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${o.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=o.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=H(a.workspace,".claude/skills",s);lt(c,{recursive:!0}),fe(At(n,"SKILL.md"))?Ai(n,c,{recursive:!0}):n.endsWith(".md")&&Ai(n,At(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Kt.command("list").alias("ls").description("list skills per agent").action(()=>{let e=ce();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=H(o.workspace,".claude/skills"),s=fe(n)?Oi(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(t)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});Kt.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,t)=>{let{createHash:o}=await import("node:crypto"),n=process.cwd(),s=t.source?[t.source]:[H(n,"src",e,"SKILL.md"),H(n,"skills",e,"SKILL.md")],i=s.find($=>fe($));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let $ of s)console.log(h.dim(` ${$}`));return}let r=jt(i,"utf-8"),a=o("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=I()}catch($){console.log(h.red(` Can't load agentx.json: ${$.message}`));return}let g=Object.entries(l.agents||{}),d=t.agent?g.filter(([$])=>$===t.agent):g;if(d.length===0){console.log(h.yellow(t.agent?` Agent "${t.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: ${t.dryRun?"dry-run":"commit"}${t.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,f=0,p=0,w=0;for(let[$,b]of d){let v=b.workspace;if(!v||!fe(v)){console.log(` ${h.yellow("\u2717")} ${$.padEnd(22)} ${h.dim("(workspace missing: "+(v||"undefined")+")")}`),w++;continue}let A=H(v,".claude/skills",e),S=H(A,"SKILL.md");if(!fe(S)){if(!t.allWorkspaces){console.log(` ${h.dim("\xB7")} ${$.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}t.dryRun||(lt(A,{recursive:!0}),Ao(S,r)),console.log(` ${h.green("+")} ${$.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let x=jt(S,"utf-8");if(o("sha256").update(x).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${$.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),p++;continue}let R=(x.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();t.dryRun||Ao(S,r),console.log(` ${h.yellow("\u21BB")} ${$.padEnd(22)} ${h.dim(`v${R} \u2192 v${c}`)}`),f++}console.log();let y=t.dryRun?"would":"did";console.log(h.dim(` Summary: ${y} seed ${u}, ${y} update ${f}, ${p} already current, ${w} skipped.`)),t.dryRun&&(u>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Kt.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:t}=await import("./loader-EVHZ2R73.js"),{auditAll:o}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),i=[];if(e.workspace){let f=ce().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(H(f.workspace))}else if(e.allWorkspaces){let u=ce();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(H(f.workspace))}else i.push(H(e.cwd));let r=H(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>t(u)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=o({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)});Kt.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,t)=>{let o=ce(),n=Object.entries(o.agents||{}),[s,i]=t.agent?n.find(([g])=>g===t.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${t.agent?` "${t.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-EVHZ2R73.js"),{pickSkillForTask:a}=await import("./select-WOUZIR3Y.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(t.min)||.6});if(t.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(`
|
|
31
|
+
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(`
|
|
32
|
+
(lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var un=new dt().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");un.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,t)=>{/^[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 o=H(t.cwd),n=H(o,"references/example"),s=H(o,"references/recipes/example.yaml");fe(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=H(o,".agentx/references",e),r=H(o,".agentx/references/recipes");lt(i,{recursive:!0}),lt(r,{recursive:!0});let a=Oi(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let u=At(i,d);if(fe(u)&&!t.force){console.log(h.dim(` skip ${u} (exists; --force to overwrite)`)),l++;continue}let p=jt(At(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);Ao(u,p),console.log(h.green(` + ${u}`)),c++}let g=At(r,`${e}.yaml`);if(fe(g)&&!t.force)console.log(h.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(fe(s)){let d=jt(s,"utf-8").replaceAll("example.",`${e}.`);Ao(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()});un.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,t)=>{/^[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:o}=await import("./loader-EVHZ2R73.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-7YFQNYLC.js"),i=H(t.cwd),r=t.from?String(t.from).split(",").map(w=>w.trim()).filter(Boolean):[e],a=await o(i),c=n(a,{namespace:e,filter:r,gitlabHost:t.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=H(t.referencesCwd||t.cwd),u=H(d,".agentx/references",e);if(!t.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(`
|
|
33
|
+
--- ${w} ---`)),console.log(y.split(`
|
|
34
|
+
`).slice(0,30).map($=>` ${$}`).join(`
|
|
35
|
+
`)),y.split(`
|
|
36
|
+
`).length>30&&console.log(h.dim(` \u2026 (${y.split(`
|
|
37
|
+
`).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}lt(u,{recursive:!0});let f=0,p=0;for(let[w,y]of Object.entries(g)){let $=At(u,w);if(fe($)&&!t.force){console.log(h.dim(` skip ${$} (exists; --force to overwrite)`)),p++;continue}Ao($,y),console.log(h.green(` + ${$}`)),f++}console.log(),console.log(h.dim(` ${f} written, ${p} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(h.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});un.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:t}=await import("./loader-KKMG24O5.js"),o=await t(H(e.cwd)),n=[...o.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=o.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 Ti=new dt().name("hook").description("manage hooks \u2014 add to agent workspace");Ti.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let o=ce().agents?.[e];if(!o){console.log(h.red(` Agent "${e}" not found`));return}let n=H(o.workspace,".claude/settings.json"),s=fe(n)?JSON.parse(jt(n,"utf-8")):{},i=await _e([{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),lt(H(o.workspace,".claude"),{recursive:!0}),Ao(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var Ii=new dt().name("migrate").description("import configuration from OpenClaw or other tools");Ii.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,t)=>{let o=[e,H(process.env.HOME||"",".openclaw/openclaw.json"),H(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of o)if(f&&fe(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(jt(n,"utf-8")),i=fe(H(process.cwd(),"agentx.json"))?ce():{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++,!t.dryRun){lt(H(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-42ARC42I.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=H(n,"../cron/jobs.json");if(fe(u)){let f=JSON.parse(jt(u,"utf-8")),p=0;for(let w of f.jobs||[]){let y=w.name||w.id,$=w.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[y]={enabled:w.enabled||!1,schedule:w.schedule?.expr||"0 9 * * *",timezone:w.schedule?.tz||"UTC",agent:$,prompt:w.payload?.message||"",timeout:w.payload?.timeoutSeconds||600,onError:["log"]},p++}console.log(` ${h.green(p)} cron jobs imported`)}t.dryRun?(console.log(h.yellow(`
|
|
38
|
+
Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await Ue(i),console.log(h.green(`
|
|
39
|
+
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Ot=new dt().name("config").description("validate and inspect configuration");Ot.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 t=I(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${t.node.name} (${t.node.id})`)),console.log(h.dim(` Bind: ${t.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(t.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(t.crons).length}`)),console.log(h.dim(` Mesh peers: ${t.mesh.peers.length}`));let o=Object.keys(t.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${t.channels.telegram.enabled?`${o} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${t.channels.whatsapp.enabled?`${t.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=Pn(t);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(t.agents)){let r=i.workspace,a=fe(H(r,".claude")),c=fe(H(r,"CLAUDE.md")),l=fe(H(r,".claude/settings.json")),g=fe(H(r,".claude/skills"))?Oi(H(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(t){console.log(h.red(` \u2717 ${t.message}`))}console.log()});Ot.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let t=I(e.config);console.log(JSON.stringify(t,null,2))}catch(t){console.log(h.red(t.message))}});function ep(e,t){if(t)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(o=>o.trim()).filter(Boolean):e}function ji(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Ot.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,t)=>{let{readFileSync:o,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-BOE7SMT5.js"),{expandEnvVars:r}=await import("./config-VV4X7PEK.js"),a=t.config||s(process.cwd(),"agentx.json");n(a)||(console.log(h.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(o(a,"utf-8")),l=t.raw?c:r(c),g=i(l,e);t.json?console.log(JSON.stringify(g)):console.log(ji(g))});Ot.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,t,o)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:i}=await import("./config-mutator-BOE7SMT5.js"),r=ep(t,!!o.string),a=await n(l=>{s(l,e,r)},{configPath:o.config,dryRun:!!o.dryRun});a.success||(console.log(h.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);o.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would become: ${ji(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${ji(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})`)))});Ot.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,t)=>{let{applyConfigMutation:o,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-BOE7SMT5.js"),i=await o(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:t.config,dryRun:!!t.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}t.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.")))});Ot.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 t=!1,o=0,n;try{let d=I(e.config);t=!!d.business?.enabled,o=(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&&t,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:t,active:a,projects:o},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 ${t?h.green("true"):h.dim("false")}`)),console.log(h.dim(` business.projects[] ${o}`)),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 tp}from"commander";import Tt from"chalk";import{resolve as It}from"path";import{existsSync as op}from"fs";var ht=new tp().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Xt(e){let t=It(e,".agentx/db.sqlite");op(t)||(console.log(Tt.red(` No SQLite at ${t}`)),console.log(Tt.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let o=Yr({path:t});return o||(console.log(Tt.red(` Could not open ${t}`)),console.log(Tt.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),o}function Qt(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Tt.dim(" (no rows)"));return}let o=Object.keys(e[0]),n=o.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(o)),console.log(o.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(o.map(r=>i[r])))}ht.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 t=Xt(It(e.cwd)),o=[],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent),e.day&&(o.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(o.push("status = @status"),n.status=e.status);let s=`
|
|
40
40
|
SELECT agent_id, channel, status, duration_ms,
|
|
41
41
|
input_tokens, output_tokens,
|
|
42
42
|
substr(message_preview, 1, 60) AS message,
|
|
@@ -142,7 +142,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
142
142
|
ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
|
|
143
143
|
WHERE d.event_id IN (${a})
|
|
144
144
|
ORDER BY d.decided_at ASC
|
|
145
|
-
`).all(c);if(t.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),
|
|
145
|
+
`).all(c);if(t.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("-"),$=p.reason?z.dim(` \u2014 ${p.reason.slice(0,60)}`):"";if(console.log(` ${z.dim(p.decided_by)} \u2192 ${w} ${y}${$}`),p.resolution_status){let b=p.resolution_status==="ok"?z.green(p.resolution_status):z.red(p.resolution_status),v=p.duration_ms?`${(p.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${z.dim("resolved")} ${b} ${z.dim(v)}`)}else p.outcome==="dispatched"&&console.log(` ${z.yellow("(in-flight, no resolution)")}`)}}console.log()});Ct.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 t=Oo(e),o=ls(e.since),n=[],s={};e.source&&(n.push("source = @source"),s.source=e.source),o!==void 0&&(n.push("ts >= @since"),s.since=o);let i=e.limit?`LIMIT ${Number(e.limit)}`:"",r=t.prepare(`
|
|
146
146
|
SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
|
|
147
147
|
FROM intent_events
|
|
148
148
|
${n.length?"WHERE "+n.join(" AND "):""}
|
|
@@ -212,7 +212,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
212
212
|
WHERE name = 'tool_use' AND action IS NOT NULL
|
|
213
213
|
AND task_id IN (SELECT task_id FROM task_traces WHERE ${a})
|
|
214
214
|
ORDER BY task_id, seq
|
|
215
|
-
`).all(...r);for(let d of g){let u=l.get(d.task_id)??[];u.push(d.action),l.set(d.task_id,u)}return c.map(d=>{let u=d.task_id,f=d.agent_id,p=Ea({taskId:u,agentId:f,channel:d.channel??"unknown",chatId:d.chat_id??"",startedAt:d.started_at,userMessage:(d.original_message??d.message_preview??"").trim(),userTurns:[],actions:l.get(u)??[],actionSummaries:[]}),w=Sl.map(
|
|
215
|
+
`).all(...r);for(let d of g){let u=l.get(d.task_id)??[];u.push(d.action),l.set(d.task_id,u)}return c.map(d=>{let u=d.task_id,f=d.agent_id,p=Ea({taskId:u,agentId:f,channel:d.channel??"unknown",chatId:d.chat_id??"",startedAt:d.started_at,userMessage:(d.original_message??d.message_preview??"").trim(),userTurns:[],actions:l.get(u)??[],actionSummaries:[]}),w=Sl.map(y=>d[y]).filter(y=>typeof y=="number");return{taskId:u,agentId:f,cluster:p,startedAt:d.started_at,ok:d.status==="ok",tokens:w.length>0?w.reduce((y,$)=>y+$,0):null,turns:d.num_turns??null,durationMs:d.duration_ms??null,injected:aa(d.injected_context)}})}function _i(e){return e.injected?[...e.injected.memory.map(t=>`memory:${t}`),...e.injected.procedures.map(t=>`procedure:${t}`),...e.injected.wiki?["wiki"]:[]]:[]}function Di(e){let t=e.filter(n=>n!==null).sort((n,s)=>n-s);if(t.length===0)return null;let o=Math.floor(t.length/2);return t.length%2?t[o]:(t[o-1]+t[o])/2}function El(e){return{n:e.length,successRate:e.length?e.filter(t=>t.ok).length/e.length:0,medianTokens:Di(e.map(t=>t.tokens)),medianTurns:Di(e.map(t=>t.turns)),medianDurationMs:Di(e.map(t=>t.durationMs))}}function jl(e,t={}){let o=Math.max(1,t.minSamples??2),n=new Map,s=new Map;for(let r of e){for(let l of _i(r)){let g=`${r.agentId}\0${l}`;n.set(g,Math.min(n.get(g)??1/0,r.startedAt))}let a=`${r.agentId}\0${r.cluster}`,c=s.get(a)??[];c.push(r),s.set(a,c)}let i=[];for(let r of s.values()){let{agentId:a,cluster:c}=r[0],l=new Set(r.flatMap(_i));for(let g of l){let d=n.get(`${a}\0${g}`),u=r.filter(p=>p.injected!==null&&p.startedAt<d),f=r.filter(p=>_i(p).includes(g));u.length<o||f.length<o||i.push({agentId:a,cluster:c,lesson:g,addedAt:d,before:El(u),after:El(f)})}}return i.sort((r,a)=>r.agentId.localeCompare(a.agentId)||r.cluster.localeCompare(a.cluster)||r.addedAt-a.addedAt)}import Nt from"chalk";function fp(e){return e==null?"\u2014":e>=1e3?`${(e/1e3).toFixed(1)}k`:`${Math.round(e)}`}function hp(e){return e==null?"\u2014":e>=6e4?`${(e/6e4).toFixed(1)}m`:`${(e/1e3).toFixed(1)}s`}function yp(e){return e==null?"\u2014":Number.isInteger(e)?`${e}`:e.toFixed(1)}function Pi(e,t){if(e==null||t==null||e===0)return"";let o=Math.round((t-e)/e*100);return o===0?" (=)":` (${o>0?"+":""}${o}%)`}function Ol(e,t,o){let n=`${Math.round(t.successRate*100)}%`,s=o?` (${t.successRate>=o.successRate?"+":""}${Math.round((t.successRate-o.successRate)*100)} pts)`:"";return[` ${e.padEnd(6)} n=${String(t.n).padEnd(4)}`,`success ${n}${s}`,`tokens ${fp(t.medianTokens)}${o?Pi(o.medianTokens,t.medianTokens):""}`,`turns ${yp(t.medianTurns)}${o?Pi(o.medianTurns,t.medianTurns):""}`,`time ${hp(t.medianDurationMs)}${o?Pi(o.medianDurationMs,t.medianDurationMs):""}`].join(" ")}function Tl(e,t){if(e.length===0)return[Nt.dim(` No lesson has at least ${t.minSamples} recorded task(s) before and after it yet.`),Nt.dim(" Tasks record which lessons they used from this version on; repeated tasks need time to build up.")];let o=[],n="";for(let s of e){let i=`${s.agentId} ${s.cluster}`;i!==n&&(n&&o.push(""),o.push(`${Nt.bold(s.agentId)} ${Nt.cyan(s.cluster)}`),n=i),o.push(` ${Nt.yellow(s.lesson)} ${Nt.dim(`first used ${new Date(s.addedAt).toISOString().slice(0,10)}`)}`),o.push(Nt.dim(Ol("before",s.before))),o.push(Ol("after",s.after,s.before))}return o.push(""),o.push(Nt.dim(" Medians per task. Small samples are noisy: treat a change as a hint until n grows.")),o}var To=new wp().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function gs(e){let t=Il(e.cwd??process.cwd()),o=Il(t,e.path??".agentx/db.sqlite");bp(o)||(console.log(O.red(` No db at ${o}`)),console.log(O.dim(" The file is created on first SQLite write \u2014 start the daemon and run a task.")),process.exit(1));try{return new $p(o,{readonly:!0})}catch(n){console.log(O.red(` Could not open ${o}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(O.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function kp(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let o=Number(t[1]),n=t[2];return o*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function Cl(e){if(!e)return;let t=kp(e);if(t===null){let o=Number(e);if(Number.isFinite(o)&&o>0)return o;console.log(O.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-t}function vp(e){let t=Math.round((Date.now()-e)/1e3);return t<60?`${t}s ago`:t<3600?`${Math.round(t/60)}m ago`:t<86400?`${Math.round(t/3600)}h ago`:`${Math.round(t/86400)}d ago`}function Mi(e){return e==="ok"?O.green:e==="error"||e==="timeout"?O.red:e==="in-flight"?O.yellow:O.dim}To.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 t=gs(e),o=ca(t,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:Cl(e.since),limit:parseInt(e.limit,10)||50});if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(O.dim(" (no traces)"));return}for(let n of o){let s=Mi(n.status)(n.status.padEnd(9)),i=n.durationMs!=null?`${(n.durationMs/1e3).toFixed(2)}s`:"\u2014",r=n.workflowRunId?O.cyan(` wf=${n.workflowRunId}`):"",a=n.inputTokens!=null?O.dim(` ${n.inputTokens}/${n.outputTokens??0} tok`):"";console.log(`${O.dim(n.taskId)} ${s} ${O.bold(n.agentId)}${O.dim(` ${n.channel??"\u2014"}:${n.chatId??"\u2014"}`)}${r} ${O.dim("\xB7")} ${i}${a} ${O.dim(vp(n.startedAt))}`),n.error&&console.log(` ${O.red("error:")} ${n.error}`)}});To.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,t)=>{let o=gs(t),n=oi(o,e);if(n||(console.log(O.red(` No trace at ${e}`)),process.exit(1)),t.json){console.log(JSON.stringify(n,null,2));return}xp(n.task,n.steps)});function xp(e,t){let o=Mi(e.status)(e.status);if(console.log(O.bold(`Trace ${e.taskId}`)),console.log(` ${O.dim("agent")} ${e.agentId}`),console.log(` ${O.dim("channel")} ${e.channel??"\u2014"}:${e.chatId??"\u2014"}`),e.workflowRunId){let n=[e.workflowId,e.workflowNodeId].filter(Boolean).join("/");console.log(` ${O.dim("workflow")} ${O.cyan(e.workflowRunId)}${n?O.dim(` (${n})`):""}`)}if(e.intentEventId&&console.log(` ${O.dim("intent")} ${e.intentEventId} ${O.dim(`(${e.intentDecidedBy??"?"})`)}`),e.model&&console.log(` ${O.dim("model")} ${e.model}`),e.resumeSessionId&&console.log(` ${O.dim("resume")} ${e.resumeSessionId.slice(0,12)}\u2026`),e.finalSessionId&&console.log(` ${O.dim("final")} ${e.finalSessionId.slice(0,12)}\u2026`),console.log(` ${O.dim("status")} ${o}`),e.durationMs!=null&&console.log(` ${O.dim("duration")} ${(e.durationMs/1e3).toFixed(2)}s`),(e.inputTokens!=null||e.outputTokens!=null)&&console.log(` ${O.dim("tokens")} in=${e.inputTokens??0} out=${e.outputTokens??0} cache_read=${e.cacheReadTokens??0} cache_create=${e.cacheCreateTokens??0}`),e.numTurns!=null&&console.log(` ${O.dim("turns")} ${e.numTurns}`),e.injectedContext){let{memory:n,procedures:s,wiki:i}=e.injectedContext,r=[...n.map(a=>`memory:${a}`),...s.map(a=>`procedure:${a}`),...i?["wiki"]:[]];console.log(` ${O.dim("lessons")} ${r.length?r.join(" "):O.dim("none")}`)}if(e.error&&console.log(` ${O.red("error")} ${e.error}`),e.messagePreview&&console.log(` ${O.dim("message")} ${e.messagePreview}`),console.log(),t.length===0){console.log(O.dim(" (no recorded steps \u2014 task may have been on a non-streaming tier or completed before any tool call)"));return}console.log(O.bold(`Steps (${t.length}):`));for(let n of t){let s=n.status?Mi(n.status)(n.status):O.dim("\u2014"),i=n.action?O.cyan(n.action):"";if(console.log(` ${O.dim(`#${n.seq}`)} ${O.bold(n.name)}${i?" "+i:""} ${s}${n.ms!=null?O.dim(` ${n.ms}ms`):""}`),n.inputSummary){let r=n.inputSummary.split(`
|
|
216
216
|
`).slice(0,8);console.log(r.map(a=>` ${O.dim("\u2192")} ${a}`).join(`
|
|
217
217
|
`)),n.inputSummary.split(`
|
|
218
218
|
`).length>8&&console.log(` ${O.dim("\u2026")}`)}if(n.outputSummary){let r=n.outputSummary.split(`
|
|
@@ -368,10 +368,10 @@ return id`:`${n}
|
|
|
368
368
|
const arrow = helpers.createArrowBetweenShapes(createShapeId(${o(e.from)}), createShapeId(${o(e.to)}), el.label ? { richText: toRichText(el.label) } : {})
|
|
369
369
|
const aid = typeof arrow === 'string' ? arrow : arrow?.id
|
|
370
370
|
if (aid) editor.updateShape({ id: aid, type: 'arrow', props: { color: el.color } })
|
|
371
|
-
return aid ?? null`}function Yu(e,t){if(e.kind==="path"){let s=e.pts,i=s[Math.floor(s.length/2)];return[yt(s[0][0],s[0][1]),yt(i[0],i[1])]}if(e.kind==="geo")return[yt(e.x,e.y),yt(e.x+e.w,e.y+e.h)];if(e.kind==="text"){let s=wd(e);return[yt(s.x,s.y+s.h/2),yt(s.x+s.w,s.y+s.h/2)]}let o=t.get(e.from),n=t.get(e.to);return[yt(o.x+o.w/2,o.y+o.h/2),yt(n.x+n.w/2,n.y+n.h/2)]}var yt=(e,t)=>({x:e,y:t,w:0,h:0});async function $d(e,t,o,n=()=>{}){let s=t.sleep??(x=>new Promise(
|
|
371
|
+
return aid ?? null`}function Yu(e,t){if(e.kind==="path"){let s=e.pts,i=s[Math.floor(s.length/2)];return[yt(s[0][0],s[0][1]),yt(i[0],i[1])]}if(e.kind==="geo")return[yt(e.x,e.y),yt(e.x+e.w,e.y+e.h)];if(e.kind==="text"){let s=wd(e);return[yt(s.x,s.y+s.h/2),yt(s.x+s.w,s.y+s.h/2)]}let o=t.get(e.from),n=t.get(e.to);return[yt(o.x+o.w/2,o.y+o.h/2),yt(n.x+n.w/2,n.y+n.h/2)]}var yt=(e,t)=>({x:e,y:t,w:0,h:0});async function $d(e,t,o,n=()=>{}){let s=t.sleep??(x=>new Promise(k=>setTimeout(k,x))),i=t.now??Date.now,r=o.stepMs??1500,a=o.runTag??i().toString(36),c=i(),l=await t.api.exec(o.docId,Hu(60)),g=new Set,d=new Map,u=[],f=!1,p=0,w=null,y=null,$=null,b=()=>{$?.(),$=null},v=x=>{if(g.size>=Ji)return;let k=hd(x,g);if(!k){x.trim()&&n({type:"skipped",line:x.slice(0,120)});return}g.add(k.id),w??=i()-c,u.push(k),n({type:"planned",n:g.size,el:k,atMs:i()-c}),b()},A=(async()=>{let x=new bs;try{for await(let k of t.model.reply(`Draw: ${e}`,o.signal))x.push(k).forEach(v);x.flush().forEach(v)}catch(k){y=k?.message??String(k)}finally{p=i()-c,f=!0,b()}})(),S=0;for(;!o.signal?.aborted;){let x=u.shift();if(!x){if(f)break;await new Promise(P=>{$=P});continue}if(x.kind==="arrow"&&!(d.has(x.from)&&d.has(x.to))){n({type:"error",error:`${x.id}: an end was not drawn`});continue}let k=i();if(x.kind==="palette"){x.say&&t.presence.say(x.say);try{await t.api.exec(o.docId,bd(x))}catch(P){n({type:"error",error:`palette: ${P?.message??P}`});continue}S++,n({type:"drawn",n:S,el:x,ms:i()-k});continue}let[R,C]=Yu(x,d);x.say&&t.presence.say(x.say),t.presence.moveTo(yd(l,R.x,R.y)),await s(250),t.presence.moveTo(yd(l,C.x,C.y));try{await t.api.exec(o.docId,zu(x,a))}catch(P){n({type:"error",error:`${x.id}: ${P?.message??P}`});continue}d.set(x.id,x.kind==="geo"?x:x.kind==="text"?wd(x):x.kind==="path"?Gu(x.pts):yt(0,0)),S++,n({type:"drawn",n:S,el:x,ms:i()-k});let T=(x.say?r:0)-(i()-k);T>0&&await s(T)}return await A,y&&n({type:"error",error:`plan: ${y}`}),t.presence.park(),{steps:S,totalMs:i()-c,firstLineMs:w,planMs:p}}import{readFileSync as Vu}from"fs";import{homedir as Ku}from"os";import{join as Xu}from"path";var $n=Xu(Ku(),"Library","Application Support","tldraw","server.json"),$s=class{constructor(t=$n,o=fetch){this.serverJson=t;this.fetchFn=o}server(){let t;try{t=Vu(this.serverJson,"utf8")}catch{throw new Error("tldraw offline is not running (no server.json)")}let{port:o,token:n}=JSON.parse(t);return{port:o,token:n}}async post(t,o){let{port:n,token:s}=this.server(),i=await this.fetchFn(`http://localhost:${n}${t}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${s}`},body:JSON.stringify(o)}),r=await i.json();if(!i.ok||r.success===!1)throw new Error(`tldraw ${t}: ${r.error??i.status}`);return r.result}createDoc(t,o){return this.post("/api/docs/create",{name:t,...o?{directory:o}:{}})}exec(t,o){return this.post(`/api/doc/${t}/exec`,{code:o})}search(t){return this.post("/api/search",{code:t})}};var nf=of(Qu),sf="claude-sonnet-5";function rf(e){e.type==="planned"?console.log(st.dim(` planned ${e.n}: ${e.el.kind} ${e.el.id} at ${(e.atMs/1e3).toFixed(1)} s`)):e.type==="drawn"?console.log(`${st.cyan(` ${e.n}. ${e.el.kind} ${e.el.id}`)} ${e.el.say}${st.dim(` (${(e.ms/1e3).toFixed(1)} s)`)}`):e.type==="skipped"?console.log(st.yellow(` skipped: ${e.line}`)):console.log(st.red(` error: ${e.error}`))}async function af(){if(!Hi($n)){await nf("open",["-a","tldraw offline"]);for(let e=0;e<40&&!Hi($n);e++)await new Promise(t=>setTimeout(t,500));if(!Hi($n))throw new Error("tldraw offline did not start")}}async function vd(e,t){let o=I(t.config),n=t.agent||process.env.AGENTX_VOICE_AGENT||o.node.defaultAgent;if(!n||!o.agents[n])throw new Error(`Unknown agent: ${n}`);let s=t.model||sf,i=tf(t.out||kd(ef(),"Documents")),r=wo(n,o.agents[n]),a=$o({system:fd(),model:s}),c=new Yn(r,Re,n),l=new $s;try{await af();let g=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),d=await l.createDoc(`agentx-draw-${g}`,i);await new Promise($=>setTimeout($,800)),console.log(st.bold(`
|
|
372
372
|
${r.name} draws: ${e}`)+st.dim(` (${s}, ${d.filePath})
|
|
373
373
|
`));let u=new AbortController;process.once("SIGINT",()=>u.abort());let f=await $d(e,{api:l,presence:c,model:a},{docId:d.id,signal:u.signal},rf);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"):kd(i,`agentx-draw-${g}.png`);Zu(w,Buffer.from(p.slice(p.indexOf(",")+1),"base64")),console.log(st.bold(`
|
|
374
|
-
${f.steps} steps in ${(f.totalMs/1e3).toFixed(1)} s`)+st.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
|
|
374
|
+
${f.steps} steps in ${(f.totalMs/1e3).toFixed(1)} s`)+st.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(st.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(st.dim(` ${d.filePath}
|
|
375
375
|
${w}
|
|
376
376
|
`))}finally{a.close(),c.close()}}var zi=df(lf),Ed=new cf().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, "${Et}" 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,t)=>{if(t.live)try{t.mode==="draw"?await vd(String(t.live),t):await dd(String(t.live),t),process.exit(0)}catch(g){console.log(ee.red(` ${g?.message??g}`)),process.exit(1)}if(!e){console.log(ee.bold(`
|
|
377
377
|
lessons
|
|
@@ -379,12 +379,12 @@ return aid ?? null`}function Yu(e,t){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
|
|
|
379
379
|
`);return}let o=Wi.find(g=>g.id===e);o||(console.log(ee.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),gf(Re)||(console.log(ee.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let n=t.speak===!1?void 0:hf(t.voice,t.agent);console.log(ee.bold(`
|
|
380
380
|
${o.title}`)),console.log(ee.dim(` ${o.appHint}
|
|
381
381
|
`));try{o.start&&(await zi("/usr/bin/open",uf(o.start)),await Dt(2e3),await ks(o.start.ready))}catch(g){console.log(ee.red(` setup stopped: ${g?.message??g}`)),process.exitCode=3;return}let s=null,i=null;t.record&&(i=Sd(t.recordDir||process.cwd(),`teach-${o.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(ee.dim(` recording \u2192 ${i}`)),s=xd("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await Dt(2e3));let r=t.hud===!1?null:xd(Re,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(g,d,u,f)=>{try{r?.stdin?.write(JSON.stringify({title:g,body:d,state:u,avoid:f})+`
|
|
382
|
-
`)}catch{}},c=[],l=!1;try{for(let[g,d]of o.steps.entries()){if(console.log(` ${ee.dim(String(g+1).padStart(2))} ${d.say}`),a(`Step ${g+1} of ${o.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 ks(d.before)}let u=t.speak===!1?Promise.resolve():wf(d.say,n),f=d.find?await ff(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 ${o.steps.length}`,d.say,"pointing",{x:f.x,y:f.y,w:f.width,h:f.height}),await zi(Re,["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 Gi(["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(ee.yellow(" \xB7 clicked, but the screen did not change")),await Dt(d.afterClickWaitMs??1500)}if(d.type){await ks(d.before),a(`Step ${g+1} of ${o.steps.length}`,d.type,"typing");let{error:p}=await Gi(["type","--text",d.type]);if(p)throw console.log(ee.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 ks(d.before),a(`Step ${g+1} of ${o.steps.length}`,`\u21B5 ${d.key}`,"typing");let{error:p}=await Gi(["key","--name",d.key]);if(p)throw console.log(ee.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 Dt((d.holdSeconds??1.2)*1e3):d.holdSeconds&&await Dt(d.holdSeconds*1e3),d.verify){a(`Step ${g+1} of ${o.steps.length}`,"Checking that worked\u2026","waiting");let p=!!(d.click||d.type||d.key),w;try{w=await wn(d.verify,p?{settle:!0,screen:at()}:{})}catch(
|
|
382
|
+
`)}catch{}},c=[],l=!1;try{for(let[g,d]of o.steps.entries()){if(console.log(` ${ee.dim(String(g+1).padStart(2))} ${d.say}`),a(`Step ${g+1} of ${o.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 ks(d.before)}let u=t.speak===!1?Promise.resolve():wf(d.say,n),f=d.find?await ff(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 ${o.steps.length}`,d.say,"pointing",{x:f.x,y:f.y,w:f.width,h:f.height}),await zi(Re,["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 Gi(["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(ee.yellow(" \xB7 clicked, but the screen did not change")),await Dt(d.afterClickWaitMs??1500)}if(d.type){await ks(d.before),a(`Step ${g+1} of ${o.steps.length}`,d.type,"typing");let{error:p}=await Gi(["type","--text",d.type]);if(p)throw console.log(ee.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 ks(d.before),a(`Step ${g+1} of ${o.steps.length}`,`\u21B5 ${d.key}`,"typing");let{error:p}=await Gi(["key","--name",d.key]);if(p)throw console.log(ee.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 Dt((d.holdSeconds??1.2)*1e3):d.holdSeconds&&await Dt(d.holdSeconds*1e3),d.verify){a(`Step ${g+1} of ${o.steps.length}`,"Checking that worked\u2026","waiting");let p=!!(d.click||d.type||d.key),w;try{w=await wn(d.verify,p?{settle:!0,screen:at()}:{})}catch(y){w=null,console.log(ee.yellow(` ? could not check: ${y?.message??y}`))}if(!w&&!d.verifyOptional)throw new Error(`Could not verify: ${d.verify}`);if(w){let y=w.outcome==="confirmed"?ee.green("\u2713"):w.outcome==="refuted"?ee.red("\u2717"):ee.yellow("?");if(console.log(` ${y} ${ee.dim(w.reason)}`),!w.ok&&!d.verifyOptional){a("Stopped",`That did not work: ${d.verify}`,"waiting"),console.log(ee.red(`
|
|
383
383
|
stopping: could not confirm \u2014 ${d.verify}`)),console.log(ee.dim(` ${w.reason}`)),console.log(ee.dim(` screenshot: ${w.sighting.shot.path}`)),await Dt(2500);try{r?.stdin?.end()}catch{}l=!0;break}}}}}catch(g){l=!0,console.log(ee.red(` stopping: ${g?.message??g}`)),a("Stopped",String(g?.message??g),"waiting")}finally{if(l)try{r?.stdin?.end()}catch{}}if(!l){a("Done",o.title,"done"),await Dt(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await Dt(2500);try{let{size:g}=mf(i);console.log(ee.green(` recorded ${(g/1048576).toFixed(1)} MB \u2192 ${i}`))}catch{console.log(ee.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(l){console.log(ee.red(` lesson stopped before the end.
|
|
384
384
|
`)),process.exitCode=3;return}console.log(ee.green(`
|
|
385
385
|
done.
|
|
386
386
|
`))});function uf(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${Sd(pf(),"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 ks(e){let t=await wn(e);if(!t.ok)throw new Error(`Not ready: ${e}. ${t.reason}`)}async function Gi(e){try{let{stdout:t}=await zi(Re,e),o=JSON.parse(t||"{}");return o.ok===!1?{error:String(o.error??"refused")}:{error:null,changed:o.changed}}catch(t){try{let o=JSON.parse(t?.stdout||"{}");if(o.error)return{error:String(o.error)}}catch{}return{error:t?.message??"failed"}}}async function ff(e,t=[]){try{let o=await Vn({max:45});if(o.candidates.length<2)return null;let n=await rt(hn,ps({request:e,app:o.app,window:o.window,candidates:o.candidates,priorAttempts:t}),us(o.candidates),{features:{app:o.app,via:"teach",ocr:o.usedOCR}});if(!n)return null;let s=fs(n.answers,o.candidates);return s.present<.5?null:an(o,s.id)}catch{return null}}function hf(e,t){if(e?.trim().toLowerCase()===Et)return{provider:"system",elevenlabs:rn(),system:null,fallback:!0};let o=e?Gn(e,sn()):null;if(o)return{provider:"system",elevenlabs:rn(),system:o.id,fallback:!0};if(e)return{provider:"elevenlabs",elevenlabs:e,system:null,fallback:!0};try{let n=I(),s=t||process.env.AGENTX_VOICE_AGENT||n.node.defaultAgent;return s&&!n.agents[s]&&console.log(ee.yellow(` no agent "${s}" in agentx.json \u2014 using the default voice`)),s&&n.agents[s]?yc(fc(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:rn(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(ee.dim(` no agent voice (${String(n?.message??n).split(`
|
|
387
|
-
`)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:rn(),system:null,fallback:!0}}}var yf=new bo;async function wf(e,t){t&&await yf.say({voice:t,text:e})}var Dt=e=>new Promise(t=>setTimeout(t,e));ae();import{Command as Ad}from"commander";import He from"chalk";import{createInterface as jd}from"readline";var bf=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function No(e,t,o){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(bf()+t,{method:e,headers:n,body:o?JSON.stringify(o):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function $f(e){e.type==="line"?console.log(`${He.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(He.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(He.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(He.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(He.dim(" \xB7 hushed")):e.type==="error"?console.log(He.red(` error: ${e.error}`)):e.type==="end"&&console.log(He.dim(` \xB7 ended (${e.reason})`))}function Od(e){if(!e.length)return"no hand-overs measured";let t=[...e].sort((n,s)=>n-s);return`gap between speakers: median ${t[Math.floor(t.length/2)]} ms, max ${t.at(-1)} ms over ${e.length} hand-overs`}async function kf(e,t,o){let n=I(o.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await No("GET","/mesh").then(u=>Array.isArray(u.data)?u.data:[]).catch(()=>[]);i=new bc(()=>n,()=>d),i.usePool(await wc(uc()))}let r=e.map(d=>s[d]?zn(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 xc({topic:t,context:o.context,maxTurns:Number(o.turns)||10,speakers:r,speech:new bo,listener:n.voice.listener,model:(d,u)=>$o({system:u})});l.on($f),l.on(d=>{d.type==="line"&&d.turn===0&&console.log(He.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=jd({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(He.dim(` ${Od(l.gaps)}`))}async function vf(e,t,o){let n=await No("POST","/talk",{agents:e,topic:t,context:o.context,maxTurns:Number(o.turns)||void 0});if(n.status>=300)throw new Error(n.data.error||`HTTP ${n.status}`);let s=jd({input:process.stdin});s.on("line",a=>{a.trim()&&No("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void No("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await No("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${He.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(He.dim(` ${Od(r)}`))}var Td=new Ad().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,t,o,n)=>{let s=o.join(" ");try{await(n.local?kf:vf)([e,t],s,n),process.exit(0)}catch(i){console.error(He.red(` ${i?.message??i}`)),process.exit(1)}}),Id=new Ad().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,t,o)=>{let n=t==="on"?!0:t==="off"?!1:t==="default"?null:void 0;n===void 0&&(console.error(He.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await No("POST","/narration",{[o.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(He.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});ae();import{Command as xf}from"commander";import ne from"chalk";import{existsSync as Sf,readFileSync as Nd,writeFileSync as Rd}from"fs";import{resolve as Cd}from"path";tm();var Ro=new xf().name("voice").description("list installed system voices and pick each agent's voice");function Yi(e){let t=e?[e]:[Cd(process.cwd(),"agentx.json"),Cd(process.cwd(),".agentx/config.json")],o=t.find(n=>Sf(n));if(!o)throw new Error(`No config found. Searched: ${t.join(", ")}`);return o}function Ef(e,t,o,n,s){let{provider:i,gender:r}=n,a=n.lang?.toLowerCase().split(/[-_]/)[0],c=e?.agents?.[t];if(!c)throw new Error(`No agent "${t}" 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&&!o)throw new Error("--lang needs a voice");if(!o&&!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
|
|
387
|
+
`)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:rn(),system:null,fallback:!0}}}var yf=new bo;async function wf(e,t){t&&await yf.say({voice:t,text:e})}var Dt=e=>new Promise(t=>setTimeout(t,e));ae();import{Command as Ad}from"commander";import He from"chalk";import{createInterface as jd}from"readline";var bf=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function No(e,t,o){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(bf()+t,{method:e,headers:n,body:o?JSON.stringify(o):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function $f(e){e.type==="line"?console.log(`${He.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(He.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(He.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(He.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(He.dim(" \xB7 hushed")):e.type==="error"?console.log(He.red(` error: ${e.error}`)):e.type==="end"&&console.log(He.dim(` \xB7 ended (${e.reason})`))}function Od(e){if(!e.length)return"no hand-overs measured";let t=[...e].sort((n,s)=>n-s);return`gap between speakers: median ${t[Math.floor(t.length/2)]} ms, max ${t.at(-1)} ms over ${e.length} hand-overs`}async function kf(e,t,o){let n=I(o.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await No("GET","/mesh").then(u=>Array.isArray(u.data)?u.data:[]).catch(()=>[]);i=new bc(()=>n,()=>d),i.usePool(await wc(uc()))}let r=e.map(d=>s[d]?zn(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 xc({topic:t,context:o.context,maxTurns:Number(o.turns)||10,speakers:r,speech:new bo,listener:n.voice.listener,model:(d,u)=>$o({system:u})});l.on($f),l.on(d=>{d.type==="line"&&d.turn===0&&console.log(He.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=jd({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(He.dim(` ${Od(l.gaps)}`))}async function vf(e,t,o){let n=await No("POST","/talk",{agents:e,topic:t,context:o.context,maxTurns:Number(o.turns)||void 0});if(n.status>=300)throw new Error(n.data.error||`HTTP ${n.status}`);let s=jd({input:process.stdin});s.on("line",a=>{a.trim()&&No("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void No("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await No("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${He.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(He.dim(` ${Od(r)}`))}var Td=new Ad().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,t,o,n)=>{let s=o.join(" ");try{await(n.local?kf:vf)([e,t],s,n),process.exit(0)}catch(i){console.error(He.red(` ${i?.message??i}`)),process.exit(1)}}),Id=new Ad().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,t,o)=>{let n=t==="on"?!0:t==="off"?!1:t==="default"?null:void 0;n===void 0&&(console.error(He.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await No("POST","/narration",{[o.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(He.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});ae();import{Command as xf}from"commander";import ne from"chalk";import{existsSync as Sf,readFileSync as Nd,writeFileSync as Rd}from"fs";import{resolve as Cd}from"path";tm();var Ro=new xf().name("voice").description("list installed system voices and pick each agent's voice");function Yi(e){let t=e?[e]:[Cd(process.cwd(),"agentx.json"),Cd(process.cwd(),".agentx/config.json")],o=t.find(n=>Sf(n));if(!o)throw new Error(`No config found. Searched: ${t.join(", ")}`);return o}function Ef(e,t,o,n,s){let{provider:i,gender:r}=n,a=n.lang?.toLowerCase().split(/[-_]/)[0],c=e?.agents?.[t];if(!c)throw new Error(`No agent "${t}" 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&&!o)throw new Error("--lang needs a voice");if(!o&&!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(o){let w=o.trim().toLowerCase()===Et,y=w?null:Gn(o,s,a??e?.voice?.locale),$=y?`system voice ${ci(y)}`:"the OS default voice";if((y||w)&&g==="system")u(w?Et:o),d.push(`${$}${f}`);else if(g==="elevenlabs"&&!y&&!w&&!a)l.elevenlabsVoiceId=o,d.push(`ElevenLabs voice ${o}`);else if(y||w)u(w?Et:o),d.push(`fallback ${$}${f}`);else throw new Error(`"${o}" 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,[t]:{...c,voice:l}}},summary:p}}Ro.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 t=sn(),o;try{o=I(e.config)}catch{}let n=o?.voice.locale??"en",s=new Map,i=o?hc(o.agents,o.voice,t):new Map;if(o)for(let[r,a]of Object.entries(o.agents)){let c=i.get(r),l=Object.values(li(r,a.voice?.system,a.voice?.gender,o.voice,t));for(let g of new Set([c,...l]))g&&s.set(g.id,[...s.get(g.id)??[],r])}if(!t.length)console.log(ne.yellow(`
|
|
388
388
|
No system voices found (system voices need macOS).
|
|
389
389
|
`));else{let r=e.all?ai(t,""):ai(t,n);console.log(ne.bold(`
|
|
390
390
|
System voices${e.all?"":` (${n})`}, best first
|
|
@@ -401,45 +401,45 @@ return aid ?? null`}function Yu(e,t){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
|
|
|
401
401
|
`));for(let[i,r]of Object.entries(s.agents)){if(e&&i!==e)continue;let a=wo(i,r).color,c=Dr(r.presence?.palette,a);console.log(` ${i.padEnd(24)} ${c.id.padEnd(10)} ${ne.dim(c.set?"chosen":`nearest its colour ${a}`)}`)}console.log()}catch(n){console.log(ne.red(` ${n.message}`)),process.exit(1)}});Ro.command("card").description("the answer shown in the pill: how long it stays open and how tall it grows").option("--timeout <seconds>",`seconds it stays open once spoken, ${di.timeout.join("\u2013")}; 0 keeps it open until closed`).option("--max-height <points>",`tallest it grows before it scrolls, ${di.maxHeight.join("\u2013")}`).option("-c, --config <path>","agentx.json to read or change").action(e=>{try{let t=Yi(e.config),o={};e.timeout!==void 0&&(o.timeout=Number(e.timeout)),e.maxHeight!==void 0&&(o.maxHeight=Number(e.maxHeight)),Object.keys(o).length&&_d(t,{general:{card:o}});let n=I(t).voice.card,s=n.timeout===0?"until closed":`${n.timeout} s after it is spoken`;console.log(` Answer card: open ${s}, at most ${n.maxHeight} pt tall`),Object.keys(o).length&&console.log(ne.dim(" AgentX Voice picks this up the next time it reads its settings."))}catch(t){console.log(ne.red(` ${t.message}`)),process.exit(1)}});import{Command as Af}from"commander";import N from"chalk";var Pt=new Af().name("attach").description("wear an agentx agent identity in this Claude Code session"),vs=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Gt()}`;function xs(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function Ss(e,t,o){let n=await fetch(`${e}${t}`,{method:o?"POST":"GET",headers:{"Content-Type":"application/json"},body:o?JSON.stringify(o):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 Es(e){let t=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(t)?`daemon not reachable \u2014 start it with ${N.cyan("agentx daemon start")}`:t}function Pd(e){return e==="auto"?N.yellow:e==="manual"?N.gray:N.green}function jf(e,t=!1){let o=e.agentIds.length?e.agentIds.join(", "):N.gray("(not bound)"),n=e.pending?N.yellow(`${e.pending} pending`):N.gray("empty"),s=t?N.cyan(" \u2190 this session"):"";console.log(` ${N.bold(o)} ${Pd(e.mode)(e.mode)} ${n} ${N.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}function Of(e){let t=e.filter(n=>n.agentIds.length>0),o=e.filter(n=>n.watch&&n.agentIds.length===0);return{bound:t,watching:o,idle:e.length-t.length-o.length}}function Tf(e,t=!1){let o=e.watch?.subscriptions.map(s=>s.kinds.join("|")).join(", ")||"default",n=t?N.cyan(" \u2190 this session"):"";console.log(` ${N.bold("watching")} ${N.gray(o)} ${N.gray(e.sessionId)}${n}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}Pt.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${ei.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",vs).action(async(e,t)=>{let o=xs(t.session);o||(console.error(N.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${N.cyan("--session <id>")} (list them with ${N.cyan("agentx attach list")}).`),process.exit(1)),ea(t.mode)||(console.error(N.red(`Invalid mode "${t.mode}". Expected one of: ${ei.join(", ")}`)),process.exit(1)),dn()||(console.error(N.yellow("Attach hooks are not installed yet.")),console.error(`Run ${N.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{let n=await Ss(t.url,"/attach/bind",{sessionId:o,agentId:e,mode:t.mode,cwd:process.cwd()});console.log(`${N.green("\u2713")} This session is now wearing ${N.bold(e)} (${Pd(t.mode)(t.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(N.yellow(` ${s} message(s) already queued for it.`)),console.log(N.gray(t.mode==="auto"?" Queued messages will be answered automatically at the end of each turn.":t.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(N.red(`Bind failed: ${Es(n)}`)),process.exit(1)}});function Dd(e){let t=(e??"").split(",").map(o=>o.trim()).filter(Boolean);return t.length?t:void 0}function If(e){let t=Dd(e.kinds),o=Dd(e.agents);if(!t&&!o&&!e.match)return;let n={kinds:t??["*"]};return o&&(n.agents=o),e.match&&(n.match=e.match),[n]}Pt.command("watch").description("watch this session: no identity, no messages, a short event digest on each prompt").option("--kinds <list>","event kinds or types to include, comma separated (default: failures, completions, approvals waiting, peers down)").option("--agents <list>","only events for these agents, comma separated").option("--match <text>","only events whose summary contains this text").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",vs).action(async e=>{let t=xs(e.session);t||(console.error(N.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${N.cyan("--session <id>")}.`),process.exit(1)),dn()||(console.error(N.yellow("Attach hooks are not installed yet.")),console.error(`Run ${N.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{await Ss(e.url,"/attach/watch",{sessionId:t,cwd:process.cwd(),subscriptions:If(e)}),console.log(`${N.green("\u2713")} This session is now ${N.bold("watching")}. It answers for no agent.`),console.log(N.gray(" Each time you send a prompt, it gets a short list of new events.")),console.log(N.gray(` Stop with ${N.cyan("agentx attach detach")}.`))}catch(o){console.error(N.red(`Watch failed: ${Es(o)}`)),process.exit(1)}});Pt.command("detach").description("stop wearing an identity or watching 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",vs).action(async e=>{let t=xs(e.session);t||(console.error(N.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await Ss(e.url,"/attach/detach",{sessionId:t,agentId:e.agent}),console.log(`${N.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(o){console.error(N.red(`Detach failed: ${Es(o)}`)),process.exit(1)}});Pt.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",vs).option("--json","raw JSON output").action(async e=>{let t=xs();try{let n=(await Ss(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:dn(),sessions:n},null,2));return}console.log(),console.log(dn()?`${N.green("\u2713")} Attach hooks installed ${N.gray(ln())}`:`${N.yellow("!")} Attach hooks not installed \u2014 run ${N.cyan("agentx attach install")}`),console.log();let{bound:s,watching:i,idle:r}=Of(n);if(console.log(N.bold(" Identities")),s.length===0)console.log(N.gray(" No session is wearing an identity right now."));else for(let a of s)jf(a,a.sessionId===t);if(i.length>0){console.log(),console.log(N.bold(" Watchers"));for(let a of i)Tf(a,a.sessionId===t)}r>0&&console.log(N.gray(`
|
|
402
402
|
${r} registered session(s) with no binding.`)),console.log()}catch(o){console.error(N.red(`Could not read attach state: ${Es(o)}`)),process.exit(1)}});Pt.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 t=String(e.port||Gt()),o=nl(t,{path:e.path,withGuard:e.guard});console.log(o.changed?`${N.green("\u2713")} Installed attach hooks in ${N.gray(o.path)}`:`${N.green("\u2713")} Attach hooks already up to date in ${N.gray(o.path)}`),console.log(N.gray(` Events: ${o.events.join(", ")} \u2192 127.0.0.1:${t}`)),o.guardInstalled?(console.log(N.gray(" PreToolUse guard installed at user scope.")),console.log(N.gray(` (An attached session runs under your permissions, not the agent's workspace
|
|
403
403
|
settings \u2014 without this an attached production identity would be less
|
|
404
|
-
guarded than a spawned one.)`))):console.log(N.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${N.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(t){console.error(N.red(`Install failed: ${t?.message??t}`)),process.exit(1)}});Pt.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 t=sl({path:e.path,keepGuard:!e.removeGuard});console.log(t.changed?`${N.green("\u2713")} Removed attach hooks from ${N.gray(t.path)} (${t.events.join(", ")})`:`${N.gray("Nothing to remove.")}`),e.removeGuard||console.log(N.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(t){console.error(N.red(`Uninstall failed: ${t?.message??t}`)),process.exit(1)}});ae();import{Command as Cf}from"commander";import we from"chalk";var As=new Cf().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Ld(e){let t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let n=I(e.config);t||(t=n.dashboard?.daemonUrl||""),o||(o=n.dashboard?.token||"")}catch{}return t||(t="http://localhost:18800"),{baseUrl:t.replace(/\/+$/,""),token:o}}function Fd(e,t){let o={};return e&&(o.Authorization=`Bearer ${e}`),t&&(o["Content-Type"]=t),o}function Md(e){let t=Math.round((Date.now()-e)/1e3);return t<60?`${t}s`:t<3600?`${Math.round(t/60)}m`:t<86400?`${Math.round(t/3600)}h`:`${Math.round(t/86400)}d`}function Nf(e){return e==="busy"?we.magenta:e==="warm-hot"?we.green:e==="warm-cold"?we.cyan:e==="idle"?we.yellow:e==="dead"?we.red:we.dim}As.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:t,token:o}=Ld(e),n;try{n=await fetch(`${t}/api/processes`,{headers:Fd(o)})}catch(r){console.log(we.red(` could not reach daemon at ${t}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(we.dim(` daemon at ${t} has no agents with persistentProcess: true`));return}n.ok||(console.log(we.red(` HTTP ${n.status} from ${t}/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(we.dim(" (no processes)"));return}for(let r of i){let a=Nf(r.state)(r.state.padEnd(9)),c=Md(r.spawnedAt),l=r.lastTurnAt?Md(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?we.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?we.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):we.dim("sess=\u2014"),u=r.pendingTaskId?we.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${we.bold(r.key.agentId)}${we.dim(":"+r.key.channel+":"+r.key.chatId)} ${we.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${u}`),r.deadReason&&console.log(` ${we.red("dead:")} ${r.deadReason}`)}});As.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,t,o,n)=>{let{baseUrl:s,token:i}=Ld(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Fd(i,"application/json"),body:JSON.stringify({agentId:e,channel:t,chatId:o,reason:n.reason})})}catch(a){console.log(we.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(we.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(we.red(` ${a}`)),process.exit(1)}console.log(we.green(` killed ${e}:${t}:${o}`))});import{Command as Rf}from"commander";import Me from"chalk";import{existsSync as Vi,rmSync as _f}from"fs";import{resolve as Ki}from"path";var _o=new Rf().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");_o.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,t,o)=>{t.length===0&&(console.log(Me.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!o.verbose,s=Date.now(),i=await sa(e,t,{verbose:n}),r=Date.now()-s;console.log(Me.green(` \u2713 indexed ${i.docs} doc(s) for ${Me.bold(e)} in ${r}ms`)),console.log(Me.dim(` \u2192 ${i.path}`))});_o.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let t=Ki(e.cwd,".agentx","rag");if(!Vi(t)){console.log(Me.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:o}=await import("fs"),n=o(t).filter(s=>Vi(Ki(t,s,"index.json")));if(n.length===0){console.log(Me.dim(" (no indexes)"));return}for(let s of n.sort()){let i=ti(s);console.log(` ${Me.bold(s)} ${i.docs} doc(s) ${Me.dim(i.path)}`)}});_o.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,t,o)=>{let n=parseInt(o.k,10)||5,s=ia(e,t,{k:n});if(o.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=ti(e);i.exists?console.log(Me.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Me.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Me.bold(i.title)} ${Me.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Me.dim(i.path)}`),console.log(` ${Me.dim(i.snippet.slice(0,200))}`)});_o.command("clear <agentId>").description("delete an agent's index").action(e=>{let t=Ki(process.cwd(),".agentx","rag",e);if(!Vi(t)){console.log(Me.dim(` no index for ${e} \u2014 nothing to clear`));return}_f(t,{recursive:!0,force:!0}),console.log(Me.green(` \u2713 cleared index for ${e}`))});ae();import{Command as Df}from"commander";import X from"chalk";import Do from"prompts";var no=new Df().name("backlog").description("manage the local backlog used by business workSource=backlog");function kn(e){let t=I(e),o=t.business?.workSource,n=o?.type==="backlog"?o.path:".agentx/backlog.md";return{config:t,storePath:n,store:new jc(n)}}function Pf(e){return e?X.cyan(`${e.type}:${e.project}#${e.iid}`):X.dim("manual")}function Mf(e){return{todo:X.gray("todo"),doing:X.yellow("doing"),blocked:X.red("blocked"),done:X.green("done")}[e]}no.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:t}=kn(e.config),o=t.list();if(e.status&&(o=o.filter(n=>n.status===e.status)),e.assignee&&(o=o.filter(n=>n.assignee===e.assignee)),e.source&&(o=o.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!o.length){console.log(X.dim(" (no items)"));return}console.log();for(let n of o){let s=n.assignee?X.magenta(`@${n.assignee}`):X.dim("unassigned");console.log(` ${Mf(n.status).padEnd(7)} ${Pf(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(X.dim(` ${n.source.url}`))}console.log(),console.log(X.dim(` ${o.length} item${o.length===1?"":"s"} \u2014 ${t.jsonPath()}`))});no.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,t,o)=>{let n=kn(o.config);n.store.findById(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:t,status:"doing"});if(console.log(X.green(` claimed: ${i.title} -> ${t}`)),i.source){let r=Oc([t],i.source,n.config),a=await pi(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(X.dim(" sync:"),...c));console.log(a.ok?X.dim(` synced -> ${a.url??i.source.type}`):X.yellow(` sync failed: ${a.error}`))}});no.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,t)=>{let o=kn(t.config);o.store.findById(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1));let s=o.store.update(e,{status:"done"});if(console.log(X.green(` done: ${s.title}`)),s.source){let i=await pi(s,{addLabels:["Done"],removeLabels:["Doing"],state:t.close?"closed":void 0,note:t.note},o.config,(...r)=>console.log(X.dim(" sync:"),...r));console.log(i.ok?X.dim(` synced -> ${i.url??s.source.type}`):X.yellow(` sync failed: ${i.error}`))}});no.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,t)=>{let{store:o}=kn(t.config);o.remove(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1)),console.log(X.green(` removed ${e}`))});no.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 t=kn(e.config),o=!!t.config.channels.gitlab?.token,n=!!t.config.channels.github?.token;!o&&!n&&(console.error(X.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 h=[o&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Do({type:"select",name:"source",message:"Source",choices:h})).source,!s)return}s==="gitlab"&&!o&&(console.error(X.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(X.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let h=s==="gitlab"?Ff(t.config):Uf(t.config);h.length?(i=(await Do({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...h.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await Do({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Do({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Do({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(X.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await qf(t.config,i,a):await Wf(t.config,i,a);if(!c.length){console.log(X.yellow(" no open issues matched"));return}console.log(X.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(t.store.list().map(h=>h.id)),d=c.map(h=>{let k=mi({type:s,project:l,iid:h.iid,url:h.url}),b=g.has(k),v=h.labels.length?` [${h.labels.slice(0,3).join(",")}]`:"";return{title:`#${h.iid} ${h.title}${v}${b?X.dim(" (already imported)"):""}`,value:h,disabled:b}}),f=(await Do({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(X.dim(" nothing selected"));return}let p=f.map(h=>{let k={type:s,host:s==="gitlab"?Lf(t.config):void 0,project:l,iid:h.iid,url:h.url};return{id:mi(k),title:h.title,description:h.description,assignee:e.assignee||h.assignee,labels:h.labels,milestone:h.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),w=t.store.addMany(p);console.log(X.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let h of w)console.log(X.dim(` ${h.id} \u2014 ${h.title}`))});function Lf(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Ff(e){let t=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&t.add(n.project);let o=e.business?.workSource;if(o?.type==="gitlab")for(let n of o.projects??[])t.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&t.add(n.id);return[...t].sort()}function Uf(e){let t=new Set;for(let o of e.channels.github?.routes??[])o.repo&&o.repo!=="*"&&t.add(o.repo);return[...t].sort()}async function qf(e,t,o){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});o&&s.set("search",o);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(t)}/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 Wf(e,t,o){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(o){let c=`repo:${t} is:issue is:open ${o}`;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(Ud)}i=`https://api.github.com/repos/${t}/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(Ud):[]}function Ud(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(t=>typeof t=="string"?t:t.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as Bf}from"commander";import W from"chalk";import{existsSync as Jf,readFileSync as Hf}from"fs";import{resolve as Gf}from"path";import zf from"prompts";ae();function qd(e){let t=e||Gf(process.cwd(),"agentx.json");return Jf(t)||(console.log(W.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(Hf(t,"utf-8"))}async function Yf(e,t){if(!e)return;if(e==="me"){let n=t?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(W.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await zf([{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 o=e.split(":");if(o.length>=2)return{channel:o[0],chatId:o[1],accountId:o[2]};console.log(W.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var wt=new Bf().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');wt.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: ${si})`,si).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,t)=>{if(!e){wt.help();return}t.agent||(console.log(W.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(W.red(' --do "<prompt>" is required')),process.exit(1));let o=ni(e);o||(console.log(W.red(` Couldn't parse: "${e}"`)),console.log(W.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(W.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(W.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=qd(t.config),s=Pr(n);n.agents?.[t.agent]||(console.log(W.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(W.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await Yf(t.notify,s),r=t.id||ma(o.matched,t.agent),a=ua({parsed:o,agent:t.agent,prompt:t.do,timezone:t.timezone,timeout:parseInt(t.timeout,10),model:t.model,notify:i,onError:pa(t.onError),enabled:!t.disabled}),c=a.onError,l=await ye(d=>Oe(d,`crons.${r}`,a),{configPath:t.config,dryRun:!!t.dryRun});l.success||(console.log(W.red(` \u2717 ${l.error}`)),process.exit(1));let g=t.dryRun?"would add":"Added";console.log(W.green(` \u2713 ${g} cron ${W.cyan(r)}`)),console.log(W.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(W.dim(` Agent: ${t.agent}`)),i&&console.log(W.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(W.dim(` On error: ${c.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wt.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 o=qd(e.config).crons||{},n=Object.entries(o);if(!n.length){console.log(W.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?W.yellow("\u25D0"):i.enabled?W.green("\u25CF"):W.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${W.cyan(s.padEnd(32))} ${W.dim(i.schedule.padEnd(14))} ${W.dim("\u2192")} ${i.agent}`),console.log(W.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(W.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(W.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=ha(fa(i.schedule,c),c);console.log(W.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(W.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,t]of[["on",!0],["off",!1]])wt.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await ba(o,t);n.success||(console.log(W.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wt.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await ye(o=>{if(!yo(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);la(o,`crons.${e}`)});t.success||(console.log(W.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});for(let[e,t,o]of[["approve",ya,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",wa,"reject an agent's pending create/delete request (drops the request)"]])wt.command(`${e} <id>`).description(o).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await t(n,{configPath:s.config});i.success||(console.log(W.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(W.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wt.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=ni(t);o||(console.log(W.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(W.green(` "${t}"`)),console.log(W.dim(` \u2192 ${o.cron}`)),console.log(W.dim(` \u2192 ${o.human}`))});import{Command as Vf}from"commander";import xe from"chalk";var Mt=new Vf("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals)"),Kf={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki"};function Wd(){return{root:process.cwd()}}function Xi(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function Xf(e){console.log(` ${xe.cyan(e.key)} ${xe.dim(`[${Kf[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?xe.dim(` (later: until ${Xi(e.snoozed_until)})`):""}`),console.log(` ${xe.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${xe.green("Recommends:")} ${e.recommend}`),e.expires&&console.log(xe.yellow(` Expires ${Xi(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(xe.dim(` ${e.detail}`)),e.source&&console.log(xe.dim(` ${e.source}`)),console.log(xe.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}Mt.command("list",{isDefault:!0}).alias("ls").description("what is waiting, most urgent first").option("--all","include items you put off with `later`").option("--json","machine-readable output").action(e=>{let t=Qa(Wd(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(t,null,2));return}for(let o of t.errors)console.log(xe.red(` couldn't read ${o.kind}: ${o.error}`));if(t.items.length===0){console.log(xe.dim(` nothing waiting${t.snoozed?` (${t.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let o of t.items)Xf(o),console.log();console.log(xe.dim(` ${t.items.length} waiting${t.snoozed?`, ${t.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function Qi(e,t,o){let n=Qn(),s=o.hours?Number(o.hours):n.laterHours;if(t==="later"&&!(s>0)){console.error(xe.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await Za(Wd(),e,t,{force:o.force,note:o.note,laterHours:s});if(!i.ok){console.error(xe.red(` ${i.error}`)),process.exitCode=1;return}console.log(xe.green(` \u2713 ${i.message}`))}Mt.command("approve").alias("yes").description("say yes: enables the schedule, lets the fact be used, writes the wiki article, or tells the agent yes").argument("<key>","item key from `agentx approvals list`, e.g. card:2026-01-05-publish-draft-ab12").option("--force","wiki: approve even if the article changed since the proposal").option("--note <text>","cards: a note passed to the agent with your answer").action((e,t)=>Qi(e,"yes",t));Mt.command("reject").alias("no").description("say no: drops the request, keeps the fact out, declines the article, or tells the agent no").argument("<key>","item key from `agentx approvals list`").option("--note <text>","why; kept with cards and wiki proposals").action((e,t)=>Qi(e,"no",t));Mt.command("later").description("put an item off; it leaves the list and comes back later (a card still expires on time)").argument("<key>","item key from `agentx approvals list`").option("--hours <n>","how long (default: approvals.laterHours, 24)").action((e,t)=>Qi(e,"later",t));Mt.command("request").description("raise a decision card yourself, for example to test the inbox (agents use the agentx_approval tool)").requiredOption("--agent <id>","the agent the card is from; it gets the result").requiredOption("--title <text>","what it is, in one line").requiredOption("--ask <text>","the yes/no question").requiredOption("--recommend <text>","the advice and why, in one line").requiredOption("--if-silent <value>",`what applies if nobody answers: ${Ka.join(", ")}`).option("--expires <when>","ISO date or time, or like 12h / 3d (default: approvals.defaultExpiryDays)").option("--source <link>","link to the draft, PR or issue").action(e=>{let t=Qn(),o=Xa(process.cwd(),{raised_by:e.agent,title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.ifSilent,expires:e.expires,source:e.source},{settings:t});if(!o.ok){console.error(xe.red(` ${o.error}`)),process.exitCode=1;return}console.log(xe.green(` \u2713 card:${o.card.id} raised; expires ${Xi(o.card.expires)}, then: ${o.card.if_silent}`))});Mt.command("settings").description('show or change expiry, "later" and digest settings (approvals in agentx.json)').option("--expiry-days <n>","days a card gets when it doesn't say").option("--max-expiry-days <n>","longest a card may wait").option("--later-hours <n>","how long `later` hides an item").option("--notify-agent <on|off>","tell the agent that raised a card its result").option("--digest <on|off>","the daily message about what is waiting").option("--digest-time <HH:MM>","when the digest goes out, 24-hour local time").option("--digest-timezone <zone>",`IANA timezone for --digest-time; "local" for this machine's`).option("--digest-to <channel:chatId>",'where the digest goes; "default" for notifications.destination').action(async e=>{let t={},o=(a,c)=>{if(c===void 0)return;let l=Number(c);if(!(l>0))throw new Error(`${a} must be a positive number`);return l},n=(a,c)=>{if(c!==void 0){if(c==="on")return!0;if(c==="off")return!1;throw new Error(`${a} takes on or off`)}};try{if(t.defaultExpiryDays=o("--expiry-days",e.expiryDays),t.maxExpiryDays=o("--max-expiry-days",e.maxExpiryDays),t.laterHours=o("--later-hours",e.laterHours),t.notifyAgent=n("--notify-agent",e.notifyAgent),t.digestEnabled=n("--digest",e.digest),e.digestTime!==void 0&&(t.digestTime=e.digestTime),e.digestTimezone!==void 0&&(t.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")t.destination=null;else{let a=Fc(e.digestTo);if(!a)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");t.destination=a}}catch(a){console.error(xe.red(` ${a.message}`)),process.exitCode=1;return}if(Object.values(t).some(a=>a!==void 0)){let a=await Uc(t);if(!a.success){console.error(xe.red(` ${a.error}`)),process.exitCode=1;return}console.log(xe.green(" \u2713 saved")+(a.reloaded?xe.dim(" (daemon reloaded)"):""))}let i=Qn(),r=i.digest.destination;console.log(` Cards expire after ${i.defaultExpiryDays} day(s) unless they say (at most ${i.maxExpiryDays})`),console.log(` "Later" hides an item ${i.laterHours} hour(s)`),console.log(` Tell the agent ${i.notifyAgent?"on":"off"}`),console.log(` Daily digest ${i.digest.enabled?`on, at ${i.digest.time}${i.digest.timezone?` (${i.digest.timezone})`:" (this machine's time)"}`:"off"}`),console.log(` Digest goes to ${r?`${r.channel} ${r.chatId}`:"notifications.destination"}`)});import{Command as $h}from"commander";import Po from"chalk";import se from"chalk";import xn from"prompts";import{readFileSync as Qf,writeFileSync as Zf,existsSync as eh}from"fs";import{resolve as Bd}from"path";var th=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function oh(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Zi(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Jd(e=".env"){let t=Bd(e);if(!eh(t))return[];let o=Qf(t,"utf-8"),n=[];for(let s of o.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(th);i?n.push({kind:"kv",key:i[1],value:oh(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function nh(e){return e.map(t=>t.kind==="kv"?`${t.key}=${Zi(t.value)}`:t.raw).join(`
|
|
404
|
+
guarded than a spawned one.)`))):console.log(N.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${N.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(t){console.error(N.red(`Install failed: ${t?.message??t}`)),process.exit(1)}});Pt.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 t=sl({path:e.path,keepGuard:!e.removeGuard});console.log(t.changed?`${N.green("\u2713")} Removed attach hooks from ${N.gray(t.path)} (${t.events.join(", ")})`:`${N.gray("Nothing to remove.")}`),e.removeGuard||console.log(N.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(t){console.error(N.red(`Uninstall failed: ${t?.message??t}`)),process.exit(1)}});ae();import{Command as Cf}from"commander";import we from"chalk";var As=new Cf().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Ld(e){let t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let n=I(e.config);t||(t=n.dashboard?.daemonUrl||""),o||(o=n.dashboard?.token||"")}catch{}return t||(t="http://localhost:18800"),{baseUrl:t.replace(/\/+$/,""),token:o}}function Fd(e,t){let o={};return e&&(o.Authorization=`Bearer ${e}`),t&&(o["Content-Type"]=t),o}function Md(e){let t=Math.round((Date.now()-e)/1e3);return t<60?`${t}s`:t<3600?`${Math.round(t/60)}m`:t<86400?`${Math.round(t/3600)}h`:`${Math.round(t/86400)}d`}function Nf(e){return e==="busy"?we.magenta:e==="warm-hot"?we.green:e==="warm-cold"?we.cyan:e==="idle"?we.yellow:e==="dead"?we.red:we.dim}As.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:t,token:o}=Ld(e),n;try{n=await fetch(`${t}/api/processes`,{headers:Fd(o)})}catch(r){console.log(we.red(` could not reach daemon at ${t}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(we.dim(` daemon at ${t} has no agents with persistentProcess: true`));return}n.ok||(console.log(we.red(` HTTP ${n.status} from ${t}/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(we.dim(" (no processes)"));return}for(let r of i){let a=Nf(r.state)(r.state.padEnd(9)),c=Md(r.spawnedAt),l=r.lastTurnAt?Md(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?we.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?we.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):we.dim("sess=\u2014"),u=r.pendingTaskId?we.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${we.bold(r.key.agentId)}${we.dim(":"+r.key.channel+":"+r.key.chatId)} ${we.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${u}`),r.deadReason&&console.log(` ${we.red("dead:")} ${r.deadReason}`)}});As.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,t,o,n)=>{let{baseUrl:s,token:i}=Ld(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Fd(i,"application/json"),body:JSON.stringify({agentId:e,channel:t,chatId:o,reason:n.reason})})}catch(a){console.log(we.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(we.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(we.red(` ${a}`)),process.exit(1)}console.log(we.green(` killed ${e}:${t}:${o}`))});import{Command as Rf}from"commander";import Me from"chalk";import{existsSync as Vi,rmSync as _f}from"fs";import{resolve as Ki}from"path";var _o=new Rf().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");_o.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,t,o)=>{t.length===0&&(console.log(Me.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!o.verbose,s=Date.now(),i=await sa(e,t,{verbose:n}),r=Date.now()-s;console.log(Me.green(` \u2713 indexed ${i.docs} doc(s) for ${Me.bold(e)} in ${r}ms`)),console.log(Me.dim(` \u2192 ${i.path}`))});_o.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let t=Ki(e.cwd,".agentx","rag");if(!Vi(t)){console.log(Me.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:o}=await import("fs"),n=o(t).filter(s=>Vi(Ki(t,s,"index.json")));if(n.length===0){console.log(Me.dim(" (no indexes)"));return}for(let s of n.sort()){let i=ti(s);console.log(` ${Me.bold(s)} ${i.docs} doc(s) ${Me.dim(i.path)}`)}});_o.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,t,o)=>{let n=parseInt(o.k,10)||5,s=ia(e,t,{k:n});if(o.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=ti(e);i.exists?console.log(Me.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Me.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Me.bold(i.title)} ${Me.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Me.dim(i.path)}`),console.log(` ${Me.dim(i.snippet.slice(0,200))}`)});_o.command("clear <agentId>").description("delete an agent's index").action(e=>{let t=Ki(process.cwd(),".agentx","rag",e);if(!Vi(t)){console.log(Me.dim(` no index for ${e} \u2014 nothing to clear`));return}_f(t,{recursive:!0,force:!0}),console.log(Me.green(` \u2713 cleared index for ${e}`))});ae();import{Command as Df}from"commander";import X from"chalk";import Do from"prompts";var no=new Df().name("backlog").description("manage the local backlog used by business workSource=backlog");function kn(e){let t=I(e),o=t.business?.workSource,n=o?.type==="backlog"?o.path:".agentx/backlog.md";return{config:t,storePath:n,store:new jc(n)}}function Pf(e){return e?X.cyan(`${e.type}:${e.project}#${e.iid}`):X.dim("manual")}function Mf(e){return{todo:X.gray("todo"),doing:X.yellow("doing"),blocked:X.red("blocked"),done:X.green("done")}[e]}no.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:t}=kn(e.config),o=t.list();if(e.status&&(o=o.filter(n=>n.status===e.status)),e.assignee&&(o=o.filter(n=>n.assignee===e.assignee)),e.source&&(o=o.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!o.length){console.log(X.dim(" (no items)"));return}console.log();for(let n of o){let s=n.assignee?X.magenta(`@${n.assignee}`):X.dim("unassigned");console.log(` ${Mf(n.status).padEnd(7)} ${Pf(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(X.dim(` ${n.source.url}`))}console.log(),console.log(X.dim(` ${o.length} item${o.length===1?"":"s"} \u2014 ${t.jsonPath()}`))});no.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,t,o)=>{let n=kn(o.config);n.store.findById(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:t,status:"doing"});if(console.log(X.green(` claimed: ${i.title} -> ${t}`)),i.source){let r=Oc([t],i.source,n.config),a=await pi(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(X.dim(" sync:"),...c));console.log(a.ok?X.dim(` synced -> ${a.url??i.source.type}`):X.yellow(` sync failed: ${a.error}`))}});no.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,t)=>{let o=kn(t.config);o.store.findById(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1));let s=o.store.update(e,{status:"done"});if(console.log(X.green(` done: ${s.title}`)),s.source){let i=await pi(s,{addLabels:["Done"],removeLabels:["Doing"],state:t.close?"closed":void 0,note:t.note},o.config,(...r)=>console.log(X.dim(" sync:"),...r));console.log(i.ok?X.dim(` synced -> ${i.url??s.source.type}`):X.yellow(` sync failed: ${i.error}`))}});no.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,t)=>{let{store:o}=kn(t.config);o.remove(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1)),console.log(X.green(` removed ${e}`))});no.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 t=kn(e.config),o=!!t.config.channels.gitlab?.token,n=!!t.config.channels.github?.token;!o&&!n&&(console.error(X.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=[o&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Do({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!o&&(console.error(X.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(X.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?Ff(t.config):Uf(t.config);y.length?(i=(await Do({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 Do({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Do({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Do({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(X.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await qf(t.config,i,a):await Wf(t.config,i,a);if(!c.length){console.log(X.yellow(" no open issues matched"));return}console.log(X.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(t.store.list().map(y=>y.id)),d=c.map(y=>{let $=mi({type:s,project:l,iid:y.iid,url:y.url}),b=g.has($),v=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${v}${b?X.dim(" (already imported)"):""}`,value:y,disabled:b}}),f=(await Do({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(X.dim(" nothing selected"));return}let p=f.map(y=>{let $={type:s,host:s==="gitlab"?Lf(t.config):void 0,project:l,iid:y.iid,url:y.url};return{id:mi($),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:$,importedAt:new Date().toISOString()}}),w=t.store.addMany(p);console.log(X.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(X.dim(` ${y.id} \u2014 ${y.title}`))});function Lf(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Ff(e){let t=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&t.add(n.project);let o=e.business?.workSource;if(o?.type==="gitlab")for(let n of o.projects??[])t.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&t.add(n.id);return[...t].sort()}function Uf(e){let t=new Set;for(let o of e.channels.github?.routes??[])o.repo&&o.repo!=="*"&&t.add(o.repo);return[...t].sort()}async function qf(e,t,o){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});o&&s.set("search",o);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(t)}/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 Wf(e,t,o){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(o){let c=`repo:${t} is:issue is:open ${o}`;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(Ud)}i=`https://api.github.com/repos/${t}/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(Ud):[]}function Ud(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(t=>typeof t=="string"?t:t.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as Bf}from"commander";import W from"chalk";import{existsSync as Jf,readFileSync as Hf}from"fs";import{resolve as Gf}from"path";import zf from"prompts";ae();function qd(e){let t=e||Gf(process.cwd(),"agentx.json");return Jf(t)||(console.log(W.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(Hf(t,"utf-8"))}async function Yf(e,t){if(!e)return;if(e==="me"){let n=t?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(W.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await zf([{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 o=e.split(":");if(o.length>=2)return{channel:o[0],chatId:o[1],accountId:o[2]};console.log(W.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var wt=new Bf().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');wt.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: ${si})`,si).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,t)=>{if(!e){wt.help();return}t.agent||(console.log(W.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(W.red(' --do "<prompt>" is required')),process.exit(1));let o=ni(e);o||(console.log(W.red(` Couldn't parse: "${e}"`)),console.log(W.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(W.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(W.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=qd(t.config),s=Pr(n);n.agents?.[t.agent]||(console.log(W.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(W.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await Yf(t.notify,s),r=t.id||ma(o.matched,t.agent),a=ua({parsed:o,agent:t.agent,prompt:t.do,timezone:t.timezone,timeout:parseInt(t.timeout,10),model:t.model,notify:i,onError:pa(t.onError),enabled:!t.disabled}),c=a.onError,l=await ye(d=>Te(d,`crons.${r}`,a),{configPath:t.config,dryRun:!!t.dryRun});l.success||(console.log(W.red(` \u2717 ${l.error}`)),process.exit(1));let g=t.dryRun?"would add":"Added";console.log(W.green(` \u2713 ${g} cron ${W.cyan(r)}`)),console.log(W.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(W.dim(` Agent: ${t.agent}`)),i&&console.log(W.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(W.dim(` On error: ${c.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wt.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 o=qd(e.config).crons||{},n=Object.entries(o);if(!n.length){console.log(W.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?W.yellow("\u25D0"):i.enabled?W.green("\u25CF"):W.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${W.cyan(s.padEnd(32))} ${W.dim(i.schedule.padEnd(14))} ${W.dim("\u2192")} ${i.agent}`),console.log(W.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(W.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(W.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=ha(fa(i.schedule,c),c);console.log(W.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(W.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,t]of[["on",!0],["off",!1]])wt.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await ba(o,t);n.success||(console.log(W.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wt.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await ye(o=>{if(!yo(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);la(o,`crons.${e}`)});t.success||(console.log(W.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});for(let[e,t,o]of[["approve",ya,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",wa,"reject an agent's pending create/delete request (drops the request)"]])wt.command(`${e} <id>`).description(o).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await t(n,{configPath:s.config});i.success||(console.log(W.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(W.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wt.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=ni(t);o||(console.log(W.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(W.green(` "${t}"`)),console.log(W.dim(` \u2192 ${o.cron}`)),console.log(W.dim(` \u2192 ${o.human}`))});import{Command as Vf}from"commander";import xe from"chalk";var Mt=new Vf("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals)"),Kf={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki"};function Wd(){return{root:process.cwd()}}function Xi(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function Xf(e){console.log(` ${xe.cyan(e.key)} ${xe.dim(`[${Kf[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?xe.dim(` (later: until ${Xi(e.snoozed_until)})`):""}`),console.log(` ${xe.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${xe.green("Recommends:")} ${e.recommend}`),e.expires&&console.log(xe.yellow(` Expires ${Xi(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(xe.dim(` ${e.detail}`)),e.source&&console.log(xe.dim(` ${e.source}`)),console.log(xe.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}Mt.command("list",{isDefault:!0}).alias("ls").description("what is waiting, most urgent first").option("--all","include items you put off with `later`").option("--json","machine-readable output").action(e=>{let t=Qa(Wd(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(t,null,2));return}for(let o of t.errors)console.log(xe.red(` couldn't read ${o.kind}: ${o.error}`));if(t.items.length===0){console.log(xe.dim(` nothing waiting${t.snoozed?` (${t.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let o of t.items)Xf(o),console.log();console.log(xe.dim(` ${t.items.length} waiting${t.snoozed?`, ${t.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function Qi(e,t,o){let n=Qn(),s=o.hours?Number(o.hours):n.laterHours;if(t==="later"&&!(s>0)){console.error(xe.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await Za(Wd(),e,t,{force:o.force,note:o.note,laterHours:s});if(!i.ok){console.error(xe.red(` ${i.error}`)),process.exitCode=1;return}console.log(xe.green(` \u2713 ${i.message}`))}Mt.command("approve").alias("yes").description("say yes: enables the schedule, lets the fact be used, writes the wiki article, or tells the agent yes").argument("<key>","item key from `agentx approvals list`, e.g. card:2026-01-05-publish-draft-ab12").option("--force","wiki: approve even if the article changed since the proposal").option("--note <text>","cards: a note passed to the agent with your answer").action((e,t)=>Qi(e,"yes",t));Mt.command("reject").alias("no").description("say no: drops the request, keeps the fact out, declines the article, or tells the agent no").argument("<key>","item key from `agentx approvals list`").option("--note <text>","why; kept with cards and wiki proposals").action((e,t)=>Qi(e,"no",t));Mt.command("later").description("put an item off; it leaves the list and comes back later (a card still expires on time)").argument("<key>","item key from `agentx approvals list`").option("--hours <n>","how long (default: approvals.laterHours, 24)").action((e,t)=>Qi(e,"later",t));Mt.command("request").description("raise a decision card yourself, for example to test the inbox (agents use the agentx_approval tool)").requiredOption("--agent <id>","the agent the card is from; it gets the result").requiredOption("--title <text>","what it is, in one line").requiredOption("--ask <text>","the yes/no question").requiredOption("--recommend <text>","the advice and why, in one line").requiredOption("--if-silent <value>",`what applies if nobody answers: ${Ka.join(", ")}`).option("--expires <when>","ISO date or time, or like 12h / 3d (default: approvals.defaultExpiryDays)").option("--source <link>","link to the draft, PR or issue").action(e=>{let t=Qn(),o=Xa(process.cwd(),{raised_by:e.agent,title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.ifSilent,expires:e.expires,source:e.source},{settings:t});if(!o.ok){console.error(xe.red(` ${o.error}`)),process.exitCode=1;return}console.log(xe.green(` \u2713 card:${o.card.id} raised; expires ${Xi(o.card.expires)}, then: ${o.card.if_silent}`))});Mt.command("settings").description('show or change expiry, "later" and digest settings (approvals in agentx.json)').option("--expiry-days <n>","days a card gets when it doesn't say").option("--max-expiry-days <n>","longest a card may wait").option("--later-hours <n>","how long `later` hides an item").option("--notify-agent <on|off>","tell the agent that raised a card its result").option("--digest <on|off>","the daily message about what is waiting").option("--digest-time <HH:MM>","when the digest goes out, 24-hour local time").option("--digest-timezone <zone>",`IANA timezone for --digest-time; "local" for this machine's`).option("--digest-to <channel:chatId>",'where the digest goes; "default" for notifications.destination').action(async e=>{let t={},o=(a,c)=>{if(c===void 0)return;let l=Number(c);if(!(l>0))throw new Error(`${a} must be a positive number`);return l},n=(a,c)=>{if(c!==void 0){if(c==="on")return!0;if(c==="off")return!1;throw new Error(`${a} takes on or off`)}};try{if(t.defaultExpiryDays=o("--expiry-days",e.expiryDays),t.maxExpiryDays=o("--max-expiry-days",e.maxExpiryDays),t.laterHours=o("--later-hours",e.laterHours),t.notifyAgent=n("--notify-agent",e.notifyAgent),t.digestEnabled=n("--digest",e.digest),e.digestTime!==void 0&&(t.digestTime=e.digestTime),e.digestTimezone!==void 0&&(t.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")t.destination=null;else{let a=Fc(e.digestTo);if(!a)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");t.destination=a}}catch(a){console.error(xe.red(` ${a.message}`)),process.exitCode=1;return}if(Object.values(t).some(a=>a!==void 0)){let a=await Uc(t);if(!a.success){console.error(xe.red(` ${a.error}`)),process.exitCode=1;return}console.log(xe.green(" \u2713 saved")+(a.reloaded?xe.dim(" (daemon reloaded)"):""))}let i=Qn(),r=i.digest.destination;console.log(` Cards expire after ${i.defaultExpiryDays} day(s) unless they say (at most ${i.maxExpiryDays})`),console.log(` "Later" hides an item ${i.laterHours} hour(s)`),console.log(` Tell the agent ${i.notifyAgent?"on":"off"}`),console.log(` Daily digest ${i.digest.enabled?`on, at ${i.digest.time}${i.digest.timezone?` (${i.digest.timezone})`:" (this machine's time)"}`:"off"}`),console.log(` Digest goes to ${r?`${r.channel} ${r.chatId}`:"notifications.destination"}`)});import{Command as $h}from"commander";import Po from"chalk";import se from"chalk";import xn from"prompts";import{readFileSync as Qf,writeFileSync as Zf,existsSync as eh}from"fs";import{resolve as Bd}from"path";var th=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function oh(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Zi(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Jd(e=".env"){let t=Bd(e);if(!eh(t))return[];let o=Qf(t,"utf-8"),n=[];for(let s of o.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(th);i?n.push({kind:"kv",key:i[1],value:oh(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function nh(e){return e.map(t=>t.kind==="kv"?`${t.key}=${Zi(t.value)}`:t.raw).join(`
|
|
405
405
|
`)+`
|
|
406
|
-
`}function vn(e,t,o=".env"){let n=Bd(o),s=Jd(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:t,raw:`${e}=${Zi(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Zi(t)}`})),Zf(n,nh(s))}function er(e,t=".env"){return Jd(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Hd="https://t.me/BotFather";async function sh(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function ih(e,t){let o=Date.now()+t,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()<o;)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 Gd(e={}){console.log(),console.log(se.bold(" Connect Telegram")),console.log(),console.log(se.dim(` 1. Open ${Hd}`)),console.log(se.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(se.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:t}=await xn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(t)try{let{spawn:b}=await import("child_process"),v=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(v,[Hd],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:o}=await xn({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"});o||(console.log(se.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await sh(o.trim());n||(console.log(se.red("\u2717 invalid or revoked")),process.exit(1)),console.log(se.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(se.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(se.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await xn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(se.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await xn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(se.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;vn(f,o.trim()),process.env[f]=o.trim();let p=await ye(b=>{Oe(b,"channels.telegram.enabled",!0),Oe(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let v=yo(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),Oe(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(p.success||(console.log(se.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(se.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(se.dim(` Token stored in .env as ${f}`)),console.log(se.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(se.dim(" Daemon hot-reloaded.")):console.log(se.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await xn({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(se.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(se.dim(" Waiting up to 90s..."));let h=await ih(o.trim(),9e4);if(!h){console.log(se.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(se.dim(" agentx config set notifications.destination.channel telegram")),console.log(se.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(se.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await ye(b=>{Oe(b,"notifications.destination",{channel:"telegram",chatId:String(h.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(se.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(se.green(" \u2713 Default --notify target set")),console.log(se.dim(` Chat: ${h.chatTitle||h.chatId} (from ${h.from})`)),console.log(se.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(se.dim(" Daemon hot-reloaded."))}import be from"chalk";import tr from"prompts";import{existsSync as nr,mkdirSync as rh,readdirSync as ah,readFileSync as zd}from"fs";import{resolve as or}from"path";var ch=".agentx/whatsapp-sessions";function lh(){let e=or(process.cwd(),".agentx/daemon.pid");if(!nr(e))return!1;try{let t=parseInt(zd(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function dh(e){if(!nr(e))return!1;try{return ah(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function gh(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(be.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(be.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;rh(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:o.makeCacheableSignalKeyStore?o.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(()=>{t(be.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){t(be.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(u),t(be.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),t(be.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Yd(e={}){if(console.log(),console.log(be.bold(" Connect WhatsApp")),console.log(),lh()){console.log(be.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(be.dim(" agentx daemon stop")),console.log();let{cont:l}=await tr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(be.red(" Aborted")),process.exit(1))}let t=e.configPath||or(process.cwd(),"agentx.json");nr(t)||(console.log(be.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(zd(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||ch,s=or(process.cwd(),n),i=Object.keys(o.agents||{});i.length===0&&(console.log(be.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await tr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(be.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(dh(s)&&a){let{keep:l}=await tr({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(be.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await gh(s,g=>console.log(g))||(console.log(be.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ye(l=>{Oe(l,"channels.whatsapp.enabled",!0),Oe(l,"channels.whatsapp.sessionDir",n),Oe(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(be.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(be.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(be.dim(` Session: ${n}`)),console.log(be.dim(" Start the daemon to begin receiving:")),console.log(be.dim(" agentx daemon start")),console.log(be.dim(" Add routes later with:")),console.log(be.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as mh}from"crypto";import Ee from"chalk";import Vd from"prompts";var js="agentx-mesh:",Os="//join/";function ph(e){return Buffer.from(e,"utf-8").toString("base64url")}function uh(e){return Buffer.from(e,"base64url").toString("utf-8")}function fh(e){return`${js}${Os}${ph(JSON.stringify(e))}`}function hh(e){if(!e.startsWith(`${js}${Os}`))throw new Error(`Not a mesh invite link \u2014 expected ${js}${Os}\u2026`);let t=e.slice(js.length+Os.length),o=JSON.parse(uh(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function yh(){return mh(32).toString("hex")}function wh(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function bh(e){return e?.node?.name||e?.node?.id||"node"}async function Kd(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Ee.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(t(s,"utf-8")),r=er("MESH_TOKEN");r||(r=yh(),vn("MESH_TOKEN",r),console.log(Ee.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||wh(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Vd({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(Ee.red(" Aborted")),process.exit(1)),a=d}let l=await ye(d=>{Oe(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ee.red(` \u2717 ${l.error}`)),process.exit(1));let g=fh({url:a,token:r,name:bh(i),version:1});console.log(),console.log(Ee.bold(" Mesh invite")),console.log(),console.log(` ${Ee.cyan(g)}`),console.log(),console.log(Ee.dim(" Run on the other node:")),console.log(Ee.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Ee.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Xd(e,t={}){let o;try{o=hh(e)}catch(i){console.log(Ee.red(` \u2717 ${i.message}`)),process.exit(1)}let n=er("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:i}=await Vd({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Ee.red(" Aborted (keeping existing .env)")),process.exit(1))}vn("MESH_TOKEN",o.token);let s=await ye(i=>{Oe(i,"mesh.enabled",!0);let r=yo(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Oe(i,"mesh.peers",r)},{configPath:t.configPath});s.success||(console.log(Ee.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ee.green(" \u2713 Joined mesh")),console.log(Ee.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ee.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ee.dim(" Daemon hot-reloaded.")):console.log(Ee.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${o.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(Ee.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ee.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Ee.yellow(` Could not reach ${o.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Mo=new $h().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Mo.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 Gd({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Mo.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 Yd({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Qd=Mo.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Qd.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 Kd({url:e.url,configPath:e.config})});Qd.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await Xd(e,{configPath:t.config})});Mo.action(()=>{console.log(),console.log(Po.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Po.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Po.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Po.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Po.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Po.dim(" GitLab connect is the next slice.")),console.log()});ae();import{Command as kh}from"commander";import ue from"chalk";var Sn=new kh().name("usage").description("token usage analysis and reporting");Sn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=I(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(ue.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ue.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${ue.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: ${ue.red(String(s.totalErrors))}`),console.log(),console.log(ue.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(` ${ue.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ue.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ue.red(" Daemon not running. Start with: agentx daemon start")):console.log(ue.red(` ${e.message}`))}});Sn.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:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(ue.red(` Script not found: ${s}`)),console.log(ue.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ue.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ue.red(" Analysis failed. Is Python 3 installed?"))}});Sn.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:t}=await import("./surface-usage-HVVP22SA.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-6PFRDQFT.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(ue.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${ue.dim("\xB7")} ${d}`);console.log(),console.log(ue.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ue.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(ue.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ue.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ue.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(ue.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=ue.dim(`${i.days}d`);console.log(` ${ue.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(ue.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as vh}from"commander";import $e from"chalk";import{readFileSync as xh}from"fs";import{resolve as Sh}from"path";ae();var Lt=new vh().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Lt.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{Gr(Sh(process.cwd(),".env"))}catch{}let t=Eh(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-ZPJHXX3U.js");o(t)}catch(t){console.log($e.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log($e.dim(t.stack)),process.exit(1)}});function Eh(e,t){try{let o=I();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log($e.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log($e.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
406
|
+
`}function vn(e,t,o=".env"){let n=Bd(o),s=Jd(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:t,raw:`${e}=${Zi(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Zi(t)}`})),Zf(n,nh(s))}function er(e,t=".env"){return Jd(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Hd="https://t.me/BotFather";async function sh(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function ih(e,t){let o=Date.now()+t,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()<o;)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 Gd(e={}){console.log(),console.log(se.bold(" Connect Telegram")),console.log(),console.log(se.dim(` 1. Open ${Hd}`)),console.log(se.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(se.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:t}=await xn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(t)try{let{spawn:b}=await import("child_process"),v=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(v,[Hd],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:o}=await xn({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"});o||(console.log(se.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await sh(o.trim());n||(console.log(se.red("\u2717 invalid or revoked")),process.exit(1)),console.log(se.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(se.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(se.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await xn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(se.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await xn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(se.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;vn(f,o.trim()),process.env[f]=o.trim();let p=await ye(b=>{Te(b,"channels.telegram.enabled",!0),Te(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let v=yo(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),Te(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(p.success||(console.log(se.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(se.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(se.dim(` Token stored in .env as ${f}`)),console.log(se.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(se.dim(" Daemon hot-reloaded.")):console.log(se.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await xn({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(se.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(se.dim(" Waiting up to 90s..."));let y=await ih(o.trim(),9e4);if(!y){console.log(se.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(se.dim(" agentx config set notifications.destination.channel telegram")),console.log(se.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(se.dim(` agentx config set notifications.destination.accountId ${u}`));return}let $=await ye(b=>{Te(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{configPath:e.configPath});if(!$.success){console.log(se.red(` \u2717 failed to save destination: ${$.error}`));return}console.log(se.green(" \u2713 Default --notify target set")),console.log(se.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(se.dim(" From now on, --notify me resolves to this chat.")),$.reloaded&&console.log(se.dim(" Daemon hot-reloaded."))}import be from"chalk";import tr from"prompts";import{existsSync as nr,mkdirSync as rh,readdirSync as ah,readFileSync as zd}from"fs";import{resolve as or}from"path";var ch=".agentx/whatsapp-sessions";function lh(){let e=or(process.cwd(),".agentx/daemon.pid");if(!nr(e))return!1;try{let t=parseInt(zd(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function dh(e){if(!nr(e))return!1;try{return ah(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function gh(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(be.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(be.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;rh(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:o.makeCacheableSignalKeyStore?o.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(()=>{t(be.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){t(be.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(u),t(be.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),t(be.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Yd(e={}){if(console.log(),console.log(be.bold(" Connect WhatsApp")),console.log(),lh()){console.log(be.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(be.dim(" agentx daemon stop")),console.log();let{cont:l}=await tr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(be.red(" Aborted")),process.exit(1))}let t=e.configPath||or(process.cwd(),"agentx.json");nr(t)||(console.log(be.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(zd(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||ch,s=or(process.cwd(),n),i=Object.keys(o.agents||{});i.length===0&&(console.log(be.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await tr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(be.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(dh(s)&&a){let{keep:l}=await tr({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(be.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await gh(s,g=>console.log(g))||(console.log(be.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ye(l=>{Te(l,"channels.whatsapp.enabled",!0),Te(l,"channels.whatsapp.sessionDir",n),Te(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(be.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(be.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(be.dim(` Session: ${n}`)),console.log(be.dim(" Start the daemon to begin receiving:")),console.log(be.dim(" agentx daemon start")),console.log(be.dim(" Add routes later with:")),console.log(be.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as mh}from"crypto";import Ae from"chalk";import Vd from"prompts";var js="agentx-mesh:",Os="//join/";function ph(e){return Buffer.from(e,"utf-8").toString("base64url")}function uh(e){return Buffer.from(e,"base64url").toString("utf-8")}function fh(e){return`${js}${Os}${ph(JSON.stringify(e))}`}function hh(e){if(!e.startsWith(`${js}${Os}`))throw new Error(`Not a mesh invite link \u2014 expected ${js}${Os}\u2026`);let t=e.slice(js.length+Os.length),o=JSON.parse(uh(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function yh(){return mh(32).toString("hex")}function wh(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function bh(e){return e?.node?.name||e?.node?.id||"node"}async function Kd(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Ae.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(t(s,"utf-8")),r=er("MESH_TOKEN");r||(r=yh(),vn("MESH_TOKEN",r),console.log(Ae.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||wh(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Vd({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(Ae.red(" Aborted")),process.exit(1)),a=d}let l=await ye(d=>{Te(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ae.red(` \u2717 ${l.error}`)),process.exit(1));let g=fh({url:a,token:r,name:bh(i),version:1});console.log(),console.log(Ae.bold(" Mesh invite")),console.log(),console.log(` ${Ae.cyan(g)}`),console.log(),console.log(Ae.dim(" Run on the other node:")),console.log(Ae.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Ae.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Xd(e,t={}){let o;try{o=hh(e)}catch(i){console.log(Ae.red(` \u2717 ${i.message}`)),process.exit(1)}let n=er("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:i}=await Vd({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Ae.red(" Aborted (keeping existing .env)")),process.exit(1))}vn("MESH_TOKEN",o.token);let s=await ye(i=>{Te(i,"mesh.enabled",!0);let r=yo(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Te(i,"mesh.peers",r)},{configPath:t.configPath});s.success||(console.log(Ae.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ae.green(" \u2713 Joined mesh")),console.log(Ae.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ae.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ae.dim(" Daemon hot-reloaded.")):console.log(Ae.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${o.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(Ae.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ae.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Ae.yellow(` Could not reach ${o.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Mo=new $h().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Mo.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 Gd({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Mo.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 Yd({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Qd=Mo.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Qd.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 Kd({url:e.url,configPath:e.config})});Qd.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await Xd(e,{configPath:t.config})});Mo.action(()=>{console.log(),console.log(Po.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Po.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Po.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Po.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Po.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Po.dim(" GitLab connect is the next slice.")),console.log()});ae();import{Command as kh}from"commander";import ue from"chalk";var Sn=new kh().name("usage").description("token usage analysis and reporting");Sn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=I(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(ue.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ue.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${ue.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: ${ue.red(String(s.totalErrors))}`),console.log(),console.log(ue.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(` ${ue.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ue.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ue.red(" Daemon not running. Start with: agentx daemon start")):console.log(ue.red(` ${e.message}`))}});Sn.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:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(ue.red(` Script not found: ${s}`)),console.log(ue.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ue.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ue.red(" Analysis failed. Is Python 3 installed?"))}});Sn.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:t}=await import("./surface-usage-HVVP22SA.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-GUBHJFZS.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(ue.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${ue.dim("\xB7")} ${d}`);console.log(),console.log(ue.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ue.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(ue.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ue.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ue.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(ue.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=ue.dim(`${i.days}d`);console.log(` ${ue.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(ue.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as vh}from"commander";import $e from"chalk";import{readFileSync as xh}from"fs";import{resolve as Sh}from"path";ae();var Lt=new vh().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Lt.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{Gr(Sh(process.cwd(),".env"))}catch{}let t=Eh(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-3WVKEGRZ.js");o(t)}catch(t){console.log($e.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log($e.dim(t.stack)),process.exit(1)}});function Eh(e,t){try{let o=I();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log($e.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log($e.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
407
407
|
`)),{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:t||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}Lt.command("list").description("list configured boards").action(()=>{try{let e=I();if(!e.boards?.length){console.log($e.dim(`
|
|
408
408
|
No boards configured.
|
|
409
409
|
`));return}console.log();for(let t of e.boards){console.log(` ${$e.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log($e.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log($e.dim(` primary label: ${t.primaryToolLabel}`)),console.log($e.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log($e.red(` ${e.message}`)),process.exit(1)}});Lt.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,t)=>{try{En(o=>{if(Array.isArray(o.boards)||(o.boards=[]),o.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(t.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:t.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(t.days,10)||30,closedWindowDays:parseInt(t.closedDays,10)||30};return t.label&&(s.primaryToolLabel=t.label),o.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(o){console.log($e.red(` ${o.message}`)),process.exit(1)}});Lt.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,t)=>{try{En(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(t.name&&(s.name=t.name,i.push(`name="${t.name}"`)),t.projects){let r=String(t.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(t.label!==void 0&&(t.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=t.label,i.push(`label="${t.label}"`))),t.days&&(s.timeRangeDays=parseInt(t.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),t.closedDays&&(s.closedWindowDays=parseInt(t.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(o){console.log($e.red(` ${o.message}`)),process.exit(1)}});var sr=Lt.command("column").description("manage a board's columns (add / remove / edit / list)");sr.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(xh("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!o)throw new Error(`board "${e}" not found`);let n=o.columns||[];if(n.length===0){console.log($e.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(` ${$e.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${$e.dim(i)}`)}}catch(t){console.log($e.red(` ${t.message}`)),process.exit(1)}});sr.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,t,o)=>{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===t))throw new Error(`column "${t}" already exists on board "${e}"`);let r={id:t,title:o.title,kind:o.kind,scopedPrefix:o.scopedPrefix};if(o.kind==="scoped-label"){if(!o.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=o.scoped}if(o.kind==="label"){if(!o.label)throw new Error("--label required for kind=label");r.mapsToLabel=o.label}return o.accent&&(r.accent=o.accent),i.columns.push(r),`column "${t}" added to board "${e}"`})}catch(n){console.log($e.red(` ${n.message}`)),process.exit(1)}});sr.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{En(o=>{let s=(Array.isArray(o.boards)?o.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!==t),s.columns.length===i)throw new Error(`column "${t}" not found`);return`column "${t}" removed from board "${e}"`})}catch(o){console.log($e.red(` ${o.message}`)),process.exit(1)}});Lt.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{En(t=>{if(!Array.isArray(t.boards)||t.boards.length===0)throw new Error("no boards configured");let o=t.boards.length;if(t.boards=t.boards.filter(n=>n.id!==e),t.boards.length===o)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(t){console.log($e.red(` ${t.message}`)),process.exit(1)}});function En(e){let{summary:t,backupPath:o}=ct(n=>e(n));console.log($e.green(`
|
|
410
410
|
\u2713 ${t}
|
|
411
411
|
`)),o&&console.log($e.dim(` Backup: ${o}`)),console.log($e.dim(` Restart the dashboard to pick up the change if not auto-reloading.
|
|
412
|
-
`))}import{Command as Oh}from"commander";import m from"chalk";import
|
|
413
|
-
Check each claim at its source, then: agentx wiki facts proposals approve <id> \xB7 reject <id>`))})),o.command("approve <id>").description("confirm a claim and record it as a fact").option("--subject <text>","correct the subject read from the claim").option("--attribute <text>","correct the attribute").option("--value <text>","correct the value").option("--source <text>","where you checked it").option("--by <id>","who confirms it","operator").option("--dir <path>","wiki directory").action(Fo(async(n,s)=>{let{approveFactProposal:i}=await import("./fact-proposals-
|
|
414
|
-
${
|
|
412
|
+
`))}import{Command as Oh}from"commander";import m from"chalk";import Se from"chalk";import{resolve as Ah}from"path";var jh=e=>e||Ah(process.cwd(),".agentx/wiki");async function Lo(e){let{FactLedger:t}=await import("./ledger-CH7R756S.js");return new t(jh(e))}function Fo(e){return async(...t)=>{try{await e(...t)}catch(o){o?.name!=="LedgerCorruptError"&&console.error(Se.red(` ${o?.message??o}`)),process.exitCode=1}}}function Zd(e){let t=e.command("facts").description("facts with a source and a check date: list, show, set, proposals");t.command("list").description("every recorded fact, with where and when it was checked").option("--dir <path>","wiki directory").option("--stale","only facts past their time limit, or never checked").option("--json").action(Fo(async n=>{let{isStaleFact:s}=await import("./ledger-CH7R756S.js"),i=(await Lo(n.dir)).list().filter(r=>!n.stale||s(r));if(n.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(Se.dim(" no facts recorded"));return}for(let r of i){let a=r.undated?Se.yellow(" UNCHECKED"):s(r)?Se.yellow(" STALE"):"";console.log(` ${Se.cyan(r.id)} ${Se.bold(r.subject)} \xB7 ${r.attribute}: ${r.value}${a}`),console.log(Se.dim(` ${r.volatility} \xB7 ${r.source} \xB7 checked ${r.verifiedAt.slice(0,10)} by ${r.verifiedBy}`))}})),t.command("show <id>").description("one fact, with its earlier values").option("--dir <path>","wiki directory").action(Fo(async(n,s)=>{let i=(await Lo(s.dir)).get(n);if(!i){console.error(Se.red(` no fact "${n}"`)),process.exitCode=1;return}console.log(JSON.stringify(i,null,2))})),t.command("set").description("record a fact you checked; a different value needs a newer --checked-at, or --confirm by a person").requiredOption("--subject <text>",'what the fact is about, e.g. "vendor account"').requiredOption("--attribute <text>",'which property, e.g. "billing status"').requiredOption("--value <text>","the value you found").requiredOption("--source <text>",'where you checked: a system, URL, command, or "owner said"').option("--by <id>","who checked it (agent id or person)",process.env.AGENTX_AGENT_ID||"operator").option("--checked-at <iso>",`when you checked it: an ISO date, or "now". Without it the value can't replace a different one already recorded`).option("--class <class>",`volatility class: ${Zs.join(" | ")}`).option("--ttl-days <n>","days it stays trusted, overriding the class").option("--confirm","a person confirms this value: replace a newer-dated one").option("--dir <path>","wiki directory").action(Fo(async n=>{if(n.class&&!Xr(n.class)){console.error(Se.red(` --class must be one of ${Zs.join(", ")}`)),process.exitCode=1;return}let i=(await Lo(n.dir)).write({subject:n.subject,attribute:n.attribute,value:n.value,source:n.source,verifiedBy:n.by,verifiedAt:n.checkedAt,volatility:n.class,ttlDays:n.ttlDays!==void 0?Number(n.ttlDays):void 0},n.confirm?{confirmedBy:n.by}:{});if(i.status==="contradiction"){let r=i.fact.confirmedBy?`${i.fact.confirmedBy} confirmed it, so only a person can change it`:n.checkedAt?"and this check is not newer":"and this value has no --checked-at";console.log(Se.yellow(` not replaced: the wiki says "${i.fact.value}" (checked ${i.fact.verifiedAt.slice(0,10)}), ${r}.`)),console.log(i.questionId?Se.dim(` Queued question ${i.questionId}: agentx wiki questions \xB7 agentx wiki answer ${i.questionId} "<true value>"`):i.questionClosed?Se.dim(` A person already ${i.questionClosed} this same claim, so it is not asked again.`):Se.red(" No question could be queued: the questions file is unreadable. Repair .agentx/wiki/_questions.json.")),process.exitCode=2;return}console.log(Se.green(` ${i.status}: ${i.fact.id} ${i.fact.subject} \xB7 ${i.fact.attribute}: ${i.fact.value}`))}));let o=t.command("proposals").description("claims from session summaries, waiting for a check (list, approve, reject)");o.command("list").description("claims waiting for a check (pending by default)").option("--dir <path>","wiki directory").option("--all","include approved and rejected").option("--json").action(Fo(async n=>{let{listFactProposals:s}=await import("./fact-proposals-LZWS5KFO.js"),i=s(await Lo(n.dir),n.all?void 0:"pending");if(n.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(Se.dim(" no fact proposals waiting"));return}for(let r of i)console.log(` ${Se.cyan(r.id)} ${r.status==="pending"?"":Se.dim(`[${r.status}] `)}${r.claim}`),console.log(Se.dim(` ${r.agentId} \xB7 ${r.origin} \xB7 ${r.source} \xB7 ${r.verifiedAt.slice(0,10)}`));console.log(Se.dim(`
|
|
413
|
+
Check each claim at its source, then: agentx wiki facts proposals approve <id> \xB7 reject <id>`))})),o.command("approve <id>").description("confirm a claim and record it as a fact").option("--subject <text>","correct the subject read from the claim").option("--attribute <text>","correct the attribute").option("--value <text>","correct the value").option("--source <text>","where you checked it").option("--by <id>","who confirms it","operator").option("--dir <path>","wiki directory").action(Fo(async(n,s)=>{let{approveFactProposal:i}=await import("./fact-proposals-LZWS5KFO.js"),{write:r}=i(await Lo(s.dir),n,s.by,{subject:s.subject,attribute:s.attribute,value:s.value,source:s.source});console.log(Se.green(` ${r.status}: ${r.fact.id} ${r.fact.subject} \xB7 ${r.fact.attribute}: ${r.fact.value}`))})),o.command("reject <id>").description("drop a claim; it is not recorded").option("--reason <text>","why, kept with the decision").option("--by <id>","who rejects it","operator").option("--dir <path>","wiki directory").action(Fo(async(n,s)=>{let{rejectFactProposal:i}=await import("./fact-proposals-LZWS5KFO.js"),r=i(await Lo(s.dir),n,s.by,s.reason);console.log(Se.dim(` rejected: ${r.claim}`))}))}import{resolve as F,relative as eg,dirname as tg}from"path";import{execSync as so}from"child_process";import{writeFileSync as io,mkdirSync as bt,readFileSync as An,readdirSync as Th,renameSync as Ts,rmSync as Ih,existsSync as Ve}from"fs";function je(e,t){return new Qs(ro(e),void 0,t||"graph")}function ro(e){return e||F(process.cwd(),".agentx/wiki")}function rr(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var Z=new Oh().name("wiki").description("wiki knowledge base management");Zd(Z);Z.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 t=e.mode,o=je(e.dir,t),n=o.summary(),i=o.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${rr(t)}]`)),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())});Z.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(async e=>{let t=je(e.dir,e.mode),o=e.agent?[e.agent]:t.listAgents(),n=0;console.log();for(let r of o){let c=t.getAgentWiki(r).lint();if(n+=c.length,c.length===0)console.log(` ${m.cyan(r)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(r)}: ${m.yellow(`${c.length} issues`)}`);for(let l of c){let g=l.type==="broken-link"?"x":l.type==="orphan"?"?":"!";console.log(` [${g}] ${m.dim(l.type)} ${l.article}: ${l.message}`)}}}let{factContradictions:s}=await import("./ledger-CH7R756S.js"),i=s(ro(e.dir));if(n+=i.length,i.length>0){console.log(` ${m.cyan("facts")}: ${m.yellow(`${i.length} contradiction(s)`)}`);for(let r of i)console.log(` [!] ${m.dim(r.type)} ${r.articles[0]}: ${r.message}`)}console.log(),n===0&&console.log(m.green(" All agent wikis are healthy")),console.log()});Z.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 t=e.mode,o=je(e.dir,t),n=e.agent?[e.agent]:o.listAgents(),s=parseInt(e.max),i=(()=>{try{let u=F(process.cwd(),".agentx/graph");return Ve(u)?new vt({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 $=f.find(S=>S.id===y);if(!$)continue;let b=c($);if(!b?.length)continue;let v=b.join("/"),A=p.get(v);A?A.n++:p.set(v,{path:b,n:1})}if(p.size===0)return;let w;for(let y of p.values())(!w||y.n>w.n)&&(w=y);return w?.path},g=0,d=0;for(let u of n){let f=typeof e.since=="string"?e.since.trim():"",p=o.getUnabsorbedEntries(u).filter(k=>!f||(k.date??"")>=f).slice(0,s);if(p.length===0){console.log(` ${m.cyan(u)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(u)}: ${p.length} entries to absorb`));for(let k of p.slice(0,3))console.log(m.dim(` [${k.date} via ${k.source}] ${k.content.slice(0,80)}...`));if(p.length>3&&console.log(m.dim(` ... and ${p.length-3} more`)),e.dryRun)continue;let w=o.getAgentWiki(u),y=w.rebuildIndex(),$=w.getWorldview()||o.getSharedStore().getWorldview()||"",b=p.map(k=>`--- ENTRY ${k.id} [${k.date} ${k.agentId} via ${k.source}] ---
|
|
414
|
+
${k.content}
|
|
415
415
|
--- END ENTRY ---`).join(`
|
|
416
416
|
|
|
417
|
-
`),v="";if(e.facts!==!1){let{extractHints:$,resolveFacts:R,mergeRecords:C,renderFactsBlock:T,installPrompts:P,defaultSources:B,recordsFromEntries:L}=await import("./facts-X44PF73W.js");if(!a){let J=new Set;for(let je of o.listAgents())for(let ke of o.getAgentWiki(je).listArticles(je))ke.meta.type==="person"&&J.add(ke.meta.title);a=[...J]}let G=$(p.map(J=>({context:J.sourceContext,content:J.content,sender:typeof J.meta?.sender=="string"?J.meta.sender:void 0})),{known:a}),me=L(p);if(G.length>0||me.length>0){let J=B(),{records:je,results:ke}=G.length>0?await R(G,{sources:J}):{records:[],results:[]},M=C([...me,...je]);v=T(M);let Ye=[...me.length>0?[`entries:${me.length}`]:[],...ke.filter(ve=>ve.records.length>0).map(ve=>`${ve.source}:${ve.records.length}`)];console.log(m.dim(` Facts: ${G.length} entities \u2192 ${M.length} resolved${Ye.length?` (${Ye.join(" ")})`:""}`));for(let ve of P(ke,J))console.log(m.yellow(` ! ${ve.source} ${ve.kind} \u2014 would supply ${ve.provides.join(", ")}`)),console.log(m.dim(` ${ve.hint}`))}}let A=Aa(t,u,k,h.articles,b,p.length,v);console.log(m.dim(` Mode: ${rr(t)}`));let S=F(w.baseDir,"_tmp");bt(S,{recursive:!0});let x=F(S,"absorb-prompt.txt");io(x,A),console.log(m.dim(" Compiling with Claude..."));try{let $;try{$=so(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:go({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(M){if($=M.stdout||"",!$)throw M}let R=$;try{let M=JSON.parse($);R=M.result||M.content||"",R||(console.log(m.dim(` Claude envelope keys: ${Object.keys(M).join(", ")}`)),console.log(m.dim(` is_error: ${M.is_error}, stop_reason: ${M.stop_reason}`)))}catch{}let C,T=[],P=R.indexOf("{"),B=R.indexOf("["),L=P>=0&&(B<0||P<B)?P:B;if(L===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(R.slice(0,500)));continue}let G=R[L],me=G==="{"?"}":"]",J=0,je=-1;for(let M=L;M<R.length;M++)if(R[M]===G)J++;else if(R[M]===me&&(J--,J===0)){je=M+1;break}if(je===-1){console.log(m.red(" Unbalanced JSON"));continue}let ke=R.slice(L,je);try{let M=JSON.parse(ke);Array.isArray(M)?C=M:(C=M.articles||[],T=M.gaps||[])}catch(M){console.log(m.red(` JSON parse error: ${M.message}`)),console.log(m.dim(` First 300 chars: ${ke.slice(0,300)}`));continue}for(let M of C){let Ye=new Date().toISOString().slice(0,10),ve=l(M.sources||[],p);w.writeArticle(M.path,{title:M.title,type:M.type,related:Array.isArray(M.related)?M.related:void 0,tags:M.tags||[],owner:u,access:"public",created:Ye,lastUpdated:Ye,sources:M.sources||[],graphPath:ve},M.content,u);let Jt=M.type?m.magenta(`[${M.type}]`)+" ":"",_=Array.isArray(M.related)&&M.related.length?` \u2192 ${M.related.slice(0,3).join(", ")}${M.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${Jt}${M.path}: ${M.title}${m.dim(_)}`);let he=(M.tags||[]).slice(0,4).join(", ");he&&console.log(m.dim(` tags: ${he}`)),ve?.length&&(console.log(m.dim(` graphPath: ${ve.join(" \u203A ")}`)),d++),g++}if(T.length>0){console.log(),console.log(m.yellow(` Gaps detected (${T.length} missing pieces):`));for(let M of T)console.log(m.yellow(` ? ${M}`));try{let{QuestionStore:M}=await import("./questions-QGITDLJY.js"),Ye=new M(ro(e.dir)).add(T.map(ve=>({kind:"article",agentId:u,path:"",subject:String(ve).slice(0,120),question:`No article yet for: ${String(ve).slice(0,160)}`})));Ye.added>0&&console.log(m.dim(` queued ${Ye.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()});Z.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("--failures","also propose lessons from failures that recur across sessions").option("--min-sessions <n>","sessions a failure must recur in for --failures","3").option("--commit","judge and write proposals for review (default: dry-run)",!1).option("--budget <tokens>","max estimated tokens for the judge prompt","60000").action(async e=>{let t=Ch(e.since),o=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=o.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-VF5IWP5P.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!Ve(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()-(t??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()}}}if(e.failures){let a=Number(e.minSessions);(!Number.isInteger(a)||a<2)&&(console.log(m.red(` Invalid --min-sessions "${e.minSessions}". Use a whole number of 2 or more.`)),process.exit(1));let{loadFailedTraces:c,failuresToCandidates:l}=await import("./failure-candidates-RIXA3Y6D.js"),{default:g}=await import("better-sqlite3"),d=F(process.cwd(),".agentx/db.sqlite");if(!Ve(d))console.log(m.yellow(` --failures: no ${d}`));else{let u=new g(d,{readonly:!0});try{let f=c(u,{since:Date.now()-(t??6048e5)}),p=l(f,{minSessions:a});console.log(m.dim(` ${f.length} failed run(s) in window \u2192 ${p.length} failure(s) seen in ${a}+ sessions`));let w=p[0];w&&console.log(m.dim(` most recurrent (${w.occurrences} sessions, ${w.failure.runs} runs): ${w.memory.description.slice(0,84)}`)),i=[...i,...p]}finally{u.close()}}}let r=await ja({extraCandidates:i,wikiDir:e.dir?F(e.dir):void 0,memoryRoot:e.memoryDir?F(e.memoryDir):void 0,sinceMs:t,agentFilter:e.agent,types:o,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,budgetTokens:Number(e.budget)||void 0,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 judge and propose")),console.log();return}for(let a of r.proposed){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=`${a.agents.length} agent(s)${a.occurrences>1?`, seen in ${a.occurrences} sessions`:""}`;console.log(` ${m.green("?")} ${c}${a.path}: ${a.title} ${m.dim(`(${l})`)}`),console.log(m.dim(` proposal ${a.id}`))}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.proposed.length} proposed, ${r.errors.length} error(s)`):m.green(` ${r.proposed.length} proposed, ${r.skipped.length} skipped`)),r.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),r.errors.length&&process.exit(1)});var Is=Z.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function Cs(e){return e?F(e):F(process.cwd(),".agentx","wiki")}Is.command("list").description("list proposals (pending by default)").option("--all","include approved and rejected").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async e=>{let{listProposals:t}=await import("./proposals-O4B5LD5T.js"),o=t(Cs(e.dir),e.all?void 0:"pending");if(o.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of o){let s=n.evidence,i=s.sources.some(l=>l.kind==="failure")?" \xB7 from a recurring failure":"",r=`${s.agents.join(", ")}${s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:""} \xB7 ${s.sources.length} source(s)${i}`,a=n.status==="pending"?"":m.dim(` [${n.status}]`),c=n.replaces?m.yellow("update"):m.green("new");console.log(` ${m.cyan(n.id)}${a}`),console.log(` ${c} ${n.article.path}: ${n.article.title}`),console.log(m.dim(` ${r}`))}});Is.command("show").description("the proposed article and the evidence behind it").argument("<id>","proposal id").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{readProposal:o}=await import("./proposals-O4B5LD5T.js"),n=o(Cs(t.dir),e);if(!n){console.error(m.red(` no proposal "${e}"`)),process.exitCode=1;return}console.log(m.bold(` ${n.article.title}`)+m.dim(` \u2192 ${n.article.path} (${n.replaces?"updates an existing article":"new article"}, ${n.status})`)),console.log(),console.log(n.article.content.split(`
|
|
417
|
+
`),v="";if(e.facts!==!1){let{extractHints:k,resolveFacts:R,mergeRecords:C,renderFactsBlock:T,installPrompts:P,defaultSources:B,recordsFromEntries:L}=await import("./facts-X44PF73W.js");if(!a){let J=new Set;for(let Oe of o.listAgents())for(let ke of o.getAgentWiki(Oe).listArticles(Oe))ke.meta.type==="person"&&J.add(ke.meta.title);a=[...J]}let G=k(p.map(J=>({context:J.sourceContext,content:J.content,sender:typeof J.meta?.sender=="string"?J.meta.sender:void 0})),{known:a}),me=L(p);if(G.length>0||me.length>0){let J=B(),{records:Oe,results:ke}=G.length>0?await R(G,{sources:J}):{records:[],results:[]},M=C([...me,...Oe]);v=T(M);let Ye=[...me.length>0?[`entries:${me.length}`]:[],...ke.filter(ve=>ve.records.length>0).map(ve=>`${ve.source}:${ve.records.length}`)];console.log(m.dim(` Facts: ${G.length} entities \u2192 ${M.length} resolved${Ye.length?` (${Ye.join(" ")})`:""}`));for(let ve of P(ke,J))console.log(m.yellow(` ! ${ve.source} ${ve.kind} \u2014 would supply ${ve.provides.join(", ")}`)),console.log(m.dim(` ${ve.hint}`))}}let A=Aa(t,u,$,y.articles,b,p.length,v);console.log(m.dim(` Mode: ${rr(t)}`));let S=F(w.baseDir,"_tmp");bt(S,{recursive:!0});let x=F(S,"absorb-prompt.txt");io(x,A),console.log(m.dim(" Compiling with Claude..."));try{let k;try{k=so(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:go({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(M){if(k=M.stdout||"",!k)throw M}let R=k;try{let M=JSON.parse(k);R=M.result||M.content||"",R||(console.log(m.dim(` Claude envelope keys: ${Object.keys(M).join(", ")}`)),console.log(m.dim(` is_error: ${M.is_error}, stop_reason: ${M.stop_reason}`)))}catch{}let C,T=[],P=R.indexOf("{"),B=R.indexOf("["),L=P>=0&&(B<0||P<B)?P:B;if(L===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(R.slice(0,500)));continue}let G=R[L],me=G==="{"?"}":"]",J=0,Oe=-1;for(let M=L;M<R.length;M++)if(R[M]===G)J++;else if(R[M]===me&&(J--,J===0)){Oe=M+1;break}if(Oe===-1){console.log(m.red(" Unbalanced JSON"));continue}let ke=R.slice(L,Oe);try{let M=JSON.parse(ke);Array.isArray(M)?C=M:(C=M.articles||[],T=M.gaps||[])}catch(M){console.log(m.red(` JSON parse error: ${M.message}`)),console.log(m.dim(` First 300 chars: ${ke.slice(0,300)}`));continue}for(let M of C){let Ye=new Date().toISOString().slice(0,10),ve=l(M.sources||[],p);w.writeArticle(M.path,{title:M.title,type:M.type,related:Array.isArray(M.related)?M.related:void 0,tags:M.tags||[],owner:u,access:"public",created:Ye,lastUpdated:Ye,sources:M.sources||[],graphPath:ve},M.content,u);let Jt=M.type?m.magenta(`[${M.type}]`)+" ":"",_=Array.isArray(M.related)&&M.related.length?` \u2192 ${M.related.slice(0,3).join(", ")}${M.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${Jt}${M.path}: ${M.title}${m.dim(_)}`);let he=(M.tags||[]).slice(0,4).join(", ");he&&console.log(m.dim(` tags: ${he}`)),ve?.length&&(console.log(m.dim(` graphPath: ${ve.join(" \u203A ")}`)),d++),g++}if(T.length>0){console.log(),console.log(m.yellow(` Gaps detected (${T.length} missing pieces):`));for(let M of T)console.log(m.yellow(` ? ${M}`));try{let{QuestionStore:M}=await import("./questions-ZATLU5AW.js"),Ye=new M(ro(e.dir)).add(T.map(ve=>({kind:"article",agentId:u,path:"",subject:String(ve).slice(0,120),question:`No article yet for: ${String(ve).slice(0,160)}`})));Ye.added>0&&console.log(m.dim(` queued ${Ye.added} for follow-up (agentx wiki questions)`))}catch{}}w.rebuildIndex()}catch(k){console.log(m.red(` Absorb failed: ${k.message?.slice(0,200)}`)),k.stderr&&console.log(m.dim(String(k.stderr).slice(0,300))),k.stdout&&console.log(m.dim("stdout: "+String(k.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let u=g>0?Math.round(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()});Z.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("--failures","also propose lessons from failures that recur across sessions").option("--min-sessions <n>","sessions a failure must recur in for --failures","3").option("--commit","judge and write proposals for review (default: dry-run)",!1).option("--budget <tokens>","max estimated tokens for the judge prompt","60000").action(async e=>{let t=Ch(e.since),o=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=o.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-VF5IWP5P.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!Ve(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()-(t??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()}}}if(e.failures){let a=Number(e.minSessions);(!Number.isInteger(a)||a<2)&&(console.log(m.red(` Invalid --min-sessions "${e.minSessions}". Use a whole number of 2 or more.`)),process.exit(1));let{loadFailedTraces:c,failuresToCandidates:l}=await import("./failure-candidates-RIXA3Y6D.js"),{default:g}=await import("better-sqlite3"),d=F(process.cwd(),".agentx/db.sqlite");if(!Ve(d))console.log(m.yellow(` --failures: no ${d}`));else{let u=new g(d,{readonly:!0});try{let f=c(u,{since:Date.now()-(t??6048e5)}),p=l(f,{minSessions:a});console.log(m.dim(` ${f.length} failed run(s) in window \u2192 ${p.length} failure(s) seen in ${a}+ sessions`));let w=p[0];w&&console.log(m.dim(` most recurrent (${w.occurrences} sessions, ${w.failure.runs} runs): ${w.memory.description.slice(0,84)}`)),i=[...i,...p]}finally{u.close()}}}let r=await ja({extraCandidates:i,wikiDir:e.dir?F(e.dir):void 0,memoryRoot:e.memoryDir?F(e.memoryDir):void 0,sinceMs:t,agentFilter:e.agent,types:o,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,budgetTokens:Number(e.budget)||void 0,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 judge and propose")),console.log();return}for(let a of r.proposed){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=`${a.agents.length} agent(s)${a.occurrences>1?`, seen in ${a.occurrences} sessions`:""}`;console.log(` ${m.green("?")} ${c}${a.path}: ${a.title} ${m.dim(`(${l})`)}`),console.log(m.dim(` proposal ${a.id}`))}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.proposed.length} proposed, ${r.errors.length} error(s)`):m.green(` ${r.proposed.length} proposed, ${r.skipped.length} skipped`)),r.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),r.errors.length&&process.exit(1)});var Is=Z.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function Cs(e){return e?F(e):F(process.cwd(),".agentx","wiki")}Is.command("list").description("list proposals (pending by default)").option("--all","include approved and rejected").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async e=>{let{listProposals:t}=await import("./proposals-O4B5LD5T.js"),o=t(Cs(e.dir),e.all?void 0:"pending");if(o.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of o){let s=n.evidence,i=s.sources.some(l=>l.kind==="failure")?" \xB7 from a recurring failure":"",r=`${s.agents.join(", ")}${s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:""} \xB7 ${s.sources.length} source(s)${i}`,a=n.status==="pending"?"":m.dim(` [${n.status}]`),c=n.replaces?m.yellow("update"):m.green("new");console.log(` ${m.cyan(n.id)}${a}`),console.log(` ${c} ${n.article.path}: ${n.article.title}`),console.log(m.dim(` ${r}`))}});Is.command("show").description("the proposed article and the evidence behind it").argument("<id>","proposal id").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{readProposal:o}=await import("./proposals-O4B5LD5T.js"),n=o(Cs(t.dir),e);if(!n){console.error(m.red(` no proposal "${e}"`)),process.exitCode=1;return}console.log(m.bold(` ${n.article.title}`)+m.dim(` \u2192 ${n.article.path} (${n.replaces?"updates an existing article":"new article"}, ${n.status})`)),console.log(),console.log(n.article.content.split(`
|
|
418
418
|
`).map(s=>` ${s}`).join(`
|
|
419
|
-
`)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let i=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,r=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${i}, ${s.updatedAt.slice(0,10)}${r})`)}`),console.log(m.dim(` ${s.description}`)),s.failure&&console.log(m.dim(` failing tool: ${s.failure.tool} \xB7 error: ${s.failure.errorClass} \xB7 ${s.failure.runs} run(s)`)),s.sessions?.length&&console.log(m.dim(` sessions: ${s.sessions.join(", ")}`)),s.tasks?.length&&console.log(m.dim(` runs: ${s.tasks.join(", ")} (agentx trace show <id>)`))}});Is.command("approve").description("write the proposed article into the shared wiki").argument("<id>","proposal id").option("--force","approve even if the article changed since the proposal").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{approveProposal:o}=await import("./promote-
|
|
420
|
-
`)||"_(none returned)_",A;try{let S=await t(
|
|
419
|
+
`)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let i=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,r=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${i}, ${s.updatedAt.slice(0,10)}${r})`)}`),console.log(m.dim(` ${s.description}`)),s.failure&&console.log(m.dim(` failing tool: ${s.failure.tool} \xB7 error: ${s.failure.errorClass} \xB7 ${s.failure.runs} run(s)`)),s.sessions?.length&&console.log(m.dim(` sessions: ${s.sessions.join(", ")}`)),s.tasks?.length&&console.log(m.dim(` runs: ${s.tasks.join(", ")} (agentx trace show <id>)`))}});Is.command("approve").description("write the proposed article into the shared wiki").argument("<id>","proposal id").option("--force","approve even if the article changed since the proposal").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{approveProposal:o}=await import("./promote-7FMPZKXN.js"),n=o(Cs(t.dir),e,{force:t.force});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${n.proposal.article.path} written to the shared wiki`))});Is.command("reject").description("decline a proposal; its sources aren't judged again until they change").argument("<id>","proposal id").option("--reason <text>","why, kept with the decision").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{rejectProposal:o}=await import("./promote-7FMPZKXN.js"),n=o(Cs(t.dir),e,{reason:t.reason});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} rejected`))});function Ch(e){if(!e)return;let t=/^(\d+)\s*([smhd])$/.exec(e.trim());t||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let o=Number(t[1]),n=t[2];return o*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}Z.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",F(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:t}=await import("./query-6272PJPD.js"),{readdirSync:o,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=je(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=o(d).sort().reverse();for(let y of f){let $=r(d,y),b=[];try{b=o($).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of b){if(u.length>=g)break;try{let A=JSON.parse(n(r($,v),"utf-8")),S=A.message||A.task?.message;typeof S=="string"&&S.trim().length>10&&u.push({id:A.id||v.replace(".json",""),message:S.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 $=u[y];process.stdout.write(m.dim(` [${y+1}/${u.length}] querying... `));let v=l.findRelevant($.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
|
|
420
|
+
`)||"_(none returned)_",A;try{let S=await t($.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(S.status!=="ok")A=`_(status: ${S.status}${S.error?" \u2014 "+S.error:""})_`;else{let x=S.citations.map(k=>`\`${k.title}\` [${k.type||"?"}]`).join(", ");A=`**Answer:**
|
|
421
421
|
|
|
422
422
|
${S.answer}
|
|
423
423
|
|
|
424
|
-
**Citations:** ${x}`}}catch(S){A=`_(error: ${S.message})_`}console.log(m.dim("done")),p.push(`## ${
|
|
425
|
-
`);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))});Z.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 t=await import("node:readline/promises"),{randomUUID:o}=await import("node:crypto"),{WIKI_ARTICLE_TYPES:n}=await import("./types-S6NHM5C3.js"),s=e.answers?An(e.answers,"utf-8").split(/\r?\n/).filter(_=>_.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=
|
|
426
|
-
`),he.trim()}return(await c.question(_)).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 _=await l(m.cyan(" Type? "));if(_==="/abort"){c?.close();return}u.has(_)?d=_:(console.log(m.yellow(` "${_}" 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=[],
|
|
427
|
-
${m.green(">")} `);if(Ke==="/abort"){
|
|
424
|
+
**Citations:** ${x}`}}catch(S){A=`_(error: ${S.message})_`}console.log(m.dim("done")),p.push(`## ${y+1}. ${$.id}`,"",`> ${$.message.replace(/\n/g," ").slice(0,400)}${$.message.length>400?"\u2026":""}`,"","### OLD \u2014 BM25 preload (top 3)","",v,"","### NEW \u2014 agentic query","",A,"","| Path | Rating 0\u20132 | Notes |","|---|---|---|","| OLD | | |","| NEW | | |","")}let w=p.join(`
|
|
425
|
+
`);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))});Z.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 t=await import("node:readline/promises"),{randomUUID:o}=await import("node:crypto"),{WIKI_ARTICLE_TYPES:n}=await import("./types-S6NHM5C3.js"),s=e.answers?An(e.answers,"utf-8").split(/\r?\n/).filter(_=>_.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=je(e.dir),a;try{a=r.getAgentWiki(e.agent)}catch(_){console.log(m.red(` can't open wiki for agent "${e.agent}": ${_.message}`));return}let c=s?null:t.createInterface({input:process.stdin,output:process.stdout}),l=async _=>{if(s){let he=s[i++]??"";return process.stdout.write(_+m.dim(`[scripted] ${he.slice(0,80)}${he.length>80?"\u2026":""}`)+`
|
|
426
|
+
`),he.trim()}return(await c.question(_)).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 _=await l(m.cyan(" Type? "));if(_==="/abort"){c?.close();return}u.has(_)?d=_:(console.log(m.yellow(` "${_}" 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 _=0;_<p.length;_++){let he=p[_],Ke=await l(` ${m.dim(`[${_+1}/${p.length}]`)} ${he}
|
|
427
|
+
${m.green(">")} `);if(Ke==="/abort"){y=!0;break}if(Ke==="/done")break;Ke!=="/skip"&&Ke&&w.push({q:he,a:Ke})}if(!y){let _=await l(`
|
|
428
428
|
${m.dim("Anything else worth capturing?")}
|
|
429
|
-
${m.green(">")} `);_&&_!=="/abort"&&_!=="/done"&&w.push({q:"Anything else worth capturing?",a:_})}if(
|
|
429
|
+
${m.green(">")} `);_&&_!=="/abort"&&_!=="/done"&&w.push({q:"Anything else worth capturing?",a:_})}if(y||w.length===0){console.log(m.yellow(`
|
|
430
430
|
Nothing captured. Exiting.`)),c?.close();return}let b=a.listArticles(e.agent).slice(0,40).map(_=>`- ${_.meta.title} [${_.meta.type||"?"}]`).join(`
|
|
431
431
|
`),v=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${g}`,`**Type:** ${d}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...w.map(_=>`
|
|
432
432
|
Q: ${_.q}
|
|
433
433
|
A: ${_.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(`
|
|
434
|
-
`),A=F(a.baseDir,"_tmp");bt(A,{recursive:!0});let S=F(A,`interview-${o().slice(0,8)}.txt`);io(S,v),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let x="";try{let _=`cat '${S}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,he=so(_,{env:go({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Ke=JSON.parse(he);x=String(Ke.result||Ke.content||"")}catch{x=he}}catch(_){console.log(m.red(` synthesis failed: ${_.message?.slice(0,200)}`)),c?.close();return}x=x.trim();let
|
|
435
|
-
`)){let he=_.match(/^(\w+):\s*(.+)$/);he&&(T[he[1]]=he[2].trim().replace(/^"(.*)"$/,"$1"))}let P=C[2],B=T.title||g,L=B.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),me=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${L}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${me}`)),console.log(),console.log(x),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 ${S} (prompt only; no article file)`));return}let
|
|
436
|
-
`)){let Ks=Zo.match(/^(\w+):\s*(.+)$/);Ks&&(kt[Ks[1]]=Ks[2].trim().replace(/^"(.*)"$/,"$1"))}
|
|
437
|
-
`)),console.log(m.dim(" citations: "+G))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let
|
|
434
|
+
`),A=F(a.baseDir,"_tmp");bt(A,{recursive:!0});let S=F(A,`interview-${o().slice(0,8)}.txt`);io(S,v),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let x="";try{let _=`cat '${S}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,he=so(_,{env:go({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Ke=JSON.parse(he);x=String(Ke.result||Ke.content||"")}catch{x=he}}catch(_){console.log(m.red(` synthesis failed: ${_.message?.slice(0,200)}`)),c?.close();return}x=x.trim();let k=x.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);k&&(x=k[1].trim());let R=x.indexOf("---");R>0&&(x=x.slice(R));let C=x.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!C){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(x.slice(0,600)),c?.close();return}let T={};for(let _ of C[1].split(`
|
|
435
|
+
`)){let he=_.match(/^(\w+):\s*(.+)$/);he&&(T[he[1]]=he[2].trim().replace(/^"(.*)"$/,"$1"))}let P=C[2],B=T.title||g,L=B.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),me=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${L}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${me}`)),console.log(),console.log(x),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 ${S} (prompt only; no article file)`));return}let Oe=P,ke={title:B,type:T.type||d,related:T.related?T.related.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:T.tags?T.tags.replace(/^\[|\]$/g,"").split(",").map(_=>_.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 _=process.env.EDITOR||"vi",he=F(A,`draft-${o().slice(0,8)}.md`);io(he,x);try{so(`${_} '${he}'`,{stdio:"inherit"});let Vs=An(he,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(Vs){let kt={};for(let Zo of Vs[1].split(`
|
|
436
|
+
`)){let Ks=Zo.match(/^(\w+):\s*(.+)$/);Ks&&(kt[Ks[1]]=Ks[2].trim().replace(/^"(.*)"$/,"$1"))}Oe=Vs[2],ke={...ke,title:kt.title||ke.title,type:kt.type||ke.type,access:kt.access||ke.access,related:kt.related?kt.related.replace(/^\[|\]$/g,"").split(",").map(Zo=>Zo.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ke.related,tags:kt.tags?kt.tags.replace(/^\[|\]$/g,"").split(",").map(Zo=>Zo.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ke.tags}}}catch(Ke){console.log(m.red(` editor failed: ${Ke.message}`));return}}if(!a.writeArticle(me,ke,Oe,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${me} saved.`));let Ye=a.extractWikilinks(Oe),ve=new Map;for(let _ of a.listArticles(e.agent))ve.set(_.meta.title.toLowerCase(),!0);let Jt=Ye.filter(_=>!ve.has(_.toLowerCase()));if(Jt.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of Jt.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});Z.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 t=await import("node:readline/promises"),{randomUUID:o}=await import("node:crypto"),{agenticQuery:n}=await import("./query-6272PJPD.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=je(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=An(e.script,"utf-8").split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);r=[];for(let w of p){let y=w.split(/\r?\n/).filter(v=>v.trim());if(y.length<2)continue;let $=y[0].replace(/^Q:\s*/i,"").trim(),b=y.slice(1).join(" ").trim();$&&b&&r.push({q:$,verdict:b})}}let a=r?null:t.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 G=r[f];if(!G)break;p=G.q,w=G.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(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(me=>`${me.title} [${me.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
|
|
437
|
+
`)),console.log(m.dim(" citations: "+G))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let $={q:p,answer:y.answer,citations:y.citations,verdict:w},b=w.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!b){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push($);continue}let v=b[1].toLowerCase(),A=(b[2]||"").trim();if(d.push($),v==="/ok"||v==="/skip")continue;if(!A){console.log(m.yellow(` ${v} without note \u2014 skipping.`));continue}let S=y.citations[0];if(!S){console.log(m.yellow(" no cited article to patch."));continue}let x=i.readArticle(S.path);if(!x){console.log(m.red(` can't read ${S.path} to patch.`));continue}console.log(m.dim(` patching ${S.title} (${S.path})...`));let k=Rh(x.content,v,A,x.meta.title,x.meta.type),R=F(i.baseDir,"_tmp");bt(R,{recursive:!0});let C=F(R,`quiz-patch-${o().slice(0,8)}.txt`);io(C,k);let T="";try{let G=`cat '${C}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,me=so(G,{env:go({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Oe=JSON.parse(me);T=String(Oe.result||Oe.content||"")}catch{T=me}let J=T.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);J&&(T=J[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 P=x.content.split(`
|
|
438
438
|
`).length,B=T.split(`
|
|
439
|
-
`).length;if(console.log(m.dim(` diff: ${P} \u2192 ${B} lines (${B-P>=0?"+":""}${B-P})`)),!g){console.log(m.dim(" (--no-commit: patch not written)"))
|
|
440
|
-
`)),console.log(m.dim(` Transcript written to ${e.out}`))}});Z.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,t,o)=>{let n=
|
|
439
|
+
`).length;if(console.log(m.dim(` diff: ${P} \u2192 ${B} lines (${B-P>=0?"+":""}${B-P})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),$.patched=S.path+" (dry)";continue}if(!i.writeArticle(S.path,{...x.meta,lastUpdated:new Date().toISOString().slice(0,10)},T,e.agent)){console.log(m.red(" write failed (permission?)"));continue}u++,$.patched=S.path,console.log(m.green(` \u2713 patched ${S.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}\``:""),"")}io(e.out,f.join(`
|
|
440
|
+
`)),console.log(m.dim(` Transcript written to ${e.out}`))}});Z.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,t,o)=>{let n=je(o.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=sg(s,t,e);if(!i){console.log(m.yellow(` no article matches "${t}" 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=F(s.baseDir,i),a=o.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${i} in ${a}...`));try{so(`${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)}`))}});Z.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,t,o,n)=>{let s=await import("node:readline/promises"),{randomUUID:i}=await import("node:crypto"),r=je(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=sg(a,t,e);if(!c){console.log(m.yellow(` no article matches "${t}" in ${e}'s wiki.`));return}let l=a.readArticle(c);if(!l){console.log(m.red(` can't read ${c}.`));return}let g=Nh(l.content,l.meta.title,l.meta.type,o),d=F(a.baseDir,"_tmp");bt(d,{recursive:!0});let u=F(d,`patch-${i().slice(0,8)}.txt`);io(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 S=`cat '${u}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,x=so(S,{env:go({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let R=JSON.parse(x);f=String(R.result||R.content||"")}catch{f=x}let k=f.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);k&&(f=k[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 p=l.content.split(`
|
|
441
441
|
`).length,w=f.split(`
|
|
442
|
-
`).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
|
|
442
|
+
`).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 S=s.createInterface({input:process.stdin,output:process.stdout}),x=(await S.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();S.close(),y=x==="y"||x==="yes"}if(!y){console.log(m.dim(" aborted."));return}let $=new Set,b=a.extractWikilinks(f).filter(S=>$.has(S)?!1:($.add(S),!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(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 sg(e,t,o){let n=t.trim(),s=e.listArticles(o),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 Nh(e,t,o,n){return["You are editing a single wiki article to incorporate an operator instruction.","",`## Article: "${t}" (type: ${o||"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(`
|
|
443
443
|
`)}function Rh(e,t,o,n,s){let i={"/correct":`The operator says the article contains an error:
|
|
444
444
|
|
|
445
445
|
${o}
|
|
@@ -453,8 +453,8 @@ Incorporate it into the most relevant existing section, or create a short new se
|
|
|
453
453
|
${o}
|
|
454
454
|
|
|
455
455
|
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 [[${o}]].`};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[t]||`Make a minimal edit per: ${o}`,"","## 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(`
|
|
456
|
-
`)}Z.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 t=
|
|
457
|
-
`)){let s=n.match(/^(\w+):\s*(.+)$/);if(!s)continue;let i=s[1]==="last_updated"?"lastUpdated":s[1];o[i]=s[2].trim().replace(/^"(.*)"$/,"$1")}return{meta:o}}function ng(e,t){let o=F(e,"_versions",`legacy-${t.mode}`,t.relPath.replace(/\.md$/,""));bt(o,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");Ts(t.absPath,F(o,`${n}.md`))}Z.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 t=
|
|
456
|
+
`)}Z.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 t=je(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=!!e.commit,s=e.dir?F(e.dir):F(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 o){let u=F(s,"agents",d);if(!Ve(u))continue;let f=F(u,i),p=r.map(b=>({mode:b,dir:F(u,b)})).filter(b=>Ve(b.dir));if(p.length===0)continue;let w=new Map;ir(f,b=>{let v=eg(f,b);if(v.startsWith("_")||v.startsWith("raw/")||v.includes("_tmp/"))return;let A=og(An(b,"utf-8"));A?.meta.title&&w.set(A.meta.title.trim().toLowerCase(),{relPath:v,type:A.meta.type,lastUpdated:A.meta.lastUpdated||""})});let y=[];for(let b of p)ir(b.dir,v=>{let A=eg(b.dir,v);if(A.startsWith("_")||A.startsWith("raw/")||A.includes("_tmp/"))return;let S=og(An(v,"utf-8"));S?.meta.title&&y.push({mode:b.mode,relPath:A,absPath:v,title:S.meta.title.trim(),type:S.meta.type,lastUpdated:S.meta.lastUpdated||""})});if(a+=y.length,y.length===0)continue;console.log();let $=p.map(b=>b.mode).join("+");console.log(m.bold(` ${m.cyan(d)}: ${y.length} legacy article(s) across ${$}`));for(let b of y){let v=b.title.toLowerCase(),A=w.get(v),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 x=b.type?m.magenta(`[${b.type}]`):m.yellow("[untyped]"),k=S==="promote"?m.green("\u2192 promote "):S==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),R=b.relPath.length>46?b.relPath.slice(0,43)+"...":b.relPath.padEnd(46);if(console.log(` ${k} ${x} ${m.dim(b.mode+"/")}${R}`),S==="upgrade"&&console.log(m.dim(` (replaces ${A.relPath}, old version kept under _versions/)`)),!n){S==="promote"?c++:S==="upgrade"?l++:g++;continue}try{if(S==="promote"){let C=F(f,b.relPath);Ve(C)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${b.relPath}`)),ng(u,b),g++):(bt(tg(C),{recursive:!0}),Ts(b.absPath,C),w.set(v,{relPath:b.relPath,type:b.type,lastUpdated:b.lastUpdated}),c++)}else if(S==="upgrade"){let C=F(f,A.relPath);if(Ve(C)){let T=F(u,"_versions",A.relPath.replace(/\.md$/,""));bt(T,{recursive:!0});let P=new Date().toISOString().replace(/[:.]/g,"-");Ts(C,F(T,`${P}.md`))}bt(tg(C),{recursive:!0}),Ts(b.absPath,C),w.set(v,{relPath:A.relPath,type:b.type,lastUpdated:b.lastUpdated}),l++}else ng(u,b),g++}catch(C){console.log(m.red(` ! ${S} failed: ${C.message?.slice(0,120)}`))}}if(n){for(let b of p)try{Ih(b.dir,{recursive:!0,force:!0})}catch{}try{t.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 ir(e,t){if(Ve(e))for(let o of Th(e,{withFileTypes:!0})){let n=F(e,o.name);o.isDirectory()?ir(n,t):o.isFile()&&o.name.endsWith(".md")&&t(n)}}function og(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let o={};for(let n of t[1].split(`
|
|
457
|
+
`)){let s=n.match(/^(\w+):\s*(.+)$/);if(!s)continue;let i=s[1]==="last_updated"?"lastUpdated":s[1];o[i]=s[2].trim().replace(/^"(.*)"$/,"$1")}return{meta:o}}function ng(e,t){let o=F(e,"_versions",`legacy-${t.mode}`,t.relPath.replace(/\.md$/,""));bt(o,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");Ts(t.absPath,F(o,`${n}.md`))}Z.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 t=je(e.dir),o=e.agent?[e.agent]:t.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 o){let g=t.getAgentWiki(l),d=g.listArticles(l),u=d.filter($=>!$.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=F(w,"_tmp");bt(y,{recursive:!0});for(let $=0;$<p;$+=n){let b=u.slice($,Math.min($+n,p)),v=Dh(b),A=F(y,"migrate-prompt.txt");io(A,v);let S;try{let x=`cat '${A}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,k=so(x,{env:go({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),R=JSON.parse(k),T=String(R.result||R.content||"").match(/\[[\s\S]*\]/);if(!T)throw new Error("no JSON array in classifier response");S=JSON.parse(T[0])}catch(x){console.log(m.red(` LLM classify failed: ${x.message?.slice(0,150)}`));continue}for(let x of b){let k=S.find(L=>L.path===x.path),R=_h(k?.type);if(!k||!R){console.log(m.yellow(` ? ${x.path}: unclassified${k?` (got "${k.type}")`:""}`));continue}let C=g.extractWikilinks(x.content),T={...x.meta,type:R.type,related:C.length?C:void 0,lastUpdated:new Date().toISOString().slice(0,10)},P=C.length?m.dim(` \u2192 ${C.slice(0,3).join(", ")}${C.length>3?", \u2026":""}`):"",B=R.alias?m.dim(` (from "${R.alias}")`):"";console.log(` ${m.green("+")} ${m.magenta("["+R.type+"]")}${B} ${x.path}${P}`),i&&(g.writeArticle(x.path,T,x.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 _h(e){if(!e)return null;let t=String(e).trim().toLowerCase().replace(/^[\s"'`]+|[\s"'`]+$/g,"");if(!t)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"}[t];return n?n===t?{type:n}:{type:n,alias:t}:null}function Dh(e){let t=e.map((o,n)=>{let s=o.content.replace(/\s+/g," ").slice(0,400),i=(o.meta.tags||[]).slice(0,8).join(", ");return`${n+1}. path: "${o.path}"
|
|
458
458
|
title: "${o.meta.title}"
|
|
459
459
|
tags: [${i}]
|
|
460
460
|
body: ${s}${o.content.length>400?"\u2026":""}`}).join(`
|
|
@@ -494,20 +494,20 @@ Output (JSON array, one entry per input article, same order):
|
|
|
494
494
|
[
|
|
495
495
|
{"path": "path/to/article.md", "type": "project"},
|
|
496
496
|
...
|
|
497
|
-
]`}Z.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=
|
|
498
|
-
${u.length} article(s) flagged; ${
|
|
499
|
-
${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."))});Z.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,t)=>{let{agenticQuery:o}=await import("./query-6272PJPD.js"),n=Ae(t.dir),s=t.agent?[t.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=F(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 o(e,r,i,{selectorModel:t.selectorModel,synthModel:t.synthModel,maxCandidates:parseInt(t.maxCandidates),maxHops:parseInt(t.maxHops),maxArticles:parseInt(t.maxArticles)});if(t.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(t.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()}});Z.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,t)=>{let o=Ae(t.dir,t.mode),n=t.agent?[t.agent]:o.listAgents();console.log();let s=0;for(let i of n){let a=await o.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()});Z.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 t=Ae(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=F(process.cwd(),".agentx/graph");if(!Ve(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new vt({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 o){let u=t.getAgentWiki(d),f=u.listArticles(d),p=t.getSharedStore().listEntries(),w=new Map(p.map(v=>[v.id,v])),h=0,k=0,b=0;for(let v of f){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;h++,c++;let A=new Map;for(let x of v.meta.sources){let $=w.get(x);if(!$)continue;let R=String($.meta?.sender??""),C=s.fingerprint({text:$.content,channel:$.source,sender:R}),T=r.get(C);if(!T?.length)continue;let P=T.join("/"),B=A.get(P);B?B.n++:A.set(P,{path:T,n:1})}if(A.size===0)continue;k++,l++;let S;for(let x of A.values())(!S||x.n>S.n)&&(S=x);S&&(e.dryRun||(u.writeArticle(v.path,{...v.meta,graphPath:S.path},v.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${h} 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()});Z.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 o=Ae(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-VV4X7PEK.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(o.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||(o.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()});Z.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 t=e.dir||F(process.cwd(),".agentx/wiki"),o=e.agent,s=["flat","graph","unified"].map(c=>{let l=new Qs(t,void 0,c),d=l.getAgentWiki(o).rebuildIndex(),u=l.getAgentEntries(o),f=l.getUnabsorbedEntries(o),p=new Set,w=0,h=new Set;for(let b of d.articles){for(let v of b.tags||[])p.add(v);w+=b.tags?.length||0;for(let v of b.sources||[])h.add(v)}let k=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:rr(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:h.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${o}`)),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()});Z.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,t)=>{let o=t.dir?F(process.cwd(),t.dir):F(process.cwd(),".agentx/wiki");Ve(o)||(console.log(m.red(` Wiki dir not found: ${o}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?F(process.cwd(),e):F(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=F(o,".."),r=o.split("/").pop()||"wiki",a=["-C",i,"-czf",s];t.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=Ve(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Ph(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});Z.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:t,reportFields:o,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-XNA2O6EO.js"),{QuestionStore:c}=await import("./questions-QGITDLJY.js"),l=Ae(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let x of d){let $=l.getAgentWiki(x);for(let R of $.listArticles(x)){if(f>=u)break e;let C=$.readArticle(R.path);if(!C||e.type&&C.meta.type!==e.type)continue;f++;let T=await a(r,n({title:C.meta.title,type:C.meta.type,body:C.content}),t(C.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:x,type:C.meta.type??"?"}});if(!T){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=o(C.meta.type,T.answers);for(let B of s(P,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:x,path:R.path,subject:C.meta.title,field:B.field,tier:B.tier,question:`${C.meta.title} (${C.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:x,article:C.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&g.length>0&&(w=new c(ro(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 h=["tier","need","how","uncertain","agent","article"],k=x=>String(x).replace(/\u001b\[[0-9;]*m/g,""),b=h.map(x=>Math.max(x.length,...p.map($=>k($[x]).length))),v=(x,$)=>String(x)+" ".repeat(Math.max(0,b[$]-k(x).length));console.log(),console.log(m.bold(h.map((x,$)=>v(x,$)).join(" ")));for(let x of p)console.log(h.map(($,R)=>v(x[$],R)).join(" "));let A=p.filter(x=>x.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 S=p[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:x}=await import("./article-fields-PITN4NHA.js"),$=x[e.notifyTier]??x.pillar,R=g.filter(C=>(x[C.tier??"furniture"]??9)<=$);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:C}=await import("./config-VV4X7PEK.js"),T=C(),P=T?.notifications?.destination;if(!P?.channel||!P?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let B=R.slice(0,10).map(J=>`\u2022 ${J.question}`).join(`
|
|
497
|
+
]`}Z.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=je(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()});Z.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 t=e.dir||F(process.cwd(),".agentx/wiki"),o=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-VV4X7PEK.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:${o}`),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: ${t}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),Hc(t,o,e.agent,n,e.mode)});Z.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:t,articleQualityState:o,gradeArticle:n,ARTICLE_QUALITY_SEAT:s}=await import("./article-quality-JFJMZWFQ.js"),{fieldQuestions:i,reportFields:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-XNA2O6EO.js"),c=je(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 $=c.getAgentWiki(y);for(let b of $.listArticles(y)){if(u.length>=g)break e;let v=$.readArticle(b.path);if(!v||e.type&&v.meta.type!==e.type)continue;let A={...t(v.meta.type),...e.fields?i(v.meta.type):{}},S=await a(s,o({path:b.path,title:v.meta.title,type:v.meta.type,tags:v.meta.tags,body:v.content}),A,{links:[{kind:"article",id:b.path}],features:{agent:y,type:v.meta.type??"?"}});if(!S){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let x=n(S.answers),k=e.fields?r(v.meta.type,S.answers):null;x.completeness>=d&&!(k&&!k.fit)||u.push({agent:y,type:v.meta.type??"?",score:x.completeness.toFixed(2),standsAlone:x.standsAlone.toFixed(2),gap:x.biggestGap,...k?{missing:k.missingCritical.join(",")||"-",cov:`${Math.round(k.coverage*100)}%`}:{},title:v.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(" no articles below the threshold"));return}u.sort((y,$)=>parseFloat(y.score)-parseFloat($.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],p=f.map(y=>Math.max(y.length,...u.map($=>String($[y]).length))),w=y=>y.map(($,b)=>String($).padEnd(p[b])).join(" ");console.log(),console.log(m.bold(w(f)));for(let y of u)console.log(w(f.map($=>y[$])));if(e.fields){let y=u.filter($=>$.missing!=="-").length;console.log(m.dim(`
|
|
498
|
+
${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(`
|
|
499
|
+
${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."))});Z.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,t)=>{let{agenticQuery:o}=await import("./query-6272PJPD.js"),n=je(t.dir),s=t.agent?[t.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=F(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 o(e,r,i,{selectorModel:t.selectorModel,synthModel:t.synthModel,maxCandidates:parseInt(t.maxCandidates),maxHops:parseInt(t.maxHops),maxArticles:parseInt(t.maxArticles)});if(t.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(t.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()}});Z.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,t)=>{let o=je(t.dir,t.mode),n=t.agent?[t.agent]:o.listAgents();console.log();let s=0;for(let i of n){let a=await o.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()});Z.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 t=je(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=F(process.cwd(),".agentx/graph");if(!Ve(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new vt({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 o){let u=t.getAgentWiki(d),f=u.listArticles(d),p=t.getSharedStore().listEntries(),w=new Map(p.map(v=>[v.id,v])),y=0,$=0,b=0;for(let v of f){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;y++,c++;let A=new Map;for(let x of v.meta.sources){let k=w.get(x);if(!k)continue;let R=String(k.meta?.sender??""),C=s.fingerprint({text:k.content,channel:k.source,sender:R}),T=r.get(C);if(!T?.length)continue;let P=T.join("/"),B=A.get(P);B?B.n++:A.set(P,{path:T,n:1})}if(A.size===0)continue;$++,l++;let S;for(let x of A.values())(!S||x.n>S.n)&&(S=x);S&&(e.dryRun||(u.writeArticle(v.path,{...v.meta,graphPath:S.path},v.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${y} eligible \xB7 ${$} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${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()});Z.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 o=je(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-VV4X7PEK.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(o.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||(o.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()});Z.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 t=e.dir||F(process.cwd(),".agentx/wiki"),o=e.agent,s=["flat","graph","unified"].map(c=>{let l=new Qs(t,void 0,c),d=l.getAgentWiki(o).rebuildIndex(),u=l.getAgentEntries(o),f=l.getUnabsorbedEntries(o),p=new Set,w=0,y=new Set;for(let b of d.articles){for(let v of b.tags||[])p.add(v);w+=b.tags?.length||0;for(let v of b.sources||[])y.add(v)}let $=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:rr(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:$.size,coverage:y.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${o}`)),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()});Z.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,t)=>{let o=t.dir?F(process.cwd(),t.dir):F(process.cwd(),".agentx/wiki");Ve(o)||(console.log(m.red(` Wiki dir not found: ${o}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?F(process.cwd(),e):F(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=F(o,".."),r=o.split("/").pop()||"wiki",a=["-C",i,"-czf",s];t.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=Ve(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Ph(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});Z.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:t,reportFields:o,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-XNA2O6EO.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=je(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let x of d){let k=l.getAgentWiki(x);for(let R of k.listArticles(x)){if(f>=u)break e;let C=k.readArticle(R.path);if(!C||e.type&&C.meta.type!==e.type)continue;f++;let T=await a(r,n({title:C.meta.title,type:C.meta.type,body:C.content}),t(C.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:x,type:C.meta.type??"?"}});if(!T){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=o(C.meta.type,T.answers);for(let B of s(P,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:x,path:R.path,subject:C.meta.title,field:B.field,tier:B.tier,question:`${C.meta.title} (${C.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:x,article:C.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&g.length>0&&(w=new c(ro(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"],$=x=>String(x).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(x=>Math.max(x.length,...p.map(k=>$(k[x]).length))),v=(x,k)=>String(x)+" ".repeat(Math.max(0,b[k]-$(x).length));console.log(),console.log(m.bold(y.map((x,k)=>v(x,k)).join(" ")));for(let x of p)console.log(y.map((k,R)=>v(x[k],R)).join(" "));let A=p.filter(x=>x.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 S=p[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:x}=await import("./article-fields-PITN4NHA.js"),k=x[e.notifyTier]??x.pillar,R=g.filter(C=>(x[C.tier??"furniture"]??9)<=k);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:C}=await import("./config-VV4X7PEK.js"),T=C(),P=T?.notifications?.destination;if(!P?.channel||!P?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let B=R.slice(0,10).map(J=>`\u2022 ${J.question}`).join(`
|
|
500
500
|
`),L=R.length>10?`
|
|
501
501
|
\u2026and ${R.length-10} more`:"",G=`${R.length} wiki gap(s) need you (${e.notifyTier}+):
|
|
502
502
|
${B}${L}
|
|
503
503
|
|
|
504
|
-
agentx wiki questions`,me=T?.daemon?.port??T?.port??18800;try{let J=await fetch(`http://127.0.0.1:${me}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:G})});console.log(J.ok?m.cyan(` Pushed ${R.length} question(s) to ${P.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.`))}}}}});Z.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:t,reportFields:o,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:r}=await import("./seat-XNA2O6EO.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-X44PF73W.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=Ae(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),h=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(T=>[T.name.toLowerCase().trim(),T])),v=0,A=0,S=[],x=!1;e:for(let T of p){let P=f.getAgentWiki(T);for(let B of P.listArticles(T)){if(v>=w)break e;if(B.meta.type!=="person")continue;let L=P.readArticle(B.path);if(!L)continue;v++;let G=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),t(L.meta.type),{links:[{kind:"article",id:B.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 J=o(L.meta.type,G.answers).missing.filter(_=>i.includes(_));if(J.length===0)continue;let{records:je,results:ke}=await a([{name:L.meta.title,type:"person"}],{sources:h}),M=b.get(L.meta.title.toLowerCase().trim());if(!x){for(let _ of l(ke,h))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));x=!0}let Ye=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,he])=>[_,he.value]))}]:[],...je]);if(Ye.length===0)continue;let{content:ve,edits:Jt}=u(L.content,Ye[0],J);if(Jt.length!==0){for(let _ of Jt)S.push({agent:T,article:L.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(B.path,L.meta,ve,T)?A++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let $=["agent","article","field","action","got"],R=$.map(T=>Math.max(T.length,...S.map(P=>String(P[T]).length))),C=T=>T.map((P,B)=>String(P).padEnd(R[B])).join(" ");console.log(),console.log(m.bold(C($)));for(let T of S)console.log(C($.map(P=>T[P])));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 ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});Z.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:t}=await import("./questions-QGITDLJY.js"),{TIER_RANK:o}=await import("./article-fields-PITN4NHA.js"),n=new t(ro(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)=>(o[s.tier??"furniture"]??9)-(o[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`))});Z.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,t,o)=>{let{QuestionStore:n}=await import("./questions-QGITDLJY.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(ro(o.dir));if(o.dismiss){let p=r.resolve(e,"dismissed");console.log(p?m.dim(` dismissed: ${p.question}`):m.red(` no question matching "${e}"`));return}if(!t){console.log(m.red(" give a value, or pass --dismiss"));return}let a=r.list("open").find(p=>p.id===e||p.id.startsWith(e));if(a?.kind==="contradiction"&&a.factId){let{FactLedger:p}=await import("./ledger-DHYRP4TN.js"),w=new p(ro(o.dir));try{let h=w.get(a.factId);if(h){let k=w.write({subject:h.subject,attribute:h.attribute,value:t,source:"owner said",verifiedBy:"operator",volatility:h.volatility},{confirmedBy:"operator"});console.log(m.green(` ${k.status}: ${h.id} ${h.subject} \xB7 ${h.attribute}: ${k.fact.value}`))}else console.log(m.yellow(` fact ${a.factId} is gone; answer recorded only.`))}catch(h){h?.name!=="LedgerCorruptError"&&console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}r.resolve(a.id,"answered",t),console.log(m.green(` answered: ${a.question}`));return}let c=r.resolve(e,"answered",t);if(!c){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${c.question}`)),c.kind!=="field"||!c.field||!c.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[c.field]){console.log(m.dim(` recorded against ${c.path}. "${c.field}" has no fixed slot, so nothing was rewritten.`));return}let g=Ae(o.dir,o.mode).getAgentWiki(c.agentId),d=g.readArticle(c.path);if(!d){console.log(m.yellow(` article gone: ${c.path}`));return}let u=s(d.content,c.field,`${t} (answered by operator)`);if(!u){console.log(m.dim(" already present \u2014 nothing to write."));return}let f=g.writeArticle(c.path,d.meta,u.content,c.agentId);console.log(f?m.green(` wrote ${c.field} into ${c.path} (prior version kept)`):m.red(` could not write ${c.path}`))});Z.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:t,entryTriageQuestions:o,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:i}=await import("./seat-XNA2O6EO.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=Ae(e.dir,"graph").getSharedStore(),p=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:h,backlog:k}=r(p,w),b=a(h,L=>L.absorbed,parseInt(e.n)),v={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},A=[],S=0,x=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(` ${h.length} labelled (${k} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let G=await i(t,n(L),o,{features:{source:L.source??"",absorbed:L.absorbed}});if(!G){S++;continue}let me=G.answers;A.push({entry:L,verdict:s(G.answers,v),citeWorthy:me.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:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),R=l(A,"seat","seat"),C=d(R,{minN:50}),T=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:$,calibration:C,failures:S,elapsed:T},null,2));return}let P=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${$.n} (${$.positives} kept by absorb, ${$.negatives} passed over)`),console.log(` recall ${P($.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P($.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P($.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 C)||!C.insufficient)&&console.log(` ECE ${C.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 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, ${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:me}=g(A,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${me.length} policies, recall floor ${P(L)})`)),G)console.log(` best: ${G.requireTyped?`typed & type>=${G.minType}`:"type gate OFF"} worth>=${G.minWorth} durability>=${G.minDurability}`),console.log(` recall ${P(G.recall)} \xB7 filtered ${P(G.filtered)} \xB7 precision ${P(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 ${P(L)} recall \u2014 not even keeping everything typed.`));let J=me.slice().sort((je,ke)=>ke.recall-je.recall)[0];J&&console.log(m.dim(` Best recall available: ${P(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${P(J.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});Z.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,t)=>{let o=F(process.cwd(),e);Ve(o)||(console.log(m.red(` archive not found: ${o}`)),process.exit(1));let n=t.dir?F(process.cwd(),t.dir):F(process.cwd(),".agentx/wiki");Ve(n)&&!t.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=F(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",o];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 Ph(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"}im();import{Command as Mh}from"commander";import D from"chalk";import{resolve as Ns}from"path";import{existsSync as Lh}from"fs";ae();var Uo=new Mh().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Uo.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 t=I();if(!t.graph?.enabled){console.log(D.yellow(" graph.enabled is false \u2014 nothing to review"));return}let o=e.agent||t.graph.reviewAgent||t.graph.draftAgent;if(!o){console.log(D.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!t.agents?.[o]){console.log(D.red(` agent "${o}" not in config`));return}let n=(e.daemonUrl||t.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new vt({baseDir:Ns(process.cwd(),t.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(D.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(D.bold(` Graph review \u2014 ${r.length} pending`)),console.log(D.dim(` Reviewer: ${o} \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],h=Mn(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${D.cyan(w.msgHash.slice(0,8))} ${D.dim(h)} ... `);let k=Fh(w,a,c),b=null;try{b=await Uh(n,o,k,t.dashboard?.token)}catch(S){u++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(D.red("ERR no decision"));continue}let v=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(A)),e.dryRun)l++;else try{qh(i,w,a,c,o),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:o,reviewReason:A}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),u++}else v==="reject"?(console.log(D.red("REJECT")+" "+D.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:o,reviewReason:A}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(A||v)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(D.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${u} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});Uo.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 t=I();if(!t.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let o=Ns(process.cwd(),t.graph.baseDir);if(!Lh(o)){console.log(D.yellow(` ${o} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-5VGHWPBW.js"),s=new vt({baseDir:o,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(D.dim(" "),...a)});console.log(),console.log(D.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(D.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});Uo.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 t=I();if(!t.graph?.enabled){console.log(D.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let o=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 vt({baseDir:Ns(process.cwd(),t.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map($=>$.id));console.log(),console.log(D.bold(` graph pull \u2190 ${o}`));let l,g,d;try{let $=await fetch(`${o}/graph/schema`,{headers:s});if(!$.ok)throw new Error(`schema HTTP ${$.status}`);l=(await $.json()).schema;let C=await fetch(`${o}/graph/nodes`,{headers:s});if(!C.ok)throw new Error(`nodes HTTP ${C.status}`);g=(await C.json()).nodes||[];let T=await fetch(`${o}/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(D.red(` fetch failed: ${$.message}`));return}let u=r.levels.map($=>$.id).join(","),f=l?.levels?.map($=>$.id).join(","),p=u===f;p?console.log(D.dim(` schema matches (${r.levels.length} levels)`)):(console.log(D.yellow(" \u26A0 schema levels differ:")),console.log(D.dim(` local: ${u}`)),console.log(D.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(D.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(D.yellow(" keeping local schema; node import may fail if levels disagree")));let w=p?r:l,h=new Map;w.levels.forEach(($,R)=>h.set($.id,R));let k=[...g].sort(($,R)=>(h.get($.level)??99)-(h.get(R.level)??99)),b=0,v=0,A=0;for(let $ of k){if(c.has($.id)){v++;continue}if(e.dryRun){b++,c.add($.id);continue}try{i.addNode({...$,createdBy:$.createdBy?`${$.createdBy} (sync)`:`sync:${o}`}),c.add($.id),b++}catch(R){A++,console.log(D.yellow(` skip node ${$.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${A} failed`));let S=0,x=0;for(let $ of d)if(!(!$.msgHash||!Array.isArray($.path))){if(i.getFingerprint($.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint($.msgHash,{path:$.path,leaf:$.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${x} already-present`)),console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` \u2713 pulled from ${o}`)),console.log()});function Fh(e,t,o){let n={};for(let r of o)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=t.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
|
|
504
|
+
agentx wiki questions`,me=T?.daemon?.port??T?.port??18800;try{let J=await fetch(`http://127.0.0.1:${me}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:G})});console.log(J.ok?m.cyan(` Pushed ${R.length} question(s) to ${P.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.`))}}}}});Z.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:t,reportFields:o,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:r}=await import("./seat-XNA2O6EO.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-X44PF73W.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=je(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=g(),$=c(d(f.getSharedStore().listEntries())),b=new Map($.map(T=>[T.name.toLowerCase().trim(),T])),v=0,A=0,S=[],x=!1;e:for(let T of p){let P=f.getAgentWiki(T);for(let B of P.listArticles(T)){if(v>=w)break e;if(B.meta.type!=="person")continue;let L=P.readArticle(B.path);if(!L)continue;v++;let G=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),t(L.meta.type),{links:[{kind:"article",id:B.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 J=o(L.meta.type,G.answers).missing.filter(_=>i.includes(_));if(J.length===0)continue;let{records:Oe,results:ke}=await a([{name:L.meta.title,type:"person"}],{sources:y}),M=b.get(L.meta.title.toLowerCase().trim());if(!x){for(let _ of l(ke,y))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));x=!0}let Ye=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,he])=>[_,he.value]))}]:[],...Oe]);if(Ye.length===0)continue;let{content:ve,edits:Jt}=u(L.content,Ye[0],J);if(Jt.length!==0){for(let _ of Jt)S.push({agent:T,article:L.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(B.path,L.meta,ve,T)?A++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let k=["agent","article","field","action","got"],R=k.map(T=>Math.max(T.length,...S.map(P=>String(P[T]).length))),C=T=>T.map((P,B)=>String(P).padEnd(R[B])).join(" ");console.log(),console.log(m.bold(C(k)));for(let T of S)console.log(C(k.map(P=>T[P])));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 ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});Z.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:t}=await import("./questions-ZATLU5AW.js"),{TIER_RANK:o}=await import("./article-fields-PITN4NHA.js"),n=new t(ro(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)=>(o[s.tier??"furniture"]??9)-(o[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`))});Z.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,t,o)=>{let{QuestionStore:n}=await import("./questions-ZATLU5AW.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(ro(o.dir)),a=r.list().find(w=>(w.id===e||w.id.startsWith(e))&&w.status!=="open"&&w.kind==="contradiction");if(a&&!r.list("open").some(w=>w.id===e||w.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(o.dismiss){try{let w=r.resolve(e,"dismissed");console.log(w?m.dim(` dismissed: ${w.question}`):m.red(` no question matching "${e}"`))}catch(w){console.log(m.red(` ${w?.message??w}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!t){console.log(m.red(" give a value, or pass --dismiss"));return}let c=r.list("open").find(w=>w.id===e||w.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:w}=await import("./ledger-CH7R756S.js"),y=new w(ro(o.dir));try{let $=y.get(c.factId);if($){let b=y.write({subject:$.subject,attribute:$.attribute,value:t,source:"owner said",verifiedBy:"operator",volatility:$.volatility},{confirmedBy:"operator"});console.log(m.green(` ${b.status}: ${$.id} ${$.subject} \xB7 ${$.attribute}: ${b.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch($){$?.name!=="LedgerCorruptError"&&console.log(m.red(` ${$?.message??$}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}r.resolve(c.id,"answered",t),console.log(m.green(` answered: ${c.question}`));return}let l;try{l=r.resolve(e,"answered",t)}catch(w){console.log(m.red(` ${w?.message??w}`)),console.log(m.yellow(" nothing changed.")),process.exitCode=1;return}if(!l){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${l.question}`)),l.kind!=="field"||!l.field||!l.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[l.field]){console.log(m.dim(` recorded against ${l.path}. "${l.field}" has no fixed slot, so nothing was rewritten.`));return}let d=je(o.dir,o.mode).getAgentWiki(l.agentId),u=d.readArticle(l.path);if(!u){console.log(m.yellow(` article gone: ${l.path}`));return}let f=s(u.content,l.field,`${t} (answered by operator)`);if(!f){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=d.writeArticle(l.path,u.meta,f.content,l.agentId);console.log(p?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.path}`))});Z.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:t,entryTriageQuestions:o,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:i}=await import("./seat-XNA2O6EO.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=je(e.dir,"graph").getSharedStore(),p=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:y,backlog:$}=r(p,w),b=a(y,L=>L.absorbed,parseInt(e.n)),v={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},A=[],S=0,x=Date.now();if(e.load){let{readFileSync:L}=await import("fs");A.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${$} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let G=await i(t,n(L),o,{features:{source:L.source??"",absorbed:L.absorbed}});if(!G){S++;continue}let me=G.answers;A.push({entry:L,verdict:s(G.answers,v),citeWorthy:me.citeWorthy?.noul})}if(A.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let k=c(A,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),R=l(A,"seat","seat"),C=d(R,{minN:50}),T=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:k,calibration:C,failures:S,elapsed:T},null,2));return}let P=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${k.n} (${k.positives} kept by absorb, ${k.negatives} passed over)`),console.log(` recall ${P(k.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P(k.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P(k.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${k.lostPositives>0?m.yellow(`lost ${k.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in C)||!C.insufficient)&&console.log(` ECE ${C.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),k.lostPositives>0){let L=k.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let B=k.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, ${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:me}=g(A,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${me.length} policies, recall floor ${P(L)})`)),G)console.log(` best: ${G.requireTyped?`typed & type>=${G.minType}`:"type gate OFF"} worth>=${G.minWorth} durability>=${G.minDurability}`),console.log(` recall ${P(G.recall)} \xB7 filtered ${P(G.filtered)} \xB7 precision ${P(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 ${P(L)} recall \u2014 not even keeping everything typed.`));let J=me.slice().sort((Oe,ke)=>ke.recall-Oe.recall)[0];J&&console.log(m.dim(` Best recall available: ${P(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${P(J.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});Z.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,t)=>{let o=F(process.cwd(),e);Ve(o)||(console.log(m.red(` archive not found: ${o}`)),process.exit(1));let n=t.dir?F(process.cwd(),t.dir):F(process.cwd(),".agentx/wiki");Ve(n)&&!t.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=F(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",o];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 Ph(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"}im();import{Command as Mh}from"commander";import D from"chalk";import{resolve as Ns}from"path";import{existsSync as Lh}from"fs";ae();var Uo=new Mh().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Uo.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 t=I();if(!t.graph?.enabled){console.log(D.yellow(" graph.enabled is false \u2014 nothing to review"));return}let o=e.agent||t.graph.reviewAgent||t.graph.draftAgent;if(!o){console.log(D.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!t.agents?.[o]){console.log(D.red(` agent "${o}" not in config`));return}let n=(e.daemonUrl||t.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new vt({baseDir:Ns(process.cwd(),t.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(D.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(D.bold(` Graph review \u2014 ${r.length} pending`)),console.log(D.dim(` Reviewer: ${o} \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=Mn(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${D.cyan(w.msgHash.slice(0,8))} ${D.dim(y)} ... `);let $=Fh(w,a,c),b=null;try{b=await Uh(n,o,$,t.dashboard?.token)}catch(S){u++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(D.red("ERR no decision"));continue}let v=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(A)),e.dryRun)l++;else try{qh(i,w,a,c,o),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:o,reviewReason:A}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),u++}else v==="reject"?(console.log(D.red("REJECT")+" "+D.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:o,reviewReason:A}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(A||v)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(D.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${u} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});Uo.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 t=I();if(!t.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let o=Ns(process.cwd(),t.graph.baseDir);if(!Lh(o)){console.log(D.yellow(` ${o} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-KOMPDC6U.js"),s=new vt({baseDir:o,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(D.dim(" "),...a)});console.log(),console.log(D.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(D.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});Uo.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 t=I();if(!t.graph?.enabled){console.log(D.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let o=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 vt({baseDir:Ns(process.cwd(),t.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(k=>k.id));console.log(),console.log(D.bold(` graph pull \u2190 ${o}`));let l,g,d;try{let k=await fetch(`${o}/graph/schema`,{headers:s});if(!k.ok)throw new Error(`schema HTTP ${k.status}`);l=(await k.json()).schema;let C=await fetch(`${o}/graph/nodes`,{headers:s});if(!C.ok)throw new Error(`nodes HTTP ${C.status}`);g=(await C.json()).nodes||[];let T=await fetch(`${o}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!T.ok)throw new Error(`classifications HTTP ${T.status}`);d=(await T.json()).classifications||[]}catch(k){console.log(D.red(` fetch failed: ${k.message}`));return}let u=r.levels.map(k=>k.id).join(","),f=l?.levels?.map(k=>k.id).join(","),p=u===f;p?console.log(D.dim(` schema matches (${r.levels.length} levels)`)):(console.log(D.yellow(" \u26A0 schema levels differ:")),console.log(D.dim(` local: ${u}`)),console.log(D.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(D.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(D.yellow(" keeping local schema; node import may fail if levels disagree")));let w=p?r:l,y=new Map;w.levels.forEach((k,R)=>y.set(k.id,R));let $=[...g].sort((k,R)=>(y.get(k.level)??99)-(y.get(R.level)??99)),b=0,v=0,A=0;for(let k of $){if(c.has(k.id)){v++;continue}if(e.dryRun){b++,c.add(k.id);continue}try{i.addNode({...k,createdBy:k.createdBy?`${k.createdBy} (sync)`:`sync:${o}`}),c.add(k.id),b++}catch(R){A++,console.log(D.yellow(` skip node ${k.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${A} failed`));let S=0,x=0;for(let k of d)if(!(!k.msgHash||!Array.isArray(k.path))){if(i.getFingerprint(k.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint(k.msgHash,{path:k.path,leaf:k.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${x} already-present`)),console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` \u2713 pulled from ${o}`)),console.log()});function Fh(e,t,o){let n={};for(let r of o)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=t.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
|
|
505
505
|
`),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(`
|
|
506
506
|
`)}async function Uh(e,t,o,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:t,message:o,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 Wr((c?.content||"").toString())}finally{clearTimeout(r)}}function qh(e,t,o,n,s){e.commitNodesAlongPath(t.path,t.proposedAxes||{},o,s),e.setFingerprint(t.msgHash,{path:t.path,leaf:t.leaf||{}})}function ar(){let e=I();if(!e.graph?.baseDir)return console.log(D.red(" graph.baseDir is not configured")),null;let t=Ns(process.cwd(),e.graph.baseDir);return{store:new vt({baseDir:t}),baseDir:t}}var cr=Uo.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");cr.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 t=ar();if(!t)return;let{ReviewStore:o,buildQueue:n}=await import("./review-store-PW3OBGZQ.js"),s=t.store.listAllClassifications(),i=new o(t.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(D.green(" nothing left unreviewed"));return}let a=t.store.loadNodes().nodes;console.log();for(let c of r){let l=typeof c.confidence=="number"?c.confidence.toFixed(2):D.dim("cache");console.log(` ${D.cyan(c.msgHash.slice(0,8))} ${l.padStart(5)} ${D.bold(Mn(c.path,a)||c.path.join(" \u203A "))}`),c.preview&&console.log(D.dim(` ${String(c.preview).replace(/\s+/g," ").slice(0,96)}`))}console.log(),console.log(D.dim(` ${r.length} to check (${e.strategy}).`)),console.log(D.dim(" agentx graph label mark <hash> correct|wrong|unsure [--path a/b/c]"))});cr.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,t,o)=>{if(!["correct","wrong","unsure"].includes(t)){console.log(D.red(" verdict must be correct | wrong | unsure"));return}let n=ar();if(!n)return;let{ReviewStore:s}=await import("./review-store-PW3OBGZQ.js"),r=n.store.listAllClassifications().filter(l=>l.msgHash===e||l.msgHash.startsWith(e));if(r.length===0){console.log(D.red(` no classification matching "${e}"`));return}if(r.length>1){console.log(D.red(` "${e}" matches ${r.length} rows \u2014 use more characters`));return}new s(n.baseDir).record({msgHash:r[0].msgHash,verdict:t,correctPath:o.path?String(o.path).split("/").filter(Boolean):void 0,note:o.note,reviewer:o.by});let c=n.store.loadNodes().nodes;console.log(D.green(` ${t}: ${Mn(r[0].path,c)||r[0].path.join(" \u203A ")}`)),o.path&&console.log(D.dim(` should have been: ${o.path}`))});cr.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let t=ar();if(!t)return;let{ReviewStore:o,labelStats:n}=await import("./review-store-PW3OBGZQ.js"),s=t.store.listAllClassifications(),i=new o(t.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} ${D.dim("reviewed rows that carry a confidence")}`),r.byBin.length>0){console.log(),console.log(D.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?D.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(D.dim(` ${100-r.calibratable} more labelled rows before a calibration report means anything.`)):console.log(D.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as zh}from"commander";import V from"chalk";import{Command as rg}from"commander";import le from"chalk";import{existsSync as Wh}from"fs";import{resolve as Bh}from"path";import Jh from"better-sqlite3";function Hh(e){if(!e)return;let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(t){let n=Number(t[1]),s=t[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let o=Number(e);if(Number.isFinite(o)&&o>0)return o;console.log(le.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function Gh(e){let t=Bh(process.cwd(),e);return Wh(t)||(console.log(le.red(` No db at ${t}`)),process.exit(1)),new Jh(t,{readonly:!0})}var ag=new rg().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(nn)).option("--max <n>","max clusters distilled per run",String(qn)).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(le.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let t=Gh(e.path),o=await Oa(t,{since:Hh(e.since),agentId:e.agent,sessions:new Kr(process.cwd()),minOccurrences:Number(e.minOccurrences)||nn,max:Number(e.max)||qn,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(le.dim(` ${n}`))});console.log(),console.log(` ${o.episodes} episode(s) \u2192 ${o.clusters} cluster(s), ${o.ready.length} at threshold`);for(let n of o.ready)console.log(` ${le.cyan(n.key)} ${le.bold(`\xD7${n.count}`)} ${le.dim(n.status)}`),n.sampleMessage&&console.log(le.dim(` "${n.sampleMessage.slice(0,100)}"`));if(o.nearMisses.length){console.log(le.dim(`
|
|
507
507
|
near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of o.nearMisses.slice(0,5))console.log(le.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of o.drafted)console.log(le.green(` \u2713 draft written: ${n.id}`)+le.dim(` (${n.count} occurrences)`));for(let n of o.skipped)console.log(le.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of o.warnings)console.log(le.yellow(` \u26A0 ${n}`));o.dryRun?console.log(le.dim(`
|
|
508
508
|
dry run only; pass --commit --via <agentId> to write drafts`)):o.drafted.length&&console.log(le.dim(`
|
|
509
509
|
review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),ig={hourly:"0 * * * *",daily:"0 3 * * *"},cg=new rg().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(nn)).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 t=e.off?void 0:e.cron??(e.hourly?ig.hourly:e.daily?ig.daily:void 0);!e.off&&!t&&!e.onTask&&(console.log(le.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(le.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let o=Number(e.minOccurrences)||nn,n={enabled:!e.off,onTaskCompletion:!e.off&&!!e.onTask,minOccurrences:o,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 ${qn} --min-occurrences ${o} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
|
|
510
|
-
`),i=await ye(a=>{
|
|
510
|
+
`),i=await ye(a=>{Te(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&Te(a,"crons.procedure-extract.enabled",!1):t&&Te(a,"crons.procedure-extract",{enabled:!0,schedule:t,timezone:e.timezone,agent:e.via,prompt:s,timeout:900,onError:"log"})},{configPath:e.config,dryRun:!!e.dryRun});i.success||(console.log(le.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(le.green(` \u2713 ${r} procedure extraction: off`)):(console.log(le.green(` \u2713 ${r} procedure extraction cadence`)),t&&console.log(le.dim(` cron: ${t} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(le.dim(" on-task counting: enabled")),console.log(le.dim(` threshold: ${o} occurrences`))),console.log(le.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var it=new zh().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");it.addCommand(ag);it.addCommand(cg);it.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 t=new xt,o=[...e.drafts?[]:t.list(),...e.drafts||e.all?t.listDrafts():[]];if(!o.length){console.log(V.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 o){let s=n.meta.status==="active"?V.green(n.meta.status):n.meta.status==="draft"?V.yellow(n.meta.status):V.dim(n.meta.status);console.log(` ${V.cyan(n.meta.id)} ${V.bold(n.meta.title)} ${s}`),console.log(` ${V.dim("trigger:")} ${n.meta.trigger}`),n.meta.source&&console.log(` ${V.dim("source:")} ${V.dim(n.meta.source)}`),n.meta.kpis?.length&&console.log(` ${V.dim("kpis:")} ${n.meta.kpis.join(", ")}`)}console.log(),console.log(V.dim(` ${o.length} procedure${o.length===1?"":"s"}.`))});it.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,t=[])=>[...t,e]).option("--expected <t>","expected output / success criterion").option("--kpi <k...>","KPI (repeatable)",(e,t=[])=>[...t,e]).option("--owner <id>","owning agent or person").option("--tag <t...>","tag (repeatable)",(e,t=[])=>[...t,e]).option("--related <r...>","related procedure id or wiki article title (repeatable)",(e,t=[])=>[...t,e]).option("--steps <md>","markdown body \u2014 usually numbered steps").action(e=>{let t=new xt,o=e.steps?String(e.steps):`## Steps
|
|
511
511
|
|
|
512
512
|
1. (fill in)
|
|
513
513
|
|
|
@@ -517,8 +517,8 @@ agentx wiki questions`,me=T?.daemon?.port??T?.port??18800;try{let J=await fetch(
|
|
|
517
517
|
${n.join(`
|
|
518
518
|
`)}`)}var Ge=new Kh().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Ge.command("list").description("list all workflows with their trigger + state count").action(()=>{let t=new Ht().list();if(!t.length){console.log(E.dim(" no workflows yet. Add one by writing .agentx/workflows/<id>.json"));return}console.log();for(let o of t){let s=o.nodes.find(a=>a.type.startsWith("trigger."))?.config??{},i=[s.filter?.project,s.filter?.repo,s.filter?.chat].filter(Boolean).join(" / "),r=o.state==="active"?E.green("dispatch: active"):E.yellow(`dispatch: ${o.state}`);console.log(` ${E.cyan(o.id)} ${E.bold(o.title)} ${E.dim(`v${o.version} \xB7`)} ${r} ${E.dim(`\xB7 review: ${o.status}`)}`),console.log(` ${E.dim("trigger:")} ${s.source??"?"}${i?` ${E.dim(i)}`:""}`),console.log(` ${E.dim("nodes: ")} ${o.nodes.length} (${o.nodes.map(a=>a.type).join(", ")})`)}console.log(),console.log(E.dim(` ${t.length} workflow${t.length===1?"":"s"}.`))});Ge.command("show <id>").description("show a single workflow's full definition").option("--format <fmt>","output format: json (default) or yaml","json").action((e,t)=>{let n=new Ht().get(e);n||(console.log(E.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=t.format.toLowerCase();s==="yaml"||s==="yml"?console.log(ta(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(E.red(` unknown format "${t.format}" \u2014 use json or yaml`)),process.exit(1))});Ge.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=Wo(process.cwd(),e);lr(i)||(console.log(E.red(` file not found: ${i}`)),process.exit(1));try{let r=dr(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?fo(r,{filePath:e}):JSON.parse(r),l=uo.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=Ln(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 o=new Ht().validateAll(),n=0,s=0;for(let i of o)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)});Ge.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${jn.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,t)=>{let o=String(t.template||"linear");jn.some(a=>a.name===o)||(console.log(E.red(` unknown template "${t.template}"`)),console.log(E.dim(` available: ${jn.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 Ht;!t.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=dg(o);s=s.replace(/__ID__/g,e).replace(/__TITLE__/g,t.title?String(t.title):`${o} workflow ${e}`).replace(/__AGENT__/g,String(t.agent)).replace(/__REVIEWER__/g,String(t.reviewer));try{let a=fo(s,{filePath:`${e}.yaml`}),c=uo.safeParse(a);if(!c.success){console.log(E.red(` template "${o}" 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=t.json?"json":"yaml",r=Wo(process.cwd(),".agentx/workflows",`${e}.${i}`);if(t.json){let a=fo(s,{filePath:`${e}.yaml`}),c=uo.parse(a);Rs(r,JSON.stringify(c,null,2)+`
|
|
519
519
|
`)}else Rs(r,s);console.log(),console.log(E.green(` \u2713 scaffolded ${r}`)),console.log(E.dim(` template: ${o}`)),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()});Ge.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of jn)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()});Ge.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,t)=>{let o=Wo(process.cwd(),e);lr(o)||(console.log(E.red(` file not found: ${o}`)),process.exit(1));let n=dr(o,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?fo(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=uo.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=Ln(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 Ht,l=s?Xh(e).match(/\.yml$/i)?"yml":"yaml":"json",g=Wo(c.baseDir,`${r.data.id}.${l}`);if(Rs(g,s?n:JSON.stringify(r.data,null,2)+`
|
|
520
|
-
`),console.log(E.green(` \u2713 ${r.data.id} \u2192 ${g}`)),t.reload===!1){console.log(E.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let d=`${String(t.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 ${t.daemon} \u2014 start it or restart to pick up the new workflow`))}});Ge.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,t)=>{let o=t.node||process.env.WF_NODE_ID||"local",n=new on({nodeId:o}).list({workflowId:e,limit:Number(t.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"}.`))});Ge.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,t)=>{let o={};if(t.input)try{o=JSON.parse(t.input)}catch{console.log(E.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=Wo(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&lr(s)){let c=dr(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),g;try{g=l?fo(c,{filePath:e}):JSON.parse(c)}catch(b){let v=b instanceof Fn?b.message:`parse error: ${b?.message??b}`;console.log(E.red(` ${v}`)),process.exit(1)}let d=uo.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=Ln(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 Ht,p=d.data.id.startsWith("_adhoc-")?d.data.id:`_adhoc-${d.data.id}-${Date.now().toString(36)}`,w=l?"yaml":"json",
|
|
521
|
-
`;Rs(
|
|
520
|
+
`),console.log(E.green(` \u2713 ${r.data.id} \u2192 ${g}`)),t.reload===!1){console.log(E.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let d=`${String(t.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 ${t.daemon} \u2014 start it or restart to pick up the new workflow`))}});Ge.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,t)=>{let o=t.node||process.env.WF_NODE_ID||"local",n=new on({nodeId:o}).list({workflowId:e,limit:Number(t.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"}.`))});Ge.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,t)=>{let o={};if(t.input)try{o=JSON.parse(t.input)}catch{console.log(E.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=Wo(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&lr(s)){let c=dr(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),g;try{g=l?fo(c,{filePath:e}):JSON.parse(c)}catch(b){let v=b instanceof Fn?b.message:`parse error: ${b?.message??b}`;console.log(E.red(` ${v}`)),process.exit(1)}let d=uo.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=Ln(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 Ht,p=d.data.id.startsWith("_adhoc-")?d.data.id:`_adhoc-${d.data.id}-${Date.now().toString(36)}`,w=l?"yaml":"json",y=Wo(f.baseDir,`${p}.${w}`),$=l?c.replace(new RegExp(`^id:\\s*${d.data.id}\\b`,"m"),`id: ${p}`):JSON.stringify({...d.data,id:p},null,2)+`
|
|
521
|
+
`;Rs(y,$),n=p,console.log(E.dim(` ad-hoc registered as "${p}" \u2192 ${y}`));try{await fetch(`${String(t.daemon).replace(/\/$/,"")}/reload`,{method:"POST"})}catch{}}let r=`${String(t.daemon).replace(/\/$/,"")}/workflows/${encodeURIComponent(n)}/run`,a;try{let c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:o,force:!!t.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)}t.watch&&a&&await Qh({daemonUrl:String(t.daemon).replace(/\/$/,""),runId:a})});async function Qh(e){let t=new Set,o=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||t.has(r.taskId)||(t.add(r.taskId),o.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(o.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(o.values())}Ge.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,t)=>{let o=String(t.daemon).replace(/\/$/,"");try{let i=await fetch(`${o}/traces/${encodeURIComponent(e)}`);if(i.ok){let r=await i.json();if(t.json){console.log(JSON.stringify(r,null,2));return}gg(r);return}}catch{}let n;try{let i=await fetch(`${o}/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(t.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)gg(i)});function gg(e){let t=e.status||"ok",o=t==="ok"?E.green:t==="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(` ${o(t.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()}Ge.command("pause <runId>").description("pause an active run").option("--node <id>","home-node id").action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local";new on({nodeId:o}).setStatus(e,"paused")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 paused ${e}`))});Ge.command("resume <runId>").description("resume a paused run").option("--node <id>","home-node id").action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local";new on({nodeId:o}).setStatus(e,"running")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 resumed ${e}`))});Ge.command("cancel <runId>").description("cancel an active run").option("--node <id>","home-node id").action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local";new on({nodeId:o}).setStatus(e,"canceled")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 canceled ${e}`))});import{Command as mg}from"commander";import ie from"chalk";import ao from"prompts";import{readFileSync as Zh,existsSync as ey}from"fs";import{resolve as ty}from"path";var On=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],gr=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),pg={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 ug(){let e=ty(process.cwd(),"agentx.json");if(!ey(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Zh(e,"utf-8"))}function oy(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?ie.yellow("\u26A0 no signing secret"):ie.green("\u2713 active"):ie.dim("disabled")}function ny(e,t){let o=t?`${t.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=gr.has(e.source)?ie.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${ie.cyan(e.id)} ${oy(e)}`),console.log(` ${ie.dim(e.source)} \u2192 ${ie.bold(e.agentId)}${n}`),console.log(` POST ${ie.dim(o)}`),e.secretEnv&&console.log(` secret: ${ie.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${ie.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${ie.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${ie.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var $t=new mg().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");$t.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let t=ug(),o=Array.isArray(t.webhooks)?t.webhooks:[];if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log(ie.dim(`
|
|
522
522
|
No webhooks registered. Add one with: agentx webhook add
|
|
523
523
|
`));return}console.log();for(let n of o)ny(n)});$t.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${On.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,t)=>{let o=ug(),n=Object.keys(o.agents||{}),s=(o.mesh?.peers||[]).map(f=>f.name).filter(Boolean),i=String(t.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(t.source||"").trim(),c=String(t.agent||"").trim(),l=String(t.secretEnv||"").trim(),g=String(t.description||"").trim(),d=t.prompt!==!1;if(!r&&d&&(r=((await ao({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 ao({type:"select",name:"source",message:"Source",choices:On.map(p=>({title:`${p}${gr.has(p)?" \u2713 wired":""}`,value:p,description:pg[p]}))})).source),!On.includes(a))throw new Error(`Source must be one of: ${On.join(", ")}`);if(!c&&d&&(i?c=((await ao({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await ao({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(!o.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 ao({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&d&&(g=((await ao({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let u=await ye(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(ie.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),u.reloaded&&console.log(ie.dim(" daemon hot-reloaded")),!l&&a!=="custom"&&console.log(ie.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});$t.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,t)=>{if(!t.yes&&!(await ao({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let o=await ye(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(!o.success)throw new Error(o.error);console.log(ie.green(`\u2713 removed webhook "${e}"`))});function fg(e){return async t=>{let o=await ye(n=>{let s=(n.webhooks||[]).find(i=>i.id===t);if(!s)throw new Error(`Webhook "${t}" not found.`);s.enabled=e});if(!o.success)throw new Error(o.error);console.log(ie.green(`\u2713 ${e?"enabled":"disabled"} webhook "${t}"`))}}$t.command("enable <id>").description("enable a webhook entry").action(fg(!0));$t.command("disable <id>").description("disable a webhook entry").action(fg(!1));var _s=new mg().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");_s.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,t,o)=>{let n=await ye(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[t]=o});if(!n.success)throw new Error(n.error);console.log(ie.green(`\u2713 ${e}: ${t} \u2192 ${o}`))});_s.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,t)=>{let o=await ye(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[t]});if(!o.success)throw new Error(o.error);console.log(ie.green(`\u2713 removed trigger ${t} from "${e}"`))});_s.command("default <id> <workflowId>").description("set the default workflow when no event-type matches (use '-' to clear)").action(async(e,t)=>{let o=t==="-"||t==="",n=await ye(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);o?delete i.defaultWorkflow:i.defaultWorkflow=t});if(!n.success)throw new Error(n.error);console.log(ie.green(`\u2713 ${e}: defaultWorkflow ${o?"cleared":`\u2192 ${t}`}`))});$t.addCommand(_s);$t.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let t=On.map(o=>({source:o,wired:gr.has(o),hint:pg[o]}));if(e.json){console.log(JSON.stringify(t,null,2));return}console.log();for(let o of t){let n=o.wired?ie.green("\u2713 wired"):ie.dim("inbound-only");console.log(` ${ie.cyan(o.source.padEnd(8))} ${n} ${ie.dim(o.hint)}`)}console.log(),console.log(ie.dim(" Wired sources emit on:<source>-* hook events that workflows can subscribe to via trigger.hook.")),console.log(ie.dim(" Use 'custom' for any service not in the list (Odoo, HubSpot, Linear, Calendly, etc.).")),console.log()});import{Command as sy}from"commander";import re from"chalk";ae();function Bo(e){let{summary:t,backupPath:o}=ct(n=>e(n));console.log(re.green(`
|
|
524
524
|
\u2713 ${t}`)),o&&console.log(re.dim(` Backup: ${o}`)),console.log(re.dim(` Restart the daemon (or POST /reload) for the change to take effect.
|
|
@@ -537,8 +537,8 @@ agentx wiki questions`,me=T?.daemon?.port??T?.port??18800;try{let J=await fetch(
|
|
|
537
537
|
|
|
538
538
|
`))>=0;){let f=l.slice(0,u);l=l.slice(u+2),yy(f)}}}catch(r){console.error(te.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function yy(e){let t="message",o="";for(let i of e.split(`
|
|
539
539
|
`))i.startsWith("event: ")?t=i.slice(7):i.startsWith("data: ")&&(o=i.slice(6));if(!o)return;let n={};try{n=JSON.parse(o)}catch{console.log(`${t}: ${o}`);return}let s=n.at?te.dim(new Date(n.at).toLocaleTimeString()):"";switch(t){case"run":{let i=te.cyan(n.phase?.padEnd(9)??"run"),r=te.bold(n.workflowId??""),a=te.dim((n.runId??"").slice(0,8)),c=n.nodeId?te.yellow(n.nodeId):"",l=n.note?te.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=te.magenta(`task.${n.phase}`.padEnd(14)),r=te.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?te.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${te.cyan(a)} ${c}`);break}case"signal":{let i=te.green("signal".padEnd(9)),r=te.bold(n.name),a=te.dim(`(${n.scope})`),c=n.workflowId?te.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=te.blue("mesh".padEnd(9)),r=te.bold(n.peer),a=n.healthy?te.green("\u2713 healthy"):te.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${te.dim(n.delta??"")}`);break}case"channel":{let i=te.yellow("channel".padEnd(9)),r=n.direction==="in"?te.cyan("\u2190"):te.magenta("\u2192"),a=te.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?te.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(te.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${t} ${JSON.stringify(n)}`)}}ae();import{Command as wy}from"commander";import zo from"chalk";function by(e,t){let o=e.replace(/\/+$/,""),n=new URLSearchParams;if(t.since&&n.set("since",t.since),t.limit&&n.set("limit",t.limit),t.agent){let s=n.toString();return`${o}/agents/${encodeURIComponent(t.agent)}/events${s?`?${s}`:""}`}return t.kind&&n.set("kind",t.kind),t.limit||n.set("limit","50"),`${o}/events/recent?${n}`}var Sg=new wy().name("events").description("recent events on this node, or those matching one agent's subscriptions").option("-c, --config <path>","daemon config file").option("-a, --agent <id>","only events matching this agent's subscriptions").option("-s, --since <id|iso>","only events after this event id or ISO time").option("-k, --kind <kind>","only this event kind (without --agent)").option("-n, --limit <n>","most events to show (with --agent: default 20, max 50)").option("--json","machine-readable output").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 t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let a=I(e.config);t||(t=a.dashboard?.daemonUrl||""),o||(o=a.dashboard?.token||"")}catch{}t||(t="http://localhost:18800");let n={};o&&(n.Authorization=`Bearer ${o}`);let s;try{let a=await fetch(by(t,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error(zo.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error(zo.red(` daemon unreachable at ${t}: ${a?.message||a}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(s,null,2));return}let i=s.events??[];if(e.agent&&!s.subscriptions){console.log(zo.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(i.length===0){console.log(zo.dim(" no events"));return}for(let a of i)console.log(` ${Zr(a)} ${zo.dim(a.id)}`);let r=s.next??i[i.length-1].id;console.log(zo.dim(`
|
|
540
|
-
${i.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${r}`))});import{Command as ky}from"commander";import Fs from"chalk";import{spawn as vy}from"node:child_process";import{execFileSync as $y}from"node:child_process";function Eg(e=()=>$y("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let t;try{t=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 o=t.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return o?Number(o[1])<2?{ok:!1,reason:`OpenCode ${t} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:t}:{ok:!1,reason:`Could not recognize the OpenCode version: ${t||"empty output"}`}}var Ag=new ky().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(Fs.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:t}=await import("./client-SWODYWKD.js"),o=t({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:Eg();if(n?.ok){let{fetchAgents:l}=await import("./client-SWODYWKD.js"),g=await l(o);if(!g.length)throw new Error(`No AgentX agents returned by ${o.baseUrl}`);let d=e.agent||g[0].id;if(!g.some(
|
|
541
|
-
bye`)),process.exit(0)});;){let g;try{g=(await a.question(K.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(K.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${Tg().slice(0,12)}`,console.log(K.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let p=await Zn(o);for(let w of p){let
|
|
540
|
+
${i.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${r}`))});import{Command as ky}from"commander";import Fs from"chalk";import{spawn as vy}from"node:child_process";import{execFileSync as $y}from"node:child_process";function Eg(e=()=>$y("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let t;try{t=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 o=t.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return o?Number(o[1])<2?{ok:!1,reason:`OpenCode ${t} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:t}:{ok:!1,reason:`Could not recognize the OpenCode version: ${t||"empty output"}`}}var Ag=new ky().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(Fs.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:t}=await import("./client-SWODYWKD.js"),o=t({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:Eg();if(n?.ok){let{fetchAgents:l}=await import("./client-SWODYWKD.js"),g=await l(o);if(!g.length)throw new Error(`No AgentX agents returned by ${o.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:`${o.baseUrl}/v1`},models:f}}})};console.error(Fs.dim(`Opening ${n.version} with AgentX model ${d}.`));let w=vy("opencode",["--standalone"],{stdio:"inherit",env:p});await new Promise((y,$)=>{w.once("error",$),w.once("exit",b=>b===0?y():$(new Error(`OpenCode exited with code ${b??"unknown"}`)))});return}n&&!n.ok&&(console.error(Fs.yellow(n.reason)),console.error(Fs.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-MMWB4O72.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:o,pollMs:a})).waitUntilExit()});import{Command as xy}from"commander";import K from"chalk";import{randomUUID as Tg}from"crypto";import{createInterface as Sy}from"node:readline/promises";import Ey from"ora";import Us from"chalk";function jg(e){console.error(),console.error(Us.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(Us.dim(` ${e.why}`)),console.error(),console.error(` Use ${Us.cyan(e.instead)} instead.`),e.note&&console.error(Us.dim(` ${e.note}`)),console.error()}var Og={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 Ig=new xy().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,t)=>{jg({what:"agentx chat",...Og});let o=Gc({node:t.node,token:t.token,config:t.config}),n=(e??"").replace(/^@/,"").trim(),s=t.channel,i=t.chatId||`chat-cli:${Tg().slice(0,12)}`,r=[];try{r=await Zn(o)}catch(g){console.error(K.red(` cannot reach daemon at ${o.baseUrl}: ${g?.message||g}`)),console.error(K.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(K.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(K.red(` unknown agent: @${n}`)),console.error(K.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(K.dim(` no agent given \u2014 defaulting to @${n}`))),process.stdout.isTTY&&process.stdin.isTTY){let{render:g}=await import("ink"),{ChatApp:d}=await import("./ChatApp-VCHZLQ57.js"),u=(await import("react")).default;await g(u.createElement(d,{conn:o,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}jy(o.baseUrl,n,i,s);let a=Sy({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(K.dim(`
|
|
541
|
+
bye`)),process.exit(0)});;){let g;try{g=(await a.question(K.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(K.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${Tg().slice(0,12)}`,console.log(K.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let p=await Zn(o);for(let w of p){let y=w.id===n?K.green("\u25CF"):K.dim("\u25CB");console.log(` ${y} @${w.id} ${K.dim(w.tier)} ${w.model??""}`)}}catch(p){console.error(K.red(` failed to list agents: ${p?.message||p}`))}continue}if(g.startsWith("/agent ")){let p=g.slice(7).replace(/^@/,"").trim();if(!p){console.log(K.red(" usage: /agent <id>"));continue}try{if(!(await Zn(o)).find(y=>y.id===p)){console.log(K.red(` unknown agent: @${p}`));continue}n=p,console.log(K.dim(` now talking to @${n}`))}catch(w){console.error(K.red(` failed to switch agent: ${w?.message||w}`))}continue}if(g.startsWith("/")){console.log(K.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(K.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=Ey({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),f=Ay(n);try{let p=await zc(o,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(K.dim(" bye"));return}}});function Ay(e){let t=!1,o=!0,n=!1,s=new Set,i=()=>{t||(process.stdout.write(`${K.green(`@${e}`)}
|
|
542
542
|
`),t=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)o&&a!==`
|
|
543
543
|
`&&(process.stdout.write(" "),o=!1),process.stdout.write(a),a===`
|
|
544
544
|
`&&(o=!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),o||(process.stdout.write(`
|
|
@@ -559,7 +559,7 @@ ${e.persona}
|
|
|
559
559
|
`),Hs(Fe(e.dir,"demo-script.json"),JSON.stringify(e.script,null,2));let s=t.filter(r=>r.id!==e.id).map(r=>({name:r.name,url:`http://127.0.0.1:${r.port}`,token:o})),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}};Hs(Fe(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function $r(e,t,o){let n=Date.now();for(;Date.now()-n<o;){try{if(await t())return}catch{}await new Promise(s=>setTimeout(s,500))}throw new Error(`Timed out waiting for ${e} (${Math.round(o/1e3)}s)`)}async function kr(e,t,o){let n=await fetch(`http://127.0.0.1:${e}${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),s=await n.json().catch(()=>({}));if(!n.ok||s.error)throw new Error(s.error||`${t} HTTP ${n.status}`);return s}function Js(e,t,o){console.log(),console.log(o(` ${e}`)),console.log(` ${t.split(`
|
|
560
560
|
`).join(`
|
|
561
561
|
`)}`)}var Pg=new Py().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 t=parseInt(e.basePort,10),o=Uy(process.cwd(),".agentx-demo"),n=By(o,t),s=Fe(o,"mesh-token"),i=!!e.reuse&&Bs(s)&&Bs(Fe(n[0].dir,"agentx.json")),r=i?Ly(s,"utf8").trim():qy(24).toString("hex"),a=e.keep||e.reuse,c=[],l=process.argv[1];if((!l||!Bs(l))&&(console.error(de.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!i){if(Bs(o))for(let f of Fy(o))Rg(Fe(o,f),{recursive:!0,force:!0});for(let f of n)Jy(f,n,r);Hs(s,r+`
|
|
562
|
-
`,{mode:384})}console.log(),console.log(de.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(de.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(de.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{Rg(o,{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,u.INTENT_LEDGER_MODE||="shadow";try{for(let
|
|
562
|
+
`,{mode:384})}console.log(),console.log(de.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(de.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(de.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{Rg(o,{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,u.INTENT_LEDGER_MODE||="shadow";try{for(let y of n){let $=_g(Fe(y.dir,"daemon.log"),"a"),b=br(process.execPath,[l,"daemon","start","-c",Fe(y.dir,"agentx.json")],{cwd:y.dir,env:{...u,MESH_TOKEN:r,AGENTX_DEMO_SCRIPT:Fe(y.dir,"demo-script.json")},stdio:["ignore",$,$]});c.push(b),console.log(de.dim(` \u25B8 ${y.name} starting on 127.0.0.1:${y.port} (log: ${Fe(y.dir,"daemon.log")})`))}for(let y of n)await $r(`${y.name} /health`,async()=>(await fetch(`http://127.0.0.1:${y.port}/health`)).ok,3e4);console.log(de.green(" \u2713 three daemons up"));let f=n[0].port+10;{let y=_g(Fe(n[0].dir,"board.log"),"a"),$=br(process.execPath,[l,"board","serve","--bind",e.bind],{cwd:n[0].dir,env:{...u,MESH_TOKEN:r},stdio:["ignore",y,y]});c.push($)}await $r("dashboard /live",async()=>(await fetch(`http://127.0.0.1:${f}/live`)).ok,3e4),console.log(de.green(" \u2713 dashboard up")),await $r("mesh discovery (laptop sees both peers)",async()=>((await(await fetch(`http://127.0.0.1:${n[0].port}/health`)).json()).mesh||[]).filter(v=>v.healthy&&v.skills?.length).length>=2,3e4),console.log(de.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: ${de.cyan(p)} (all three nodes via the mesh)`),console.log(de.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{br(y,[p],{stdio:"ignore",detached:!0}).unref()}catch{}}let w=async()=>{console.log(),console.log(de.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),Js("You \u2192 @cx (laptop-paris)",Dg,de.cyan);let y=await kr(n[0].port,"/task",{agent:"cx",message:Dg});Js("@cx (laptop-paris)",y.content||"(no content)",de.green),console.log(),console.log(de.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let $=await kr(n[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:Wy}),b=typeof $.messageId=="string"?$.messageId:$.content||"(no reply)";Js("@builder (vps-nyc)",b,de.yellow);let v=await kr(n[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${b}`});Js("@cx (laptop-paris)",v.content||"(no content)",de.green),console.log(),console.log(de.dim(` Inspect the run: ${p} \xB7 ledger rows on each node record every dispatch`)),console.log(de.dim(` Worth your time? A star helps others find it: ${de.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(i?console.log(de.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await w(),e.once){console.log(),console.log(de.dim(" --once: shutting down.")),d(0);return}console.log(),console.log(de.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(de.red(` Replay failed: ${y.message}`)))}),process.stdin.resume()}catch(f){console.error(),console.error(de.red(` Demo failed: ${f.message}`)),console.error(de.dim(` Node logs: ${n.map(p=>Fe(p.dir,"daemon.log")).join(", ")}`)),d(1)}});import{Command as Hy}from"commander";import{randomUUID as Gy}from"crypto";import{readFileSync as zy}from"fs";import{resolve as Yy}from"path";ae();var Lg=new Hy().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,t)=>{let o=(e??zy(0,"utf8")).trim();o||Mg("no task given (pass it as an argument or on stdin)");let n=I(t.config?Yy(t.config):void 0),s=n.agents[t.agent];s||Mg(`unknown agent "${t.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`);let i=(...l)=>console.error("[agentx exec]",...l);if(t.setupWorkspace){let l=n.node.bind.split(":")[1]||"19900";zr(t.agent,s,l,i)}let r=new ga(n,i),a=Date.now(),c=await r.execute({agentId:t.agent,message:o,model:t.model,timeoutMinutes:t.timeout?Number(t.timeout):void 0,context:{channel:"exec",chatId:`exec-${Gy()}`,sender:"cli"}});t.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})+`
|
|
563
563
|
`):c.error?console.error(c.error):process.stdout.write(c.content+`
|
|
564
564
|
`),process.exit(c.error?1:0)});function Mg(e){console.error(`agentx exec: ${e}`),process.exit(1)}ae();import{Command as Vy}from"commander";import Ce from"chalk";var Wt=new Vy().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Wt.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 o=(await In("/whatsapp/chats")).chats??[];if(e.group&&(o=o.filter(n=>n.isGroup)),e.dm&&(o=o.filter(n=>!n.isGroup)),e.format==="json"){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(Ce.dim(" no chats cached yet"));return}console.log(),console.log(Ce.bold(` ${o.length} chat${o.length===1?"":"s"}`)),console.log();for(let n of o){let s=n.isGroup?Ce.cyan("group"):Ce.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Ce.dim(n.jid.padEnd(40))} ${Ce.dim(i)}`)}console.log()}catch(t){Yo(t)}});Wt.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 o=(await In("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(Ce.dim(" no contacts cached yet"));return}console.log(),console.log(Ce.bold(` ${o.length} contact${o.length===1?"":"s"}`)),console.log();for(let n of o){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} ${Ce.dim(i)} ${Ce.dim(n.jid)}`)}console.log()}catch(t){Yo(t)}});Wt.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 t={dryRun:!!e.dryRun,force:!!e.force};e.agent&&(t.agent=e.agent);let o=await xr("/whatsapp/ingest",t);vr(o,!!e.dryRun)}catch(t){Yo(t)}});Wt.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,t)=>{try{let o={dryRun:!!t.dryRun,force:!0,onlyJid:e,onlyKind:"contact"};t.agent&&(o.agent=t.agent);let n=await xr("/whatsapp/ingest",o);vr(n,!!t.dryRun)}catch(o){Yo(o)}});Wt.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,t)=>{try{let o={dryRun:!!t.dryRun,force:!0,onlyJid:e};t.agent&&(o.agent=t.agent),t.messages&&(o.forceMode="messages");let n=await xr("/whatsapp/ingest",o);vr(n,!!t.dryRun)}catch(o){Yo(o)}});Wt.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await In("/whatsapp/state"),t=await In("/whatsapp/chats"),o=await In("/whatsapp/contacts");console.log(),console.log(Ce.bold(" WhatsApp status")),console.log(),console.log(` connection: ${e.connection||"\u2014"}`),console.log(` cached chats: ${t.chats?.length??0}`),console.log(` cached contacts: ${o.contacts?.length??0}`),console.log()}catch(e){Yo(e)}});function vr(e,t){if(console.log(),console.log(Ce.bold(t?" 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(Ce.yellow(` errors: ${e.errors.length}`));for(let o of e.errors.slice(0,5))console.log(Ce.yellow(` - [${o.kind}] ${o.jid}: ${o.message}`))}if(t&&e.dryRunEntries?.length){console.log(),console.log(Ce.dim(" would-be entries:"));for(let o of e.dryRunEntries.slice(0,10))console.log(Ce.dim(` - ${o.id} (${o.source}, ${o.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Ce.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function Fg(){try{let e=I(),[t,o]=e.node.bind.split(":");return`http://${t||"127.0.0.1"}:${o||"19900"}`}catch{return"http://127.0.0.1:19900"}}async function In(e){let t=await fetch(`${Fg()}${e}`,{signal:AbortSignal.timeout(1e4)}),o=await t.json().catch(()=>({}));if(!t.ok)throw new Error(o.error||`HTTP ${t.status}`);return o}async function xr(e,t){let o=await fetch(`${Fg()}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(6e5)}),n=await o.json().catch(()=>({}));if(!o.ok)throw new Error(n.error||`HTTP ${o.status}`);return n}function Yo(e){console.error(Ce.red(` ${e.message||e}`)),process.exit(1)}ae();import{Command as Ky}from"commander";import ge from"chalk";import{existsSync as Xy,mkdirSync as Ug,writeFileSync as Cn}from"fs";import{join as Vo,resolve as Qy}from"path";var Nn=new Ky().name("plugin").description("manage agentx plugins (Move B)");Nn.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let t=I().plugins??[];if(console.log(),t.length===0){console.log(ge.dim(" No plugins configured.")),console.log(ge.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(ge.bold(` Plugins configured: ${t.length}`)),console.log();for(let o of t)console.log(` ${ge.cyan(o)}`);console.log(),console.log(ge.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(ge.red(` ${e.message}`)),process.exitCode=1}});Nn.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,t)=>{/^(@[a-z0-9-]+\/)?[a-z0-9][a-z0-9._-]*$/i.test(e)||(console.log(ge.red(` invalid package name "${e}". Use lowercase letters, digits, hyphens; optional @scope/ prefix.`)),process.exit(1));let o=e.startsWith("@")?e.split("/")[1]:e,n=Qy(t.cwd,o);Xy(n)&&!t.force&&(console.log(ge.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),Ug(n,{recursive:!0}),Ug(Vo(n,"src"),{recursive:!0});let s=t.description||`AgentX plugin: ${e}`;Cn(Vo(n,"package.json"),ow(e,s)),Cn(Vo(n,"tsconfig.json"),nw()),Cn(Vo(n,"src/index.ts"),sw(e)),Cn(Vo(n,"README.md"),iw(e,s)),Cn(Vo(n,".gitignore"),rw()),console.log(),console.log(ge.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(ge.bold(" Next steps:")),console.log(ge.dim(` cd ${o}`)),console.log(ge.dim(" pnpm install")),console.log(ge.dim(" pnpm build")),console.log(ge.dim(" pnpm link --global # for local testing")),console.log(ge.dim(" # then in your agentx project:")),console.log(ge.dim(` pnpm link --global ${e}`)),console.log(ge.dim(` agentx config set plugins[0] "${e}"`)),console.log(ge.dim(" agentx plugin doctor")),console.log()});Nn.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let t=I().plugins??[];if(console.log(),t.length===0){console.log(ge.dim(" No plugins configured. Nothing to check.")),console.log();return}let o=0;for(let n of t){let s=await Zy(n);s.kind==="ok"?console.log(` ${ge.green("\u2713")} ${ge.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(o++,console.log(` ${ge.red("\u2717")} ${ge.cyan(n)} \u2014 ${s.reason}`))}console.log(),o>0&&(console.log(ge.red(` ${o}/${t.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(ge.red(` ${e.message}`)),process.exitCode=1}});async function Zy(e){let t;try{t=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let o=ew(t);if(!tw(o))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=ec.safeParse(o.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 ew(e){if(e==null||typeof e!="object")return e;let t=e;if(t.default&&typeof t.default=="object"){let o=t.default;if(o.manifest&&typeof o.setup=="function")return o;if(o.default&&typeof o.default=="object"){let n=o.default;if(n.manifest&&typeof n.setup=="function")return n}}return t.manifest&&typeof t.setup=="function"?t:t.default??t}function tw(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function ow(e,t){return JSON.stringify({name:e,version:"0.1.0",description:t,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)+`
|
|
565
565
|
`}function nw(){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)+`
|
|
@@ -630,7 +630,7 @@ Restart the daemon to activate.
|
|
|
630
630
|
dist/
|
|
631
631
|
*.log
|
|
632
632
|
.env
|
|
633
|
-
`}import{Command as aw}from"commander";import Ne from"chalk";import{writeFileSync as cw,mkdirSync as lw,existsSync as Gs,readFileSync as qg,appendFileSync as Wg}from"fs";import{resolve as Ko,dirname as Hg}from"path";import{homedir as Er}from"os";var Gg=new aw().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:t}=await import("./program-
|
|
633
|
+
`}import{Command as aw}from"commander";import Ne from"chalk";import{writeFileSync as cw,mkdirSync as lw,existsSync as Gs,readFileSync as qg,appendFileSync as Wg}from"fs";import{resolve as Ko,dirname as Hg}from"path";import{homedir as Er}from"os";var Gg=new aw().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:t}=await import("./program-GUBHJFZS.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=mw(o);break;case"bash":s=yw(o);break;case"fish":s=ww(o);break;default:console.error(Ne.red(`unsupported shell: ${n}`)),console.error(Ne.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?Ko(String(e.output)):dw(n);lw(Hg(i),{recursive:!0}),cw(i,s),console.log(Ne.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),gw(n,i,!!e.yes)});function dw(e){let t=Er();switch(e){case"zsh":return Ko(t,".zsh","completions","_agentx");case"bash":return Ko(t,".bash_completion.d","agentx.bash");case"fish":return Ko(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function gw(e,t,o){if(e==="zsh"){let n=Ko(Er(),".zshrc"),s=Hg(t),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Gs(n)?qg(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Ne.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&Gs(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Wg(n,g.join(`
|
|
634
634
|
`)+`
|
|
635
635
|
`),console.log(Ne.green("\u2713 Patched ~/.zshrc")),console.log(Ne.dim("Reload your shell: exec zsh"));return}console.log(Ne.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Ne.cyan(` ${i}`)),l&&console.log(Ne.cyan(` ${r}`)),console.log(),console.log(Ne.dim("Then reload: exec zsh")),console.log(Ne.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Ko(Er(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((Gs(n)?qg(n,"utf-8"):"").includes(t)){console.log(Ne.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&Gs(n)){Wg(n,`
|
|
636
636
|
# agentx completion
|
|
@@ -646,4 +646,4 @@ ${bw({...t,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
|
|
|
646
646
|
${o.url}`)}catch(t){console.error(Qo.red(` ${t.message}`)),process.exitCode=1}});_n.command("draft <file>").description("turn a draft JSON file ({category, title, fields}) into a pre-filled issue form link; '-' reads stdin").requiredOption("--model <model>","the model that wrote the draft").option("--models <pathOrUrl>","model list to read",jr).action(async(e,t)=>{try{let o=await Ir(t.models);if(!Or(t.model,o)){console.log(Tr(t.model,o)),process.exitCode=1;return}let n=e==="-"?await vw():await kw(e,"utf8"),s=JSON.parse(n),{version:i}=await Un(),r=Kg({...s,fields:s.fields??{}},{model:t.model,version:i??"unknown"});console.log(r)}catch(o){console.error(Qo.red(` ${o.message}`)),process.exitCode=1}});async function vw(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function Sj(){let e=await Un(),t=new xw().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");t.hook("preAction",(o,n)=>{let s=Wc(n);Bc(s)&&qc("cli",s)});for(let o of[yl,ul,Mo,vo,Eo,Qe,Lc,Yt,cs,wt,Mt,Pt,as,Ag,Rt,Ml,Gl,bn,nd,ad,cd,Ed,Td,Id,Ro,Sn,Cg,mn,Ot,Gg,_n])t.addCommand(o);for(let o of Qg)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=Qg.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Sw(o,74," "),""].join(`
|
|
647
647
|
`)}),t}var Qg=[Z,Uo,qt,it,un,_o,Ge,$t,Lt,no,Jo,Ho,Ct,Be,To,As,xg,Sg,ht,Vt,Yc,Kt,Nn,Ti,Ut,jo,Ii,Ls,pt,Wt,Pg,Lg,Ig];function Sw(e,t,o){let n=[],s="";for(let i of e)s&&s.length+i.length+2>t&&(n.push(o+s),s=""),s+=(s?", ":"")+i;return s&&n.push(o+s),n.join(`
|
|
648
648
|
`)}export{Sj as a};
|
|
649
|
-
//# sourceMappingURL=chunk-
|
|
649
|
+
//# sourceMappingURL=chunk-X4FD5OBK.js.map
|