agentix-cli 0.44.0 → 0.44.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/dist/{board-dashboard-OYGL7Z7X.js → board-dashboard-B5FMUMGA.js} +108 -114
- package/dist/board-dashboard-B5FMUMGA.js.map +1 -0
- package/dist/{chunk-Q3Q6FTFY.js → chunk-3TL5EIVN.js} +4 -4
- package/dist/chunk-MX5GCR7Y.js +36 -0
- package/dist/chunk-MX5GCR7Y.js.map +1 -0
- package/dist/{chunk-7HHVZJO4.js → chunk-ZQOGAUQS.js} +130 -130
- package/dist/chunk-ZQOGAUQS.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/{program-HGI5C2MP.js → program-JLCKBO2A.js} +2 -2
- package/package.json +1 -1
- package/dist/board-dashboard-OYGL7Z7X.js.map +0 -1
- package/dist/chunk-7HHVZJO4.js.map +0 -1
- package/dist/chunk-P2Y7DFFP.js +0 -36
- package/dist/chunk-P2Y7DFFP.js.map +0 -1
- /package/dist/{chunk-Q3Q6FTFY.js.map → chunk-3TL5EIVN.js.map} +0 -0
- /package/dist/{program-HGI5C2MP.js.map → program-JLCKBO2A.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as ha,b as An,g as ya}from"./chunk-7A7RC3R4.js";import{b as da}from"./chunk-YQVR2HQS.js";import{a as Do,b as la,f as En,i as Cs,j as ua,l as fa}from"./chunk-SAFAI4AV.js";import{a as ga,c as ma,d as pa}from"./chunk-2TJ5L7CB.js";import{a as $s,b as pr,c as ks,g as ur,h as fr,j as hr,k as yr,m as wr,n as br,o as $r}from"./chunk-WLVQDEOT.js";import{a as tt}from"./chunk-GV7S5BAX.js";import{e as sr}from"./chunk-GSX4NK2N.js";import{c as ir}from"./chunk-SZDACK6O.js";import{$ as aa,A as zr,B as st,C as yo,D as Yr,E as Ss,F as Es,G as Vr,H as Kr,I as _t,J as kn,K as Xr,L as Qr,M as Zr,N as ea,O as it,P as oa,Q as ta,R as $e,S as vn,T as Pt,U as As,V as na,W as xn,X as Sn,Y as ra,Z as Is,_ as js,a as kr,aa as ca,b as vr,h as Ar,i as Or,j as Rt,k as hn,l as Tr,m as Ir,n as jr,o as Cr,p as Fr,q as Ur,r as qr,s as Wr,t as Br,u as Jr,v as Gr,w as Hr,x as Dt,y as xs,z as $n}from"./chunk-
|
|
1
|
+
import{a as ha,b as An,g as ya}from"./chunk-7A7RC3R4.js";import{b as da}from"./chunk-YQVR2HQS.js";import{a as Do,b as la,f as En,i as Cs,j as ua,l as fa}from"./chunk-SAFAI4AV.js";import{a as ga,c as ma,d as pa}from"./chunk-2TJ5L7CB.js";import{a as $s,b as pr,c as ks,g as ur,h as fr,j as hr,k as yr,m as wr,n as br,o as $r}from"./chunk-WLVQDEOT.js";import{a as tt}from"./chunk-GV7S5BAX.js";import{e as sr}from"./chunk-GSX4NK2N.js";import{c as ir}from"./chunk-SZDACK6O.js";import{$ as aa,A as zr,B as st,C as yo,D as Yr,E as Ss,F as Es,G as Vr,H as Kr,I as _t,J as kn,K as Xr,L as Qr,M as Zr,N as ea,O as it,P as oa,Q as ta,R as $e,S as vn,T as Pt,U as As,V as na,W as xn,X as Sn,Y as ra,Z as Is,_ as js,a as kr,aa as ca,b as vr,h as Ar,i as Or,j as Rt,k as hn,l as Tr,m as Ir,n as jr,o as Cr,p as Fr,q as Ur,r as qr,s as Wr,t as Br,u as Jr,v as Gr,w as Hr,x as Dt,y as xs,z as $n}from"./chunk-ZQOGAUQS.js";import{A as Os,B as ia,C as Ts,k as vs,l as yn,m as wn,n as Nr,o as Rr,p as Dr,q as _r,r as Pr,u as bn,v as Mr,w as Lr,z as sa}from"./chunk-MX5GCR7Y.js";import{a as xr,d as Sr,e as Er}from"./chunk-V5FZJUK4.js";import{D as gr,N as mr,h as Zi,q as er,s as Zo,u as ys,v as tr,x as ho}from"./chunk-T76YTN34.js";import{b as et,c as un,d as fn,e as ot,f as nr,g as Ro,h as Nt}from"./chunk-TCJ3SMOF.js";import{d as bs,f as lr}from"./chunk-VMDA2SX2.js";import{a as Qi}from"./chunk-QLTM3F7M.js";import{a as or,e as cr}from"./chunk-BIFJSQB5.js";import{f as rr,g as ar,h as ws}from"./chunk-76Z4VHDX.js";import{b as ue,c as Se,d as nt,e as dr}from"./chunk-NSYY5NCR.js";import{h as Xi}from"./chunk-DWADWDMU.js";import{b as fo,d as pn,f as hs}from"./chunk-MTVRYTLL.js";import{b as Qo,d as Ki}from"./chunk-2GIDVZ4H.js";import{a as fs,b as Li,c as Zl,d as gn,e as Fi,f as Ji,g as od,h as Gi,i as td,m as Xo,n as zi,o as Yi,s as Vi,v as Ze,w as Ct}from"./chunk-6HMZ5TTM.js";import{a as ro,b as Ko,e as qi,f as jt}from"./chunk-F4HZTZHW.js";import{a as Hi,b as nd}from"./chunk-AJONZWLT.js";import{a as io,b as Ql}from"./chunk-L2WSPY6S.js";import{k as Ui,l as _,m as mn,o as ge}from"./chunk-QJANPP4C.js";import{g as Wi,k as Bi,l as ed}from"./chunk-BH3GTCZ6.js";import{a as Xl}from"./chunk-FIOB3MEX.js";import{Command as sd}from"commander";var wa=new sd().name("a2a").description("start an A2A (Agent-to-Agent) protocol server for external agent integration").option("--port <port>","server port","3171").option("--host <host>","server host","0.0.0.0").option("-p, --provider <provider>","AI provider","claude-code").option("-m, --model <model>","model to use").option("--api-key <key>","API key for the provider").option("-c, --cwd <cwd>","working directory",process.cwd()).option("--no-cors","disable CORS headers").action(async e=>{await new vr({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});ge();import{Command as id}from"commander";import{execFileSync as ao}from"node:child_process";import{cpSync as ba,existsSync as Ds,mkdirSync as Ns,mkdtempSync as rd,readFileSync as ad,rmSync as cd,writeFileSync as $a}from"node:fs";import{dirname as Rs,join as je,resolve as ka}from"node:path";import{homedir as On,release as ld,tmpdir as dd}from"node:os";import{fileURLToPath as gd}from"node:url";import{setTimeout as md}from"node:timers/promises";function Tn(){let e=Nr(process.platform,process.arch,ld());if(e)throw new Error(e)}function Mt(){return`gui/${process.getuid()}/${vs}`}function rt(){return je(On(),"Library/LaunchAgents",`${vs}.plist`)}async function va(){try{ao("launchctl",["bootout",Mt()],{stdio:"pipe"})}catch{}for(let e=0;e<30;e++){try{ao("launchctl",["print",Mt()],{stdio:"pipe"})}catch{return}await md(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function xa(){if(!Ds(rt()))throw new Error("Run agentx desktop install first.");let e=!0;try{ao("launchctl",["print",Mt()],{stdio:"pipe"})}catch{e=!1}e||ao("launchctl",["bootstrap",`gui/${process.getuid()}`,rt()],{stdio:"pipe"}),ao("launchctl",["kickstart",Mt()],{stdio:"pipe"})}function pd(){let e=Rs(gd(import.meta.url));for(let o of[ka(e,".."),ka(e,"../.."),process.cwd()])try{if(JSON.parse(ad(je(o,"package.json"),"utf8")).name==="agentix-cli"&&Ds(je(o,"apps/mac-voice/build.sh")))return o}catch{}throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var at=new id("desktop").description("install and control the macOS desktop assistant");at.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","agent to use (defaults to the first configured agent)").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{Tn();let o=_(),t=Rr(o.agents,e.agent),n=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,s=pd(),i=je(On(),"Applications");if(console.log(`Desktop assistant \u2192 ${je(i,yn)}
|
|
2
2
|
Computer-use helper \u2192 ${je(i,wn)}
|
|
3
3
|
Agent \u2192 ${t}
|
|
4
4
|
Daemon \u2192 ${n}
|
|
@@ -379,7 +379,7 @@ return aid ?? null`}function Nm(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
|
|
|
379
379
|
settings \u2014 without this an attached production identity would be less
|
|
380
380
|
guarded than a spawned one.)`))):console.log(L.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${L.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(L.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Jo.command("uninstall").description("remove the attach hooks from ~/.claude/settings.json").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--remove-guard","also remove the PreToolUse guard hook").action(e=>{try{let o=Ta({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${L.green("\u2713")} Removed attach hooks from ${L.gray(o.path)} (${o.events.join(", ")})`:`${L.gray("Nothing to remove.")}`),e.removeGuard||console.log(L.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(L.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});ge();import{Command as up}from"commander";import fe from"chalk";var Vn=new up().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Bc(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=_(e.config);o||(o=n.dashboard?.daemonUrl||""),t||(t=n.dashboard?.token||"")}catch{}return o||(o="http://localhost:18800"),{baseUrl:o.replace(/\/+$/,""),token:t}}function Jc(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function Wc(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s`:o<3600?`${Math.round(o/60)}m`:o<86400?`${Math.round(o/3600)}h`:`${Math.round(o/86400)}d`}function fp(e){return e==="busy"?fe.magenta:e==="warm-hot"?fe.green:e==="warm-cold"?fe.cyan:e==="idle"?fe.yellow:e==="dead"?fe.red:fe.dim}Vn.command("list").description("list every live persistent claude process").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("--json","emit JSON").action(async e=>{let{baseUrl:o,token:t}=Bc(e),n;try{n=await fetch(`${o}/api/processes`,{headers:Jc(t)})}catch(r){console.log(fe.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(fe.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(fe.red(` HTTP ${n.status} from ${o}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(fe.dim(" (no processes)"));return}for(let r of i){let a=fp(r.state)(r.state.padEnd(9)),c=Wc(r.spawnedAt),l=r.lastTurnAt?Wc(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?fe.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?fe.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):fe.dim("sess=\u2014"),u=r.pendingTaskId?fe.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${fe.bold(r.key.agentId)}${fe.dim(":"+r.key.channel+":"+r.key.chatId)} ${fe.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${u}`),r.deadReason&&console.log(` ${fe.red("dead:")} ${r.deadReason}`)}});Vn.command("kill <agentId> <channel> <chatId>").description("force-kill one persistent process (the next dispatch will spawn fresh)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("-r, --reason <reason>","kill reason (recorded on the dead-process snapshot)","operator-cli").action(async(e,o,t,n)=>{let{baseUrl:s,token:i}=Bc(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Jc(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(fe.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(fe.dim(" daemon has no persistent-process registry"));return}if(!r.ok){let a=`HTTP ${r.status}`;try{let c=await r.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(fe.red(` ${a}`)),process.exit(1)}console.log(fe.green(` killed ${e}:${o}:${t}`))});import{Command as hp}from"commander";import Ne from"chalk";import{existsSync as ci,rmSync as yp}from"fs";import{resolve as li}from"path";var ht=new hp().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");ht.command("add <agentId>").description("build or refresh an agent's lexical index from one or more globs").argument("<globs...>","glob patterns relative to cwd (e.g. './docs/**/*.md')").option("-v, --verbose","log each indexed file").action(async(e,o,t)=>{o.length===0&&(console.log(Ne.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await rr(e,o,{verbose:n}),r=Date.now()-s;console.log(Ne.green(` \u2713 indexed ${i.docs} doc(s) for ${Ne.bold(e)} in ${r}ms`)),console.log(Ne.dim(` \u2192 ${i.path}`))});ht.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=li(e.cwd,".agentx","rag");if(!ci(o)){console.log(Ne.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>ci(li(o,s,"index.json")));if(n.length===0){console.log(Ne.dim(" (no indexes)"));return}for(let s of n.sort()){let i=ws(s);console.log(` ${Ne.bold(s)} ${i.docs} doc(s) ${Ne.dim(i.path)}`)}});ht.command("search <agentId> <query>").description("query an agent's index \u2014 useful for debugging recall before the agent calls rag.lexical").option("-k, --k <n>","top-k results","5").option("--json","emit JSON").action((e,o,t)=>{let n=parseInt(t.k,10)||5,s=ar(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=ws(e);i.exists?console.log(Ne.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Ne.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Ne.bold(i.title)} ${Ne.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Ne.dim(i.path)}`),console.log(` ${Ne.dim(i.snippet.slice(0,200))}`)});ht.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=li(process.cwd(),".agentx","rag",e);if(!ci(o)){console.log(Ne.dim(` no index for ${e} \u2014 nothing to clear`));return}yp(o,{recursive:!0,force:!0}),console.log(Ne.green(` \u2713 cleared index for ${e}`))});ge();import{Command as wp}from"commander";import K from"chalk";import yt from"prompts";var Go=new wp().name("backlog").description("manage the local backlog used by business workSource=backlog");function Kt(e){let o=_(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new sa(n)}}function bp(e){return e?K.cyan(`${e.type}:${e.project}#${e.iid}`):K.dim("manual")}function $p(e){return{todo:K.gray("todo"),doing:K.yellow("doing"),blocked:K.red("blocked"),done:K.green("done")}[e]}Go.command("list",{isDefault:!0}).description("list backlog items").option("--status <status>","filter by status (todo|doing|blocked|done)").option("--assignee <agent>","filter by assignee").option("--source <type>","filter by source.type (gitlab|github|manual)").option("-c, --config <path>","config path").action(async e=>{let{store:o}=Kt(e.config),t=o.list();if(e.status&&(t=t.filter(n=>n.status===e.status)),e.assignee&&(t=t.filter(n=>n.assignee===e.assignee)),e.source&&(t=t.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!t.length){console.log(K.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?K.magenta(`@${n.assignee}`):K.dim("unassigned");console.log(` ${$p(n.status).padEnd(7)} ${bp(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(K.dim(` ${n.source.url}`))}console.log(),console.log(K.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});Go.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,o,t)=>{let n=Kt(t.config);n.store.findById(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(K.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=ia([o],i.source,n.config),a=await Ts(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(K.dim(" sync:"),...c));console.log(a.ok?K.dim(` synced -> ${a.url??i.source.type}`):K.yellow(` sync failed: ${a.error}`))}});Go.command("done <id>").description("mark an item as done; closes the upstream issue if linked").option("--note <text>","comment to post upstream").option("--close","also close the upstream issue (default: only labels change)",!1).option("-c, --config <path>","config path").action(async(e,o)=>{let t=Kt(o.config);t.store.findById(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(K.green(` done: ${s.title}`)),s.source){let i=await Ts(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(K.dim(" sync:"),...r));console.log(i.ok?K.dim(` synced -> ${i.url??s.source.type}`):K.yellow(` sync failed: ${i.error}`))}});Go.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,o)=>{let{store:t}=Kt(o.config);t.remove(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1)),console.log(K.green(` removed ${e}`))});Go.command("import").description("import open issues from gitlab/github into the backlog (interactive)").option("--source <type>","source type (gitlab|github)").option("--project <id>","project id (group/repo for gitlab, owner/repo for github)").option("--assignee <agent>","assign all imported items to this agentId").option("-c, --config <path>","config path").action(async e=>{let o=Kt(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(K.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let y=[t&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await yt({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!t&&(console.error(K.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(K.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?vp(o.config):xp(o.config);y.length?(i=(await yt({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...y.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await yt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await yt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await yt({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(K.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await Sp(o.config,i,a):await Ep(o.config,i,a);if(!c.length){console.log(K.yellow(" no open issues matched"));return}console.log(K.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(o.store.list().map(y=>y.id)),d=c.map(y=>{let k=Os({type:s,project:l,iid:y.iid,url:y.url}),b=g.has(k),S=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${S}${b?K.dim(" (already imported)"):""}`,value:y,disabled:b}}),f=(await yt({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!f.length){console.log(K.dim(" nothing selected"));return}let p=f.map(y=>{let k={type:s,host:s==="gitlab"?kp(o.config):void 0,project:l,iid:y.iid,url:y.url};return{id:Os(k),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),w=o.store.addMany(p);console.log(K.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(K.dim(` ${y.id} \u2014 ${y.title}`))});function kp(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function vp(e){let o=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&o.add(n.project);let t=e.business?.workSource;if(t?.type==="gitlab")for(let n of t.projects??[])o.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&o.add(n.id);return[...o].sort()}function xp(e){let o=new Set;for(let t of e.channels.github?.routes??[])t.repo&&t.repo!=="*"&&o.add(t.repo);return[...o].sort()}async function Sp(e,o,t){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});t&&s.set("search",t);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(o)}/issues?${s}`,{headers:{"PRIVATE-TOKEN":n.token}});if(!i.ok)throw new Error(`GitLab ${i.status}: ${await i.text().catch(()=>"")}`);let r=await i.json();return Array.isArray(r)?r.map(a=>({iid:a.iid,title:a.title,description:a.description||void 0,labels:Array.isArray(a.labels)?a.labels.map(c=>typeof c=="string"?c:c.name):[],milestone:a.milestone?.title||void 0,assignee:a.assignee?.username||a.assignees?.[0]?.username||void 0,url:a.web_url})):[]}async function Ep(e,o,t){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(t){let c=`repo:${o} is:issue is:open ${t}`;i=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let l=await fetch(i,{headers:s});if(!l.ok)throw new Error(`GitHub ${l.status}: ${await l.text().catch(()=>"")}`);return((await l.json()).items??[]).map(Gc)}i=`https://api.github.com/repos/${o}/issues?state=open&per_page=100&sort=updated&direction=desc`;let r=await fetch(i,{headers:s});if(!r.ok)throw new Error(`GitHub ${r.status}: ${await r.text().catch(()=>"")}`);let a=await r.json();return Array.isArray(a)?a.filter(c=>!c.pull_request).map(Gc):[]}function Gc(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(o=>typeof o=="string"?o:o.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as Ap}from"commander";import q from"chalk";import{existsSync as Op,readFileSync as Tp}from"fs";import{resolve as Ip}from"path";import jp from"prompts";ge();function Hc(e){let o=e||Ip(process.cwd(),"agentx.json");return Op(o)||(console.log(q.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Tp(o,"utf-8"))}async function Cp(e,o){if(!e)return;if(e==="me"){let n=o?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(q.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await jp([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let t=e.split(":");if(t.length>=2)return{channel:t[0],chatId:t[1],accountId:t[2]};console.log(q.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var go=new Ap().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');go.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>",`IANA timezone (default: ${ks})`,ks).option("--timeout <seconds>","max run time","600").option("--model <model>","override model").option("--disabled","create but leave disabled").option("--dry-run","print what would be written without writing").action(async(e,o)=>{if(!e){go.help();return}o.agent||(console.log(q.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(q.red(' --do "<prompt>" is required')),process.exit(1));let t=$s(e);t||(console.log(q.red(` Couldn't parse: "${e}"`)),console.log(q.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(q.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(q.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=Hc(o.config),s=Ui(n);n.agents?.[o.agent]||(console.log(q.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(q.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await Cp(o.notify,s),r=o.id||pr(t.matched,o.agent),a=fr({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:ur(o.onError),enabled:!o.disabled}),c=a.onError,l=await ue(d=>Se(d,`crons.${r}`,a),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(q.red(` \u2717 ${l.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(q.green(` \u2713 ${g} cron ${q.cyan(r)}`)),console.log(q.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(q.dim(` Agent: ${o.agent}`)),i&&console.log(q.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(q.dim(` On error: ${c.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(q.dim(" Daemon hot-reloaded."))});go.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async e=>{let t=Hc(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(q.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?q.yellow("\u25D0"):i.enabled?q.green("\u25CF"):q.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${q.cyan(s.padEnd(32))} ${q.dim(i.schedule.padEnd(14))} ${q.dim("\u2192")} ${i.agent}`),console.log(q.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(q.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(q.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=yr(hr(i.schedule,c),c);console.log(q.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(q.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,o]of[["on",!0],["off",!1]])go.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await $r(t,o);n.success||(console.log(q.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(q.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(q.dim(" Daemon hot-reloaded."))});go.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await ue(t=>{if(!nt(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);dr(t,`crons.${e}`)});o.success||(console.log(q.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(q.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(q.dim(" Daemon hot-reloaded."))});for(let[e,o,t]of[["approve",wr,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",br,"reject an agent's pending create/delete request (drops the request)"]])go.command(`${e} <id>`).description(t).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await o(n,{configPath:s.config});i.success||(console.log(q.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(q.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(q.dim(" Daemon hot-reloaded."))});go.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=$s(o);t||(console.log(q.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(q.green(` "${o}"`)),console.log(q.dim(` \u2192 ${t.cron}`)),console.log(q.dim(` \u2192 ${t.human}`))});import{Command as eu}from"commander";import wt from"chalk";import Z from"chalk";import Qt from"prompts";import{readFileSync as Np,writeFileSync as Rp,existsSync as Dp}from"fs";import{resolve as zc}from"path";var _p=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Pp(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function di(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Yc(e=".env"){let o=zc(e);if(!Dp(o))return[];let t=Np(o,"utf-8"),n=[];for(let s of t.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let i=s.match(_p);i?n.push({kind:"kv",key:i[1],value:Pp(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Mp(e){return e.map(o=>o.kind==="kv"?`${o.key}=${di(o.value)}`:o.raw).join(`
|
|
381
381
|
`)+`
|
|
382
|
-
`}function Xt(e,o,t=".env"){let n=zc(t),s=Yc(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${di(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${di(o)}`})),Rp(n,Mp(s))}function gi(e,o=".env"){return Yc(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var Vc="https://t.me/BotFather";async function Lp(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function Fp(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function Kc(e={}){console.log(),console.log(Z.bold(" Connect Telegram")),console.log(),console.log(Z.dim(` 1. Open ${Vc}`)),console.log(Z.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Z.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await Qt({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),S=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(S,[Vc],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Qt({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(Z.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Lp(t.trim());n||(console.log(Z.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Z.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(Z.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(Z.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Qt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(S=>({title:S,value:S})),initial:0})).agent),g||(console.log(Z.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Qt({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(Z.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Xt(f,t.trim()),process.env[f]=t.trim();let p=await ue(b=>{Se(b,"channels.telegram.enabled",!0),Se(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let S=nt(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;S.includes(A)||(S.push(A),Se(b,`agents.${g}.mentions`,S))},{configPath:e.configPath});if(p.success||(console.log(Z.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(Z.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(Z.dim(` Token stored in .env as ${f}`)),console.log(Z.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(Z.dim(" Daemon hot-reloaded.")):console.log(Z.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await Qt({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(Z.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Z.dim(" Waiting up to 90s..."));let y=await Fp(t.trim(),9e4);if(!y){console.log(Z.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Z.dim(" agentx config set notifications.destination.channel telegram")),console.log(Z.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Z.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await ue(b=>{Se(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(Z.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(Z.green(" \u2713 Default --notify target set")),console.log(Z.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Z.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(Z.dim(" Daemon hot-reloaded."))}import he from"chalk";import mi from"prompts";import{existsSync as ui,mkdirSync as Up,readdirSync as qp,readFileSync as Xc}from"fs";import{resolve as pi}from"path";var Wp=".agentx/whatsapp-sessions";function Bp(){let e=pi(process.cwd(),".agentx/daemon.pid");if(!ui(e))return!1;try{let o=parseInt(Xc(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Jp(e){if(!ui(e))return!1;try{return qp(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Gp(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(he.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(he.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;Up(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(he.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(he.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(he.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(he.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Qc(e={}){if(console.log(),console.log(he.bold(" Connect WhatsApp")),console.log(),Bp()){console.log(he.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(he.dim(" agentx daemon stop")),console.log();let{cont:l}=await mi({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(he.red(" Aborted")),process.exit(1))}let o=e.configPath||pi(process.cwd(),"agentx.json");ui(o)||(console.log(he.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Xc(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Wp,s=pi(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(he.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await mi({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(he.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Jp(s)&&a){let{keep:l}=await mi({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(he.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Gp(s,g=>console.log(g))||(console.log(he.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ue(l=>{Se(l,"channels.whatsapp.enabled",!0),Se(l,"channels.whatsapp.sessionDir",n),Se(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(he.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(he.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(he.dim(` Session: ${n}`)),console.log(he.dim(" Start the daemon to begin receiving:")),console.log(he.dim(" agentx daemon start")),console.log(he.dim(" Add routes later with:")),console.log(he.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Hp}from"crypto";import ke from"chalk";import Zc from"prompts";var Kn="agentx-mesh:",Xn="//join/";function zp(e){return Buffer.from(e,"utf-8").toString("base64url")}function Yp(e){return Buffer.from(e,"base64url").toString("utf-8")}function Vp(e){return`${Kn}${Xn}${zp(JSON.stringify(e))}`}function Kp(e){if(!e.startsWith(`${Kn}${Xn}`))throw new Error(`Not a mesh invite link \u2014 expected ${Kn}${Xn}\u2026`);let o=e.slice(Kn.length+Xn.length),t=JSON.parse(Yp(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function Xp(){return Hp(32).toString("hex")}function Qp(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Zp(e){return e?.node?.name||e?.node?.id||"node"}async function el(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(ke.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=gi("MESH_TOKEN");r||(r=Xp(),Xt("MESH_TOKEN",r),console.log(ke.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Qp(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Zc({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(ke.red(" Aborted")),process.exit(1)),a=d}let l=await ue(d=>{Se(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(ke.red(` \u2717 ${l.error}`)),process.exit(1));let g=Vp({url:a,token:r,name:Zp(i),version:1});console.log(),console.log(ke.bold(" Mesh invite")),console.log(),console.log(` ${ke.cyan(g)}`),console.log(),console.log(ke.dim(" Run on the other node:")),console.log(ke.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(ke.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function ol(e,o={}){let t;try{t=Kp(e)}catch(i){console.log(ke.red(` \u2717 ${i.message}`)),process.exit(1)}let n=gi("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Zc({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(ke.red(" Aborted (keeping existing .env)")),process.exit(1))}Xt("MESH_TOKEN",t.token);let s=await ue(i=>{Se(i,"mesh.enabled",!0);let r=nt(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Se(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(ke.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(ke.green(" \u2713 Joined mesh")),console.log(ke.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(ke.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(ke.dim(" Daemon hot-reloaded.")):console.log(ke.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(ke.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(ke.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(ke.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var bt=new eu().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");bt.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await Kc({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});bt.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Qc({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var tl=bt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");tl.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await el({url:e.url,configPath:e.config})});tl.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await ol(e,{configPath:o.config})});bt.action(()=>{console.log(),console.log(wt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${wt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${wt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${wt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${wt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(wt.dim(" GitLab connect is the next slice.")),console.log()});ge();import{Command as ou}from"commander";import de from"chalk";var Zt=new ou().name("usage").description("token usage analysis and reporting");Zt.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=_(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(de.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(de.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${de.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${de.red(String(s.totalErrors))}`),console.log(),console.log(de.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${de.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${de.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(de.red(" Daemon not running. Start with: agentx daemon start")):console.log(de.red(` ${e.message}`))}});Zt.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(de.red(` Script not found: ${s}`)),console.log(de.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(de.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(de.red(" Analysis failed. Is Python 3 installed?"))}});Zt.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:o}=await import("./surface-usage-UREILT2E.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-HGI5C2MP.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(de.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${de.dim("\xB7")} ${d}`);console.log(),console.log(de.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(de.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(de.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(de.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(de.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(de.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=de.dim(`${i.days}d`);console.log(` ${de.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(de.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as tu}from"commander";import ye from"chalk";import{resolve as nu}from"path";ge();var Ao=new tu().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Ao.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{Ki(nu(process.cwd(),".env"))}catch{}let o=su(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-OYGL7Z7X.js");t(o)}catch(o){console.log(ye.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(ye.dim(o.stack)),process.exit(1)}});function su(e,o){try{let t=_();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(ye.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(ye.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
382
|
+
`}function Xt(e,o,t=".env"){let n=zc(t),s=Yc(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${di(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${di(o)}`})),Rp(n,Mp(s))}function gi(e,o=".env"){return Yc(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var Vc="https://t.me/BotFather";async function Lp(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function Fp(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function Kc(e={}){console.log(),console.log(Z.bold(" Connect Telegram")),console.log(),console.log(Z.dim(` 1. Open ${Vc}`)),console.log(Z.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Z.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await Qt({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),S=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(S,[Vc],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Qt({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(Z.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Lp(t.trim());n||(console.log(Z.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Z.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(Z.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(Z.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Qt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(S=>({title:S,value:S})),initial:0})).agent),g||(console.log(Z.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Qt({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(Z.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Xt(f,t.trim()),process.env[f]=t.trim();let p=await ue(b=>{Se(b,"channels.telegram.enabled",!0),Se(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let S=nt(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;S.includes(A)||(S.push(A),Se(b,`agents.${g}.mentions`,S))},{configPath:e.configPath});if(p.success||(console.log(Z.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(Z.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(Z.dim(` Token stored in .env as ${f}`)),console.log(Z.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(Z.dim(" Daemon hot-reloaded.")):console.log(Z.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await Qt({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(Z.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Z.dim(" Waiting up to 90s..."));let y=await Fp(t.trim(),9e4);if(!y){console.log(Z.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Z.dim(" agentx config set notifications.destination.channel telegram")),console.log(Z.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Z.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await ue(b=>{Se(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(Z.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(Z.green(" \u2713 Default --notify target set")),console.log(Z.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Z.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(Z.dim(" Daemon hot-reloaded."))}import he from"chalk";import mi from"prompts";import{existsSync as ui,mkdirSync as Up,readdirSync as qp,readFileSync as Xc}from"fs";import{resolve as pi}from"path";var Wp=".agentx/whatsapp-sessions";function Bp(){let e=pi(process.cwd(),".agentx/daemon.pid");if(!ui(e))return!1;try{let o=parseInt(Xc(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Jp(e){if(!ui(e))return!1;try{return qp(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Gp(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(he.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(he.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;Up(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(he.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(he.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(he.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(he.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Qc(e={}){if(console.log(),console.log(he.bold(" Connect WhatsApp")),console.log(),Bp()){console.log(he.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(he.dim(" agentx daemon stop")),console.log();let{cont:l}=await mi({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(he.red(" Aborted")),process.exit(1))}let o=e.configPath||pi(process.cwd(),"agentx.json");ui(o)||(console.log(he.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Xc(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Wp,s=pi(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(he.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await mi({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(he.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Jp(s)&&a){let{keep:l}=await mi({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(he.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Gp(s,g=>console.log(g))||(console.log(he.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ue(l=>{Se(l,"channels.whatsapp.enabled",!0),Se(l,"channels.whatsapp.sessionDir",n),Se(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(he.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(he.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(he.dim(` Session: ${n}`)),console.log(he.dim(" Start the daemon to begin receiving:")),console.log(he.dim(" agentx daemon start")),console.log(he.dim(" Add routes later with:")),console.log(he.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Hp}from"crypto";import ke from"chalk";import Zc from"prompts";var Kn="agentx-mesh:",Xn="//join/";function zp(e){return Buffer.from(e,"utf-8").toString("base64url")}function Yp(e){return Buffer.from(e,"base64url").toString("utf-8")}function Vp(e){return`${Kn}${Xn}${zp(JSON.stringify(e))}`}function Kp(e){if(!e.startsWith(`${Kn}${Xn}`))throw new Error(`Not a mesh invite link \u2014 expected ${Kn}${Xn}\u2026`);let o=e.slice(Kn.length+Xn.length),t=JSON.parse(Yp(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function Xp(){return Hp(32).toString("hex")}function Qp(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Zp(e){return e?.node?.name||e?.node?.id||"node"}async function el(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(ke.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=gi("MESH_TOKEN");r||(r=Xp(),Xt("MESH_TOKEN",r),console.log(ke.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Qp(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Zc({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(ke.red(" Aborted")),process.exit(1)),a=d}let l=await ue(d=>{Se(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(ke.red(` \u2717 ${l.error}`)),process.exit(1));let g=Vp({url:a,token:r,name:Zp(i),version:1});console.log(),console.log(ke.bold(" Mesh invite")),console.log(),console.log(` ${ke.cyan(g)}`),console.log(),console.log(ke.dim(" Run on the other node:")),console.log(ke.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(ke.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function ol(e,o={}){let t;try{t=Kp(e)}catch(i){console.log(ke.red(` \u2717 ${i.message}`)),process.exit(1)}let n=gi("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Zc({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(ke.red(" Aborted (keeping existing .env)")),process.exit(1))}Xt("MESH_TOKEN",t.token);let s=await ue(i=>{Se(i,"mesh.enabled",!0);let r=nt(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Se(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(ke.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(ke.green(" \u2713 Joined mesh")),console.log(ke.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(ke.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(ke.dim(" Daemon hot-reloaded.")):console.log(ke.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(ke.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(ke.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(ke.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var bt=new eu().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");bt.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await Kc({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});bt.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Qc({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var tl=bt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");tl.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await el({url:e.url,configPath:e.config})});tl.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await ol(e,{configPath:o.config})});bt.action(()=>{console.log(),console.log(wt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${wt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${wt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${wt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${wt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(wt.dim(" GitLab connect is the next slice.")),console.log()});ge();import{Command as ou}from"commander";import de from"chalk";var Zt=new ou().name("usage").description("token usage analysis and reporting");Zt.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=_(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(de.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(de.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${de.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${de.red(String(s.totalErrors))}`),console.log(),console.log(de.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${de.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${de.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(de.red(" Daemon not running. Start with: agentx daemon start")):console.log(de.red(` ${e.message}`))}});Zt.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(de.red(` Script not found: ${s}`)),console.log(de.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(de.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(de.red(" Analysis failed. Is Python 3 installed?"))}});Zt.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:o}=await import("./surface-usage-UREILT2E.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-JLCKBO2A.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(de.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${de.dim("\xB7")} ${d}`);console.log(),console.log(de.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(de.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(de.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(de.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(de.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(de.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=de.dim(`${i.days}d`);console.log(` ${de.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(de.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as tu}from"commander";import ye from"chalk";import{resolve as nu}from"path";ge();var Ao=new tu().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Ao.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{Ki(nu(process.cwd(),".env"))}catch{}let o=su(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-B5FMUMGA.js");t(o)}catch(o){console.log(ye.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(ye.dim(o.stack)),process.exit(1)}});function su(e,o){try{let t=_();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(ye.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(ye.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
383
383
|
`)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:o||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}Ao.command("list").description("list configured boards").action(()=>{try{let e=_();if(!e.boards?.length){console.log(ye.dim(`
|
|
384
384
|
No boards configured.
|
|
385
385
|
`));return}console.log();for(let o of e.boards){console.log(` ${ye.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(ye.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(ye.dim(` primary label: ${o.primaryToolLabel}`)),console.log(ye.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(ye.red(` ${e.message}`)),process.exit(1)}});Ao.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,o)=>{try{en(t=>{if(Array.isArray(t.boards)||(t.boards=[]),t.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(o.projects).split(",").map(i=>i.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:o.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(o.days,10)||30,closedWindowDays:parseInt(o.closedDays,10)||30};return o.label&&(s.primaryToolLabel=o.label),t.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(t){console.log(ye.red(` ${t.message}`)),process.exit(1)}});Ao.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,o)=>{try{en(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(o.name&&(s.name=o.name,i.push(`name="${o.name}"`)),o.projects){let r=String(o.projects).split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:r},i.push(`projects=${r.length}`)}if(o.label!==void 0&&(o.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=o.label,i.push(`label="${o.label}"`))),o.days&&(s.timeRangeDays=parseInt(o.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),o.closedDays&&(s.closedWindowDays=parseInt(o.closedDays,10)||s.closedWindowDays,i.push(`closed-days=${s.closedWindowDays}`)),i.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${i.join(", ")})`})}catch(t){console.log(ye.red(` ${t.message}`)),process.exit(1)}});var fi=Ao.command("column").description("manage a board's columns (add / remove / edit / list)");fi.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(Xl("fs").readFileSync("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!t)throw new Error(`board "${e}" not found`);let n=t.columns||[];if(n.length===0){console.log(ye.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let i=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${ye.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${ye.dim(i)}`)}}catch(o){console.log(ye.red(` ${o.message}`)),process.exit(1)}});fi.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,o,t)=>{try{en(n=>{let i=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!i)throw new Error(`board "${e}" not found`);if(i.columns=i.columns||[],i.columns.find(a=>a.id===o))throw new Error(`column "${o}" already exists on board "${e}"`);let r={id:o,title:t.title,kind:t.kind,scopedPrefix:t.scopedPrefix};if(t.kind==="scoped-label"){if(!t.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=t.scoped}if(t.kind==="label"){if(!t.label)throw new Error("--label required for kind=label");r.mapsToLabel=t.label}return t.accent&&(r.accent=t.accent),i.columns.push(r),`column "${o}" added to board "${e}"`})}catch(n){console.log(ye.red(` ${n.message}`)),process.exit(1)}});fi.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{en(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(r=>r.id!==o),s.columns.length===i)throw new Error(`column "${o}" not found`);return`column "${o}" removed from board "${e}"`})}catch(t){console.log(ye.red(` ${t.message}`)),process.exit(1)}});Ao.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{en(o=>{if(!Array.isArray(o.boards)||o.boards.length===0)throw new Error("no boards configured");let t=o.boards.length;if(o.boards=o.boards.filter(n=>n.id!==e),o.boards.length===t)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(o){console.log(ye.red(` ${o.message}`)),process.exit(1)}});function en(e){let{summary:o,backupPath:t}=Do(n=>e(n));console.log(ye.green(`
|
|
@@ -600,7 +600,7 @@ Restart the daemon to activate.
|
|
|
600
600
|
dist/
|
|
601
601
|
*.log
|
|
602
602
|
.env
|
|
603
|
-
`}import{Command as Rf}from"commander";import Te from"chalk";import{writeFileSync as Df,mkdirSync as _f,existsSync as ms,readFileSync as Bl,appendFileSync as Jl}from"fs";import{resolve as Tt,dirname as zl}from"path";import{homedir as Pi}from"os";var Yl=new Rf().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:o}=await import("./program-
|
|
603
|
+
`}import{Command as Rf}from"commander";import Te from"chalk";import{writeFileSync as Df,mkdirSync as _f,existsSync as ms,readFileSync as Bl,appendFileSync as Jl}from"fs";import{resolve as Tt,dirname as zl}from"path";import{homedir as Pi}from"os";var Yl=new Rf().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:o}=await import("./program-JLCKBO2A.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Lf(t);break;case"bash":s=Bf(t);break;case"fish":s=Jf(t);break;default:console.error(Te.red(`unsupported shell: ${n}`)),console.error(Te.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?Tt(String(e.output)):Pf(n);_f(zl(i),{recursive:!0}),Df(i,s),console.log(Te.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Mf(n,i,!!e.yes)});function Pf(e){let o=Pi();switch(e){case"zsh":return Tt(o,".zsh","completions","_agentx");case"bash":return Tt(o,".bash_completion.d","agentx.bash");case"fish":return Tt(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Mf(e,o,t){if(e==="zsh"){let n=Tt(Pi(),".zshrc"),s=zl(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=ms(n)?Bl(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Te.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&ms(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Jl(n,g.join(`
|
|
604
604
|
`)+`
|
|
605
605
|
`),console.log(Te.green("\u2713 Patched ~/.zshrc")),console.log(Te.dim("Reload your shell: exec zsh"));return}console.log(Te.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Te.cyan(` ${i}`)),l&&console.log(Te.cyan(` ${r}`)),console.log(),console.log(Te.dim("Then reload: exec zsh")),console.log(Te.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Tt(Pi(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((ms(n)?Bl(n,"utf-8"):"").includes(o)){console.log(Te.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&ms(n)){Jl(n,`
|
|
606
606
|
# agentx completion
|
|
@@ -611,4 +611,4 @@ ${s}
|
|
|
611
611
|
`)}function Mi(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function _i(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=Mi(e.description||""),r=["complete -c agentx",o.map(a=>`-n "${a}"`).join(" ")];return t&&r.push(`-s ${t}`),n&&r.push(`-l ${n}`),r.push(`-d "${s}"`),r.join(" ")}async function xS(){let e=await ca(),o=new Gf().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");o.hook("preAction",(t,n)=>{let s=ma(n);pa(s)&&ga("cli",s)});for(let t of[Ma,Da,bt,at,eo,da,Po,_n,go,Jo,Dn,Tl,So,Ya,nc,pc,hc,yc,Dc,Lc,Fc,Yn,Zt,Rl,qt,$o,Yl])o.addCommand(t);for(let t of Kl)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Kl.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Hf(t,74," "),""].join(`
|
|
612
612
|
`)}),o}var Kl=[ee,$t,Vo,Qe,Bt,ht,qe,po,Ao,Go,St,Et,xo,Le,Jt,Vn,Al,co,gt,wa,Mo,ln,Us,Io,dt,qs,is,Oo,jo,Ll,Ul,Nl];function Hf(e,o,t){let n=[],s="";for(let i of e)s&&s.length+i.length+2>o&&(n.push(t+s),s=""),s+=(s?", ":"")+i;return s&&n.push(t+s),n.join(`
|
|
613
613
|
`)}export{xS as a};
|
|
614
|
-
//# sourceMappingURL=chunk-
|
|
614
|
+
//# sourceMappingURL=chunk-3TL5EIVN.js.map
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import{i as se}from"./chunk-BIFJSQB5.js";import{existsSync as Re,readdirSync as Ie,readFileSync as ve,statSync as Ae}from"fs";import{resolve as je}from"path";function re(s,e,t=Date.now(),r=7){let n=r*864e5,o=new Map;for(let a of e){let i=o.get(a.workflowId);i?i.push(a):o.set(a.workflowId,[a])}return s.map(a=>{let i=o.get(a.id)??[],l=i.filter(f=>t-f.at<=n),c=i.filter(f=>t-f.at>n&&t-f.at<=n*2),u=l.filter(f=>f.status==="failed").length,m=i.filter(f=>f.status==="paused").length,d=i.length?Math.max(...i.map(f=>f.at)):null,g=i.length?c.length>0&&l.length===0?"dormant":l.length>0&&u*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:a.id,name:a.name||a.id,state:g,lastRunAt:d,recent:l.length,prior:c.length,failed:u,paused:m}}).sort((a,i)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[a.state]-l[i.state]||(i.lastRunAt??0)-(a.lastRunAt??0)})}var _=new Map;function wt(s,e=1e3){if(!Re(s))return[];let t=Ie(s).filter(o=>o.endsWith(".jsonl")).map(o=>{let a=je(s,o);return{path:a,mtime:Ae(a).mtimeMs}}).sort((o,a)=>a.mtime-o.mtime).slice(0,e),r=new Set(t.map(o=>o.path));for(let o of _.keys())r.has(o)||_.delete(o);let n=[];for(let{path:o,mtime:a}of t){let i=_.get(o);if(i&&i.mtime===a){i.summary&&n.push(i.summary);continue}let l=Te(o,a);_.set(o,{mtime:a,summary:l}),l&&n.push(l)}return n}function Te(s,e){try{let t=ve(s,"utf-8").split(`
|
|
2
|
+
`).filter(Boolean);if(!t.length)return null;let r=JSON.parse(t[0]),n=r.run?.workflowId;if(!n)return null;let o=r.run?.status??"unknown";for(let a=t.length-1;a>=0;a--){let i=JSON.parse(t[a]),l=i.status??i.run?.status;if(l){o=l;break}}return{workflowId:n,status:o,at:e}}catch{return null}}var _e={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},y={routines:200,summary:160,filters:6,filterValue:60,text:120},Le=(s,e,t)=>{try{return se(s,e,t)}catch{return null}},ie=864e5;function Rt(s){let e=s.now??Date.now(),t={..._e,...s.thresholds},r=s.nextFire??Le,n=[];for(let i of s.crons){let l=s.cronRuns.get(i.id)??[],c=i.timezone||"UTC",u=l.map(g=>({at:Date.parse(g.startedAt),status:g.status})),m=l[0],d={id:`cron:${i.id}`,source:"cron",kind:"schedule",name:S(i.id,y.text),trigger:{schedule:S(i.schedule,y.text),timezone:c},agent:i.agent||null,enabled:i.enabled,state:i.enabled?"enabled":"disabled",nextRunAt:i.enabled?B(i.nextRun)??B(r(i.schedule,new Date(e),c)):null,lastRun:m?{at:m.startedAt,status:m.status,summary:Be(m.status==="success"?void 0:m.errorSummary,y.summary)}:null,lastSuccessAt:l.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:oe(u),sampledRuns:l.length,flags:[],attention:null};d.flags=ae(d,u,i.schedule,c,null,e,t,r),n.push(le(d))}let o=new Map(re(s.workflows.map(i=>({id:i.id,name:i.title})),s.workflowRuns,e).map(i=>[i.id,i])),a=new Map;for(let i of s.workflowRuns){let l=a.get(i.workflowId);l?l.push(i):a.set(i.workflowId,[i])}for(let i of s.workflows){let l=i.nodes.find(x=>x.type.startsWith("trigger."));if(!l||l.type!=="trigger.cron"&&l.type!=="trigger.hook")continue;let c=l.config??{},u=i.state||"active",m=u==="active",d=(a.get(i.id)??[]).slice().sort((x,D)=>D.at-x.at),g=d.map(x=>({at:x.at,status:Pe(x.status)})),f=g[0],h=l.type==="trigger.cron",b=typeof c.spec=="string"?c.spec:"",O=typeof c.timezone=="string"?c.timezone:"UTC",j={id:`workflow:${i.id}`,source:"workflow",kind:h?"schedule":"event",name:S(i.title||i.id,y.text),trigger:h?{schedule:S(b,y.text),timezone:O}:{event:S(typeof c.event=="string"?c.event:"",y.text),filters:De(c.filter,i)},agent:Oe(i),enabled:m,state:u,nextRunAt:h&&m&&b?B(r(b,new Date(e),O)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let x=g.find(D=>D.status==="success");return x?new Date(x.at).toISOString():null})(),consecutiveFailures:oe(g),sampledRuns:d.length,flags:[],attention:null},T=Date.parse(i.updated||i.created||"");j.flags=h?ae(j,g,b,O,Number.isFinite(T)?T:null,e,t,r):Ee(j,o.get(i.id)?.state==="dormant",Number.isFinite(T)?T:null,e,t),n.push(le(j))}return n.sort(Ce).slice(0,y.routines)}function oe(s){let e=0;for(let t of s)if(!(t.status==="running"||t.status==="paused"||t.status==="unknown"))if(t.status==="failed"||t.status==="timeout")e++;else break;return e}function ae(s,e,t,r,n,o,a,i){let l=[],c=e.length?e[0].at:null;if(!s.enabled){let d=ue(c,n,o,a);return d&&l.push(d),l}if(s.consecutiveFailures>=a.failStreak&&l.push({reason:"failing",detail:`${s.consecutiveFailures} failed attempts in a row`}),c===null)return l.push({reason:"never-ran",detail:"No persisted attempt"}),l;let u=new Date(c),m=null;for(let d=0;d<a.missedFires&&(m=i(t,u,r),!!m);d++)u=m;return m&&o>m.getTime()+a.graceMs&&l.push({reason:"overdue",detail:`No attempt since ${new Date(c).toISOString()}; ${a.missedFires} scheduled fires missed`}),l}function Ee(s,e,t,r,n){let o=[],a=s.lastRun?Date.parse(s.lastRun.at):null;if(!s.enabled){let i=ue(a,t,r,n);return i&&o.push(i),o}return s.consecutiveFailures>=n.failStreak&&o.push({reason:"failing",detail:`${s.consecutiveFailures} failed runs in a row`}),a===null?o.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&o.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),o}function ue(s,e,t,r){let n=Math.max(s??0,e??0);return n&&t-n<r.disabledDays*ie?null:{reason:"disabled-long",detail:n?`Disabled; no activity for ${Math.floor((t-n)/ie)} days`:"Disabled and never ran"}}function le(s){let e=new Set(s.flags.map(t=>t.reason));return s.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,s}var ce={critical:0,warning:1,info:2};function Ce(s,e){let t=s.attention?ce[s.attention]:3,r=e.attention?ce[e.attention]:3;return t-r||Number(e.enabled)-Number(s.enabled)||s.name.localeCompare(e.name)}function Pe(s){switch(s){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function Oe(s){if(s.ownerAgent)return S(s.ownerAgent,y.text);let e=s.nodes.find(t=>t.type==="agent"&&typeof t.config?.agentId=="string"&&t.config.agentId);return e?S(String(e.config.agentId),y.text):null}function De(s,e){let t=[],r=e?.project;if(r&&t.push(S(`project=${r}`,y.filterValue)),s&&typeof s=="object"&&!Array.isArray(s))for(let[n,o]of Object.entries(s)){let a=Array.isArray(o)?o.map(String):o==null?[]:[String(o)];a.length&&t.push(S(`${n}=${a.join(",")}`,y.filterValue))}return t.slice(0,y.filters)}function B(s){if(!s)return null;let e=s instanceof Date?s:new Date(s);return Number.isFinite(e.getTime())?e.toISOString():null}function S(s,e){return s.length<=e?s:s.slice(0,e-3)+"..."}function Be(s,e){return s===void 0?void 0:S(s,e)}function L(s){return(Array.isArray(s)?s[0]:s)?.trim()??""}function Ue(s){try{return new URL(s).host.toLowerCase()}catch{return null}}function Fe(s=process.env){return new Set((s.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function vt(s,e=Fe()){let t=L(s.origin);if(t){if(e.has(t.replace(/\/+$/,"").toLowerCase()))return"same-origin";let n=Ue(t),o=[L(s.host),L(s["x-forwarded-host"])].filter(Boolean).map(a=>a.toLowerCase());return n&&o.includes(n)?"same-origin":"foreign"}let r=L(s["sec-fetch-site"]).toLowerCase();return r==="cross-site"||r==="same-site"?"foreign":"none"}function At(s){let e=(s||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}import{readFileSync as F,writeFileSync as he,existsSync as W,readdirSync as Je,statSync as Xe}from"fs";import{resolve as N,join as Ve}from"path";import{existsSync as de,mkdirSync as We,readFileSync as Ne,writeFileSync as ge}from"fs";import{dirname as Me,resolve as me}from"path";import{z as p}from"zod";var ze=p.object({type:p.enum(["gitlab","github"]),host:p.string().optional(),project:p.string(),iid:p.number().int().positive(),url:p.string()}),He=p.object({id:p.string(),title:p.string(),description:p.string().optional(),assignee:p.string().optional(),labels:p.array(p.string()).default([]),milestone:p.string().optional(),status:p.enum(["todo","doing","blocked","done"]).default("todo"),priority:p.number().int().optional(),estimatedSeconds:p.number().int().optional(),source:ze.optional(),importedAt:p.string().optional(),createdAt:p.string(),updatedAt:p.string(),blocker:p.string().optional(),doneNote:p.string().optional()}),Ge=p.object({version:p.literal(1),items:p.array(He).default([])}),E=class{constructor(e){this.path=e}jsonPath(){return me(process.cwd(),this.path).replace(/\.md$/i,".json")}mdPath(){return me(process.cwd(),this.path).replace(/\.json$/i,".md")}exists(){return de(this.jsonPath())}load(){let e=this.jsonPath();if(!de(e))return{version:1,items:[]};let t=Ne(e,"utf-8");try{return Ge.parse(JSON.parse(t))}catch(r){throw new Error(`Backlog file invalid (${e}): ${r.message}`)}}save(e){let t=this.jsonPath();We(Me(t),{recursive:!0}),ge(t,JSON.stringify(e,null,2)+`
|
|
3
|
+
`),ge(this.mdPath(),this.toMarkdown(e))}list(){return this.load().items}findById(e){return this.list().find(t=>t.id===e)}add(e){let t=this.load();if(t.items.some(o=>o.id===e.id))throw new Error(`backlog item ${e.id} already exists`);let r=new Date().toISOString(),n={...e,labels:e.labels??[],status:e.status??"todo",createdAt:e.createdAt??r,updatedAt:r};return t.items.push(n),this.save(t),n}addMany(e){let t=this.load(),r=new Set(t.items.map(a=>a.id)),n=new Date().toISOString(),o=[];for(let a of e){if(r.has(a.id))continue;let i={...a,labels:a.labels??[],status:a.status??"todo",createdAt:a.createdAt??n,updatedAt:n};t.items.push(i),o.push(i),r.add(i.id)}return o.length&&this.save(t),o}update(e,t){let r=this.load(),n=r.items.findIndex(a=>a.id===e);if(n<0)throw new Error(`backlog item ${e} not found`);let o={...r.items[n],...t,id:r.items[n].id,createdAt:r.items[n].createdAt,updatedAt:new Date().toISOString()};return r.items[n]=o,this.save(r),o}remove(e){let t=this.load(),r=t.items.length;return t.items=t.items.filter(n=>n.id!==e),t.items.length===r?!1:(this.save(t),!0)}toMarkdown(e){let t=["# Backlog","","_Generated from `backlog.json`. Do not edit by hand \u2014 use `agentx backlog` commands._",""],r={doing:[],blocked:[],todo:[],done:[]};for(let o of e.items)r[o.status].push(o);let n=[["doing","Doing"],["blocked","Blocked"],["todo","To Do"],["done","Done"]];for(let[o,a]of n)if(r[o].length){t.push(`## ${a}`,"");for(let i of r[o]){let l=o==="done"?"x":" ",c=i.assignee?`@${i.assignee} `:"",u=i.estimatedSeconds?` [time: ${Math.round(i.estimatedSeconds/60)}m]`:"",m=i.source?` (${i.source.type}: ${i.source.project}#${i.source.iid})`:"";t.push(`- [${l}] ${c}${i.title}${u}${m}`),i.source?.url&&t.push(` - <${i.source.url}>`),i.labels.length&&t.push(` - labels: ${i.labels.join(", ")}`),i.milestone&&t.push(` - milestone: ${i.milestone}`),i.blocker&&t.push(` - BLOCKED: ${i.blocker}`)}t.push("")}return t.join(`
|
|
4
|
+
`)}};function Et(s){return`${s.type}:${s.project}:${s.iid}`}function fe(s,e,t){let r=[];if(e.type==="gitlab"){let n=t.channels.gitlab?.agentMappings??[];for(let o of s){let a=n.find(i=>i.agentId===o);a?.gitlabUsernames?.length?r.push(a.gitlabUsernames[0]):r.push(o)}}else if(e.type==="github"){let n=t.channels.github?.agentMappings??[];for(let o of s){let a=n.find(i=>i.agentId===o);a?.githubUsernames?.length?r.push(a.githubUsernames[0]):r.push(o)}}return r}async function U(s,e,t,r=()=>{}){return s.source?s.source.type==="gitlab"?Ke(s.source,e,t,r):s.source.type==="github"?qe(s.source,e,t,r):{ok:!1,error:`unknown source.type ${s.source.type}`,attempts:[]}:{ok:!0,attempts:[]}}async function Ke(s,e,t,r){let n=t.channels.gitlab,o=n?.token,a=n?.host||(s.host?`https://${s.host}`:void 0);if(!o||!a)return{ok:!1,error:"gitlab token/host not configured",attempts:[]};let i=[],l=async(g,f={})=>fetch(`${a}/api/v4${g}`,{...f,headers:{"PRIVATE-TOKEN":o,"Content-Type":"application/json",...f.headers||{}}}),c=encodeURIComponent(s.project),u;e.assigneeUsernames!==void 0&&(u=(await Promise.all(e.assigneeUsernames.map(async f=>{try{let h=await fetch(`${a}/api/v4/users?username=${encodeURIComponent(f)}`,{headers:{"PRIVATE-TOKEN":o}});if(!h.ok)return null;let b=await h.json();return Array.isArray(b)&&b[0]?.id?b[0].id:null}catch{return null}}))).filter(f=>typeof f=="number"));let m;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")m=0;else try{let g=await l(`/projects/${c}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);if(g.ok){let f=await g.json();Array.isArray(f)&&f[0]?.id&&(m=f[0].id)}}catch(g){r(`[backlog-sync] milestone lookup failed: ${g.message}`)}let d={};if(e.title!==void 0&&(d.title=e.title),e.description!==void 0&&(d.description=e.description),e.labels!==void 0&&(d.labels=e.labels.join(",")),e.addLabels?.length&&(d.add_labels=e.addLabels.join(",")),e.removeLabels?.length&&(d.remove_labels=e.removeLabels.join(",")),u!==void 0&&(d.assignee_ids=u),m!==void 0&&(d.milestone_id=m),e.state&&(d.state_event=e.state==="closed"?"close":"reopen"),Object.keys(d).length)try{let g=await l(`/projects/${c}/issues/${s.iid}`,{method:"PUT",body:JSON.stringify(d)});if(i.push({kind:"PUT issue",ok:g.ok,status:g.status}),!g.ok){let f=await g.text().catch(()=>"");return{ok:!1,attempts:i,error:`PUT issue ${g.status}: ${f.slice(0,200)}`,url:s.url}}}catch(g){return i.push({kind:"PUT issue",ok:!1,error:g.message}),{ok:!1,attempts:i,error:g.message,url:s.url}}if(e.note)try{let g=await l(`/projects/${c}/issues/${s.iid}/notes`,{method:"POST",body:JSON.stringify({body:e.note})});i.push({kind:"POST note",ok:g.ok,status:g.status})}catch(g){i.push({kind:"POST note",ok:!1,error:g.message})}return{ok:i.every(g=>g.ok),attempts:i,url:s.url}}async function qe(s,e,t,r){let o=t.channels.github?.token;if(!o)return{ok:!1,error:"github token not configured",attempts:[]};let a=[],i=async(d,g={})=>fetch(`https://api.github.com${d}`,{...g,headers:{Authorization:`Bearer ${o}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...g.headers||{}}}),l=s.project,c;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")c=null;else try{let d=await i(`/repos/${l}/milestones?state=all&per_page=100`);if(d.ok){let g=await d.json(),f=Array.isArray(g)?g.find(h=>h.title===e.milestoneTitle):null;f?.number&&(c=f.number)}}catch(d){r(`[backlog-sync] github milestone lookup failed: ${d.message}`)}let u;if(e.labels!==void 0)u=e.labels;else if(e.addLabels?.length||e.removeLabels?.length)try{let d=await i(`/repos/${l}/issues/${s.iid}`);if(d.ok){let g=await d.json(),f=Array.isArray(g.labels)?g.labels.map(b=>typeof b=="string"?b:b.name):[],h=new Set([...f,...e.addLabels??[]]);for(let b of e.removeLabels??[])h.delete(b);u=[...h]}}catch(d){r(`[backlog-sync] github label fetch failed: ${d.message}`)}let m={};if(e.title!==void 0&&(m.title=e.title),e.description!==void 0&&(m.body=e.description),u!==void 0&&(m.labels=u),e.assigneeUsernames!==void 0&&(m.assignees=e.assigneeUsernames),c!==void 0&&(m.milestone=c),e.state&&(m.state=e.state),Object.keys(m).length)try{let d=await i(`/repos/${l}/issues/${s.iid}`,{method:"PATCH",body:JSON.stringify(m)});if(a.push({kind:"PATCH issue",ok:d.ok,status:d.status}),!d.ok){let g=await d.text().catch(()=>"");return{ok:!1,attempts:a,error:`PATCH issue ${d.status}: ${g.slice(0,200)}`,url:s.url}}}catch(d){return a.push({kind:"PATCH issue",ok:!1,error:d.message}),{ok:!1,attempts:a,error:d.message,url:s.url}}if(e.note)try{let d=await i(`/repos/${l}/issues/${s.iid}/comments`,{method:"POST",body:JSON.stringify({body:e.note})});a.push({kind:"POST comment",ok:d.ok,status:d.status})}catch(d){a.push({kind:"POST comment",ok:!1,error:d.message})}return{ok:a.every(d=>d.ok),attempts:a,url:s.url}}var M=/^(\s*)-\s*\[( |x|X)\]\s*(.*)$/,C=/@([a-z0-9_-]+)/i,pe=/\[time:\s*([0-9hm\s]+)\]/i;function Ye(s){let e=s.match(/(\d+)\s*h/i),t=s.match(/(\d+)\s*m/i);return(e?parseInt(e[1],10)*3600:0)+(t?parseInt(t[1],10)*60:0)}var z=class{constructor(e,t,r=()=>{}){this.path=e;this.daemon=t;this.log=r;this.store=new E(this.path)}type="backlog";capabilities={listAll:!0,create:!1,transition:!1,labels:!0,search:!1};store;getStore(){return this.store}readMd(){let e=N(process.cwd(),this.path);return W(e)?F(e,"utf-8").split(`
|
|
5
|
+
`):[]}writeMd(e){let t=N(process.cwd(),this.path);he(t,e.join(`
|
|
6
|
+
`))}async listOpen(e){if(this.store.exists())return this.store.list().filter(o=>o.status!=="done"&&(!o.assignee||o.assignee.toLowerCase()===e.toLowerCase())).map(o=>this.toWorkItem(o));let t=this.readMd(),r=[];for(let n=0;n<t.length;n++){let o=t[n].match(M);if(!o||o[2].toLowerCase()==="x")continue;let i=o[3],l=i.match(C);if(l&&l[1].toLowerCase()!==e.toLowerCase())continue;let c=i.match(pe),u=i.replace(C,"").replace(pe,"").trim();r.push({id:`backlog:${n}`,title:u||`Task at line ${n+1}`,assignee:l?l[1]:void 0,estimatedSeconds:c?Ye(c[1]):void 0,priority:n})}return r}async listAll(e={}){return this.store.exists()?this.store.list().map(t=>this.toWorkItem(t)):[]}async claim(e,t){if(!this.store.exists())return;let r=this.store.findById(t);if(!r)return;let n=this.store.update(t,{assignee:r.assignee||e,status:"doing"});if(n.source&&this.daemon){let o=fe([n.assignee||e],n.source,this.daemon);U(n,{assigneeUsernames:o,addLabels:["Doing"],removeLabels:["To Do"]},this.daemon,this.log).catch(a=>this.log(`[backlog-sync] claim failed for ${t}: ${a?.message??a}`))}}async report(e,t){if(this.store.exists()&&this.store.findById(e)){let i={};t.status==="done"?i.status="done":t.status==="blocked"?(i.status="blocked",i.blocker=t.blocker||t.note||void 0):t.status==="in-progress"&&(i.status="doing"),t.timeSeconds&&(i.estimatedSeconds=t.timeSeconds);let l=this.store.update(e,i);if(l.source&&this.daemon){let c={};t.status==="done"?(c.addLabels=["Done"],c.removeLabels=["Doing"]):t.status==="blocked"&&(c.addLabels=["Blocked"]),t.note&&(c.note=t.note),Object.keys(c).length&&U(l,c,this.daemon,this.log).catch(u=>this.log(`[backlog-sync] report failed for ${e}: ${u?.message??u}`))}return}if(!e.startsWith("backlog:"))throw new Error(`not a backlog id: ${e}`);let r=parseInt(e.slice(8),10),n=this.readMd(),o=n[r];if(!o)throw new Error(`backlog line ${r} missing`);if(!o.match(M))throw new Error(`backlog line ${r} not a checkbox`);if(t.status==="done"){n[r]=o.replace(/- \[ \]/,"- [x]");let i=t.timeSeconds?` <!-- done by agent, ${Math.round(t.timeSeconds/60)}m -->`:" <!-- done by agent -->";n.splice(r+1,0,i)}else t.status==="blocked"?n.splice(r+1,0,` <!-- BLOCKED: ${t.blocker||t.note||"?"} -->`):t.note&&n.splice(r+1,0,` <!-- ${t.note.replace(/-->/g,"\u2014 >")} -->`);this.writeMd(n)}toWorkItem(e){let t={todo:"todo",doing:"doing",blocked:"onhold",done:"done"}[e.status];return{id:e.id,title:e.title,description:e.description,assignee:e.assignee,estimatedSeconds:e.estimatedSeconds,priority:e.priority,labels:e.labels,stage:t,milestone:e.milestone,url:e.source?.url,updatedAt:e.updatedAt,state:e.status==="done"?"closed":"opened"}}},H=class{constructor(e,t){this.root=e;this.glob=t}type="wiki";capabilities={listAll:!1,create:!1,transition:!1,labels:!1,search:!1};walk(e,t){if(W(e))for(let r of Je(e)){let n=Ve(e,r);Xe(n).isDirectory()?this.walk(n,t):r.endsWith(".md")&&t.push(n)}}async listOpen(e){let t=[];this.walk(N(process.cwd(),this.root),t);let r=[];for(let n of t){let o=F(n,"utf-8").split(`
|
|
7
|
+
`);for(let a=0;a<o.length;a++){let i=o[a].match(M);if(!i||i[2].toLowerCase()==="x")continue;let l=i[3].match(C);!l||l[1].toLowerCase()!==e.toLowerCase()||r.push({id:`wiki:${n}:${a}`,title:i[3].replace(C,"").trim(),assignee:l[1],priority:a})}}return r}async claim(){}async report(e,t){let r=e.split(":"),n=parseInt(r[r.length-1],10),o=r.slice(1,-1).join(":");if(!W(o))return;let a=F(o,"utf-8").split(`
|
|
8
|
+
`);t.status==="done"&&a[n]&&(a[n]=a[n].replace(/- \[ \]/,"- [x]"),he(o,a.join(`
|
|
9
|
+
`)))}},G=class{constructor(e,t,r,n,o){this.host=e;this.token=t;this.projects=r;this.agentUsernames=n;this.log=o}type="gitlab";capabilities={listAll:!0,create:!0,transition:!0,labels:!0,search:!0};usernameToAgent(e){for(let[t,r]of Object.entries(this.agentUsernames))if(r.some(n=>n.toLowerCase()===e.toLowerCase()))return t}mapIssue(e,t){let r=e.references?.full?.split("#")[0]||t,n=[],o;Array.isArray(e.labels)&&(e.labels.length&&typeof e.labels[0]=="object"?(o=e.labels.map(c=>({name:c.name,color:c.color,text_color:c.text_color})),n=o.map(c=>c.name)):n=e.labels);let i=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(c=>({username:c.username,name:c.name,avatarUrl:c.avatar_url})),l=i[0]?.username;return{id:`gitlab:${r}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:l?this.usernameToAgent(l)||l:void 0,assignees:i,url:e.web_url,priority:e.weight??99,estimatedSeconds:e.time_stats?.time_estimate||void 0,labels:n,labelDetails:o,updatedAt:e.updated_at,state:e.state==="closed"?"closed":"opened",milestone:e.milestone?.title||void 0}}async api(e,t={}){let r=await fetch(`${this.host}/api/v4${e}`,{...t,headers:{"PRIVATE-TOKEN":this.token,"Content-Type":"application/json",...t.headers||{}}});if(!r.ok)throw new Error(`GitLab ${r.status}: ${await r.text().catch(()=>"")}`);return r.json()}async listOpen(e){let t=this.agentUsernames[e]||[];if(!t.length)return[];let r=[],n=this.projects.length?this.projects:["__ALL__"];for(let o of t)for(let a of n)try{let i=`assignee_username=${encodeURIComponent(o)}&state=opened&scope=all&per_page=20`,l=a==="__ALL__"?`/issues?${i}`:`/projects/${encodeURIComponent(a)}/issues?${i}`,c=await this.api(l);for(let u of c){let m=this.mapIssue(u,a);m.assignee=e,r.push(m)}}catch(i){this.log(`[business] GitLab listOpen failed for ${o} on ${a}: ${i.message}`)}return r}async claim(e,t){let{project:r,iid:n,type:o}=this.parseId(t),a=`/projects/${encodeURIComponent(r)}/${o==="issue"?"issues":"merge_requests"}/${n}?add_labels=Doing&remove_labels=To Do`;try{await this.api(a,{method:"PUT"})}catch(i){this.log(`[business] claim label update failed: ${i.message}`)}}async report(e,t){let{project:r,iid:n,type:o}=this.parseId(e),a=o==="issue"?"issues":"merge_requests";if(t.timeSeconds&&t.timeSeconds>0){let i=Math.max(1,Math.round(t.timeSeconds/60)),l=i>=60?`${Math.floor(i/60)}h${i%60?` ${i%60}m`:""}`:`${i}m`;try{await this.api(`/projects/${encodeURIComponent(r)}/${a}/${n}/add_spent_time?duration=${encodeURIComponent(l)}`,{method:"POST"})}catch(c){this.log(`[business] add_spent_time failed: ${c.message}`)}}if(t.status==="done")try{await this.api(`/projects/${encodeURIComponent(r)}/${a}/${n}?add_labels=Done&remove_labels=Doing`,{method:"PUT"})}catch(i){this.log(`[business] done label update failed: ${i.message}`)}else if(t.status==="blocked")try{await this.api(`/projects/${encodeURIComponent(r)}/${a}/${n}?add_labels=Blocked`,{method:"PUT"})}catch(i){this.log(`[business] blocked label update failed: ${i.message}`)}if(t.note)try{await this.api(`/projects/${encodeURIComponent(r)}/${a}/${n}/notes`,{method:"POST",body:JSON.stringify({body:t.note})})}catch(i){this.log(`[business] report note failed: ${i.message}`)}}async listAll(e={}){let t=e.sinceDays??30,r=new Date(Date.now()-t*24*36e5).toISOString(),n=new URLSearchParams,o=e.state??"opened";n.set("state",o),n.set("updated_after",r),n.set("scope","all"),n.set("per_page","100"),n.set("with_labels_details","true"),n.set("order_by","updated_at"),n.set("sort","desc"),e.labels?.length&&n.set("labels",e.labels.join(",")),e.milestone&&n.set("milestone",e.milestone),e.search&&n.set("search",e.search);let a=this.projects.length?this.projects:["__ALL__"],i=[];for(let c of a)try{let u=c==="__ALL__"?`/issues?${n.toString()}`:`/projects/${encodeURIComponent(c)}/issues?${n.toString()}`,m=await this.api(u);for(let d of m)i.push(this.mapIssue(d,c))}catch(u){this.log(`[business] GitLab listAll failed on ${c}: ${u.message}`)}let l=i;if(e.notLabels?.length){let c=new Set(e.notLabels);l=l.filter(u=>!(u.labels||[]).some(m=>c.has(m)))}if(e.withoutScopedPrefix){let c=e.withoutScopedPrefix+"::";l=l.filter(u=>!(u.labels||[]).some(m=>m.startsWith(c)))}return l}async setState(e,t){let{project:r,iid:n,type:o}=this.parseId(e),a=o==="issue"?"issues":"merge_requests";await this.api(`/projects/${encodeURIComponent(r)}/${a}/${n}?state_event=${t}`,{method:"PUT"})}async getItem(e){let{project:t,iid:r}=this.parseId(e);try{let n=await this.api(`/projects/${encodeURIComponent(t)}/issues/${r}?with_labels_details=true`);return{...this.mapIssue(n,t),descriptionHtml:n.description_html||void 0,createdAt:n.created_at,author:n.author?{username:n.author.username,name:n.author.name,avatarUrl:n.author.avatar_url}:void 0,allLabels:Array.isArray(n.labels)?typeof n.labels[0]=="object"?n.labels.map(a=>a.name):n.labels:[]}}catch(n){return this.log(`[board] GitLab getItem failed for ${e}: ${n.message}`),null}}async updateItem(e,t){let{project:r,iid:n}=this.parseId(e),o;t.assigneeUsernames&&(o=(await Promise.all(t.assigneeUsernames.map(async u=>{try{let m=await this.api(`/users?username=${encodeURIComponent(u)}`);return Array.isArray(m)&&m[0]?.id?m[0].id:null}catch{return null}}))).filter(u=>typeof u=="number"));let a;if(t.milestoneTitle!==void 0)if(t.milestoneTitle===null||t.milestoneTitle==="")a=0;else try{let c=await this.api(`/projects/${encodeURIComponent(r)}/milestones?title=${encodeURIComponent(t.milestoneTitle)}`);Array.isArray(c)&&c[0]?.id&&(a=c[0].id)}catch(c){this.log(`[board] milestone lookup failed for "${t.milestoneTitle}": ${c.message}`)}let i={};t.title!==void 0&&(i.title=t.title),t.description!==void 0&&(i.description=t.description),t.labels!==void 0&&(i.labels=t.labels.join(",")),t.addLabels?.length&&(i.add_labels=t.addLabels.join(",")),t.removeLabels?.length&&(i.remove_labels=t.removeLabels.join(",")),o!==void 0&&(i.assignee_ids=o),a!==void 0&&(i.milestone_id=a);let l=await this.api(`/projects/${encodeURIComponent(r)}/issues/${n}`,{method:"PUT",body:JSON.stringify(i)});return this.mapIssue(l,r)}async listMembers(){let e=new Map;for(let t of this.projects)try{let r=await this.api(`/projects/${encodeURIComponent(t)}/members/all?per_page=100`);for(let n of r)n.username&&!e.has(n.username)&&e.set(n.username,{username:n.username,name:n.name,avatarUrl:n.avatar_url})}catch(r){this.log(`[board] listMembers failed for ${t}: ${r.message}`)}return[...e.values()].sort((t,r)=>t.username.localeCompare(r.username))}async listMilestones(){let e=new Map;for(let r of this.projects)try{let n=await this.api(`/projects/${encodeURIComponent(r)}/milestones?per_page=100`);for(let o of n)o.title&&!e.has(o.title)&&e.set(o.title,{id:o.id,title:o.title,state:o.state,dueDate:o.due_date})}catch(n){this.log(`[board] listMilestones failed for ${r}: ${n.message}`)}let t=[...e.values()];return t.sort((r,n)=>r.state!==n.state?r.state==="active"?-1:1:r.title.localeCompare(n.title)),t}async create(e){let t=e.projectHint||this.projects[0];if(!t)throw new Error("GitLabWorkSource.create requires projectHint or configured projects");let r,n=e.assigneeUsernames?.length?e.assigneeUsernames:e.assignee?(this.agentUsernames[e.assignee]||[]).slice(0,1):[];n.length&&(r=(await Promise.all(n.map(async c=>{try{let u=await this.api(`/users?username=${encodeURIComponent(c)}`);return Array.isArray(u)&&u[0]?.id?u[0].id:null}catch(u){return this.log(`[board] user lookup failed for ${c}: ${u.message}`),null}}))).filter(c=>typeof c=="number"));let o;if(e.milestoneTitle)try{let l=await this.api(`/projects/${encodeURIComponent(t)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(o=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${l.message}`)}let a={title:e.title,description:e.description,labels:(e.labels||[]).join(",")};r?.length&&(a.assignee_ids=r),o!==void 0&&(a.milestone_id=o);let i=await this.api(`/projects/${encodeURIComponent(t)}/issues`,{method:"POST",body:JSON.stringify(a)});return this.mapIssue(i,t)}async transition(e,t,r){await this.transitionMany(e,t?[t]:[],r?[r]:[])}async transitionMany(e,t,r){let{project:n,iid:o,type:a}=this.parseId(e),i=a==="issue"?"issues":"merge_requests",l=new URLSearchParams;t.length&&l.set("add_labels",t.join(",")),r.length&&l.set("remove_labels",r.join(",")),l.toString()&&await this.api(`/projects/${encodeURIComponent(n)}/${i}/${o}?${l.toString()}`,{method:"PUT"})}parseId(e){let r=e.replace(/^gitlab:/,"").split(":"),n=r.pop(),o=r.pop()==="mr"?"mr":"issue";return{project:r.join(":"),type:o,iid:n}}};function Ft(s,e,t){let r=s.workSource;switch(r.type){case"backlog":return new z(r.path,e,t);case"wiki":return new H(r.path,r.glob);case"gitlab":{let n=e.channels.gitlab;if(!n?.token)throw new Error("business.workSource.type=gitlab requires channels.gitlab.token");let o={};for(let i of n.agentMappings)i.gitlabUsernames.length&&(o[i.agentId]=i.gitlabUsernames);let a=r.projects.length?r.projects:n.routes.map(i=>i.project);return new G(n.host,n.token,a,o,t)}}}var K="unmapped";function q(s,e=[]){if(!s)return K;let t=e.find(n=>n.id===s);if(t?.client)return t.client;let r=s.indexOf("/");return r>0?s.slice(0,r):s}function Qe(s){let e=new Map,t=s.projects??[],r=s.orgChart??{};for(let o of t)o.pm&&(e.has(o.pm)||e.set(o.pm,q(o.id,t)));let n=(o,a=new Set)=>{if(e.has(o))return e.get(o);if(a.has(o))return;a.add(o);let i=r[o]?.reportsTo;if(!i)return;let l=n(i,a);return l&&e.set(o,l),l};for(let o of Object.keys(r))n(o);return e}function Ze(s,e,t=[]){if(!t.length)return;let r=t.filter(n=>!n.channel||n.channel===s);return r.find(n=>n.chatId&&e.chatId&&n.chatId===e.chatId)??r.find(n=>n.username&&e.username&&n.username===e.username)??r.find(n=>n.senderId&&e.senderId&&n.senderId===e.senderId)??r.find(n=>n.channel&&!n.chatId&&!n.username&&!n.senderId)}function Nt(s,e){let t=Ze(s.channel,{chatId:s.chatId,username:s.username},e.contactMap);if(t)return t.client;if(s.project)return q(s.project,e.projects);if(s.agentId){let r=Qe(e).get(s.agentId);if(r)return r}return K}function Mt(s,e){let t=String(s||"").split(":");if(t.length<3)return{agentId:e};let[r,n,...o]=t,a=o.join(":"),i={agentId:e||r,channel:n};return n==="gitlab"||n==="github"?i.project=a.split(":")[0]:n==="cron"||n==="api"||(i.chatId=a.split("@")[0]),i}var et=s=>s===K?"internal":"client";function tt(s,e){let t=e.clients?.[s];return{id:s,name:t?.name||s,kind:t?.kind??et(s),respondWithinMinutes:nt(t?.respondWithin),standing:t?.standing??[],declared:!!t}}function zt(s){let e=new Set;for(let t of s.projects??[])e.add(q(t.id,s.projects));for(let t of s.contactMap??[])e.add(t.client);for(let t of Object.keys(s.clients??{}))e.add(t);return[...e].sort().map(t=>tt(t,s))}function nt(s){let e=/^(\d+)\s*([mhd])$/.exec(String(s??"").trim());if(!e)return;let t=Number(e[1]);return e[2]==="m"?t:e[2]==="h"?t*60:t*1440}import{existsSync as st}from"node:fs";import{join as be}from"node:path";var rt="tn.acme.agentx.voice",qt="AgentX Desktop.app",it="AgentX Helper.app";function Jt(s,e,t){return s!=="darwin"||e!=="arm64"||Number(t.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function Xt(s,e){if(e&&!Object.hasOwn(s,e))throw new Error(`Unknown agent: ${e}. Run agentx agent list.`);let t=e||Object.keys(s)[0];if(!t)throw new Error("No agents configured. Run agentx setup first.");return t}function J(s){return`'${s.replace(/'/g,"'\\''")}'`}function Vt(s){let e=r=>r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),t={AGENTX_VOICE_AGENT:s.agent,AGENTX_DAEMON_URL:s.url,AGENTX_MAC_HELPER:s.helper,AGENTX_PASTE_COMMAND:`cd ${J(s.cwd)} && ${J(s.node)} ${J(s.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
|
|
10
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
11
|
+
<plist version="1.0"><dict>
|
|
12
|
+
<key>Label</key><string>${rt}</string>
|
|
13
|
+
<key>ProgramArguments</key><array><string>${e(s.executable)}</string></array>
|
|
14
|
+
<key>WorkingDirectory</key><string>${e(s.cwd)}</string>
|
|
15
|
+
<key>EnvironmentVariables</key><dict>${Object.entries(t).map(([r,n])=>`<key>${r}</key><string>${e(n)}</string>`).join("")}</dict>
|
|
16
|
+
<key>RunAtLoad</key><true/><key>KeepAlive</key><true/>
|
|
17
|
+
<key>ProcessType</key><string>Interactive</string>
|
|
18
|
+
<key>StandardErrorPath</key><string>${e(s.log)}</string>
|
|
19
|
+
</dict></plist>
|
|
20
|
+
`}function Yt(s){return s?["--icon",s]:[]}function ot(s){return be(s,"Applications",it,"Contents/MacOS/agentx-mac-helper")}function ye(s,e,t){if(t)return t;let r=ot(e);return st(r)?r:be(s,"apps/mac-helper/build/AgentX Helper.app/Contents/MacOS/agentx-mac-helper")}import{execFile as at}from"child_process";import{existsSync as X}from"fs";import{homedir as ke}from"os";import{isAbsolute as lt}from"path";var ct={banner:!0,sound:!0,soundName:"Glass",volume:.4},ut=5e3,dt=(s,e)=>new Promise(t=>{try{at(s,e,{timeout:ut},r=>t(!r))}catch{t(!1)}});function rn(s){return{...ct,...s??{}}}function we(s){if(!/^[\w -]+$/.test(s))return null;let e=`/System/Library/Sounds/${s}.aiff`;return X(e)?e:null}function gt(){let s=ye(process.cwd(),ke());return X(s)?s:null}function on(s,e={}){let t=e.run??dt,r=e.platform??process.platform,n=async(o,a)=>{let i=e.helper===void 0?gt():e.helper;i&&await t(i,["notify","--title",o,"--message",a])||await t("/usr/bin/osascript",["-e","on run argv","-e","display notification (item 2 of argv) with title (item 1 of argv)","-e","end run",o,a])};return async(o,a)=>{if(r!=="darwin")return;let i=[];s.banner&&i.push(n(o,a));let l=s.sound?we(s.soundName):null;if(l){let c=Math.min(1,Math.max(0,s.volume));i.push(t("/usr/bin/afplay",["-v",String(c),l]))}await Promise.all(i)}}function an(s,e,t=process.platform){let r={...s??{}};if("banner"in e&&(r.banner=!!e.banner),"sound"in e&&(r.sound=!!e.sound),"soundName"in e){let n=String(e.soundName).trim();if(!(t==="darwin"?we(n)!==null:/^[\w -]+$/.test(n)))throw new Error(`no system sound named "${n}" in /System/Library/Sounds`);r.soundName=n}if("icon"in e){let n=String(e.icon??"").trim().replace(/^~(?=\/)/,ke());if(!n)delete r.icon;else{if(!lt(n)||!/\.(png|jpe?g|icns)$/i.test(n))throw new Error("icon must be the full path to a .png, .jpg or .icns file");if(t==="darwin"&&!X(n))throw new Error(`no icon file at ${n}`);r.icon=n}}if("volume"in e){let n=Number(e.volume);if(!Number.isFinite(n)||n<0||n>1)throw new Error("volume must be between 0 and 1");r.volume=n}return r}import{existsSync as w,readFileSync as Z,writeFileSync as ee,mkdirSync as P,readdirSync as Q,rmSync as mt,statSync as $}from"fs";import{resolve as Se,relative as ft,dirname as te,join as I,extname as A,basename as ne}from"path";var k=200*1024,$e=new Set([".md",".markdown",".txt"]),v=new Set([".md",".markdown",".txt",".json",".jsonc",".yaml",".yml",".toml",".sh",".bash",".zsh",".py",".js",".mjs",".ts",".tsx",".jsx",".css",".html",".lock",".cfg",".ini",".env",".gitignore"]),pt=6,ht=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function R(s,e){if(!s)throw new Error("Agent workspace is not configured.");let t=Se(s);if(w(t)||P(t,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let r=Se(t,e);if(ft(t,r).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return r}function xe(s){let e=A(s).toLowerCase();if(!$e.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function V(s,e){let t=s.split(/\r?\n/).find(r=>r.trim().startsWith("#"));return t&&t.replace(/^#+\s*/,"").trim().slice(0,120)||e}function dn(s){let e=R(s,"."),t=[],r=new Set,n=[];try{n=Q(e)}catch{}for(let i of ht){let l=I(e,i);if(w(l)&&$(l).isFile()){let c=$(l).size,u=c>0&&c<k?Y(l):"";t.push({path:i,title:V(u,i),size:c,exists:!0}),r.add(i)}else t.push({path:i,title:i,size:0,exists:!1}),r.add(i)}for(let i of n){if(r.has(i))continue;let l=I(e,i);try{let c=$(l);if(!c.isFile()||!$e.has(A(i).toLowerCase()))continue;let u=c.size>0&&c.size<k?Y(l):"";t.push({path:i,title:V(u,i),size:c.size,exists:!0})}catch{}}let o=[],a=I(e,".claude","skills");if(w(a))try{for(let i of Q(a)){let l=I(a,i),c;try{c=$(l)}catch{continue}if(!c.isDirectory())continue;let u=I(l,"SKILL.md");if(!w(u))continue;let m=$(u),d=m.size<k?Y(u):"";o.push({slug:i,title:V(d,i),size:m.size,path:`.claude/skills/${i}/SKILL.md`})}}catch{}return o.sort((i,l)=>i.slug.localeCompare(l.slug)),{identity:t,skills:o,workspace:e}}function Y(s){try{return Z(s,"utf-8")}catch{return""}}function gn(s,e){let t=R(s,e);if(xe(t),!w(t))return{path:e,content:""};if($(t).size>k)throw new Error(`File is too large to edit in the admin panel (> ${k/1024} KB).`);return{path:e,content:Z(t,"utf-8")}}function mn(s,e,t){let r=R(s,e);xe(r);let n=Buffer.from(t,"utf-8");if(n.length>k)throw new Error(`File too large (${n.length} > ${k} bytes).`);return P(te(r),{recursive:!0}),ee(r,n),{path:e,bytes:n.length}}function fn(s,e,t={}){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error("Skill slug must be lowercase (letters, digits, -, _) and start with a letter or digit.");let r=`.claude/skills/${e}/SKILL.md`,n=R(s,r);if(w(n))throw new Error(`Skill "${e}" already exists.`);P(te(n),{recursive:!0});let o=t.content?.trim()?t.content:bt(e,t.title);return ee(n,o),{slug:e,path:r}}function pn(s,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let t=R(s,`.claude/skills/${e}`);if(!w(t))throw new Error(`Skill "${e}" not found.`);if(!$(t).isDirectory())throw new Error(`Skill path is not a directory: ${e}`);return mt(t,{recursive:!0,force:!0}),{slug:e}}function hn(s,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let t=R(s,`.claude/skills/${e}`);if(!w(t))throw new Error(`Skill "${e}" not found.`);let r=[];return n(t,"",0,r),r.sort((o,a)=>o.kind!==a.kind?o.kind==="dir"?-1:1:o.path.localeCompare(a.path)),r;function n(o,a,i,l){if(i>pt)return;let c=[];try{c=Q(o)}catch{return}for(let u of c){if(u==="node_modules"||u===".git")continue;let m=I(o,u),d=a?`${a}/${u}`:u,g;try{g=$(m)}catch{continue}if(g.isDirectory())l.push({path:`${d}/`,kind:"dir",size:0,editable:!1}),n(m,d,i+1,l);else if(g.isFile()){let f=A(u).toLowerCase(),h=v.has(f)||v.has(u.toLowerCase());l.push({path:d,kind:"file",size:g.size,editable:h&&g.size<k})}}}}function bn(s,e,t){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!t||t.includes(".."))throw new Error(`Invalid file path: ${t}`);let r=R(s,`.claude/skills/${e}/${t}`);if(!w(r)||!$(r).isFile())throw new Error(`File not found: ${t}`);let n=A(r).toLowerCase(),o=ne(r).toLowerCase();if(!v.has(n)&&!v.has(o))throw new Error(`File type not editable: ${t}`);if($(r).size>k)throw new Error(`File too large to edit (> ${k/1024} KB): ${t}`);return{path:t,content:Z(r,"utf-8")}}function yn(s,e,t,r){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!t||t.includes(".."))throw new Error(`Invalid file path: ${t}`);let n=R(s,`.claude/skills/${e}/${t}`),o=A(n).toLowerCase(),a=ne(n).toLowerCase();if(!v.has(o)&&!v.has(a))throw new Error(`File type not editable: ${t}`);let i=Buffer.from(r,"utf-8");if(i.length>k)throw new Error(`File too large (${i.length} > ${k} bytes).`);return P(te(n),{recursive:!0}),ee(n,i),{path:t,bytes:i.length}}function kn(s,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let t=R(s,`.claude/skills/${e}`);if(!w(t))throw new Error(`Skill "${e}" not found.`);let r=n=>w(I(t,n));return r("pnpm-lock.yaml")?{manager:"pnpm",file:"pnpm-lock.yaml",command:"pnpm install"}:r("yarn.lock")?{manager:"yarn",file:"yarn.lock",command:"yarn install"}:r("package.json")?{manager:"npm",file:"package.json",command:"npm install"}:r("requirements.txt")?{manager:"pip",file:"requirements.txt",command:"pip install -r requirements.txt"}:r("Gemfile")?{manager:"bundle",file:"Gemfile",command:"bundle install"}:{manager:null,file:null,command:null}}function bt(s,e){return`# ${e?.trim()||s}
|
|
21
|
+
|
|
22
|
+
Describe what this skill does and when the agent should use it. Keep it under ~5 lines \u2014 the agent reads this to decide whether to invoke the skill.
|
|
23
|
+
|
|
24
|
+
## When to use
|
|
25
|
+
- Trigger condition 1
|
|
26
|
+
- Trigger condition 2
|
|
27
|
+
|
|
28
|
+
## How to use
|
|
29
|
+
Document the arguments, commands, or files the skill expects. Example:
|
|
30
|
+
|
|
31
|
+
\`\`\`bash
|
|
32
|
+
# Example invocation
|
|
33
|
+
claude-code ${ne(s)} --arg value
|
|
34
|
+
\`\`\`
|
|
35
|
+
`}export{re as a,wt as b,q as c,Qe as d,Ze as e,Nt as f,Mt as g,zt as h,y as i,Rt as j,rt as k,qt as l,it as m,Jt as n,Xt as o,Vt as p,Yt as q,ot as r,ye as s,ct as t,rn as u,on as v,an as w,vt as x,At as y,E as z,Et as A,fe as B,U as C,G as D,Ft as E,dn as F,gn as G,mn as H,fn as I,pn as J,hn as K,bn as L,yn as M,kn as N};
|
|
36
|
+
//# sourceMappingURL=chunk-MX5GCR7Y.js.map
|