agentix-cli 0.75.0 → 0.75.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apps/mac-voice/Sources/AgentXVoice/PillMenu.swift +16 -0
- package/apps/mac-voice/Sources/AgentXVoice/StatusMenu.swift +3 -3
- package/dist/{chunk-YZVX4RDY.js → chunk-6O2MCBOD.js} +4 -4
- package/dist/{chunk-LWPRFAQX.js → chunk-VCE2DBHB.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/{program-EHCDAWI7.js → program-6MNNHNMY.js} +2 -2
- package/package.json +1 -1
- /package/dist/{chunk-YZVX4RDY.js.map → chunk-6O2MCBOD.js.map} +0 -0
- /package/dist/{chunk-LWPRFAQX.js.map → chunk-VCE2DBHB.js.map} +0 -0
- /package/dist/{program-EHCDAWI7.js.map → program-6MNNHNMY.js.map} +0 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/// "Show floating pill" in the menu.
|
|
2
|
+
///
|
|
3
|
+
/// Closing the pill hides it without turning the setting off, so the
|
|
4
|
+
/// setting alone said "checked" over an empty screen, and the first click
|
|
5
|
+
/// only turned it off. The checkmark follows what is on screen instead,
|
|
6
|
+
/// and a click on an unchecked item always brings the pill back.
|
|
7
|
+
enum PillMenu {
|
|
8
|
+
static func isChecked(showPill: Bool, visible: Bool) -> Bool {
|
|
9
|
+
showPill && visible
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/// The setting after a click.
|
|
13
|
+
static func click(showPill: Bool, visible: Bool) -> Bool {
|
|
14
|
+
!isChecked(showPill: showPill, visible: visible)
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -47,7 +47,7 @@ final class StatusMenu: NSObject, NSMenuDelegate {
|
|
|
47
47
|
var onHidePill: (() -> Void)?
|
|
48
48
|
/// Put the pill back in the bottom-right corner.
|
|
49
49
|
var onResetPosition: (() -> Void)?
|
|
50
|
-
/// Whether the pill is on screen, for "Hide pill".
|
|
50
|
+
/// Whether the pill is on screen, for "Hide pill" and "Show floating pill".
|
|
51
51
|
var pillVisible: () -> Bool = { false }
|
|
52
52
|
var onSettings: (() -> Void)?
|
|
53
53
|
|
|
@@ -238,7 +238,7 @@ final class StatusMenu: NSObject, NSMenuDelegate {
|
|
|
238
238
|
hold.state = Hold.isOn ? .on : .off
|
|
239
239
|
menu.addItem(hold)
|
|
240
240
|
let pill = action("Show floating pill", #selector(togglePill), key: "")
|
|
241
|
-
pill.state = Config.showPill ? .on : .off
|
|
241
|
+
pill.state = PillMenu.isChecked(showPill: Config.showPill, visible: pillVisible()) ? .on : .off
|
|
242
242
|
menu.addItem(pill)
|
|
243
243
|
let orb = action("Animated orb", #selector(toggleOrb), key: "")
|
|
244
244
|
orb.state = Config.animatedOrb ? .on : .off
|
|
@@ -293,7 +293,7 @@ final class StatusMenu: NSObject, NSMenuDelegate {
|
|
|
293
293
|
}
|
|
294
294
|
|
|
295
295
|
@objc private func togglePill() {
|
|
296
|
-
Config.showPill.
|
|
296
|
+
Config.showPill = PillMenu.click(showPill: Config.showPill, visible: pillVisible())
|
|
297
297
|
onPillChanged?(Config.showPill)
|
|
298
298
|
}
|
|
299
299
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as ml,b as ms,g as pl}from"./chunk-JGEHN4VE.js";import{a as nl,c as sl}from"./chunk-GZAGG3ES.js";import{a as Qe,b as Zc,f as el,g as tl,h as ol,i as gs,j as il,k as rl,l as Oi,m as dl,o as gl}from"./chunk-UBGQ7AOG.js";import{a as al,c as cl,d as ll}from"./chunk-Z3IP66SL.js";import{a as fi,b as Ca}from"./chunk-RKPAVWXF.js";import{c as ba}from"./chunk-SZDACK6O.js";import{a as vo}from"./chunk-GV7S5BAX.js";import{e as $a}from"./chunk-GSX4NK2N.js";import{$ as Vc,A as Sc,B as wi,C as Ec,D as Ac,E as Tc,F as jc,G as Oc,H as Ic,I as Mc,J as Lc,K as Fc,L as So,M as as,N as xi,O as Uc,P as qc,Q as Wc,R as Bc,S as Eo,T as Ao,U as Jc,V as Hc,W as _e,X as cs,Y as hn,Z as Si,_ as Gc,a as Oa,aa as Ti,b as Ia,ba as Xc,c as mn,ca as ls,d as Fa,da as To,e as Ua,ea as ds,fa as ji,ga as Qc,k as Zn,l as Ja,m as pn,n as es,o as za,p as Ya,q as rc,r as ac,s as ss,t as yi,u as mc,v as yc,w as bc,x as kc,y as vc,z as xc}from"./chunk-
|
|
1
|
+
import{a as ml,b as ms,g as pl}from"./chunk-JGEHN4VE.js";import{a as nl,c as sl}from"./chunk-GZAGG3ES.js";import{a as Qe,b as Zc,f as el,g as tl,h as ol,i as gs,j as il,k as rl,l as Oi,m as dl,o as gl}from"./chunk-UBGQ7AOG.js";import{a as al,c as cl,d as ll}from"./chunk-Z3IP66SL.js";import{a as fi,b as Ca}from"./chunk-RKPAVWXF.js";import{c as ba}from"./chunk-SZDACK6O.js";import{a as vo}from"./chunk-GV7S5BAX.js";import{e as $a}from"./chunk-GSX4NK2N.js";import{$ as Vc,A as Sc,B as wi,C as Ec,D as Ac,E as Tc,F as jc,G as Oc,H as Ic,I as Mc,J as Lc,K as Fc,L as So,M as as,N as xi,O as Uc,P as qc,Q as Wc,R as Bc,S as Eo,T as Ao,U as Jc,V as Hc,W as _e,X as cs,Y as hn,Z as Si,_ as Gc,a as Oa,aa as Ti,b as Ia,ba as Xc,c as mn,ca as ls,d as Fa,da as To,e as Ua,ea as ds,fa as ji,ga as Qc,k as Zn,l as Ja,m as pn,n as es,o as za,p as Ya,q as rc,r as ac,s as ss,t as yi,u as mc,v as yc,w as bc,x as kc,y as vc,z as xc}from"./chunk-VCE2DBHB.js";import{H as fc,I as hc,Na as zc,Oa as Ei,Pa as Yc,Qa as Ai,V as un,Y as $i,Z as is,_ as Cc,cb as mt,eb as Kc,fa as It,ga as Nc,ha as bi,ja as ki,la as Rc,ma as _c,na as fn,p as Ot,ra as rs,t as pc,ua as Dc,va as Pc,w as uc,wa as vi}from"./chunk-SKIDVXWG.js";import{a as qa,d as Wa,e as Ba}from"./chunk-ISBM2C3D.js";import{a as ts,b as os,c as Va,d as Ka,e as Xa,g as Qa,h as Za,j as ec,k as tc,l as oc,m as nc,p as ns,r as sc,s as ic}from"./chunk-BYJ3A55Y.js";import{a as Ha,p as Ga}from"./chunk-WC4TPXD3.js";import{a as cc,b as lc,c as dc,d as gc}from"./chunk-2D3RYIDU.js";import{a as wc,b as $c}from"./chunk-EKJG63EJ.js";import{C as jt,I as Ta,T as ja,g as ma,p as pa,w as mi,x as ya}from"./chunk-DIHLL45I.js";import{b as wo,g as bo,h as Xn,i as Qn,j as ko,k as wa,l as Vt,m as gn}from"./chunk-OEUII2QP.js";import{e as Sa,f as ui,k as Ea}from"./chunk-WP6KLXTP.js";import{a as Vn}from"./chunk-N6EWZGIX.js";import{b as $o}from"./chunk-DP7RTNDM.js";import{a as hi,e as Na,f as Ra,h as _a,i as Da,k as Pa,l as Ma,m as La}from"./chunk-S5JGQKON.js";import{f as ka,g as va,h as pi}from"./chunk-76Z4VHDX.js";import{a as fa,k as xa}from"./chunk-PUU2ESI2.js";import{b as pe,c as Oe,d as xo,e as Aa}from"./chunk-IR2Q63IV.js";import{a as di}from"./chunk-L3MEAKL7.js";import{a as gi,b as ua}from"./chunk-GQ76J72O.js";import{j as ha}from"./chunk-X5C5W3E4.js";import{h as ga}from"./chunk-DWADWDMU.js";import{g as Tt,i as Kn}from"./chunk-KEJOBB5E.js";import{b as yo,d as da}from"./chunk-2GIDVZ4H.js";import{a as li,b as Yr,c as Nm,d as zn,e as Vr,f as sa,g as Dm,h as ia,i as Pm,m as ho,n as aa,o as ca,s as la,v as gt,w as dn}from"./chunk-6HPJKD3X.js";import{a as ra,b as Mm}from"./chunk-FX3D7YON.js";import{a as $t,b as fo,e as ta,f as ln}from"./chunk-72SZI2UW.js";import{a as wt,b as Cm}from"./chunk-7I7IEX4S.js";import{A as I,B as Yn,D as ne,m as Kr,n as Xr,p as Qr,q as Rm,y as Zr,z as ea}from"./chunk-CXZ4YDHJ.js";import{g as oa,k as na,l as _m}from"./chunk-RGDKHYY2.js";import{Command as Lm}from"commander";var ul=new Lm().name("a2a").description("start an A2A (Agent-to-Agent) protocol server for external agent integration").option("--port <port>","server port","3171").option("--host <host>","server host","0.0.0.0").option("-p, --provider <provider>","AI provider","claude-code").option("-m, --model <model>","model to use").option("--api-key <key>","API key for the provider").option("-c, --cwd <cwd>","working directory",process.cwd()).option("--no-cors","disable CORS headers").action(async e=>{await new Ua({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});ne();import{Command as Fm}from"commander";import{execFileSync as et}from"node:child_process";import{cpSync as fl,existsSync as Ni,mkdirSync as Ii,mkdtempSync as Um,readdirSync as qm,rmSync as hl,writeFileSync as yl}from"node:fs";import{dirname as wl,join as Pe}from"node:path";import{homedir as ps,release as Wm,tmpdir as Bm}from"node:os";import{setTimeout as Jm}from"node:timers/promises";function us(){let e=Va(process.platform,process.arch,Wm());if(e)throw new Error(e)}function fs(){let e=Pe(ps(),"Library/LaunchAgents"),t=[];try{t=qm(e).filter(Qa)}catch{}let o=t.flatMap(n=>{let s=Pe(e,n);try{return[{file:s,plist:et("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Za(e,o)}function yn(e){return`gui/${process.getuid()}/${e.label}`}async function Ci(e){try{et("launchctl",["bootout",yn(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{et("launchctl",["print",yn(e)],{stdio:"pipe"})}catch{return}await Jm(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function $l(e){if(!Ni(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{et("launchctl",["print",yn(e)],{stdio:"pipe"})}catch{t=!1}t||et("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),et("launchctl",["kickstart",yn(e)],{stdio:"pipe"})}function Hm(){let e=nc();if(e&&Ni(Pe(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var jo=new Fm("desktop").description("install and control the macOS desktop assistant");jo.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{us();let t=I(),o=Ka(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=Hm(),r=Pe(ps(),"Applications"),{keep:a,remove:c}=fs();if(console.log(`Desktop assistant \u2192 ${Pe(r,ts)}
|
|
2
2
|
Computer-use helper \u2192 ${Pe(r,os)}
|
|
3
3
|
Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
|
|
4
4
|
Daemon \u2192 ${s}
|
|
@@ -409,7 +409,7 @@ return aid ?? null`}function Mf(e,t){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
|
|
|
409
409
|
settings \u2014 without this an attached production identity would be less
|
|
410
410
|
guarded than a spawned one.)`))):console.log(N.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${N.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(t){console.error(N.red(`Install failed: ${t?.message??t}`)),process.exit(1)}});qt.command("uninstall").description("remove the attach hooks from ~/.claude/settings.json").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--remove-guard","also remove the PreToolUse guard hook").action(e=>{try{let t=Sl({path:e.path,keepGuard:!e.removeGuard});console.log(t.changed?`${N.green("\u2713")} Removed attach hooks from ${N.gray(t.path)} (${t.events.join(", ")})`:`${N.gray("Nothing to remove.")}`),e.removeGuard||console.log(N.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(t){console.error(N.red(`Uninstall failed: ${t?.message??t}`)),process.exit(1)}});ne();import{Command as $h}from"commander";import we from"chalk";var Fs=new $h().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function dg(e){let t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let n=I(e.config);t||(t=n.dashboard?.daemonUrl||""),o||(o=n.dashboard?.token||"")}catch{}return t||(t="http://localhost:18800"),{baseUrl:t.replace(/\/+$/,""),token:o}}function gg(e,t){let o={};return e&&(o.Authorization=`Bearer ${e}`),t&&(o["Content-Type"]=t),o}function lg(e){let t=Math.round((Date.now()-e)/1e3);return t<60?`${t}s`:t<3600?`${Math.round(t/60)}m`:t<86400?`${Math.round(t/3600)}h`:`${Math.round(t/86400)}d`}function bh(e){return e==="busy"?we.magenta:e==="warm-hot"?we.green:e==="warm-cold"?we.cyan:e==="idle"?we.yellow:e==="dead"?we.red:we.dim}Fs.command("list").description("list every live persistent claude process").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("--json","emit JSON").action(async e=>{let{baseUrl:t,token:o}=dg(e),n;try{n=await fetch(`${t}/api/processes`,{headers:gg(o)})}catch(r){console.log(we.red(` could not reach daemon at ${t}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(we.dim(` daemon at ${t} has no agents with persistentProcess: true`));return}n.ok||(console.log(we.red(` HTTP ${n.status} from ${t}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(we.dim(" (no processes)"));return}for(let r of i){let a=bh(r.state)(r.state.padEnd(9)),c=lg(r.spawnedAt),l=r.lastTurnAt?lg(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?we.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?we.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):we.dim("sess=\u2014"),u=r.pendingTaskId?we.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${we.bold(r.key.agentId)}${we.dim(":"+r.key.channel+":"+r.key.chatId)} ${we.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${u}`),r.deadReason&&console.log(` ${we.red("dead:")} ${r.deadReason}`)}});Fs.command("kill <agentId> <channel> <chatId>").description("force-kill one persistent process (the next dispatch will spawn fresh)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("-r, --reason <reason>","kill reason (recorded on the dead-process snapshot)","operator-cli").action(async(e,t,o,n)=>{let{baseUrl:s,token:i}=dg(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:gg(i,"application/json"),body:JSON.stringify({agentId:e,channel:t,chatId:o,reason:n.reason})})}catch(a){console.log(we.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(we.dim(" daemon has no persistent-process registry"));return}if(!r.ok){let a=`HTTP ${r.status}`;try{let c=await r.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(we.red(` ${a}`)),process.exit(1)}console.log(we.green(` killed ${e}:${t}:${o}`))});import{Command as kh}from"commander";import Le from"chalk";import{existsSync as dr,rmSync as vh}from"fs";import{resolve as gr}from"path";var Wo=new kh().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Wo.command("add <agentId>").description("build or refresh an agent's lexical index from one or more globs").argument("<globs...>","glob patterns relative to cwd (e.g. './docs/**/*.md')").option("-v, --verbose","log each indexed file").action(async(e,t,o)=>{t.length===0&&(console.log(Le.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!o.verbose,s=Date.now(),i=await ka(e,t,{verbose:n}),r=Date.now()-s;console.log(Le.green(` \u2713 indexed ${i.docs} doc(s) for ${Le.bold(e)} in ${r}ms`)),console.log(Le.dim(` \u2192 ${i.path}`))});Wo.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let t=gr(e.cwd,".agentx","rag");if(!dr(t)){console.log(Le.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:o}=await import("fs"),n=o(t).filter(s=>dr(gr(t,s,"index.json")));if(n.length===0){console.log(Le.dim(" (no indexes)"));return}for(let s of n.sort()){let i=pi(s);console.log(` ${Le.bold(s)} ${i.docs} doc(s) ${Le.dim(i.path)}`)}});Wo.command("search <agentId> <query>").description("query an agent's index \u2014 useful for debugging recall before the agent calls rag.lexical").option("-k, --k <n>","top-k results","5").option("--json","emit JSON").action((e,t,o)=>{let n=parseInt(o.k,10)||5,s=va(e,t,{k:n});if(o.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=pi(e);i.exists?console.log(Le.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Le.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Le.bold(i.title)} ${Le.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Le.dim(i.path)}`),console.log(` ${Le.dim(i.snippet.slice(0,200))}`)});Wo.command("clear <agentId>").description("delete an agent's index").action(e=>{let t=gr(process.cwd(),".agentx","rag",e);if(!dr(t)){console.log(Le.dim(` no index for ${e} \u2014 nothing to clear`));return}vh(t,{recursive:!0,force:!0}),console.log(Le.green(` \u2713 cleared index for ${e}`))});ne();import{Command as xh}from"commander";import Q from"chalk";import Bo from"prompts";var co=new xh().name("backlog").description("manage the local backlog used by business workSource=backlog");function Cn(e){let t=I(e),o=t.business?.workSource,n=o?.type==="backlog"?o.path:".agentx/backlog.md";return{config:t,storePath:n,store:new zc(n)}}function Sh(e){return e?Q.cyan(`${e.type}:${e.project}#${e.iid}`):Q.dim("manual")}function Eh(e){return{todo:Q.gray("todo"),doing:Q.yellow("doing"),blocked:Q.red("blocked"),done:Q.green("done")}[e]}co.command("list",{isDefault:!0}).description("list backlog items").option("--status <status>","filter by status (todo|doing|blocked|done)").option("--assignee <agent>","filter by assignee").option("--source <type>","filter by source.type (gitlab|github|manual)").option("-c, --config <path>","config path").action(async e=>{let{store:t}=Cn(e.config),o=t.list();if(e.status&&(o=o.filter(n=>n.status===e.status)),e.assignee&&(o=o.filter(n=>n.assignee===e.assignee)),e.source&&(o=o.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!o.length){console.log(Q.dim(" (no items)"));return}console.log();for(let n of o){let s=n.assignee?Q.magenta(`@${n.assignee}`):Q.dim("unassigned");console.log(` ${Eh(n.status).padEnd(7)} ${Sh(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(Q.dim(` ${n.source.url}`))}console.log(),console.log(Q.dim(` ${o.length} item${o.length===1?"":"s"} \u2014 ${t.jsonPath()}`))});co.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,t,o)=>{let n=Cn(o.config);n.store.findById(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:t,status:"doing"});if(console.log(Q.green(` claimed: ${i.title} -> ${t}`)),i.source){let r=Yc([t],i.source,n.config),a=await Ai(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(Q.dim(" sync:"),...c));console.log(a.ok?Q.dim(` synced -> ${a.url??i.source.type}`):Q.yellow(` sync failed: ${a.error}`))}});co.command("done <id>").description("mark an item as done; closes the upstream issue if linked").option("--note <text>","comment to post upstream").option("--close","also close the upstream issue (default: only labels change)",!1).option("-c, --config <path>","config path").action(async(e,t)=>{let o=Cn(t.config);o.store.findById(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1));let s=o.store.update(e,{status:"done"});if(console.log(Q.green(` done: ${s.title}`)),s.source){let i=await Ai(s,{addLabels:["Done"],removeLabels:["Doing"],state:t.close?"closed":void 0,note:t.note},o.config,(...r)=>console.log(Q.dim(" sync:"),...r));console.log(i.ok?Q.dim(` synced -> ${i.url??s.source.type}`):Q.yellow(` sync failed: ${i.error}`))}});co.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,t)=>{let{store:o}=Cn(t.config);o.remove(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1)),console.log(Q.green(` removed ${e}`))});co.command("import").description("import open issues from gitlab/github into the backlog (interactive)").option("--source <type>","source type (gitlab|github)").option("--project <id>","project id (group/repo for gitlab, owner/repo for github)").option("--assignee <agent>","assign all imported items to this agentId").option("-c, --config <path>","config path").action(async e=>{let t=Cn(e.config),o=!!t.config.channels.gitlab?.token,n=!!t.config.channels.github?.token;!o&&!n&&(console.error(Q.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let w=[o&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Bo({type:"select",name:"source",message:"Source",choices:w})).source,!s)return}s==="gitlab"&&!o&&(console.error(Q.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(Q.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let w=s==="gitlab"?Th(t.config):jh(t.config);w.length?(i=(await Bo({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...w.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await Bo({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Bo({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Bo({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(Q.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await Oh(t.config,i,a):await Ih(t.config,i,a);if(!c.length){console.log(Q.yellow(" no open issues matched"));return}console.log(Q.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(t.store.list().map(w=>w.id)),d=c.map(w=>{let k=Ei({type:s,project:l,iid:w.iid,url:w.url}),b=g.has(k),$=w.labels.length?` [${w.labels.slice(0,3).join(",")}]`:"";return{title:`#${w.iid} ${w.title}${$}${b?Q.dim(" (already imported)"):""}`,value:w,disabled:b}}),f=(await Bo({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!f.length){console.log(Q.dim(" nothing selected"));return}let p=f.map(w=>{let k={type:s,host:s==="gitlab"?Ah(t.config):void 0,project:l,iid:w.iid,url:w.url};return{id:Ei(k),title:w.title,description:w.description,assignee:e.assignee||w.assignee,labels:w.labels,milestone:w.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),h=t.store.addMany(p);console.log(Q.green(` imported ${h.length} item${h.length===1?"":"s"}`));for(let w of h)console.log(Q.dim(` ${w.id} \u2014 ${w.title}`))});function Ah(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Th(e){let t=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&t.add(n.project);let o=e.business?.workSource;if(o?.type==="gitlab")for(let n of o.projects??[])t.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&t.add(n.id);return[...t].sort()}function jh(e){let t=new Set;for(let o of e.channels.github?.routes??[])o.repo&&o.repo!=="*"&&t.add(o.repo);return[...t].sort()}async function Oh(e,t,o){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});o&&s.set("search",o);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(t)}/issues?${s}`,{headers:{"PRIVATE-TOKEN":n.token}});if(!i.ok)throw new Error(`GitLab ${i.status}: ${await i.text().catch(()=>"")}`);let r=await i.json();return Array.isArray(r)?r.map(a=>({iid:a.iid,title:a.title,description:a.description||void 0,labels:Array.isArray(a.labels)?a.labels.map(c=>typeof c=="string"?c:c.name):[],milestone:a.milestone?.title||void 0,assignee:a.assignee?.username||a.assignees?.[0]?.username||void 0,url:a.web_url})):[]}async function Ih(e,t,o){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(o){let c=`repo:${t} is:issue is:open ${o}`;i=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let l=await fetch(i,{headers:s});if(!l.ok)throw new Error(`GitHub ${l.status}: ${await l.text().catch(()=>"")}`);return((await l.json()).items??[]).map(mg)}i=`https://api.github.com/repos/${t}/issues?state=open&per_page=100&sort=updated&direction=desc`;let r=await fetch(i,{headers:s});if(!r.ok)throw new Error(`GitHub ${r.status}: ${await r.text().catch(()=>"")}`);let a=await r.json();return Array.isArray(a)?a.filter(c=>!c.pull_request).map(mg):[]}function mg(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(t=>typeof t=="string"?t:t.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as Ch}from"commander";import W from"chalk";import{existsSync as Nh,readFileSync as Rh}from"fs";import{resolve as _h}from"path";import Dh from"prompts";ne();function pg(e){let t=e||_h(process.cwd(),"agentx.json");return Nh(t)||(console.log(W.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(Rh(t,"utf-8"))}async function Ph(e,t){if(!e)return;if(e==="me"){let n=t?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(W.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await Dh([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let o=e.split(":");if(o.length>=2)return{channel:o[0],chatId:o[1],accountId:o[2]};console.log(W.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var vt=new Ch().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');vt.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>",`IANA timezone (default: ${hi})`,hi).option("--timeout <seconds>","max run time","600").option("--model <model>","override model").option("--disabled","create but leave disabled").option("--dry-run","print what would be written without writing").action(async(e,t)=>{if(!e){vt.help();return}t.agent||(console.log(W.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(W.red(' --do "<prompt>" is required')),process.exit(1));let o=fi(e);o||(console.log(W.red(` Couldn't parse: "${e}"`)),console.log(W.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(W.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(W.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=pg(t.config),s=ea(n);n.agents?.[t.agent]||(console.log(W.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(W.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await Ph(t.notify,s),r=t.id||Ca(o.matched,t.agent),a=Ra({parsed:o,agent:t.agent,prompt:t.do,timezone:t.timezone,timeout:parseInt(t.timeout,10),model:t.model,notify:i,onError:Na(t.onError),enabled:!t.disabled}),c=a.onError,l=await pe(d=>Oe(d,`crons.${r}`,a),{configPath:t.config,dryRun:!!t.dryRun});l.success||(console.log(W.red(` \u2717 ${l.error}`)),process.exit(1));let g=t.dryRun?"would add":"Added";console.log(W.green(` \u2713 ${g} cron ${W.cyan(r)}`)),console.log(W.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(W.dim(` Agent: ${t.agent}`)),i&&console.log(W.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(W.dim(` On error: ${c.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});vt.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async e=>{let o=pg(e.config).crons||{},n=Object.entries(o);if(!n.length){console.log(W.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?W.yellow("\u25D0"):i.enabled?W.green("\u25CF"):W.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${W.cyan(s.padEnd(32))} ${W.dim(i.schedule.padEnd(14))} ${W.dim("\u2192")} ${i.agent}`),console.log(W.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(W.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(W.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=Da(_a(i.schedule,c),c);console.log(W.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(W.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,t]of[["on",!0],["off",!1]])vt.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await La(o,t);n.success||(console.log(W.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});vt.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await pe(o=>{if(!xo(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);Aa(o,`crons.${e}`)});t.success||(console.log(W.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});for(let[e,t,o]of[["approve",Pa,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",Ma,"reject an agent's pending create/delete request (drops the request)"]])vt.command(`${e} <id>`).description(o).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await t(n,{configPath:s.config});i.success||(console.log(W.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(W.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});vt.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=fi(t);o||(console.log(W.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(W.green(` "${t}"`)),console.log(W.dim(` \u2192 ${o.cron}`)),console.log(W.dim(` \u2192 ${o.human}`))});import{Command as Mh}from"commander";import xe from"chalk";var Wt=new Mh("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals, WhatsApp replies)"),Lh={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki",whatsapp:"whatsapp"};function ug(){return{root:process.cwd()}}function mr(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function Fh(e){console.log(` ${xe.cyan(e.key)} ${xe.dim(`[${Lh[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?xe.dim(` (later: until ${mr(e.snoozed_until)})`):""}`),console.log(` ${xe.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${xe.green("Recommends:")} ${e.recommend}`),e.expires&&console.log(xe.yellow(` Expires ${mr(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(xe.dim(` ${e.detail}`)),e.source&&console.log(xe.dim(` ${e.source}`)),console.log(xe.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}Wt.command("list",{isDefault:!0}).alias("ls").description("what is waiting, most urgent first").option("--all","include items you put off with `later`").option("--json","machine-readable output").action(e=>{let t=fc(ug(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(t,null,2));return}for(let o of t.errors)console.log(xe.red(` couldn't read ${o.kind}: ${o.error}`));if(t.items.length===0){console.log(xe.dim(` nothing waiting${t.snoozed?` (${t.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let o of t.items)Fh(o),console.log();console.log(xe.dim(` ${t.items.length} waiting${t.snoozed?`, ${t.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function pr(e,t,o){let n=gs(),s=o.hours?Number(o.hours):n.laterHours;if(t==="later"&&!(s>0)){console.error(xe.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await hc(ug(),e,t,{force:o.force,note:o.note,laterHours:s});if(!i.ok){console.error(xe.red(` ${i.error}`)),process.exitCode=1;return}console.log(xe.green(` \u2713 ${i.message}`))}Wt.command("approve").alias("yes").description("say yes: enables the schedule, lets the fact be used, writes the wiki article, or tells the agent yes").argument("<key>","item key from `agentx approvals list`, e.g. card:2026-01-05-publish-draft-ab12").option("--force","wiki: approve even if the article changed since the proposal").option("--note <text>","cards: a note passed to the agent with your answer").action((e,t)=>pr(e,"yes",t));Wt.command("reject").alias("no").description("say no: drops the request, keeps the fact out, declines the article, or tells the agent no").argument("<key>","item key from `agentx approvals list`").option("--note <text>","why; kept with cards and wiki proposals").action((e,t)=>pr(e,"no",t));Wt.command("later").description("put an item off; it leaves the list and comes back later (a card still expires on time)").argument("<key>","item key from `agentx approvals list`").option("--hours <n>","how long (default: approvals.laterHours, 24)").action((e,t)=>pr(e,"later",t));Wt.command("request").description("raise a decision card yourself, for example to test the inbox (agents use the agentx_approval tool)").requiredOption("--agent <id>","the agent the card is from; it gets the result").requiredOption("--title <text>","what it is, in one line").requiredOption("--ask <text>","the yes/no question").requiredOption("--recommend <text>","the advice and why, in one line").requiredOption("--if-silent <value>",`what applies if nobody answers: ${pc.join(", ")}`).option("--expires <when>","ISO date or time, or like 12h / 3d (default: approvals.defaultExpiryDays)").option("--source <link>","link to the draft, PR or issue").action(e=>{let t=gs(),o=uc(process.cwd(),{raised_by:e.agent,title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.ifSilent,expires:e.expires,source:e.source},{settings:t});if(!o.ok){console.error(xe.red(` ${o.error}`)),process.exitCode=1;return}console.log(xe.green(` \u2713 card:${o.card.id} raised; expires ${mr(o.card.expires)}, then: ${o.card.if_silent}`))});Wt.command("settings").description('show or change expiry, "later" and digest settings (approvals in agentx.json)').option("--expiry-days <n>","days a card gets when it doesn't say").option("--max-expiry-days <n>","longest a card may wait").option("--later-hours <n>","how long `later` hides an item").option("--notify-agent <on|off>","tell the agent that raised a card its result").option("--digest <on|off>","the daily message about what is waiting").option("--digest-time <HH:MM>","when the digest goes out, 24-hour local time").option("--digest-timezone <zone>",`IANA timezone for --digest-time; "local" for this machine's`).option("--digest-to <channel:chatId>",'where the digest goes; "default" for notifications.destination').action(async e=>{let t={},o=(a,c)=>{if(c===void 0)return;let l=Number(c);if(!(l>0))throw new Error(`${a} must be a positive number`);return l},n=(a,c)=>{if(c!==void 0){if(c==="on")return!0;if(c==="off")return!1;throw new Error(`${a} takes on or off`)}};try{if(t.defaultExpiryDays=o("--expiry-days",e.expiryDays),t.maxExpiryDays=o("--max-expiry-days",e.maxExpiryDays),t.laterHours=o("--later-hours",e.laterHours),t.notifyAgent=n("--notify-agent",e.notifyAgent),t.digestEnabled=n("--digest",e.digest),e.digestTime!==void 0&&(t.digestTime=e.digestTime),e.digestTimezone!==void 0&&(t.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")t.destination=null;else{let a=il(e.digestTo);if(!a)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");t.destination=a}}catch(a){console.error(xe.red(` ${a.message}`)),process.exitCode=1;return}if(Object.values(t).some(a=>a!==void 0)){let a=await rl(t);if(!a.success){console.error(xe.red(` ${a.error}`)),process.exitCode=1;return}console.log(xe.green(" \u2713 saved")+(a.reloaded?xe.dim(" (daemon reloaded)"):""))}let i=gs(),r=i.digest.destination;console.log(` Cards expire after ${i.defaultExpiryDays} day(s) unless they say (at most ${i.maxExpiryDays})`),console.log(` "Later" hides an item ${i.laterHours} hour(s)`),console.log(` Tell the agent ${i.notifyAgent?"on":"off"}`),console.log(` Daily digest ${i.digest.enabled?`on, at ${i.digest.time}${i.digest.timezone?` (${i.digest.timezone})`:" (this machine's time)"}`:"off"}`),console.log(` Digest goes to ${r?`${r.channel} ${r.chatId}`:"notifications.destination"}`)});import{Command as cy}from"commander";import Jo from"chalk";import ie from"chalk";import Rn from"prompts";import{readFileSync as Uh,writeFileSync as qh,existsSync as Wh}from"fs";import{resolve as fg}from"path";var Bh=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Jh(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function ur(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function hg(e=".env"){let t=fg(e);if(!Wh(t))return[];let o=Uh(t,"utf-8"),n=[];for(let s of o.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let i=s.match(Bh);i?n.push({kind:"kv",key:i[1],value:Jh(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Hh(e){return e.map(t=>t.kind==="kv"?`${t.key}=${ur(t.value)}`:t.raw).join(`
|
|
411
411
|
`)+`
|
|
412
|
-
`}function Nn(e,t,o=".env"){let n=fg(o),s=hg(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:t,raw:`${e}=${ur(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${ur(t)}`})),qh(n,Hh(s))}function fr(e,t=".env"){return hg(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var yg="https://t.me/BotFather";async function Gh(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function zh(e,t){let o=Date.now()+t,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function wg(e={}){console.log(),console.log(ie.bold(" Connect Telegram")),console.log(),console.log(ie.dim(` 1. Open ${yg}`)),console.log(ie.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ie.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:t}=await Rn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(t)try{let{spawn:b}=await import("child_process"),$=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b($,[yg],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:o}=await Rn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});o||(console.log(ie.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Gh(o.trim());n||(console.log(ie.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ie.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(ie.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(ie.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Rn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ie.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Rn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ie.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Nn(f,o.trim()),process.env[f]=o.trim();let p=await pe(b=>{Oe(b,"channels.telegram.enabled",!0),Oe(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=xo(b,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),Oe(b,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ie.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ie.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ie.dim(` Token stored in .env as ${f}`)),console.log(ie.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ie.dim(" Daemon hot-reloaded.")):console.log(ie.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Rn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(ie.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ie.dim(" Waiting up to 90s..."));let w=await zh(o.trim(),9e4);if(!w){console.log(ie.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ie.dim(" agentx config set notifications.destination.channel telegram")),console.log(ie.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ie.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await pe(b=>{Oe(b,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ie.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ie.green(" \u2713 Default --notify target set")),console.log(ie.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ie.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ie.dim(" Daemon hot-reloaded."))}import $e from"chalk";import hr from"prompts";import{existsSync as wr,mkdirSync as Yh,readdirSync as Vh,readFileSync as $g}from"fs";import{resolve as yr}from"path";var Kh=".agentx/whatsapp-sessions";function Xh(){let e=yr(process.cwd(),".agentx/daemon.pid");if(!wr(e))return!1;try{let t=parseInt($g(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function Qh(e){if(!wr(e))return!1;try{return Vh(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function Zh(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t($e.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t($e.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;Yh(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{t($e.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){t($e.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(u),t($e.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),t($e.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function bg(e={}){if(console.log(),console.log($e.bold(" Connect WhatsApp")),console.log(),Xh()){console.log($e.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log($e.dim(" agentx daemon stop")),console.log();let{cont:l}=await hr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log($e.red(" Aborted")),process.exit(1))}let t=e.configPath||yr(process.cwd(),"agentx.json");wr(t)||(console.log($e.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse($g(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||Kh,s=yr(process.cwd(),n),i=Object.keys(o.agents||{});i.length===0&&(console.log($e.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await hr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log($e.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Qh(s)&&a){let{keep:l}=await hr({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log($e.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Zh(s,g=>console.log(g))||(console.log($e.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await pe(l=>{Oe(l,"channels.whatsapp.enabled",!0),Oe(l,"channels.whatsapp.sessionDir",n),Oe(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log($e.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log($e.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log($e.dim(` Session: ${n}`)),console.log($e.dim(" Start the daemon to begin receiving:")),console.log($e.dim(" agentx daemon start")),console.log($e.dim(" Add routes later with:")),console.log($e.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as ey}from"crypto";import Ae from"chalk";import kg from"prompts";var Us="agentx-mesh:",qs="//join/";function ty(e){return Buffer.from(e,"utf-8").toString("base64url")}function oy(e){return Buffer.from(e,"base64url").toString("utf-8")}function ny(e){return`${Us}${qs}${ty(JSON.stringify(e))}`}function sy(e){if(!e.startsWith(`${Us}${qs}`))throw new Error(`Not a mesh invite link \u2014 expected ${Us}${qs}\u2026`);let t=e.slice(Us.length+qs.length),o=JSON.parse(oy(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function iy(){return ey(32).toString("hex")}function ry(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function ay(e){return e?.node?.name||e?.node?.id||"node"}async function vg(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Ae.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(t(s,"utf-8")),r=fr("MESH_TOKEN");r||(r=iy(),Nn("MESH_TOKEN",r),console.log(Ae.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||ry(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await kg({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(Ae.red(" Aborted")),process.exit(1)),a=d}let l=await pe(d=>{Oe(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ae.red(` \u2717 ${l.error}`)),process.exit(1));let g=ny({url:a,token:r,name:ay(i),version:1});console.log(),console.log(Ae.bold(" Mesh invite")),console.log(),console.log(` ${Ae.cyan(g)}`),console.log(),console.log(Ae.dim(" Run on the other node:")),console.log(Ae.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Ae.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function xg(e,t={}){let o;try{o=sy(e)}catch(i){console.log(Ae.red(` \u2717 ${i.message}`)),process.exit(1)}let n=fr("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:i}=await kg({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Ae.red(" Aborted (keeping existing .env)")),process.exit(1))}Nn("MESH_TOKEN",o.token);let s=await pe(i=>{Oe(i,"mesh.enabled",!0);let r=xo(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Oe(i,"mesh.peers",r)},{configPath:t.configPath});s.success||(console.log(Ae.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ae.green(" \u2713 Joined mesh")),console.log(Ae.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ae.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ae.dim(" Daemon hot-reloaded.")):console.log(Ae.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(Ae.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ae.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Ae.yellow(` Could not reach ${o.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Ho=new cy().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Ho.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await wg({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Ho.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await bg({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Sg=Ho.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Sg.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await vg({url:e.url,configPath:e.config})});Sg.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await xg(e,{configPath:t.config})});Ho.action(()=>{console.log(),console.log(Jo.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Jo.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Jo.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Jo.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Jo.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Jo.dim(" GitLab connect is the next slice.")),console.log()});ne();import{Command as ly}from"commander";import fe from"chalk";var _n=new ly().name("usage").description("token usage analysis and reporting");_n.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=I(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(fe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(fe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${fe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${fe.red(String(s.totalErrors))}`),console.log(),console.log(fe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${fe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${fe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(fe.red(" Daemon not running. Start with: agentx daemon start")):console.log(fe.red(` ${e.message}`))}});_n.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(fe.red(` Script not found: ${s}`)),console.log(fe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(fe.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(fe.red(" Analysis failed. Is Python 3 installed?"))}});_n.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-HVVP22SA.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-EHCDAWI7.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(fe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${fe.dim("\xB7")} ${d}`);console.log(),console.log(fe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(fe.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(fe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(fe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(fe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(fe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=fe.dim(`${i.days}d`);console.log(` ${fe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(fe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as dy}from"commander";import be from"chalk";import{readFileSync as gy}from"fs";import{resolve as my}from"path";ne();var Bt=new dy().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Bt.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{da(my(process.cwd(),".env"))}catch{}let t=py(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-CDBPGUU3.js");o(t)}catch(t){console.log(be.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(be.dim(t.stack)),process.exit(1)}});function py(e,t){try{let o=I();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(be.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(be.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
412
|
+
`}function Nn(e,t,o=".env"){let n=fg(o),s=hg(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:t,raw:`${e}=${ur(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${ur(t)}`})),qh(n,Hh(s))}function fr(e,t=".env"){return hg(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var yg="https://t.me/BotFather";async function Gh(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function zh(e,t){let o=Date.now()+t,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function wg(e={}){console.log(),console.log(ie.bold(" Connect Telegram")),console.log(),console.log(ie.dim(` 1. Open ${yg}`)),console.log(ie.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ie.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:t}=await Rn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(t)try{let{spawn:b}=await import("child_process"),$=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b($,[yg],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:o}=await Rn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});o||(console.log(ie.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Gh(o.trim());n||(console.log(ie.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ie.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(ie.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(ie.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Rn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ie.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Rn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ie.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Nn(f,o.trim()),process.env[f]=o.trim();let p=await pe(b=>{Oe(b,"channels.telegram.enabled",!0),Oe(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=xo(b,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),Oe(b,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ie.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ie.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ie.dim(` Token stored in .env as ${f}`)),console.log(ie.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ie.dim(" Daemon hot-reloaded.")):console.log(ie.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Rn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(ie.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ie.dim(" Waiting up to 90s..."));let w=await zh(o.trim(),9e4);if(!w){console.log(ie.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ie.dim(" agentx config set notifications.destination.channel telegram")),console.log(ie.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ie.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await pe(b=>{Oe(b,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ie.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ie.green(" \u2713 Default --notify target set")),console.log(ie.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ie.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ie.dim(" Daemon hot-reloaded."))}import $e from"chalk";import hr from"prompts";import{existsSync as wr,mkdirSync as Yh,readdirSync as Vh,readFileSync as $g}from"fs";import{resolve as yr}from"path";var Kh=".agentx/whatsapp-sessions";function Xh(){let e=yr(process.cwd(),".agentx/daemon.pid");if(!wr(e))return!1;try{let t=parseInt($g(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function Qh(e){if(!wr(e))return!1;try{return Vh(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function Zh(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t($e.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t($e.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;Yh(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{t($e.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){t($e.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(u),t($e.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),t($e.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function bg(e={}){if(console.log(),console.log($e.bold(" Connect WhatsApp")),console.log(),Xh()){console.log($e.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log($e.dim(" agentx daemon stop")),console.log();let{cont:l}=await hr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log($e.red(" Aborted")),process.exit(1))}let t=e.configPath||yr(process.cwd(),"agentx.json");wr(t)||(console.log($e.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse($g(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||Kh,s=yr(process.cwd(),n),i=Object.keys(o.agents||{});i.length===0&&(console.log($e.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await hr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log($e.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Qh(s)&&a){let{keep:l}=await hr({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log($e.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Zh(s,g=>console.log(g))||(console.log($e.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await pe(l=>{Oe(l,"channels.whatsapp.enabled",!0),Oe(l,"channels.whatsapp.sessionDir",n),Oe(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log($e.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log($e.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log($e.dim(` Session: ${n}`)),console.log($e.dim(" Start the daemon to begin receiving:")),console.log($e.dim(" agentx daemon start")),console.log($e.dim(" Add routes later with:")),console.log($e.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as ey}from"crypto";import Ae from"chalk";import kg from"prompts";var Us="agentx-mesh:",qs="//join/";function ty(e){return Buffer.from(e,"utf-8").toString("base64url")}function oy(e){return Buffer.from(e,"base64url").toString("utf-8")}function ny(e){return`${Us}${qs}${ty(JSON.stringify(e))}`}function sy(e){if(!e.startsWith(`${Us}${qs}`))throw new Error(`Not a mesh invite link \u2014 expected ${Us}${qs}\u2026`);let t=e.slice(Us.length+qs.length),o=JSON.parse(oy(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function iy(){return ey(32).toString("hex")}function ry(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function ay(e){return e?.node?.name||e?.node?.id||"node"}async function vg(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Ae.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(t(s,"utf-8")),r=fr("MESH_TOKEN");r||(r=iy(),Nn("MESH_TOKEN",r),console.log(Ae.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||ry(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await kg({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(Ae.red(" Aborted")),process.exit(1)),a=d}let l=await pe(d=>{Oe(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ae.red(` \u2717 ${l.error}`)),process.exit(1));let g=ny({url:a,token:r,name:ay(i),version:1});console.log(),console.log(Ae.bold(" Mesh invite")),console.log(),console.log(` ${Ae.cyan(g)}`),console.log(),console.log(Ae.dim(" Run on the other node:")),console.log(Ae.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Ae.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function xg(e,t={}){let o;try{o=sy(e)}catch(i){console.log(Ae.red(` \u2717 ${i.message}`)),process.exit(1)}let n=fr("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:i}=await kg({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Ae.red(" Aborted (keeping existing .env)")),process.exit(1))}Nn("MESH_TOKEN",o.token);let s=await pe(i=>{Oe(i,"mesh.enabled",!0);let r=xo(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Oe(i,"mesh.peers",r)},{configPath:t.configPath});s.success||(console.log(Ae.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ae.green(" \u2713 Joined mesh")),console.log(Ae.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ae.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ae.dim(" Daemon hot-reloaded.")):console.log(Ae.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(Ae.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ae.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Ae.yellow(` Could not reach ${o.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Ho=new cy().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Ho.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await wg({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Ho.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await bg({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Sg=Ho.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Sg.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await vg({url:e.url,configPath:e.config})});Sg.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await xg(e,{configPath:t.config})});Ho.action(()=>{console.log(),console.log(Jo.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Jo.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Jo.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Jo.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Jo.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Jo.dim(" GitLab connect is the next slice.")),console.log()});ne();import{Command as ly}from"commander";import fe from"chalk";var _n=new ly().name("usage").description("token usage analysis and reporting");_n.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=I(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(fe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(fe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${fe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${fe.red(String(s.totalErrors))}`),console.log(),console.log(fe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${fe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${fe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(fe.red(" Daemon not running. Start with: agentx daemon start")):console.log(fe.red(` ${e.message}`))}});_n.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(fe.red(` Script not found: ${s}`)),console.log(fe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(fe.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(fe.red(" Analysis failed. Is Python 3 installed?"))}});_n.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-HVVP22SA.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-6MNNHNMY.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(fe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${fe.dim("\xB7")} ${d}`);console.log(),console.log(fe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(fe.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(fe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(fe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(fe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(fe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=fe.dim(`${i.days}d`);console.log(` ${fe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(fe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as dy}from"commander";import be from"chalk";import{readFileSync as gy}from"fs";import{resolve as my}from"path";ne();var Bt=new dy().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Bt.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{da(my(process.cwd(),".env"))}catch{}let t=py(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-CDBPGUU3.js");o(t)}catch(t){console.log(be.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(be.dim(t.stack)),process.exit(1)}});function py(e,t){try{let o=I();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(be.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(be.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
413
413
|
`)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:t||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}Bt.command("list").description("list configured boards").action(()=>{try{let e=I();if(!e.boards?.length){console.log(be.dim(`
|
|
414
414
|
No boards configured.
|
|
415
415
|
`));return}console.log();for(let t of e.boards){console.log(` ${be.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(be.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(be.dim(` primary label: ${t.primaryToolLabel}`)),console.log(be.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(be.red(` ${e.message}`)),process.exit(1)}});Bt.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,t)=>{try{Dn(o=>{if(Array.isArray(o.boards)||(o.boards=[]),o.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(t.projects).split(",").map(i=>i.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:t.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(t.days,10)||30,closedWindowDays:parseInt(t.closedDays,10)||30};return t.label&&(s.primaryToolLabel=t.label),o.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(o){console.log(be.red(` ${o.message}`)),process.exit(1)}});Bt.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,t)=>{try{Dn(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(t.name&&(s.name=t.name,i.push(`name="${t.name}"`)),t.projects){let r=String(t.projects).split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:r},i.push(`projects=${r.length}`)}if(t.label!==void 0&&(t.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=t.label,i.push(`label="${t.label}"`))),t.days&&(s.timeRangeDays=parseInt(t.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),t.closedDays&&(s.closedWindowDays=parseInt(t.closedDays,10)||s.closedWindowDays,i.push(`closed-days=${s.closedWindowDays}`)),i.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${i.join(", ")})`})}catch(o){console.log(be.red(` ${o.message}`)),process.exit(1)}});var $r=Bt.command("column").description("manage a board's columns (add / remove / edit / list)");$r.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(gy("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!o)throw new Error(`board "${e}" not found`);let n=o.columns||[];if(n.length===0){console.log(be.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let i=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${be.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${be.dim(i)}`)}}catch(t){console.log(be.red(` ${t.message}`)),process.exit(1)}});$r.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,t,o)=>{try{Dn(n=>{let i=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!i)throw new Error(`board "${e}" not found`);if(i.columns=i.columns||[],i.columns.find(a=>a.id===t))throw new Error(`column "${t}" already exists on board "${e}"`);let r={id:t,title:o.title,kind:o.kind,scopedPrefix:o.scopedPrefix};if(o.kind==="scoped-label"){if(!o.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=o.scoped}if(o.kind==="label"){if(!o.label)throw new Error("--label required for kind=label");r.mapsToLabel=o.label}return o.accent&&(r.accent=o.accent),i.columns.push(r),`column "${t}" added to board "${e}"`})}catch(n){console.log(be.red(` ${n.message}`)),process.exit(1)}});$r.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{Dn(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(r=>r.id!==t),s.columns.length===i)throw new Error(`column "${t}" not found`);return`column "${t}" removed from board "${e}"`})}catch(o){console.log(be.red(` ${o.message}`)),process.exit(1)}});Bt.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Dn(t=>{if(!Array.isArray(t.boards)||t.boards.length===0)throw new Error("no boards configured");let o=t.boards.length;if(t.boards=t.boards.filter(n=>n.id!==e),t.boards.length===o)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(t){console.log(be.red(` ${t.message}`)),process.exit(1)}});function Dn(e){let{summary:t,backupPath:o}=Qe(n=>e(n));console.log(be.green(`
|
|
@@ -636,7 +636,7 @@ Restart the daemon to activate.
|
|
|
636
636
|
dist/
|
|
637
637
|
*.log
|
|
638
638
|
.env
|
|
639
|
-
`}import{Command as s$}from"commander";import Re from"chalk";import{writeFileSync as i$,mkdirSync as r$,existsSync as si,readFileSync as $m,appendFileSync as bm}from"fs";import{resolve as sn,dirname as xm}from"path";import{homedir as Wr}from"os";var Sm=new s$().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-
|
|
639
|
+
`}import{Command as s$}from"commander";import Re from"chalk";import{writeFileSync as i$,mkdirSync as r$,existsSync as si,readFileSync as $m,appendFileSync as bm}from"fs";import{resolve as sn,dirname as xm}from"path";import{homedir as Wr}from"os";var Sm=new s$().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-6MNNHNMY.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=l$(o);break;case"bash":s=u$(o);break;case"fish":s=f$(o);break;default:console.error(Re.red(`unsupported shell: ${n}`)),console.error(Re.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?sn(String(e.output)):a$(n);r$(xm(i),{recursive:!0}),i$(i,s),console.log(Re.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),c$(n,i,!!e.yes)});function a$(e){let t=Wr();switch(e){case"zsh":return sn(t,".zsh","completions","_agentx");case"bash":return sn(t,".bash_completion.d","agentx.bash");case"fish":return sn(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function c$(e,t,o){if(e==="zsh"){let n=sn(Wr(),".zshrc"),s=xm(t),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=si(n)?$m(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Re.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&si(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),bm(n,g.join(`
|
|
640
640
|
`)+`
|
|
641
641
|
`),console.log(Re.green("\u2713 Patched ~/.zshrc")),console.log(Re.dim("Reload your shell: exec zsh"));return}console.log(Re.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Re.cyan(` ${i}`)),l&&console.log(Re.cyan(` ${r}`)),console.log(),console.log(Re.dim("Then reload: exec zsh")),console.log(Re.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=sn(Wr(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((si(n)?$m(n,"utf-8"):"").includes(t)){console.log(Re.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&si(n)){bm(n,`
|
|
642
642
|
# agentx completion
|
|
@@ -652,4 +652,4 @@ ${h$({...t,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
|
|
|
652
652
|
${o.url}`)}catch(t){console.error(an.red(` ${t.message}`)),process.exitCode=1}});Gn.command("draft <file>").description("turn a draft JSON file ({category, title, fields}) into a pre-filled issue form link; '-' reads stdin").requiredOption("--model <model>","the model that wrote the draft").option("--models <pathOrUrl>","model list to read",Jr).action(async(e,t)=>{try{let o=await zr(t.models);if(!Hr(t.model,o)){console.log(Gr(t.model,o)),process.exitCode=1;return}let n=e==="-"?await $$():await w$(e,"utf8"),s=JSON.parse(n),{version:i}=await Zn(),r=jm({...s,fields:s.fields??{}},{model:t.model,version:i??"unknown"});console.log(r)}catch(o){console.error(an.red(` ${o.message}`)),process.exitCode=1}});async function $$(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function Y1(){let e=await Zn(),t=new b$().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");t.hook("preAction",(o,n)=>{let s=cl(n);ll(s)&&al("cli",s)});for(let o of[Ml,_l,Ho,jo,Co,tt,sl,Qt,ks,vt,Wt,qt,bs,Qg,Lt,nd,md,jn,xd,Td,Id,Rd,_d,Xd,tg,og,qo,_n,nm,kn,Rt,Sm,Gn])t.addCommand(o);for(let o of Im)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=Im.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,k$(o,74," "),""].join(`
|
|
653
653
|
`)}),t}var Im=[ee,Yo,Gt,dt,xn,Wo,Ye,St,Bt,co,Qo,Zo,Pt,Je,Do,Fs,Vg,Kg,bt,Zt,ul,eo,Jn,Wi,Ht,Ro,Bi,Xs,yt,Et,mm,um,om];function k$(e,t,o){let n=[],s="";for(let i of e)s&&s.length+i.length+2>t&&(n.push(o+s),s=""),s+=(s?", ":"")+i;return s&&n.push(o+s),n.join(`
|
|
654
654
|
`)}export{Y1 as a};
|
|
655
|
-
//# sourceMappingURL=chunk-
|
|
655
|
+
//# sourceMappingURL=chunk-6O2MCBOD.js.map
|
|
@@ -490,7 +490,7 @@ ${l}`)}let $={agentId:o,message:v,context:{channel:b,sender:m?"opencode":"openai
|
|
|
490
490
|
|
|
491
491
|
`)}}function ud(r){r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"})}function gd(r,e,t,n,s,i){r.write(`data: ${JSON.stringify({id:e,object:"chat.completion.chunk",created:t,model:n,choices:[{index:0,delta:s,finish_reason:i}]})}
|
|
492
492
|
|
|
493
|
-
`)}function hd(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);_r(r,200,{id:e,object:"chat.completion",created:t,model:n,choices:[{index:0,message:{role:"assistant",content:s},finish_reason:"stop"}],usage:{prompt_tokens:o,completion_tokens:a,total_tokens:o+a}})}function _r(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Rt=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Rt(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(Rt.levelOrder[e]<Rt.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",o=`[${this.module}]`,a=i?`${o} ${i}: ${t}`:`${o} ${t}`;console.error(a)}},At=Rt;ze(At,"levelOrder",{debug:0,info:1,warn:2,error:3});var On={version:"0.75.
|
|
493
|
+
`)}function hd(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);_r(r,200,{id:e,object:"chat.completion",created:t,model:n,choices:[{index:0,message:{role:"assistant",content:s},finish_reason:"stop"}],usage:{prompt_tokens:o,completion_tokens:a,total_tokens:o+a}})}function _r(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Rt=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Rt(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(Rt.levelOrder[e]<Rt.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",o=`[${this.module}]`,a=i?`${o} ${i}: ${t}`:`${o} ${t}`;console.error(a)}},At=Rt;ze(At,"levelOrder",{debug:0,info:1,warn:2,error:3});var On={version:"0.75.1",commit:"9630561",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};import{randomUUID as zf}from"crypto";var Dn=class{constructor(e=new _o){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!Kf.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};Yf(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:zf(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=qf(t);this.core.publish({id:t.id,at:t.at,kind:t.kind,type:n,summary:s,ref:i,agentId:o,rootId:typeof e.rootId=="string"?e.rootId:void 0,data:t})}get size(){return this.count}},Kf=["run","task","signal","mesh","channel","status"];function qf(r){switch(r.kind){case"run":return{type:r.phase,ref:r.runId,summary:[r.workflowId,r.nodeId,r.phase,r.note].filter(Boolean).join(" ")};case"task":return{type:r.phase,ref:r.taskId,summary:`${r.title??r.taskId} ${r.phase}`};case"signal":return{type:"emitted",summary:`signal ${r.name} (${r.scope})`};case"mesh":return{type:r.delta,summary:`peer ${r.peer} ${r.delta}`};case"channel":return{type:r.direction,ref:r.messageId,agentId:r.agentId,summary:`${r.channel} ${r.direction==="in"?"inbound":"outbound"}`};case"status":return{type:"status",summary:r.message}}}function Yf(r,e){return!(r.kinds&&r.kinds.length>0&&!r.kinds.includes(e.kind)||r.workflowId&&(e.kind==="run"&&e.workflowId!==r.workflowId||e.kind==="task"&&e.workflowId!==r.workflowId||e.kind==="signal"&&e.workflowId&&e.workflowId!==r.workflowId)||r.runId&&(e.kind==="run"&&e.runId!==r.runId||e.kind==="task"&&e.runId!==r.runId)||r.actor&&(e.kind!=="task"||!(e.assignedTo?.includes(r.actor)||e.submittedBy===r.actor))||r.channel&&(e.kind!=="channel"||e.channel!==r.channel))}function md(r){if(!r)return;let e=["run","task","signal","mesh","channel","status"],n=r.split(",").map(s=>s.trim()).filter(Boolean).filter(s=>e.includes(s));return n.length?n:void 0}import{createHmac as Nn,timingSafeEqual as fd}from"crypto";var jn=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),l=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let y={};for(let[v,$]of Object.entries(e.headers))(v.startsWith("x-hubspot")||v.startsWith("x-hub")||v.startsWith("x-github")||v.startsWith("x-gitlab")||v.startsWith("stripe")||v.startsWith("sentry")||v.startsWith("x-vercel")||v.startsWith("x-odoo")||v.startsWith("x-webhook")||v==="user-agent"||v==="content-type"||v==="host"||v==="x-forwarded-host"||v==="x-forwarded-proto"||v==="x-forwarded-for")&&(y[v]=$);this.log(`Webhook [${l}] reqUrl=${e.url} headers: ${JSON.stringify(y)}`)}let d=this.validateSignature(e.headers,a,l,i,e.url);if(d){this.log(`Webhook [${l}] -> ${i}: REJECTED (${d})`),this.sendJson(t,401,{error:d});return}let u=this.buildSummary(l,c,e.headers);this.log(`Webhook [${l}] -> ${i}: ${u.slice(0,100)}`);let g=this.extractEventType(l,c,e.headers),f=this.webhookEntries.find(y=>y.enabled&&y.agentId===i&&y.source===l),m=g&&f?.triggers?.[g]||f?.defaultWorkflow||null;if(await this.fireHookSafe(l,g,i,c),m&&this.workflowDispatcher)try{let y=await this.workflowDispatcher.dispatchWorkflow({workflowId:m,entityRef:{kind:"webhook",id:`${l}:${i}:${g??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:g,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${g??"\u2014"}] -> workflow=${m} (claimed=${y.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:g,workflow:m,claimed:y.claimed});return}catch(y){this.log(`Workflow dispatch failed [${l}/${g}/${m}]: ${y.message}`)}let b=this.webhookEntries.find(y=>y.enabled&&y.node&&y.agentId===i&&y.source===l);if(b?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:b.node,status:"accepted"}),this.mesh.sendTask(b.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(y=>this.log(`Mesh-forwarded webhook [${l}] -> ${b.node}/${i}: ${y?.slice(0,100)||"ok"}`),y=>this.log(`Mesh forward failed [${l}] -> ${b.node}/${i}: ${y.message}`));return}try{let y=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${l}`,sender:`webhook:${l}`}});this.sendJson(t,y.error?500:200,{ok:!y.error,agent:i,source:l,response:y.content?.slice(0,500),error:y.error,duration:y.duration})}catch(y){this.sendJson(t,500,{error:y.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let d of t.commits.slice(0,3))s.push(` - ${d.message?.split(`
|
|
494
494
|
`)[0]||"no message"} (${d.author?.name||""})`)}let l=t.object_attributes;if(l?.title&&(s.push(`Title: ${l.title}`),s.push(`State: ${l.state||""}`),s.push(`Action: ${l.action||""}`),l.source_branch&&s.push(`Branch: ${l.source_branch} -> ${l.target_branch}`),l.url&&s.push(`URL: ${l.url}`)),l?.iid&&!l?.source_branch&&(s.push(`Issue #${l.iid}: ${l.title||""}`),l.description&&s.push(`Description: ${l.description.slice(0,200)}`)),t.object_kind==="pipeline"){let d=t.object_attributes;s.push(`Pipeline: ${d?.status||""} (${d?.ref||""})`),s.push(`Duration: ${d?.duration||0}s`)}break}case"github":{let o=n["x-github-event"]||"event",a=t.repository?.full_name||"",c=t.sender?.login||"";if(s.push(`Event: ${o}`),a&&s.push(`Repository: ${a}`),c&&s.push(`Sender: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits))for(let u of t.commits.slice(0,3))s.push(` - ${u.message?.split(`
|
|
495
495
|
`)[0]||""} (${u.author?.name||""})`);let l=t.pull_request;l&&(s.push(`PR #${l.number}: ${l.title}`),s.push(`Action: ${t.action}`),s.push(`Branch: ${l.head?.ref} -> ${l.base?.ref}`));let d=t.issue;d&&(s.push(`Issue #${d.number}: ${d.title}`),s.push(`Action: ${t.action}`));break}case"stripe":{let o=t.type||"event",a=t.data?.object||{};s.push(`Event: ${o}`),a.amount&&s.push(`Amount: ${(a.amount/100).toFixed(2)} ${a.currency?.toUpperCase()||""}`),a.customer_email&&s.push(`Customer: ${a.customer_email}`),a.description&&s.push(`Description: ${a.description}`),a.status&&s.push(`Status: ${a.status}`);break}case"sentry":{let o=n["sentry-hook-resource"]||"event";s.push(`Resource: ${o}`);let a=t.data||t;a.error?.title&&s.push(`Error: ${a.error.title}`),a.error?.culprit&&s.push(`Culprit: ${a.error.culprit}`),a.error?.metadata?.value&&s.push(`Message: ${a.error.metadata.value}`),t.url&&s.push(`URL: ${t.url}`);break}case"hubspot":{let o=Array.isArray(t)?t:null,a=o||null;if(a&&a.length){s.push(`Events: ${a.length}`);for(let l of a.slice(0,3)){let d=l.subscriptionType??"?",u=l.objectId??"?",g=l.changeFlag??l.changeSource??"";s.push(` - ${d} (object ${u}${g?`, ${g}`:""})`)}}else{let l=t.subscriptionType??"event",d=t.objectId??"?";s.push(`Event: ${l} (object ${d})`)}let c=a?.[0]?.portalId??t.portalId;c!=null&&s.push(`Portal: ${c}`);break}case"odoo":{let o=typeof t.event=="string"&&t.event||typeof t.subscriptionType=="string"&&t.subscriptionType||typeof t.model=="string"&&(typeof t.action=="string"?`${t.model}.${t.action}`:t.model)||"event";s.push(`Event: ${o}`);let a=n["x-odoo-database"]||(typeof t.database=="string"?t.database:"");a&&s.push(`Database: ${a}`);let c=t.record||t;c?.id&&s.push(`Record id: ${c.id}`),c?.name&&s.push(`Name: ${String(c.name).slice(0,200)}`),c?.partner_id?.[1]&&s.push(`Partner: ${c.partner_id[1]}`),c?.email&&s.push(`Email: ${c.email}`),c?.amount_total!=null&&s.push(`Amount: ${c.amount_total}`),c?.state&&s.push(`State: ${c.state}`);break}default:s.push(`Headers: ${JSON.stringify(Object.keys(n).filter(o=>o.startsWith("x-")).slice(0,5))}`),s.push(`Payload keys: ${Object.keys(t).slice(0,10).join(", ")}`);let i=JSON.stringify(t).slice(0,500);s.push(`Body: ${i}`)}return s.join(`
|
|
496
496
|
`)}async readBody(e){return new Promise(t=>{let n="";e.on("data",s=>n+=s.toString()),e.on("end",()=>{let s;try{s=n?JSON.parse(n):{}}catch{s={raw:n}}t({raw:n,parsed:s})}),e.on("error",()=>t({raw:"",parsed:{}}))})}validateSignature(e,t,n,s,i){let o=this.webhookEntries.find(d=>d.enabled&&d.agentId===s&&d.source===n);if(!o?.secretEnv)return null;let a=process.env[o.secretEnv];if(!a)return`webhook entry "${o.id}" expects env ${o.secretEnv} but it is unset`;let c=d=>{let u=e[d.toLowerCase()];return Array.isArray(u)?u[0]:u};if(n==="github"){let d=c("x-hub-signature-256");if(!d)return"missing X-Hub-Signature-256";let u="sha256="+Nn("sha256",a).update(t).digest("hex");return ot(u,d)}if(n==="gitlab"){let d=c("x-gitlab-token");return d?ot(a,d):"missing X-Gitlab-Token"}if(n==="stripe"){let d=c("stripe-signature");if(!d)return"missing Stripe-Signature";let u=Object.fromEntries(d.split(",").map(f=>f.split("=")));if(!u.t||!u.v1)return"malformed Stripe-Signature";let g=Nn("sha256",a).update(`${u.t}.${t}`).digest("hex");return ot(g,u.v1)}if(n==="hubspot"){let d=c("x-hubspot-signature-v3"),u=c("x-hubspot-request-timestamp");if(!d)return"missing X-HubSpot-Signature-v3";if(!u)return"missing X-HubSpot-Request-Timestamp";let g=parseInt(u,10);if(!Number.isFinite(g))return"malformed X-HubSpot-Request-Timestamp";let f=Date.now()-g;if(f>5*6e4)return`HubSpot webhook is ${Math.floor(f/1e3)}s old (>5min replay window)`;let m="POST",b=i||e["x-original-uri"]||e["x-forwarded-path"]||"",y=e["x-forwarded-host"],v=e.host,$=e["x-forwarded-proto"]||"https",T=new Set;y&&b&&T.add(`${$}://${y}${b}`),v&&b&&T.add(`https://${v}${b}`),v&&b&&T.add(`http://${v}${b}`),b&&T.add(b),T.add("");for(let M of T){let D=Nn("sha256",a).update(`${m}${M}${t}${u}`).digest("base64");if(d.length===D.length&&fd(Buffer.from(d),Buffer.from(D)))return null}return`signature mismatch (tried ${T.size} URI variants)`}if(n==="odoo"){let d=c("x-odoo-signature");if(d){let g=Nn("sha256",a).update(t).digest("hex"),f=d.startsWith("sha256=")?d.slice(7):d;return ot(g,f)}let u=c("x-odoo-webhook-token")??c("x-webhook-secret");return u?ot(a,u):"missing X-Odoo-Signature or X-Odoo-Webhook-Token"}let l=c("x-webhook-secret");return l?ot(a,l):"missing X-Webhook-Secret"}sendJson(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}};function ot(r,e){if(r.length!==e.length)return"signature mismatch";let t=Buffer.from(r),n=Buffer.from(e);return fd(t,n)?null:"signature mismatch"}Ep();function Qf(r){return{insertTaskHistory:r.prepare(`
|
|
@@ -1103,4 +1103,4 @@ data: ${JSON.stringify(O)}
|
|
|
1103
1103
|
`)}catch{}},C=setInterval(()=>{try{t.write(`: ping
|
|
1104
1104
|
|
|
1105
1105
|
`)}catch{}},15e3);C.unref?.();let R=new AbortController;t.on("close",()=>{t.writableEnded||R.abort()});try{for await(let x of this.mesh.sendTaskStream(h.peer,h.message,h.agent,{context:h.context,signal:R.signal}))P(x.event,x.data)}catch(x){P("error",{error:x?.message??String(x)})}finally{clearInterval(C);try{t.end()}catch{}}break}let k=h.context,S=typeof h.senderAgentId=="string"?h.senderAgentId:void 0;if(ip(h,!0)==="callback"){let P=this.delegationGate(e,h,{callee:h.agent,peer:h.peer,message:h.message,calleeContext:k});if(!("track"in P)){let C=$s(P);this.json(t,C.status,C.body);break}}if(h.async===!0){let P=k?.channel,C=k?.chatId;if(!P||!C){this.json(t,400,{error:"async requires context.channel and context.chatId \u2014 there is no route back otherwise"});return}let R=`mesh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;this.json(t,202,{accepted:!0,taskId:R,deliverTo:`${P}:${C}`,note:"result will be delivered to the originating chat when the peer finishes"});let x=h.peer,O=h.agent,L=this.mesh;(async()=>{let N=Date.now(),W;try{W=await L.sendTask(x,h.message,O,{context:k,senderAgentId:S}),this.log(`[mesh/task async ${R}] ${x}/${O??"default"} finished in ${Date.now()-N}ms`)}catch(z){W=`Delegation to ${x}/${O??"default"} failed: ${z?.message??z}`,this.log(`[mesh/task async ${R}] failed: ${z?.message??z}`)}try{await this.router.sendOutbound({channel:P,chatId:C,text:W,agentId:k?.agentId??S,accountId:k?.accountId})}catch(z){this.log(`[mesh/task async ${R}] delivery failed: ${z?.message??z}`)}})();break}let I=await this.mesh.sendTask(h.peer,h.message,h.agent,{context:k,senderAgentId:S});this.json(t,200,{response:I});break}case"POST /webrtc/signal/out":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let p=await U(e);if(!p.kind||!p.callId||!p.from||!p.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let w=await this.webrtc.handleOutgoing(p);this.json(t,w.ok?200:400,w);break}case"POST /webrtc/signal":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let p=await U(e);if(!p.kind||!p.callId||!p.from||!p.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let w=this.webrtc.handleIncoming(p);this.json(t,w.ok?200:400,w);break}case"POST /webrtc/bot/invite":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled (channels.webrtc.bot.enabled=false)"});return}let h=await U(e),p=h.callId,w=h.target,k=h.agentId||this.config.channels.webrtc?.bot.defaultAgentId;if(!p||!w||!k){this.json(t,400,{error:"Missing: callId, target, agentId (or defaultAgentId in config)"});return}let S=await this.botManager.invite({callId:p,target:w,agentId:k});this.json(t,S.ok?200:500,S);break}case"GET /webrtc/bots":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active()});break}case"GET /webrtc/history":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active(),history:this.botManager.history()});break}case"GET /webrtc/config":{let h=this.config.channels.webrtc;if(!h?.enabled){this.json(t,404,{error:"WebRTC signaling not enabled"});return}this.json(t,200,{localName:this.config.node.name,iceServers:[...h.stunServers.map(p=>({urls:p})),...h.turnServers],peers:this.mesh?.directory().map(p=>({name:p.peer,healthy:p.healthy}))||[],camera:h.camera,agents:this.registry.list().map(p=>({id:p.id,name:p.name}))});break}case"GET /.well-known/agent-card.json":this.json(t,200,{name:this.config.node.name,description:`AgentX daemon node "${this.config.node.name}"`,url:`http://${this.config.node.bind}`,version:"1.0.0",capabilities:{streaming:!1,pushNotifications:!1,stateTransitionHistory:!1},skills:this.registry.list().map(h=>{let p=this.config.agents[h.id]||{},w=typeof p.description=="string"&&p.description.trim()||Qv(p.systemPrompt)||`Agent "${h.name}" (${h.tier})`,k=Array.isArray(p.mentions)?p.mentions.slice(0,4):[];return{id:h.id,name:h.name,description:w,tags:[h.tier,...k],color:se(h.id,p).color}}),channels:this.router.getChannelNames(),defaultInputModes:["text"],defaultOutputModes:["text"]});break;case"GET /wiki/agents":{let h=this.registry.getWikiHub();this.json(t,200,{nodeId:this.config.node.id,agents:h.summary()});break}case"GET /wiki/entries":{let h=this.registry.getWikiHub(),p=n.searchParams.get("agent")||void 0,w=n.searchParams.get("after")||void 0,k=p?h.getAgentEntries(p):h.getSharedStore().listEntries({after:w});this.json(t,200,{nodeId:this.config.node.id,count:k.length,entries:k.map(S=>({id:S.id,date:S.date,agentId:S.agentId,source:S.source,sourceContext:S.sourceContext,content:S.content}))});break}case"GET /wiki/articles":{let h=this.registry.getWikiHub(),p=n.searchParams.get("agent");if(!p){this.json(t,400,{error:"?agent= required"});break}let k=h.getAgentWiki(p).rebuildIndex();this.json(t,200,{nodeId:this.config.node.id,agentId:p,articles:k.articles});break}case"GET /wiki/article":{let h=this.registry.getWikiHub(),p=n.searchParams.get("agent"),w=n.searchParams.get("path");if(!p||!w){this.json(t,400,{error:"?agent= and ?path= required"});break}let S=h.getAgentWiki(p).readArticle(w);if(!S){this.json(t,404,{error:"Article not found"});break}this.json(t,200,{nodeId:this.config.node.id,agentId:p,path:S.path,title:S.meta.title,tags:S.meta.tags,owner:S.meta.owner,created:S.meta.created,lastUpdated:S.meta.lastUpdated,sources:S.meta.sources,content:S.content});break}case"GET /graph/schema":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,schema:h.loadSchema()});break}case"GET /graph/nodes":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,...h.loadNodes()});break}case"GET /graph/classifications":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}let p=n.searchParams.get("status")||"approved",w=Math.max(1,Math.min(1e3,parseInt(n.searchParams.get("limit")||"200",10)||200)),k=h.listByStatus(p,w);this.json(t,200,{nodeId:this.config.node.id,status:p,count:k.length,classifications:k});break}default:this.json(t,404,{error:"Not found",endpoints:["GET /health","GET /agents","GET /crons","GET /routines \u2014 schedules + cron/hook workflows with staleness flags","GET /mesh","GET /wiki/agents","GET /wiki/entries[?agent=X&after=YYYY-MM-DD]","GET /wiki/articles?agent=X","GET /graph/schema","GET /graph/nodes","GET /graph/classifications[?status=approved|pending|rejected&limit=N]","POST /task { agent, message, context?, freshSession?: bool }","GET /agents/:id \u2014 resolved agent config (permission, tier, model, persistentProcess, toolUseRequired)","POST /agents/:id/selftest { message? } \u2014 canary probe; runs a fresh-session task and reports {ok, durationMs, tokens, billedModel}","GET /traces[?agentId=&channel=&chatId=&workflowRunId=&status=&since=&until=&limit=]","GET /traces/:taskId \u2014 full per-task execution trace (steps + tokens)","GET /voice/history[?agent=&limit=&before=] \u2014 past voice exchanges, bounded summaries","GET /voice/history/:id \u2014 one voice exchange in full; POST /voice/history/:id/replay","GET /api/processes \u2014 live persistent claude processes (JSON)","POST /api/processes/kill { agentId, channel, chatId, reason? }","GET /api/actions/builtin \u2014 list shipped built-in typed actions","POST /api/actions/builtin/:name \u2014 run a built-in with JSON body input","POST /mesh/task { peer, message }","POST /webhook/:agentId[/:source] \u2014 webhook callback","POST /reload \u2014 re-read agentx.json (hot-swaps crons)","GET /daemon/restart \u2014 in-flight count, service manager, pending restart","POST /daemon/restart \u2014 restart when idle { timeoutMinutes?, onTimeout? }","POST /daemon/restart/cancel","GET /.well-known/agent-card.json","GET /call \u2014 browser UI for P2P A/V calls (requires channels.webrtc.enabled)","GET /webrtc/config \u2014 ICE servers + peer directory for the call page","GET /webrtc/events?callId=&as= \u2014 SSE stream of signaling events","POST /webrtc/signal/out \u2014 browser-originated signal, forwarded to remote peer","POST /webrtc/signal \u2014 remote-peer-originated signal, fanned out to local browser","POST /webrtc/bot/invite { callId, target, agentId } \u2014 spawn a transcribing bot peer for a call","GET /webrtc/bots \u2014 active bot sessions","POST /webrtc/camera/watch { callId, agentId } \u2014 an agent watches the phone camera share","GET /webrtc/camera/watch \u2014 agents watching a camera now","POST /webrtc/camera/watch/:id/look { note? } \u2014 ask the watching agent what it sees","POST /webrtc/camera/look { agentId } \u2014 from an agent's run: the newest frame as a PNG path"]})}}catch(i){this.json(t,500,{error:i.message})}}async handleOpenAICompat(e,t,n){let s=await U(e);await pd(e,t,n,s,{execute:(i,o,a,c)=>this.registry.execute(i,o,a,c),agentIds:Object.keys(this.config.agents),cancel:(i,o,a,c)=>{let l=this.registry.list().find(d=>d.id===i)?.runningTasks.filter(d=>d.channel===o&&d.chatId===a)||[];for(let d of l)this.registry.cancelRunningTask(d.id,c)},log:i=>this.log(i)})}json(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}resolveGitlabTokenForAgent(e){if(!e)return{token:this.config.channels.gitlab?.token,source:"global"};let t=(this.config.channels.gitlab?.agentMappings||[]).find(s=>s.agentId===e);if(t?.token)return{token:t.token,source:"agentMappings"};let n=Ku(this.config,e,"gitlab-user","tokenEnv");return n.status==="ok"&&n.value?{token:n.value,source:`integrations(${n.envVar})`}:this.config.channels.gitlab?.token?{token:this.config.channels.gitlab.token,source:"global"}:{token:void 0,source:n.status}}resolveTodayUsage(){let e=Ud();if(e==="json")return this.registry.getTodayUsage();let t=Fd(this.db);return e==="sqlite"||Object.keys(t.agents).length>0?t:this.registry.getTodayUsage()}installAgentMemorySurface(){let e=parseInt(this.config.node.bind.split(":")[1]||"18800",10);for(let t of this.registry.list()){let n=t.workspace;if(!(!n||!ht(n)))try{let s=ne(n,".claude","skills");Tp(s,{recursive:!0});let i=ne(s,Qu);if(!ht(i))Ki(i,si(e)),this.log(` memory-skill: installed remember.md \u2192 ${t.id}`);else{let o=eg(Ht(i,"utf-8"),e);o&&(Ki(i,o),this.log(` memory-skill: updated remember.md \u2192 ${t.id}`))}this.agentMemory.syncToWorkspace(t.id,n)}catch(s){this.log(` memory-skill: ${t.id} install failed \u2014 ${s?.message??s}`)}}}installAgentMcpConfig(){for(let[e,t]of Object.entries(this.config.agents)){let n=t.workspace;if(!n||!ht(n))continue;let s=fo(t);try{switch(Yu(n,s)){case"installed":this.log(` mcp: installed ${Object.keys(s).length} server(s) \u2192 ${e}`);break;case"updated":this.log(` mcp: updated .mcp.json (${Object.keys(s).length} server(s)) \u2192 ${e}`);break;case"removed":this.log(` mcp: removed managed .mcp.json (config now empty) \u2192 ${e}`);break;case"skipped-operator-owned":Object.keys(s).length>0&&this.log(` mcp: ${e} has operator-owned .mcp.json \u2014 skipping (delete file or marker to let agentx manage)`);break;case"noop":break}}catch(i){this.log(` mcp: ${e} install failed \u2014 ${i?.message??i}`)}}}workspaceFor(e){for(let t of this.registry.list())if(t.id===e)return t.workspace;return null}handleMemoryApi(e,t,n,s){return Mu(e,t,n,s,{mem:this.agentMemory,workspaceFor:i=>this.workspaceFor(i),runningTaskOwner:i=>this.registry.runningTaskOwner(i)})}async handleWorkflowEvent(e,t){if(!this.workflowDispatcher){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let n;try{n=await Z(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let s=n?.payload??n,i=s?.event,o=s?.entityRef;if(!i?.id||!o?.backend||!o?.id){this.json(t,400,{error:"missing event or entityRef"});return}let a=n?.kind;try{if(a==="trigger"&&s.trigger){let g=typeof n?.fromPeer=="string"?n.fromPeer:"unknown";this.log(`[workflows/mesh] received trigger from "${g}" source="${s.trigger.source}" chat="${s.trigger.chat??"*"}"`);let f=await this.workflowDispatcher.dispatch({trigger:s.trigger,entityRef:o,event:i,fromRemote:{peer:g}});this.log(`[workflows/mesh] dispatched broadcast: matched=${f.claimed.length} ${f.claimed.length?`(${f.claimed.map(m=>m.id).join(", ")})`:"[none \u2014 no workflow with mesh.allowRemote matched]"}`),this.json(t,202,{ok:!0,mode:"trigger-broadcast",matched:f.claimed.map(m=>m.id)});return}let d=(s.workflowId?this.workflowStore?.get(s.workflowId):null)?.nodes.find(g=>g.type.startsWith("trigger."))?.config??{},u={source:String(d.source??"hook"),project:d.filter?.project,repo:d.filter?.repo,chat:d.filter?.chat,labels:d.filter?.labels};await this.workflowDispatcher.dispatch({trigger:u,entityRef:o,event:i}),this.json(t,202,{ok:!0})}catch(c){this.log(`[workflows] /workflow/event failed: ${c.message}`),this.json(t,500,{error:c.message})}}async relayPush(e,t){let n=e.toLowerCase(),s=this.mesh?.directory().find(a=>a.peer.toLowerCase()===n);if(!s)throw new Error(`push: channels.push.relayTo "${e}" is not a mesh peer of this node`);let i=await fetch(`${s.peerUrl}/channel/send`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(s.peer)},body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)});if(!i.ok)throw new Error(`push: ${s.peer} /channel/send -> ${i.status} ${(await i.text().catch(()=>"")).slice(0,200)}`);return(await i.json().catch(()=>({}))).messageId??void 0}async handleChannelSend(e,t){let n;try{n=await Z(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let s=String(n?.channel??""),i=String(n?.chatId??""),o=String(n?.text??"");if(!s||!i||!o){this.json(t,400,{error:"channel, chatId, and text are required"});return}if(!this.router.getChannel(s)){this.json(t,404,{error:`channel "${s}" not hosted on this node`});return}try{let c=await this.router.sendOutbound({channel:s,chatId:i,text:o,accountId:typeof n.accountId=="string"?n.accountId:void 0,parseMode:typeof n.parseMode=="string"?n.parseMode:void 0,replyTo:typeof n.replyTo=="string"?n.replyTo:void 0,buttons:Array.isArray(n.buttons)?n.buttons:void 0,agentId:typeof n.agentId=="string"?n.agentId:void 0,relayed:n.relayed===!0?!0:void 0},{recordInSession:!1});this.json(t,200,{ok:!0,messageId:c??null})}catch(c){this.log(`[mesh] /channel/send "${s}" failed: ${c.message}`),this.json(t,500,{error:c.message})}}async handleChannelChats(e,t,n={}){let s=new Set,i=[],o=[],a=(l,d)=>{let u=0;for(let g of l)!g.id||s.has(g.id)||(s.add(g.id),i.push({...g,source:d}),u++);u>0&&o.push(`${d}:${u}`)},c=this.router.getChannel(t);if(c?.listKnownChats)try{a(c.listKnownChats(),"local")}catch{}else if(c?.listChats)try{a(c.listChats().map(l=>({id:l.jid,name:l.name,kind:l.isGroup?"group":"dm"})),"local")}catch{}if(!n.localOnly&&this.mesh){let l=this.mesh.directory().filter(d=>d.healthy&&d.channels?.includes(t));await Promise.allSettled(l.map(async d=>{try{let u=await fetch(`${d.peerUrl}/channels/${encodeURIComponent(t)}/chats?local=1`,{headers:this.mesh.authHeaders(d.peer),signal:AbortSignal.timeout(5e3)});if(!u.ok)return;let g=await u.json();Array.isArray(g.chats)&&a(g.chats.map(f=>({id:f.id,name:f.name,kind:f.kind??"dm",accountId:f.accountId})),`mesh:${d.peer}`)}catch{}}))}this.json(e,200,{channel:t,source:o.join(", ")||"none",chats:i})}async handleWorkflowManualRun(e,t,n){if(!this.workflowDispatcher||!this.workflowStore){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let s=this.workflowStore.get(n);if(!s){this.json(t,404,{error:`unknown workflow "${n}"`});return}let i=s.nodes.find(m=>m.type.startsWith("trigger."));if(!i){this.json(t,400,{error:`workflow "${n}" has no trigger node`});return}let o;try{o=await Z(e)}catch{o={}}let a=!!o?.force,c=o?.payload||{};if(i.type!=="trigger.manual"&&!a){this.json(t,409,{error:`workflow "${n}" trigger is "${i.type}"`,hint:'pass { "force": true } to fire anyway with a synthesized event (for testing)'});return}let l=i.config??{},d=a?String(l.source??"manual"):"manual",u=String(c.entityId||c.chatId||`manual-${Date.now().toString(36)}`),g={backend:a&&l.source?"channel":"manual",id:u},f=`manual:${n}:${u}:${Date.now()}`;try{let b=(await this.workflowDispatcher.dispatch({trigger:a?{source:d,project:l.filter?.project,repo:l.filter?.repo,chat:l.filter?.chat,labels:l.filter?.labels}:{source:"manual"},entityRef:g,event:{id:f,payload:c}})).runs[0]?.id;this.json(t,b?200:202,{ok:!0,runId:b,entityRef:g,source:d,force:a})}catch(m){this.log(`[workflows] manual run "${n}" failed: ${m.message}`),this.json(t,500,{error:m.message})}}},qi=Yi;ze(qi,"MESH_PROTECTED_PATHS",new Set(["/task","/ask","/mesh/task","/mesh/inbox/send","/workflow/event","/workflow/transition","/channel/send","/webrtc/signal","/gitlab/react","/gitlab/send-note","/gitlab/log-time","/github/send-comment"]));function Qv(r){if(typeof r!="string")return"";let e=r.trim();if(!e)return"";let t=e.match(/^[^.!?\n]+[.!?]?/),n=(t?t[0]:e).trim();return n.length>140?n.slice(0,137)+"\u2026":n}function Z(r){return new Promise((e,t)=>{let n="";r.setEncoding("utf8"),r.on("data",s=>{n+=s}),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch(s){t(s)}}),r.on("error",t)})}function Zv(r,e){let t=["model","workspace","tier","permissionMode","mcpServers"],n=new Set,s=new Set([...Object.keys(r),...Object.keys(e)]);for(let i of s){let o=r[i],a=e[i];if(!o||!a){n.add("add/remove");continue}for(let c of t)JSON.stringify(o[c])!==JSON.stringify(a[c])&&n.add(`${i}.${c}`)}return Array.from(n).slice(0,6)}async function U(r){return new Promise((e,t)=>{let n="";r.on("data",s=>n+=s.toString()),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch{e({})}}),r.on("error",t)})}Rp();function j_(r){typeof r=="string"&&(Bt.error(r),process.exit(1)),r instanceof Error&&(Bt.error(r.message),process.exit(1)),Bt.error("Something went wrong. Please try again."),process.exit(1)}export{Ee as a,Ce as b,dn as c,kS as d,ur as e,Ge as f,vt as g,$t as h,Ve as i,kn as j,lI as k,Ed as l,cy as m,ly as n,Od as o,Me as p,Fn as q,jd as r,Un as s,nT as t,sT as u,qr as v,dx as w,ux as x,gx as y,Uu as z,Cw as A,yx as B,wx as C,qn as D,Ct as E,mg as F,Eb as G,PA as H,es as I,Yg as J,rs as K,se as L,is as M,wk as N,hh as O,bk as P,Nt as Q,ds as R,gs as S,vh as T,Ci as U,Ie as V,fe as W,Eh as X,Ch as Y,Mh as Z,Ph as _,Ms as $,fp as aa,Ji as ba,wp as ca,Fv as da,HC as ea,qi as fa,j_ as ga};
|
|
1106
|
-
//# sourceMappingURL=chunk-
|
|
1106
|
+
//# sourceMappingURL=chunk-VCE2DBHB.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-6O2MCBOD.js";import"./chunk-JGEHN4VE.js";import"./chunk-GZAGG3ES.js";import"./chunk-UBGQ7AOG.js";import"./chunk-Z3IP66SL.js";import"./chunk-C4CDVE2E.js";import"./chunk-RKPAVWXF.js";import"./chunk-SZDACK6O.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-VCE2DBHB.js";import"./chunk-SKIDVXWG.js";import"./chunk-ISBM2C3D.js";import"./chunk-BYJ3A55Y.js";import"./chunk-7XB2CVC3.js";import"./chunk-LQRBGQIR.js";import"./chunk-ZVP6GB4G.js";import"./chunk-WC4TPXD3.js";import"./chunk-AQASR6KR.js";import"./chunk-2D3RYIDU.js";import"./chunk-EKJG63EJ.js";import"./chunk-DIHLL45I.js";import"./chunk-OEUII2QP.js";import"./chunk-WP6KLXTP.js";import"./chunk-N6EWZGIX.js";import"./chunk-DP7RTNDM.js";import"./chunk-BAPRRPNU.js";import"./chunk-SFQUP3BP.js";import"./chunk-S5JGQKON.js";import"./chunk-2AXFYDWF.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-PUU2ESI2.js";import"./chunk-IR2Q63IV.js";import"./chunk-VWTBHLMX.js";import"./chunk-L3MEAKL7.js";import"./chunk-66VSATH3.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-APYG4RB3.js";import"./chunk-MYVHVJWZ.js";import"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-5B5J3WVW.js";import"./chunk-KEJOBB5E.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import"./chunk-6HPJKD3X.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import"./chunk-CXZ4YDHJ.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
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as L}from"./chunk-C245D4BZ.js";import{d as St,e as kt,f as vt,fa as Tt,g as xt,ga as Mt,h as $t,i as Ct,j as Pt,k as bt}from"./chunk-
|
|
1
|
+
import{a as L}from"./chunk-C245D4BZ.js";import{d as St,e as kt,f as vt,fa as Tt,g as xt,ga as Mt,h as $t,i as Ct,j as Pt,k as bt}from"./chunk-VCE2DBHB.js";import"./chunk-SKIDVXWG.js";import"./chunk-ISBM2C3D.js";import"./chunk-BYJ3A55Y.js";import"./chunk-7XB2CVC3.js";import"./chunk-LQRBGQIR.js";import"./chunk-ZVP6GB4G.js";import"./chunk-WC4TPXD3.js";import"./chunk-AQASR6KR.js";import"./chunk-2D3RYIDU.js";import"./chunk-EKJG63EJ.js";import{T as yt,k as lt,l as ct,m as dt,n as mt,o as pt}from"./chunk-DIHLL45I.js";import"./chunk-OEUII2QP.js";import"./chunk-WP6KLXTP.js";import"./chunk-N6EWZGIX.js";import"./chunk-DP7RTNDM.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-BAPRRPNU.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-S5JGQKON.js";import"./chunk-2AXFYDWF.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{s as ut}from"./chunk-PUU2ESI2.js";import"./chunk-IR2Q63IV.js";import"./chunk-VWTBHLMX.js";import"./chunk-L3MEAKL7.js";import{a as ht}from"./chunk-66VSATH3.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-APYG4RB3.js";import"./chunk-MYVHVJWZ.js";import"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-5B5J3WVW.js";import{f as gt,g as ft}from"./chunk-KEJOBB5E.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import{j as it,k as rt,l as at}from"./chunk-6HPJKD3X.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-5MUJZODV.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{A as st,B as ot,D as nt,y as tt}from"./chunk-CXZ4YDHJ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
|
|
2
2
|
`)}
|
|
3
3
|
|
|
4
4
|
${t}`}async function It(o){let{loadLocalSkills:e}=await import("./loader-YFVSSYSL.js");return e(o)}async function Ot(o,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=program-
|
|
1
|
+
import{a}from"./chunk-6O2MCBOD.js";import"./chunk-JGEHN4VE.js";import"./chunk-GZAGG3ES.js";import"./chunk-UBGQ7AOG.js";import"./chunk-Z3IP66SL.js";import"./chunk-C4CDVE2E.js";import"./chunk-RKPAVWXF.js";import"./chunk-SZDACK6O.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-VCE2DBHB.js";import"./chunk-SKIDVXWG.js";import"./chunk-ISBM2C3D.js";import"./chunk-BYJ3A55Y.js";import"./chunk-7XB2CVC3.js";import"./chunk-LQRBGQIR.js";import"./chunk-ZVP6GB4G.js";import"./chunk-WC4TPXD3.js";import"./chunk-AQASR6KR.js";import"./chunk-2D3RYIDU.js";import"./chunk-EKJG63EJ.js";import"./chunk-DIHLL45I.js";import"./chunk-OEUII2QP.js";import"./chunk-WP6KLXTP.js";import"./chunk-N6EWZGIX.js";import"./chunk-DP7RTNDM.js";import"./chunk-BAPRRPNU.js";import"./chunk-SFQUP3BP.js";import"./chunk-S5JGQKON.js";import"./chunk-2AXFYDWF.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-PUU2ESI2.js";import"./chunk-IR2Q63IV.js";import"./chunk-VWTBHLMX.js";import"./chunk-L3MEAKL7.js";import"./chunk-66VSATH3.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-APYG4RB3.js";import"./chunk-MYVHVJWZ.js";import"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-5B5J3WVW.js";import"./chunk-KEJOBB5E.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import"./chunk-6HPJKD3X.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import"./chunk-CXZ4YDHJ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{a as buildProgram};
|
|
2
|
+
//# sourceMappingURL=program-6MNNHNMY.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentix-cli",
|
|
3
|
-
"version": "0.75.
|
|
3
|
+
"version": "0.75.1",
|
|
4
4
|
"description": "AI operations layer for small and medium businesses. Routes Telegram, WhatsApp, GitLab, GitHub, crons, webhooks, and mesh tasks to AI agents. Web wizard for operators, CLI for engineers. Self-hosted.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|
|
File without changes
|
|
File without changes
|
|
File without changes
|