agentix-cli 0.69.1 → 0.69.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-K7EPLYCP.js → agent-P2UO35ZW.js} +2 -2
- package/dist/{board-dashboard-BWB2FLOA.js → board-dashboard-3WVKEGRZ.js} +6 -5
- package/dist/{board-dashboard-BWB2FLOA.js.map → board-dashboard-3WVKEGRZ.js.map} +1 -1
- package/dist/{chunk-ART666G6.js → chunk-2V7IQUEA.js} +2 -2
- package/dist/{chunk-PNWNVOEZ.js → chunk-4DRNEOOW.js} +2 -2
- package/dist/{chunk-KSUCHOH2.js → chunk-4UMYRIEI.js} +2 -2
- package/dist/{chunk-HEJOWP7O.js → chunk-56AQBWEJ.js} +2 -2
- package/dist/{chunk-JHWBCDD2.js → chunk-A5ZCMRB3.js} +12 -9
- package/dist/chunk-A5ZCMRB3.js.map +1 -0
- package/dist/{chunk-PDGPHE35.js → chunk-AIV547JW.js} +2 -2
- package/dist/{chunk-X5BWHPR7.js → chunk-JSF2THM4.js} +2 -2
- package/dist/{chunk-3XEN24B7.js → chunk-L2K4N3DA.js} +3 -3
- package/dist/chunk-M6HJDSLS.js +109 -0
- package/dist/chunk-M6HJDSLS.js.map +1 -0
- package/dist/{chunk-USTQPX4Y.js → chunk-U3XQ7USK.js} +9 -9
- package/dist/{chunk-USTQPX4Y.js.map → chunk-U3XQ7USK.js.map} +1 -1
- package/dist/{chunk-S4ASFOJU.js → chunk-VXDM7JAT.js} +2 -2
- package/dist/{chunk-37P3DKSX.js → chunk-X4FD5OBK.js} +6 -6
- package/dist/{chunk-NEC4RXFT.js → chunk-XMW422NO.js} +2 -2
- package/dist/{chunk-LPWPFEIE.js → chunk-YBLITM6C.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/index.d.ts +12 -0
- package/dist/index.js +1 -1
- package/dist/{migrate-v2-5VGHWPBW.js → migrate-v2-KOMPDC6U.js} +2 -2
- package/dist/{program-44FEGUCB.js → program-GUBHJFZS.js} +2 -2
- package/dist/{promote-XRKH73IB.js → promote-7FMPZKXN.js} +2 -2
- package/dist/{registry-HMVIS6QJ.js → registry-MUMQPZDM.js} +2 -2
- package/dist/{schedule-tool-ZVKBZOVG.js → schedule-tool-BY72YNNU.js} +2 -2
- package/dist/{scheduler-5NBO3J2G.js → scheduler-XWYFGG2S.js} +2 -2
- package/dist/{tool-ZENVUVBO.js → tool-ZUGNQZGI.js} +2 -2
- package/dist/{wiki-W6WI6HL3.js → wiki-LLL7VWRJ.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-CUZWGTXT.js +0 -109
- package/dist/chunk-CUZWGTXT.js.map +0 -1
- package/dist/chunk-JHWBCDD2.js.map +0 -1
- /package/dist/{agent-K7EPLYCP.js.map → agent-P2UO35ZW.js.map} +0 -0
- /package/dist/{chunk-ART666G6.js.map → chunk-2V7IQUEA.js.map} +0 -0
- /package/dist/{chunk-PNWNVOEZ.js.map → chunk-4DRNEOOW.js.map} +0 -0
- /package/dist/{chunk-KSUCHOH2.js.map → chunk-4UMYRIEI.js.map} +0 -0
- /package/dist/{chunk-HEJOWP7O.js.map → chunk-56AQBWEJ.js.map} +0 -0
- /package/dist/{chunk-PDGPHE35.js.map → chunk-AIV547JW.js.map} +0 -0
- /package/dist/{chunk-X5BWHPR7.js.map → chunk-JSF2THM4.js.map} +0 -0
- /package/dist/{chunk-3XEN24B7.js.map → chunk-L2K4N3DA.js.map} +0 -0
- /package/dist/{chunk-S4ASFOJU.js.map → chunk-VXDM7JAT.js.map} +0 -0
- /package/dist/{chunk-37P3DKSX.js.map → chunk-X4FD5OBK.js.map} +0 -0
- /package/dist/{chunk-NEC4RXFT.js.map → chunk-XMW422NO.js.map} +0 -0
- /package/dist/{chunk-LPWPFEIE.js.map → chunk-YBLITM6C.js.map} +0 -0
- /package/dist/{migrate-v2-5VGHWPBW.js.map → migrate-v2-KOMPDC6U.js.map} +0 -0
- /package/dist/{program-44FEGUCB.js.map → program-GUBHJFZS.js.map} +0 -0
- /package/dist/{promote-XRKH73IB.js.map → promote-7FMPZKXN.js.map} +0 -0
- /package/dist/{registry-HMVIS6QJ.js.map → registry-MUMQPZDM.js.map} +0 -0
- /package/dist/{schedule-tool-ZVKBZOVG.js.map → schedule-tool-BY72YNNU.js.map} +0 -0
- /package/dist/{scheduler-5NBO3J2G.js.map → scheduler-XWYFGG2S.js.map} +0 -0
- /package/dist/{tool-ZENVUVBO.js.map → tool-ZUGNQZGI.js.map} +0 -0
- /package/dist/{wiki-W6WI6HL3.js.map → wiki-LLL7VWRJ.js.map} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{e as o}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{e as o}from"./chunk-M6HJDSLS.js";import{resolve as a}from"path";import{existsSync as d,readdirSync as c,mkdirSync as l}from"fs";var g=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(t=a(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki-hub]"),r="graph"){this.baseDir=t,this.agentsDir=a(t,"agents"),this.mode=r,this.log=e,l(this.agentsDir,{recursive:!0}),this.sharedStore=new o(t,e)}getMode(){return this.mode}getAgentWiki(t){let e=`${t}:${this.mode}`;if(this.agentStores.has(e))return this.agentStores.get(e);let r=a(this.agentsDir,t,this.mode),i=new o(r,this.log);return this.agentStores.set(e,i),i}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}listAgents(){let t=new Set,e=this.sharedStore.listEntries();for(let r of e)t.add(r.agentId);if(d(this.agentsDir))for(let r of c(this.agentsDir))!r.startsWith("_")&&!r.startsWith(".")&&t.add(r);return[...t].sort()}getAgentEntries(t){return this.sharedStore.listEntries({agentId:t})}getUnabsorbedEntries(t){let e=this.getAgentWiki(t),r=this.getAgentEntries(t),i=new Set,n=e.rebuildIndex();for(let s of n.articles)if(s.sources)for(let h of s.sources)i.add(h);return r.filter(s=>!i.has(s.id))}summary(){return this.listAgents().map(e=>{let r=this.getAgentEntries(e),n=this.getAgentWiki(e).rebuildIndex(),s=this.getUnabsorbedEntries(e);return{agentId:e,totalEntries:r.length,totalArticles:n.articles.length,unabsorbed:s.length,articles:n.articles}})}};export{g as a};
|
|
2
|
+
//# sourceMappingURL=chunk-VXDM7JAT.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Gc,b as Zn,g as zc}from"./chunk-G3SOCQII.js";import{a as Mc,c as Lc}from"./chunk-APKKQGTG.js";import{a as ct,b as Rc,f as _c,g as Dc,h as Pc,i as Qn,j as Fc,k as Uc,l as hi,m as Jc,o as Hc}from"./chunk-
|
|
1
|
+
import{a as Gc,b as Zn,g as zc}from"./chunk-G3SOCQII.js";import{a as Mc,c as Lc}from"./chunk-APKKQGTG.js";import{a as ct,b as Rc,f as _c,g as Dc,h as Pc,i as Qn,j as Fc,k as Uc,l as hi,m as Jc,o as Hc}from"./chunk-56AQBWEJ.js";import{a as qc,c as Wc,d as Bc}from"./chunk-Z3IP66SL.js";import{a as ni,b as ma}from"./chunk-RKPAVWXF.js";import{a as ho}from"./chunk-GV7S5BAX.js";import{e as oa}from"./chunk-GSX4NK2N.js";import{c as na}from"./chunk-SZDACK6O.js";import{$ as Cc,A as ri,B as cc,C as lc,D as dc,E as gc,F as mc,G as pc,H as wc,I as bc,J as wo,K as Yn,L as di,M as $c,N as kc,O as vc,P as xc,Q as bo,R as $o,S as Sc,T as Ec,U as Re,V as Vn,W as an,X as gi,Y as Ac,Z as Tc,_ as ui,a as $a,aa as Kn,b as ka,ba as ko,ca as Xn,da as fi,ea as Nc,h as Un,i as Ea,j as nn,k as qn,l as Oa,m as Ta,n as Ia,o as Ca,p as Ba,q as Ja,r as Hn,s as ii,t as Va,u as ec,v as nc,w as sc,x as ic,y as rc,z as ac}from"./chunk-U3XQ7USK.js";import{A as Qa,B as Za,Ma as at,N as sn,Oa as Ic,P as ai,Q as Gn,R as uc,ba as Et,ca as fc,da as ci,fa as li,ha as hc,ia as yc,ja as rn,m as St,na as zn,q as Ka,t as Xa,va as jc,wa as mi,xa as Oc,ya as pi}from"./chunk-JSF2THM4.js";import{a as Wn,b as Bn,c as Na,d as Ra,e as _a,g as Da,h as Pa,j as Ma,k as La,l as Fa,m as Ua,p as Jn,r as qa,s as Wa}from"./chunk-BYJ3A55Y.js";import{a as va,d as xa,e as Sa}from"./chunk-F2DEKA2Q.js";import{a as Aa,p as ja}from"./chunk-2V7IQUEA.js";import{a as Ha,b as Ga,c as za,d as Ya}from"./chunk-2D3RYIDU.js";import{a as tc,b as oc}from"./chunk-L53FTKEP.js";import{B as xt,H as da,S as ga,h as Vr,q as Kr,v as ei,w as ea}from"./chunk-L2K4N3DA.js";import{b as mo,g as uo,h as Ln,i as Fn,j as fo,k as ta,l as Ht,m as on}from"./chunk-4UMYRIEI.js";import{a as Yr}from"./chunk-N6EWZGIX.js";import{e as aa,f as oi,k as ca}from"./chunk-WP6KLXTP.js";import{b as po}from"./chunk-DP7RTNDM.js";import{a as si,e as pa,f as ua,h as fa,i as ha,k as ya,l as wa,m as ba}from"./chunk-XMW422NO.js";import{f as sa,g as ia,h as ti}from"./chunk-76Z4VHDX.js";import{a as Qr,k as ra}from"./chunk-A5ZCMRB3.js";import{b as ye,c as Te,d as yo,e as la}from"./chunk-APKAW7LU.js";import{a as Zs,b as Xr}from"./chunk-GQ76J72O.js";import{j as Zr}from"./chunk-X5C5W3E4.js";import{h as zr}from"./chunk-DWADWDMU.js";import{a as Qs}from"./chunk-VXDM7JAT.js";import{b as vt,d as Mn}from"./chunk-M6HJDSLS.js";import{b as go,d as Gr}from"./chunk-2GIDVZ4H.js";import{a as Xs,b as Cr,c as em,d as Dn,e as Nr,f as Ur,g as nm,h as qr,i as sm,m as lo,n as Br,o as Jr,s as Hr,v as rt,w as tn}from"./chunk-VOS2IW4V.js";import{a as Wr,b as im}from"./chunk-FX3D7YON.js";import{a as ft,b as co,e as Mr,f as en}from"./chunk-72SZI2UW.js";import{a as ut,b as Zg}from"./chunk-7I7IEX4S.js";import{m as Rr,n as _r,p as Dr,q as tm,v as Pr,w as I,x as Pn,z as ae}from"./chunk-N5NPJ6DJ.js";import{g as Lr,k as Fr,l as om}from"./chunk-RGDKHYY2.js";import{Command as rm}from"commander";var Yc=new rm().name("a2a").description("start an A2A (Agent-to-Agent) protocol server for external agent integration").option("--port <port>","server port","3171").option("--host <host>","server host","0.0.0.0").option("-p, --provider <provider>","AI provider","claude-code").option("-m, --model <model>","model to use").option("--api-key <key>","API key for the provider").option("-c, --cwd <cwd>","working directory",process.cwd()).option("--no-cors","disable CORS headers").action(async e=>{await new ka({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});ae();import{Command as am}from"commander";import{execFileSync as Xe}from"node:child_process";import{cpSync as Vc,existsSync as bi,mkdirSync as yi,mkdtempSync as cm,readdirSync as lm,rmSync as Kc,writeFileSync as Xc}from"node:fs";import{dirname as Qc,join as De}from"node:path";import{homedir as es,release as dm,tmpdir as gm}from"node:os";import{setTimeout as mm}from"node:timers/promises";function ts(){let e=Na(process.platform,process.arch,dm());if(e)throw new Error(e)}function os(){let e=De(es(),"Library/LaunchAgents"),t=[];try{t=lm(e).filter(Da)}catch{}let o=t.flatMap(n=>{let s=De(e,n);try{return[{file:s,plist:Xe("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Pa(e,o)}function cn(e){return`gui/${process.getuid()}/${e.label}`}async function wi(e){try{Xe("launchctl",["bootout",cn(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{Xe("launchctl",["print",cn(e)],{stdio:"pipe"})}catch{return}await mm(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Zc(e){if(!bi(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{Xe("launchctl",["print",cn(e)],{stdio:"pipe"})}catch{t=!1}t||Xe("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),Xe("launchctl",["kickstart",cn(e)],{stdio:"pipe"})}function pm(){let e=Ua();if(e&&bi(De(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var vo=new am("desktop").description("install and control the macOS desktop assistant");vo.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{ts();let t=I(),o=Ra(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=pm(),r=De(es(),"Applications"),{keep:a,remove:c}=os();if(console.log(`Desktop assistant \u2192 ${De(r,Wn)}
|
|
2
2
|
Computer-use helper \u2192 ${De(r,Bn)}
|
|
3
3
|
Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
|
|
4
4
|
Daemon \u2192 ${s}
|
|
@@ -403,7 +403,7 @@ return aid ?? null`}function Yu(e,t){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
|
|
|
403
403
|
settings \u2014 without this an attached production identity would be less
|
|
404
404
|
guarded than a spawned one.)`))):console.log(N.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${N.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(t){console.error(N.red(`Install failed: ${t?.message??t}`)),process.exit(1)}});Pt.command("uninstall").description("remove the attach hooks from ~/.claude/settings.json").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--remove-guard","also remove the PreToolUse guard hook").action(e=>{try{let t=sl({path:e.path,keepGuard:!e.removeGuard});console.log(t.changed?`${N.green("\u2713")} Removed attach hooks from ${N.gray(t.path)} (${t.events.join(", ")})`:`${N.gray("Nothing to remove.")}`),e.removeGuard||console.log(N.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(t){console.error(N.red(`Uninstall failed: ${t?.message??t}`)),process.exit(1)}});ae();import{Command as Cf}from"commander";import we from"chalk";var As=new Cf().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Ld(e){let t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let n=I(e.config);t||(t=n.dashboard?.daemonUrl||""),o||(o=n.dashboard?.token||"")}catch{}return t||(t="http://localhost:18800"),{baseUrl:t.replace(/\/+$/,""),token:o}}function Fd(e,t){let o={};return e&&(o.Authorization=`Bearer ${e}`),t&&(o["Content-Type"]=t),o}function Md(e){let t=Math.round((Date.now()-e)/1e3);return t<60?`${t}s`:t<3600?`${Math.round(t/60)}m`:t<86400?`${Math.round(t/3600)}h`:`${Math.round(t/86400)}d`}function Nf(e){return e==="busy"?we.magenta:e==="warm-hot"?we.green:e==="warm-cold"?we.cyan:e==="idle"?we.yellow:e==="dead"?we.red:we.dim}As.command("list").description("list every live persistent claude process").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("--json","emit JSON").action(async e=>{let{baseUrl:t,token:o}=Ld(e),n;try{n=await fetch(`${t}/api/processes`,{headers:Fd(o)})}catch(r){console.log(we.red(` could not reach daemon at ${t}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(we.dim(` daemon at ${t} has no agents with persistentProcess: true`));return}n.ok||(console.log(we.red(` HTTP ${n.status} from ${t}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(we.dim(" (no processes)"));return}for(let r of i){let a=Nf(r.state)(r.state.padEnd(9)),c=Md(r.spawnedAt),l=r.lastTurnAt?Md(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?we.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?we.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):we.dim("sess=\u2014"),u=r.pendingTaskId?we.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${we.bold(r.key.agentId)}${we.dim(":"+r.key.channel+":"+r.key.chatId)} ${we.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${u}`),r.deadReason&&console.log(` ${we.red("dead:")} ${r.deadReason}`)}});As.command("kill <agentId> <channel> <chatId>").description("force-kill one persistent process (the next dispatch will spawn fresh)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("-r, --reason <reason>","kill reason (recorded on the dead-process snapshot)","operator-cli").action(async(e,t,o,n)=>{let{baseUrl:s,token:i}=Ld(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Fd(i,"application/json"),body:JSON.stringify({agentId:e,channel:t,chatId:o,reason:n.reason})})}catch(a){console.log(we.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(we.dim(" daemon has no persistent-process registry"));return}if(!r.ok){let a=`HTTP ${r.status}`;try{let c=await r.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(we.red(` ${a}`)),process.exit(1)}console.log(we.green(` killed ${e}:${t}:${o}`))});import{Command as Rf}from"commander";import Me from"chalk";import{existsSync as Vi,rmSync as _f}from"fs";import{resolve as Ki}from"path";var _o=new Rf().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");_o.command("add <agentId>").description("build or refresh an agent's lexical index from one or more globs").argument("<globs...>","glob patterns relative to cwd (e.g. './docs/**/*.md')").option("-v, --verbose","log each indexed file").action(async(e,t,o)=>{t.length===0&&(console.log(Me.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!o.verbose,s=Date.now(),i=await sa(e,t,{verbose:n}),r=Date.now()-s;console.log(Me.green(` \u2713 indexed ${i.docs} doc(s) for ${Me.bold(e)} in ${r}ms`)),console.log(Me.dim(` \u2192 ${i.path}`))});_o.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let t=Ki(e.cwd,".agentx","rag");if(!Vi(t)){console.log(Me.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:o}=await import("fs"),n=o(t).filter(s=>Vi(Ki(t,s,"index.json")));if(n.length===0){console.log(Me.dim(" (no indexes)"));return}for(let s of n.sort()){let i=ti(s);console.log(` ${Me.bold(s)} ${i.docs} doc(s) ${Me.dim(i.path)}`)}});_o.command("search <agentId> <query>").description("query an agent's index \u2014 useful for debugging recall before the agent calls rag.lexical").option("-k, --k <n>","top-k results","5").option("--json","emit JSON").action((e,t,o)=>{let n=parseInt(o.k,10)||5,s=ia(e,t,{k:n});if(o.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=ti(e);i.exists?console.log(Me.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Me.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Me.bold(i.title)} ${Me.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Me.dim(i.path)}`),console.log(` ${Me.dim(i.snippet.slice(0,200))}`)});_o.command("clear <agentId>").description("delete an agent's index").action(e=>{let t=Ki(process.cwd(),".agentx","rag",e);if(!Vi(t)){console.log(Me.dim(` no index for ${e} \u2014 nothing to clear`));return}_f(t,{recursive:!0,force:!0}),console.log(Me.green(` \u2713 cleared index for ${e}`))});ae();import{Command as Df}from"commander";import X from"chalk";import Do from"prompts";var no=new Df().name("backlog").description("manage the local backlog used by business workSource=backlog");function kn(e){let t=I(e),o=t.business?.workSource,n=o?.type==="backlog"?o.path:".agentx/backlog.md";return{config:t,storePath:n,store:new jc(n)}}function Pf(e){return e?X.cyan(`${e.type}:${e.project}#${e.iid}`):X.dim("manual")}function Mf(e){return{todo:X.gray("todo"),doing:X.yellow("doing"),blocked:X.red("blocked"),done:X.green("done")}[e]}no.command("list",{isDefault:!0}).description("list backlog items").option("--status <status>","filter by status (todo|doing|blocked|done)").option("--assignee <agent>","filter by assignee").option("--source <type>","filter by source.type (gitlab|github|manual)").option("-c, --config <path>","config path").action(async e=>{let{store:t}=kn(e.config),o=t.list();if(e.status&&(o=o.filter(n=>n.status===e.status)),e.assignee&&(o=o.filter(n=>n.assignee===e.assignee)),e.source&&(o=o.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!o.length){console.log(X.dim(" (no items)"));return}console.log();for(let n of o){let s=n.assignee?X.magenta(`@${n.assignee}`):X.dim("unassigned");console.log(` ${Mf(n.status).padEnd(7)} ${Pf(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(X.dim(` ${n.source.url}`))}console.log(),console.log(X.dim(` ${o.length} item${o.length===1?"":"s"} \u2014 ${t.jsonPath()}`))});no.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,t,o)=>{let n=kn(o.config);n.store.findById(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:t,status:"doing"});if(console.log(X.green(` claimed: ${i.title} -> ${t}`)),i.source){let r=Oc([t],i.source,n.config),a=await pi(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(X.dim(" sync:"),...c));console.log(a.ok?X.dim(` synced -> ${a.url??i.source.type}`):X.yellow(` sync failed: ${a.error}`))}});no.command("done <id>").description("mark an item as done; closes the upstream issue if linked").option("--note <text>","comment to post upstream").option("--close","also close the upstream issue (default: only labels change)",!1).option("-c, --config <path>","config path").action(async(e,t)=>{let o=kn(t.config);o.store.findById(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1));let s=o.store.update(e,{status:"done"});if(console.log(X.green(` done: ${s.title}`)),s.source){let i=await pi(s,{addLabels:["Done"],removeLabels:["Doing"],state:t.close?"closed":void 0,note:t.note},o.config,(...r)=>console.log(X.dim(" sync:"),...r));console.log(i.ok?X.dim(` synced -> ${i.url??s.source.type}`):X.yellow(` sync failed: ${i.error}`))}});no.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,t)=>{let{store:o}=kn(t.config);o.remove(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1)),console.log(X.green(` removed ${e}`))});no.command("import").description("import open issues from gitlab/github into the backlog (interactive)").option("--source <type>","source type (gitlab|github)").option("--project <id>","project id (group/repo for gitlab, owner/repo for github)").option("--assignee <agent>","assign all imported items to this agentId").option("-c, --config <path>","config path").action(async e=>{let t=kn(e.config),o=!!t.config.channels.gitlab?.token,n=!!t.config.channels.github?.token;!o&&!n&&(console.error(X.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let y=[o&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Do({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!o&&(console.error(X.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(X.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?Ff(t.config):Uf(t.config);y.length?(i=(await Do({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...y.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await Do({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Do({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Do({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(X.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await qf(t.config,i,a):await Wf(t.config,i,a);if(!c.length){console.log(X.yellow(" no open issues matched"));return}console.log(X.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(t.store.list().map(y=>y.id)),d=c.map(y=>{let $=mi({type:s,project:l,iid:y.iid,url:y.url}),b=g.has($),v=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${v}${b?X.dim(" (already imported)"):""}`,value:y,disabled:b}}),f=(await Do({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!f.length){console.log(X.dim(" nothing selected"));return}let p=f.map(y=>{let $={type:s,host:s==="gitlab"?Lf(t.config):void 0,project:l,iid:y.iid,url:y.url};return{id:mi($),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:$,importedAt:new Date().toISOString()}}),w=t.store.addMany(p);console.log(X.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(X.dim(` ${y.id} \u2014 ${y.title}`))});function Lf(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Ff(e){let t=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&t.add(n.project);let o=e.business?.workSource;if(o?.type==="gitlab")for(let n of o.projects??[])t.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&t.add(n.id);return[...t].sort()}function Uf(e){let t=new Set;for(let o of e.channels.github?.routes??[])o.repo&&o.repo!=="*"&&t.add(o.repo);return[...t].sort()}async function qf(e,t,o){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});o&&s.set("search",o);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(t)}/issues?${s}`,{headers:{"PRIVATE-TOKEN":n.token}});if(!i.ok)throw new Error(`GitLab ${i.status}: ${await i.text().catch(()=>"")}`);let r=await i.json();return Array.isArray(r)?r.map(a=>({iid:a.iid,title:a.title,description:a.description||void 0,labels:Array.isArray(a.labels)?a.labels.map(c=>typeof c=="string"?c:c.name):[],milestone:a.milestone?.title||void 0,assignee:a.assignee?.username||a.assignees?.[0]?.username||void 0,url:a.web_url})):[]}async function Wf(e,t,o){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(o){let c=`repo:${t} is:issue is:open ${o}`;i=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let l=await fetch(i,{headers:s});if(!l.ok)throw new Error(`GitHub ${l.status}: ${await l.text().catch(()=>"")}`);return((await l.json()).items??[]).map(Ud)}i=`https://api.github.com/repos/${t}/issues?state=open&per_page=100&sort=updated&direction=desc`;let r=await fetch(i,{headers:s});if(!r.ok)throw new Error(`GitHub ${r.status}: ${await r.text().catch(()=>"")}`);let a=await r.json();return Array.isArray(a)?a.filter(c=>!c.pull_request).map(Ud):[]}function Ud(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(t=>typeof t=="string"?t:t.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as Bf}from"commander";import W from"chalk";import{existsSync as Jf,readFileSync as Hf}from"fs";import{resolve as Gf}from"path";import zf from"prompts";ae();function qd(e){let t=e||Gf(process.cwd(),"agentx.json");return Jf(t)||(console.log(W.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(Hf(t,"utf-8"))}async function Yf(e,t){if(!e)return;if(e==="me"){let n=t?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(W.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await zf([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let o=e.split(":");if(o.length>=2)return{channel:o[0],chatId:o[1],accountId:o[2]};console.log(W.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var wt=new Bf().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');wt.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>",`IANA timezone (default: ${si})`,si).option("--timeout <seconds>","max run time","600").option("--model <model>","override model").option("--disabled","create but leave disabled").option("--dry-run","print what would be written without writing").action(async(e,t)=>{if(!e){wt.help();return}t.agent||(console.log(W.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(W.red(' --do "<prompt>" is required')),process.exit(1));let o=ni(e);o||(console.log(W.red(` Couldn't parse: "${e}"`)),console.log(W.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(W.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(W.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=qd(t.config),s=Pr(n);n.agents?.[t.agent]||(console.log(W.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(W.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await Yf(t.notify,s),r=t.id||ma(o.matched,t.agent),a=ua({parsed:o,agent:t.agent,prompt:t.do,timezone:t.timezone,timeout:parseInt(t.timeout,10),model:t.model,notify:i,onError:pa(t.onError),enabled:!t.disabled}),c=a.onError,l=await ye(d=>Te(d,`crons.${r}`,a),{configPath:t.config,dryRun:!!t.dryRun});l.success||(console.log(W.red(` \u2717 ${l.error}`)),process.exit(1));let g=t.dryRun?"would add":"Added";console.log(W.green(` \u2713 ${g} cron ${W.cyan(r)}`)),console.log(W.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(W.dim(` Agent: ${t.agent}`)),i&&console.log(W.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(W.dim(` On error: ${c.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wt.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async e=>{let o=qd(e.config).crons||{},n=Object.entries(o);if(!n.length){console.log(W.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?W.yellow("\u25D0"):i.enabled?W.green("\u25CF"):W.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${W.cyan(s.padEnd(32))} ${W.dim(i.schedule.padEnd(14))} ${W.dim("\u2192")} ${i.agent}`),console.log(W.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(W.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(W.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=ha(fa(i.schedule,c),c);console.log(W.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(W.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,t]of[["on",!0],["off",!1]])wt.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await ba(o,t);n.success||(console.log(W.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wt.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await ye(o=>{if(!yo(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);la(o,`crons.${e}`)});t.success||(console.log(W.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});for(let[e,t,o]of[["approve",ya,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",wa,"reject an agent's pending create/delete request (drops the request)"]])wt.command(`${e} <id>`).description(o).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await t(n,{configPath:s.config});i.success||(console.log(W.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(W.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wt.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=ni(t);o||(console.log(W.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(W.green(` "${t}"`)),console.log(W.dim(` \u2192 ${o.cron}`)),console.log(W.dim(` \u2192 ${o.human}`))});import{Command as Vf}from"commander";import xe from"chalk";var Mt=new Vf("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals)"),Kf={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki"};function Wd(){return{root:process.cwd()}}function Xi(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function Xf(e){console.log(` ${xe.cyan(e.key)} ${xe.dim(`[${Kf[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?xe.dim(` (later: until ${Xi(e.snoozed_until)})`):""}`),console.log(` ${xe.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${xe.green("Recommends:")} ${e.recommend}`),e.expires&&console.log(xe.yellow(` Expires ${Xi(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(xe.dim(` ${e.detail}`)),e.source&&console.log(xe.dim(` ${e.source}`)),console.log(xe.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}Mt.command("list",{isDefault:!0}).alias("ls").description("what is waiting, most urgent first").option("--all","include items you put off with `later`").option("--json","machine-readable output").action(e=>{let t=Qa(Wd(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(t,null,2));return}for(let o of t.errors)console.log(xe.red(` couldn't read ${o.kind}: ${o.error}`));if(t.items.length===0){console.log(xe.dim(` nothing waiting${t.snoozed?` (${t.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let o of t.items)Xf(o),console.log();console.log(xe.dim(` ${t.items.length} waiting${t.snoozed?`, ${t.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function Qi(e,t,o){let n=Qn(),s=o.hours?Number(o.hours):n.laterHours;if(t==="later"&&!(s>0)){console.error(xe.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await Za(Wd(),e,t,{force:o.force,note:o.note,laterHours:s});if(!i.ok){console.error(xe.red(` ${i.error}`)),process.exitCode=1;return}console.log(xe.green(` \u2713 ${i.message}`))}Mt.command("approve").alias("yes").description("say yes: enables the schedule, lets the fact be used, writes the wiki article, or tells the agent yes").argument("<key>","item key from `agentx approvals list`, e.g. card:2026-01-05-publish-draft-ab12").option("--force","wiki: approve even if the article changed since the proposal").option("--note <text>","cards: a note passed to the agent with your answer").action((e,t)=>Qi(e,"yes",t));Mt.command("reject").alias("no").description("say no: drops the request, keeps the fact out, declines the article, or tells the agent no").argument("<key>","item key from `agentx approvals list`").option("--note <text>","why; kept with cards and wiki proposals").action((e,t)=>Qi(e,"no",t));Mt.command("later").description("put an item off; it leaves the list and comes back later (a card still expires on time)").argument("<key>","item key from `agentx approvals list`").option("--hours <n>","how long (default: approvals.laterHours, 24)").action((e,t)=>Qi(e,"later",t));Mt.command("request").description("raise a decision card yourself, for example to test the inbox (agents use the agentx_approval tool)").requiredOption("--agent <id>","the agent the card is from; it gets the result").requiredOption("--title <text>","what it is, in one line").requiredOption("--ask <text>","the yes/no question").requiredOption("--recommend <text>","the advice and why, in one line").requiredOption("--if-silent <value>",`what applies if nobody answers: ${Ka.join(", ")}`).option("--expires <when>","ISO date or time, or like 12h / 3d (default: approvals.defaultExpiryDays)").option("--source <link>","link to the draft, PR or issue").action(e=>{let t=Qn(),o=Xa(process.cwd(),{raised_by:e.agent,title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.ifSilent,expires:e.expires,source:e.source},{settings:t});if(!o.ok){console.error(xe.red(` ${o.error}`)),process.exitCode=1;return}console.log(xe.green(` \u2713 card:${o.card.id} raised; expires ${Xi(o.card.expires)}, then: ${o.card.if_silent}`))});Mt.command("settings").description('show or change expiry, "later" and digest settings (approvals in agentx.json)').option("--expiry-days <n>","days a card gets when it doesn't say").option("--max-expiry-days <n>","longest a card may wait").option("--later-hours <n>","how long `later` hides an item").option("--notify-agent <on|off>","tell the agent that raised a card its result").option("--digest <on|off>","the daily message about what is waiting").option("--digest-time <HH:MM>","when the digest goes out, 24-hour local time").option("--digest-timezone <zone>",`IANA timezone for --digest-time; "local" for this machine's`).option("--digest-to <channel:chatId>",'where the digest goes; "default" for notifications.destination').action(async e=>{let t={},o=(a,c)=>{if(c===void 0)return;let l=Number(c);if(!(l>0))throw new Error(`${a} must be a positive number`);return l},n=(a,c)=>{if(c!==void 0){if(c==="on")return!0;if(c==="off")return!1;throw new Error(`${a} takes on or off`)}};try{if(t.defaultExpiryDays=o("--expiry-days",e.expiryDays),t.maxExpiryDays=o("--max-expiry-days",e.maxExpiryDays),t.laterHours=o("--later-hours",e.laterHours),t.notifyAgent=n("--notify-agent",e.notifyAgent),t.digestEnabled=n("--digest",e.digest),e.digestTime!==void 0&&(t.digestTime=e.digestTime),e.digestTimezone!==void 0&&(t.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")t.destination=null;else{let a=Fc(e.digestTo);if(!a)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");t.destination=a}}catch(a){console.error(xe.red(` ${a.message}`)),process.exitCode=1;return}if(Object.values(t).some(a=>a!==void 0)){let a=await Uc(t);if(!a.success){console.error(xe.red(` ${a.error}`)),process.exitCode=1;return}console.log(xe.green(" \u2713 saved")+(a.reloaded?xe.dim(" (daemon reloaded)"):""))}let i=Qn(),r=i.digest.destination;console.log(` Cards expire after ${i.defaultExpiryDays} day(s) unless they say (at most ${i.maxExpiryDays})`),console.log(` "Later" hides an item ${i.laterHours} hour(s)`),console.log(` Tell the agent ${i.notifyAgent?"on":"off"}`),console.log(` Daily digest ${i.digest.enabled?`on, at ${i.digest.time}${i.digest.timezone?` (${i.digest.timezone})`:" (this machine's time)"}`:"off"}`),console.log(` Digest goes to ${r?`${r.channel} ${r.chatId}`:"notifications.destination"}`)});import{Command as $h}from"commander";import Po from"chalk";import se from"chalk";import xn from"prompts";import{readFileSync as Qf,writeFileSync as Zf,existsSync as eh}from"fs";import{resolve as Bd}from"path";var th=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function oh(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Zi(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Jd(e=".env"){let t=Bd(e);if(!eh(t))return[];let o=Qf(t,"utf-8"),n=[];for(let s of o.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let i=s.match(th);i?n.push({kind:"kv",key:i[1],value:oh(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function nh(e){return e.map(t=>t.kind==="kv"?`${t.key}=${Zi(t.value)}`:t.raw).join(`
|
|
405
405
|
`)+`
|
|
406
|
-
`}function vn(e,t,o=".env"){let n=Bd(o),s=Jd(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:t,raw:`${e}=${Zi(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Zi(t)}`})),Zf(n,nh(s))}function er(e,t=".env"){return Jd(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Hd="https://t.me/BotFather";async function sh(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function ih(e,t){let o=Date.now()+t,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function Gd(e={}){console.log(),console.log(se.bold(" Connect Telegram")),console.log(),console.log(se.dim(` 1. Open ${Hd}`)),console.log(se.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(se.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:t}=await xn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(t)try{let{spawn:b}=await import("child_process"),v=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(v,[Hd],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:o}=await xn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});o||(console.log(se.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await sh(o.trim());n||(console.log(se.red("\u2717 invalid or revoked")),process.exit(1)),console.log(se.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(se.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(se.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await xn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(se.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await xn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(se.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;vn(f,o.trim()),process.env[f]=o.trim();let p=await ye(b=>{Te(b,"channels.telegram.enabled",!0),Te(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let v=yo(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),Te(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(p.success||(console.log(se.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(se.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(se.dim(` Token stored in .env as ${f}`)),console.log(se.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(se.dim(" Daemon hot-reloaded.")):console.log(se.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await xn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(se.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(se.dim(" Waiting up to 90s..."));let y=await ih(o.trim(),9e4);if(!y){console.log(se.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(se.dim(" agentx config set notifications.destination.channel telegram")),console.log(se.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(se.dim(` agentx config set notifications.destination.accountId ${u}`));return}let $=await ye(b=>{Te(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{configPath:e.configPath});if(!$.success){console.log(se.red(` \u2717 failed to save destination: ${$.error}`));return}console.log(se.green(" \u2713 Default --notify target set")),console.log(se.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(se.dim(" From now on, --notify me resolves to this chat.")),$.reloaded&&console.log(se.dim(" Daemon hot-reloaded."))}import be from"chalk";import tr from"prompts";import{existsSync as nr,mkdirSync as rh,readdirSync as ah,readFileSync as zd}from"fs";import{resolve as or}from"path";var ch=".agentx/whatsapp-sessions";function lh(){let e=or(process.cwd(),".agentx/daemon.pid");if(!nr(e))return!1;try{let t=parseInt(zd(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function dh(e){if(!nr(e))return!1;try{return ah(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function gh(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(be.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(be.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;rh(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{t(be.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){t(be.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(u),t(be.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),t(be.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Yd(e={}){if(console.log(),console.log(be.bold(" Connect WhatsApp")),console.log(),lh()){console.log(be.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(be.dim(" agentx daemon stop")),console.log();let{cont:l}=await tr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(be.red(" Aborted")),process.exit(1))}let t=e.configPath||or(process.cwd(),"agentx.json");nr(t)||(console.log(be.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(zd(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||ch,s=or(process.cwd(),n),i=Object.keys(o.agents||{});i.length===0&&(console.log(be.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await tr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(be.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(dh(s)&&a){let{keep:l}=await tr({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(be.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await gh(s,g=>console.log(g))||(console.log(be.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ye(l=>{Te(l,"channels.whatsapp.enabled",!0),Te(l,"channels.whatsapp.sessionDir",n),Te(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(be.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(be.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(be.dim(` Session: ${n}`)),console.log(be.dim(" Start the daemon to begin receiving:")),console.log(be.dim(" agentx daemon start")),console.log(be.dim(" Add routes later with:")),console.log(be.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as mh}from"crypto";import Ae from"chalk";import Vd from"prompts";var js="agentx-mesh:",Os="//join/";function ph(e){return Buffer.from(e,"utf-8").toString("base64url")}function uh(e){return Buffer.from(e,"base64url").toString("utf-8")}function fh(e){return`${js}${Os}${ph(JSON.stringify(e))}`}function hh(e){if(!e.startsWith(`${js}${Os}`))throw new Error(`Not a mesh invite link \u2014 expected ${js}${Os}\u2026`);let t=e.slice(js.length+Os.length),o=JSON.parse(uh(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function yh(){return mh(32).toString("hex")}function wh(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function bh(e){return e?.node?.name||e?.node?.id||"node"}async function Kd(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Ae.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(t(s,"utf-8")),r=er("MESH_TOKEN");r||(r=yh(),vn("MESH_TOKEN",r),console.log(Ae.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||wh(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Vd({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(Ae.red(" Aborted")),process.exit(1)),a=d}let l=await ye(d=>{Te(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ae.red(` \u2717 ${l.error}`)),process.exit(1));let g=fh({url:a,token:r,name:bh(i),version:1});console.log(),console.log(Ae.bold(" Mesh invite")),console.log(),console.log(` ${Ae.cyan(g)}`),console.log(),console.log(Ae.dim(" Run on the other node:")),console.log(Ae.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Ae.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Xd(e,t={}){let o;try{o=hh(e)}catch(i){console.log(Ae.red(` \u2717 ${i.message}`)),process.exit(1)}let n=er("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:i}=await Vd({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Ae.red(" Aborted (keeping existing .env)")),process.exit(1))}vn("MESH_TOKEN",o.token);let s=await ye(i=>{Te(i,"mesh.enabled",!0);let r=yo(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Te(i,"mesh.peers",r)},{configPath:t.configPath});s.success||(console.log(Ae.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ae.green(" \u2713 Joined mesh")),console.log(Ae.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ae.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ae.dim(" Daemon hot-reloaded.")):console.log(Ae.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(Ae.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ae.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Ae.yellow(` Could not reach ${o.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Mo=new $h().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Mo.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await Gd({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Mo.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Yd({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Qd=Mo.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Qd.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Kd({url:e.url,configPath:e.config})});Qd.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await Xd(e,{configPath:t.config})});Mo.action(()=>{console.log(),console.log(Po.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Po.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Po.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Po.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Po.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Po.dim(" GitLab connect is the next slice.")),console.log()});ae();import{Command as kh}from"commander";import ue from"chalk";var Sn=new kh().name("usage").description("token usage analysis and reporting");Sn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=I(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(ue.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ue.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${ue.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${ue.red(String(s.totalErrors))}`),console.log(),console.log(ue.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ue.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ue.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ue.red(" Daemon not running. Start with: agentx daemon start")):console.log(ue.red(` ${e.message}`))}});Sn.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(ue.red(` Script not found: ${s}`)),console.log(ue.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ue.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ue.red(" Analysis failed. Is Python 3 installed?"))}});Sn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-HVVP22SA.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-44FEGUCB.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(ue.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${ue.dim("\xB7")} ${d}`);console.log(),console.log(ue.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ue.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(ue.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ue.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ue.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(ue.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=ue.dim(`${i.days}d`);console.log(` ${ue.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(ue.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as vh}from"commander";import $e from"chalk";import{readFileSync as xh}from"fs";import{resolve as Sh}from"path";ae();var Lt=new vh().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Lt.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{Gr(Sh(process.cwd(),".env"))}catch{}let t=Eh(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-BWB2FLOA.js");o(t)}catch(t){console.log($e.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log($e.dim(t.stack)),process.exit(1)}});function Eh(e,t){try{let o=I();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log($e.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log($e.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
406
|
+
`}function vn(e,t,o=".env"){let n=Bd(o),s=Jd(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:t,raw:`${e}=${Zi(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Zi(t)}`})),Zf(n,nh(s))}function er(e,t=".env"){return Jd(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Hd="https://t.me/BotFather";async function sh(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function ih(e,t){let o=Date.now()+t,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function Gd(e={}){console.log(),console.log(se.bold(" Connect Telegram")),console.log(),console.log(se.dim(` 1. Open ${Hd}`)),console.log(se.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(se.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:t}=await xn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(t)try{let{spawn:b}=await import("child_process"),v=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(v,[Hd],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:o}=await xn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});o||(console.log(se.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await sh(o.trim());n||(console.log(se.red("\u2717 invalid or revoked")),process.exit(1)),console.log(se.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(se.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(se.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await xn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(se.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await xn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(se.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;vn(f,o.trim()),process.env[f]=o.trim();let p=await ye(b=>{Te(b,"channels.telegram.enabled",!0),Te(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let v=yo(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),Te(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(p.success||(console.log(se.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(se.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(se.dim(` Token stored in .env as ${f}`)),console.log(se.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(se.dim(" Daemon hot-reloaded.")):console.log(se.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await xn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(se.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(se.dim(" Waiting up to 90s..."));let y=await ih(o.trim(),9e4);if(!y){console.log(se.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(se.dim(" agentx config set notifications.destination.channel telegram")),console.log(se.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(se.dim(` agentx config set notifications.destination.accountId ${u}`));return}let $=await ye(b=>{Te(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{configPath:e.configPath});if(!$.success){console.log(se.red(` \u2717 failed to save destination: ${$.error}`));return}console.log(se.green(" \u2713 Default --notify target set")),console.log(se.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(se.dim(" From now on, --notify me resolves to this chat.")),$.reloaded&&console.log(se.dim(" Daemon hot-reloaded."))}import be from"chalk";import tr from"prompts";import{existsSync as nr,mkdirSync as rh,readdirSync as ah,readFileSync as zd}from"fs";import{resolve as or}from"path";var ch=".agentx/whatsapp-sessions";function lh(){let e=or(process.cwd(),".agentx/daemon.pid");if(!nr(e))return!1;try{let t=parseInt(zd(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function dh(e){if(!nr(e))return!1;try{return ah(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function gh(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(be.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(be.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;rh(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{t(be.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){t(be.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(u),t(be.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),t(be.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Yd(e={}){if(console.log(),console.log(be.bold(" Connect WhatsApp")),console.log(),lh()){console.log(be.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(be.dim(" agentx daemon stop")),console.log();let{cont:l}=await tr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(be.red(" Aborted")),process.exit(1))}let t=e.configPath||or(process.cwd(),"agentx.json");nr(t)||(console.log(be.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(zd(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||ch,s=or(process.cwd(),n),i=Object.keys(o.agents||{});i.length===0&&(console.log(be.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await tr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(be.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(dh(s)&&a){let{keep:l}=await tr({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(be.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await gh(s,g=>console.log(g))||(console.log(be.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ye(l=>{Te(l,"channels.whatsapp.enabled",!0),Te(l,"channels.whatsapp.sessionDir",n),Te(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(be.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(be.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(be.dim(` Session: ${n}`)),console.log(be.dim(" Start the daemon to begin receiving:")),console.log(be.dim(" agentx daemon start")),console.log(be.dim(" Add routes later with:")),console.log(be.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as mh}from"crypto";import Ae from"chalk";import Vd from"prompts";var js="agentx-mesh:",Os="//join/";function ph(e){return Buffer.from(e,"utf-8").toString("base64url")}function uh(e){return Buffer.from(e,"base64url").toString("utf-8")}function fh(e){return`${js}${Os}${ph(JSON.stringify(e))}`}function hh(e){if(!e.startsWith(`${js}${Os}`))throw new Error(`Not a mesh invite link \u2014 expected ${js}${Os}\u2026`);let t=e.slice(js.length+Os.length),o=JSON.parse(uh(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function yh(){return mh(32).toString("hex")}function wh(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function bh(e){return e?.node?.name||e?.node?.id||"node"}async function Kd(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Ae.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(t(s,"utf-8")),r=er("MESH_TOKEN");r||(r=yh(),vn("MESH_TOKEN",r),console.log(Ae.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||wh(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Vd({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(Ae.red(" Aborted")),process.exit(1)),a=d}let l=await ye(d=>{Te(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ae.red(` \u2717 ${l.error}`)),process.exit(1));let g=fh({url:a,token:r,name:bh(i),version:1});console.log(),console.log(Ae.bold(" Mesh invite")),console.log(),console.log(` ${Ae.cyan(g)}`),console.log(),console.log(Ae.dim(" Run on the other node:")),console.log(Ae.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Ae.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Xd(e,t={}){let o;try{o=hh(e)}catch(i){console.log(Ae.red(` \u2717 ${i.message}`)),process.exit(1)}let n=er("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:i}=await Vd({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Ae.red(" Aborted (keeping existing .env)")),process.exit(1))}vn("MESH_TOKEN",o.token);let s=await ye(i=>{Te(i,"mesh.enabled",!0);let r=yo(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Te(i,"mesh.peers",r)},{configPath:t.configPath});s.success||(console.log(Ae.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ae.green(" \u2713 Joined mesh")),console.log(Ae.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ae.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ae.dim(" Daemon hot-reloaded.")):console.log(Ae.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(Ae.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ae.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Ae.yellow(` Could not reach ${o.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Mo=new $h().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Mo.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await Gd({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Mo.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Yd({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Qd=Mo.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Qd.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Kd({url:e.url,configPath:e.config})});Qd.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await Xd(e,{configPath:t.config})});Mo.action(()=>{console.log(),console.log(Po.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Po.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Po.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Po.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Po.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Po.dim(" GitLab connect is the next slice.")),console.log()});ae();import{Command as kh}from"commander";import ue from"chalk";var Sn=new kh().name("usage").description("token usage analysis and reporting");Sn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=I(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(ue.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ue.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${ue.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${ue.red(String(s.totalErrors))}`),console.log(),console.log(ue.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ue.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ue.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ue.red(" Daemon not running. Start with: agentx daemon start")):console.log(ue.red(` ${e.message}`))}});Sn.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(ue.red(` Script not found: ${s}`)),console.log(ue.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ue.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ue.red(" Analysis failed. Is Python 3 installed?"))}});Sn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-HVVP22SA.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-GUBHJFZS.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(ue.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${ue.dim("\xB7")} ${d}`);console.log(),console.log(ue.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ue.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(ue.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ue.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ue.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(ue.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=ue.dim(`${i.days}d`);console.log(` ${ue.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(ue.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as vh}from"commander";import $e from"chalk";import{readFileSync as xh}from"fs";import{resolve as Sh}from"path";ae();var Lt=new vh().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Lt.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{Gr(Sh(process.cwd(),".env"))}catch{}let t=Eh(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-3WVKEGRZ.js");o(t)}catch(t){console.log($e.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log($e.dim(t.stack)),process.exit(1)}});function Eh(e,t){try{let o=I();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log($e.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log($e.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
407
407
|
`)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:t||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}Lt.command("list").description("list configured boards").action(()=>{try{let e=I();if(!e.boards?.length){console.log($e.dim(`
|
|
408
408
|
No boards configured.
|
|
409
409
|
`));return}console.log();for(let t of e.boards){console.log(` ${$e.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log($e.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log($e.dim(` primary label: ${t.primaryToolLabel}`)),console.log($e.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log($e.red(` ${e.message}`)),process.exit(1)}});Lt.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,t)=>{try{En(o=>{if(Array.isArray(o.boards)||(o.boards=[]),o.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(t.projects).split(",").map(i=>i.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:t.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(t.days,10)||30,closedWindowDays:parseInt(t.closedDays,10)||30};return t.label&&(s.primaryToolLabel=t.label),o.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(o){console.log($e.red(` ${o.message}`)),process.exit(1)}});Lt.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,t)=>{try{En(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(t.name&&(s.name=t.name,i.push(`name="${t.name}"`)),t.projects){let r=String(t.projects).split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:r},i.push(`projects=${r.length}`)}if(t.label!==void 0&&(t.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=t.label,i.push(`label="${t.label}"`))),t.days&&(s.timeRangeDays=parseInt(t.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),t.closedDays&&(s.closedWindowDays=parseInt(t.closedDays,10)||s.closedWindowDays,i.push(`closed-days=${s.closedWindowDays}`)),i.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${i.join(", ")})`})}catch(o){console.log($e.red(` ${o.message}`)),process.exit(1)}});var sr=Lt.command("column").description("manage a board's columns (add / remove / edit / list)");sr.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(xh("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!o)throw new Error(`board "${e}" not found`);let n=o.columns||[];if(n.length===0){console.log($e.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let i=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${$e.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${$e.dim(i)}`)}}catch(t){console.log($e.red(` ${t.message}`)),process.exit(1)}});sr.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,t,o)=>{try{En(n=>{let i=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!i)throw new Error(`board "${e}" not found`);if(i.columns=i.columns||[],i.columns.find(a=>a.id===t))throw new Error(`column "${t}" already exists on board "${e}"`);let r={id:t,title:o.title,kind:o.kind,scopedPrefix:o.scopedPrefix};if(o.kind==="scoped-label"){if(!o.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=o.scoped}if(o.kind==="label"){if(!o.label)throw new Error("--label required for kind=label");r.mapsToLabel=o.label}return o.accent&&(r.accent=o.accent),i.columns.push(r),`column "${t}" added to board "${e}"`})}catch(n){console.log($e.red(` ${n.message}`)),process.exit(1)}});sr.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{En(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(r=>r.id!==t),s.columns.length===i)throw new Error(`column "${t}" not found`);return`column "${t}" removed from board "${e}"`})}catch(o){console.log($e.red(` ${o.message}`)),process.exit(1)}});Lt.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{En(t=>{if(!Array.isArray(t.boards)||t.boards.length===0)throw new Error("no boards configured");let o=t.boards.length;if(t.boards=t.boards.filter(n=>n.id!==e),t.boards.length===o)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(t){console.log($e.red(` ${t.message}`)),process.exit(1)}});function En(e){let{summary:t,backupPath:o}=ct(n=>e(n));console.log($e.green(`
|
|
@@ -416,7 +416,7 @@ ${k.content}
|
|
|
416
416
|
|
|
417
417
|
`),v="";if(e.facts!==!1){let{extractHints:k,resolveFacts:R,mergeRecords:C,renderFactsBlock:T,installPrompts:P,defaultSources:B,recordsFromEntries:L}=await import("./facts-X44PF73W.js");if(!a){let J=new Set;for(let Oe of o.listAgents())for(let ke of o.getAgentWiki(Oe).listArticles(Oe))ke.meta.type==="person"&&J.add(ke.meta.title);a=[...J]}let G=k(p.map(J=>({context:J.sourceContext,content:J.content,sender:typeof J.meta?.sender=="string"?J.meta.sender:void 0})),{known:a}),me=L(p);if(G.length>0||me.length>0){let J=B(),{records:Oe,results:ke}=G.length>0?await R(G,{sources:J}):{records:[],results:[]},M=C([...me,...Oe]);v=T(M);let Ye=[...me.length>0?[`entries:${me.length}`]:[],...ke.filter(ve=>ve.records.length>0).map(ve=>`${ve.source}:${ve.records.length}`)];console.log(m.dim(` Facts: ${G.length} entities \u2192 ${M.length} resolved${Ye.length?` (${Ye.join(" ")})`:""}`));for(let ve of P(ke,J))console.log(m.yellow(` ! ${ve.source} ${ve.kind} \u2014 would supply ${ve.provides.join(", ")}`)),console.log(m.dim(` ${ve.hint}`))}}let A=Aa(t,u,$,y.articles,b,p.length,v);console.log(m.dim(` Mode: ${rr(t)}`));let S=F(w.baseDir,"_tmp");bt(S,{recursive:!0});let x=F(S,"absorb-prompt.txt");io(x,A),console.log(m.dim(" Compiling with Claude..."));try{let k;try{k=so(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:go({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(M){if(k=M.stdout||"",!k)throw M}let R=k;try{let M=JSON.parse(k);R=M.result||M.content||"",R||(console.log(m.dim(` Claude envelope keys: ${Object.keys(M).join(", ")}`)),console.log(m.dim(` is_error: ${M.is_error}, stop_reason: ${M.stop_reason}`)))}catch{}let C,T=[],P=R.indexOf("{"),B=R.indexOf("["),L=P>=0&&(B<0||P<B)?P:B;if(L===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(R.slice(0,500)));continue}let G=R[L],me=G==="{"?"}":"]",J=0,Oe=-1;for(let M=L;M<R.length;M++)if(R[M]===G)J++;else if(R[M]===me&&(J--,J===0)){Oe=M+1;break}if(Oe===-1){console.log(m.red(" Unbalanced JSON"));continue}let ke=R.slice(L,Oe);try{let M=JSON.parse(ke);Array.isArray(M)?C=M:(C=M.articles||[],T=M.gaps||[])}catch(M){console.log(m.red(` JSON parse error: ${M.message}`)),console.log(m.dim(` First 300 chars: ${ke.slice(0,300)}`));continue}for(let M of C){let Ye=new Date().toISOString().slice(0,10),ve=l(M.sources||[],p);w.writeArticle(M.path,{title:M.title,type:M.type,related:Array.isArray(M.related)?M.related:void 0,tags:M.tags||[],owner:u,access:"public",created:Ye,lastUpdated:Ye,sources:M.sources||[],graphPath:ve},M.content,u);let Jt=M.type?m.magenta(`[${M.type}]`)+" ":"",_=Array.isArray(M.related)&&M.related.length?` \u2192 ${M.related.slice(0,3).join(", ")}${M.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${Jt}${M.path}: ${M.title}${m.dim(_)}`);let he=(M.tags||[]).slice(0,4).join(", ");he&&console.log(m.dim(` tags: ${he}`)),ve?.length&&(console.log(m.dim(` graphPath: ${ve.join(" \u203A ")}`)),d++),g++}if(T.length>0){console.log(),console.log(m.yellow(` Gaps detected (${T.length} missing pieces):`));for(let M of T)console.log(m.yellow(` ? ${M}`));try{let{QuestionStore:M}=await import("./questions-ZATLU5AW.js"),Ye=new M(ro(e.dir)).add(T.map(ve=>({kind:"article",agentId:u,path:"",subject:String(ve).slice(0,120),question:`No article yet for: ${String(ve).slice(0,160)}`})));Ye.added>0&&console.log(m.dim(` queued ${Ye.added} for follow-up (agentx wiki questions)`))}catch{}}w.rebuildIndex()}catch(k){console.log(m.red(` Absorb failed: ${k.message?.slice(0,200)}`)),k.stderr&&console.log(m.dim(String(k.stderr).slice(0,300))),k.stdout&&console.log(m.dim("stdout: "+String(k.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let u=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${u}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});Z.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--failures","also propose lessons from failures that recur across sessions").option("--min-sessions <n>","sessions a failure must recur in for --failures","3").option("--commit","judge and write proposals for review (default: dry-run)",!1).option("--budget <tokens>","max estimated tokens for the judge prompt","60000").action(async e=>{let t=Ch(e.since),o=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=o.find(a=>!n.includes(a));s&&(console.log(m.red(` Invalid memory type "${s}". Valid: ${n.join(", ")}`)),process.exit(1)),e.commit&&!e.via&&!e.model&&(console.log(m.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1)),console.log(),console.log(m.bold(" Memory \u2192 Wiki Promotion")),console.log();let i=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-VF5IWP5P.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!Ve(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(t??6048e5));i=a(d,{kinds:String(e.reviewKinds).split(",").map(p=>p.trim()).filter(Boolean)});let u=i.filter(p=>(p.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${u} seen in more than one session`));let f=i[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.memory.description.slice(0,84)}`))}finally{g.close()}}}if(e.failures){let a=Number(e.minSessions);(!Number.isInteger(a)||a<2)&&(console.log(m.red(` Invalid --min-sessions "${e.minSessions}". Use a whole number of 2 or more.`)),process.exit(1));let{loadFailedTraces:c,failuresToCandidates:l}=await import("./failure-candidates-RIXA3Y6D.js"),{default:g}=await import("better-sqlite3"),d=F(process.cwd(),".agentx/db.sqlite");if(!Ve(d))console.log(m.yellow(` --failures: no ${d}`));else{let u=new g(d,{readonly:!0});try{let f=c(u,{since:Date.now()-(t??6048e5)}),p=l(f,{minSessions:a});console.log(m.dim(` ${f.length} failed run(s) in window \u2192 ${p.length} failure(s) seen in ${a}+ sessions`));let w=p[0];w&&console.log(m.dim(` most recurrent (${w.occurrences} sessions, ${w.failure.runs} runs): ${w.memory.description.slice(0,84)}`)),i=[...i,...p]}finally{u.close()}}}let r=await ja({extraCandidates:i,wikiDir:e.dir?F(e.dir):void 0,memoryRoot:e.memoryDir?F(e.memoryDir):void 0,sinceMs:t,agentFilter:e.agent,types:o,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,budgetTokens:Number(e.budget)||void 0,log:a=>console.log(m.dim(` ${a}`))});if(r.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.clusters){let c=a.candidates[0],l=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${l} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${c.memory.description}`))}if(console.log(),r.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to judge and propose")),console.log();return}for(let a of r.proposed){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=`${a.agents.length} agent(s)${a.occurrences>1?`, seen in ${a.occurrences} sessions`:""}`;console.log(` ${m.green("?")} ${c}${a.path}: ${a.title} ${m.dim(`(${l})`)}`),console.log(m.dim(` proposal ${a.id}`))}for(let a of r.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(m.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(m.dim(` ! ${a}`));for(let a of r.errors)console.log(m.red(` x ${a}`));console.log(),console.log(r.errors.length?m.red(` ${r.proposed.length} proposed, ${r.errors.length} error(s)`):m.green(` ${r.proposed.length} proposed, ${r.skipped.length} skipped`)),r.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),r.errors.length&&process.exit(1)});var Is=Z.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function Cs(e){return e?F(e):F(process.cwd(),".agentx","wiki")}Is.command("list").description("list proposals (pending by default)").option("--all","include approved and rejected").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async e=>{let{listProposals:t}=await import("./proposals-O4B5LD5T.js"),o=t(Cs(e.dir),e.all?void 0:"pending");if(o.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of o){let s=n.evidence,i=s.sources.some(l=>l.kind==="failure")?" \xB7 from a recurring failure":"",r=`${s.agents.join(", ")}${s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:""} \xB7 ${s.sources.length} source(s)${i}`,a=n.status==="pending"?"":m.dim(` [${n.status}]`),c=n.replaces?m.yellow("update"):m.green("new");console.log(` ${m.cyan(n.id)}${a}`),console.log(` ${c} ${n.article.path}: ${n.article.title}`),console.log(m.dim(` ${r}`))}});Is.command("show").description("the proposed article and the evidence behind it").argument("<id>","proposal id").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{readProposal:o}=await import("./proposals-O4B5LD5T.js"),n=o(Cs(t.dir),e);if(!n){console.error(m.red(` no proposal "${e}"`)),process.exitCode=1;return}console.log(m.bold(` ${n.article.title}`)+m.dim(` \u2192 ${n.article.path} (${n.replaces?"updates an existing article":"new article"}, ${n.status})`)),console.log(),console.log(n.article.content.split(`
|
|
418
418
|
`).map(s=>` ${s}`).join(`
|
|
419
|
-
`)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let i=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,r=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${i}, ${s.updatedAt.slice(0,10)}${r})`)}`),console.log(m.dim(` ${s.description}`)),s.failure&&console.log(m.dim(` failing tool: ${s.failure.tool} \xB7 error: ${s.failure.errorClass} \xB7 ${s.failure.runs} run(s)`)),s.sessions?.length&&console.log(m.dim(` sessions: ${s.sessions.join(", ")}`)),s.tasks?.length&&console.log(m.dim(` runs: ${s.tasks.join(", ")} (agentx trace show <id>)`))}});Is.command("approve").description("write the proposed article into the shared wiki").argument("<id>","proposal id").option("--force","approve even if the article changed since the proposal").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{approveProposal:o}=await import("./promote-
|
|
419
|
+
`)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let i=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,r=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${i}, ${s.updatedAt.slice(0,10)}${r})`)}`),console.log(m.dim(` ${s.description}`)),s.failure&&console.log(m.dim(` failing tool: ${s.failure.tool} \xB7 error: ${s.failure.errorClass} \xB7 ${s.failure.runs} run(s)`)),s.sessions?.length&&console.log(m.dim(` sessions: ${s.sessions.join(", ")}`)),s.tasks?.length&&console.log(m.dim(` runs: ${s.tasks.join(", ")} (agentx trace show <id>)`))}});Is.command("approve").description("write the proposed article into the shared wiki").argument("<id>","proposal id").option("--force","approve even if the article changed since the proposal").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{approveProposal:o}=await import("./promote-7FMPZKXN.js"),n=o(Cs(t.dir),e,{force:t.force});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${n.proposal.article.path} written to the shared wiki`))});Is.command("reject").description("decline a proposal; its sources aren't judged again until they change").argument("<id>","proposal id").option("--reason <text>","why, kept with the decision").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{rejectProposal:o}=await import("./promote-7FMPZKXN.js"),n=o(Cs(t.dir),e,{reason:t.reason});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} rejected`))});function Ch(e){if(!e)return;let t=/^(\d+)\s*([smhd])$/.exec(e.trim());t||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let o=Number(t[1]),n=t[2];return o*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}Z.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",F(process.cwd(),".agentx/task-history")).option("--n <n>","number of messages to sample (newest first)","10").option("--out <path>","markdown output file (default: stdout)").option("--selector-model <m>","agentic selector model","haiku").option("--synth-model <m>","agentic synthesis model","sonnet").action(async e=>{let{agenticQuery:t}=await import("./query-6272PJPD.js"),{readdirSync:o,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=je(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),g=parseInt(e.n),d=i(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let u=[],f=o(d).sort().reverse();for(let y of f){let $=r(d,y),b=[];try{b=o($).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of b){if(u.length>=g)break;try{let A=JSON.parse(n(r($,v),"utf-8")),S=A.message||A.task?.message;typeof S=="string"&&S.trim().length>10&&u.push({id:A.id||v.replace(".json",""),message:S.trim(),ts:A.at||A.timestamp||y})}catch{}}if(u.length>=g)break}if(u.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${u.length} messages from ${c}`)),console.log(m.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(m.dim(` NEW: agenticQuery() catalog+wikilink walk (selector=${e.selectorModel}, synth=${e.synthModel})`)),console.log();let p=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${u.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let y=0;y<u.length;y++){let $=u[y];process.stdout.write(m.dim(` [${y+1}/${u.length}] querying... `));let v=l.findRelevant($.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
|
|
420
420
|
`)||"_(none returned)_",A;try{let S=await t($.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(S.status!=="ok")A=`_(status: ${S.status}${S.error?" \u2014 "+S.error:""})_`;else{let x=S.citations.map(k=>`\`${k.title}\` [${k.type||"?"}]`).join(", ");A=`**Answer:**
|
|
421
421
|
|
|
422
422
|
${S.answer}
|
|
@@ -501,7 +501,7 @@ Output (JSON array, one entry per input article, same order):
|
|
|
501
501
|
\u2026and ${R.length-10} more`:"",G=`${R.length} wiki gap(s) need you (${e.notifyTier}+):
|
|
502
502
|
${B}${L}
|
|
503
503
|
|
|
504
|
-
agentx wiki questions`,me=T?.daemon?.port??T?.port??18800;try{let J=await fetch(`http://127.0.0.1:${me}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:G})});console.log(J.ok?m.cyan(` Pushed ${R.length} question(s) to ${P.channel}.`):m.yellow(` Push failed (${J.status}) \u2014 questions are still queued.`))}catch(J){console.log(m.yellow(` Push failed (${String(J?.message??J).slice(0,80)}) \u2014 questions are still queued.`))}}}}});Z.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:t,reportFields:o,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:r}=await import("./seat-XNA2O6EO.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-X44PF73W.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=je(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=g(),$=c(d(f.getSharedStore().listEntries())),b=new Map($.map(T=>[T.name.toLowerCase().trim(),T])),v=0,A=0,S=[],x=!1;e:for(let T of p){let P=f.getAgentWiki(T);for(let B of P.listArticles(T)){if(v>=w)break e;if(B.meta.type!=="person")continue;let L=P.readArticle(B.path);if(!L)continue;v++;let G=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),t(L.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:T,op:"backfill"}});if(!G){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=o(L.meta.type,G.answers).missing.filter(_=>i.includes(_));if(J.length===0)continue;let{records:Oe,results:ke}=await a([{name:L.meta.title,type:"person"}],{sources:y}),M=b.get(L.meta.title.toLowerCase().trim());if(!x){for(let _ of l(ke,y))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));x=!0}let Ye=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,he])=>[_,he.value]))}]:[],...Oe]);if(Ye.length===0)continue;let{content:ve,edits:Jt}=u(L.content,Ye[0],J);if(Jt.length!==0){for(let _ of Jt)S.push({agent:T,article:L.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(B.path,L.meta,ve,T)?A++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let k=["agent","article","field","action","got"],R=k.map(T=>Math.max(T.length,...S.map(P=>String(P[T]).length))),C=T=>T.map((P,B)=>String(P).padEnd(R[B])).join(" ");console.log(),console.log(m.bold(C(k)));for(let T of S)console.log(C(k.map(P=>T[P])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${A} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});Z.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:t}=await import("./questions-ZATLU5AW.js"),{TIER_RANK:o}=await import("./article-fields-PITN4NHA.js"),n=new t(ro(e.dir)).list(e.status);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(m.green(` no ${e.status} questions`));return}n.sort((s,i)=>(o[s.tier??"furniture"]??9)-(o[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});Z.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,t,o)=>{let{QuestionStore:n}=await import("./questions-ZATLU5AW.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(ro(o.dir)),a=r.list().find(w=>(w.id===e||w.id.startsWith(e))&&w.status!=="open"&&w.kind==="contradiction");if(a&&!r.list("open").some(w=>w.id===e||w.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(o.dismiss){try{let w=r.resolve(e,"dismissed");console.log(w?m.dim(` dismissed: ${w.question}`):m.red(` no question matching "${e}"`))}catch(w){console.log(m.red(` ${w?.message??w}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!t){console.log(m.red(" give a value, or pass --dismiss"));return}let c=r.list("open").find(w=>w.id===e||w.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:w}=await import("./ledger-CH7R756S.js"),y=new w(ro(o.dir));try{let $=y.get(c.factId);if($){let b=y.write({subject:$.subject,attribute:$.attribute,value:t,source:"owner said",verifiedBy:"operator",volatility:$.volatility},{confirmedBy:"operator"});console.log(m.green(` ${b.status}: ${$.id} ${$.subject} \xB7 ${$.attribute}: ${b.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch($){$?.name!=="LedgerCorruptError"&&console.log(m.red(` ${$?.message??$}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}r.resolve(c.id,"answered",t),console.log(m.green(` answered: ${c.question}`));return}let l;try{l=r.resolve(e,"answered",t)}catch(w){console.log(m.red(` ${w?.message??w}`)),console.log(m.yellow(" nothing changed.")),process.exitCode=1;return}if(!l){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${l.question}`)),l.kind!=="field"||!l.field||!l.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[l.field]){console.log(m.dim(` recorded against ${l.path}. "${l.field}" has no fixed slot, so nothing was rewritten.`));return}let d=je(o.dir,o.mode).getAgentWiki(l.agentId),u=d.readArticle(l.path);if(!u){console.log(m.yellow(` article gone: ${l.path}`));return}let f=s(u.content,l.field,`${t} (answered by operator)`);if(!f){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=d.writeArticle(l.path,u.meta,f.content,l.agentId);console.log(p?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.path}`))});Z.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:t,entryTriageQuestions:o,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:i}=await import("./seat-XNA2O6EO.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=je(e.dir,"graph").getSharedStore(),p=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:y,backlog:$}=r(p,w),b=a(y,L=>L.absorbed,parseInt(e.n)),v={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},A=[],S=0,x=Date.now();if(e.load){let{readFileSync:L}=await import("fs");A.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${$} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let G=await i(t,n(L),o,{features:{source:L.source??"",absorbed:L.absorbed}});if(!G){S++;continue}let me=G.answers;A.push({entry:L,verdict:s(G.answers,v),citeWorthy:me.citeWorthy?.noul})}if(A.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let k=c(A,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),R=l(A,"seat","seat"),C=d(R,{minN:50}),T=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:k,calibration:C,failures:S,elapsed:T},null,2));return}let P=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${k.n} (${k.positives} kept by absorb, ${k.negatives} passed over)`),console.log(` recall ${P(k.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P(k.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P(k.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${k.lostPositives>0?m.yellow(`lost ${k.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in C)||!C.insufficient)&&console.log(` ECE ${C.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),k.lostPositives>0){let L=k.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let B=k.positiveMeans;if(console.log(m.dim(` positives avg: worth ${B.worth.toFixed(2)} \xB7 durability ${B.durability.toFixed(2)} \xB7 typeConf ${B.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${T}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let L=parseFloat(e.minRecall),{best:G,points:me}=g(A,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${me.length} policies, recall floor ${P(L)})`)),G)console.log(` best: ${G.requireTyped?`typed & type>=${G.minType}`:"type gate OFF"} worth>=${G.minWorth} durability>=${G.minDurability}`),console.log(` recall ${P(G.recall)} \xB7 filtered ${P(G.filtered)} \xB7 precision ${P(G.precision)} \xB7 lost ${G.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${P(L)} recall \u2014 not even keeping everything typed.`));let J=me.slice().sort((Oe,ke)=>ke.recall-Oe.recall)[0];J&&console.log(m.dim(` Best recall available: ${P(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${P(J.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});Z.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,t)=>{let o=F(process.cwd(),e);Ve(o)||(console.log(m.red(` archive not found: ${o}`)),process.exit(1));let n=t.dir?F(process.cwd(),t.dir):F(process.cwd(),".agentx/wiki");Ve(n)&&!t.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=F(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",o];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function Ph(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}im();import{Command as Mh}from"commander";import D from"chalk";import{resolve as Ns}from"path";import{existsSync as Lh}from"fs";ae();var Uo=new Mh().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Uo.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let t=I();if(!t.graph?.enabled){console.log(D.yellow(" graph.enabled is false \u2014 nothing to review"));return}let o=e.agent||t.graph.reviewAgent||t.graph.draftAgent;if(!o){console.log(D.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!t.agents?.[o]){console.log(D.red(` agent "${o}" not in config`));return}let n=(e.daemonUrl||t.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new vt({baseDir:Ns(process.cwd(),t.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(D.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(D.bold(` Graph review \u2014 ${r.length} pending`)),console.log(D.dim(` Reviewer: ${o} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,u=0;for(let p=0;p<r.length;p++){let w=r[p],y=Mn(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${D.cyan(w.msgHash.slice(0,8))} ${D.dim(y)} ... `);let $=Fh(w,a,c),b=null;try{b=await Uh(n,o,$,t.dashboard?.token)}catch(S){u++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(D.red("ERR no decision"));continue}let v=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(A)),e.dryRun)l++;else try{qh(i,w,a,c,o),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:o,reviewReason:A}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),u++}else v==="reject"?(console.log(D.red("REJECT")+" "+D.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:o,reviewReason:A}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(A||v)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(D.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${u} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});Uo.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let t=I();if(!t.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let o=Ns(process.cwd(),t.graph.baseDir);if(!Lh(o)){console.log(D.yellow(` ${o} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-5VGHWPBW.js"),s=new vt({baseDir:o,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(D.dim(" "),...a)});console.log(),console.log(D.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(D.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});Uo.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let t=I();if(!t.graph?.enabled){console.log(D.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let o=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new vt({baseDir:Ns(process.cwd(),t.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(k=>k.id));console.log(),console.log(D.bold(` graph pull \u2190 ${o}`));let l,g,d;try{let k=await fetch(`${o}/graph/schema`,{headers:s});if(!k.ok)throw new Error(`schema HTTP ${k.status}`);l=(await k.json()).schema;let C=await fetch(`${o}/graph/nodes`,{headers:s});if(!C.ok)throw new Error(`nodes HTTP ${C.status}`);g=(await C.json()).nodes||[];let T=await fetch(`${o}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!T.ok)throw new Error(`classifications HTTP ${T.status}`);d=(await T.json()).classifications||[]}catch(k){console.log(D.red(` fetch failed: ${k.message}`));return}let u=r.levels.map(k=>k.id).join(","),f=l?.levels?.map(k=>k.id).join(","),p=u===f;p?console.log(D.dim(` schema matches (${r.levels.length} levels)`)):(console.log(D.yellow(" \u26A0 schema levels differ:")),console.log(D.dim(` local: ${u}`)),console.log(D.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(D.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(D.yellow(" keeping local schema; node import may fail if levels disagree")));let w=p?r:l,y=new Map;w.levels.forEach((k,R)=>y.set(k.id,R));let $=[...g].sort((k,R)=>(y.get(k.level)??99)-(y.get(R.level)??99)),b=0,v=0,A=0;for(let k of $){if(c.has(k.id)){v++;continue}if(e.dryRun){b++,c.add(k.id);continue}try{i.addNode({...k,createdBy:k.createdBy?`${k.createdBy} (sync)`:`sync:${o}`}),c.add(k.id),b++}catch(R){A++,console.log(D.yellow(` skip node ${k.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${A} failed`));let S=0,x=0;for(let k of d)if(!(!k.msgHash||!Array.isArray(k.path))){if(i.getFingerprint(k.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint(k.msgHash,{path:k.path,leaf:k.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${x} already-present`)),console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` \u2713 pulled from ${o}`)),console.log()});function Fh(e,t,o){let n={};for(let r of o)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=t.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
|
|
504
|
+
agentx wiki questions`,me=T?.daemon?.port??T?.port??18800;try{let J=await fetch(`http://127.0.0.1:${me}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:G})});console.log(J.ok?m.cyan(` Pushed ${R.length} question(s) to ${P.channel}.`):m.yellow(` Push failed (${J.status}) \u2014 questions are still queued.`))}catch(J){console.log(m.yellow(` Push failed (${String(J?.message??J).slice(0,80)}) \u2014 questions are still queued.`))}}}}});Z.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:t,reportFields:o,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:r}=await import("./seat-XNA2O6EO.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-X44PF73W.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=je(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=g(),$=c(d(f.getSharedStore().listEntries())),b=new Map($.map(T=>[T.name.toLowerCase().trim(),T])),v=0,A=0,S=[],x=!1;e:for(let T of p){let P=f.getAgentWiki(T);for(let B of P.listArticles(T)){if(v>=w)break e;if(B.meta.type!=="person")continue;let L=P.readArticle(B.path);if(!L)continue;v++;let G=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),t(L.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:T,op:"backfill"}});if(!G){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=o(L.meta.type,G.answers).missing.filter(_=>i.includes(_));if(J.length===0)continue;let{records:Oe,results:ke}=await a([{name:L.meta.title,type:"person"}],{sources:y}),M=b.get(L.meta.title.toLowerCase().trim());if(!x){for(let _ of l(ke,y))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));x=!0}let Ye=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,he])=>[_,he.value]))}]:[],...Oe]);if(Ye.length===0)continue;let{content:ve,edits:Jt}=u(L.content,Ye[0],J);if(Jt.length!==0){for(let _ of Jt)S.push({agent:T,article:L.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(B.path,L.meta,ve,T)?A++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let k=["agent","article","field","action","got"],R=k.map(T=>Math.max(T.length,...S.map(P=>String(P[T]).length))),C=T=>T.map((P,B)=>String(P).padEnd(R[B])).join(" ");console.log(),console.log(m.bold(C(k)));for(let T of S)console.log(C(k.map(P=>T[P])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${A} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});Z.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:t}=await import("./questions-ZATLU5AW.js"),{TIER_RANK:o}=await import("./article-fields-PITN4NHA.js"),n=new t(ro(e.dir)).list(e.status);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(m.green(` no ${e.status} questions`));return}n.sort((s,i)=>(o[s.tier??"furniture"]??9)-(o[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});Z.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,t,o)=>{let{QuestionStore:n}=await import("./questions-ZATLU5AW.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(ro(o.dir)),a=r.list().find(w=>(w.id===e||w.id.startsWith(e))&&w.status!=="open"&&w.kind==="contradiction");if(a&&!r.list("open").some(w=>w.id===e||w.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(o.dismiss){try{let w=r.resolve(e,"dismissed");console.log(w?m.dim(` dismissed: ${w.question}`):m.red(` no question matching "${e}"`))}catch(w){console.log(m.red(` ${w?.message??w}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!t){console.log(m.red(" give a value, or pass --dismiss"));return}let c=r.list("open").find(w=>w.id===e||w.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:w}=await import("./ledger-CH7R756S.js"),y=new w(ro(o.dir));try{let $=y.get(c.factId);if($){let b=y.write({subject:$.subject,attribute:$.attribute,value:t,source:"owner said",verifiedBy:"operator",volatility:$.volatility},{confirmedBy:"operator"});console.log(m.green(` ${b.status}: ${$.id} ${$.subject} \xB7 ${$.attribute}: ${b.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch($){$?.name!=="LedgerCorruptError"&&console.log(m.red(` ${$?.message??$}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}r.resolve(c.id,"answered",t),console.log(m.green(` answered: ${c.question}`));return}let l;try{l=r.resolve(e,"answered",t)}catch(w){console.log(m.red(` ${w?.message??w}`)),console.log(m.yellow(" nothing changed.")),process.exitCode=1;return}if(!l){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${l.question}`)),l.kind!=="field"||!l.field||!l.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[l.field]){console.log(m.dim(` recorded against ${l.path}. "${l.field}" has no fixed slot, so nothing was rewritten.`));return}let d=je(o.dir,o.mode).getAgentWiki(l.agentId),u=d.readArticle(l.path);if(!u){console.log(m.yellow(` article gone: ${l.path}`));return}let f=s(u.content,l.field,`${t} (answered by operator)`);if(!f){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=d.writeArticle(l.path,u.meta,f.content,l.agentId);console.log(p?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.path}`))});Z.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:t,entryTriageQuestions:o,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:i}=await import("./seat-XNA2O6EO.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=je(e.dir,"graph").getSharedStore(),p=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:y,backlog:$}=r(p,w),b=a(y,L=>L.absorbed,parseInt(e.n)),v={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},A=[],S=0,x=Date.now();if(e.load){let{readFileSync:L}=await import("fs");A.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${$} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let G=await i(t,n(L),o,{features:{source:L.source??"",absorbed:L.absorbed}});if(!G){S++;continue}let me=G.answers;A.push({entry:L,verdict:s(G.answers,v),citeWorthy:me.citeWorthy?.noul})}if(A.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let k=c(A,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),R=l(A,"seat","seat"),C=d(R,{minN:50}),T=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:k,calibration:C,failures:S,elapsed:T},null,2));return}let P=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${k.n} (${k.positives} kept by absorb, ${k.negatives} passed over)`),console.log(` recall ${P(k.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P(k.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P(k.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${k.lostPositives>0?m.yellow(`lost ${k.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in C)||!C.insufficient)&&console.log(` ECE ${C.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),k.lostPositives>0){let L=k.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let B=k.positiveMeans;if(console.log(m.dim(` positives avg: worth ${B.worth.toFixed(2)} \xB7 durability ${B.durability.toFixed(2)} \xB7 typeConf ${B.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${T}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let L=parseFloat(e.minRecall),{best:G,points:me}=g(A,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${me.length} policies, recall floor ${P(L)})`)),G)console.log(` best: ${G.requireTyped?`typed & type>=${G.minType}`:"type gate OFF"} worth>=${G.minWorth} durability>=${G.minDurability}`),console.log(` recall ${P(G.recall)} \xB7 filtered ${P(G.filtered)} \xB7 precision ${P(G.precision)} \xB7 lost ${G.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${P(L)} recall \u2014 not even keeping everything typed.`));let J=me.slice().sort((Oe,ke)=>ke.recall-Oe.recall)[0];J&&console.log(m.dim(` Best recall available: ${P(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${P(J.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});Z.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,t)=>{let o=F(process.cwd(),e);Ve(o)||(console.log(m.red(` archive not found: ${o}`)),process.exit(1));let n=t.dir?F(process.cwd(),t.dir):F(process.cwd(),".agentx/wiki");Ve(n)&&!t.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=F(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",o];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function Ph(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}im();import{Command as Mh}from"commander";import D from"chalk";import{resolve as Ns}from"path";import{existsSync as Lh}from"fs";ae();var Uo=new Mh().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Uo.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let t=I();if(!t.graph?.enabled){console.log(D.yellow(" graph.enabled is false \u2014 nothing to review"));return}let o=e.agent||t.graph.reviewAgent||t.graph.draftAgent;if(!o){console.log(D.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!t.agents?.[o]){console.log(D.red(` agent "${o}" not in config`));return}let n=(e.daemonUrl||t.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new vt({baseDir:Ns(process.cwd(),t.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(D.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(D.bold(` Graph review \u2014 ${r.length} pending`)),console.log(D.dim(` Reviewer: ${o} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,u=0;for(let p=0;p<r.length;p++){let w=r[p],y=Mn(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${D.cyan(w.msgHash.slice(0,8))} ${D.dim(y)} ... `);let $=Fh(w,a,c),b=null;try{b=await Uh(n,o,$,t.dashboard?.token)}catch(S){u++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(D.red("ERR no decision"));continue}let v=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(A)),e.dryRun)l++;else try{qh(i,w,a,c,o),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:o,reviewReason:A}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),u++}else v==="reject"?(console.log(D.red("REJECT")+" "+D.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:o,reviewReason:A}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(A||v)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(D.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${u} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});Uo.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let t=I();if(!t.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let o=Ns(process.cwd(),t.graph.baseDir);if(!Lh(o)){console.log(D.yellow(` ${o} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-KOMPDC6U.js"),s=new vt({baseDir:o,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(D.dim(" "),...a)});console.log(),console.log(D.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(D.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});Uo.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let t=I();if(!t.graph?.enabled){console.log(D.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let o=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new vt({baseDir:Ns(process.cwd(),t.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(k=>k.id));console.log(),console.log(D.bold(` graph pull \u2190 ${o}`));let l,g,d;try{let k=await fetch(`${o}/graph/schema`,{headers:s});if(!k.ok)throw new Error(`schema HTTP ${k.status}`);l=(await k.json()).schema;let C=await fetch(`${o}/graph/nodes`,{headers:s});if(!C.ok)throw new Error(`nodes HTTP ${C.status}`);g=(await C.json()).nodes||[];let T=await fetch(`${o}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!T.ok)throw new Error(`classifications HTTP ${T.status}`);d=(await T.json()).classifications||[]}catch(k){console.log(D.red(` fetch failed: ${k.message}`));return}let u=r.levels.map(k=>k.id).join(","),f=l?.levels?.map(k=>k.id).join(","),p=u===f;p?console.log(D.dim(` schema matches (${r.levels.length} levels)`)):(console.log(D.yellow(" \u26A0 schema levels differ:")),console.log(D.dim(` local: ${u}`)),console.log(D.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(D.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(D.yellow(" keeping local schema; node import may fail if levels disagree")));let w=p?r:l,y=new Map;w.levels.forEach((k,R)=>y.set(k.id,R));let $=[...g].sort((k,R)=>(y.get(k.level)??99)-(y.get(R.level)??99)),b=0,v=0,A=0;for(let k of $){if(c.has(k.id)){v++;continue}if(e.dryRun){b++,c.add(k.id);continue}try{i.addNode({...k,createdBy:k.createdBy?`${k.createdBy} (sync)`:`sync:${o}`}),c.add(k.id),b++}catch(R){A++,console.log(D.yellow(` skip node ${k.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${A} failed`));let S=0,x=0;for(let k of d)if(!(!k.msgHash||!Array.isArray(k.path))){if(i.getFingerprint(k.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint(k.msgHash,{path:k.path,leaf:k.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${x} already-present`)),console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` \u2713 pulled from ${o}`)),console.log()});function Fh(e,t,o){let n={};for(let r of o)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=t.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
|
|
505
505
|
`),i=JSON.stringify(e.proposedAxes||{},null,2);return["You are reviewing a pending intent classification. Decide whether it is reasonable.","","--- MESSAGE (first 500 chars) ---",(e.preview||"").slice(0,500),`channel: ${e.channel||"?"} \xB7 sender: ${e.sender||"?"}`,"","--- PROPOSED PATH ---",e.path.join(" \u203A "),"","--- PROPOSED AXES (per new node) ---",i,"","--- CURRENT NODES BY LEVEL (first 10 per level) ---",s,"","--- YOUR JOB ---","Decide one of:"," approve \u2014 the path is right and the axes make sense for the message"," reject \u2014 the path is wrong (e.g. the message is NOT about the proposed org/topic, or the axes are bogus)"," skip \u2014 you can't confidently decide; leave it for a human","",'BEFORE you decide, you MAY call `agentx wiki query` (via Bash) to check institutional context \u2014 e.g. "is there an article for this project" or "who is this person". This is optional; don\'t call it for obvious cases.',"","Bias toward reject over approve when uncertain. A wrong approval pollutes the graph; a wrong rejection just keeps the entry pending.","","Return EXACTLY one JSON object on one line, no prose, no fences:",' {"decision":"approve"|"reject"|"skip","reason":"one sentence"}'].join(`
|
|
506
506
|
`)}async function Uh(e,t,o,n){let s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);let i=new AbortController,r=setTimeout(()=>i.abort(),12e4);try{let a=await fetch(`${e}/task`,{method:"POST",headers:s,body:JSON.stringify({agent:t,message:o,context:{channel:"a2a",sender:"graph-review"}}),signal:i.signal});if(!a.ok)throw new Error(`daemon /task HTTP ${a.status}`);let c=await a.json();if(c?.error)throw new Error(String(c.error));return Wr((c?.content||"").toString())}finally{clearTimeout(r)}}function qh(e,t,o,n,s){e.commitNodesAlongPath(t.path,t.proposedAxes||{},o,s),e.setFingerprint(t.msgHash,{path:t.path,leaf:t.leaf||{}})}function ar(){let e=I();if(!e.graph?.baseDir)return console.log(D.red(" graph.baseDir is not configured")),null;let t=Ns(process.cwd(),e.graph.baseDir);return{store:new vt({baseDir:t}),baseDir:t}}var cr=Uo.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");cr.command("next").alias("list").description("what to check next, spread across the confidence range").option("--n <n>","how many","10").option("--strategy <s>","stratified | uncertain","stratified").option("--json").action(async e=>{let t=ar();if(!t)return;let{ReviewStore:o,buildQueue:n}=await import("./review-store-PW3OBGZQ.js"),s=t.store.listAllClassifications(),i=new o(t.baseDir).load(),r=n(s,new Set(i.keys()),{n:parseInt(e.n),strategy:e.strategy});if(e.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(D.green(" nothing left unreviewed"));return}let a=t.store.loadNodes().nodes;console.log();for(let c of r){let l=typeof c.confidence=="number"?c.confidence.toFixed(2):D.dim("cache");console.log(` ${D.cyan(c.msgHash.slice(0,8))} ${l.padStart(5)} ${D.bold(Mn(c.path,a)||c.path.join(" \u203A "))}`),c.preview&&console.log(D.dim(` ${String(c.preview).replace(/\s+/g," ").slice(0,96)}`))}console.log(),console.log(D.dim(` ${r.length} to check (${e.strategy}).`)),console.log(D.dim(" agentx graph label mark <hash> correct|wrong|unsure [--path a/b/c]"))});cr.command("mark <hash> <verdict>").description("record a verdict: correct | wrong | unsure").option("--path <p>","for `wrong`: the path it should have been, slash-separated").option("--note <t>","why, when it is worth remembering").option("--by <who>","reviewer","operator").action(async(e,t,o)=>{if(!["correct","wrong","unsure"].includes(t)){console.log(D.red(" verdict must be correct | wrong | unsure"));return}let n=ar();if(!n)return;let{ReviewStore:s}=await import("./review-store-PW3OBGZQ.js"),r=n.store.listAllClassifications().filter(l=>l.msgHash===e||l.msgHash.startsWith(e));if(r.length===0){console.log(D.red(` no classification matching "${e}"`));return}if(r.length>1){console.log(D.red(` "${e}" matches ${r.length} rows \u2014 use more characters`));return}new s(n.baseDir).record({msgHash:r[0].msgHash,verdict:t,correctPath:o.path?String(o.path).split("/").filter(Boolean):void 0,note:o.note,reviewer:o.by});let c=n.store.loadNodes().nodes;console.log(D.green(` ${t}: ${Mn(r[0].path,c)||r[0].path.join(" \u203A ")}`)),o.path&&console.log(D.dim(` should have been: ${o.path}`))});cr.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let t=ar();if(!t)return;let{ReviewStore:o,labelStats:n}=await import("./review-store-PW3OBGZQ.js"),s=t.store.listAllClassifications(),i=new o(t.baseDir).load(),r=n(s,i);if(e.json){console.log(JSON.stringify(r,null,2));return}let a=c=>`${(c*100).toFixed(1)}%`;if(console.log(),console.log(` classifications ${r.classifications}`),console.log(` reviewed ${r.reviewed} (${r.correct} correct \xB7 ${r.wrong} wrong \xB7 ${r.unsure} unsure)`),r.correct+r.wrong>0&&console.log(` accuracy ${a(r.accuracy)}`),console.log(` calibratable ${r.calibratable} ${D.dim("reviewed rows that carry a confidence")}`),r.byBin.length>0){console.log(),console.log(D.bold(" reliability \u2014 confidence vs how often it was right"));for(let c of r.byBin){let l=Math.abs(parseFloat(c.bin.split("-")[0])+.05-c.accuracy),g=c.n>=5&&l>.15?D.yellow(" \u2190 miscalibrated"):"";console.log(` ${c.bin} n=${String(c.n).padStart(3)} right ${a(c.accuracy).padStart(6)}${g}`)}}console.log(),r.calibratable<100?console.log(D.dim(` ${100-r.calibratable} more labelled rows before a calibration report means anything.`)):console.log(D.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as zh}from"commander";import V from"chalk";import{Command as rg}from"commander";import le from"chalk";import{existsSync as Wh}from"fs";import{resolve as Bh}from"path";import Jh from"better-sqlite3";function Hh(e){if(!e)return;let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(t){let n=Number(t[1]),s=t[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let o=Number(e);if(Number.isFinite(o)&&o>0)return o;console.log(le.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function Gh(e){let t=Bh(process.cwd(),e);return Wh(t)||(console.log(le.red(` No db at ${t}`)),process.exit(1)),new Jh(t,{readonly:!0})}var ag=new rg().name("extract").description("mine recurring user activity into procedure drafts (dry-run by default)").option("--path <path>","SQLite db path",".agentx/db.sqlite").option("--since <duration>","activity window, e.g. 24h, 7d, or ms epoch","7d").option("--agent <id>","only mine one agent's activity").option("--min-occurrences <n>","recurrences before a pattern becomes a draft",String(nn)).option("--max <n>","max clusters distilled per run",String(qn)).option("--via <agentId>","route the LLM call through a running agent \u2014 uses the agent's own session").option("--model <model>","direct Anthropic API model \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--commit","write drafts and persist recurrence counts",!1).action(async e=>{e.commit&&!e.via&&!e.model&&(console.log(le.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let t=Gh(e.path),o=await Oa(t,{since:Hh(e.since),agentId:e.agent,sessions:new Kr(process.cwd()),minOccurrences:Number(e.minOccurrences)||nn,max:Number(e.max)||qn,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(le.dim(` ${n}`))});console.log(),console.log(` ${o.episodes} episode(s) \u2192 ${o.clusters} cluster(s), ${o.ready.length} at threshold`);for(let n of o.ready)console.log(` ${le.cyan(n.key)} ${le.bold(`\xD7${n.count}`)} ${le.dim(n.status)}`),n.sampleMessage&&console.log(le.dim(` "${n.sampleMessage.slice(0,100)}"`));if(o.nearMisses.length){console.log(le.dim(`
|
|
507
507
|
near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of o.nearMisses.slice(0,5))console.log(le.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of o.drafted)console.log(le.green(` \u2713 draft written: ${n.id}`)+le.dim(` (${n.count} occurrences)`));for(let n of o.skipped)console.log(le.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of o.warnings)console.log(le.yellow(` \u26A0 ${n}`));o.dryRun?console.log(le.dim(`
|
|
@@ -630,7 +630,7 @@ Restart the daemon to activate.
|
|
|
630
630
|
dist/
|
|
631
631
|
*.log
|
|
632
632
|
.env
|
|
633
|
-
`}import{Command as aw}from"commander";import Ne from"chalk";import{writeFileSync as cw,mkdirSync as lw,existsSync as Gs,readFileSync as qg,appendFileSync as Wg}from"fs";import{resolve as Ko,dirname as Hg}from"path";import{homedir as Er}from"os";var Gg=new aw().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-
|
|
633
|
+
`}import{Command as aw}from"commander";import Ne from"chalk";import{writeFileSync as cw,mkdirSync as lw,existsSync as Gs,readFileSync as qg,appendFileSync as Wg}from"fs";import{resolve as Ko,dirname as Hg}from"path";import{homedir as Er}from"os";var Gg=new aw().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-GUBHJFZS.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=mw(o);break;case"bash":s=yw(o);break;case"fish":s=ww(o);break;default:console.error(Ne.red(`unsupported shell: ${n}`)),console.error(Ne.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?Ko(String(e.output)):dw(n);lw(Hg(i),{recursive:!0}),cw(i,s),console.log(Ne.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),gw(n,i,!!e.yes)});function dw(e){let t=Er();switch(e){case"zsh":return Ko(t,".zsh","completions","_agentx");case"bash":return Ko(t,".bash_completion.d","agentx.bash");case"fish":return Ko(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function gw(e,t,o){if(e==="zsh"){let n=Ko(Er(),".zshrc"),s=Hg(t),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Gs(n)?qg(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Ne.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&Gs(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Wg(n,g.join(`
|
|
634
634
|
`)+`
|
|
635
635
|
`),console.log(Ne.green("\u2713 Patched ~/.zshrc")),console.log(Ne.dim("Reload your shell: exec zsh"));return}console.log(Ne.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Ne.cyan(` ${i}`)),l&&console.log(Ne.cyan(` ${r}`)),console.log(),console.log(Ne.dim("Then reload: exec zsh")),console.log(Ne.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Ko(Er(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((Gs(n)?qg(n,"utf-8"):"").includes(t)){console.log(Ne.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&Gs(n)){Wg(n,`
|
|
636
636
|
# agentx completion
|
|
@@ -646,4 +646,4 @@ ${bw({...t,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
|
|
|
646
646
|
${o.url}`)}catch(t){console.error(Qo.red(` ${t.message}`)),process.exitCode=1}});_n.command("draft <file>").description("turn a draft JSON file ({category, title, fields}) into a pre-filled issue form link; '-' reads stdin").requiredOption("--model <model>","the model that wrote the draft").option("--models <pathOrUrl>","model list to read",jr).action(async(e,t)=>{try{let o=await Ir(t.models);if(!Or(t.model,o)){console.log(Tr(t.model,o)),process.exitCode=1;return}let n=e==="-"?await vw():await kw(e,"utf8"),s=JSON.parse(n),{version:i}=await Un(),r=Kg({...s,fields:s.fields??{}},{model:t.model,version:i??"unknown"});console.log(r)}catch(o){console.error(Qo.red(` ${o.message}`)),process.exitCode=1}});async function vw(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function Sj(){let e=await Un(),t=new xw().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");t.hook("preAction",(o,n)=>{let s=Wc(n);Bc(s)&&qc("cli",s)});for(let o of[yl,ul,Mo,vo,Eo,Qe,Lc,Yt,cs,wt,Mt,Pt,as,Ag,Rt,Ml,Gl,bn,nd,ad,cd,Ed,Td,Id,Ro,Sn,Cg,mn,Ot,Gg,_n])t.addCommand(o);for(let o of Qg)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=Qg.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Sw(o,74," "),""].join(`
|
|
647
647
|
`)}),t}var Qg=[Z,Uo,qt,it,un,_o,Ge,$t,Lt,no,Jo,Ho,Ct,Be,To,As,xg,Sg,ht,Vt,Yc,Kt,Nn,Ti,Ut,jo,Ii,Ls,pt,Wt,Pg,Lg,Ig];function Sw(e,t,o){let n=[],s="";for(let i of e)s&&s.length+i.length+2>t&&(n.push(o+s),s=""),s+=(s?", ":"")+i;return s&&n.push(o+s),n.join(`
|
|
648
648
|
`)}export{Sj as a};
|
|
649
|
-
//# sourceMappingURL=chunk-
|
|
649
|
+
//# sourceMappingURL=chunk-X4FD5OBK.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{q as p}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{q as p}from"./chunk-A5ZCMRB3.js";import{b as i,c as u,d as l,e as c}from"./chunk-APKAW7LU.js";import d from"cronstrue";var f=Intl.DateTimeFormat().resolvedOptions().timeZone,m=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',g=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function w(e){return g.test(e)}function x(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function $(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function S(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||f,agent:e.agent,prompt:e.prompt,timeout:e.timeout??m,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){try{return d.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function T(e,r,t=new Date){try{return p(e,t,r)}catch{return null}}function A(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function h(e){return e?.approval?.action==="create"}async function D(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&h(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{f as a,E as b,w as c,x as d,$ as e,S as f,P as g,T as h,A as i,h as j,D as k,I as l,O as m};
|
|
2
|
+
//# sourceMappingURL=chunk-XMW422NO.js.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as q,b as O,c as R,d as B,f as b,g as S,h as E,i as w,j as y}from"./chunk-
|
|
1
|
+
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as q,b as O,c as R,d as B,f as b,g as S,h as E,i as w,j as y}from"./chunk-XMW422NO.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-APKAW7LU.js";import{existsSync as X,readFileSync as F}from"fs";var J=new Set(["cron","heartbeat","api","a2a","mesh"]),M=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function A(n,e=M){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function V(n){let e=T(n);if(!X(e))throw new Error(`config not found at ${e}`);return JSON.parse(F(e,"utf-8"))}function W(n,e){return n?.agents?.[e]?.admin===!0}function Y(n,e,t){return W(n,t.agentId)||e?.createdBy===t.agentId}function Z(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function K(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!J.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function Q(n,e,t){let r=e.timezone||"UTC",u=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",p=[`- ${n} [${h}] ${e.schedule} \u2014 ${S(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${u}`];return e.notify&&p.push(` notify: ${e.notify.channel} ${e.notify.chatId}`),e.command?p.push(` command: ${A(String(e.command))}`):e.prompt&&p.push(` prompt: ${A(String(e.prompt))}`),p.join(`
|
|
2
2
|
`)}async function k(n,e,t){let r=n?.notifications?.destination;if(!r?.channel||!r?.chatId)return"No operator notification destination is configured (notifications.destination); the operator must check `agentx schedule list`.";if(!e.notifyOperator)return"Operator notification is unavailable in this context.";try{return await e.notifyOperator({channel:r.channel,chatId:r.chatId,accountId:r.accountId},t),"The operator has been notified."}catch(u){return`Could not notify the operator (${u?.message??u}); the request is still recorded.`}}async function re(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),u=t.now?t.now():new Date,h;try{h=V(t.configPath)}catch(a){return`Error: ${a.message}`}let p=h.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(p).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,f])=>Q(i,f,u)).join(`
|
|
3
3
|
`):a?"You have no schedules.":"No schedules."}if(!e?.agentId)return"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.";if(!h.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),m=a=>C(a,{configPath:t.configPath,reload:t.reload});if(r==="create"){let a=s(n.when),l=s(n.prompt);if(!a||!l)return"Error: create needs `when` (plain English) and `prompt`.";let i=D(a);if(!i)return`Error: couldn't parse "${a}". ${O}.`;let f=s(n.agent)||e.agentId;if(!h.agents?.[f])return`Error: agent "${f}" not found on this node.`;let g=s(n.timezone)||q;if(!B(g))return`Error: unknown timezone "${g}".`;let d=o||_(i.matched,f);if(!R(d))return`Error: invalid id "${d}" (letters, digits, "-" and "_" only).`;if(p[d])return`Error: a schedule "${d}" already exists. Pick another \`id\`.`;let $=K(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let z={action:"create",requestedBy:e.agentId,requestedAt:u.toISOString()},L=b({parsed:i,agent:f,prompt:l,timezone:g,notify:$,enabled:!1,createdBy:e.agentId,approval:z}),v=await m(U=>I(U,`crons.${d}`,L));if(!v.success)return`Error: ${v.error}`;let N=w(E(i.cron,g,u),g),G=[`Schedule approval requested by ${e.agentId}`,`Create: ${d}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${N}`,`Agent: ${f}`,$?`Notify: ${$.channel} ${$.chatId}`:"Notify: none",`Prompt: ${A(l,400)}`,"",`Approve: agentx schedule approve ${d}`,`Reject: agentx schedule reject ${d}`].join(`
|
|
4
4
|
`),H=await k(h,t,G);return[`Requested schedule "${d}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${N}.`,"It is saved DISABLED and will not run until the operator approves it.",H].join(`
|
|
5
5
|
`)}if(!o)return`Error: ${r} needs \`id\`.`;let c=p[o];if(!c)return`Error: schedule "${o}" not found.`;if(!Y(h,c,e))return Z(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&y(c))return`"${o}" is still awaiting operator approval; it can't be resumed until approved.`;if(c.enabled===a)return`"${o}" is already ${a?"active":"paused"}.`;let l=await m(i=>I(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(y(c)&&c.approval.requestedBy===e.agentId){let d=await m($=>P($,`crons.${o}`));return d.success?`Withdrew the pending request "${o}".`:`Error: ${d.error}`}if(y(c))return`"${o}" is a creation request still awaiting approval; only its requester or the operator (\`agentx schedule reject ${o}\`) can drop it.`;if(c.approval?.action==="delete")return`Deletion of "${o}" is already awaiting approval.`;let a={action:"delete",requestedBy:e.agentId,requestedAt:u.toISOString()},l=await m(d=>{if(!x(d,`crons.${o}`))throw new Error(`schedule "${o}" not found`);I(d,`crons.${o}.approval`,a)});if(!l.success)return`Error: ${l.error}`;let i=c.timezone||"UTC",f=[`Schedule approval requested by ${e.agentId}`,`Delete: ${o}`,`When: ${S(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?w(E(c.schedule,i,u),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
|
|
6
6
|
`),g=await k(h,t,f);return[`Deletion of "${o}" requested. It keeps its current state until the operator approves.`,g].join(`
|
|
7
7
|
`)}return`Error: unknown action "${r}". Use list, create, pause, resume or delete.`}function oe(n,e=process.env){let t=s(e.AGENTX_AGENT_ID)||s(n.callerAgentId);if(!t)return null;let r=!!(s(e.AGENTX_CHANNEL)&&s(e.AGENTX_CHAT_ID)),u=s(r?e.AGENTX_CHANNEL:n.channel),h=s(r?e.AGENTX_CHAT_ID:n.chatId),p=s(n.accountId);return{agentId:t,channel:u,chatId:h,...p?{accountId:p}:{}}}export{re as a,oe as b};
|
|
8
|
-
//# sourceMappingURL=chunk-
|
|
8
|
+
//# sourceMappingURL=chunk-YBLITM6C.js.map
|
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as n}from"./chunk-
|
|
2
|
+
import{a as n}from"./chunk-X4FD5OBK.js";import"./chunk-G3SOCQII.js";import"./chunk-APKKQGTG.js";import"./chunk-56AQBWEJ.js";import"./chunk-Z3IP66SL.js";import"./chunk-C4CDVE2E.js";import"./chunk-RKPAVWXF.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-SZDACK6O.js";import"./chunk-U3XQ7USK.js";import"./chunk-JSF2THM4.js";import"./chunk-BYJ3A55Y.js";import"./chunk-NMFXY3QU.js";import"./chunk-F2DEKA2Q.js";import"./chunk-LQRBGQIR.js";import"./chunk-ZVP6GB4G.js";import"./chunk-2V7IQUEA.js";import"./chunk-2D3RYIDU.js";import"./chunk-L53FTKEP.js";import"./chunk-L2K4N3DA.js";import"./chunk-4UMYRIEI.js";import"./chunk-N6EWZGIX.js";import"./chunk-WP6KLXTP.js";import"./chunk-DP7RTNDM.js";import"./chunk-AIV547JW.js";import"./chunk-SFQUP3BP.js";import"./chunk-XMW422NO.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-A5ZCMRB3.js";import"./chunk-APKAW7LU.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-Q2WW2HF4.js";import"./chunk-DWADWDMU.js";import"./chunk-NO2HOK4B.js";import"./chunk-QD6IICK7.js";import"./chunk-VWTBHLMX.js";import"./chunk-VXDM7JAT.js";import"./chunk-M6HJDSLS.js";import"./chunk-4DRNEOOW.js";import"./chunk-64P4QHSZ.js";import"./chunk-KSDVKLHN.js";import"./chunk-TFVUOC2C.js";import"./chunk-2GIDVZ4H.js";import"./chunk-VOS2IW4V.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-SZJMS7K4.js";import"./chunk-7I7IEX4S.js";import"./chunk-VDMYBPYB.js";import"./chunk-DSYKYZMT.js";import"./chunk-N5NPJ6DJ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";var r=["SIGINT","SIGTERM"];function o(t=process){for(let i of r)t.on(i,()=>{t.listenerCount(i)<=1&&t.exit(0)})}o();async function s(){let t=await n();if(process.argv.slice(2).length===0){t.outputHelp();return}t.parse()}s();
|
|
3
3
|
//# sourceMappingURL=cli.js.map
|