agentix-cli 0.75.0 → 0.75.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/apps/mac-voice/Sources/AgentXVoice/PillMenu.swift +16 -0
- package/apps/mac-voice/Sources/AgentXVoice/StatusMenu.swift +3 -3
- package/dist/{agent-UOOL6R4V.js → agent-B46X7Y6V.js} +2 -2
- package/dist/{board-dashboard-CDBPGUU3.js → board-dashboard-W64VXH6Y.js} +2 -2
- package/dist/{chunk-OEUII2QP.js → chunk-2HMI5PJG.js} +2 -2
- package/dist/{chunk-5B5J3WVW.js → chunk-55RM7V4N.js} +2 -2
- package/dist/{chunk-SKIDVXWG.js → chunk-663BLK67.js} +2 -2
- package/dist/{chunk-APYG4RB3.js → chunk-6CCJMHBA.js} +2 -2
- package/dist/{chunk-YZVX4RDY.js → chunk-7ZO2UZRI.js} +11 -11
- package/dist/{chunk-L3MEAKL7.js → chunk-CAVAMWI5.js} +2 -2
- package/dist/{chunk-BAPRRPNU.js → chunk-F2RIMHW5.js} +2 -2
- package/dist/{chunk-6HPJKD3X.js → chunk-KHEI4VNM.js} +13 -13
- package/dist/{chunk-6HPJKD3X.js.map → chunk-KHEI4VNM.js.map} +1 -1
- package/dist/{chunk-LWPRFAQX.js → chunk-KIXYU2DD.js} +4 -4
- package/dist/{chunk-KEJOBB5E.js → chunk-NWL5KPBJ.js} +2 -2
- package/dist/chunk-PBUJBWOF.js +152 -0
- package/dist/chunk-PBUJBWOF.js.map +1 -0
- package/dist/{chunk-WC4TPXD3.js → chunk-Q2FFZX7Y.js} +2 -2
- package/dist/{chunk-ISBM2C3D.js → chunk-RGTHA2EI.js} +2 -2
- package/dist/{chunk-UBGQ7AOG.js → chunk-TS4JCBSP.js} +2 -2
- package/dist/{chunk-66VSATH3.js → chunk-UJ5JLS6Z.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.js +1 -1
- package/dist/{program-EHCDAWI7.js → program-3DBXC6DX.js} +2 -2
- package/dist/{promote-KSYTHPYB.js → promote-PMMUU4G2.js} +2 -2
- package/dist/{query-GRLLX7RG.js → query-CB6FV6JU.js} +2 -2
- package/dist/{registry-WJRF3D5H.js → registry-A2LPURNS.js} +2 -2
- package/dist/{request-planner-G2NJIXQY.js → request-planner-44WOTYCY.js} +2 -2
- package/dist/{review-candidates-F5QKVUQ4.js → review-candidates-BZLS37MN.js} +2 -2
- package/dist/{routing-XIDQWGKT.js → routing-CPLPRA2E.js} +2 -2
- package/dist/{seat-DNI7G7B2.js → seat-CBAZAYGY.js} +2 -2
- package/dist/{select-L45K2452.js → select-4CW3CXBU.js} +2 -2
- package/dist/wiki-4LKOLCP4.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-DIHLL45I.js +0 -152
- package/dist/chunk-DIHLL45I.js.map +0 -1
- package/dist/wiki-WWVSDXSX.js +0 -2
- /package/dist/{agent-UOOL6R4V.js.map → agent-B46X7Y6V.js.map} +0 -0
- /package/dist/{board-dashboard-CDBPGUU3.js.map → board-dashboard-W64VXH6Y.js.map} +0 -0
- /package/dist/{chunk-OEUII2QP.js.map → chunk-2HMI5PJG.js.map} +0 -0
- /package/dist/{chunk-5B5J3WVW.js.map → chunk-55RM7V4N.js.map} +0 -0
- /package/dist/{chunk-SKIDVXWG.js.map → chunk-663BLK67.js.map} +0 -0
- /package/dist/{chunk-APYG4RB3.js.map → chunk-6CCJMHBA.js.map} +0 -0
- /package/dist/{chunk-YZVX4RDY.js.map → chunk-7ZO2UZRI.js.map} +0 -0
- /package/dist/{chunk-L3MEAKL7.js.map → chunk-CAVAMWI5.js.map} +0 -0
- /package/dist/{chunk-BAPRRPNU.js.map → chunk-F2RIMHW5.js.map} +0 -0
- /package/dist/{chunk-LWPRFAQX.js.map → chunk-KIXYU2DD.js.map} +0 -0
- /package/dist/{chunk-KEJOBB5E.js.map → chunk-NWL5KPBJ.js.map} +0 -0
- /package/dist/{chunk-WC4TPXD3.js.map → chunk-Q2FFZX7Y.js.map} +0 -0
- /package/dist/{chunk-ISBM2C3D.js.map → chunk-RGTHA2EI.js.map} +0 -0
- /package/dist/{chunk-UBGQ7AOG.js.map → chunk-TS4JCBSP.js.map} +0 -0
- /package/dist/{chunk-66VSATH3.js.map → chunk-UJ5JLS6Z.js.map} +0 -0
- /package/dist/{program-EHCDAWI7.js.map → program-3DBXC6DX.js.map} +0 -0
- /package/dist/{promote-KSYTHPYB.js.map → promote-PMMUU4G2.js.map} +0 -0
- /package/dist/{query-GRLLX7RG.js.map → query-CB6FV6JU.js.map} +0 -0
- /package/dist/{registry-WJRF3D5H.js.map → registry-A2LPURNS.js.map} +0 -0
- /package/dist/{request-planner-G2NJIXQY.js.map → request-planner-44WOTYCY.js.map} +0 -0
- /package/dist/{review-candidates-F5QKVUQ4.js.map → review-candidates-BZLS37MN.js.map} +0 -0
- /package/dist/{routing-XIDQWGKT.js.map → routing-CPLPRA2E.js.map} +0 -0
- /package/dist/{seat-DNI7G7B2.js.map → seat-CBAZAYGY.js.map} +0 -0
- /package/dist/{select-L45K2452.js.map → select-4CW3CXBU.js.map} +0 -0
- /package/dist/{wiki-WWVSDXSX.js.map → wiki-4LKOLCP4.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as ml,b as ms,g as pl}from"./chunk-JGEHN4VE.js";import{a as nl,c as sl}from"./chunk-GZAGG3ES.js";import{a as Qe,b as Zc,f as el,g as tl,h as ol,i as gs,j as il,k as rl,l as Oi,m as dl,o as gl}from"./chunk-
|
|
1
|
+
import{a as ml,b as ms,g as pl}from"./chunk-JGEHN4VE.js";import{a as nl,c as sl}from"./chunk-GZAGG3ES.js";import{a as Qe,b as Zc,f as el,g as tl,h as ol,i as gs,j as il,k as rl,l as Oi,m as dl,o as gl}from"./chunk-TS4JCBSP.js";import{a as al,c as cl,d as ll}from"./chunk-Z3IP66SL.js";import{a as fi,b as Ca}from"./chunk-RKPAVWXF.js";import{c as ba}from"./chunk-SZDACK6O.js";import{a as vo}from"./chunk-GV7S5BAX.js";import{e as $a}from"./chunk-GSX4NK2N.js";import{$ as Vc,A as Sc,B as wi,C as Ec,D as Ac,E as Tc,F as jc,G as Oc,H as Ic,I as Mc,J as Lc,K as Fc,L as So,M as as,N as xi,O as Uc,P as qc,Q as Wc,R as Bc,S as Eo,T as Ao,U as Jc,V as Hc,W as _e,X as cs,Y as hn,Z as Si,_ as Gc,a as Oa,aa as Ti,b as Ia,ba as Xc,c as mn,ca as ls,d as Fa,da as To,e as Ua,ea as ds,fa as ji,ga as Qc,k as Zn,l as Ja,m as pn,n as es,o as za,p as Ya,q as rc,r as ac,s as ss,t as yi,u as mc,v as yc,w as bc,x as kc,y as vc,z as xc}from"./chunk-KIXYU2DD.js";import{H as fc,I as hc,Na as zc,Oa as Ei,Pa as Yc,Qa as Ai,V as un,Y as $i,Z as is,_ as Cc,cb as mt,eb as Kc,fa as It,ga as Nc,ha as bi,ja as ki,la as Rc,ma as _c,na as fn,p as Ot,ra as rs,t as pc,ua as Dc,va as Pc,w as uc,wa as vi}from"./chunk-663BLK67.js";import{a as qa,d as Wa,e as Ba}from"./chunk-RGTHA2EI.js";import{a as ts,b as os,c as Va,d as Ka,e as Xa,g as Qa,h as Za,j as ec,k as tc,l as oc,m as nc,p as ns,r as sc,s as ic}from"./chunk-BYJ3A55Y.js";import{a as Ha,p as Ga}from"./chunk-Q2FFZX7Y.js";import{a as cc,b as lc,c as dc,d as gc}from"./chunk-2D3RYIDU.js";import{a as wc,b as $c}from"./chunk-EKJG63EJ.js";import{C as jt,I as Ta,T as ja,g as ma,p as pa,w as mi,x as ya}from"./chunk-PBUJBWOF.js";import{b as wo,g as bo,h as Xn,i as Qn,j as ko,k as wa,l as Vt,m as gn}from"./chunk-2HMI5PJG.js";import{e as Sa,f as ui,k as Ea}from"./chunk-WP6KLXTP.js";import{a as Vn}from"./chunk-N6EWZGIX.js";import{b as $o}from"./chunk-DP7RTNDM.js";import{a as hi,e as Na,f as Ra,h as _a,i as Da,k as Pa,l as Ma,m as La}from"./chunk-S5JGQKON.js";import{f as ka,g as va,h as pi}from"./chunk-76Z4VHDX.js";import{a as fa,k as xa}from"./chunk-PUU2ESI2.js";import{b as pe,c as Oe,d as xo,e as Aa}from"./chunk-IR2Q63IV.js";import{a as di}from"./chunk-CAVAMWI5.js";import{a as gi,b as ua}from"./chunk-GQ76J72O.js";import{j as ha}from"./chunk-X5C5W3E4.js";import{h as ga}from"./chunk-DWADWDMU.js";import{g as Tt,i as Kn}from"./chunk-NWL5KPBJ.js";import{b as yo,d as da}from"./chunk-2GIDVZ4H.js";import{a as li,b as Yr,c as Nm,d as zn,e as Vr,f as sa,g as Dm,h as ia,i as Pm,m as ho,n as aa,o as ca,s as la,v as gt,w as dn}from"./chunk-KHEI4VNM.js";import{a as ra,b as Mm}from"./chunk-FX3D7YON.js";import{a as $t,b as fo,e as ta,f as ln}from"./chunk-72SZI2UW.js";import{a as wt,b as Cm}from"./chunk-7I7IEX4S.js";import{A as I,B as Yn,D as ne,m as Kr,n as Xr,p as Qr,q as Rm,y as Zr,z as ea}from"./chunk-CXZ4YDHJ.js";import{g as oa,k as na,l as _m}from"./chunk-RGDKHYY2.js";import{Command as Lm}from"commander";var ul=new Lm().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 Ua({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()});ne();import{Command as Fm}from"commander";import{execFileSync as et}from"node:child_process";import{cpSync as fl,existsSync as Ni,mkdirSync as Ii,mkdtempSync as Um,readdirSync as qm,rmSync as hl,writeFileSync as yl}from"node:fs";import{dirname as wl,join as Pe}from"node:path";import{homedir as ps,release as Wm,tmpdir as Bm}from"node:os";import{setTimeout as Jm}from"node:timers/promises";function us(){let e=Va(process.platform,process.arch,Wm());if(e)throw new Error(e)}function fs(){let e=Pe(ps(),"Library/LaunchAgents"),t=[];try{t=qm(e).filter(Qa)}catch{}let o=t.flatMap(n=>{let s=Pe(e,n);try{return[{file:s,plist:et("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Za(e,o)}function yn(e){return`gui/${process.getuid()}/${e.label}`}async function Ci(e){try{et("launchctl",["bootout",yn(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{et("launchctl",["print",yn(e)],{stdio:"pipe"})}catch{return}await Jm(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function $l(e){if(!Ni(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{et("launchctl",["print",yn(e)],{stdio:"pipe"})}catch{t=!1}t||et("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),et("launchctl",["kickstart",yn(e)],{stdio:"pipe"})}function Hm(){let e=nc();if(e&&Ni(Pe(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 jo=new Fm("desktop").description("install and control the macOS desktop assistant");jo.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=>{us();let t=I(),o=Ka(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=Hm(),r=Pe(ps(),"Applications"),{keep:a,remove:c}=fs();if(console.log(`Desktop assistant \u2192 ${Pe(r,ts)}
|
|
2
2
|
Computer-use helper \u2192 ${Pe(r,os)}
|
|
3
3
|
Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
|
|
4
4
|
Daemon \u2192 ${s}
|
|
@@ -27,7 +27,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
27
27
|
`))});function Ep(e){let t=Math.round(el/6e4),o=[` Pairing code: ${Ee.bold.cyan(tl(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 Ap(){let e;try{e=JSON.parse(Fl("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 Tp=new Set(["/app","/api/app"]);function jp(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&&!Tp.has(g)&&n.push(`${i}${a}`)}return n}function Op(){try{return JSON.parse(Fl("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function Li(){try{return I().dashboard.port||4202}catch{return 4202}}ne();import{Command as ut}from"commander";import y from"chalk";import De from"prompts";import{readFileSync as Nt,writeFileSync as No,existsSync as he,mkdirSync as pt,cpSync as Fi,readdirSync as qi}from"fs";import{resolve as H,join as Ct,dirname as Ip}from"path";import{fileURLToPath as Cp}from"url";function le(){let e=H(process.cwd(),"agentx.json");if(!he(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Nt(e,"utf-8"))}function qe(e){return pe(t=>{for(let o of Object.keys(t))delete t[o];Object.assign(t,e)}).then(t=>{if(!t.success){console.error(y.red(` Config save failed: ${t.error}`));return}t.reloaded?console.error(y.dim(" (daemon hot-reloaded)")):t.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(t.reloadSkipped)&&console.error(y.dim(` (daemon reload skipped: ${t.reloadSkipped})`))})}var Qt=new ut().name("agent").description("manage agents \u2014 add, list, remove");Qt.command("list").alias("ls").description("list configured agents").action(()=>{let e=le();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=o.mentions?.join(", ")||"";console.log(` ${y.cyan(t)} \u2014 ${o.name} (${o.tier})`),console.log(y.dim(` workspace: ${o.workspace}`)),n&&console.log(y.dim(` mentions: ${n}`))}console.log()});Qt.command("add").description("add a new agent interactively").action(async()=>{let e=le(),t=await De([{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:Ct(t.workspace,t.id);pt(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(y.dim(` ${l.join(" ")}`))}),r=H(process.cwd(),"src/wiki/SKILL.md"),a=H(Ip(Cp(import.meta.url)),"../wiki/SKILL.md"),c=he(r)?r:a;he(c)&&(pt(H(o,".claude/skills/wiki"),{recursive:!0}),Fi(c,H(o,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[t.id]=n,await qe(e),console.log(y.green(`
|
|
28
28
|
Agent "${t.id}" added`)),console.log(y.dim(` Workspace: ${o}`)),console.log(y.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});Qt.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let t=le();if(!t.agents?.[e]){console.log(y.red(` Agent "${e}" not found`));return}delete t.agents[e],await qe(t),console.log(y.green(` Agent "${e}" removed from config (workspace preserved)`))});Qt.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=le(),n=o.agents?.[e];if(n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1)),t.show){console.log(),console.log(y.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):y.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":y.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||y.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(y.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(y.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(y.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(y.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(y.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await qe(o),console.log(y.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(y.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var vn=new ut().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");vn.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,t)=>{let n=le().agents?.[e];n||(console.log(y.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(y.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()});vn.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=le();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-A23CU2XT.js"),i=String(t.kind||"").trim();!i&&n&&(i=((await De({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 De({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 De({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 De({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 De({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 De({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,...h]=f.split("=");p&&(g[p.trim()]=h.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 qe(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`))});vn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,t)=>{let o=le(),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 qe(o),console.log(y.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});vn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,t)=>{let n=le().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)});Qt.addCommand(vn);var ks=new ut().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");ks.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=le();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()});ks.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=le(),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 De({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 De([{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 qe(e),console.log(y.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await De([{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 De([{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 qe(e),pt(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 De([{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 De([{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 qe(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 Ro=new ut().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Ro.command("list").alias("ls").description("list cron jobs").action(()=>{let e=le();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()});Ro.command("add").description("add a cron job").action(async()=>{let e=le(),t=Object.keys(e.agents||{}),o=await De([{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 qe(e),console.log(y.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});Ro.command("enable <id>").description("enable a cron job").action(async e=>{let t=le();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 qe(t),console.log(y.green(` Cron "${e}" enabled`))});Ro.command("disable <id>").description("disable a cron job").action(async e=>{let t=le();if(!t.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await qe(t),console.log(y.green(` Cron "${e}" disabled`))});var Zt=new ut().name("mesh").description("manage mesh peers \u2014 add, list, remove");Zt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=le();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()});Zt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=le(),t=await De([{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 qe(e),console.log(y.green(` Peer "${t.name}" added`)),console.log()}});Zt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=le();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await qe(t),console.log(y.green(` Peer "${e}" removed`)))});Zt.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=le();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 qe(t),console.log(y.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log(y.dim(" Restart the daemon for the new cadence to take effect."))});Zt.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 eo=new ut().name("skill").description("manage skills \u2014 add to agent(s), list");eo.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=le(),n=H(e);if(!he(n)){console.log(y.red(` Skill not found: ${n}`));return}let s=he(Ct(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 De({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);pt(c,{recursive:!0}),he(Ct(n,"SKILL.md"))?Fi(n,c,{recursive:!0}):n.endsWith(".md")&&Fi(n,Ct(c,"SKILL.md")),console.log(y.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});eo.command("list").alias("ls").description("list skills per agent").action(()=>{let e=le();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=H(o.workspace,".claude/skills"),s=he(n)?qi(n).filter(i=>!i.startsWith(".")):[];console.log(` ${y.cyan(t)}: ${s.length?s.join(", "):y.dim("(none)")}`)}console.log()});eo.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=>he(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=Nt(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,h=0;for(let[k,b]of d){let $=b.workspace;if(!$||!he($)){console.log(` ${y.yellow("\u2717")} ${k.padEnd(22)} ${y.dim("(workspace missing: "+($||"undefined")+")")}`),h++;continue}let E=H($,".claude/skills",e),S=H(E,"SKILL.md");if(!he(S)){if(!t.allWorkspaces){console.log(` ${y.dim("\xB7")} ${k.padEnd(22)} ${y.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),h++;continue}t.dryRun||(pt(E,{recursive:!0}),No(S,r)),console.log(` ${y.green("+")} ${k.padEnd(22)} ${y.dim("\u2192 seeded v"+c)}`),u++;continue}let x=Nt(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||No(S,r),console.log(` ${y.yellow("\u21BB")} ${k.padEnd(22)} ${y.dim(`v${R} \u2192 v${c}`)}`),f++}console.log();let w=t.dryRun?"would":"did";console.log(y.dim(` Summary: ${w} seed ${u}, ${w} update ${f}, ${p} already current, ${h} skipped.`)),t.dryRun&&(u>0||f>0)&&console.log(y.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});eo.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-YFVSSYSL.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=le().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=le();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 h of f.reasons)console.log(` ${y.dim("\xB7")} ${h}`)}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)});eo.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=le(),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-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-L45K2452.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(`
|
|
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()});vn.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=le();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-A23CU2XT.js"),i=String(t.kind||"").trim();!i&&n&&(i=((await De({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 De({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 De({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 De({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 De({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 De({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,...h]=f.split("=");p&&(g[p.trim()]=h.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 qe(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`))});vn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,t)=>{let o=le(),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 qe(o),console.log(y.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});vn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,t)=>{let n=le().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)});Qt.addCommand(vn);var ks=new ut().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");ks.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=le();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()});ks.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=le(),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 De({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 De([{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 qe(e),console.log(y.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await De([{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 De([{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 qe(e),pt(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 De([{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 De([{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 qe(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 Ro=new ut().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Ro.command("list").alias("ls").description("list cron jobs").action(()=>{let e=le();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()});Ro.command("add").description("add a cron job").action(async()=>{let e=le(),t=Object.keys(e.agents||{}),o=await De([{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 qe(e),console.log(y.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});Ro.command("enable <id>").description("enable a cron job").action(async e=>{let t=le();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 qe(t),console.log(y.green(` Cron "${e}" enabled`))});Ro.command("disable <id>").description("disable a cron job").action(async e=>{let t=le();if(!t.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await qe(t),console.log(y.green(` Cron "${e}" disabled`))});var Zt=new ut().name("mesh").description("manage mesh peers \u2014 add, list, remove");Zt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=le();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()});Zt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=le(),t=await De([{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 qe(e),console.log(y.green(` Peer "${t.name}" added`)),console.log()}});Zt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=le();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await qe(t),console.log(y.green(` Peer "${e}" removed`)))});Zt.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=le();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 qe(t),console.log(y.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log(y.dim(" Restart the daemon for the new cadence to take effect."))});Zt.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 eo=new ut().name("skill").description("manage skills \u2014 add to agent(s), list");eo.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=le(),n=H(e);if(!he(n)){console.log(y.red(` Skill not found: ${n}`));return}let s=he(Ct(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 De({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);pt(c,{recursive:!0}),he(Ct(n,"SKILL.md"))?Fi(n,c,{recursive:!0}):n.endsWith(".md")&&Fi(n,Ct(c,"SKILL.md")),console.log(y.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});eo.command("list").alias("ls").description("list skills per agent").action(()=>{let e=le();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=H(o.workspace,".claude/skills"),s=he(n)?qi(n).filter(i=>!i.startsWith(".")):[];console.log(` ${y.cyan(t)}: ${s.length?s.join(", "):y.dim("(none)")}`)}console.log()});eo.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=>he(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=Nt(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,h=0;for(let[k,b]of d){let $=b.workspace;if(!$||!he($)){console.log(` ${y.yellow("\u2717")} ${k.padEnd(22)} ${y.dim("(workspace missing: "+($||"undefined")+")")}`),h++;continue}let E=H($,".claude/skills",e),S=H(E,"SKILL.md");if(!he(S)){if(!t.allWorkspaces){console.log(` ${y.dim("\xB7")} ${k.padEnd(22)} ${y.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),h++;continue}t.dryRun||(pt(E,{recursive:!0}),No(S,r)),console.log(` ${y.green("+")} ${k.padEnd(22)} ${y.dim("\u2192 seeded v"+c)}`),u++;continue}let x=Nt(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||No(S,r),console.log(` ${y.yellow("\u21BB")} ${k.padEnd(22)} ${y.dim(`v${R} \u2192 v${c}`)}`),f++}console.log();let w=t.dryRun?"would":"did";console.log(y.dim(` Summary: ${w} seed ${u}, ${w} update ${f}, ${p} already current, ${h} skipped.`)),t.dryRun&&(u>0||f>0)&&console.log(y.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});eo.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-YFVSSYSL.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=le().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=le();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 h of f.reasons)console.log(` ${y.dim("\xB7")} ${h}`)}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)});eo.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=le(),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-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-4CW3CXBU.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
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(y.dim(` ${g.lexical.toFixed(2)} -> ${d} ${g.name}`))}}l.judged||console.log(y.dim(`
|
|
32
32
|
(lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var xn=new ut().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");xn.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(y.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");he(n)||(console.log(y.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");pt(i,{recursive:!0}),pt(r,{recursive:!0});let a=qi(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let u=Ct(i,d);if(he(u)&&!t.force){console.log(y.dim(` skip ${u} (exists; --force to overwrite)`)),l++;continue}let p=Nt(Ct(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);No(u,p),console.log(y.green(` + ${u}`)),c++}let g=Ct(r,`${e}.yaml`);if(he(g)&&!t.force)console.log(y.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(he(s)){let d=Nt(s,"utf-8").replaceAll("example.",`${e}.`);No(g,d),console.log(y.green(` + ${g}`)),c++}console.log(),console.log(y.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log(y.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(y.dim(" 2. agentx skill audit # verify references resolve")),console.log(y.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});xn.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(y.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:o}=await import("./loader-YFVSSYSL.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-7YFQNYLC.js"),i=H(t.cwd),r=t.from?String(t.from).split(",").map(h=>h.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(y.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(y.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(y.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([h,w])=>[h,w.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(y.dim(` Dry-run \u2014 would write to ${u}/`));for(let[h,w]of Object.entries(g))console.log(y.cyan(`
|
|
33
33
|
--- ${h} ---`)),console.log(w.split(`
|
|
@@ -409,7 +409,7 @@ return aid ?? null`}function Mf(e,t){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
|
|
|
409
409
|
settings \u2014 without this an attached production identity would be less
|
|
410
410
|
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)}});qt.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)}});ne();import{Command as $h}from"commander";import we from"chalk";var Fs=new $h().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function dg(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 gg(e,t){let o={};return e&&(o.Authorization=`Bearer ${e}`),t&&(o["Content-Type"]=t),o}function lg(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 bh(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}Fs.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}=dg(e),n;try{n=await fetch(`${t}/api/processes`,{headers:gg(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=bh(r.state)(r.state.padEnd(9)),c=lg(r.spawnedAt),l=r.lastTurnAt?lg(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}`)}});Fs.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}=dg(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:gg(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 kh}from"commander";import Le from"chalk";import{existsSync as dr,rmSync as vh}from"fs";import{resolve as gr}from"path";var Wo=new kh().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Wo.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(Le.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!o.verbose,s=Date.now(),i=await ka(e,t,{verbose:n}),r=Date.now()-s;console.log(Le.green(` \u2713 indexed ${i.docs} doc(s) for ${Le.bold(e)} in ${r}ms`)),console.log(Le.dim(` \u2192 ${i.path}`))});Wo.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let t=gr(e.cwd,".agentx","rag");if(!dr(t)){console.log(Le.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:o}=await import("fs"),n=o(t).filter(s=>dr(gr(t,s,"index.json")));if(n.length===0){console.log(Le.dim(" (no indexes)"));return}for(let s of n.sort()){let i=pi(s);console.log(` ${Le.bold(s)} ${i.docs} doc(s) ${Le.dim(i.path)}`)}});Wo.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=va(e,t,{k:n});if(o.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=pi(e);i.exists?console.log(Le.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Le.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Le.bold(i.title)} ${Le.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Le.dim(i.path)}`),console.log(` ${Le.dim(i.snippet.slice(0,200))}`)});Wo.command("clear <agentId>").description("delete an agent's index").action(e=>{let t=gr(process.cwd(),".agentx","rag",e);if(!dr(t)){console.log(Le.dim(` no index for ${e} \u2014 nothing to clear`));return}vh(t,{recursive:!0,force:!0}),console.log(Le.green(` \u2713 cleared index for ${e}`))});ne();import{Command as xh}from"commander";import Q from"chalk";import Bo from"prompts";var co=new xh().name("backlog").description("manage the local backlog used by business workSource=backlog");function Cn(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 zc(n)}}function Sh(e){return e?Q.cyan(`${e.type}:${e.project}#${e.iid}`):Q.dim("manual")}function Eh(e){return{todo:Q.gray("todo"),doing:Q.yellow("doing"),blocked:Q.red("blocked"),done:Q.green("done")}[e]}co.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}=Cn(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(Q.dim(" (no items)"));return}console.log();for(let n of o){let s=n.assignee?Q.magenta(`@${n.assignee}`):Q.dim("unassigned");console.log(` ${Eh(n.status).padEnd(7)} ${Sh(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(Q.dim(` ${n.source.url}`))}console.log(),console.log(Q.dim(` ${o.length} item${o.length===1?"":"s"} \u2014 ${t.jsonPath()}`))});co.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=Cn(o.config);n.store.findById(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:t,status:"doing"});if(console.log(Q.green(` claimed: ${i.title} -> ${t}`)),i.source){let r=Yc([t],i.source,n.config),a=await Ai(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(Q.dim(" sync:"),...c));console.log(a.ok?Q.dim(` synced -> ${a.url??i.source.type}`):Q.yellow(` sync failed: ${a.error}`))}});co.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=Cn(t.config);o.store.findById(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1));let s=o.store.update(e,{status:"done"});if(console.log(Q.green(` done: ${s.title}`)),s.source){let i=await Ai(s,{addLabels:["Done"],removeLabels:["Doing"],state:t.close?"closed":void 0,note:t.note},o.config,(...r)=>console.log(Q.dim(" sync:"),...r));console.log(i.ok?Q.dim(` synced -> ${i.url??s.source.type}`):Q.yellow(` sync failed: ${i.error}`))}});co.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}=Cn(t.config);o.remove(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1)),console.log(Q.green(` removed ${e}`))});co.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=Cn(e.config),o=!!t.config.channels.gitlab?.token,n=!!t.config.channels.github?.token;!o&&!n&&(console.error(Q.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 w=[o&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Bo({type:"select",name:"source",message:"Source",choices:w})).source,!s)return}s==="gitlab"&&!o&&(console.error(Q.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(Q.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let w=s==="gitlab"?Th(t.config):jh(t.config);w.length?(i=(await Bo({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...w.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await Bo({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Bo({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Bo({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(Q.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await Oh(t.config,i,a):await Ih(t.config,i,a);if(!c.length){console.log(Q.yellow(" no open issues matched"));return}console.log(Q.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(t.store.list().map(w=>w.id)),d=c.map(w=>{let k=Ei({type:s,project:l,iid:w.iid,url:w.url}),b=g.has(k),$=w.labels.length?` [${w.labels.slice(0,3).join(",")}]`:"";return{title:`#${w.iid} ${w.title}${$}${b?Q.dim(" (already imported)"):""}`,value:w,disabled:b}}),f=(await Bo({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(Q.dim(" nothing selected"));return}let p=f.map(w=>{let k={type:s,host:s==="gitlab"?Ah(t.config):void 0,project:l,iid:w.iid,url:w.url};return{id:Ei(k),title:w.title,description:w.description,assignee:e.assignee||w.assignee,labels:w.labels,milestone:w.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),h=t.store.addMany(p);console.log(Q.green(` imported ${h.length} item${h.length===1?"":"s"}`));for(let w of h)console.log(Q.dim(` ${w.id} \u2014 ${w.title}`))});function Ah(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Th(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 jh(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 Oh(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 Ih(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(mg)}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(mg):[]}function mg(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 Ch}from"commander";import W from"chalk";import{existsSync as Nh,readFileSync as Rh}from"fs";import{resolve as _h}from"path";import Dh from"prompts";ne();function pg(e){let t=e||_h(process.cwd(),"agentx.json");return Nh(t)||(console.log(W.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(Rh(t,"utf-8"))}async function Ph(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 Dh([{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 vt=new Ch().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');vt.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: ${hi})`,hi).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){vt.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=fi(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=pg(t.config),s=ea(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 Ph(t.notify,s),r=t.id||Ca(o.matched,t.agent),a=Ra({parsed:o,agent:t.agent,prompt:t.do,timezone:t.timezone,timeout:parseInt(t.timeout,10),model:t.model,notify:i,onError:Na(t.onError),enabled:!t.disabled}),c=a.onError,l=await pe(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."))});vt.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=pg(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=Da(_a(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]])vt.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await La(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."))});vt.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await pe(o=>{if(!xo(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);Aa(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",Pa,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",Ma,"reject an agent's pending create/delete request (drops the request)"]])vt.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."))});vt.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=fi(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 Mh}from"commander";import xe from"chalk";var Wt=new Mh("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals, WhatsApp replies)"),Lh={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki",whatsapp:"whatsapp"};function ug(){return{root:process.cwd()}}function mr(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function Fh(e){console.log(` ${xe.cyan(e.key)} ${xe.dim(`[${Lh[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?xe.dim(` (later: until ${mr(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 ${mr(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}`:""}`))}Wt.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=fc(ug(),{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)Fh(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 pr(e,t,o){let n=gs(),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 hc(ug(),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}`))}Wt.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)=>pr(e,"yes",t));Wt.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)=>pr(e,"no",t));Wt.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)=>pr(e,"later",t));Wt.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: ${pc.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=gs(),o=uc(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 ${mr(o.card.expires)}, then: ${o.card.if_silent}`))});Wt.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=il(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 rl(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=gs(),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 cy}from"commander";import Jo from"chalk";import ie from"chalk";import Rn from"prompts";import{readFileSync as Uh,writeFileSync as qh,existsSync as Wh}from"fs";import{resolve as fg}from"path";var Bh=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Jh(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function ur(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function hg(e=".env"){let t=fg(e);if(!Wh(t))return[];let o=Uh(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(Bh);i?n.push({kind:"kv",key:i[1],value:Jh(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Hh(e){return e.map(t=>t.kind==="kv"?`${t.key}=${ur(t.value)}`:t.raw).join(`
|
|
411
411
|
`)+`
|
|
412
|
-
`}function Nn(e,t,o=".env"){let n=fg(o),s=hg(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:t,raw:`${e}=${ur(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${ur(t)}`})),qh(n,Hh(s))}function fr(e,t=".env"){return hg(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var yg="https://t.me/BotFather";async function Gh(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 zh(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 wg(e={}){console.log(),console.log(ie.bold(" Connect Telegram")),console.log(),console.log(ie.dim(` 1. Open ${yg}`)),console.log(ie.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ie.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:t}=await Rn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(t)try{let{spawn:b}=await import("child_process"),$=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b($,[yg],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:o}=await Rn({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(ie.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Gh(o.trim());n||(console.log(ie.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ie.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(ie.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(ie.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Rn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ie.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Rn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ie.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Nn(f,o.trim()),process.env[f]=o.trim();let p=await pe(b=>{Oe(b,"channels.telegram.enabled",!0),Oe(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=xo(b,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),Oe(b,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ie.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ie.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ie.dim(` Token stored in .env as ${f}`)),console.log(ie.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ie.dim(" Daemon hot-reloaded.")):console.log(ie.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Rn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(ie.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ie.dim(" Waiting up to 90s..."));let w=await zh(o.trim(),9e4);if(!w){console.log(ie.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ie.dim(" agentx config set notifications.destination.channel telegram")),console.log(ie.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ie.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await pe(b=>{Oe(b,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ie.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ie.green(" \u2713 Default --notify target set")),console.log(ie.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ie.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ie.dim(" Daemon hot-reloaded."))}import $e from"chalk";import hr from"prompts";import{existsSync as wr,mkdirSync as Yh,readdirSync as Vh,readFileSync as $g}from"fs";import{resolve as yr}from"path";var Kh=".agentx/whatsapp-sessions";function Xh(){let e=yr(process.cwd(),".agentx/daemon.pid");if(!wr(e))return!1;try{let t=parseInt($g(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function Qh(e){if(!wr(e))return!1;try{return Vh(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function Zh(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t($e.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t($e.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;Yh(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($e.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($e.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($e.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($e.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function bg(e={}){if(console.log(),console.log($e.bold(" Connect WhatsApp")),console.log(),Xh()){console.log($e.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log($e.dim(" agentx daemon stop")),console.log();let{cont:l}=await hr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log($e.red(" Aborted")),process.exit(1))}let t=e.configPath||yr(process.cwd(),"agentx.json");wr(t)||(console.log($e.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse($g(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||Kh,s=yr(process.cwd(),n),i=Object.keys(o.agents||{});i.length===0&&(console.log($e.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await hr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log($e.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Qh(s)&&a){let{keep:l}=await hr({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($e.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Zh(s,g=>console.log(g))||(console.log($e.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await pe(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($e.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log($e.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log($e.dim(` Session: ${n}`)),console.log($e.dim(" Start the daemon to begin receiving:")),console.log($e.dim(" agentx daemon start")),console.log($e.dim(" Add routes later with:")),console.log($e.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as ey}from"crypto";import Ae from"chalk";import kg from"prompts";var Us="agentx-mesh:",qs="//join/";function ty(e){return Buffer.from(e,"utf-8").toString("base64url")}function oy(e){return Buffer.from(e,"base64url").toString("utf-8")}function ny(e){return`${Us}${qs}${ty(JSON.stringify(e))}`}function sy(e){if(!e.startsWith(`${Us}${qs}`))throw new Error(`Not a mesh invite link \u2014 expected ${Us}${qs}\u2026`);let t=e.slice(Us.length+qs.length),o=JSON.parse(oy(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 iy(){return ey(32).toString("hex")}function ry(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function ay(e){return e?.node?.name||e?.node?.id||"node"}async function vg(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=fr("MESH_TOKEN");r||(r=iy(),Nn("MESH_TOKEN",r),console.log(Ae.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||ry(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await kg({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 pe(d=>{Oe(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ae.red(` \u2717 ${l.error}`)),process.exit(1));let g=ny({url:a,token:r,name:ay(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 xg(e,t={}){let o;try{o=sy(e)}catch(i){console.log(Ae.red(` \u2717 ${i.message}`)),process.exit(1)}let n=fr("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:i}=await kg({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))}Nn("MESH_TOKEN",o.token);let s=await pe(i=>{Oe(i,"mesh.enabled",!0);let r=xo(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(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 Ho=new cy().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Ho.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 wg({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Ho.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 bg({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Sg=Ho.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Sg.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 vg({url:e.url,configPath:e.config})});Sg.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 xg(e,{configPath:t.config})});Ho.action(()=>{console.log(),console.log(Jo.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Jo.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Jo.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Jo.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Jo.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Jo.dim(" GitLab connect is the next slice.")),console.log()});ne();import{Command as ly}from"commander";import fe from"chalk";var _n=new ly().name("usage").description("token usage analysis and reporting");_n.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(fe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(fe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${fe.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: ${fe.red(String(s.totalErrors))}`),console.log(),console.log(fe.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(` ${fe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${fe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(fe.red(" Daemon not running. Start with: agentx daemon start")):console.log(fe.red(` ${e.message}`))}});_n.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(fe.red(` Script not found: ${s}`)),console.log(fe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(fe.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(fe.red(" Analysis failed. Is Python 3 installed?"))}});_n.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-EHCDAWI7.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(fe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${fe.dim("\xB7")} ${d}`);console.log(),console.log(fe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(fe.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(fe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(fe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(fe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(fe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=fe.dim(`${i.days}d`);console.log(` ${fe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(fe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as dy}from"commander";import be from"chalk";import{readFileSync as gy}from"fs";import{resolve as my}from"path";ne();var Bt=new dy().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Bt.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{da(my(process.cwd(),".env"))}catch{}let t=py(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-CDBPGUU3.js");o(t)}catch(t){console.log(be.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(be.dim(t.stack)),process.exit(1)}});function py(e,t){try{let o=I();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(be.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(be.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
412
|
+
`}function Nn(e,t,o=".env"){let n=fg(o),s=hg(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:t,raw:`${e}=${ur(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${ur(t)}`})),qh(n,Hh(s))}function fr(e,t=".env"){return hg(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var yg="https://t.me/BotFather";async function Gh(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 zh(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 wg(e={}){console.log(),console.log(ie.bold(" Connect Telegram")),console.log(),console.log(ie.dim(` 1. Open ${yg}`)),console.log(ie.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ie.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:t}=await Rn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(t)try{let{spawn:b}=await import("child_process"),$=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b($,[yg],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:o}=await Rn({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(ie.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Gh(o.trim());n||(console.log(ie.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ie.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(ie.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(ie.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Rn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ie.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Rn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ie.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Nn(f,o.trim()),process.env[f]=o.trim();let p=await pe(b=>{Oe(b,"channels.telegram.enabled",!0),Oe(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=xo(b,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),Oe(b,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ie.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ie.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ie.dim(` Token stored in .env as ${f}`)),console.log(ie.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ie.dim(" Daemon hot-reloaded.")):console.log(ie.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Rn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(ie.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ie.dim(" Waiting up to 90s..."));let w=await zh(o.trim(),9e4);if(!w){console.log(ie.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ie.dim(" agentx config set notifications.destination.channel telegram")),console.log(ie.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ie.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await pe(b=>{Oe(b,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ie.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ie.green(" \u2713 Default --notify target set")),console.log(ie.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ie.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ie.dim(" Daemon hot-reloaded."))}import $e from"chalk";import hr from"prompts";import{existsSync as wr,mkdirSync as Yh,readdirSync as Vh,readFileSync as $g}from"fs";import{resolve as yr}from"path";var Kh=".agentx/whatsapp-sessions";function Xh(){let e=yr(process.cwd(),".agentx/daemon.pid");if(!wr(e))return!1;try{let t=parseInt($g(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function Qh(e){if(!wr(e))return!1;try{return Vh(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function Zh(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t($e.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t($e.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;Yh(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($e.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($e.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($e.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($e.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function bg(e={}){if(console.log(),console.log($e.bold(" Connect WhatsApp")),console.log(),Xh()){console.log($e.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log($e.dim(" agentx daemon stop")),console.log();let{cont:l}=await hr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log($e.red(" Aborted")),process.exit(1))}let t=e.configPath||yr(process.cwd(),"agentx.json");wr(t)||(console.log($e.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse($g(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||Kh,s=yr(process.cwd(),n),i=Object.keys(o.agents||{});i.length===0&&(console.log($e.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await hr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log($e.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Qh(s)&&a){let{keep:l}=await hr({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($e.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Zh(s,g=>console.log(g))||(console.log($e.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await pe(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($e.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log($e.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log($e.dim(` Session: ${n}`)),console.log($e.dim(" Start the daemon to begin receiving:")),console.log($e.dim(" agentx daemon start")),console.log($e.dim(" Add routes later with:")),console.log($e.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as ey}from"crypto";import Ae from"chalk";import kg from"prompts";var Us="agentx-mesh:",qs="//join/";function ty(e){return Buffer.from(e,"utf-8").toString("base64url")}function oy(e){return Buffer.from(e,"base64url").toString("utf-8")}function ny(e){return`${Us}${qs}${ty(JSON.stringify(e))}`}function sy(e){if(!e.startsWith(`${Us}${qs}`))throw new Error(`Not a mesh invite link \u2014 expected ${Us}${qs}\u2026`);let t=e.slice(Us.length+qs.length),o=JSON.parse(oy(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 iy(){return ey(32).toString("hex")}function ry(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function ay(e){return e?.node?.name||e?.node?.id||"node"}async function vg(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=fr("MESH_TOKEN");r||(r=iy(),Nn("MESH_TOKEN",r),console.log(Ae.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||ry(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await kg({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 pe(d=>{Oe(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ae.red(` \u2717 ${l.error}`)),process.exit(1));let g=ny({url:a,token:r,name:ay(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 xg(e,t={}){let o;try{o=sy(e)}catch(i){console.log(Ae.red(` \u2717 ${i.message}`)),process.exit(1)}let n=fr("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:i}=await kg({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))}Nn("MESH_TOKEN",o.token);let s=await pe(i=>{Oe(i,"mesh.enabled",!0);let r=xo(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(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 Ho=new cy().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Ho.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 wg({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Ho.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 bg({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Sg=Ho.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Sg.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 vg({url:e.url,configPath:e.config})});Sg.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 xg(e,{configPath:t.config})});Ho.action(()=>{console.log(),console.log(Jo.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Jo.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Jo.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Jo.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Jo.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Jo.dim(" GitLab connect is the next slice.")),console.log()});ne();import{Command as ly}from"commander";import fe from"chalk";var _n=new ly().name("usage").description("token usage analysis and reporting");_n.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(fe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(fe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${fe.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: ${fe.red(String(s.totalErrors))}`),console.log(),console.log(fe.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(` ${fe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${fe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(fe.red(" Daemon not running. Start with: agentx daemon start")):console.log(fe.red(` ${e.message}`))}});_n.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(fe.red(` Script not found: ${s}`)),console.log(fe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(fe.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(fe.red(" Analysis failed. Is Python 3 installed?"))}});_n.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-3DBXC6DX.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(fe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${fe.dim("\xB7")} ${d}`);console.log(),console.log(fe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(fe.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(fe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(fe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(fe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(fe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=fe.dim(`${i.days}d`);console.log(` ${fe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(fe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as dy}from"commander";import be from"chalk";import{readFileSync as gy}from"fs";import{resolve as my}from"path";ne();var Bt=new dy().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Bt.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{da(my(process.cwd(),".env"))}catch{}let t=py(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-W64VXH6Y.js");o(t)}catch(t){console.log(be.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(be.dim(t.stack)),process.exit(1)}});function py(e,t){try{let o=I();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(be.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(be.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
413
413
|
`)),{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}}}}Bt.command("list").description("list configured boards").action(()=>{try{let e=I();if(!e.boards?.length){console.log(be.dim(`
|
|
414
414
|
No boards configured.
|
|
415
415
|
`));return}console.log();for(let t of e.boards){console.log(` ${be.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(be.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(be.dim(` primary label: ${t.primaryToolLabel}`)),console.log(be.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(be.red(` ${e.message}`)),process.exit(1)}});Bt.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{Dn(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(be.red(` ${o.message}`)),process.exit(1)}});Bt.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{Dn(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(be.red(` ${o.message}`)),process.exit(1)}});var $r=Bt.command("column").description("manage a board's columns (add / remove / edit / list)");$r.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(gy("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(be.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(` ${be.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${be.dim(i)}`)}}catch(t){console.log(be.red(` ${t.message}`)),process.exit(1)}});$r.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{Dn(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(be.red(` ${n.message}`)),process.exit(1)}});$r.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{Dn(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(be.red(` ${o.message}`)),process.exit(1)}});Bt.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Dn(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(be.red(` ${t.message}`)),process.exit(1)}});function Dn(e){let{summary:t,backupPath:o}=Qe(n=>e(n));console.log(be.green(`
|
|
@@ -420,9 +420,9 @@ return aid ?? null`}function Mf(e,t){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
|
|
|
420
420
|
${v.content}
|
|
421
421
|
--- END ENTRY ---`).join(`
|
|
422
422
|
|
|
423
|
-
`),$="";if(e.facts!==!1){let{extractHints:v,resolveFacts:R,mergeRecords:C,renderFactsBlock:O,installPrompts:P,defaultSources:B,recordsFromEntries:L}=await import("./facts-2K6UX5GD.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=v(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]);$=O(M);let Ke=[...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${Ke.length?` (${Ke.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 E=Ha(t,u,k,w.articles,b,p.length,$);console.log(m.dim(` Mode: ${kr(t)}`));let S=F(h.baseDir,"_tmp");xt(S,{recursive:!0});let x=F(S,"absorb-prompt.txt");go(x,E),console.log(m.dim(" Compiling with Claude..."));try{let v;try{v=lo(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:yo({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(M){if(v=M.stdout||"",!v)throw M}let R=v;try{let M=JSON.parse(v);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,O=[],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||[],O=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 Ke=new Date().toISOString().slice(0,10),ve=l(M.sources||[],p);h.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:Ke,lastUpdated:Ke,sources:M.sources||[],graphPath:ve},M.content,u);let Yt=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("+")} ${Yt}${M.path}: ${M.title}${m.dim(_)}`);let ye=(M.tags||[]).slice(0,4).join(", ");ye&&console.log(m.dim(` tags: ${ye}`)),ve?.length&&(console.log(m.dim(` graphPath: ${ve.join(" \u203A ")}`)),d++),g++}if(O.length>0){console.log(),console.log(m.yellow(` Gaps detected (${O.length} missing pieces):`));for(let M of O)console.log(m.yellow(` ? ${M}`));try{let{QuestionStore:M}=await import("./questions-ZATLU5AW.js"),Ke=new M(mo(e.dir)).add(O.map(ve=>({kind:"article",agentId:u,path:"",subject:String(ve).slice(0,120),question:`No article yet for: ${String(ve).slice(0,160)}`})));Ke.added>0&&console.log(m.dim(` queued ${Ke.added} for follow-up (agentx wiki questions)`))}catch{}}h.rebuildIndex()}catch(v){console.log(m.red(` Absorb failed: ${v.message?.slice(0,200)}`)),v.stderr&&console.log(m.dim(String(v.stderr).slice(0,300))),v.stdout&&console.log(m.dim("stdout: "+String(v.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let u=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${u}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});ee.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--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=$y(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-F5QKVUQ4.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!Xe(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(!Xe(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 h=p[0];h&&console.log(m.dim(` most recurrent (${h.occurrences} sessions, ${h.failure.runs} runs): ${h.memory.description.slice(0,84)}`)),i=[...i,...p]}finally{u.close()}}}let r=await Ga({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 Bs=ee.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function Js(e){return e?F(e):F(process.cwd(),".agentx","wiki")}Bs.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(Js(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}`))}});Bs.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(Js(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(`
|
|
423
|
+
`),$="";if(e.facts!==!1){let{extractHints:v,resolveFacts:R,mergeRecords:C,renderFactsBlock:O,installPrompts:P,defaultSources:B,recordsFromEntries:L}=await import("./facts-2K6UX5GD.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=v(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]);$=O(M);let Ke=[...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${Ke.length?` (${Ke.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 E=Ha(t,u,k,w.articles,b,p.length,$);console.log(m.dim(` Mode: ${kr(t)}`));let S=F(h.baseDir,"_tmp");xt(S,{recursive:!0});let x=F(S,"absorb-prompt.txt");go(x,E),console.log(m.dim(" Compiling with Claude..."));try{let v;try{v=lo(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:yo({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(M){if(v=M.stdout||"",!v)throw M}let R=v;try{let M=JSON.parse(v);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,O=[],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||[],O=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 Ke=new Date().toISOString().slice(0,10),ve=l(M.sources||[],p);h.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:Ke,lastUpdated:Ke,sources:M.sources||[],graphPath:ve},M.content,u);let Yt=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("+")} ${Yt}${M.path}: ${M.title}${m.dim(_)}`);let ye=(M.tags||[]).slice(0,4).join(", ");ye&&console.log(m.dim(` tags: ${ye}`)),ve?.length&&(console.log(m.dim(` graphPath: ${ve.join(" \u203A ")}`)),d++),g++}if(O.length>0){console.log(),console.log(m.yellow(` Gaps detected (${O.length} missing pieces):`));for(let M of O)console.log(m.yellow(` ? ${M}`));try{let{QuestionStore:M}=await import("./questions-ZATLU5AW.js"),Ke=new M(mo(e.dir)).add(O.map(ve=>({kind:"article",agentId:u,path:"",subject:String(ve).slice(0,120),question:`No article yet for: ${String(ve).slice(0,160)}`})));Ke.added>0&&console.log(m.dim(` queued ${Ke.added} for follow-up (agentx wiki questions)`))}catch{}}h.rebuildIndex()}catch(v){console.log(m.red(` Absorb failed: ${v.message?.slice(0,200)}`)),v.stderr&&console.log(m.dim(String(v.stderr).slice(0,300))),v.stdout&&console.log(m.dim("stdout: "+String(v.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let u=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${u}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});ee.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--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=$y(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-BZLS37MN.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!Xe(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(!Xe(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 h=p[0];h&&console.log(m.dim(` most recurrent (${h.occurrences} sessions, ${h.failure.runs} runs): ${h.memory.description.slice(0,84)}`)),i=[...i,...p]}finally{u.close()}}}let r=await Ga({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 Bs=ee.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function Js(e){return e?F(e):F(process.cwd(),".agentx","wiki")}Bs.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(Js(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}`))}});Bs.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(Js(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(`
|
|
424
424
|
`).map(s=>` ${s}`).join(`
|
|
425
|
-
`)),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>)`))}});Bs.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-
|
|
425
|
+
`)),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>)`))}});Bs.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-PMMUU4G2.js"),n=o(Js(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`))});Bs.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-PMMUU4G2.js"),n=o(Js(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 $y(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)}ee.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",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-CB6FV6JU.js"),{readdirSync:o,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=Te(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 w of f){let k=r(d,w),b=[];try{b=o(k).filter($=>$.endsWith(".json")).sort().reverse()}catch{continue}for(let $ of b){if(u.length>=g)break;try{let E=JSON.parse(n(r(k,$),"utf-8")),S=E.message||E.task?.message;typeof S=="string"&&S.trim().length>10&&u.push({id:E.id||$.replace(".json",""),message:S.trim(),ts:E.at||E.timestamp||w})}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 w=0;w<u.length;w++){let k=u[w];process.stdout.write(m.dim(` [${w+1}/${u.length}] querying... `));let $=l.findRelevant(k.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
|
|
426
426
|
`)||"_(none returned)_",E;try{let S=await t(k.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(S.status!=="ok")E=`_(status: ${S.status}${S.error?" \u2014 "+S.error:""})_`;else{let x=S.citations.map(v=>`\`${v.title}\` [${v.type||"?"}]`).join(", ");E=`**Answer:**
|
|
427
427
|
|
|
428
428
|
${S.answer}
|
|
@@ -439,7 +439,7 @@ Q: ${_.q}
|
|
|
439
439
|
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(`
|
|
440
440
|
`),E=F(a.baseDir,"_tmp");xt(E,{recursive:!0});let S=F(E,`interview-${o().slice(0,8)}.txt`);go(S,$),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"`,ye=lo(_,{env:yo({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Ze=JSON.parse(ye);x=String(Ze.result||Ze.content||"")}catch{x=ye}}catch(_){console.log(m.red(` synthesis failed: ${_.message?.slice(0,200)}`)),c?.close();return}x=x.trim();let v=x.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);v&&(x=v[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 O={};for(let _ of C[1].split(`
|
|
441
441
|
`)){let ye=_.match(/^(\w+):\s*(.+)$/);ye&&(O[ye[1]]=ye[2].trim().replace(/^"(.*)"$/,"$1"))}let P=C[2],B=O.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 je=P,ke={title:B,type:O.type||d,related:O.related?O.related.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:O.tags?O.tags.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:O.access||"public",created:O.created||new Date().toISOString().slice(0,10),lastUpdated:O.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(J==="edit"){let _=process.env.EDITOR||"vi",ye=F(E,`draft-${o().slice(0,8)}.md`);go(ye,x);try{lo(`${_} '${ye}'`,{stdio:"inherit"});let ai=Pn(ye,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(ai){let At={};for(let cn of ai[1].split(`
|
|
442
|
-
`)){let ci=cn.match(/^(\w+):\s*(.+)$/);ci&&(At[ci[1]]=ci[2].trim().replace(/^"(.*)"$/,"$1"))}je=ai[2],ke={...ke,title:At.title||ke.title,type:At.type||ke.type,access:At.access||ke.access,related:At.related?At.related.replace(/^\[|\]$/g,"").split(",").map(cn=>cn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ke.related,tags:At.tags?At.tags.replace(/^\[|\]$/g,"").split(",").map(cn=>cn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ke.tags}}}catch(Ze){console.log(m.red(` editor failed: ${Ze.message}`));return}}if(!a.writeArticle(me,ke,je,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${me} saved.`));let Ke=a.extractWikilinks(je),ve=new Map;for(let _ of a.listArticles(e.agent))ve.set(_.meta.title.toLowerCase(),!0);let Yt=Ke.filter(_=>!ve.has(_.toLowerCase()));if(Yt.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of Yt.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});ee.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let t=await import("node:readline/promises"),{randomUUID:o}=await import("node:crypto"),{agenticQuery:n}=await import("./query-
|
|
442
|
+
`)){let ci=cn.match(/^(\w+):\s*(.+)$/);ci&&(At[ci[1]]=ci[2].trim().replace(/^"(.*)"$/,"$1"))}je=ai[2],ke={...ke,title:At.title||ke.title,type:At.type||ke.type,access:At.access||ke.access,related:At.related?At.related.replace(/^\[|\]$/g,"").split(",").map(cn=>cn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ke.related,tags:At.tags?At.tags.replace(/^\[|\]$/g,"").split(",").map(cn=>cn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ke.tags}}}catch(Ze){console.log(m.red(` editor failed: ${Ze.message}`));return}}if(!a.writeArticle(me,ke,je,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${me} saved.`));let Ke=a.extractWikilinks(je),ve=new Map;for(let _ of a.listArticles(e.agent))ve.set(_.meta.title.toLowerCase(),!0);let Yt=Ke.filter(_=>!ve.has(_.toLowerCase()));if(Yt.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of Yt.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});ee.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let t=await import("node:readline/promises"),{randomUUID:o}=await import("node:crypto"),{agenticQuery:n}=await import("./query-CB6FV6JU.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=Te(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=Pn(e.script,"utf-8").split(/\n\s*\n/).map(h=>h.trim()).filter(Boolean);r=[];for(let h of p){let w=h.split(/\r?\n/).filter($=>$.trim());if(w.length<2)continue;let k=w[0].replace(/^Q:\s*/i,"").trim(),b=w.slice(1).join(" ").trim();k&&b&&r.push({q:k,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,h;if(r){let G=r[f];if(!G)break;p=G.q,h=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;h=""}process.stdout.write(m.dim(" querying... "));let w;try{w=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")),w.status!=="ok")console.log(m.yellow(` (status: ${w.status}${w.error?" \u2014 "+w.error:""})`));else{let G=w.citations.map(me=>`${me.title} [${me.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+w.answer.replace(/\n/g,`
|
|
443
443
|
`)),console.log(m.dim(" citations: "+G))}r||(h=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+h);let k={q:p,answer:w.answer,citations:w.citations,verdict:h},b=h.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!b){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(k);continue}let $=b[1].toLowerCase(),E=(b[2]||"").trim();if(d.push(k),$==="/ok"||$==="/skip")continue;if(!E){console.log(m.yellow(` ${$} without note \u2014 skipping.`));continue}let S=w.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 v=ky(x.content,$,E,x.meta.title,x.meta.type),R=F(i.baseDir,"_tmp");xt(R,{recursive:!0});let C=F(R,`quiz-patch-${o().slice(0,8)}.txt`);go(C,v);let O="";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=lo(G,{env:yo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let je=JSON.parse(me);O=String(je.result||je.content||"")}catch{O=me}let J=O.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);J&&(O=J[1].trim()),O=O.trim()}catch(G){console.log(m.red(` patch failed: ${G.message?.slice(0,120)}`));continue}if(!O||O.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let P=x.content.split(`
|
|
444
444
|
`).length,B=O.split(`
|
|
445
445
|
`).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)")),k.patched=S.path+" (dry)";continue}if(!i.writeArticle(S.path,{...x.meta,lastUpdated:new Date().toISOString().slice(0,10)},O,e.agent)){console.log(m.red(" write failed (permission?)"));continue}u++,k.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 h=d[p];f.push(`## ${p+1}. Q: ${h.q}`,"",`**A:** ${h.answer}`,"",`**Citations:** ${h.citations.map(w=>`\`${w.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${h.verdict}\``+(h.patched?` \u2192 patched \`${h.patched}\``:""),"")}go(e.out,f.join(`
|
|
@@ -500,14 +500,14 @@ Output (JSON array, one entry per input article, same order):
|
|
|
500
500
|
[
|
|
501
501
|
{"path": "path/to/article.md", "type": "project"},
|
|
502
502
|
...
|
|
503
|
-
]`}ee.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Te(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});ee.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let 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-A23CU2XT.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(),gl(t,o,e.agent,n,e.mode)});ee.command("grade").description("grade absorbed articles with the article-quality seat").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","grade only this agent's wiki").option("--limit <n>","articles to grade","20").option("--min <n>","only show articles scoring below this","3").option("--fields","also check the required fields for each article's type").option("--type <t>","grade only articles of this type (person, place, project, \u2026)").option("--json").action(async e=>{let{articleQualityQuestionsFor: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-
|
|
503
|
+
]`}ee.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Te(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});ee.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let 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-A23CU2XT.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(),gl(t,o,e.agent,n,e.mode)});ee.command("grade").description("grade absorbed articles with the article-quality seat").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","grade only this agent's wiki").option("--limit <n>","articles to grade","20").option("--min <n>","only show articles scoring below this","3").option("--fields","also check the required fields for each article's type").option("--type <t>","grade only articles of this type (person, place, project, \u2026)").option("--json").action(async e=>{let{articleQualityQuestionsFor: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-CBAZAYGY.js"),c=Te(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),u=[];e:for(let w of l){let k=c.getAgentWiki(w);for(let b of k.listArticles(w)){if(u.length>=g)break e;let $=k.readArticle(b.path);if(!$||e.type&&$.meta.type!==e.type)continue;let E={...t($.meta.type),...e.fields?i($.meta.type):{}},S=await a(s,o({path:b.path,title:$.meta.title,type:$.meta.type,tags:$.meta.tags,body:$.content}),E,{links:[{kind:"article",id:b.path}],features:{agent:w,type:$.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),v=e.fields?r($.meta.type,S.answers):null;x.completeness>=d&&!(v&&!v.fit)||u.push({agent:w,type:$.meta.type??"?",score:x.completeness.toFixed(2),standsAlone:x.standsAlone.toFixed(2),gap:x.biggestGap,...v?{missing:v.missingCritical.join(",")||"-",cov:`${Math.round(v.coverage*100)}%`}:{},title:$.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((w,k)=>parseFloat(w.score)-parseFloat(k.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],p=f.map(w=>Math.max(w.length,...u.map(k=>String(k[w]).length))),h=w=>w.map((k,b)=>String(k).padEnd(p[b])).join(" ");console.log(),console.log(m.bold(h(f)));for(let w of u)console.log(h(f.map(k=>w[k])));if(e.fields){let w=u.filter(k=>k.missing!=="-").length;console.log(m.dim(`
|
|
504
504
|
${u.length} article(s) flagged; ${w} 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(`
|
|
505
|
-
${u.length} article(s) below ${d}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});ee.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,t)=>{let{agenticQuery:o}=await import("./query-GRLLX7RG.js"),n=Te(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()}});ee.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,t)=>{let o=Te(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()});ee.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let t=Te(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=F(process.cwd(),".agentx/graph");if(!Xe(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Tt({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(),h=new Map(p.map($=>[$.id,$])),w=0,k=0,b=0;for(let $ of f){if(a++,$.meta.graphPath?.length||!$.meta.sources?.length)continue;w++,c++;let E=new Map;for(let x of $.meta.sources){let v=h.get(x);if(!v)continue;let R=String(v.meta?.sender??""),C=s.fingerprint({text:v.content,channel:v.source,sender:R}),O=r.get(C);if(!O?.length)continue;let P=O.join("/"),B=E.get(P);B?B.n++:E.set(P,{path:O,n:1})}if(E.size===0)continue;k++,l++;let S;for(let x of E.values())(!S||x.n>S.n)&&(S=x);S&&(e.dryRun||(u.writeArticle($.path,{...$.meta,graphPath:S.path},$.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${w} eligible \xB7 ${k} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});ee.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let o=Te(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-A23CU2XT.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()});ee.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let t=e.dir||F(process.cwd(),".agentx/wiki"),o=e.agent,s=["flat","graph","unified"].map(c=>{let l=new di(t,void 0,c),d=l.getAgentWiki(o).rebuildIndex(),u=l.getAgentEntries(o),f=l.getUnabsorbedEntries(o),p=new Set,h=0,w=new Set;for(let b of d.articles){for(let $ of b.tags||[])p.add($);h+=b.tags?.length||0;for(let $ of b.sources||[])w.add($)}let k=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:kr(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(h/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:w.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()});ee.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,t)=>{let o=t.dir?F(process.cwd(),t.dir):F(process.cwd(),".agentx/wiki");Xe(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=Xe(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Sy(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});ee.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions: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-DNI7G7B2.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=Te(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 v=l.getAgentWiki(x);for(let R of v.listArticles(x)){if(f>=u)break e;let C=v.readArticle(R.path);if(!C||e.type&&C.meta.type!==e.type)continue;f++;let O=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(!O){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=o(C.meta.type,O.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 h={added:0,skipped:0};if(e.ask&&g.length>0&&(h=new c(mo(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 w=["tier","need","how","uncertain","agent","article"],k=x=>String(x).replace(/\u001b\[[0-9;]*m/g,""),b=w.map(x=>Math.max(x.length,...p.map(v=>k(v[x]).length))),$=(x,v)=>String(x)+" ".repeat(Math.max(0,b[v]-k(x).length));console.log(),console.log(m.bold(w.map((x,v)=>$(x,v)).join(" ")));for(let x of p)console.log(w.map((v,R)=>$(x[v],R)).join(" "));let E=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(` ${E} can be closed by a lookup; ${p.length-E} 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 ${h.added} question(s) for a person (${h.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&h.added>0){let{TIER_RANK:x}=await import("./article-fields-PITN4NHA.js"),v=x[e.notifyTier]??x.pillar,R=g.filter(C=>(x[C.tier??"furniture"]??9)<=v);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-A23CU2XT.js"),O=C(),P=O?.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(`
|
|
505
|
+
${u.length} article(s) below ${d}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});ee.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,t)=>{let{agenticQuery:o}=await import("./query-CB6FV6JU.js"),n=Te(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()}});ee.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,t)=>{let o=Te(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()});ee.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let t=Te(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=F(process.cwd(),".agentx/graph");if(!Xe(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Tt({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(),h=new Map(p.map($=>[$.id,$])),w=0,k=0,b=0;for(let $ of f){if(a++,$.meta.graphPath?.length||!$.meta.sources?.length)continue;w++,c++;let E=new Map;for(let x of $.meta.sources){let v=h.get(x);if(!v)continue;let R=String(v.meta?.sender??""),C=s.fingerprint({text:v.content,channel:v.source,sender:R}),O=r.get(C);if(!O?.length)continue;let P=O.join("/"),B=E.get(P);B?B.n++:E.set(P,{path:O,n:1})}if(E.size===0)continue;k++,l++;let S;for(let x of E.values())(!S||x.n>S.n)&&(S=x);S&&(e.dryRun||(u.writeArticle($.path,{...$.meta,graphPath:S.path},$.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${w} eligible \xB7 ${k} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});ee.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let o=Te(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-A23CU2XT.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()});ee.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let t=e.dir||F(process.cwd(),".agentx/wiki"),o=e.agent,s=["flat","graph","unified"].map(c=>{let l=new di(t,void 0,c),d=l.getAgentWiki(o).rebuildIndex(),u=l.getAgentEntries(o),f=l.getUnabsorbedEntries(o),p=new Set,h=0,w=new Set;for(let b of d.articles){for(let $ of b.tags||[])p.add($);h+=b.tags?.length||0;for(let $ of b.sources||[])w.add($)}let k=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:kr(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(h/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:w.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()});ee.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,t)=>{let o=t.dir?F(process.cwd(),t.dir):F(process.cwd(),".agentx/wiki");Xe(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=Xe(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Sy(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});ee.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions: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-CBAZAYGY.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=Te(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 v=l.getAgentWiki(x);for(let R of v.listArticles(x)){if(f>=u)break e;let C=v.readArticle(R.path);if(!C||e.type&&C.meta.type!==e.type)continue;f++;let O=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(!O){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=o(C.meta.type,O.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 h={added:0,skipped:0};if(e.ask&&g.length>0&&(h=new c(mo(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 w=["tier","need","how","uncertain","agent","article"],k=x=>String(x).replace(/\u001b\[[0-9;]*m/g,""),b=w.map(x=>Math.max(x.length,...p.map(v=>k(v[x]).length))),$=(x,v)=>String(x)+" ".repeat(Math.max(0,b[v]-k(x).length));console.log(),console.log(m.bold(w.map((x,v)=>$(x,v)).join(" ")));for(let x of p)console.log(w.map((v,R)=>$(x[v],R)).join(" "));let E=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(` ${E} can be closed by a lookup; ${p.length-E} 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 ${h.added} question(s) for a person (${h.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&h.added>0){let{TIER_RANK:x}=await import("./article-fields-PITN4NHA.js"),v=x[e.notifyTier]??x.pillar,R=g.filter(C=>(x[C.tier??"furniture"]??9)<=v);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-A23CU2XT.js"),O=C(),P=O?.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(`
|
|
506
506
|
`),L=R.length>10?`
|
|
507
507
|
\u2026and ${R.length-10} more`:"",G=`${R.length} wiki gap(s) need you (${e.notifyTier}+):
|
|
508
508
|
${B}${L}
|
|
509
509
|
|
|
510
|
-
agentx wiki questions`,me=O?.daemon?.port??O?.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.`))}}}}});ee.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:t,reportFields:o,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:r}=await import("./seat-DNI7G7B2.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-2K6UX5GD.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=Te(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),h=parseInt(e.limit),w=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(O=>[O.name.toLowerCase().trim(),O])),$=0,E=0,S=[],x=!1;e:for(let O of p){let P=f.getAgentWiki(O);for(let B of P.listArticles(O)){if($>=h)break e;if(B.meta.type!=="person")continue;let L=P.readArticle(B.path);if(!L)continue;$++;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:O,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:w}),M=b.get(L.meta.title.toLowerCase().trim());if(!x){for(let _ of l(ke,w))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));x=!0}let Ke=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,ye])=>[_,ye.value]))}]:[],...je]);if(Ke.length===0)continue;let{content:ve,edits:Yt}=u(L.content,Ke[0],J);if(Yt.length!==0){for(let _ of Yt)S.push({agent:O,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,O)?E++: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(` ${$} person article(s) considered \u2014 nothing to backfill`));return}let v=["agent","article","field","action","got"],R=v.map(O=>Math.max(O.length,...S.map(P=>String(P[O]).length))),C=O=>O.map((P,B)=>String(P).padEnd(R[B])).join(" ");console.log(),console.log(m.bold(C(v)));for(let O of S)console.log(C(v.map(P=>O[P])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${E} 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 ${$} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});ee.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:t}=await import("./questions-ZATLU5AW.js"),{TIER_RANK:o}=await import("./article-fields-PITN4NHA.js"),n=new t(mo(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`))});ee.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,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(mo(o.dir)),a=r.list().find(h=>(h.id===e||h.id.startsWith(e))&&h.status!=="open"&&h.kind==="contradiction");if(a&&!r.list("open").some(h=>h.id===e||h.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(o.dismiss){try{let h=r.resolve(e,"dismissed");console.log(h?m.dim(` dismissed: ${h.question}`):m.red(` no question matching "${e}"`))}catch(h){console.log(m.red(` ${h?.message??h}`)),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(h=>h.id===e||h.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:h}=await import("./ledger-CH7R756S.js"),w=new h(mo(o.dir));try{let k=w.get(c.factId);if(k){let b=w.write({subject:k.subject,attribute:k.attribute,value:t,source:"owner said",verifiedBy:"operator",volatility:k.volatility},{confirmedBy:"operator"});console.log(m.green(` ${b.status}: ${k.id} ${k.subject} \xB7 ${k.attribute}: ${b.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch(k){k?.name!=="LedgerCorruptError"&&console.log(m.red(` ${k?.message??k}`)),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(h){console.log(m.red(` ${h?.message??h}`)),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=Te(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}`))});ee.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:t,entryTriageQuestions:o,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:i}=await import("./seat-DNI7G7B2.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=Te(e.dir,"graph").getSharedStore(),p=f.listEntries(),h=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:w,backlog:k}=r(p,h),b=a(w,L=>L.absorbed,parseInt(e.n)),$={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},E=[],S=0,x=Date.now();if(e.load){let{readFileSync:L}=await import("fs");E.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${E.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${w.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;E.push({entry:L,verdict:s(G.answers,$),citeWorthy:me.citeWorthy?.noul})}if(E.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(E)),console.log(m.dim(` saved ${E.length} outcome(s) to ${e.save}`))}let v=c(E,{minType:$.minTypeConfidence,minWorth:$.minWorth,minDurability:$.minDurability}),R=l(E,"seat","seat"),C=d(R,{minN:50}),O=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:v,calibration:C,failures:S,elapsed:O},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 ${v.n} (${v.positives} kept by absorb, ${v.negatives} passed over)`),console.log(` recall ${P(v.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P(v.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P(v.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${v.lostPositives>0?m.yellow(`lost ${v.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)")}`),v.lostPositives>0){let L=v.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=v.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(` ${O}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(E,{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."))}}});ee.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,t)=>{let o=F(process.cwd(),e);Xe(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");Xe(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 Sy(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"}Mm();import{Command as Ey}from"commander";import D from"chalk";import{resolve as Hs}from"path";import{existsSync as Ay}from"fs";ne();var Yo=new Ey().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Yo.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 Tt({baseDir:Hs(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 h=r[p],w=Kn(h.path,c)||h.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${D.cyan(h.msgHash.slice(0,8))} ${D.dim(w)} ... `);let k=Ty(h,a,c),b=null;try{b=await jy(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 $=String(b.decision).toLowerCase().trim(),E=(b.reason||"").toString().slice(0,180);if($==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(E)),e.dryRun)l++;else try{Oy(i,h,a,c,o),i.updateClassificationStatus(h.msgHash,{status:"approved",reviewer:o,reviewReason:E}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),u++}else $==="reject"?(console.log(D.red("REJECT")+" "+D.dim(E)),e.dryRun||i.updateClassificationStatus(h.msgHash,{status:"rejected",reviewer:o,reviewReason:E}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(E||$)),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()});Yo.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=Hs(process.cwd(),t.graph.baseDir);if(!Ay(o)){console.log(D.yellow(` ${o} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-W7RRFM24.js"),s=new Tt({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()});Yo.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 Tt({baseDir:Hs(process.cwd(),t.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(v=>v.id));console.log(),console.log(D.bold(` graph pull \u2190 ${o}`));let l,g,d;try{let v=await fetch(`${o}/graph/schema`,{headers:s});if(!v.ok)throw new Error(`schema HTTP ${v.status}`);l=(await v.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 O=await fetch(`${o}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!O.ok)throw new Error(`classifications HTTP ${O.status}`);d=(await O.json()).classifications||[]}catch(v){console.log(D.red(` fetch failed: ${v.message}`));return}let u=r.levels.map(v=>v.id).join(","),f=l?.levels?.map(v=>v.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 h=p?r:l,w=new Map;h.levels.forEach((v,R)=>w.set(v.id,R));let k=[...g].sort((v,R)=>(w.get(v.level)??99)-(w.get(R.level)??99)),b=0,$=0,E=0;for(let v of k){if(c.has(v.id)){$++;continue}if(e.dryRun){b++,c.add(v.id);continue}try{i.addNode({...v,createdBy:v.createdBy?`${v.createdBy} (sync)`:`sync:${o}`}),c.add(v.id),b++}catch(R){E++,console.log(D.yellow(` skip node ${v.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${b} added \xB7 ${$} already-present \xB7 ${E} failed`));let S=0,x=0;for(let v of d)if(!(!v.msgHash||!Array.isArray(v.path))){if(i.getFingerprint(v.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint(v.msgHash,{path:v.path,leaf:v.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 Ty(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(`
|
|
510
|
+
agentx wiki questions`,me=O?.daemon?.port??O?.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.`))}}}}});ee.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:t,reportFields:o,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:r}=await import("./seat-CBAZAYGY.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-2K6UX5GD.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=Te(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),h=parseInt(e.limit),w=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(O=>[O.name.toLowerCase().trim(),O])),$=0,E=0,S=[],x=!1;e:for(let O of p){let P=f.getAgentWiki(O);for(let B of P.listArticles(O)){if($>=h)break e;if(B.meta.type!=="person")continue;let L=P.readArticle(B.path);if(!L)continue;$++;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:O,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:w}),M=b.get(L.meta.title.toLowerCase().trim());if(!x){for(let _ of l(ke,w))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));x=!0}let Ke=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,ye])=>[_,ye.value]))}]:[],...je]);if(Ke.length===0)continue;let{content:ve,edits:Yt}=u(L.content,Ke[0],J);if(Yt.length!==0){for(let _ of Yt)S.push({agent:O,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,O)?E++: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(` ${$} person article(s) considered \u2014 nothing to backfill`));return}let v=["agent","article","field","action","got"],R=v.map(O=>Math.max(O.length,...S.map(P=>String(P[O]).length))),C=O=>O.map((P,B)=>String(P).padEnd(R[B])).join(" ");console.log(),console.log(m.bold(C(v)));for(let O of S)console.log(C(v.map(P=>O[P])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${E} 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 ${$} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});ee.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:t}=await import("./questions-ZATLU5AW.js"),{TIER_RANK:o}=await import("./article-fields-PITN4NHA.js"),n=new t(mo(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`))});ee.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,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(mo(o.dir)),a=r.list().find(h=>(h.id===e||h.id.startsWith(e))&&h.status!=="open"&&h.kind==="contradiction");if(a&&!r.list("open").some(h=>h.id===e||h.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(o.dismiss){try{let h=r.resolve(e,"dismissed");console.log(h?m.dim(` dismissed: ${h.question}`):m.red(` no question matching "${e}"`))}catch(h){console.log(m.red(` ${h?.message??h}`)),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(h=>h.id===e||h.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:h}=await import("./ledger-CH7R756S.js"),w=new h(mo(o.dir));try{let k=w.get(c.factId);if(k){let b=w.write({subject:k.subject,attribute:k.attribute,value:t,source:"owner said",verifiedBy:"operator",volatility:k.volatility},{confirmedBy:"operator"});console.log(m.green(` ${b.status}: ${k.id} ${k.subject} \xB7 ${k.attribute}: ${b.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch(k){k?.name!=="LedgerCorruptError"&&console.log(m.red(` ${k?.message??k}`)),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(h){console.log(m.red(` ${h?.message??h}`)),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=Te(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}`))});ee.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:t,entryTriageQuestions:o,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:i}=await import("./seat-CBAZAYGY.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=Te(e.dir,"graph").getSharedStore(),p=f.listEntries(),h=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:w,backlog:k}=r(p,h),b=a(w,L=>L.absorbed,parseInt(e.n)),$={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},E=[],S=0,x=Date.now();if(e.load){let{readFileSync:L}=await import("fs");E.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${E.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${w.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;E.push({entry:L,verdict:s(G.answers,$),citeWorthy:me.citeWorthy?.noul})}if(E.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(E)),console.log(m.dim(` saved ${E.length} outcome(s) to ${e.save}`))}let v=c(E,{minType:$.minTypeConfidence,minWorth:$.minWorth,minDurability:$.minDurability}),R=l(E,"seat","seat"),C=d(R,{minN:50}),O=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:v,calibration:C,failures:S,elapsed:O},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 ${v.n} (${v.positives} kept by absorb, ${v.negatives} passed over)`),console.log(` recall ${P(v.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P(v.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P(v.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${v.lostPositives>0?m.yellow(`lost ${v.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)")}`),v.lostPositives>0){let L=v.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=v.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(` ${O}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(E,{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."))}}});ee.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,t)=>{let o=F(process.cwd(),e);Xe(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");Xe(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 Sy(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"}Mm();import{Command as Ey}from"commander";import D from"chalk";import{resolve as Hs}from"path";import{existsSync as Ay}from"fs";ne();var Yo=new Ey().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Yo.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 Tt({baseDir:Hs(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 h=r[p],w=Kn(h.path,c)||h.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${D.cyan(h.msgHash.slice(0,8))} ${D.dim(w)} ... `);let k=Ty(h,a,c),b=null;try{b=await jy(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 $=String(b.decision).toLowerCase().trim(),E=(b.reason||"").toString().slice(0,180);if($==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(E)),e.dryRun)l++;else try{Oy(i,h,a,c,o),i.updateClassificationStatus(h.msgHash,{status:"approved",reviewer:o,reviewReason:E}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),u++}else $==="reject"?(console.log(D.red("REJECT")+" "+D.dim(E)),e.dryRun||i.updateClassificationStatus(h.msgHash,{status:"rejected",reviewer:o,reviewReason:E}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(E||$)),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()});Yo.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=Hs(process.cwd(),t.graph.baseDir);if(!Ay(o)){console.log(D.yellow(` ${o} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-W7RRFM24.js"),s=new Tt({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()});Yo.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 Tt({baseDir:Hs(process.cwd(),t.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(v=>v.id));console.log(),console.log(D.bold(` graph pull \u2190 ${o}`));let l,g,d;try{let v=await fetch(`${o}/graph/schema`,{headers:s});if(!v.ok)throw new Error(`schema HTTP ${v.status}`);l=(await v.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 O=await fetch(`${o}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!O.ok)throw new Error(`classifications HTTP ${O.status}`);d=(await O.json()).classifications||[]}catch(v){console.log(D.red(` fetch failed: ${v.message}`));return}let u=r.levels.map(v=>v.id).join(","),f=l?.levels?.map(v=>v.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 h=p?r:l,w=new Map;h.levels.forEach((v,R)=>w.set(v.id,R));let k=[...g].sort((v,R)=>(w.get(v.level)??99)-(w.get(R.level)??99)),b=0,$=0,E=0;for(let v of k){if(c.has(v.id)){$++;continue}if(e.dryRun){b++,c.add(v.id);continue}try{i.addNode({...v,createdBy:v.createdBy?`${v.createdBy} (sync)`:`sync:${o}`}),c.add(v.id),b++}catch(R){E++,console.log(D.yellow(` skip node ${v.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${b} added \xB7 ${$} already-present \xB7 ${E} failed`));let S=0,x=0;for(let v of d)if(!(!v.msgHash||!Array.isArray(v.path))){if(i.getFingerprint(v.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint(v.msgHash,{path:v.path,leaf:v.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 Ty(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(`
|
|
511
511
|
`),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(`
|
|
512
512
|
`)}async function jy(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 ra((c?.content||"").toString())}finally{clearTimeout(r)}}function Oy(e,t,o,n,s){e.commitNodesAlongPath(t.path,t.proposedAxes||{},o,s),e.setFingerprint(t.msgHash,{path:t.path,leaf:t.leaf||{}})}function vr(){let e=I();if(!e.graph?.baseDir)return console.log(D.red(" graph.baseDir is not configured")),null;let t=Hs(process.cwd(),e.graph.baseDir);return{store:new Tt({baseDir:t}),baseDir:t}}var xr=Yo.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");xr.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=vr();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(Kn(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]"))});xr.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=vr();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}: ${Kn(r[0].path,c)||r[0].path.join(" \u203A ")}`)),o.path&&console.log(D.dim(` should have been: ${o.path}`))});xr.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let t=vr();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 Dy}from"commander";import V from"chalk";import{Command as Ng}from"commander";import de from"chalk";import{existsSync as Iy}from"fs";import{resolve as Cy}from"path";import Ny from"better-sqlite3";function Ry(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(de.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function _y(e){let t=Cy(process.cwd(),e);return Iy(t)||(console.log(de.red(` No db at ${t}`)),process.exit(1)),new Ny(t,{readonly:!0})}var Rg=new Ng().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(pn)).option("--max <n>","max clusters distilled per run",String(es)).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(de.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let t=_y(e.path),o=await za(t,{since:Ry(e.since),agentId:e.agent,sessions:new pa(process.cwd()),minOccurrences:Number(e.minOccurrences)||pn,max:Number(e.max)||es,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(de.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(` ${de.cyan(n.key)} ${de.bold(`\xD7${n.count}`)} ${de.dim(n.status)}`),n.sampleMessage&&console.log(de.dim(` "${n.sampleMessage.slice(0,100)}"`));if(o.nearMisses.length){console.log(de.dim(`
|
|
513
513
|
near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of o.nearMisses.slice(0,5))console.log(de.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of o.drafted)console.log(de.green(` \u2713 draft written: ${n.id}`)+de.dim(` (${n.count} occurrences)`));for(let n of o.skipped)console.log(de.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of o.warnings)console.log(de.yellow(` \u26A0 ${n}`));o.dryRun?console.log(de.dim(`
|
|
@@ -636,7 +636,7 @@ Restart the daemon to activate.
|
|
|
636
636
|
dist/
|
|
637
637
|
*.log
|
|
638
638
|
.env
|
|
639
|
-
`}import{Command as s$}from"commander";import Re from"chalk";import{writeFileSync as i$,mkdirSync as r$,existsSync as si,readFileSync as $m,appendFileSync as bm}from"fs";import{resolve as sn,dirname as xm}from"path";import{homedir as Wr}from"os";var Sm=new s$().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-
|
|
639
|
+
`}import{Command as s$}from"commander";import Re from"chalk";import{writeFileSync as i$,mkdirSync as r$,existsSync as si,readFileSync as $m,appendFileSync as bm}from"fs";import{resolve as sn,dirname as xm}from"path";import{homedir as Wr}from"os";var Sm=new s$().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-3DBXC6DX.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=l$(o);break;case"bash":s=u$(o);break;case"fish":s=f$(o);break;default:console.error(Re.red(`unsupported shell: ${n}`)),console.error(Re.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?sn(String(e.output)):a$(n);r$(xm(i),{recursive:!0}),i$(i,s),console.log(Re.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),c$(n,i,!!e.yes)});function a$(e){let t=Wr();switch(e){case"zsh":return sn(t,".zsh","completions","_agentx");case"bash":return sn(t,".bash_completion.d","agentx.bash");case"fish":return sn(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function c$(e,t,o){if(e==="zsh"){let n=sn(Wr(),".zshrc"),s=xm(t),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=si(n)?$m(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Re.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&si(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),bm(n,g.join(`
|
|
640
640
|
`)+`
|
|
641
641
|
`),console.log(Re.green("\u2713 Patched ~/.zshrc")),console.log(Re.dim("Reload your shell: exec zsh"));return}console.log(Re.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Re.cyan(` ${i}`)),l&&console.log(Re.cyan(` ${r}`)),console.log(),console.log(Re.dim("Then reload: exec zsh")),console.log(Re.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=sn(Wr(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((si(n)?$m(n,"utf-8"):"").includes(t)){console.log(Re.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&si(n)){bm(n,`
|
|
642
642
|
# agentx completion
|
|
@@ -652,4 +652,4 @@ ${h$({...t,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
|
|
|
652
652
|
${o.url}`)}catch(t){console.error(an.red(` ${t.message}`)),process.exitCode=1}});Gn.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 zr(t.models);if(!Hr(t.model,o)){console.log(Gr(t.model,o)),process.exitCode=1;return}let n=e==="-"?await $$():await w$(e,"utf8"),s=JSON.parse(n),{version:i}=await Zn(),r=jm({...s,fields:s.fields??{}},{model:t.model,version:i??"unknown"});console.log(r)}catch(o){console.error(an.red(` ${o.message}`)),process.exitCode=1}});async function $$(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function Y1(){let e=await Zn(),t=new b$().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=cl(n);ll(s)&&al("cli",s)});for(let o of[Ml,_l,Ho,jo,Co,tt,sl,Qt,ks,vt,Wt,qt,bs,Qg,Lt,nd,md,jn,xd,Td,Id,Rd,_d,Xd,tg,og,qo,_n,nm,kn,Rt,Sm,Gn])t.addCommand(o);for(let o of Im)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=Im.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,k$(o,74," "),""].join(`
|
|
653
653
|
`)}),t}var Im=[ee,Yo,Gt,dt,xn,Wo,Ye,St,Bt,co,Qo,Zo,Pt,Je,Do,Fs,Vg,Kg,bt,Zt,ul,eo,Jn,Wi,Ht,Ro,Bi,Xs,yt,Et,mm,um,om];function k$(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(`
|
|
654
654
|
`)}export{Y1 as a};
|
|
655
|
-
//# sourceMappingURL=chunk-
|
|
655
|
+
//# sourceMappingURL=chunk-7ZO2UZRI.js.map
|