agentix-cli 0.177.0 → 0.178.0

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.
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
48
48
  ... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
49
49
  ${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
50
50
  ${c.join(`
51
- `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-3MN45PGY.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
51
+ `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-5YYMCHMF.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
52
52
 
53
53
  ${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
54
54
  Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
123
123
  Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
124
124
 
125
125
  `)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
126
- //# sourceMappingURL=chunk-SRX5O2BY.js.map
126
+ //# sourceMappingURL=chunk-XXWSFJFZ.js.map
package/dist/cli.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{b as o}from"./chunk-OSH2PEBH.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-JMATAWA6.js"),{installCliSignalExit:r}=await import("./signal-exit-WL7G3EEZ.js"),{applyConnectAttemptTimeout:i,configPathFromArgv:a,readConnectAttemptTimeout:n}=await import("./net-family-X2P3OVDP.js");r();i(n(process.cwd(),a(process.argv.slice(2))));var t=await s();process.argv.slice(2).length===0?t.outputHelp():t.parse();
2
+ import{b as o}from"./chunk-OSH2PEBH.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-CP4OE2OF.js"),{installCliSignalExit:r}=await import("./signal-exit-WL7G3EEZ.js"),{applyConnectAttemptTimeout:i,configPathFromArgv:a,readConnectAttemptTimeout:n}=await import("./net-family-X2P3OVDP.js");r();i(n(process.cwd(),a(process.argv.slice(2))));var t=await s();process.argv.slice(2).length===0?t.outputHelp():t.parse();
3
3
  //# sourceMappingURL=cli.js.map
package/dist/index.d.ts CHANGED
@@ -18001,6 +18001,10 @@ interface RunningTask {
18001
18001
  step?: string;
18002
18002
  title?: string;
18003
18003
  };
18004
+ /** The last line the run wrote to its live output (#1381): a tool
18005
+ * call, a result or a line of its reply. Filled in when the agent list
18006
+ * is read, never stored. */
18007
+ lastActivity?: string;
18004
18008
  }
18005
18009
  type TaskOutputSubscriber = (chunk: string) => void;
18006
18010
  /** Persisted record of a finished task, written to .agentx/task-history. */
@@ -18327,6 +18331,9 @@ declare class AgentRegistry {
18327
18331
  };
18328
18332
  hourlyTasks?: number[];
18329
18333
  }>;
18334
+ /** Running tasks with the last line each wrote (#1381); the stored list
18335
+ * is not touched. */
18336
+ private withLastActivity;
18330
18337
  /** Running tasks with the workflow run each belongs to and the step it
18331
18338
  * is on (#858), read from the run store; the stored list is not touched. */
18332
18339
  private withWorkflowSteps;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{Ia as Tt,Ja as Mt,a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt}from"./chunk-FXCBW52X.js";import"./chunk-FZMS4UFL.js";import"./chunk-GTJIKXDB.js";import"./chunk-YIR6FABW.js";import"./chunk-ZVP6GB4G.js";import"./chunk-6FNJ7GQ2.js";import"./chunk-EKJG63EJ.js";import"./chunk-PHT6HTAW.js";import"./chunk-N6VBEITO.js";import"./chunk-IMLAPB7G.js";import"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import"./chunk-5HLD66CW.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-FRR6DRLY.js";import"./chunk-LQS27HSV.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-A5GYG56I.js";import"./chunk-3X2BFCOZ.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import"./chunk-IS2IWRP7.js";import"./chunk-MNG2AMKZ.js";import"./chunk-RX5O5637.js";import"./chunk-X7UQY7CH.js";import"./chunk-QPABR72X.js";import"./chunk-OHPCZOOM.js";import"./chunk-AJ5HMDRW.js";import"./chunk-KP7KDLZ2.js";import{m as lt,n as ct,o as dt,p as mt,q as pt,xa as yt}from"./chunk-XWDZ37QZ.js";import"./chunk-M4BNVLGJ.js";import"./chunk-MEFPXHQJ.js";import{a as L}from"./chunk-BAXGL6TY.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-SRX5O2BY.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import"./chunk-SZDACK6O.js";import"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-VJVXEVZ7.js";import{t as ut}from"./chunk-CVFQA3TH.js";import"./chunk-KUZATIJA.js";import"./chunk-3UOTLMXD.js";import"./chunk-BE64IJWM.js";import"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import"./chunk-BCDC7BOQ.js";import{a as ht}from"./chunk-2BI43ZKI.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-5DJOGAS2.js";import"./chunk-JTFCU5LH.js";import{f as gt,g as ft}from"./chunk-3VZNOJJK.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-DUWKRQKT.js";import{j as it,k as rt,l as at}from"./chunk-FXMUUDSH.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-QUFIUXMQ.js";import"./chunk-AV7T3SYT.js";import"./chunk-LE3BXIUF.js";import"./chunk-BERWTVG2.js";import"./chunk-QOYAX2FT.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-DCIYOPJF.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{nb as tt,pb as st,rb as ot,yb as nt}from"./chunk-P7FSTC5E.js";import"./chunk-VJ5HC63R.js";import"./chunk-UEEB3UTU.js";import"./chunk-VQRY4IDI.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
1
+ import{Ia as Tt,Ja as Mt,a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt}from"./chunk-GQJMY5NH.js";import"./chunk-FZMS4UFL.js";import"./chunk-GTJIKXDB.js";import"./chunk-YIR6FABW.js";import"./chunk-ZVP6GB4G.js";import"./chunk-6FNJ7GQ2.js";import"./chunk-EKJG63EJ.js";import"./chunk-PHT6HTAW.js";import"./chunk-N6VBEITO.js";import"./chunk-IMLAPB7G.js";import"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import"./chunk-5HLD66CW.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-FRR6DRLY.js";import"./chunk-LQS27HSV.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-A5GYG56I.js";import"./chunk-3X2BFCOZ.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import"./chunk-IS2IWRP7.js";import"./chunk-MNG2AMKZ.js";import"./chunk-RX5O5637.js";import"./chunk-X7UQY7CH.js";import"./chunk-QPABR72X.js";import"./chunk-OHPCZOOM.js";import"./chunk-AJ5HMDRW.js";import"./chunk-KP7KDLZ2.js";import{m as lt,n as ct,o as dt,p as mt,q as pt,ya as yt}from"./chunk-S25OP23O.js";import"./chunk-M4BNVLGJ.js";import"./chunk-MEFPXHQJ.js";import{a as L}from"./chunk-BAXGL6TY.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-XXWSFJFZ.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import"./chunk-SZDACK6O.js";import"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-VJVXEVZ7.js";import{t as ut}from"./chunk-CVFQA3TH.js";import"./chunk-KUZATIJA.js";import"./chunk-3UOTLMXD.js";import"./chunk-BE64IJWM.js";import"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import"./chunk-BCDC7BOQ.js";import{a as ht}from"./chunk-2BI43ZKI.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-5DJOGAS2.js";import"./chunk-JTFCU5LH.js";import{f as gt,g as ft}from"./chunk-3VZNOJJK.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-DUWKRQKT.js";import{j as it,k as rt,l as at}from"./chunk-FXMUUDSH.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-QUFIUXMQ.js";import"./chunk-AV7T3SYT.js";import"./chunk-LE3BXIUF.js";import"./chunk-BERWTVG2.js";import"./chunk-QOYAX2FT.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-DCIYOPJF.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{nb as tt,pb as st,rb as ot,yb as nt}from"./chunk-P7FSTC5E.js";import"./chunk-VJ5HC63R.js";import"./chunk-UEEB3UTU.js";import"./chunk-VQRY4IDI.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
2
2
  `)}
3
3
 
4
4
  ${t}`}async function It(o){let{loadLocalSkills:e}=await import("./loader-YFVSSYSL.js");return e(o)}async function Ot(o,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
@@ -1,4 +1,4 @@
1
- import{a as Wf,b as Fi,g as Bf}from"./chunk-T7E33M6T.js";import{b as qf}from"./chunk-7NJLRLQN.js";import{$ as Pf,A as ff,B as hf,C as wf,D as sl,E as yf,J as bf,K as $f,L as rl,M as kf,P as vf,Q as xf,R as Sf,S as Af,T as Cf,U as Of,V as If,X as il,Y as Nf,_ as jf,a as Yp,aa as _f,b as Kp,f as Xp,g as Vp,i as Qp,k as fs,l as hs,m as Zp,n as ef,o as tf,p as of,q as nf,r as sf,t as co,v as cf,w as lf,x as mf,y as pf}from"./chunk-BU57BT5P.js";import{n as al}from"./chunk-KPRWATQR.js";import{a as Df,b as Mf,d as mr,e as Lf}from"./chunk-7WMZJFYD.js";import{a as Ff,b as Uf}from"./chunk-N4TDTQOQ.js";import"./chunk-XVTD6I34.js";import{d as df,e as nl,h as gf,i as uf}from"./chunk-CTN4KYE6.js";import{a as Ef,c as Rf,d as Tf}from"./chunk-TADIDWYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-MTX4UPNB.js";import{a as jt}from"./chunk-RMSB6DKW.js";import{a as rf,c as af}from"./chunk-L7F226TX.js";import{a as tl}from"./chunk-LNY6N73E.js";import"./chunk-DMCMV4UJ.js";import{a as Ic,b as Bu}from"./chunk-RKPAVWXF.js";import{$ as vp,A as Ym,Aa as Qc,B as Wc,Ba as Wp,C as Km,Ca as Jp,D as Xm,Da as el,E as Vm,Ea as Gp,F as Qm,Fa as Li,G as Zm,Ga as ps,H as ep,Ha as qi,I as Oi,Ia as ol,J as tp,Ja as zp,K as Bc,L as op,M as np,N as sp,O as rp,P as ip,Q as Ii,R as gp,S as pp,T as fp,U as hp,V as wp,W as yp,X as Hc,Y as bp,Z as $p,_ as kp,a as sm,aa as xp,b as rm,ba as Sp,ca as Ap,da as Ep,ea as jp,fa as Pi,ga as vo,h as hi,ha as Fo,i as lm,ia as gs,j as cr,ja as _i,k as wi,ka as Di,l as gm,la as Vc,m as mm,ma as Pp,n as Am,na as _p,o as Em,oa as Dp,p as xi,pa as Mp,q as qc,qa as Lp,r as jm,ra as qp,s as Wm,sa as us,t as Bm,ta as ms,u as Jm,ua as Fp,v as Hm,va as gr,w as Ci,wa as Up,x as Gm,xa as lt,y as zm,ya as Mi,z as Uc,za as ur}from"./chunk-FXCBW52X.js";import{$a as ji,Da as lr,Ga as Gc,Ha as Ni,Ia as Rp,Kb as ao,Mb as Hp,Pa as qo,Q as qm,Qa as Tp,Ra as zc,S as Ri,T as Fm,Ta as Yc,Va as Cp,W as Um,Wa as Op,X as Ti,Xa as dr,cb as Ip,db as Np,ea as ap,eb as Kc,fa as cp,ga as lp,ha as Jc,ja as dp,lb as Xc,v as um,vb as Bp,wb as Zc}from"./chunk-FZMS4UFL.js";import"./chunk-GTJIKXDB.js";import{a as im,c as Dc,e as am,f as cm}from"./chunk-YIR6FABW.js";import"./chunk-ZVP6GB4G.js";import{F as $i,G as xm,H as Sm,a as Cc,b as Mu,e as Lu,f as qu,n as yi,o as bi,p as pm,q as fm,r as hm,t as wm,u as ym,w as bm,x as $m,y as km,z as vm}from"./chunk-6FNJ7GQ2.js";import{a as up,b as mp}from"./chunk-EKJG63EJ.js";import"./chunk-PHT6HTAW.js";import"./chunk-N6VBEITO.js";import"./chunk-IMLAPB7G.js";import{c as Rm}from"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import{b as Lc}from"./chunk-5HLD66CW.js";import{c as Tm,e as ki,g as vi}from"./chunk-LQE73AZR.js";import{a as Cm,b as Om,c as Im,d as Nm}from"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-FRR6DRLY.js";import{a as Pm,b as un,c as _m,d as Si,g as Dm,h as Mm,j as Lm,k as Fc,n as Ai,o as mn,p as Ei}from"./chunk-LQS27HSV.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-A5GYG56I.js";import{a as Mc,p as dm}from"./chunk-3X2BFCOZ.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as Nt}from"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import"./chunk-IS2IWRP7.js";import{a as io}from"./chunk-MNG2AMKZ.js";import{a as Vu,b as Qu,c as Zu,d as em,e as jc,f as tm,g as Pc,h as _c,l as om,m as nm}from"./chunk-RX5O5637.js";import"./chunk-X7UQY7CH.js";import{a as Oc,d as Fu,e as fi}from"./chunk-QPABR72X.js";import{a as ar,e as Ju,f as Hu,g as Nc,i as Gu,j as zu,l as Yu,m as Ku,n as Xu}from"./chunk-OHPCZOOM.js";import{b as ds,e as Wu}from"./chunk-AJ5HMDRW.js";import{c as Uu}from"./chunk-KP7KDLZ2.js";import{B as Sc,C as wu,O as Lo,U as Nu,X as Pu,Y as _u,g as lu,r as du,xa as Du}from"./chunk-XWDZ37QZ.js";import{I as rs,J as mi,K as pi,L as is,M as bu,N as Do,P as Mo,b as ss,fa as Ou,r as ko,s as Ac,t as yu,u as Ec,ua as Iu,w as gi,wa as ju,x as ui}from"./chunk-M4BNVLGJ.js";import{b as dn}from"./chunk-MEFPXHQJ.js";import"./chunk-SRX5O2BY.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{c as ku}from"./chunk-SZDACK6O.js";import{f as vu,g as xu,h as Rc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as Au,f as gn,k as cs}from"./chunk-VJVXEVZ7.js";import{a as fu,k as Su,n as Cu}from"./chunk-CVFQA3TH.js";import{a as Tt,b as de,c as qe,d as ls,e as Eu}from"./chunk-KUZATIJA.js";import{a as Ru,b as Tc,h as Tu}from"./chunk-3UOTLMXD.js";import{i as uu,j as mu}from"./chunk-BE64IJWM.js";import"./chunk-PE5V2LI7.js";import{a as xc,b as pu}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as hu}from"./chunk-X5C5W3E4.js";import{a as as}from"./chunk-GV7S5BAX.js";import{e as $u}from"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import{a as vc}from"./chunk-BCDC7BOQ.js";import"./chunk-2BI43ZKI.js";import{c as gu}from"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-5DJOGAS2.js";import"./chunk-JTFCU5LH.js";import{g as _o,i as di}from"./chunk-3VZNOJJK.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-DUWKRQKT.js";import{a as hc,b as Mg,c as Fv,d as ni,e as Lg,f as tu,g as Kv,h as ou,i as Xv,m as ns,n as su,q as ru,u as iu,y as ro,z as ir}from"./chunk-FXMUUDSH.js";import{a as $o,b as os,e as Qg,f as rr}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as li,b as nu}from"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import{h as Po,j as au}from"./chunk-QUFIUXMQ.js";import{n as cu}from"./chunk-AV7T3SYT.js";import"./chunk-LE3BXIUF.js";import"./chunk-BERWTVG2.js";import"./chunk-QOYAX2FT.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as so,b as qv}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$a as Vg,Ia as Kg,Ja as bc,La as $c,M as Hg,N as Jv,S as si,Sa as Gv,T as ri,Ta as kc,Va as Xg,W as Gg,Wa as zv,X as zg,Y as ii,Z as yc,ga as Yg,ha as Hv,j as Fg,k as Ug,l as Wg,m as Bg,n as Jg,nb as ai,o as Wv,ob as sr,pb as T,rb as ci,x as wc,y as Bv,yb as oe}from"./chunk-P7FSTC5E.js";import"./chunk-VJ5HC63R.js";import{j as bt,r as ts}from"./chunk-UEEB3UTU.js";import{a as qg,e as Uv}from"./chunk-VQRY4IDI.js";import{g as Zg,k as eu,l as Yv}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Vv}from"commander";var Jf=new Vv().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 rm({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()});oe();import{Command as Qv}from"commander";import{execFileSync as Bt}from"node:child_process";import{cpSync as Hf,existsSync as dl,mkdirSync as cl,mkdtempSync as Zv,readdirSync as ex,rmSync as Gf,writeFileSync as zf}from"node:fs";import{dirname as Yf,join as dt}from"node:path";import{homedir as Ui,release as tx,tmpdir as ox}from"node:os";import{setTimeout as nx}from"node:timers/promises";function Wi(){let e=pm(process.platform,process.arch,tx());if(e)throw new Error(e)}function Bi(){let e=dt(Ui(),"Library/LaunchAgents"),t=[];try{t=ex(e).filter(wm)}catch{}let o=t.flatMap(n=>{let s=dt(e,n);try{return[{file:s,plist:Bt("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return ym(e,o)}function pr(e){return`gui/${process.getuid()}/${e.label}`}async function ll(e){try{Bt("launchctl",["bootout",pr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{Bt("launchctl",["print",pr(e)],{stdio:"pipe"})}catch{return}await nx(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Kf(e){if(!dl(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{Bt("launchctl",["print",pr(e)],{stdio:"pipe"})}catch{t=!1}t||Bt("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),Bt("launchctl",["kickstart",pr(e)],{stdio:"pipe"})}function sx(){let e=vm();if(e&&dl(dt(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var ws=new Qv("desktop").description("install and control the macOS desktop assistant");ws.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{Wi();let t=T(),o=fm(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,r=sx(),i=dt(Ui(),"Applications"),{keep:a,remove:c}=Bi();if(console.log(`Desktop assistant \u2192 ${dt(i,yi)}
1
+ import{a as Wf,b as Fi,g as Bf}from"./chunk-T7E33M6T.js";import{b as qf}from"./chunk-7NJLRLQN.js";import{$ as Pf,A as ff,B as hf,C as wf,D as sl,E as yf,J as bf,K as $f,L as rl,M as kf,P as vf,Q as xf,R as Sf,S as Af,T as Cf,U as Of,V as If,X as il,Y as Nf,_ as jf,a as Yp,aa as _f,b as Kp,f as Xp,g as Vp,i as Qp,k as fs,l as hs,m as Zp,n as ef,o as tf,p as of,q as nf,r as sf,t as co,v as cf,w as lf,x as mf,y as pf}from"./chunk-BU57BT5P.js";import{n as al}from"./chunk-KPRWATQR.js";import{a as Df,b as Mf,d as mr,e as Lf}from"./chunk-7WMZJFYD.js";import{a as Ff,b as Uf}from"./chunk-N4TDTQOQ.js";import"./chunk-XVTD6I34.js";import{d as df,e as nl,h as gf,i as uf}from"./chunk-CTN4KYE6.js";import{a as Ef,c as Rf,d as Tf}from"./chunk-TADIDWYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-MTX4UPNB.js";import{a as jt}from"./chunk-RMSB6DKW.js";import{a as rf,c as af}from"./chunk-L7F226TX.js";import{a as tl}from"./chunk-LNY6N73E.js";import"./chunk-DMCMV4UJ.js";import{a as Ic,b as Bu}from"./chunk-RKPAVWXF.js";import{$ as vp,A as Ym,Aa as Qc,B as Wc,Ba as Wp,C as Km,Ca as Jp,D as Xm,Da as el,E as Vm,Ea as Gp,F as Qm,Fa as Li,G as Zm,Ga as ps,H as ep,Ha as qi,I as Oi,Ia as ol,J as tp,Ja as zp,K as Bc,L as op,M as np,N as sp,O as rp,P as ip,Q as Ii,R as gp,S as pp,T as fp,U as hp,V as wp,W as yp,X as Hc,Y as bp,Z as $p,_ as kp,a as sm,aa as xp,b as rm,ba as Sp,ca as Ap,da as Ep,ea as jp,fa as Pi,ga as vo,h as hi,ha as Fo,i as lm,ia as gs,j as cr,ja as _i,k as wi,ka as Di,l as gm,la as Vc,m as mm,ma as Pp,n as Am,na as _p,o as Em,oa as Dp,p as xi,pa as Mp,q as qc,qa as Lp,r as jm,ra as qp,s as Wm,sa as us,t as Bm,ta as ms,u as Jm,ua as Fp,v as Hm,va as gr,w as Ci,wa as Up,x as Gm,xa as lt,y as zm,ya as Mi,z as Uc,za as ur}from"./chunk-GQJMY5NH.js";import{$a as ji,Da as lr,Ga as Gc,Ha as Ni,Ia as Rp,Kb as ao,Mb as Hp,Pa as qo,Q as qm,Qa as Tp,Ra as zc,S as Ri,T as Fm,Ta as Yc,Va as Cp,W as Um,Wa as Op,X as Ti,Xa as dr,cb as Ip,db as Np,ea as ap,eb as Kc,fa as cp,ga as lp,ha as Jc,ja as dp,lb as Xc,v as um,vb as Bp,wb as Zc}from"./chunk-FZMS4UFL.js";import"./chunk-GTJIKXDB.js";import{a as im,c as Dc,e as am,f as cm}from"./chunk-YIR6FABW.js";import"./chunk-ZVP6GB4G.js";import{F as $i,G as xm,H as Sm,a as Cc,b as Mu,e as Lu,f as qu,n as yi,o as bi,p as pm,q as fm,r as hm,t as wm,u as ym,w as bm,x as $m,y as km,z as vm}from"./chunk-6FNJ7GQ2.js";import{a as up,b as mp}from"./chunk-EKJG63EJ.js";import"./chunk-PHT6HTAW.js";import"./chunk-N6VBEITO.js";import"./chunk-IMLAPB7G.js";import{c as Rm}from"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import{b as Lc}from"./chunk-5HLD66CW.js";import{c as Tm,e as ki,g as vi}from"./chunk-LQE73AZR.js";import{a as Cm,b as Om,c as Im,d as Nm}from"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-FRR6DRLY.js";import{a as Pm,b as un,c as _m,d as Si,g as Dm,h as Mm,j as Lm,k as Fc,n as Ai,o as mn,p as Ei}from"./chunk-LQS27HSV.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-A5GYG56I.js";import{a as Mc,p as dm}from"./chunk-3X2BFCOZ.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as Nt}from"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import"./chunk-IS2IWRP7.js";import{a as io}from"./chunk-MNG2AMKZ.js";import{a as Vu,b as Qu,c as Zu,d as em,e as jc,f as tm,g as Pc,h as _c,l as om,m as nm}from"./chunk-RX5O5637.js";import"./chunk-X7UQY7CH.js";import{a as Oc,d as Fu,e as fi}from"./chunk-QPABR72X.js";import{a as ar,e as Ju,f as Hu,g as Nc,i as Gu,j as zu,l as Yu,m as Ku,n as Xu}from"./chunk-OHPCZOOM.js";import{b as ds,e as Wu}from"./chunk-AJ5HMDRW.js";import{c as Uu}from"./chunk-KP7KDLZ2.js";import{B as Sc,C as wu,O as Lo,U as Nu,X as Pu,Y as _u,g as lu,r as du,ya as Du}from"./chunk-S25OP23O.js";import{I as rs,J as mi,K as pi,L as is,M as bu,N as Do,P as Mo,b as ss,fa as Ou,r as ko,s as Ac,t as yu,u as Ec,ua as Iu,w as gi,wa as ju,x as ui}from"./chunk-M4BNVLGJ.js";import{b as dn}from"./chunk-MEFPXHQJ.js";import"./chunk-XXWSFJFZ.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{c as ku}from"./chunk-SZDACK6O.js";import{f as vu,g as xu,h as Rc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as Au,f as gn,k as cs}from"./chunk-VJVXEVZ7.js";import{a as fu,k as Su,n as Cu}from"./chunk-CVFQA3TH.js";import{a as Tt,b as de,c as qe,d as ls,e as Eu}from"./chunk-KUZATIJA.js";import{a as Ru,b as Tc,h as Tu}from"./chunk-3UOTLMXD.js";import{i as uu,j as mu}from"./chunk-BE64IJWM.js";import"./chunk-PE5V2LI7.js";import{a as xc,b as pu}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as hu}from"./chunk-X5C5W3E4.js";import{a as as}from"./chunk-GV7S5BAX.js";import{e as $u}from"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import{a as vc}from"./chunk-BCDC7BOQ.js";import"./chunk-2BI43ZKI.js";import{c as gu}from"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-5DJOGAS2.js";import"./chunk-JTFCU5LH.js";import{g as _o,i as di}from"./chunk-3VZNOJJK.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-DUWKRQKT.js";import{a as hc,b as Mg,c as Fv,d as ni,e as Lg,f as tu,g as Kv,h as ou,i as Xv,m as ns,n as su,q as ru,u as iu,y as ro,z as ir}from"./chunk-FXMUUDSH.js";import{a as $o,b as os,e as Qg,f as rr}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as li,b as nu}from"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import{h as Po,j as au}from"./chunk-QUFIUXMQ.js";import{n as cu}from"./chunk-AV7T3SYT.js";import"./chunk-LE3BXIUF.js";import"./chunk-BERWTVG2.js";import"./chunk-QOYAX2FT.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as so,b as qv}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$a as Vg,Ia as Kg,Ja as bc,La as $c,M as Hg,N as Jv,S as si,Sa as Gv,T as ri,Ta as kc,Va as Xg,W as Gg,Wa as zv,X as zg,Y as ii,Z as yc,ga as Yg,ha as Hv,j as Fg,k as Ug,l as Wg,m as Bg,n as Jg,nb as ai,o as Wv,ob as sr,pb as T,rb as ci,x as wc,y as Bv,yb as oe}from"./chunk-P7FSTC5E.js";import"./chunk-VJ5HC63R.js";import{j as bt,r as ts}from"./chunk-UEEB3UTU.js";import{a as qg,e as Uv}from"./chunk-VQRY4IDI.js";import{g as Zg,k as eu,l as Yv}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Vv}from"commander";var Jf=new Vv().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 rm({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()});oe();import{Command as Qv}from"commander";import{execFileSync as Bt}from"node:child_process";import{cpSync as Hf,existsSync as dl,mkdirSync as cl,mkdtempSync as Zv,readdirSync as ex,rmSync as Gf,writeFileSync as zf}from"node:fs";import{dirname as Yf,join as dt}from"node:path";import{homedir as Ui,release as tx,tmpdir as ox}from"node:os";import{setTimeout as nx}from"node:timers/promises";function Wi(){let e=pm(process.platform,process.arch,tx());if(e)throw new Error(e)}function Bi(){let e=dt(Ui(),"Library/LaunchAgents"),t=[];try{t=ex(e).filter(wm)}catch{}let o=t.flatMap(n=>{let s=dt(e,n);try{return[{file:s,plist:Bt("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return ym(e,o)}function pr(e){return`gui/${process.getuid()}/${e.label}`}async function ll(e){try{Bt("launchctl",["bootout",pr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{Bt("launchctl",["print",pr(e)],{stdio:"pipe"})}catch{return}await nx(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Kf(e){if(!dl(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{Bt("launchctl",["print",pr(e)],{stdio:"pipe"})}catch{t=!1}t||Bt("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),Bt("launchctl",["kickstart",pr(e)],{stdio:"pipe"})}function sx(){let e=vm();if(e&&dl(dt(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var ws=new Qv("desktop").description("install and control the macOS desktop assistant");ws.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{Wi();let t=T(),o=fm(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,r=sx(),i=dt(Ui(),"Applications"),{keep:a,remove:c}=Bi();if(console.log(`Desktop assistant \u2192 ${dt(i,yi)}
2
2
  Computer-use helper \u2192 ${dt(i,bi)}
3
3
  Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
4
4
  Daemon \u2192 ${s}
@@ -550,7 +550,7 @@ People who asked not to be contacted. The sales agent never drafts a message to
550
550
  Plan ${P.dim(`[${r.state}] by ${r.createdBy}, ${Fn(r.createdAt)}`)}`),u$(s.steps(e)),console.log(`
551
551
  Log`);for(let i of s.events(e))console.log(P.dim(` ${Fn(i.at)} ${i.step?`step ${i.step} `:""}${i.kind}: ${i.detail}`))}});en.command("step <id> <step>").description("move a step of a request's plan on: --retry, --skip or --done").option("--retry","hand the step to its agent again, with a fresh count of nudges (approves a message whose card expired)").option("--skip","leave the step out; the plan goes on with the next one").option("--done","mark the step done yourself").option("--note <text>","why, or the evidence for --done").action((e,t,o)=>{let n=["retry","skip","done"].filter(c=>o[c]);if(n.length!==1){console.error(P.red(" give one of --retry, --skip or --done")),process.exitCode=1;return}let s=Lr();if(!s)return;let r=qa();if(!r){process.exitCode=1;return}let i=Number(t),a=tp(s,r,{requestId:e,step:i,action:n[0],detail:o.note},Date.now());if(a){console.error(P.red(` ${a}`)),process.exitCode=1;return}console.log(P.green(` \u2713 step ${i} of ${e}: ${n[0]==="retry"?"handed over again":n[0]==="skip"?"skipped":"done"}`)+P.dim(" (the daemon goes on within a minute)")),u$(r.steps(e))});function m$(e,t,o,n){let s=en.command(`${e} <id>`).description(t).option(o,e==="done"?"link to the proof: PR, issue, message, deploy":"why it is dropped");e==="done"&&s.option("--reason <text>",'close it by hand without a link, saying why ("checked by hand"); also closes a loop its check cannot verify'),s.action((r,i)=>{let a=Lr();if(!a)return;let c=e==="done"?i.evidence??(i.reason?`closed by owner: ${i.reason}`:void 0):i.reason??"dropped by the owner";if(!c){console.error(P.red(` ${n}`)),process.exitCode=1;return}let l=a.get(r);if(!l||l.state==="candidate"){console.error(P.red(` no request "${r}"`)),process.exitCode=1;return}if(!a.close(r,e==="done"?"done":"dropped",c,Date.now())){console.error(P.red(` ${r} is already closed (${Ld[l.state]??l.state})`)),process.exitCode=1;return}console.log(P.green(` \u2713 ${r} ${e==="done"?"closed as done":"dropped"}`))})}m$("done","close a request as finished, with a link to the evidence or the reason","--evidence <link>","a finished request needs --evidence <link> or --reason <text>");m$("drop","drop a request you no longer want","--reason <text>","");en.command("settings").description("show or change the requests settings").option("--enabled <on|off>","record and follow your requests").option("--from <id,...>",'who counts as you on channels other people can reach, as channel:id (your login on GitLab and GitHub, your sender id elsewhere); "none" to clear').option("--channels <name,...>",'channels to record on; "all" for every channel a person writes on').option("--stale-hours <n>","hours without activity before an open request comes back to you").option("--retention-days <n>","days a closed request is kept").option("--headlines <on|off>","write a headline for a request its agent did not describe (one small model call each)").option("--catch <on|off>","read the reply of each of your turns for a promise or a question to you (one small model call each)").option("--catch-cap <n>","model calls a day the promise catch may make").option("--settle <on|off>","close a quiet request whose handed work all came back done, instead of bringing it back to you").option("--plans <on|off>","follow requests of two or more steps as tracked plans").option("--stall-minutes <n>","minutes without progress before a plan step's agent is nudged").option("--max-nudges <n>","nudges per step before it counts as blocked and you are told").option("--approve-kinds <kind,...>",'step kinds you approve once when the plan is made; "none" to clear').option("--plans-off-for <agent,...>",'agents that may not open a plan; "none" to clear').option("--plan-for <work,...>",'kinds of work an agent must plan before it starts (default code); "none" to clear').option("--plan-over <minutes>","work estimated over this many minutes needs a plan (default 30); 0 turns it off").option("--checks <kind,...>",`checks agents may use to close a loop (${si.join(", ")}); "none" to turn them all off`).option("--check-every <minutes>","how often each open loop's check runs").action(async e=>{let t={};try{let l=(u,h)=>{if(h===void 0)return;let w=Number(h);if(!(w>0))throw new Error(`${u} must be a positive number`);return w},g=(u,h)=>u===void 0?void 0:u===h?[]:u.split(",").map(w=>w.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");t.enabled=e.enabled==="on"}if(t.from=g(e.from,"none"),t.channels=g(e.channels,"all"),t.staleAfterHours=l("--stale-hours",e.staleHours),t.retentionDays=l("--retention-days",e.retentionDays),e.headlines!==void 0){if(e.headlines!=="on"&&e.headlines!=="off")throw new Error("--headlines takes on or off");t.headlines={enabled:e.headlines==="on"}}if(e.catch!==void 0||e.catchCap!==void 0){if(e.catch!==void 0&&e.catch!=="on"&&e.catch!=="off")throw new Error("--catch takes on or off");let u=l("--catch-cap",e.catchCap);if(u!==void 0&&!Number.isInteger(u))throw new Error("--catch-cap must be a whole number");t.catchPromises={...e.catch!==void 0?{enabled:e.catch==="on"}:{},...u!==void 0?{dailyCap:u}:{}}}if(e.settle!==void 0){if(e.settle!=="on"&&e.settle!=="off")throw new Error("--settle takes on or off");t.settleHandedBack=e.settle==="on"}let d={};if(e.plans!==void 0){if(e.plans!=="on"&&e.plans!=="off")throw new Error("--plans takes on or off");d.enabled=e.plans==="on"}if(d.stallMinutes=l("--stall-minutes",e.stallMinutes),e.maxNudges!==void 0){let u=Number(e.maxNudges);if(!Number.isInteger(u)||u<0)throw new Error("--max-nudges must be a whole number, 0 or more");d.maxNudges=u}if(d.approveKinds=g(e.approveKinds,"none"),d.disabledAgents=g(e.plansOffFor,"none"),d.requireForWork=g(e.planFor,"none"),e.planOver!==void 0){let u=Number(e.planOver);if(!(u>=0))throw new Error("--plan-over must be a number of minutes, 0 or more");d.requireOverMinutes=u}Object.values(d).some(u=>u!==void 0)&&(t.plans=d);let f={},p=g(e.checks,"none");if(p){let u=p.filter(h=>!si.includes(h));if(u.length)throw new Error(`unknown check ${u.join(", ")}: use ${si.join(", ")}`);f.enabled=p}f.checkEveryMinutes=l("--check-every",e.checkEvery),Object.values(f).some(u=>u!==void 0)&&(t.checkers=f)}catch(l){console.error(P.red(` ${l.message}`)),process.exitCode=1;return}if(Object.values(t).some(l=>l!==void 0)){let l=await Fm(t);if(!l.success){console.error(P.red(` ${l.error}`)),process.exitCode=1;return}console.log(P.green(" \u2713 saved")+(l.reloaded?P.dim(" (daemon reloaded)"):""))}let o=Ri();console.log(` Requests ${o.enabled?"on":"off"}`),console.log(` Channels ${o.channels.length?o.channels.join(", "):"every channel a person writes on"}`),console.log(` Counts as you ${o.from.length?o.from.join(", "):"only voice, the app and the dashboard on this machine"}`),console.log(` Comes back after ${o.staleAfterHours} hour(s) without activity`),console.log(` Closed requests kept ${o.retentionDays} day(s)`),console.log(` Headlines ${o.headlines?.enabled===!1?"off: titled with the start of your words":"on: written when the agent gave none"}`);let n=o.catchPromises;console.log(` Catch promises ${n?.enabled?`on: each of your turns' reply is read, up to ${n.dailyCap} call(s) a day`:"off"}`),console.log(` Handed work came back ${o.settleHandedBack===!1?"comes back to you when quiet":"closed when quiet, with its link or marked unproven"}`);let s=o.plans??Oi;console.log(` Plans ${s.enabled?"on":"off"}`),console.log(` Nudge a quiet step after ${s.stallMinutes} minute(s), up to ${s.maxNudges} time(s)`),console.log(` You approve up front ${s.approveKinds.length?s.approveKinds.join(", "):"nothing"}`),console.log(` Plans off for ${s.disabledAgents.length?s.disabledAgents.join(", "):"no agent"}`);let r=s.requireOverMinutes??Oi.requireOverMinutes,i=s.requireForWork??Oi.requireForWork;console.log(` Plan before starting ${[i.length?`${i.join(", ")} work`:"",r>0?`work over ${r} minute(s)`:""].filter(Boolean).join("; ")||"never required"}`);let a=o.checkers??ri;console.log(` Loop checks ${a.enabled.length?a.enabled.join(", "):"off"}, every ${a.checkEveryMinutes} minute(s)`);let c=Object.keys(a.repos);console.log(` Repos for git-ancestor ${c.length?c.join(", "):"none (requests.checkers.repos in agentx.json)"}`)});import{Command as gC}from"commander";import Ws from"chalk";oe();var p$=new gC("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",rl.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(Ws.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await de(r=>{n=kf(r,e,t==="on")});s.success||(console.error(Ws.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(Ws.green(`\u2713 ${n}`)),s.reloaded&&console.log(Ws.dim(" daemon hot-reloaded"))}let o=T().requestStatus.channels.map(n=>n.toLowerCase());for(let n of rl)console.log(` ${n.padEnd(8)} ${o.includes(n)?Ws.green("on"):Ws.dim("off")}`)});import{Command as FC}from"commander";import Bs from"chalk";import we from"chalk";import qr from"prompts";import{readFileSync as uC,writeFileSync as mC,existsSync as pC}from"fs";import{resolve as f$}from"path";var fC=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function hC(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Fd(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function h$(e=".env"){let t=f$(e);if(!pC(t))return[];let o=uC(t,"utf-8"),n=[];for(let s of o.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let r=s.match(fC);r?n.push({kind:"kv",key:r[1],value:hC(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function wC(e){return e.map(t=>t.kind==="kv"?`${t.key}=${Fd(t.value)}`:t.raw).join(`
552
552
  `)+`
553
- `}function Un(e,t,o=".env"){let n=f$(o),s=h$(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Fd(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Fd(t)}`})),mC(n,wC(s))}function Ud(e,t=".env"){return h$(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var w$="https://t.me/BotFather";async function yC(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function bC(e,t){let o=Date.now()+t,n=0;try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();r?.result?.length&&(n=r.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let i of r?.result||[]){n=Math.max(n,i.update_id+1);let a=i.message||i.edited_message||i.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 y$(e={}){console.log(),console.log(we.bold(" Connect Telegram")),console.log(),console.log(we.dim(` 1. Open ${w$}`)),console.log(we.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(we.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await qr({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&xo(w$);let{token:o}=await qr({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:S=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(S.trim())||"That doesn't look like a Telegram token"});o||(console.log(we.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await yC(o.trim());n||(console.log(we.red("\u2717 invalid or revoked")),process.exit(1)),console.log(we.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:r}=await import("fs"),{resolve:i}=await import("path"),a=e.configPath||i(process.cwd(),"agentx.json");r(a)||(console.log(we.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(we.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await qr({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(x=>({title:x,value:x})),initial:0})).agent),g||(console.log(we.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||g;d[f]&&d[f].agentBinding!==g&&(f=(await qr({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(we.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Un(p,o.trim()),process.env[p]=o.trim();let u=await de(S=>{qe(S,"channels.telegram.enabled",!0),qe(S,`channels.telegram.accounts.${f}`,{token:`\${${p}}`,agentBinding:g});let x=ls(S,`agents.${g}.mentions`)||[],k=`@${n.username}`;x.includes(k)||(x.push(k),qe(S,`agents.${g}.mentions`,x))},{configPath:e.configPath});if(u.success||(console.log(we.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(we.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(we.dim(` Token stored in .env as ${p}`)),console.log(we.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(we.dim(" Daemon hot-reloaded.")):console.log(we.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await qr({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(we.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(we.dim(" Waiting up to 90s..."));let w=await bC(o.trim(),9e4);if(!w){console.log(we.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(we.dim(" agentx config set notifications.destination.channel telegram")),console.log(we.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(we.dim(` agentx config set notifications.destination.accountId ${f}`));return}let b={channel:"telegram",chatId:String(w.chatId),accountId:f},$=[],v=await de(S=>{qe(S,"notifications.destination",b),$=Vi(S,b)},{configPath:e.configPath});if(!v.success){console.log(we.red(` \u2717 failed to save destination: ${v.error}`));return}console.log(we.green(" \u2713 Default --notify target set")),console.log(we.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(we.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(we.dim(` Schedules that now report here: ${$.join(", ")}`)),v.reloaded&&console.log(we.dim(" Daemon hot-reloaded."))}import je from"chalk";import Wd from"prompts";import{existsSync as Jd,mkdirSync as $C,readdirSync as kC,readFileSync as b$}from"fs";import{resolve as Bd}from"path";var vC=".agentx/whatsapp-sessions";function xC(){let e=Bd(process.cwd(),".agentx/daemon.pid");if(!Jd(e))return!1;try{let t=parseInt(b$(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function SC(e){if(!Jd(e))return!1;try{return kC(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function AC(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(je.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(je.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;$C(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(g=>{let f=setTimeout(()=>{t(je.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async p=>{if(p.qr){t(je.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:u}=await import("qrcode-terminal");u.generate(p.qr,{small:!0})}catch{t(` QR: ${p.qr}`)}t("")}if(p.connection==="open"){clearTimeout(f),t(je.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(je.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function $$(e={}){if(console.log(),console.log(je.bold(" Connect WhatsApp")),console.log(),xC()){console.log(je.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(je.dim(" agentx daemon stop")),console.log();let{cont:l}=await Wd({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(je.red(" Aborted")),process.exit(1))}let t=e.configPath||Bd(process.cwd(),"agentx.json");Jd(t)||(console.log(je.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(b$(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||vC,s=Bd(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(je.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Wd({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(g=>({title:g,value:g})),initial:0})).agent),i||(console.log(je.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(SC(s)&&a){let{keep:l}=await Wd({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(je.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await AC(s,g=>console.log(g))||(console.log(je.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await de(l=>{qe(l,"channels.whatsapp.enabled",!0),qe(l,"channels.whatsapp.sessionDir",n),qe(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(je.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(je.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(je.dim(` Session: ${n}`)),console.log(je.dim(" Start the daemon to begin receiving:")),console.log(je.dim(" agentx daemon start")),console.log(je.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(je.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(je.dim(" Add routes later with:")),console.log(je.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import At from"chalk";import EC from"prompts";import{existsSync as RC,readFileSync as TC}from"fs";import{resolve as CC}from"path";async function OC(e,t){let o=e.user||e.address,[{ImapFlow:n},{default:s}]=await Promise.all([import("imapflow"),import("nodemailer")]),r=new n({host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,auth:{user:o,pass:t},logger:!1});try{await r.connect(),await r.logout()}catch(a){return r.close(),`IMAP ${e.imapHost}:${e.imapPort}: ${a?.responseText||a?.message||a}`}let i=s.createTransport({host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465,auth:{user:o,pass:t},connectionTimeout:15e3});try{await i.verify()}catch(a){return`SMTP ${e.smtpHost}:${e.smtpPort}: ${a?.response||a?.message||a}`}finally{i.close()}return null}function IC(e,t){return!t.includes("*")||e==="sdk"?null:`Anyone can email an agent that runs commands (engine ${e||"claude-code"}). Limit who may write with --allow-from.`}function Co(e){console.log(At.red(` ${e}`)),process.exit(1)}async function Wn(e){return(await EC(e,{onCancel:()=>Co("Aborted")}))[e.name]}async function k$(e={}){console.log(),console.log(At.bold(" Connect email")),console.log();let t=e.configPath||CC(process.cwd(),"agentx.json");RC(t)||Co(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(TC(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Co("No agents configured. Run: agentx agent add");let s=e.agent??await Wn({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(b=>({title:b,value:b}))});o.agents?.[s]||Co(`No agent "${s}" in ${t}`);let r=(e.address??await Wn({type:"text",name:"address",message:"Email address customers write to:",validate:b=>/^\S+@\S+\.\S+$/.test(b.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=xf(r),c=e.imapHost??a?.imapHost??await Wn({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),l=Number(e.imapPort??a?.imapPort??await Wn({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),g=e.smtpHost??a?.smtpHost??await Wn({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await Wn({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(l)||!Number.isInteger(d))&&Co("Ports must be numbers.");let f=e.passwordEnv||Af(i),p=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!p&&Co(`${e.passwordEnv} is not set in the environment.`),p||(a?.imapHost==="imap.gmail.com"&&(console.log(At.dim(` Gmail needs an app password, not your account password: ${vf}`)),console.log(At.dim(" (2-step verification must be on for that page to show.)"))),p=(await Wn({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),p||Co("Aborted");let u={agent:s,address:r,imapHost:c,imapPort:l,smtpHost:g,smtpPort:d,user:e.user,passwordEnv:f,allowFrom:e.allowFrom?.length?e.allowFrom:["*"],send:e.auto?"auto":"approve"};if(!e.skipCheck){process.stdout.write(" Logging in to IMAP and SMTP... ");let b=await OC(u,p);b&&(console.log(At.red("\u2717")),Co(b)),console.log(At.green("\u2713"))}e.passwordEnv||(Un(f,p),process.env[f]=p);let h=await de(b=>{qe(b,"channels.email.enabled",!0),qe(b,`channels.email.accounts.${i}`,Sf(u))},{configPath:e.configPath});h.success||Co(`Config save failed: ${h.error}`),console.log(),console.log(At.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(At.dim(` Password stored in .env as ${f}`)),console.log(At.dim(` Who may write: ${u.allowFrom.join(", ")}${u.allowFrom.includes("*")?" (anyone)":""}`));let w=IC(o.agents[s]?.tier,u.allowFrom);w&&console.log(At.yellow(` ${w}`)),console.log(u.send==="auto"?At.yellow(" Replies are sent as soon as the agent writes them."):At.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(At.dim(" Only mail that arrives from now on is answered.")),console.log(At.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as NC}from"crypto";import ze from"chalk";import v$ from"prompts";var Fa="agentx-mesh:",Ua="//join/";function jC(e){return Buffer.from(e,"utf-8").toString("base64url")}function PC(e){return Buffer.from(e,"base64url").toString("utf-8")}function _C(e){return`${Fa}${Ua}${jC(JSON.stringify(e))}`}function DC(e){if(!e.startsWith(`${Fa}${Ua}`))throw new Error(`Not a mesh invite link \u2014 expected ${Fa}${Ua}\u2026`);let t=e.slice(Fa.length+Ua.length),o=JSON.parse(PC(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function MC(){return NC(32).toString("hex")}function LC(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function qC(e){return e?.node?.name||e?.node?.id||"node"}async function x$(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(ze.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=Ud("MESH_TOKEN");i||(i=MC(),Un("MESH_TOKEN",i),console.log(ze.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||LC(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await v$({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:f=>/^https?:\/\//.test(f)||"must start with http:// or https://"});d||(console.log(ze.red(" Aborted")),process.exit(1)),a=d}let l=await de(d=>{qe(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(ze.red(` \u2717 ${l.error}`)),process.exit(1));let g=_C({url:a,token:i,name:qC(r),version:1});console.log(),console.log(ze.bold(" Mesh invite")),console.log(),console.log(` ${ze.cyan(g)}`),console.log(),console.log(ze.dim(" Run on the other node:")),console.log(ze.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(ze.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function S$(e,t={}){let o;try{o=DC(e)}catch(r){console.log(ze.red(` \u2717 ${r.message}`)),process.exit(1)}let n=Ud("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await v$({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(ze.red(" Aborted (keeping existing .env)")),process.exit(1))}Un("MESH_TOKEN",o.token);let s=await de(r=>{qe(r,"mesh.enabled",!0);let i=ls(r,"mesh.peers")||[],a=i.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=c:i.push(c),qe(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(ze.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(ze.green(" \u2713 Joined mesh")),console.log(ze.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(ze.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(ze.dim(" Daemon hot-reloaded.")):console.log(ze.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(ze.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(ze.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(ze.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Bn=new FC().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Bn.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 y$({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Bn.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 $$({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});Bn.command("email").description("bind a mailbox to an agent \u2014 IMAP in, SMTP out; the password goes to .env, replies wait for your approval").option("--agent <id>","agent that answers the mailbox (skips the prompt)").option("--address <email>","the address customers write to").option("--account <name>","account label in channels.email.accounts (defaults to agent id)").option("--imap-host <host>","IMAP server (Gmail is filled in by itself)").option("--imap-port <n>","IMAP port (993: TLS; 143: STARTTLS)").option("--smtp-host <host>","SMTP server").option("--smtp-port <n>","SMTP port (465: TLS; 587: STARTTLS)").option("--user <login>","login name, when it is not the address").option("--password-env <VAR>","read the password from this environment variable instead of asking").option("--allow-from <entries...>","who may write: addresses, @domain, or * (default: *)").option("--auto","send replies as soon as the agent writes them, without your approval").option("--skip-check","don't try the IMAP and SMTP logins first").option("-c, --config <path>","path to agentx.json").action(async e=>{await k$({agent:e.agent,account:e.account,address:e.address,imapHost:e.imapHost,imapPort:e.imapPort,smtpHost:e.smtpHost,smtpPort:e.smtpPort,user:e.user,passwordEnv:e.passwordEnv,allowFrom:e.allowFrom,auto:!!e.auto,skipCheck:!!e.skipCheck,configPath:e.config})});var A$=Bn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");A$.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 x$({url:e.url,configPath:e.config})});A$.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await S$(e,{configPath:t.config})});Bn.action(()=>{console.log(),console.log(Bs.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Bs.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Bs.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Bs.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Bs.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Bs.dim(" GitLab connect is the next slice.")),console.log()});oe();import{Command as UC}from"commander";import se from"chalk";var Jn=new UC().name("usage").description("token usage analysis and reporting");Jn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(se.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(se.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${se.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${se.red(String(s.totalErrors))}`),console.log(),console.log(se.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${se.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${se.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(se.red(" Daemon not running. Start with: agentx daemon start")):console.log(se.red(` ${e.message}`))}});Jn.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let t=T(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(f=>a(f.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:se.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(se.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(se.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let f=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,p=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",u=Math.max(1,Math.round((d.resetsAt-c)/6e4)),h=d.resetsAt>c?u<60?`resets in ${u} min`:u<48*60?`resets in ${Math.round(u/60)} h`:`resets in ${Math.round(u/1440)} days`:"",w=l.has(d.window)?se.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[p,h,w].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${g(i.maxPerHour)} in the last hour, ${i.last5h}${g(i.maxPer5h)} in the last 5 hours`),l.size&&console.log(se.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(se.red(" Daemon not running. Start with: agentx daemon start")):console.log(se.red(` ${t.message}`))}});Jn.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(se.red(` Script not found: ${s}`)),console.log(se.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(se.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(se.red(" Analysis failed. Is Python 3 installed?"))}});Jn.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:t,writeFileSync:o}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-XTHSSPLB.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=u=>/^\d{4}-\d{2}-\d{2}$/.test(u)&&!Number.isNaN(Date.parse(u));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(se.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&o(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(t(e.baseline,"utf-8"))}catch(u){console.log(se.red(` Cannot read baseline ${e.baseline}: ${u.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=u=>u===null?"-":`$${u.toFixed(u<10?3:2)}`,g=u=>`${(u/1e6).toFixed(1)}M`;console.log(),console.log(se.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(se.dim(` Baseline: ${c.from} to ${c.to} (${c.days} day(s) with data)`)),console.log();let d=` ${"channel".padEnd(14)} ${"tasks".padStart(6)} ${"cache read".padStart(11)} ${"cache write".padStart(11)} ${"output".padStart(8)} ${"cost".padStart(10)} ${"per task".padStart(9)}`;console.log(se.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let p=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(u=>[u,a.channels[u],c?.channels[u]]).sort((u,h)=>(h[1]?.cost||0)-(u[1]?.cost||0));p.push(["TOTAL",a.total,c?.total]);for(let[u,h,w]of p){let b=r(h),$=` ${u.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${g(h?.cacheRead||0).padStart(11)} ${g(h?.cacheCreate||0).padStart(11)} ${g(h?.output||0).padStart(8)} ${l(h?.cost||0).padStart(10)} ${l(b).padStart(9)}`;if(c){let v=r(w),S=b!==null&&v?`${((b-v)/v*100).toFixed(0)}%`:"-";$+=` ${l(v).padStart(9)} ${S.padStart(7)}`}console.log($)}console.log(),c&&console.log(se.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(se.dim(` Saved ${e.save}`)),console.log()});Jn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-Y7D5W52I.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:r}=await import("./program-JMATAWA6.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,f)=>{for(let p of d.commands??[]){let u=f?`${f} ${p.name()}`:p.name();c.push(u),l(p,u)}};l(i,"");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(se.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${se.dim("\xB7")} ${d}`);console.log(),console.log(se.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(se.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(se.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(se.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(se.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(se.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=se.dim(`${r.days}d`);console.log(` ${se.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(se.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as WC}from"commander";import We from"chalk";import{readFileSync as BC}from"fs";import{resolve as JC}from"path";oe();var tn=new WC().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");tn.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{au(JC(process.cwd(),".env"))}catch{}let t=HC(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-2GTMAPGB.js");o(t)}catch(t){console.log(We.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(We.dim(t.stack)),process.exit(1)}});function HC(e,t){try{let o=T();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(We.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(We.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
553
+ `}function Un(e,t,o=".env"){let n=f$(o),s=h$(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Fd(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Fd(t)}`})),mC(n,wC(s))}function Ud(e,t=".env"){return h$(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var w$="https://t.me/BotFather";async function yC(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function bC(e,t){let o=Date.now()+t,n=0;try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();r?.result?.length&&(n=r.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let i of r?.result||[]){n=Math.max(n,i.update_id+1);let a=i.message||i.edited_message||i.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 y$(e={}){console.log(),console.log(we.bold(" Connect Telegram")),console.log(),console.log(we.dim(` 1. Open ${w$}`)),console.log(we.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(we.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await qr({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&xo(w$);let{token:o}=await qr({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:S=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(S.trim())||"That doesn't look like a Telegram token"});o||(console.log(we.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await yC(o.trim());n||(console.log(we.red("\u2717 invalid or revoked")),process.exit(1)),console.log(we.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:r}=await import("fs"),{resolve:i}=await import("path"),a=e.configPath||i(process.cwd(),"agentx.json");r(a)||(console.log(we.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(we.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await qr({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(x=>({title:x,value:x})),initial:0})).agent),g||(console.log(we.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||g;d[f]&&d[f].agentBinding!==g&&(f=(await qr({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(we.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Un(p,o.trim()),process.env[p]=o.trim();let u=await de(S=>{qe(S,"channels.telegram.enabled",!0),qe(S,`channels.telegram.accounts.${f}`,{token:`\${${p}}`,agentBinding:g});let x=ls(S,`agents.${g}.mentions`)||[],k=`@${n.username}`;x.includes(k)||(x.push(k),qe(S,`agents.${g}.mentions`,x))},{configPath:e.configPath});if(u.success||(console.log(we.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(we.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(we.dim(` Token stored in .env as ${p}`)),console.log(we.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(we.dim(" Daemon hot-reloaded.")):console.log(we.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await qr({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(we.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(we.dim(" Waiting up to 90s..."));let w=await bC(o.trim(),9e4);if(!w){console.log(we.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(we.dim(" agentx config set notifications.destination.channel telegram")),console.log(we.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(we.dim(` agentx config set notifications.destination.accountId ${f}`));return}let b={channel:"telegram",chatId:String(w.chatId),accountId:f},$=[],v=await de(S=>{qe(S,"notifications.destination",b),$=Vi(S,b)},{configPath:e.configPath});if(!v.success){console.log(we.red(` \u2717 failed to save destination: ${v.error}`));return}console.log(we.green(" \u2713 Default --notify target set")),console.log(we.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(we.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(we.dim(` Schedules that now report here: ${$.join(", ")}`)),v.reloaded&&console.log(we.dim(" Daemon hot-reloaded."))}import je from"chalk";import Wd from"prompts";import{existsSync as Jd,mkdirSync as $C,readdirSync as kC,readFileSync as b$}from"fs";import{resolve as Bd}from"path";var vC=".agentx/whatsapp-sessions";function xC(){let e=Bd(process.cwd(),".agentx/daemon.pid");if(!Jd(e))return!1;try{let t=parseInt(b$(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function SC(e){if(!Jd(e))return!1;try{return kC(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function AC(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(je.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(je.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;$C(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(g=>{let f=setTimeout(()=>{t(je.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async p=>{if(p.qr){t(je.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:u}=await import("qrcode-terminal");u.generate(p.qr,{small:!0})}catch{t(` QR: ${p.qr}`)}t("")}if(p.connection==="open"){clearTimeout(f),t(je.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(je.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function $$(e={}){if(console.log(),console.log(je.bold(" Connect WhatsApp")),console.log(),xC()){console.log(je.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(je.dim(" agentx daemon stop")),console.log();let{cont:l}=await Wd({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(je.red(" Aborted")),process.exit(1))}let t=e.configPath||Bd(process.cwd(),"agentx.json");Jd(t)||(console.log(je.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(b$(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||vC,s=Bd(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(je.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Wd({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(g=>({title:g,value:g})),initial:0})).agent),i||(console.log(je.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(SC(s)&&a){let{keep:l}=await Wd({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(je.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await AC(s,g=>console.log(g))||(console.log(je.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await de(l=>{qe(l,"channels.whatsapp.enabled",!0),qe(l,"channels.whatsapp.sessionDir",n),qe(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(je.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(je.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(je.dim(` Session: ${n}`)),console.log(je.dim(" Start the daemon to begin receiving:")),console.log(je.dim(" agentx daemon start")),console.log(je.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(je.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(je.dim(" Add routes later with:")),console.log(je.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import At from"chalk";import EC from"prompts";import{existsSync as RC,readFileSync as TC}from"fs";import{resolve as CC}from"path";async function OC(e,t){let o=e.user||e.address,[{ImapFlow:n},{default:s}]=await Promise.all([import("imapflow"),import("nodemailer")]),r=new n({host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,auth:{user:o,pass:t},logger:!1});try{await r.connect(),await r.logout()}catch(a){return r.close(),`IMAP ${e.imapHost}:${e.imapPort}: ${a?.responseText||a?.message||a}`}let i=s.createTransport({host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465,auth:{user:o,pass:t},connectionTimeout:15e3});try{await i.verify()}catch(a){return`SMTP ${e.smtpHost}:${e.smtpPort}: ${a?.response||a?.message||a}`}finally{i.close()}return null}function IC(e,t){return!t.includes("*")||e==="sdk"?null:`Anyone can email an agent that runs commands (engine ${e||"claude-code"}). Limit who may write with --allow-from.`}function Co(e){console.log(At.red(` ${e}`)),process.exit(1)}async function Wn(e){return(await EC(e,{onCancel:()=>Co("Aborted")}))[e.name]}async function k$(e={}){console.log(),console.log(At.bold(" Connect email")),console.log();let t=e.configPath||CC(process.cwd(),"agentx.json");RC(t)||Co(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(TC(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Co("No agents configured. Run: agentx agent add");let s=e.agent??await Wn({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(b=>({title:b,value:b}))});o.agents?.[s]||Co(`No agent "${s}" in ${t}`);let r=(e.address??await Wn({type:"text",name:"address",message:"Email address customers write to:",validate:b=>/^\S+@\S+\.\S+$/.test(b.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=xf(r),c=e.imapHost??a?.imapHost??await Wn({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),l=Number(e.imapPort??a?.imapPort??await Wn({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),g=e.smtpHost??a?.smtpHost??await Wn({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await Wn({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(l)||!Number.isInteger(d))&&Co("Ports must be numbers.");let f=e.passwordEnv||Af(i),p=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!p&&Co(`${e.passwordEnv} is not set in the environment.`),p||(a?.imapHost==="imap.gmail.com"&&(console.log(At.dim(` Gmail needs an app password, not your account password: ${vf}`)),console.log(At.dim(" (2-step verification must be on for that page to show.)"))),p=(await Wn({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),p||Co("Aborted");let u={agent:s,address:r,imapHost:c,imapPort:l,smtpHost:g,smtpPort:d,user:e.user,passwordEnv:f,allowFrom:e.allowFrom?.length?e.allowFrom:["*"],send:e.auto?"auto":"approve"};if(!e.skipCheck){process.stdout.write(" Logging in to IMAP and SMTP... ");let b=await OC(u,p);b&&(console.log(At.red("\u2717")),Co(b)),console.log(At.green("\u2713"))}e.passwordEnv||(Un(f,p),process.env[f]=p);let h=await de(b=>{qe(b,"channels.email.enabled",!0),qe(b,`channels.email.accounts.${i}`,Sf(u))},{configPath:e.configPath});h.success||Co(`Config save failed: ${h.error}`),console.log(),console.log(At.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(At.dim(` Password stored in .env as ${f}`)),console.log(At.dim(` Who may write: ${u.allowFrom.join(", ")}${u.allowFrom.includes("*")?" (anyone)":""}`));let w=IC(o.agents[s]?.tier,u.allowFrom);w&&console.log(At.yellow(` ${w}`)),console.log(u.send==="auto"?At.yellow(" Replies are sent as soon as the agent writes them."):At.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(At.dim(" Only mail that arrives from now on is answered.")),console.log(At.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as NC}from"crypto";import ze from"chalk";import v$ from"prompts";var Fa="agentx-mesh:",Ua="//join/";function jC(e){return Buffer.from(e,"utf-8").toString("base64url")}function PC(e){return Buffer.from(e,"base64url").toString("utf-8")}function _C(e){return`${Fa}${Ua}${jC(JSON.stringify(e))}`}function DC(e){if(!e.startsWith(`${Fa}${Ua}`))throw new Error(`Not a mesh invite link \u2014 expected ${Fa}${Ua}\u2026`);let t=e.slice(Fa.length+Ua.length),o=JSON.parse(PC(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function MC(){return NC(32).toString("hex")}function LC(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function qC(e){return e?.node?.name||e?.node?.id||"node"}async function x$(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(ze.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=Ud("MESH_TOKEN");i||(i=MC(),Un("MESH_TOKEN",i),console.log(ze.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||LC(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await v$({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:f=>/^https?:\/\//.test(f)||"must start with http:// or https://"});d||(console.log(ze.red(" Aborted")),process.exit(1)),a=d}let l=await de(d=>{qe(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(ze.red(` \u2717 ${l.error}`)),process.exit(1));let g=_C({url:a,token:i,name:qC(r),version:1});console.log(),console.log(ze.bold(" Mesh invite")),console.log(),console.log(` ${ze.cyan(g)}`),console.log(),console.log(ze.dim(" Run on the other node:")),console.log(ze.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(ze.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function S$(e,t={}){let o;try{o=DC(e)}catch(r){console.log(ze.red(` \u2717 ${r.message}`)),process.exit(1)}let n=Ud("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await v$({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(ze.red(" Aborted (keeping existing .env)")),process.exit(1))}Un("MESH_TOKEN",o.token);let s=await de(r=>{qe(r,"mesh.enabled",!0);let i=ls(r,"mesh.peers")||[],a=i.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=c:i.push(c),qe(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(ze.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(ze.green(" \u2713 Joined mesh")),console.log(ze.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(ze.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(ze.dim(" Daemon hot-reloaded.")):console.log(ze.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(ze.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(ze.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(ze.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Bn=new FC().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Bn.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 y$({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Bn.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 $$({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});Bn.command("email").description("bind a mailbox to an agent \u2014 IMAP in, SMTP out; the password goes to .env, replies wait for your approval").option("--agent <id>","agent that answers the mailbox (skips the prompt)").option("--address <email>","the address customers write to").option("--account <name>","account label in channels.email.accounts (defaults to agent id)").option("--imap-host <host>","IMAP server (Gmail is filled in by itself)").option("--imap-port <n>","IMAP port (993: TLS; 143: STARTTLS)").option("--smtp-host <host>","SMTP server").option("--smtp-port <n>","SMTP port (465: TLS; 587: STARTTLS)").option("--user <login>","login name, when it is not the address").option("--password-env <VAR>","read the password from this environment variable instead of asking").option("--allow-from <entries...>","who may write: addresses, @domain, or * (default: *)").option("--auto","send replies as soon as the agent writes them, without your approval").option("--skip-check","don't try the IMAP and SMTP logins first").option("-c, --config <path>","path to agentx.json").action(async e=>{await k$({agent:e.agent,account:e.account,address:e.address,imapHost:e.imapHost,imapPort:e.imapPort,smtpHost:e.smtpHost,smtpPort:e.smtpPort,user:e.user,passwordEnv:e.passwordEnv,allowFrom:e.allowFrom,auto:!!e.auto,skipCheck:!!e.skipCheck,configPath:e.config})});var A$=Bn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");A$.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 x$({url:e.url,configPath:e.config})});A$.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await S$(e,{configPath:t.config})});Bn.action(()=>{console.log(),console.log(Bs.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Bs.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Bs.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Bs.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Bs.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Bs.dim(" GitLab connect is the next slice.")),console.log()});oe();import{Command as UC}from"commander";import se from"chalk";var Jn=new UC().name("usage").description("token usage analysis and reporting");Jn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(se.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(se.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${se.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${se.red(String(s.totalErrors))}`),console.log(),console.log(se.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${se.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${se.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(se.red(" Daemon not running. Start with: agentx daemon start")):console.log(se.red(` ${e.message}`))}});Jn.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let t=T(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(f=>a(f.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:se.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(se.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(se.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let f=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,p=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",u=Math.max(1,Math.round((d.resetsAt-c)/6e4)),h=d.resetsAt>c?u<60?`resets in ${u} min`:u<48*60?`resets in ${Math.round(u/60)} h`:`resets in ${Math.round(u/1440)} days`:"",w=l.has(d.window)?se.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[p,h,w].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${g(i.maxPerHour)} in the last hour, ${i.last5h}${g(i.maxPer5h)} in the last 5 hours`),l.size&&console.log(se.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(se.red(" Daemon not running. Start with: agentx daemon start")):console.log(se.red(` ${t.message}`))}});Jn.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(se.red(` Script not found: ${s}`)),console.log(se.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(se.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(se.red(" Analysis failed. Is Python 3 installed?"))}});Jn.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:t,writeFileSync:o}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-XTHSSPLB.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=u=>/^\d{4}-\d{2}-\d{2}$/.test(u)&&!Number.isNaN(Date.parse(u));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(se.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&o(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(t(e.baseline,"utf-8"))}catch(u){console.log(se.red(` Cannot read baseline ${e.baseline}: ${u.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=u=>u===null?"-":`$${u.toFixed(u<10?3:2)}`,g=u=>`${(u/1e6).toFixed(1)}M`;console.log(),console.log(se.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(se.dim(` Baseline: ${c.from} to ${c.to} (${c.days} day(s) with data)`)),console.log();let d=` ${"channel".padEnd(14)} ${"tasks".padStart(6)} ${"cache read".padStart(11)} ${"cache write".padStart(11)} ${"output".padStart(8)} ${"cost".padStart(10)} ${"per task".padStart(9)}`;console.log(se.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let p=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(u=>[u,a.channels[u],c?.channels[u]]).sort((u,h)=>(h[1]?.cost||0)-(u[1]?.cost||0));p.push(["TOTAL",a.total,c?.total]);for(let[u,h,w]of p){let b=r(h),$=` ${u.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${g(h?.cacheRead||0).padStart(11)} ${g(h?.cacheCreate||0).padStart(11)} ${g(h?.output||0).padStart(8)} ${l(h?.cost||0).padStart(10)} ${l(b).padStart(9)}`;if(c){let v=r(w),S=b!==null&&v?`${((b-v)/v*100).toFixed(0)}%`:"-";$+=` ${l(v).padStart(9)} ${S.padStart(7)}`}console.log($)}console.log(),c&&console.log(se.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(se.dim(` Saved ${e.save}`)),console.log()});Jn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-Y7D5W52I.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:r}=await import("./program-CP4OE2OF.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,f)=>{for(let p of d.commands??[]){let u=f?`${f} ${p.name()}`:p.name();c.push(u),l(p,u)}};l(i,"");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(se.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${se.dim("\xB7")} ${d}`);console.log(),console.log(se.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(se.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(se.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(se.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(se.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(se.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=se.dim(`${r.days}d`);console.log(` ${se.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(se.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as WC}from"commander";import We from"chalk";import{readFileSync as BC}from"fs";import{resolve as JC}from"path";oe();var tn=new WC().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");tn.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{au(JC(process.cwd(),".env"))}catch{}let t=HC(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-I2S6CBKR.js");o(t)}catch(t){console.log(We.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(We.dim(t.stack)),process.exit(1)}});function HC(e,t){try{let o=T();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(We.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(We.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
554
554
  `)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:t||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}tn.command("list").description("list configured boards").action(()=>{try{let e=T();if(!e.boards?.length){console.log(We.dim(`
555
555
  No boards configured.
556
556
  `));return}console.log();for(let t of e.boards){console.log(` ${We.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(We.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(We.dim(` primary label: ${t.primaryToolLabel}`)),console.log(We.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(We.red(` ${e.message}`)),process.exit(1)}});tn.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,t)=>{try{Fr(o=>{if(Array.isArray(o.boards)||(o.boards=[]),o.boards.find(r=>r.id===e))throw new Error(`board "${e}" already exists`);let n=String(t.projects).split(",").map(r=>r.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:t.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(t.days,10)||30,closedWindowDays:parseInt(t.closedDays,10)||30};return t.label&&(s.primaryToolLabel=t.label),o.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(o){console.log(We.red(` ${o.message}`)),process.exit(1)}});tn.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,t)=>{try{Fr(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=[];if(t.name&&(s.name=t.name,r.push(`name="${t.name}"`)),t.projects){let i=String(t.projects).split(",").map(a=>a.trim()).filter(Boolean);if(i.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:i},r.push(`projects=${i.length}`)}if(t.label!==void 0&&(t.label==="-"?(delete s.primaryToolLabel,r.push("label cleared")):(s.primaryToolLabel=t.label,r.push(`label="${t.label}"`))),t.days&&(s.timeRangeDays=parseInt(t.days,10)||s.timeRangeDays,r.push(`days=${s.timeRangeDays}`)),t.closedDays&&(s.closedWindowDays=parseInt(t.closedDays,10)||s.closedWindowDays,r.push(`closed-days=${s.closedWindowDays}`)),r.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${r.join(", ")})`})}catch(o){console.log(We.red(` ${o.message}`)),process.exit(1)}});var Hd=tn.command("column").description("manage a board's columns (add / remove / edit / list)");Hd.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(BC("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!o)throw new Error(`board "${e}" not found`);let n=o.columns||[];if(n.length===0){console.log(We.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let r=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${We.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${We.dim(r)}`)}}catch(t){console.log(We.red(` ${t.message}`)),process.exit(1)}});Hd.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,t,o)=>{try{Fr(n=>{let r=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!r)throw new Error(`board "${e}" not found`);if(r.columns=r.columns||[],r.columns.find(a=>a.id===t))throw new Error(`column "${t}" already exists on board "${e}"`);let i={id:t,title:o.title,kind:o.kind,scopedPrefix:o.scopedPrefix};if(o.kind==="scoped-label"){if(!o.scoped)throw new Error("--scoped required for kind=scoped-label");i.scopedLabel=o.scoped}if(o.kind==="label"){if(!o.label)throw new Error("--label required for kind=label");i.mapsToLabel=o.label}return o.accent&&(i.accent=o.accent),r.columns.push(i),`column "${t}" added to board "${e}"`})}catch(n){console.log(We.red(` ${n.message}`)),process.exit(1)}});Hd.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{Fr(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(i=>i.id!==t),s.columns.length===r)throw new Error(`column "${t}" not found`);return`column "${t}" removed from board "${e}"`})}catch(o){console.log(We.red(` ${o.message}`)),process.exit(1)}});tn.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Fr(t=>{if(!Array.isArray(t.boards)||t.boards.length===0)throw new Error("no boards configured");let o=t.boards.length;if(t.boards=t.boards.filter(n=>n.id!==e),t.boards.length===o)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(t){console.log(We.red(` ${t.message}`)),process.exit(1)}});function Fr(e){let{summary:t,backupPath:o}=jt(n=>e(n));console.log(We.green(`
@@ -852,7 +852,7 @@ Restart the daemon to activate.
852
852
  dist/
853
853
  *.log
854
854
  .env
855
- `}import{Command as kI}from"commander";import st from"chalk";import{writeFileSync as vI,mkdirSync as xI,existsSync as uc,readFileSync as Sv,appendFileSync as Av}from"fs";import{resolve as tr,dirname as Tv}from"path";import{homedir as Og}from"os";var Cv=new kI().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-JMATAWA6.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=EI(o);break;case"bash":s=II(o);break;case"fish":s=NI(o);break;default:console.error(st.red(`unsupported shell: ${n}`)),console.error(st.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?tr(String(e.output)):SI(n);xI(Tv(r),{recursive:!0}),vI(r,s),console.log(st.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),AI(n,r,!!e.yes)});function SI(e){let t=Og();switch(e){case"zsh":return tr(t,".zsh","completions","_agentx");case"bash":return tr(t,".bash_completion.d","agentx.bash");case"fish":return tr(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function AI(e,t,o){if(e==="zsh"){let n=tr(Og(),".zshrc"),s=Tv(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=uc(n)?Sv(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(st.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&uc(n)){let g=["","# agentx completion"];c&&g.push(r),l&&g.push(i),Av(n,g.join(`
855
+ `}import{Command as kI}from"commander";import st from"chalk";import{writeFileSync as vI,mkdirSync as xI,existsSync as uc,readFileSync as Sv,appendFileSync as Av}from"fs";import{resolve as tr,dirname as Tv}from"path";import{homedir as Og}from"os";var Cv=new kI().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-CP4OE2OF.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=EI(o);break;case"bash":s=II(o);break;case"fish":s=NI(o);break;default:console.error(st.red(`unsupported shell: ${n}`)),console.error(st.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?tr(String(e.output)):SI(n);xI(Tv(r),{recursive:!0}),vI(r,s),console.log(st.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),AI(n,r,!!e.yes)});function SI(e){let t=Og();switch(e){case"zsh":return tr(t,".zsh","completions","_agentx");case"bash":return tr(t,".bash_completion.d","agentx.bash");case"fish":return tr(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function AI(e,t,o){if(e==="zsh"){let n=tr(Og(),".zshrc"),s=Tv(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=uc(n)?Sv(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(st.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&uc(n)){let g=["","# agentx completion"];c&&g.push(r),l&&g.push(i),Av(n,g.join(`
856
856
  `)+`
857
857
  `),console.log(st.green("\u2713 Patched ~/.zshrc")),console.log(st.dim("Reload your shell: exec zsh"));return}console.log(st.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(st.cyan(` ${r}`)),l&&console.log(st.cyan(` ${i}`)),console.log(),console.log(st.dim("Then reload: exec zsh")),console.log(st.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=tr(Og(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((uc(n)?Sv(n,"utf-8"):"").includes(t)){console.log(st.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&uc(n)){Av(n,`
858
858
  # agentx completion
@@ -868,4 +868,4 @@ ${jI({...t,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
868
868
  ${o.url}`)}catch(t){console.error(nr.red(` ${t.message}`)),process.exitCode=1}});ti.command("draft <file>").description("turn a draft JSON file ({category, title, fields}) into a pre-filled issue form link; '-' reads stdin").requiredOption("--model <model>","the model that wrote the draft").option("--models <pathOrUrl>","model list to read",Ng).action(async(e,t)=>{try{let o=await _g(t.models);if(!jg(t.model,o)){console.log(Pg(t.model,o)),process.exitCode=1;return}let n=e==="-"?await DI():await _I(e,"utf8"),s=JSON.parse(n),{version:r}=await hi(),i=jv({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(nr.red(` ${o.message}`)),process.exitCode=1}});async function DI(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function h8(){let e=await hi(),t=new MI().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");t.hook("preAction",(o,n)=>{let s=Rf(n);Tf(s)&&Ef("cli",s)});for(let o of[vw,_h,Ph,Bn,ws,lo,Pt,af,So,na,Eo,bn,Ln,To,en,p$,Zo,Yi,rv,Ko,dy,gy,$y,jr,Iy,Dy,ay,qy,Fy,nb,ab,cb,qt,Jn,gv,vr,Jo,Cv,ti])t.addCommand(o);for(let o of _v)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=_v.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,LI(o,74," "),""].join(`
869
869
  `)}),t}var _v=[z,Gs,Io,to,Ar,Ms,Qe,Oo,tn,Mn,Ks,Xs,zo,$t,Cs,ha,Na,_n,ja,Pa,ev,nv,Ao,zr,Dt,Jf,vn,Zr,Ll,sn,St,Rs,ql,tc,wo,No,wv,Zs,yv,lv];function LI(e,t,o){let n=[],s="";for(let r of e)s&&s.length+r.length+2>t&&(n.push(o+s),s=""),s+=(s?", ":"")+r;return s&&n.push(o+s),n.join(`
870
870
  `)}export{h8 as buildProgram};
871
- //# sourceMappingURL=program-JMATAWA6.js.map
871
+ //# sourceMappingURL=program-CP4OE2OF.js.map
@@ -0,0 +1,2 @@
1
+ import{ka as a,la as b,ma as c,na as d,oa as e,pa as f,qa as g,ra as h,sa as i,ta as j,ua as k,va as l,wa as m,xa as n,ya as o,za as p}from"./chunk-S25OP23O.js";import"./chunk-M4BNVLGJ.js";import"./chunk-MEFPXHQJ.js";import"./chunk-SZDACK6O.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-VJVXEVZ7.js";import"./chunk-CVFQA3TH.js";import"./chunk-KUZATIJA.js";import"./chunk-3UOTLMXD.js";import"./chunk-BE64IJWM.js";import"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import"./chunk-BCDC7BOQ.js";import"./chunk-2BI43ZKI.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-5DJOGAS2.js";import"./chunk-JTFCU5LH.js";import"./chunk-3VZNOJJK.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-DUWKRQKT.js";import"./chunk-FXMUUDSH.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-QUFIUXMQ.js";import"./chunk-AV7T3SYT.js";import"./chunk-LE3BXIUF.js";import"./chunk-BERWTVG2.js";import"./chunk-QOYAX2FT.js";import"./chunk-DCIYOPJF.js";import"./chunk-7I7IEX4S.js";import"./chunk-DSYKYZMT.js";import"./chunk-P7FSTC5E.js";import"./chunk-VJ5HC63R.js";import"./chunk-UEEB3UTU.js";import"./chunk-VQRY4IDI.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{o as AgentRegistry,f as DEFAULT_SLOT_WAIT_MS,a as EDIT_TOOL_INSTRUCTION,j as TRACE_STEP_SUMMARY_BYTES,g as buildEntryMeta,h as buildEventDigest,i as buildWikiContext,k as clipForTrace,b as codingInstructions,n as emitTraceStepsFromStreamEvent,m as firstMissingRequiredTool,d as getGlobalRegistry,e as lastActivityLine,p as richReplyPrompt,c as setGlobalRegistry,l as tallyToolUses};
2
+ //# sourceMappingURL=registry-5YYMCHMF.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentix-cli",
3
- "version": "0.177.0",
3
+ "version": "0.178.0",
4
4
  "description": "AI staff for a small company: they find sales, answer clients, write your posts and watch the money, on a machine you own. You approve what matters. Runs a team of AI agents across Telegram, WhatsApp, GitLab, GitHub, crons, webhooks and mesh tasks, on Claude Code, Codex, OpenCode or any LLM API. Web wizard for operators, CLI for engineers.",
5
5
  "license": "MIT",
6
6
  "author": {