agentix-cli 0.226.4 → 0.226.5

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.
@@ -1,4 +1,4 @@
1
- import{Aa as fi,Ba as hi,Da as yi,G as ti,Ia as wi,Ka as bi,N as Zt,O as ni,X as en,Z as si,a as Eo,b as Po,d as ts,f as $e,i as Xo,j as Yo,ja as ri,k as Yt,ka as oi,la as ii,n as Vt,na as ai,oa as di,pa as ci,q as Vo,qa as ui,r as Zo,ta as li,ua as gi,v as ei,xa as pi,za as mi}from"./chunk-TA437DWX.js";import{b as Oo}from"./chunk-MEFPXHQJ.js";import{a as os}from"./chunk-W4YR2RO2.js";import{a as _o}from"./chunk-IH65GDJR.js";import{a as Do,b as No,c as Lo,e as Uo,g as rs,h as Fo,i as ct,l as Ho}from"./chunk-CF2R6BOX.js";import{a as ns,b as Bo}from"./chunk-J3SOEFRE.js";import{a as ss,b as jo}from"./chunk-SIU6STB2.js";import{e as Wo,i as qo,j as Go,k as Ko}from"./chunk-X5C5W3E4.js";import{d as Jo}from"./chunk-KWWBDLE6.js";import{f as zo,g as Qo}from"./chunk-HVMUYEQP.js";import{h as Co,i as Ro}from"./chunk-BE64IJWM.js";import{a as lo,c as go}from"./chunk-MYVHVJWZ.js";import{a as po,b as mo,c as fo,d as ho,l as bo,q as xo}from"./chunk-74MHOALB.js";import{a as yo,b as wo}from"./chunk-LY4G7PCW.js";import{a as So,b as Io}from"./chunk-DPG6VHPX.js";import{c as ko}from"./chunk-BERWTVG2.js";import{a as To,b as es}from"./chunk-A7JSRDJL.js";import{d as vo}from"./chunk-Z5CMA4JN.js";import{b as Mo}from"./chunk-MM7U4PWY.js";import{g as Ao,h as $o}from"./chunk-2XQMUSGM.js";import{c as Wr,d as qr}from"./chunk-AHWWJ7AF.js";import{b as oo,c as io,f as ao}from"./chunk-QZ24XACR.js";import{s as so,v as ze,w as ro,y as pe,z as Xt}from"./chunk-BTLADRMY.js";import{a as be,b as Ae,f as dt}from"./chunk-72SZI2UW.js";import{a as Ke,b as Xn}from"./chunk-FCPTN6NF.js";import{d as uo}from"./chunk-7IW25T4K.js";import{e as Qe,h as co,i as Le}from"./chunk-QUFIUXMQ.js";import{e as Ne}from"./chunk-DSYKYZMT.js";import{Ab as Gu,Ba as zt,Db as Yr,Dc as Ju,Ea as Qr,Ib as Ku,Ob as Vr,Pb as Qt,Qb as Zr,Rb as at,Sb as eo,Tb as to,Zb as no,vb as Xr,yb as Zn}from"./chunk-FWNP27H4.js";import{f as zr,g as Je,h as Wu}from"./chunk-KEUW6YLL.js";import{j as Vn,r as qu}from"./chunk-N47Y5ADQ.js";import{a as Gr,b as we,c as Kr,d as Jr,e as Yn}from"./chunk-VQRY4IDI.js";var zu="[agentx:mid-turn",xi="Delivered into the run that was already working in this chat: it read this before it finished, and its answer covers it.",Si="Got it, I passed that on to the work in progress.";function nn(n,e,t){return`${n}\0${e}\0${t}`}var Qu=new Set(["requests","cron","workflow","events","reminder","business","sprint","notices"]);function Xu(n){return!!n&&!Qu.has(n)}function ki(n,e){return!Xu(n)||!e?!1:!(n==="a2a"&&e==="a2a")}var tn=class{constructor(e={}){this.opts=e}byKey=new Map;taken=new Map;seq=0;now(){return this.opts.now?.()??Date.now()}offer(e,t,s,r){let o={id:`mt-${this.now().toString(36)}-${++this.seq}`,key:e,runId:t,text:s.length>4e3?s.slice(0,3999)+"\u2026":s,from:r,at:this.now()},i=this.byKey.get(e)??[];return i.push(o),this.byKey.set(e,i),o}take(e){let t=this.byKey.get(e);if(!t?.length)return[];this.byKey.delete(e);let s=this.now();for(let r of t)this.taken.set(r.id,s);return this.prune(s),t}isTaken(e){return!!e&&this.taken.has(e)}endRun(e){for(let[t,s]of this.byKey){let r=s.filter(o=>o.runId!==e);r.length?this.byKey.set(t,r):this.byKey.delete(t)}}endChat(e){this.byKey.delete(e)}pending(e){return this.byKey.get(e)?.length??0}prune(e){for(let[t,s]of this.taken)e-s>72e5&&this.taken.delete(t)}};function Yu(n){let e=n.map(t=>`- ${new Date(t.at).toISOString().slice(11,16)}Z, ${t.from}: ${t.text}`);return[`${zu} count=${n.length}]`,`While you were working, ${n.length===1?"this message":"these messages"} arrived in this chat:`,...e,"Take it into account now. If it changes what you should do, change course before your next step. In your answer, say that you saw it and what you did about it. It will not be sent to you again."].join(`
1
+ import{Aa as fi,Ba as hi,Da as yi,G as ti,Ia as wi,Ka as bi,N as Zt,O as ni,X as en,Z as si,a as Eo,b as Po,d as ts,f as $e,i as Xo,j as Yo,ja as ri,k as Yt,ka as oi,la as ii,n as Vt,na as ai,oa as di,pa as ci,q as Vo,qa as ui,r as Zo,ta as li,ua as gi,v as ei,xa as pi,za as mi}from"./chunk-WXV3KLNI.js";import{b as Oo}from"./chunk-MEFPXHQJ.js";import{a as os}from"./chunk-W4YR2RO2.js";import{a as _o}from"./chunk-IH65GDJR.js";import{a as Do,b as No,c as Lo,e as Uo,g as rs,h as Fo,i as ct,l as Ho}from"./chunk-CF2R6BOX.js";import{a as ns,b as Bo}from"./chunk-J3SOEFRE.js";import{a as ss,b as jo}from"./chunk-SIU6STB2.js";import{e as Wo,i as qo,j as Go,k as Ko}from"./chunk-X5C5W3E4.js";import{d as Jo}from"./chunk-KWWBDLE6.js";import{f as zo,g as Qo}from"./chunk-HVMUYEQP.js";import{h as Co,i as Ro}from"./chunk-BE64IJWM.js";import{a as lo,c as go}from"./chunk-MYVHVJWZ.js";import{a as po,b as mo,c as fo,d as ho,l as bo,q as xo}from"./chunk-74MHOALB.js";import{a as yo,b as wo}from"./chunk-LY4G7PCW.js";import{a as So,b as Io}from"./chunk-DPG6VHPX.js";import{c as ko}from"./chunk-BERWTVG2.js";import{a as To,b as es}from"./chunk-A7JSRDJL.js";import{d as vo}from"./chunk-Z5CMA4JN.js";import{b as Mo}from"./chunk-MM7U4PWY.js";import{g as Ao,h as $o}from"./chunk-2XQMUSGM.js";import{c as Wr,d as qr}from"./chunk-AHWWJ7AF.js";import{b as oo,c as io,f as ao}from"./chunk-QZ24XACR.js";import{s as so,v as ze,w as ro,y as pe,z as Xt}from"./chunk-BTLADRMY.js";import{a as be,b as Ae,f as dt}from"./chunk-72SZI2UW.js";import{a as Ke,b as Xn}from"./chunk-FCPTN6NF.js";import{d as uo}from"./chunk-7IW25T4K.js";import{e as Qe,h as co,i as Le}from"./chunk-QUFIUXMQ.js";import{e as Ne}from"./chunk-DSYKYZMT.js";import{Ab as Gu,Ba as zt,Db as Yr,Dc as Ju,Ea as Qr,Ib as Ku,Ob as Vr,Pb as Qt,Qb as Zr,Rb as at,Sb as eo,Tb as to,Zb as no,vb as Xr,yb as Zn}from"./chunk-FWNP27H4.js";import{f as zr,g as Je,h as Wu}from"./chunk-KEUW6YLL.js";import{j as Vn,r as qu}from"./chunk-N47Y5ADQ.js";import{a as Gr,b as we,c as Kr,d as Jr,e as Yn}from"./chunk-VQRY4IDI.js";var zu="[agentx:mid-turn",xi="Delivered into the run that was already working in this chat: it read this before it finished, and its answer covers it.",Si="Got it, I passed that on to the work in progress.";function nn(n,e,t){return`${n}\0${e}\0${t}`}var Qu=new Set(["requests","cron","workflow","events","reminder","business","sprint","notices"]);function Xu(n){return!!n&&!Qu.has(n)}function ki(n,e){return!Xu(n)||!e?!1:!(n==="a2a"&&e==="a2a")}var tn=class{constructor(e={}){this.opts=e}byKey=new Map;taken=new Map;seq=0;now(){return this.opts.now?.()??Date.now()}offer(e,t,s,r){let o={id:`mt-${this.now().toString(36)}-${++this.seq}`,key:e,runId:t,text:s.length>4e3?s.slice(0,3999)+"\u2026":s,from:r,at:this.now()},i=this.byKey.get(e)??[];return i.push(o),this.byKey.set(e,i),o}take(e){let t=this.byKey.get(e);if(!t?.length)return[];this.byKey.delete(e);let s=this.now();for(let r of t)this.taken.set(r.id,s);return this.prune(s),t}isTaken(e){return!!e&&this.taken.has(e)}endRun(e){for(let[t,s]of this.byKey){let r=s.filter(o=>o.runId!==e);r.length?this.byKey.set(t,r):this.byKey.delete(t)}}endChat(e){this.byKey.delete(e)}pending(e){return this.byKey.get(e)?.length??0}prune(e){for(let[t,s]of this.taken)e-s>72e5&&this.taken.delete(t)}};function Yu(n){let e=n.map(t=>`- ${new Date(t.at).toISOString().slice(11,16)}Z, ${t.from}: ${t.text}`);return[`${zu} count=${n.length}]`,`While you were working, ${n.length===1?"this message":"these messages"} arrived in this chat:`,...e,"Take it into account now. If it changes what you should do, change course before your next step. In your answer, say that you saw it and what you did about it. It will not be sent to you again."].join(`
2
2
  `)}function Ph(n){return n.length?JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:Yu(n)}}):""}Xt();dt();var is="task-edge";function vi(n){return{task:Ii(n.message,2e3),agent:n.agent,channel:n.channel??null,continuesExistingSession:n.isFollowUp??!1,...n.agentPrompt?{agentInstructions:Ii(n.agentPrompt,600)}:{}}}var Ti={needsEdge:be("This task is harder than a strong everyday model does reliably, and needs the most capable model available.",{true:"It is at the limit of what a strong model gets right: designing or changing the architecture of a system, a root cause that earlier attempts did not find, a subtle concurrency, security or data-loss problem, a long build with many dependent steps and nobody checking in between, a decision that cannot be undone and turns on fine reasoning, or research that must weigh sources that disagree.",false:"It is ordinary work for a strong model: a routine code change or review, a clear bug with a known cause, answering a question, writing a message or a summary, a status report, a lookup, routing or acknowledging something, or a scheduled check."}),subagentsHelp:be("This task would be done faster or better if separate workers did parts of it at the same time.",{true:"It has several parts that do not depend on each other (many files, repositories, issues, sources or items to handle the same way), or it needs a wide search whose raw results the main worker does not need to keep, or it asks for an independent second review of the work.",false:"It is one line of work where each step needs the result of the step before, or it is small: one file, one question, one message, one command."})},Vu={workAsked:Ae({asked:"The message asks outright for something to be done or answered.",implied:"The message describes a problem, a complaint or something that does not work, and asks for nothing. Work to find the cause or fix it is implied.",none:"The message only informs, thanks, agrees or chats. No work is wanted."},"What does the sender of this message want from the agent?"),designChange:be("Fixing the problem this message describes needs a change to how the system is designed, not one local fix.",{true:"The problem comes from how parts of the system work together, shows up in many places or over time, and its cause is not stated, so someone must investigate and design a change.",false:"The cause and the place are clear and one small change fixes it, or the message describes no problem."})};function Ai(n){return n?{...Ti,...Vu}:Ti}function $i(n){let e=n?.workAsked?.probabilities?.implied;return typeof e=="number"&&Number.isFinite(e)?e:null}function Ii(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}function me(n){return`${n.agentId}:${n.channel}:${n.chatId}`}var ut="CLAUDE_CODE_SUBAGENT_MODEL";function Zu(n,e){if(n.state()==="busy")return null;let s=n.snapshot(),r=n.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:n.opts&&(n.opts.subagentModel??null)!==(e.subagentModel??null)?`sub-agent model changed (${n.opts.subagentModel??"default"} -> ${e.subagentModel??"default"})`:e.resumeSessionId?s.claudeSessionId&&s.claudeSessionId!==e.resumeSessionId?`session changed (${s.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:s.claudeSessionId?"session rotated":null}var Xe=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},Mi=class{handles=new Map;sweeper;handleWorkspace=new Map;unaskedReplyHandler;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,backgroundMaxMs:e.backgroundMaxMs??3*60*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,keepBackground:e.keepBackground,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}setUnaskedReplyHandler(e){this.unaskedReplyHandler=e}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let s=me(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=Zu(r,t);if(!a)return r.claim?.(),r;this.handles.delete(s),this.handleWorkspace.delete(s),this.cfg.log(`[process-registry] respawning ${s}: ${a}`),r.kill(a).catch(()=>{})}if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new Xe(`process registry at global cap (${this.cfg.maxProcessesGlobal}) and no idle handle to evict`,"global",this.cfg.maxProcessesGlobal);if(this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent)throw new Xe(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t,{onUnaskedReply:a=>this.unaskedReplyHandler?.(a)});return this.handles.set(s,i),this.handleWorkspace.set(s,t.workspace),this.cfg.log(`[process-registry] spawned ${s}`),i}release(e,t={}){let s=me(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=me(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}backgroundOpen(e){let t=this.handles.get(me(e));if(!t||t.state()==="dead")return 0;let s=t.snapshot();return Math.max(s.backgroundTasks??0,s.unaskedTurn?1:0)}async kill(e,t="operator"){let s=me(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),await r.kill(t))}closeIdle(e){let t=Date.now(),s=[];for(let[o,i]of this.handles.entries()){if(i.state()!=="idle")continue;let a=i.snapshot();if((a.backgroundTasks??0)>0||a.unaskedTurn)continue;let d=t-Math.max(a.lastTurnAt,a.lastActivityAt??0);d<e.minQuietMs||e.skip?.(i.key)||s.push({ks:o,handle:i,quietFor:d})}let r=s.sort((o,i)=>i.quietFor-o.quietFor).slice(0,e.max);if(e.dryRun)return r.map(o=>o.handle.key);for(let{ks:o,handle:i,quietFor:a}of r){let d=`quiet ${Math.round(a/1e3)}s, ${e.reason}`;this.handles.delete(o),this.handleWorkspace.delete(o),this.cfg.log(`[process-registry] closed idle ${o}: ${d}`),i.kill(`closed idle (${d})`).catch(c=>{this.cfg.log(`[process-registry] closing ${o} failed: ${c?.message||c}`)})}return r.map(o=>o.handle.key)}countForAgent(e){let t=0;for(let s of this.handles.values())s.key.agentId===e&&s.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,s=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot();if((i.backgroundTasks??0)>0||i.unaskedTurn)continue;let a=i.lastTurnAt;a<s&&(s=a,t=o)}if(!t)return!1;let r=me(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt,i=r.backgroundTasks??0,a=i>0||!!r.unaskedTurn,d=a&&(this.cfg.keepBackground?.()??!0);if(o>=(d?this.cfg.backgroundMaxMs:this.cfg.staleTimeoutMs)){this.handles.delete(t),this.handleWorkspace.delete(t);let u=a?`stale with background work (idle ${Math.round(o/1e3)}s, ${i} open)`:`stale (idle ${Math.round(o/1e3)}s)`;s.kill(u),this.cfg.log(`[process-registry] killed stale ${t}: ${u}`);continue}if(a)continue;let c=e-Math.max(r.lastTurnAt,r.lastActivityAt??0);if(c>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`idle (${Math.round(c/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let u=this.handleWorkspace.get(t);if(u){let l=null;try{l=this.cfg.currentWorkspaceHash(s.key,u)}catch(g){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${g?.message||g}`);continue}if(l!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let g=r.claudeMdHash??"unmarked",m=l??"unmarked";s.kill(`claude-md drifted (${g} \u2192 ${m})`),this.cfg.log(`[process-registry] killed drifted ${t} (${g} \u2192 ${m})`)}}}}}};var el=.7,tl=.7,cs=.8,nl=.7,sl="[Implied request] This message describes a problem and does not say what to do. Start your reply with one sentence that states the job as you understand it, then do that job. If it could mean two different jobs, or the work cannot be undone, ask one question first.",rl="[Sub-agents] This job has parts that do not depend on each other. Start sub-agents (the Agent tool, named Task in older Claude Code) for those parts in one message so they run at the same time, give each a complete brief, and check their results yourself before you report.";function Ci(){try{return ze(is)!=="off"}catch{return!1}}function Ri(n,e){if(n==="claude-code"){let t=e?.edgeModels?.[n];return t&&/^(claude-|fable$|opus$|sonnet$)/.test(t)?t:void 0}if(n==="codex-cli"){let t=e?.edgeModels?.[n];return t&&/^(gpt-|o\d)/.test(t)?t:void 0}}function ol(n){let e=n?.indexOf("--tools")??-1;if(e<0)return!0;let t=(n[e+1]??"").split(",").map(s=>s.trim());return t.includes("Agent")||t.includes("Task")}async function _i(n){let e=null,t=null,s=(_,L=null,B=null)=>({upgraded:!1,subagents:!1,needsEdge:L,subagentsHelp:B,...e!==null||t!==null?{impliedWork:!1,impliedP:e,designChange:t}:{},reason:_}),r=n.impliedWork??"off",o=r!=="off";if(oo(n.channel))return s(`${n.channel} requests retain the configured model`);let i;try{i=await pe(is,vi(n),Ai(o),{incumbent:{needsEdge:0,subagentsHelp:0,...o?{workAsked:"asked",designChange:0}:{}},features:{agent:n.agent,channel:n.channel??"unknown"},timeoutMs:1500})}catch{return s("edge seat threw \u2014 keeping the agent's model")}if(!i)return s("edge seat unavailable \u2014 keeping the agent's model");let a=i.answers,d=as(a.needsEdge?.noul),c=as(a.subagentsHelp?.noul),u=n.upgradeAt??el,l=n.subagentsAt??tl;o&&(e=$i(i.answers),t=as(a.designChange?.noul));let g=e!==null&&e>=cs,m=g&&t!==null&&t>=nl,h=r==="active",y=d!==null&&d>=u,S=y||h&&m,x=h&&g,C=n.tier==="claude-code"&&c!==null&&c>=l,N=`edge ${sn(d)}, sub-agents ${sn(c)}`+(o?`, implied ${sn(e)}, design ${sn(t)}`:""),w=r==="shadow"&&g?` \u2014 implied work (shadow): would state the job${m&&!y?" and move up":""}`:"";if(i.mode!=="active")return s(`shadow \u2014 would ${S||g&&m?"move up":"keep the model"}${C?" and ask for sub-agents":""}${g?" and state the implied job":""} (${N})`,d,c);let v=S&&n.edgeModel?n.edgeModel:void 0,R=!!v&&v!==n.currentModel;return!v&&!C&&!x?s(`${S?"needs the edge model, but none is configured":"the agent's model is enough"} (${N})${w}`,d,c):{...v?{model:v}:{},upgraded:R,subagents:C,needsEdge:d,subagentsHelp:c,...o?{impliedWork:x,impliedP:e,designChange:t}:{},reason:[R?`${y?"hard task":"implied hard task"} \u2192 ${v} for this job`:"",v&&!R?`${y?"hard task":"implied hard task"}, already on the edge model (${v})`:"",C?"sub-agents advised":"",x?"implied work: the agent states the job":""].filter(Boolean).join(", ")+` (${N})${w}`}}function Ei(n,e){return n?.model?n.upgraded?n.model:void 0:e}function Pi(n,e){if(!n)return{};let s=e.tier==="claude-code"&&ol(e.claudeArgs),r=[n.impliedWork?sl:"",n.subagents&&s?rl:""].filter(Boolean);return{...n.upgraded&&n.model?{model:n.model}:{},...n.upgraded&&n.model&&s?{subagentModel:n.model}:{},...r.length?{turnNote:r.join(`
3
3
  `)}:{}}}function as(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function sn(n){return n===null?"-":n.toFixed(2)}Xt();dt();var rn="tool-set",Oi=["answer","code","full"],Di={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},il=.1;function Li(n){return{task:Ni(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:Ni(n.agentPrompt,600)}:{}}}var Bi={bundle:Ae({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function Ui(n,e=il){let s=n?.bundle?.probabilities;if(!s)return"full";let r=us(s.answer),o=us(s.code),i=us(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function ji(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Di.answer.includes(t))?"answer":e.every(t=>Di.code.includes(t))?"code":"full"}function Fi(n,e){return Oi.indexOf(n)<Oi.indexOf(e)}function us(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Ni(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var Hi=!1;function Wi(n,e){let t=ze(rn);if(t!=="off")return t==="active"&&!Hi&&(Hi=!0,e(`[decisions] seat "${rn}" is set to active, but only shadow is built: it records and changes nothing`)),pe(rn,Li(n),Bi,{incumbent:{bundle:"full"},links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel??"unknown"}}).then(s=>{if(!s)return null;let r=s.answers,o=Ui(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function qi(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=ji(r);ro(s.callId,"bundle",o,{kind:"outcome",labeledBy:"tool-use"});let i=a=>typeof s.probabilities[a]=="number"?s.probabilities[a].toFixed(2):"-";t(`[${e.agentId}] tool-set shadow: would start with ${s.bundle} (answer ${i("answer")}, code ${i("code")}, full ${i("full")}); run used ${r.filter(a=>!a.startsWith("mcp__")).join(", ")||"no built-in tool"} \u2192 needed ${o}`+(Fi(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function al(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function Gi(n,e){let t=al(n.contextTokens,n.turnInputTokens),s=n.idleMs<e.cacheTtlMinutes*6e4,r=.1*(t-1),o=e.freshTokens*(e.cacheWriteFactor+r),i=n.contextTokens;if(!i||i<=0)return{rotate:!1,resumeCost:null,freshCost:o,warm:s,requestsPerTurn:t};let a=i*((s?.1:e.cacheWriteFactor)+r);return{rotate:a>o*e.margin,resumeCost:a,freshCost:o,warm:s,requestsPerTurn:t}}function ls(n){let e=s=>`${Math.round(s/1e3)}k`,t=n.warm?"warm cache":"cold cache";return n.resumeCost===null?`resume: no context reading (${t})`:`${n.rotate?"start fresh":"resume"}: resume \u2248${e(n.resumeCost)}, fresh \u2248${e(n.freshCost)} input-token equivalents (${t}, ${n.requestsPerTurn} requests/turn)`}Xt();dt();var Ki="session-continuity",Ji={continues:be("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:be("Does the new request refer to something stated earlier in the conversation?")};function zi(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:gs(n.message,1200),previousRequest:n.previousMessage?gs(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>gs(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function Qi(n,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,s=n.continues.noul,r=n.needsHistory.noul;return s<=t&&r<=t}function gs(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}function Xi(n,e){let t=uo(n,e,"gitlab-user","tokenEnv");return t.status==="ok"&&t.value?{token:t.value,source:`integrations(${t.envVar})`}:{source:t.status}}function Zh(n,e){let t=n.channels.gitlab?.token;if(!e)return{token:t,source:"global"};let s=(n.channels.gitlab?.agentMappings||[]).find(o=>o.agentId===e);if(s?.token)return{token:s.token,source:"agentMappings"};let r=Xi(n,e);return r.token?{token:r.token,source:r.source}:t?{token:t,source:"global"}:{token:void 0,source:r.source}}function ey(n,e){let t=(n.channels.gitlab?.agentMappings||[]).find(s=>s.agentId===e);return t?.token?t.token:Xi(n,e).token}var Yi=null;function ty(n){Yi=n}function on(n,e){let t;try{t=Yi?.(e)}catch{t=void 0}return t&&(n.GITLAB_TOKEN=t,n.GITLAB_ACCESS_TOKEN=t),n}import{execa as mn}from"execa";import{spawn as dl}from"node:child_process";import{createHash as cl}from"node:crypto";import{createInterface as ul}from"node:readline";var Me=class extends Error{},ll=n=>dl("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),ps=class{child;pending=new Map;nextId=0;dead=!1;busy=!1;threadId;idle;notify;failTurn;constructor(e,t){this.child=t(e),this.child.stderr.resume(),ul({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
4
4
  `)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let s=++this.nextId;return new Promise((r,o)=>{this.pending.set(s,{resolve:r,reject:o}),this.write({id:s,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let s of this.pending.values())s.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},ms=class{constructor(e=ll,t=8,s=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=s}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let s=cl("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([x],[C])=>x.localeCompare(C))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new Me("Conversation already running");r&&(r.fingerprint!==s||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let x=[...this.entries].find(([,C])=>!C.connection.busy);if(!x)throw new Me("Codex warm process capacity reached");x[1].connection.close(),this.entries.delete(x[0])}try{r={fingerprint:s,connection:new ps(e,this.launchProcess)}}catch{throw new Me("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,d="",c,u,l,g,m=!1,h=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",h,{once:!0});let y=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),S=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let x={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...x,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(S),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let N=new Promise((w,v)=>{i.failTurn=v,i.notify=(R,_)=>{if(_?.threadId!==u)return;let L=_.item,B={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({..._,type:R.replace("/","."),...L?{item:{...L,type:B[L.type]||L.type}}:{}}),R==="item/completed"&&L?.type==="agentMessage"&&L.phase==="final_answer"&&(c=L.text),R==="item/agentMessage/delta"&&(m||(m=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),d+=_.delta,e.onDelta?.(_.delta,d)),R==="thread/tokenUsage/updated"){let H=_.tokenUsage.last;g=H.inputTokens;let q=H.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(H.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(H.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(H.cacheWriteInputTokens||0)}}R==="turn/completed"&&(_.turn.status==="completed"?w():v(new Error(_.turn.error?.message||`Codex turn ${_.turn.status}`)))}});return N.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await N,{content:c??d,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:g,duration:Date.now()-t}}catch(x){if(i.close(),!a&&!e.signal?.aborted)throw new Me(x.message);return{content:d,codexSessionId:u,usage:l,contextTokens:g,error:x.message,duration:Date.now()-t}}finally{clearTimeout(S),clearTimeout(y),e.signal?.removeEventListener("abort",h),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},Vi=new ms;import{execFile as Dl}from"child_process";import{StringDecoder as ft}from"string_decoder";import{mkdtempSync as fa,readFileSync as ha,rmSync as ya}from"fs";import{join as gn}from"path";import{tmpdir as wa}from"os";function an(n){let e=(n||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let c=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${c?` Resets ${c[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),d=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||d===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||d===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||d===529||d===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||d===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:d&&d>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${d}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function dn(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function cn(n){if(!n||typeof n!="object")return;let e,t=-1,s=-1;for(let[r,o]of Object.entries(n)){let i=o&&typeof o=="object"?o:{},a=typeof i.costUSD=="number"?i.costUSD:0,d=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&d>s)&&(e=r,t=a,s=d)}return e}var Be=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}};var Zi=null;function lt(){return Zi}function uy(n){Zi=n}import{spawn as gl}from"child_process";import{randomUUID as pl}from"crypto";import{existsSync as ml,readFileSync as fl}from"fs";import{resolve as hl}from"path";function yl(n){let e=hl(n,"CLAUDE.md");if(!ml(e))return null;try{let t=fl(e,"utf8");return xo(t)}catch{return null}}var wl=20*60*1e3,bl=5e3,gt=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},pt=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function xl(n,e){return n.AGENTX_AGENT_ID=e.agentId,on(n,e.agentId),n.AGENTX_GUARD="required",n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,n.AGENTX_QUEUE_CHANNEL=e.channel,n.AGENTX_QUEUE_CHAT=e.chatId,delete n.AGENTX_TASK_ID,n}var Sl=200;function kl(n){return n.type==="result"||n.type==="system"&&n.subtype==="init"}function Tl(n,e){return e&&(n[ut]=e),n}var ea=class{constructor(e={}){this.opts=e}spawn(e,t,s){return new fs(e,t,this.opts,s)}},fs=class{constructor(e,t,s,r={}){this.key=e;this.opts=t;this.factoryOpts=s;this.hooks=r;let o=s.binary??"claude",i=this.buildArgs(t),a=this.log=s.log??(()=>{});this.child=gl(o,i,{cwd:t.workspace,env:Le(Tl(xl({...process.env},e),t.subagentModel),t.billing),stdio:["pipe","pipe","pipe"]}),this.snap={key:e,pid:this.child.pid??null,claudeSessionId:t.resumeSessionId??null,state:"warm-cold",spawnedAt:Date.now(),lastTurnAt:Date.now(),turnCount:0,lastInputTokens:0,pendingTaskId:null,claudeMdHash:yl(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",d=>this.onStdout(d)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",d=>a(`[claude pid=${this.snap.pid}] stderr: ${d.trim()}`)),this.child.on("exit",d=>{this.exited=!0,this.exitCode=d,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${d}`};let c=this.waiters.splice(0);for(let u of c)u(null)}),this.child.on("error",d=>{a(`[claude pid=${this.snap.pid}] spawn error: ${d.message}`),this.killReason=`spawn-error: ${d.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();background=new Be;passedOn=new WeakSet;snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(m=>{t=m}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=pl(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
@@ -33,7 +33,7 @@ ${n}`}function Ll(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
33
33
  `,l)}};w.stdout?.on("data",A=>{L+=H.write(A);let k=L.split(`
34
34
  `);L=k.pop()||"";for(let U of k)J(U)}),w.stderr?.on("data",A=>{B+=q.write(A)});let M=await w;if(i&&i.removeEventListener("abort",_),L+=H.end(),L.trim()&&J(L),B+=q.end(),v)return{content:"",error:R||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d,opencodeSessionId:m};if(M.exitCode!==0||h){let A=M,k;return A.timedOut?k=`OpenCode timed out after ${Math.round(C/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:h?k=h:A.code==="ENOENT"||/ENOENT|spawn opencode/i.test((A.shortMessage||"")+" "+B)?k=ga():k=B.trim()||`OpenCode exited with code ${A.exitCode??"unknown"}`,{content:"",...V(k),duration:Date.now()-d,usage:g,opencodeSessionId:m}}return S=!1,{content:l.trim(),duration:Date.now()-d,usage:g,billedModel:e.model||n.model,opencodeSessionId:m}}catch(C){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d};let N=/ENOENT|spawn opencode/i.test(C?.message||"")?ga():C?.message;return{content:l,...V(N||"OpenCode failed"),duration:Date.now()-d,usage:g,opencodeSessionId:m}}finally{x?.(),y?.release(S)}}async function zl(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=Ce(n,e,s),d="",c=i({prompt:a,options:{model:e.model||n.model,cwd:e.cwd??n.workspace,permissionMode:"bypassPermissions"}});for await(let u of c)u.type==="result"&&u.subtype==="success"&&(d=u.result||"");return{content:d,duration:Date.now()-r}}catch(o){return{content:"",...V(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Ql(n,e,t,s,r,o,i,a,d){let c=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,g=!1,m=()=>{let S=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(S))}catch{}};a&&(a.aborted?m():a.addEventListener("abort",m,{once:!0}));let h=setTimeout(()=>{g=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);h.unref?.();let y=()=>({content:"",...V(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-c});try{let S=n.provider||"claude-code",x=s?`${s}
35
35
 
36
- ${e.message}`:e.message,C=e.context?.sender,N=typeof C=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(C),w=e.context?.channel==="web-chat"&&N?{userId:C,agentId:e.agentId||"acme-public"}:void 0,v=ho(n),R=Object.keys(v).length>0,_={task:x,cwd:e.cwd??n.workspace,provider:S,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:w,providerOpts:o,abortSignal:l.signal,mcpServers:R?v:void 0,beforeMcpCall:R?(J,M)=>bo(J,M,v,{root:process.cwd(),agentId:e.agentId}):void 0};if(r){let{generateStream:J}=await import("./agent-F2VJKD7X.js"),M="",A,k,U,W;for await(let P of J(_)){if(d)try{d(P)}catch{}if(P.type==="text_delta")M+=P.text,r(P.text,M);else if(P.type==="thinking_delta")P.text&&i&&i(P.text);else if(P.type==="generate_result"){if(P.result.content&&P.result.content!==M){let Q=P.result.content.slice(M.length);Q?(M=P.result.content,r(Q,M)):M=P.result.content}A=P.result.tokensUsed,P.result.inputTokens!=null&&(k=P.result.inputTokens),P.result.outputTokens!=null&&(U=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==M){let Q=P.result.content.slice(M.length);Q?(M=P.result.content,r(Q,M)):M=P.result.content}P.result.tokensUsed!=null&&(A=P.result.tokensUsed)}else P.type==="error"&&(W=P.error)}return W&&!M?g?y():W==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...V(`Orchestrator error: ${W}`),duration:Date.now()-c}:((k===void 0||U===void 0)&&A&&(k=Math.round(A*.7),U=A-k),{content:M||"Done.",tokensUsed:A,usage:k!==void 0||U!==void 0?{inputTokens:k||0,outputTokens:U||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c})}let{generate:L}=await import("./agent-F2VJKD7X.js"),B=await L(_),H=B.inputTokens,q=B.outputTokens;if((H===void 0||q===void 0)&&B.tokensUsed){let J=B.tokensUsed;H=Math.round(J*.7),q=J-H}return{content:B.content||"Done.",tokensUsed:B.tokensUsed,usage:H!==void 0||q!==void 0?{inputTokens:H||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c}}catch(S){return g?y():S?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...V(`Orchestrator error: ${S.message}`),duration:Date.now()-c}}finally{clearTimeout(h),a&&a.removeEventListener("abort",m)}}var Xl=1e3;async function Yl(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),Xl),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function Vl(n,e,t,s,r,o,i){let a=lt();if(!a)return null;let d=Date.now(),{channel:c,chatId:u}=yt(e.context),l={agentId:e.agentId,channel:c,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let g,m=!1;try{let M=a.list().length;g=a.acquire(l,{agentId:e.agentId,channel:c,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs,subagentModel:e.subagentModel}),m=a.list().length>M}catch(M){return M instanceof Xe,null}m&&xs(e.agentId,n,e.model,s,"persistent");let h=Ce(n,e,t),y="",S,x,C,N,w,v,R,_="",L="",B=M=>{if(!i||!M)return;let A;if(L&&M.startsWith(L)?A=M.slice(L.length):A=_&&!_.endsWith(`
36
+ ${e.message}`:e.message,C=e.context?.sender,N=typeof C=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(C),w=e.context?.channel==="web-chat"&&N?{userId:C,agentId:e.agentId||"acme-public"}:void 0,v=ho(n),R=Object.keys(v).length>0,_={task:x,cwd:e.cwd??n.workspace,provider:S,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:w,providerOpts:o,abortSignal:l.signal,mcpServers:R?v:void 0,beforeMcpCall:R?(J,M)=>bo(J,M,v,{root:process.cwd(),agentId:e.agentId}):void 0};if(r){let{generateStream:J}=await import("./agent-XNZ5TOG5.js"),M="",A,k,U,W;for await(let P of J(_)){if(d)try{d(P)}catch{}if(P.type==="text_delta")M+=P.text,r(P.text,M);else if(P.type==="thinking_delta")P.text&&i&&i(P.text);else if(P.type==="generate_result"){if(P.result.content&&P.result.content!==M){let Q=P.result.content.slice(M.length);Q?(M=P.result.content,r(Q,M)):M=P.result.content}A=P.result.tokensUsed,P.result.inputTokens!=null&&(k=P.result.inputTokens),P.result.outputTokens!=null&&(U=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==M){let Q=P.result.content.slice(M.length);Q?(M=P.result.content,r(Q,M)):M=P.result.content}P.result.tokensUsed!=null&&(A=P.result.tokensUsed)}else P.type==="error"&&(W=P.error)}return W&&!M?g?y():W==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...V(`Orchestrator error: ${W}`),duration:Date.now()-c}:((k===void 0||U===void 0)&&A&&(k=Math.round(A*.7),U=A-k),{content:M||"Done.",tokensUsed:A,usage:k!==void 0||U!==void 0?{inputTokens:k||0,outputTokens:U||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c})}let{generate:L}=await import("./agent-XNZ5TOG5.js"),B=await L(_),H=B.inputTokens,q=B.outputTokens;if((H===void 0||q===void 0)&&B.tokensUsed){let J=B.tokensUsed;H=Math.round(J*.7),q=J-H}return{content:B.content||"Done.",tokensUsed:B.tokensUsed,usage:H!==void 0||q!==void 0?{inputTokens:H||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c}}catch(S){return g?y():S?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...V(`Orchestrator error: ${S.message}`),duration:Date.now()-c}}finally{clearTimeout(h),a&&a.removeEventListener("abort",m)}}var Xl=1e3;async function Yl(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),Xl),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function Vl(n,e,t,s,r,o,i){let a=lt();if(!a)return null;let d=Date.now(),{channel:c,chatId:u}=yt(e.context),l={agentId:e.agentId,channel:c,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let g,m=!1;try{let M=a.list().length;g=a.acquire(l,{agentId:e.agentId,channel:c,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs,subagentModel:e.subagentModel}),m=a.list().length>M}catch(M){return M instanceof Xe,null}m&&xs(e.agentId,n,e.model,s,"persistent");let h=Ce(n,e,t),y="",S,x,C,N,w,v,R,_="",L="",B=M=>{if(!i||!M)return;let A;if(L&&M.startsWith(L)?A=M.slice(L.length):A=_&&!_.endsWith(`
37
37
  `)?`
38
38
 
39
39
  ${M}`:M,L=M,!!A){_+=A;try{i(A,_)}catch{}}},H=!1,q=()=>{H=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let J=!1;try{let M=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let A of g.runTurn({message:h,taskId:e.taskId??"unknown",deadlineMs:M})){if(J=!0,r)try{r(A.raw)}catch{}if(A.type==="assistant"){let k=A.raw.message?.content??[];for(let W of k)W.type==="text"&&typeof W.text=="string"?(y=W.text,B(W.text)):W.type==="tool_use"&&(L="");let U=A.raw.message?.usage;if(U){let W=(U.input_tokens||0)+(U.cache_read_input_tokens||0)+(U.cache_creation_input_tokens||0);W>0&&(N=W)}}if(A.type==="result"){let k=A.raw;if(k.is_error){let U=V(typeof k.result=="string"?k.result:"claude error");S=U.error,x=U.errorKind}else typeof k.result=="string"&&k.result.length>0&&(y=k.result,_||B(k.result));typeof k.session_id=="string"&&(R=k.session_id),k.usage&&(C={inputTokens:k.usage.input_tokens||0,outputTokens:k.usage.output_tokens||0,cacheReadTokens:k.usage.cache_read_input_tokens||0,cacheCreateTokens:k.usage.cache_creation_input_tokens||0}),typeof k.num_turns=="number"&&(w=k.num_turns),typeof k.message?.model=="string"?v=k.message.model:typeof k.model=="string"?v=k.model:v=cn(k.modelUsage)||v}}}catch(M){if(H)S="task cancelled by operator",x="cancelled";else if(J)if(M instanceof pt)S=`Claude Code was stopped mid-turn (${M.reason}), before its time limit`,x="interrupted";else if(M instanceof gt){let A=V(`Claude Code timed out after ${Math.round(M.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);S=A.error,x=A.errorKind}else{let A=V(`persistent claude process error: ${M?.message||String(M)}`);S=A.error,x=A.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${M?.message||M}); falling back to spawn-per-task`),a.release(l,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",q),null}finally{o&&o.removeEventListener("abort",q)}return H&&!S&&(S="task cancelled by operator",x="cancelled"),{content:H?"":y,error:S,errorKind:x,duration:Date.now()-d,usage:C,contextTokens:N,numTurns:w,billedModel:v,claudeSessionId:R}}function Ma(n){let e=we(n.autonomy);if(!e&&!n.personLimits)return{args:[]};if(!n.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?oa(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:ua(t.args,n.taskId,n.agentId)}function Zl(n){return we(n.autonomy)||!!n.personLimits}async function eg(n,e,t,s,r,o,i){let a=we(e.autonomy)?e.autonomy:void 0,d=a&&ia(a,n.tier)||e.personLimits&&la(n.tier);if(d)return{content:"",error:d,...a?{autonomy:a}:{}};let c=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:c,message:a?`${Jr(a)}
@@ -201,4 +201,4 @@ ${Oe}`),f+=Oe.length}catch{}}}let Nu=Wn.length>0?Wn.join(`
201
201
 
202
202
  Agent: ${E.content}`,meta:vh(te,e.context)})},ue=>this.log(ue)),Io(e.agentId,e.message,E.content,{channel:b,chatId:T,sender:Un},this.memoryStore).catch(()=>{}),dd(e.agentId,e.message,E.content,{channel:b,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{}));let he=E.billedModel||e.model||c.def.model,Ge=e.context?.channel,ye=Ge&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${Ge}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,E.duration||0,E.usage,e.message.length,E.content.length,!1,he,Ge,ye),this.log(`[${e.agentId}] completed in ${E.duration}ms`+(E.tokensUsed?` (${E.tokensUsed} tokens)`:"")+` ${D()}`)}return E}catch(p){c.errors++,this.log(`[${e.agentId}] unexpected error: ${p.message}`);let f=an(p.message);return se={content:"",error:dn(f),errorKind:f.kind},se}finally{if(Fr.stop(),Hr&&ce&&Ee)try{let p=se?.usage,f=li(Ee,ce,{error:se?se.error||void 0:R.signal.aborted?qe(R.signal).message:"run ended before completion",canceled:gi(se?.errorKind)||this.stoppedRuns.has(w.id)||this.interruptedRuns.has(w.id)||!se&&R.signal.aborted,durationMs:Date.now()-w.startedAt.getTime(),...p?{inputTokens:p.inputTokens,outputTokens:p.outputTokens}:{},readOnly:zn,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});f&&f!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ce} ${f.status} (${f.meta?.wrap?.mode??"linear"})`)}catch(p){this.log(`[${e.agentId}] workflows.required: could not close run ${ce} (non-fatal): ${p?.message||p}`)}dr(se),ur(se)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:this.withLastActivity(this.withWorkflowSteps(e.runningTasks)),lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}withLastActivity(e){return e.map(t=>{let s=this.taskOutputs.get(t.id),r=s?bh(s.buffer.slice(-2e3)):void 0;return r?{...t,lastActivity:r}:t})}withWorkflowSteps(e){let t=this.workflowRuns;return!t||!e.some(s=>s.workflow)?e:e.map(s=>{if(!s.workflow)return s;try{let r=t.get(s.workflow.runId);return r?{...s,workflow:{...s.workflow,workflowId:r.workflowId,step:pi(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=G(process.cwd(),st,this.safe(e.agentId),t);ae(s)||lh(s,{recursive:!0});let r=G(s,`${this.safe(e.id)}.json`);ph(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=G(process.cwd(),st,this.safe(e));if(!ae(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let d=new Date(s).toISOString().slice(0,10),c=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[c,d]){let g=G(a,l);if(ae(g))try{for(let m of ke(g)){if(!m.endsWith(".json"))continue;let h=m.split("-")[0],y=parseInt(h,10);if(!Number.isFinite(y)||y<i||y>s)continue;let S=Math.floor((s-y)/36e5),x=t-1-S;x>=0&&x<t&&o[x]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=G(process.cwd(),st);if(!ae(e))return 0;let t=0;for(let s of ke(e)){let r=G(e,s),o;try{o=ke(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=G(r,i),d;try{d=ke(a).filter(c=>c.endsWith(".json")).sort().reverse()}catch{continue}for(let c of d)try{let u=JSON.parse(_t(G(a,c),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let g=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:g,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Ih){let t=G(process.cwd(),st);if(!ae(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of ke(t)){let i=G(t,o),a;try{a=ke(i)}catch{continue}for(let d of a){let c=Date.parse(d+"T00:00:00Z");if(!(Number.isNaN(c)||c>=s))try{gh(G(i,d),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=G(process.cwd(),st,this.safe(e));if(!ae(s))return[];let r=ke(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=G(s,i),d;try{d=ke(a).filter(c=>c.endsWith(".json"))}catch{continue}d.sort().reverse();for(let c of d){if(o.length>=t)break;try{let u=JSON.parse(_t(G(a,c),"utf-8")),{transcript:l,responseText:g,...m}=u;o.push(m)}catch{}}}return o}getTaskRecord(e,t){let s=G(process.cwd(),st,this.safe(e));if(!ae(s))return null;let r=this.safe(t),o=ke(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=G(s,i,`${r}.json`);if(ae(a))try{return JSON.parse(_t(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}armBudgetRelease(){this.budgetReleaseTimer||(this.budgetReleaseTimer=setInterval(()=>this.releaseBudgetHolds(),6e4),this.budgetReleaseTimer.unref?.())}releaseBudgetHolds(){let e=0;for(let t of this.budgetHolds.agents()){let s=this.budgetHolds.take(t,r=>!Vt(t,void 0,Yt(t,r.chatId)));if(s.length){e+=s.length,this.log(`[${t}] budget allows runs again \u2014 releasing ${s.length} held message(s)`);for(let r of s){let o=r.context||{channel:r.channel,chatId:r.chatId};this.execute({message:r.text,agentId:t,context:o,queuedAt:r.heldAt}).then(i=>this.postQueuedResponseToChannel(t,o,i)).catch(i=>this.log(`[${t}] held message failed: ${i?.message??i}`))}}}return this.budgetHolds.size===0&&this.budgetReleaseTimer&&(clearInterval(this.budgetReleaseTimer),this.budgetReleaseTimer=null),e}heldForBudget(e){return this.budgetHolds.count(e)}postQueuedResponseToChannel(e,t,s){let r=os();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||$e(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();if(a){if(!r.getChannel(o)){hh.has(o.split("@")[0])||this.log(`[${e}] queued response not posted: no adapter for channel "${o}"`);return}r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(d=>this.log(`[${e}] queued response post failed: ${d?.message??d}`))}}runningTaskRoot(e){return this.taskAborts.get(e)?.rootId}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}runningTraceId(e,t){return this.agents.get(e)?.runningTasks.find(s=>s.id===t)?.traceId??null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let d=yt(a);return d.channel===t.channel&&d.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let s=[...this.taskAborts].filter(([,r])=>r.agentId===e.agentId&&r.channel===e.channel&&r.chatId===e.chatId).map(([r])=>r);t=s.length===1?s[0]:void 0}return t?this.signalTargetOf(t):null}signalTargets(){return[...this.taskAborts].filter(([,e])=>!e.controller.signal.aborted).map(([e])=>this.signalTargetOf(e)).filter(e=>e!==null)}signalTargetOf(e){let t=this.taskAborts.get(e);return t?{taskId:e,traceId:t.traceId,agentId:t.agentId,channel:t.channel,chatId:t.chatId,sender:t.sender,rootId:t.rootId,originalMessage:t.originalMessage,origin:t.origin??null,...t.workflowRunId?{workflowRunId:t.workflowRunId}:{}}:null}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator",o){let i=0;for(let[a,d]of this.taskAborts)d.agentId!==e||d.channel!==t||d.chatId!==s||o!==void 0&&d.sender!==o||this.cancelRunningTask(a,r)&&i++;return i}offerMidTurn(e,t,s,r){if(this.config.session?.midTurnMessages===!1||e.midTurnId||t.def.tier!=="claude-code"||!ki(s,r)||e.preSpawnRetry||e.timeLimitContinuation||e.message.startsWith("[agentx:")||!this.messageQueue.isBusy(e.agentId,s,r))return;let o=t.runningTasks.find(d=>d.channel===s&&d.chatId===r),i=String(e.context?.sender?.name??e.context?.sender??"the owner"),a=this.midTurn.offer(nn(e.agentId,s,r),o?.id??"-",e.message,i);e.midTurnId=a.id,this.log(`[${e.agentId}] message offered to the running turn ${o?.id??"in this chat"} (${a.id}) chat=${s}:${r}`)}takeMidTurn(e,t,s){let r=this.midTurn.take(nn(e,t,s));return r.length&&this.log(`[${e}] running turn read ${r.length} message(s) mid-turn chat=${t}:${s}`),r}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:d,originalMessage:c}=o,u=o.controller.signal.aborted,l=!1;u&&c&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,d,c));let g=Date.now();this.messageQueue.enqueue(i,a,d,{text:t,sender:s,timestamp:g,channel:a,chatId:d,originalContext:{channel:a,chatId:d,sender:s}});let m=this.messageQueue.pendingCount(i,a,d);Z().emit("task:queued",{agentId:i,channel:a,chatId:d,at:new Date(g).toISOString(),sender:{name:s},humanRoot:!1,person:Vr(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:g});let h=!1;if(r.replace){let y=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(y))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${y}`),h=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${m}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:d,replaced:h,edited:l,pending:m}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,d=i.chatId;return new Promise(c=>{let u=!1,l=g=>{u||(u=!0,c(g))};this.log(`[${e}] operator resumed ${a}:${d} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(d),context:{channel:a,chatId:d,sender:r},onStart:g=>l({ok:!0,agentId:e,channel:a,chatId:d,taskId:g,queued:!1})}).then(g=>{$e(g.error)?l({ok:!0,agentId:e,channel:a,chatId:d,queued:!0}):g.error?l({ok:!1,status:500,error:g.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:d,queued:!1,answeredBy:g.viaAttachedSession?"attached":"other"})}).catch(g=>l({ok:!1,status:500,error:g?.message??String(g)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function Eh(n,e){return n===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
203
203
  `)}export{Ph as a,Mi as b,Xi as c,Zh as d,ey as e,ty as f,Vi as g,uy as h,yl as i,ea as j,un as k,vy as l,Cy as m,Ry as n,Dy as o,yt as p,Hl as q,Aa as r,Jl as s,zl as t,Ql as u,Ca as v,yn as w,Da as x,pw as y,wn as z,bg as A,ww as B,bw as C,Sw as D,As as E,Iw as F,vw as G,xt as H,Va as I,xn as J,Eg as K,Mw as L,Rs as M,Z as N,md as O,Yg as P,tp as Q,yd as R,Jw as S,wd as T,vd as U,ab as V,db as W,_d as X,cb as Y,Ed as Z,An as _,wb as $,bb as aa,Tt as ba,gm as ca,pm as da,mm as ea,fm as fa,hm as ga,Hs as ha,Vb as ia,Zb as ja,Rm as ka,xc as la,_n as ma,tx as na,Pn as oa,En as pa,Rc as qa,$t as ra,_c as sa,dx as ta,cx as ua,ux as va,lx as wa,gx as xa,px as ya,mx as za,rf as Aa,Wc as Ba,nt as Ca,su as Da,rr as Ea,Mx as Fa,Rx as Ga,_x as Ha,Ex as Ia,yh as Ja,wh as Ka,h0 as La,y0 as Ma,bh as Na,Th as Oa,vh as Pa,Ah as Qa,Mh as Ra,ir as Sa,pu as Ta,mu as Ua,Rh as Va,fu as Wa,hu as Xa,Eh as Ya};
204
- //# sourceMappingURL=chunk-4H5B42VW.js.map
204
+ //# sourceMappingURL=chunk-XDSYUBEP.js.map
@@ -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
  ${l}`,is_error:!0}:{tool_use_id:e.id,content:l||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,r=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:r,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 ne.readFile(r,"utf8"),l=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),l.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):l.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await ne.writeFile(r,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:r,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
50
50
  ${l.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||""),r=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-PA45HSJ4.js"),l=i();if(!l)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(l).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:r*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||""),r=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-S5TXGCQH.js"),l=i();if(!l)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(l).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:r*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,r=t;return o?.length&&(r+=`
54
54
  Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:r}}};async function Oe(n){let{provider:e,systemPrompt:t,messages:o,providerOptions:r,cwd:s,maxIterations:i=20,enabledTools:l,interactive:a=!0,overwrite:p=!1,dryRun:c=!1,onProgress:d,abortSignal:u}=n,m=u?{...r,abortSignal:u}:r;if(!e.generateRaw)return mt(n);let I=new se(s,{interactive:a,overwrite:p,dryRun:c,acmeContext:n.acmeContext,abortSignal:u}),D=be(l);if(n.acmeContext)for(let g of ct)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(n.mcpTools?.length)for(let g of n.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,O=0,A="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),k.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let S=null,H=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"?S=x.result:x.type==="error"&&(H=x.error);if(H&&!S)throw new Error(H);if(!S)throw new Error("generateRawStream returned no raw_result event");g=S,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(S){if(S.message?.includes("not available"))return mt(n);throw S}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,O+=g.usage.output_tokens;let P=g._streamedText;for(let S of g.content)S.type==="text"&&(A+=S.text,P===void 0&&d?.({type:"text_delta",text:S.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 S=g.content.filter(v=>v.type==="tool_use");if(S.length===0)break;C.push({role:"assistant",content:g.content});let H=[];for(let v of S){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),k.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&n.mcpDispatch){let h=await n.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),H.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:H}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:A,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:O||void 0,iterations:_}}async function mt(n){let{provider:e,systemPrompt:t,messages:o,providerOptions:r,maxIterations:s=5}=n,l=[{role:"system",content:t+`
@@ -123,4 +123,4 @@ ${n.projectInstructions}`),n.memoryContext&&o.push(n.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{We as a,Xt as b,Qt as c,Je as d,Ke as e,Xe as f,Qe as g,Pe as h,ee as i,Re as j,ce as k,te as l,Pt as m,oe as n,Et as o,f as p,ot as q,rt as r,Me as s,de as t,W as u,re as v,lt as w,Ee as x,$e as y,se as z,gt as A,tn as B,on as C};
126
- //# sourceMappingURL=chunk-LACHXOBO.js.map
126
+ //# sourceMappingURL=chunk-ZQN2UETA.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-W6CGC2EO.js"),{installCliSignalExit:r}=await import("./signal-exit-C5EUGHKI.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-QUIOI4AU.js"),{installCliSignalExit:r}=await import("./signal-exit-C5EUGHKI.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.js CHANGED
@@ -1,4 +1,4 @@
1
- import{Oa as Tt,Pa 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-ZFMUF3NU.js";import"./chunk-LLVVT5OB.js";import"./chunk-GTJIKXDB.js";import"./chunk-2TVJTWFC.js";import"./chunk-BDHWTWD7.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-MRIVENBY.js";import"./chunk-KQ3LPQ2Z.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-UBONPGNT.js";import"./chunk-UKUH662W.js";import"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import"./chunk-JWDJMFU6.js";import"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-A24QXLEG.js";import"./chunk-A5GYG56I.js";import"./chunk-7K7ZQU3C.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-RX5O5637.js";import"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import"./chunk-EYVPRIO3.js";import"./chunk-LTOSEP7C.js";import"./chunk-QPABR72X.js";import"./chunk-QU7ICYFR.js";import"./chunk-IFUAP7UD.js";import"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{Xa as yt,r as lt,s as ct,t as dt,u as mt,v as pt}from"./chunk-4H5B42VW.js";import"./chunk-TA437DWX.js";import"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.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-LACHXOBO.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import"./chunk-EFXZACH4.js";import"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-7YOLZGB5.js";import"./chunk-IH65GDJR.js";import{x as ut}from"./chunk-CF2R6BOX.js";import"./chunk-Q6TGKWZE.js";import"./chunk-3UOTLMXD.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-HVMUYEQP.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-FG2FPOML.js";import"./chunk-VWTBHLMX.js";import"./chunk-LGYIHB73.js";import"./chunk-JTFCU5LH.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-MYVHVJWZ.js";import"./chunk-74MHOALB.js";import"./chunk-3323WFVK.js";import"./chunk-4NZ4T3TQ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-Z5CMA4JN.js";import"./chunk-MM7U4PWY.js";import{a as ht}from"./chunk-6ECXITK2.js";import{f as gt,g as ft}from"./chunk-2XQMUSGM.js";import"./chunk-WPNRDEHW.js";import"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QZ24XACR.js";import{j as it,k as rt,l as at}from"./chunk-BTLADRMY.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import"./chunk-BYEL7KKR.js";import"./chunk-QUFIUXMQ.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{Dc as nt,rc as tt,tc as st,wc as ot}from"./chunk-FWNP27H4.js";import"./chunk-KEUW6YLL.js";import"./chunk-N47Y5ADQ.js";import"./chunk-VQRY4IDI.js";import"./chunk-YSCT6DPR.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{Oa as Tt,Pa 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-HRCK6K36.js";import"./chunk-SPVGDMR7.js";import"./chunk-GTJIKXDB.js";import"./chunk-2TVJTWFC.js";import"./chunk-BDHWTWD7.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-MRIVENBY.js";import"./chunk-KQ3LPQ2Z.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-UBONPGNT.js";import"./chunk-UKUH662W.js";import"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import"./chunk-JWDJMFU6.js";import"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-A24QXLEG.js";import"./chunk-A5GYG56I.js";import"./chunk-7K7ZQU3C.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-RX5O5637.js";import"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import"./chunk-EYVPRIO3.js";import"./chunk-LTOSEP7C.js";import"./chunk-QPABR72X.js";import"./chunk-QU7ICYFR.js";import"./chunk-IFUAP7UD.js";import"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{Xa as yt,r as lt,s as ct,t as dt,u as mt,v as pt}from"./chunk-XDSYUBEP.js";import"./chunk-WXV3KLNI.js";import"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.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-ZQN2UETA.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import"./chunk-EFXZACH4.js";import"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-7YOLZGB5.js";import"./chunk-IH65GDJR.js";import{x as ut}from"./chunk-CF2R6BOX.js";import"./chunk-Q6TGKWZE.js";import"./chunk-3UOTLMXD.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-HVMUYEQP.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-FG2FPOML.js";import"./chunk-VWTBHLMX.js";import"./chunk-LGYIHB73.js";import"./chunk-JTFCU5LH.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-MYVHVJWZ.js";import"./chunk-74MHOALB.js";import"./chunk-3323WFVK.js";import"./chunk-4NZ4T3TQ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-Z5CMA4JN.js";import"./chunk-MM7U4PWY.js";import{a as ht}from"./chunk-6ECXITK2.js";import{f as gt,g as ft}from"./chunk-2XQMUSGM.js";import"./chunk-WPNRDEHW.js";import"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QZ24XACR.js";import{j as it,k as rt,l as at}from"./chunk-BTLADRMY.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import"./chunk-BYEL7KKR.js";import"./chunk-QUFIUXMQ.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{Dc as nt,rc as tt,tc as st,wc as ot}from"./chunk-FWNP27H4.js";import"./chunk-KEUW6YLL.js";import"./chunk-N47Y5ADQ.js";import"./chunk-VQRY4IDI.js";import"./chunk-YSCT6DPR.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 Uy,b as ka,g as Wy}from"./chunk-DG56PTYL.js";import{n as rd}from"./chunk-GMAORBGM.js";import{a as qy,b as Fy}from"./chunk-ZUZYJQJ4.js";import{b as Ly}from"./chunk-XV3QPZWH.js";import{a as Dy,b as Py,d as Ur,e as My}from"./chunk-I32TCCAK.js";import{d as sy,e as td,h as ry,i as iy}from"./chunk-6UI7GJSB.js";import{$ as yy,A as ny,B as ay,C as ly,E as cy,G as dy,H as uy,I as od,J as gy,U as my,V as py,W as nd,X as fy,_ as hy,aa as wy,ba as by,ca as xy,da as Sy,ea as Ey,fa as Ay,g as Jh,ga as Ry,h as Hh,ha as Ty,ja as sd,ka as Cy,l as Gh,la as Oy,m as zh,na as Iy,o as Fs,p as Us,q as Yh,qa as Ny,r as Kh,ra as jy,s as Xh,sa as _y,t as Vh,u as Qh,v as Zh,x as Xt,z as oy}from"./chunk-ATZRBMUZ.js";import"./chunk-EFGAPAYZ.js";import{a as $y,c as ky,d as vy}from"./chunk-FFOGEFPT.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{b as Mo}from"./chunk-7NQQIDDI.js";import{a as ey,c as ty}from"./chunk-D6LX27PO.js";import"./chunk-WMZ4TGMR.js";import"./chunk-2YDG5CSS.js";import{a as Zc}from"./chunk-LNY6N73E.js";import{b as Yp}from"./chunk-FGHJDZDB.js";import{a as Wp,b as Ic}from"./chunk-GMP2IB4E.js";import{a as Ac,b as xp}from"./chunk-VNXYQH45.js";import{$ as mh,A as Lc,Aa as qr,B as qf,Ba as Mh,C as qc,Ca as ht,D as Ff,Da as ya,E as Uf,Ea as wa,F as Wf,Fa as Fr,G as Bf,Ga as Xc,H as Jf,Ha as Lh,I as Gf,Ia as Fh,J as Fc,Ja as Qc,K as zf,Ka as Wh,L as da,La as ba,M as Yf,Ma as qs,N as Uc,Na as $a,O as Xf,Oa as ed,P as Vf,Pa as Bh,Q as Qf,R as Zf,S as eh,T as ua,U as rh,V as lh,W as ch,X as dh,Y as uh,Z as gh,_ as Bc,a as Kp,aa as ph,b as Xp,ba as fh,ca as hh,da as yh,ea as wh,fa as bh,ga as $h,h as ea,ha as kh,i as Ds,ia as vh,j as ef,ja as Ch,k as Dr,ka as pa,l as ta,la as Po,m as of,ma as Qo,n as sf,na as Ps,o as $f,oa as fa,p as kf,pa as ha,q as aa,qa as Kc,r as Mc,ra as Oh,s as Tf,sa as Ih,t as jf,ta as Nh,u as _f,ua as jh,v as Df,va as _h,w as Pf,wa as Dh,x as ca,xa as Ms,y as Mf,ya as Ls,z as Lf,za as Ph}from"./chunk-ZFMUF3NU.js";import{$b as Vc,Cb as Rh,Db as Th,Eb as zc,Lb as Yc,M as Pr,N as Cf,Q as Of,R as la,_b as qh,bb as Mr,eb as Jc,fb as ga,gb as xh,ia as Hf,ja as Kf,nb as Vo,nc as fo,ob as Sh,pb as Hc,pc as Uh,qa as th,ra as oh,rb as Gc,sa as nh,t as nf,ta as Wc,tb as Eh,ub as Ah,vb as Lr,wa as sh,zb as ma}from"./chunk-LLVVT5OB.js";import"./chunk-GTJIKXDB.js";import{a as Vp,c as _c,d as _r,f as Qp,g as Zp}from"./chunk-2TVJTWFC.js";import{A as oa,B as na,C as af,D as lf,E as cf,G as df,H as uf,I as gf,J as mf,K as pf,L as ff,M as hf,N as yf,S as sa,T as wf,U as bf,Y as If,Z as Nf,i as Sc,j as yp,m as wp,n as bp,w as rf}from"./chunk-BDHWTWD7.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-MRIVENBY.js";import"./chunk-KQ3LPQ2Z.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as ih,b as ah}from"./chunk-EKJG63EJ.js";import"./chunk-UBONPGNT.js";import{b as Ft}from"./chunk-UKUH662W.js";import{c as vf}from"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import"./chunk-JWDJMFU6.js";import{c as Pc}from"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import{c as xf,e as ra,g as ia}from"./chunk-LQE73AZR.js";import{a as Sf,b as Ef,c as Af,d as Rf}from"./chunk-2D3RYIDU.js";import{a as Ut}from"./chunk-A24QXLEG.js";import"./chunk-A5GYG56I.js";import{a as Dc,p as tf}from"./chunk-7K7ZQU3C.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{a as Ip,b as Np,c as jp,d as _p,e as Tc,f as Dp,g as Cc,h as Oc,l as Pp,m as Mp}from"./chunk-RX5O5637.js";import{f as Lp,i as qp,l as Fp,m as Up}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{n as Bp,o as Jp,p as Nc,q as Zi,r as Hp,s as Gp}from"./chunk-EYVPRIO3.js";import{b as jc,d as zp}from"./chunk-LTOSEP7C.js";import{a as Ec,d as $p,e as Qi}from"./chunk-QPABR72X.js";import{a as jr,e as Sp,f as Ep,g as Rc,i as Ap,j as Rp,l as Tp,m as Cp,n as Op}from"./chunk-QU7ICYFR.js";import{b as _s,e as vp}from"./chunk-IFUAP7UD.js";import{c as kp}from"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{O as bc,P as Vm,Xa as hp,ba as Xo,ha as gp,l as Um,oa as pp,pa as fp,w as Wm,x as Bm,y as Jm}from"./chunk-4H5B42VW.js";import{Da as mp,I as Cs,J as Xi,K as Vi,L as Os,M as Zm,N as Yo,P as Ko,b as Ts,ha as dp,r as jo,s as $c,t as Qm,u as kc,w as _o,wa as up,x as Ki}from"./chunk-TA437DWX.js";import{b as Tn}from"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import"./chunk-LACHXOBO.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{c as tp}from"./chunk-EFXZACH4.js";import{f as op,g as np,h as vc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-7YOLZGB5.js";import{e as rp,f as Do,k as Ns}from"./chunk-IH65GDJR.js";import{d as Km,o as sp,r as cp}from"./chunk-CF2R6BOX.js";import{a as Fe,b as pe,c as Ge,d as js,e as ip}from"./chunk-Q6TGKWZE.js";import{a as ap,b as xc,h as lp}from"./chunk-3UOTLMXD.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Xm}from"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-HVMUYEQP.js";import{a as Is}from"./chunk-GV7S5BAX.js";import{e as ep}from"./chunk-GSX4NK2N.js";import"./chunk-FG2FPOML.js";import"./chunk-VWTBHLMX.js";import"./chunk-LGYIHB73.js";import"./chunk-JTFCU5LH.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import{i as Gm,j as zm}from"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import{a as wc,b as Ym}from"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-MYVHVJWZ.js";import{n as hc,p as qm,w as Fm}from"./chunk-74MHOALB.js";import{e as _m,f as Rn,g as Dm,h as Rs,k as Pm,l as Mm,n as Lm,o as fc,s as Gi,t as jt,u as zi}from"./chunk-3323WFVK.js";import{a as po}from"./chunk-4NZ4T3TQ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-Z5CMA4JN.js";import{b as yc}from"./chunk-MM7U4PWY.js";import"./chunk-6ECXITK2.js";import{g as zo,i as Yi}from"./chunk-2XQMUSGM.js";import"./chunk-WPNRDEHW.js";import{c as Hm}from"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QZ24XACR.js";import{a as rc,b as Gg,c as xS,d as Di,e as zg,f as Am,g as DS,h as Rm,i as PS,m as As,n as Cm,q as Om,u as Im,y as mo,z as Nr}from"./chunk-BTLADRMY.js";import{a as No,b as Es,e as xm,f as Ir}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as Hi,b as Tm}from"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import{a as jm}from"./chunk-BYEL7KKR.js";import{h as Go,j as Nm}from"./chunk-QUFIUXMQ.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as go,b as vS}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as im,Ab as IS,Ca as dm,Da as um,Dc as Z,Ea as cc,I as qi,J as om,Jb as bm,Kb as En,M as qt,Mb as uc,N as ac,Oa as Ui,P as nm,Pa as Wi,Q as Fi,S as RS,Sa as gm,Tb as gc,Ua as mm,Ub as mc,Va as Ss,Wa as dc,Wb as $m,Xa as pm,Xb as NS,_ as rm,aa as am,b as ic,bc as vm,c as Yg,ca as lm,d as Pi,da as cm,e as Kg,ea as CS,eb as fm,f as Xg,gb as hm,h as Vg,hb as ym,i as Mi,j as Qg,l as SS,na as lc,nc as pc,oa as OS,q as Zg,r as ES,rc as Bi,sc as An,t as em,tc as O,w as AS,wb as wm,wc as Ji,x as Li,y as tm,ya as xs,za as Or}from"./chunk-FWNP27H4.js";import"./chunk-KEUW6YLL.js";import{j as He,r as Io}from"./chunk-N47Y5ADQ.js";import{a as sm,e as TS}from"./chunk-VQRY4IDI.js";import{a as km,c as jS}from"./chunk-YSCT6DPR.js";import{g as Sm,k as Em,l as _S}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as MS}from"commander";var By=new MS().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 Xp({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()});Z();import{Command as LS}from"commander";import{execFileSync as ho}from"node:child_process";import{cpSync as Jy,existsSync as ld,mkdirSync as id,mkdtempSync as qS,readdirSync as FS,rmSync as Hy,writeFileSync as Gy}from"node:fs";import{dirname as zy,join as yt}from"node:path";import{homedir as va,release as US,tmpdir as WS}from"node:os";import{setTimeout as BS}from"node:timers/promises";function xa(){let e=af(process.platform,process.arch,US());if(e)throw new Error(e)}function Sa(){let e=yt(va(),"Library/LaunchAgents"),t=[];try{t=FS(e).filter(df)}catch{}let o=t.flatMap(n=>{let s=yt(e,n);try{return[{file:s,plist:ho("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return uf(e,o)}function Wr(e){return`gui/${process.getuid()}/${e.label}`}async function ad(e){try{ho("launchctl",["bootout",Wr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{ho("launchctl",["print",Wr(e)],{stdio:"pipe"})}catch{return}await BS(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Yy(e){if(!ld(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{ho("launchctl",["print",Wr(e)],{stdio:"pipe"})}catch{t=!1}t||ho("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),ho("launchctl",["kickstart",Wr(e)],{stdio:"pipe"})}function JS(){let e=yf();if(e&&ld(yt(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 LS("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=>{xa();let t=O(),o=lf(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=JS(),i=yt(va(),"Applications"),{keep:a,remove:l}=Sa();if(console.log(`Desktop assistant \u2192 ${yt(i,oa)}
1
+ import{a as Uy,b as ka,g as Wy}from"./chunk-DG56PTYL.js";import{n as rd}from"./chunk-GMAORBGM.js";import{a as qy,b as Fy}from"./chunk-ZUZYJQJ4.js";import{b as Ly}from"./chunk-XV3QPZWH.js";import{a as Dy,b as Py,d as Ur,e as My}from"./chunk-I32TCCAK.js";import{d as sy,e as td,h as ry,i as iy}from"./chunk-6UI7GJSB.js";import{$ as yy,A as ny,B as ay,C as ly,E as cy,G as dy,H as uy,I as od,J as gy,U as my,V as py,W as nd,X as fy,_ as hy,aa as wy,ba as by,ca as xy,da as Sy,ea as Ey,fa as Ay,g as Jh,ga as Ry,h as Hh,ha as Ty,ja as sd,ka as Cy,l as Gh,la as Oy,m as zh,na as Iy,o as Fs,p as Us,q as Yh,qa as Ny,r as Kh,ra as jy,s as Xh,sa as _y,t as Vh,u as Qh,v as Zh,x as Xt,z as oy}from"./chunk-3IL57455.js";import"./chunk-EFGAPAYZ.js";import{a as $y,c as ky,d as vy}from"./chunk-FFOGEFPT.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{b as Mo}from"./chunk-7NQQIDDI.js";import{a as ey,c as ty}from"./chunk-D6LX27PO.js";import"./chunk-WMZ4TGMR.js";import"./chunk-2YDG5CSS.js";import{a as Zc}from"./chunk-LNY6N73E.js";import{b as Yp}from"./chunk-FGHJDZDB.js";import{a as Wp,b as Ic}from"./chunk-GMP2IB4E.js";import{a as Ac,b as xp}from"./chunk-VNXYQH45.js";import{$ as mh,A as Lc,Aa as qr,B as qf,Ba as Mh,C as qc,Ca as ht,D as Ff,Da as ya,E as Uf,Ea as wa,F as Wf,Fa as Fr,G as Bf,Ga as Xc,H as Jf,Ha as Lh,I as Gf,Ia as Fh,J as Fc,Ja as Qc,K as zf,Ka as Wh,L as da,La as ba,M as Yf,Ma as qs,N as Uc,Na as $a,O as Xf,Oa as ed,P as Vf,Pa as Bh,Q as Qf,R as Zf,S as eh,T as ua,U as rh,V as lh,W as ch,X as dh,Y as uh,Z as gh,_ as Bc,a as Kp,aa as ph,b as Xp,ba as fh,ca as hh,da as yh,ea as wh,fa as bh,ga as $h,h as ea,ha as kh,i as Ds,ia as vh,j as ef,ja as Ch,k as Dr,ka as pa,l as ta,la as Po,m as of,ma as Qo,n as sf,na as Ps,o as $f,oa as fa,p as kf,pa as ha,q as aa,qa as Kc,r as Mc,ra as Oh,s as Tf,sa as Ih,t as jf,ta as Nh,u as _f,ua as jh,v as Df,va as _h,w as Pf,wa as Dh,x as ca,xa as Ms,y as Mf,ya as Ls,z as Lf,za as Ph}from"./chunk-HRCK6K36.js";import{$b as Vc,Cb as Rh,Db as Th,Eb as zc,Lb as Yc,M as Pr,N as Cf,Q as Of,R as la,_b as qh,bb as Mr,eb as Jc,fb as ga,gb as xh,ia as Hf,ja as Kf,nb as Vo,nc as fo,ob as Sh,pb as Hc,pc as Uh,qa as th,ra as oh,rb as Gc,sa as nh,t as nf,ta as Wc,tb as Eh,ub as Ah,vb as Lr,wa as sh,zb as ma}from"./chunk-SPVGDMR7.js";import"./chunk-GTJIKXDB.js";import{a as Vp,c as _c,d as _r,f as Qp,g as Zp}from"./chunk-2TVJTWFC.js";import{A as oa,B as na,C as af,D as lf,E as cf,G as df,H as uf,I as gf,J as mf,K as pf,L as ff,M as hf,N as yf,S as sa,T as wf,U as bf,Y as If,Z as Nf,i as Sc,j as yp,m as wp,n as bp,w as rf}from"./chunk-BDHWTWD7.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-MRIVENBY.js";import"./chunk-KQ3LPQ2Z.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as ih,b as ah}from"./chunk-EKJG63EJ.js";import"./chunk-UBONPGNT.js";import{b as Ft}from"./chunk-UKUH662W.js";import{c as vf}from"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import"./chunk-JWDJMFU6.js";import{c as Pc}from"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import{c as xf,e as ra,g as ia}from"./chunk-LQE73AZR.js";import{a as Sf,b as Ef,c as Af,d as Rf}from"./chunk-2D3RYIDU.js";import{a as Ut}from"./chunk-A24QXLEG.js";import"./chunk-A5GYG56I.js";import{a as Dc,p as tf}from"./chunk-7K7ZQU3C.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{a as Ip,b as Np,c as jp,d as _p,e as Tc,f as Dp,g as Cc,h as Oc,l as Pp,m as Mp}from"./chunk-RX5O5637.js";import{f as Lp,i as qp,l as Fp,m as Up}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{n as Bp,o as Jp,p as Nc,q as Zi,r as Hp,s as Gp}from"./chunk-EYVPRIO3.js";import{b as jc,d as zp}from"./chunk-LTOSEP7C.js";import{a as Ec,d as $p,e as Qi}from"./chunk-QPABR72X.js";import{a as jr,e as Sp,f as Ep,g as Rc,i as Ap,j as Rp,l as Tp,m as Cp,n as Op}from"./chunk-QU7ICYFR.js";import{b as _s,e as vp}from"./chunk-IFUAP7UD.js";import{c as kp}from"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{O as bc,P as Vm,Xa as hp,ba as Xo,ha as gp,l as Um,oa as pp,pa as fp,w as Wm,x as Bm,y as Jm}from"./chunk-XDSYUBEP.js";import{Da as mp,I as Cs,J as Xi,K as Vi,L as Os,M as Zm,N as Yo,P as Ko,b as Ts,ha as dp,r as jo,s as $c,t as Qm,u as kc,w as _o,wa as up,x as Ki}from"./chunk-WXV3KLNI.js";import{b as Tn}from"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import"./chunk-ZQN2UETA.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{c as tp}from"./chunk-EFXZACH4.js";import{f as op,g as np,h as vc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-7YOLZGB5.js";import{e as rp,f as Do,k as Ns}from"./chunk-IH65GDJR.js";import{d as Km,o as sp,r as cp}from"./chunk-CF2R6BOX.js";import{a as Fe,b as pe,c as Ge,d as js,e as ip}from"./chunk-Q6TGKWZE.js";import{a as ap,b as xc,h as lp}from"./chunk-3UOTLMXD.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Xm}from"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-HVMUYEQP.js";import{a as Is}from"./chunk-GV7S5BAX.js";import{e as ep}from"./chunk-GSX4NK2N.js";import"./chunk-FG2FPOML.js";import"./chunk-VWTBHLMX.js";import"./chunk-LGYIHB73.js";import"./chunk-JTFCU5LH.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import{i as Gm,j as zm}from"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import{a as wc,b as Ym}from"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-MYVHVJWZ.js";import{n as hc,p as qm,w as Fm}from"./chunk-74MHOALB.js";import{e as _m,f as Rn,g as Dm,h as Rs,k as Pm,l as Mm,n as Lm,o as fc,s as Gi,t as jt,u as zi}from"./chunk-3323WFVK.js";import{a as po}from"./chunk-4NZ4T3TQ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-Z5CMA4JN.js";import{b as yc}from"./chunk-MM7U4PWY.js";import"./chunk-6ECXITK2.js";import{g as zo,i as Yi}from"./chunk-2XQMUSGM.js";import"./chunk-WPNRDEHW.js";import{c as Hm}from"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QZ24XACR.js";import{a as rc,b as Gg,c as xS,d as Di,e as zg,f as Am,g as DS,h as Rm,i as PS,m as As,n as Cm,q as Om,u as Im,y as mo,z as Nr}from"./chunk-BTLADRMY.js";import{a as No,b as Es,e as xm,f as Ir}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as Hi,b as Tm}from"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import{a as jm}from"./chunk-BYEL7KKR.js";import{h as Go,j as Nm}from"./chunk-QUFIUXMQ.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as go,b as vS}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as im,Ab as IS,Ca as dm,Da as um,Dc as Z,Ea as cc,I as qi,J as om,Jb as bm,Kb as En,M as qt,Mb as uc,N as ac,Oa as Ui,P as nm,Pa as Wi,Q as Fi,S as RS,Sa as gm,Tb as gc,Ua as mm,Ub as mc,Va as Ss,Wa as dc,Wb as $m,Xa as pm,Xb as NS,_ as rm,aa as am,b as ic,bc as vm,c as Yg,ca as lm,d as Pi,da as cm,e as Kg,ea as CS,eb as fm,f as Xg,gb as hm,h as Vg,hb as ym,i as Mi,j as Qg,l as SS,na as lc,nc as pc,oa as OS,q as Zg,r as ES,rc as Bi,sc as An,t as em,tc as O,w as AS,wb as wm,wc as Ji,x as Li,y as tm,ya as xs,za as Or}from"./chunk-FWNP27H4.js";import"./chunk-KEUW6YLL.js";import{j as He,r as Io}from"./chunk-N47Y5ADQ.js";import{a as sm,e as TS}from"./chunk-VQRY4IDI.js";import{a as km,c as jS}from"./chunk-YSCT6DPR.js";import{g as Sm,k as Em,l as _S}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as MS}from"commander";var By=new MS().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 Xp({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()});Z();import{Command as LS}from"commander";import{execFileSync as ho}from"node:child_process";import{cpSync as Jy,existsSync as ld,mkdirSync as id,mkdtempSync as qS,readdirSync as FS,rmSync as Hy,writeFileSync as Gy}from"node:fs";import{dirname as zy,join as yt}from"node:path";import{homedir as va,release as US,tmpdir as WS}from"node:os";import{setTimeout as BS}from"node:timers/promises";function xa(){let e=af(process.platform,process.arch,US());if(e)throw new Error(e)}function Sa(){let e=yt(va(),"Library/LaunchAgents"),t=[];try{t=FS(e).filter(df)}catch{}let o=t.flatMap(n=>{let s=yt(e,n);try{return[{file:s,plist:ho("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return uf(e,o)}function Wr(e){return`gui/${process.getuid()}/${e.label}`}async function ad(e){try{ho("launchctl",["bootout",Wr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{ho("launchctl",["print",Wr(e)],{stdio:"pipe"})}catch{return}await BS(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Yy(e){if(!ld(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{ho("launchctl",["print",Wr(e)],{stdio:"pipe"})}catch{t=!1}t||ho("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),ho("launchctl",["kickstart",Wr(e)],{stdio:"pipe"})}function JS(){let e=yf();if(e&&ld(yt(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 LS("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=>{xa();let t=O(),o=lf(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=JS(),i=yt(va(),"Applications"),{keep:a,remove:l}=Sa();if(console.log(`Desktop assistant \u2192 ${yt(i,oa)}
2
2
  Computer-use helper \u2192 ${yt(i,na)}
3
3
  Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
4
4
  Daemon \u2192 ${s}
@@ -608,7 +608,7 @@ ${oe.text}`));T.delivery.reached.of++,ie&&T.delivery.reached.n++;let j=P[0]??Q[0
608
608
  Plan ${q.dim(`[${r.state}] by ${r.createdBy}, ${rs(r.createdAt)}`)}`),Hv(s.steps(e)),console.log(`
609
609
  Log`);for(let i of s.events(e))console.log(q.dim(` ${rs(i.at)} ${i.step?`step ${i.step} `:""}${i.kind}: ${i.detail}`))}});Fo.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(l=>o[l]);if(n.length!==1){console.error(q.red(" give one of --retry, --skip or --done")),process.exitCode=1;return}let s=fr();if(!s)return;let r=Sl();if(!r){process.exitCode=1;return}let i=Number(t),a=Yf(s,r,{requestId:e,step:i,action:n[0],detail:o.note},Date.now());if(a){console.error(q.red(` ${a}`)),process.exitCode=1;return}console.log(q.green(` \u2713 step ${i} of ${e}: ${n[0]==="retry"?"handed over again":n[0]==="skip"?"skipped":"done"}`)+q.dim(" (the daemon goes on within a minute)")),Hv(r.steps(e))});function Gv(e,t,o,n){let s=Fo.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=fr();if(!a)return;let l=e==="done"?i.evidence??(i.reason?`closed by owner: ${i.reason}`:void 0):i.reason??"dropped by the owner";if(!l){console.error(q.red(` ${n}`)),process.exitCode=1;return}let c=a.get(r);if(!c||c.state==="candidate"){console.error(q.red(` no request "${r}"`)),process.exitCode=1;return}let u=process.env.AGENTX_AGENT_ID?.trim()||pm;if(!a.close(r,e==="done"?"done":"dropped",l,Date.now(),null,u)){console.error(q.red(` ${r} is already closed (${Gu[c.state]??c.state})`)),process.exitCode=1;return}console.log(q.green(` \u2713 ${r} ${e==="done"?"closed as done":"dropped"}`))})}Gv("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>");Gv("drop","drop a request you no longer want","--reason <text>","");Fo.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("--home-closes <on|off>","close a request once its issue or merge request home is merged or closed as completed").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 (${Ui.join(", ")}); "none" to turn them all off`).option("--check-every <minutes>","how often each open loop's check runs").option("--auto-resend <on|off>","send a request stopped by a usage limit or a restart back to its agent once, on its own").option("--resend-after <minutes>","minutes after it stopped before it is resent (a limit also waits for its reset)").option("--resend-hold-hours <n>","hours your notice waits for the resend before you are told anyway").option("--flow-zone <zone>","the time zone whose day the flow rate counts by, for example Africa/Tunis").action(async e=>{let t={};try{let u=(y,w)=>{if(w===void 0)return;let $=Number(w);if(!($>0))throw new Error(`${y} must be a positive number`);return $},d=(y,w)=>y===void 0?void 0:y===w?[]:y.split(",").map($=>$.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=d(e.from,"none"),t.channels=d(e.channels,"all"),t.staleAfterHours=u("--stale-hours",e.staleHours),t.retentionDays=u("--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 y=u("--catch-cap",e.catchCap);if(y!==void 0&&!Number.isInteger(y))throw new Error("--catch-cap must be a whole number");t.catchPromises={...e.catch!==void 0?{enabled:e.catch==="on"}:{},...y!==void 0?{dailyCap:y}:{}}}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"}if(e.homeCloses!==void 0){if(e.homeCloses!=="on"&&e.homeCloses!=="off")throw new Error("--home-closes takes on or off");t.homeCloses=e.homeCloses==="on"}let p={};if(e.plans!==void 0){if(e.plans!=="on"&&e.plans!=="off")throw new Error("--plans takes on or off");p.enabled=e.plans==="on"}if(p.stallMinutes=u("--stall-minutes",e.stallMinutes),e.maxNudges!==void 0){let y=Number(e.maxNudges);if(!Number.isInteger(y)||y<0)throw new Error("--max-nudges must be a whole number, 0 or more");p.maxNudges=y}if(p.approveKinds=d(e.approveKinds,"none"),p.disabledAgents=d(e.plansOffFor,"none"),p.requireForWork=d(e.planFor,"none"),e.planOver!==void 0){let y=Number(e.planOver);if(!(y>=0))throw new Error("--plan-over must be a number of minutes, 0 or more");p.requireOverMinutes=y}Object.values(p).some(y=>y!==void 0)&&(t.plans=p);let f={},g=d(e.checks,"none");if(g){let y=g.filter(w=>!Ui.includes(w));if(y.length)throw new Error(`unknown check ${y.join(", ")}: use ${Ui.join(", ")}`);f.enabled=g}f.checkEveryMinutes=u("--check-every",e.checkEvery),Object.values(f).some(y=>y!==void 0)&&(t.checkers=f);let h={};if(e.autoResend!==void 0){if(e.autoResend!=="on"&&e.autoResend!=="off")throw new Error("--auto-resend takes on or off");h.enabled=e.autoResend==="on"}if(e.resendAfter!==void 0){let y=Number(e.resendAfter);if(!(y>=0))throw new Error("--resend-after must be a number of minutes, 0 or more");h.afterMinutes=y}h.holdMaxHours=u("--resend-hold-hours",e.resendHoldHours),Object.values(h).some(y=>y!==void 0)&&(t.autoResend=h),e.flowZone!==void 0&&(t.flow={timeZone:e.flowZone})}catch(u){console.error(q.red(` ${u.message}`)),process.exitCode=1;return}if(Object.values(t).some(u=>u!==void 0)){let u=await Cf(t);if(!u.success){console.error(q.red(` ${u.error}`)),process.exitCode=1;return}console.log(q.green(" \u2713 saved")+(u.reloaded?q.dim(" (daemon reloaded)"):""))}let o=Pr();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"}`),console.log(` Home closed ${o.homeCloses===!1?"left open":"closes the request: merged, or closed as completed"}`);let s=o.plans??da;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??da.requireOverMinutes,i=s.requireForWork??da.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.autoResend??zf;console.log(` Resend once ${a.enabled?`on: after a usage limit resets or a restart, ${a.afterMinutes} minute(s) on; you are told after ${a.holdMaxHours} hour(s) or a second stop`:"off"}`),console.log(` Flow rate counts by ${(o.flow??Nc).timeZone} days`);let l=o.checkers??Wi;console.log(` Loop checks ${l.enabled.length?l.enabled.join(", "):"off"}, every ${l.checkEveryMinutes} minute(s)`);let c=Object.keys(l.repos);console.log(` Repos for git-ancestor ${c.length?c.join(", "):"none (requests.checkers.repos in agentx.json)"}`)});import{Command as NI}from"commander";import hr from"chalk";Z();var zv=new NI("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",nd.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(hr.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await pe(r=>{n=fy(r,e,t==="on")});s.success||(console.error(hr.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(hr.green(`\u2713 ${n}`)),s.reloaded&&console.log(hr.dim(" daemon hot-reloaded"))}let o=O().requestStatus.channels.map(n=>n.toLowerCase());for(let n of nd)console.log(` ${n.padEnd(8)} ${o.includes(n)?hr.green("on"):hr.dim("off")}`)});import{Command as aN}from"commander";import yr from"chalk";import Ee from"chalk";import wi from"prompts";import{readFileSync as jI,writeFileSync as _I,existsSync as DI}from"fs";import{resolve as Yv}from"path";var PI=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function MI(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Yu(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Kv(e=".env"){let t=Yv(e);if(!DI(t))return[];let o=jI(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(PI);r?n.push({kind:"kv",key:r[1],value:MI(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function LI(e){return e.map(t=>t.kind==="kv"?`${t.key}=${Yu(t.value)}`:t.raw).join(`
610
610
  `)+`
611
- `}function is(e,t,o=".env"){let n=Yv(o),s=Kv(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Yu(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Yu(t)}`})),_I(n,LI(s))}function Ku(e,t=".env"){return Kv(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Xv="https://t.me/BotFather";async function qI(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 FI(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 Vv(e={}){console.log(),console.log(Ee.bold(" Connect Telegram")),console.log(),console.log(Ee.dim(` 1. Open ${Xv}`)),console.log(Ee.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Ee.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await wi({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&Mo(Xv);let{token:o}=await wi({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:v=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(v.trim())||"That doesn't look like a Telegram token"});o||(console.log(Ee.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await qI(o.trim());n||(console.log(Ee.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Ee.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(Ee.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let l=JSON.parse(s(a,"utf-8")),c=Object.keys(l.agents||{});c.length===0&&(console.log(Ee.red(" No agents configured. Run: agentx agent add")),process.exit(1));let u=e.agent;u||(u=(await wi({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:c.map(x=>({title:x,value:x})),initial:0})).agent),u||(console.log(Ee.red(" Aborted")),process.exit(1));let d=l.channels?.telegram?.accounts||{},p=e.account||u;d[p]&&d[p].agentBinding!==u&&(p=(await wi({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${u}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(Ee.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;is(f,o.trim()),process.env[f]=o.trim();let g=await pe(v=>{Ge(v,"channels.telegram.enabled",!0),Ge(v,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:u});let x=js(v,`agents.${u}.mentions`)||[],k=`@${n.username}`;x.includes(k)||(x.push(k),Ge(v,`agents.${u}.mentions`,x))},{configPath:e.configPath});if(g.success||(console.log(Ee.red(` \u2717 ${g.error}`)),process.exit(1)),console.log(),console.log(Ee.green(` \u2713 Bot @${n.username} bound to agent "${u}"`)),console.log(Ee.dim(` Token stored in .env as ${f}`)),console.log(Ee.dim(` Mentions updated to include @${n.username}`)),g.reloaded?console.log(Ee.dim(" Daemon hot-reloaded.")):console.log(Ee.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await wi({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(Ee.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Ee.dim(" Waiting up to 90s..."));let y=await FI(o.trim(),9e4);if(!y){console.log(Ee.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Ee.dim(" agentx config set notifications.destination.channel telegram")),console.log(Ee.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Ee.dim(` agentx config set notifications.destination.accountId ${p}`));return}let w={channel:"telegram",chatId:String(y.chatId),accountId:p},$=[],S=await pe(v=>{Ge(v,"notifications.destination",w),$=Na(v,w)},{configPath:e.configPath});if(!S.success){console.log(Ee.red(` \u2717 failed to save destination: ${S.error}`));return}console.log(Ee.green(" \u2713 Default --notify target set")),console.log(Ee.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Ee.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(Ee.dim(` Schedules that now report here: ${$.join(", ")}`)),S.reloaded&&console.log(Ee.dim(" Daemon hot-reloaded."))}import qe from"chalk";import Xu from"prompts";import{existsSync as Qu,mkdirSync as UI,readdirSync as WI,readFileSync as Qv}from"fs";import{resolve as Vu}from"path";var BI=".agentx/whatsapp-sessions";function JI(){let e=Vu(process.cwd(),".agentx/daemon.pid");if(!Qu(e))return!1;try{let t=parseInt(Qv(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function HI(e){if(!Qu(e))return!1;try{return WI(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function GI(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(qe.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(qe.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;UI(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let l={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>l},c=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,l):r.keys},...a?{version:a}:{},logger:l,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return c.ev.on("creds.update",i),await new Promise(u=>{let p=setTimeout(()=>{t(qe.yellow(" Timed out waiting for scan (2min)."));try{c.end(void 0)}catch{}u(!1)},12e4);c.ev.on("connection.update",async f=>{if(f.qr){t(qe.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:g}=await import("qrcode-terminal");g.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(p),t(qe.green(" \u2713 Paired"));try{c.end(void 0)}catch{}u(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),t(qe.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function Zv(e={}){if(console.log(),console.log(qe.bold(" Connect WhatsApp")),console.log(),JI()){console.log(qe.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(qe.dim(" agentx daemon stop")),console.log();let{cont:c}=await Xu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});c||(console.log(qe.red(" Aborted")),process.exit(1))}let t=e.configPath||Vu(process.cwd(),"agentx.json");Qu(t)||(console.log(qe.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Qv(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||BI,s=Vu(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(qe.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Xu({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(u=>({title:u,value:u})),initial:0})).agent),i||(console.log(qe.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(HI(s)&&a){let{keep:c}=await Xu({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!c,c&&console.log(qe.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await GI(s,u=>console.log(u))||(console.log(qe.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let l=await pe(c=>{Ge(c,"channels.whatsapp.enabled",!0),Ge(c,"channels.whatsapp.sessionDir",n),Ge(c,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});l.success||(console.log(qe.red(` \u2717 ${l.error}`)),process.exit(1)),console.log(),console.log(qe.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(qe.dim(` Session: ${n}`)),console.log(qe.dim(" Start the daemon to begin receiving:")),console.log(qe.dim(" agentx daemon start")),console.log(qe.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(qe.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(qe.dim(" Add routes later with:")),console.log(qe.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import Ot from"chalk";import zI from"prompts";import{existsSync as YI,readFileSync as KI}from"fs";import{resolve as XI}from"path";async function VI(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 QI(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 Uo(e){console.log(Ot.red(` ${e}`)),process.exit(1)}async function as(e){return(await zI(e,{onCancel:()=>Uo("Aborted")}))[e.name]}async function ex(e={}){console.log(),console.log(Ot.bold(" Connect email")),console.log();let t=e.configPath||XI(process.cwd(),"agentx.json");YI(t)||Uo(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(KI(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Uo("No agents configured. Run: agentx agent add");let s=e.agent??await as({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(w=>({title:w,value:w}))});o.agents?.[s]||Uo(`No agent "${s}" in ${t}`);let r=(e.address??await as({type:"text",name:"address",message:"Email address customers write to:",validate:w=>/^\S+@\S+\.\S+$/.test(w.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=yy(r),l=e.imapHost??a?.imapHost??await as({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),c=Number(e.imapPort??a?.imapPort??await as({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await as({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await as({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(c)||!Number.isInteger(d))&&Uo("Ports must be numbers.");let p=e.passwordEnv||by(i),f=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!f&&Uo(`${e.passwordEnv} is not set in the environment.`),f||(a?.imapHost==="imap.gmail.com"&&(console.log(Ot.dim(` Gmail needs an app password, not your account password: ${hy}`)),console.log(Ot.dim(" (2-step verification must be on for that page to show.)"))),f=(await as({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),f||Uo("Aborted");let g={agent:s,address:r,imapHost:l,imapPort:c,smtpHost:u,smtpPort:d,user:e.user,passwordEnv:p,allowFrom:e.allowFrom?.length?e.allowFrom:["*"],send:e.auto?"auto":"approve"};if(!e.skipCheck){process.stdout.write(" Logging in to IMAP and SMTP... ");let w=await VI(g,f);w&&(console.log(Ot.red("\u2717")),Uo(w)),console.log(Ot.green("\u2713"))}e.passwordEnv||(is(p,f),process.env[p]=f);let h=await pe(w=>{Ge(w,"channels.email.enabled",!0),Ge(w,`channels.email.accounts.${i}`,wy(g))},{configPath:e.configPath});h.success||Uo(`Config save failed: ${h.error}`),console.log(),console.log(Ot.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Ot.dim(` Password stored in .env as ${p}`)),console.log(Ot.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let y=QI(o.agents[s]?.tier,g.allowFrom);y&&console.log(Ot.yellow(` ${y}`)),console.log(g.send==="auto"?Ot.yellow(" Replies are sent as soon as the agent writes them."):Ot.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(Ot.dim(" Only mail that arrives from now on is answered.")),console.log(Ot.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as ZI}from"crypto";import Ze from"chalk";import tx from"prompts";var El="agentx-mesh:",Al="//join/";function eN(e){return Buffer.from(e,"utf-8").toString("base64url")}function tN(e){return Buffer.from(e,"base64url").toString("utf-8")}function oN(e){return`${El}${Al}${eN(JSON.stringify(e))}`}function nN(e){if(!e.startsWith(`${El}${Al}`))throw new Error(`Not a mesh invite link \u2014 expected ${El}${Al}\u2026`);let t=e.slice(El.length+Al.length),o=JSON.parse(tN(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 sN(){return ZI(32).toString("hex")}function rN(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function iN(e){return e?.node?.name||e?.node?.id||"node"}async function ox(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=Ku("MESH_TOKEN");i||(i=sN(),is("MESH_TOKEN",i),console.log(Ze.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||rN(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await tx({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:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});d||(console.log(Ze.red(" Aborted")),process.exit(1)),a=d}let c=await pe(d=>{Ge(d,"mesh.enabled",!0)},{configPath:e.configPath});c.success||(console.log(Ze.red(` \u2717 ${c.error}`)),process.exit(1));let u=oN({url:a,token:i,name:iN(r),version:1});console.log(),console.log(Ze.bold(" Mesh invite")),console.log(),console.log(` ${Ze.cyan(u)}`),console.log(),console.log(Ze.dim(" Run on the other node:")),console.log(Ze.dim(` agentx connect mesh join "${u}"`)),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 nx(e,t={}){let o;try{o=nN(e)}catch(r){console.log(Ze.red(` \u2717 ${r.message}`)),process.exit(1)}let n=Ku("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await tx({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))}is("MESH_TOKEN",o.token);let s=await pe(r=>{Ge(r,"mesh.enabled",!0);let i=js(r,"mesh.peers")||[],a=i.findIndex(c=>c.name===o.name),l={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=l:i.push(l),Ge(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 ls=new aN().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");ls.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 Vv({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});ls.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 Zv({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});ls.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 ex({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 sx=ls.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");sx.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 ox({url:e.url,configPath:e.config})});sx.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 nx(e,{configPath:t.config})});ls.action(()=>{console.log(),console.log(yr.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${yr.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${yr.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${yr.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${yr.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(yr.dim(" GitLab connect is the next slice.")),console.log()});Z();import{Command as lN}from"commander";import ce from"chalk";var cs=new lN().name("usage").description("token usage analysis and reporting");cs.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=O(),[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(ce.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ce.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${ce.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: ${ce.red(String(s.totalErrors))}`),console.log(),console.log(ce.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,l)=>l[1].total-a[1].total);for(let[a,l]of i){let c=r(l.total||l.input+l.output+l.cacheRead+l.cacheCreate),u=l.avgDuration?`${(l.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ce.cyan(a)}: ${c} tokens (${l.tasks} tasks) ${ce.dim(u)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${e.message}`))}});cs.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=O(),[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(p=>a(p.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:ce.dim(" No hold to lift.")),console.log();return}let l=i.now,c=new Set(i.holds.map(d=>d.window));console.log(ce.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(ce.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 p=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",g=Math.max(1,Math.round((d.resetsAt-l)/6e4)),h=d.resetsAt>l?g<60?`resets in ${g} min`:g<48*60?`resets in ${Math.round(g/60)} h`:`resets in ${Math.round(g/1440)} days`:"",y=c.has(d.window)?ce.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${p.padEnd(12)} ${[f,h,y].filter(Boolean).join(", ")}`)}console.log();let u=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${u(i.maxPerHour)} in the last hour, ${i.last5h}${u(i.maxPer5h)} in the last 5 hours`),c.size&&console.log(ce.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${t.message}`))}});cs.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(ce.red(` Script not found: ${s}`)),console.log(ce.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ce.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ce.red(" Analysis failed. Is Python 3 installed?"))}});cs.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=g=>/^\d{4}-\d{2}-\d{2}$/.test(g)&&!Number.isNaN(Date.parse(g));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(ce.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 l=null;if(e.baseline)try{l=JSON.parse(t(e.baseline,"utf-8"))}catch(g){console.log(ce.red(` Cannot read baseline ${e.baseline}: ${g.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(l?{baseline:l,current:a}:a,null,2));return}let c=g=>g===null?"-":`$${g.toFixed(g<10?3:2)}`,u=g=>`${(g/1e6).toFixed(1)}M`;console.log(),console.log(ce.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),l&&console.log(ce.dim(` Baseline: ${l.from} to ${l.to} (${l.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(ce.dim(l?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let f=[...new Set([...Object.keys(a.channels),...Object.keys(l?.channels||{})])].map(g=>[g,a.channels[g],l?.channels[g]]).sort((g,h)=>(h[1]?.cost||0)-(g[1]?.cost||0));f.push(["TOTAL",a.total,l?.total]);for(let[g,h,y]of f){let w=r(h),$=` ${g.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${u(h?.cacheRead||0).padStart(11)} ${u(h?.cacheCreate||0).padStart(11)} ${u(h?.output||0).padStart(8)} ${c(h?.cost||0).padStart(10)} ${c(w).padStart(9)}`;if(l){let S=r(y),v=w!==null&&S?`${((w-S)/S*100).toFixed(0)}%`:"-";$+=` ${c(S).padStart(9)} ${v.padStart(7)}`}console.log($)}console.log(),l&&console.log(ce.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(ce.dim(` Saved ${e.save}`)),console.log()});cs.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-Y23TE5AN.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-W6CGC2EO.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),l=[],c=(d,p)=>{for(let f of d.commands??[]){let g=p?`${p} ${f.name()}`:f.name();l.push(g),c(f,g)}};c(i,"");let u=l.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:u},null,2));return}console.log(),console.log(ce.bold(` Never used in the last ${e.days} days (${u.length}/${l.length})`)),console.log();for(let d of u)console.log(` ${ce.dim("\xB7")} ${d}`);console.log(),console.log(ce.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ce.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(ce.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ce.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ce.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(ce.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=ce.dim(`${r.days}d`);console.log(` ${ce.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(ce.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as cN}from"commander";import Ke from"chalk";import{readFileSync as dN}from"fs";import{resolve as uN}from"path";Z();var fn=new cN().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");fn.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{Nm(uN(process.cwd(),".env"))}catch{}let t=gN(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-B6QSOGCC.js");o(t)}catch(t){console.log(Ke.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Ke.dim(t.stack)),process.exit(1)}});function gN(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Ke.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Ke.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
611
+ `}function is(e,t,o=".env"){let n=Yv(o),s=Kv(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Yu(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Yu(t)}`})),_I(n,LI(s))}function Ku(e,t=".env"){return Kv(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Xv="https://t.me/BotFather";async function qI(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 FI(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 Vv(e={}){console.log(),console.log(Ee.bold(" Connect Telegram")),console.log(),console.log(Ee.dim(` 1. Open ${Xv}`)),console.log(Ee.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Ee.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await wi({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&Mo(Xv);let{token:o}=await wi({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:v=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(v.trim())||"That doesn't look like a Telegram token"});o||(console.log(Ee.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await qI(o.trim());n||(console.log(Ee.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Ee.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(Ee.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let l=JSON.parse(s(a,"utf-8")),c=Object.keys(l.agents||{});c.length===0&&(console.log(Ee.red(" No agents configured. Run: agentx agent add")),process.exit(1));let u=e.agent;u||(u=(await wi({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:c.map(x=>({title:x,value:x})),initial:0})).agent),u||(console.log(Ee.red(" Aborted")),process.exit(1));let d=l.channels?.telegram?.accounts||{},p=e.account||u;d[p]&&d[p].agentBinding!==u&&(p=(await wi({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${u}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(Ee.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;is(f,o.trim()),process.env[f]=o.trim();let g=await pe(v=>{Ge(v,"channels.telegram.enabled",!0),Ge(v,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:u});let x=js(v,`agents.${u}.mentions`)||[],k=`@${n.username}`;x.includes(k)||(x.push(k),Ge(v,`agents.${u}.mentions`,x))},{configPath:e.configPath});if(g.success||(console.log(Ee.red(` \u2717 ${g.error}`)),process.exit(1)),console.log(),console.log(Ee.green(` \u2713 Bot @${n.username} bound to agent "${u}"`)),console.log(Ee.dim(` Token stored in .env as ${f}`)),console.log(Ee.dim(` Mentions updated to include @${n.username}`)),g.reloaded?console.log(Ee.dim(" Daemon hot-reloaded.")):console.log(Ee.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await wi({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(Ee.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Ee.dim(" Waiting up to 90s..."));let y=await FI(o.trim(),9e4);if(!y){console.log(Ee.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Ee.dim(" agentx config set notifications.destination.channel telegram")),console.log(Ee.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Ee.dim(` agentx config set notifications.destination.accountId ${p}`));return}let w={channel:"telegram",chatId:String(y.chatId),accountId:p},$=[],S=await pe(v=>{Ge(v,"notifications.destination",w),$=Na(v,w)},{configPath:e.configPath});if(!S.success){console.log(Ee.red(` \u2717 failed to save destination: ${S.error}`));return}console.log(Ee.green(" \u2713 Default --notify target set")),console.log(Ee.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Ee.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(Ee.dim(` Schedules that now report here: ${$.join(", ")}`)),S.reloaded&&console.log(Ee.dim(" Daemon hot-reloaded."))}import qe from"chalk";import Xu from"prompts";import{existsSync as Qu,mkdirSync as UI,readdirSync as WI,readFileSync as Qv}from"fs";import{resolve as Vu}from"path";var BI=".agentx/whatsapp-sessions";function JI(){let e=Vu(process.cwd(),".agentx/daemon.pid");if(!Qu(e))return!1;try{let t=parseInt(Qv(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function HI(e){if(!Qu(e))return!1;try{return WI(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function GI(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(qe.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(qe.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;UI(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let l={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>l},c=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,l):r.keys},...a?{version:a}:{},logger:l,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return c.ev.on("creds.update",i),await new Promise(u=>{let p=setTimeout(()=>{t(qe.yellow(" Timed out waiting for scan (2min)."));try{c.end(void 0)}catch{}u(!1)},12e4);c.ev.on("connection.update",async f=>{if(f.qr){t(qe.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:g}=await import("qrcode-terminal");g.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(p),t(qe.green(" \u2713 Paired"));try{c.end(void 0)}catch{}u(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),t(qe.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function Zv(e={}){if(console.log(),console.log(qe.bold(" Connect WhatsApp")),console.log(),JI()){console.log(qe.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(qe.dim(" agentx daemon stop")),console.log();let{cont:c}=await Xu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});c||(console.log(qe.red(" Aborted")),process.exit(1))}let t=e.configPath||Vu(process.cwd(),"agentx.json");Qu(t)||(console.log(qe.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Qv(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||BI,s=Vu(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(qe.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Xu({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(u=>({title:u,value:u})),initial:0})).agent),i||(console.log(qe.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(HI(s)&&a){let{keep:c}=await Xu({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!c,c&&console.log(qe.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await GI(s,u=>console.log(u))||(console.log(qe.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let l=await pe(c=>{Ge(c,"channels.whatsapp.enabled",!0),Ge(c,"channels.whatsapp.sessionDir",n),Ge(c,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});l.success||(console.log(qe.red(` \u2717 ${l.error}`)),process.exit(1)),console.log(),console.log(qe.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(qe.dim(` Session: ${n}`)),console.log(qe.dim(" Start the daemon to begin receiving:")),console.log(qe.dim(" agentx daemon start")),console.log(qe.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(qe.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(qe.dim(" Add routes later with:")),console.log(qe.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import Ot from"chalk";import zI from"prompts";import{existsSync as YI,readFileSync as KI}from"fs";import{resolve as XI}from"path";async function VI(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 QI(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 Uo(e){console.log(Ot.red(` ${e}`)),process.exit(1)}async function as(e){return(await zI(e,{onCancel:()=>Uo("Aborted")}))[e.name]}async function ex(e={}){console.log(),console.log(Ot.bold(" Connect email")),console.log();let t=e.configPath||XI(process.cwd(),"agentx.json");YI(t)||Uo(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(KI(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Uo("No agents configured. Run: agentx agent add");let s=e.agent??await as({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(w=>({title:w,value:w}))});o.agents?.[s]||Uo(`No agent "${s}" in ${t}`);let r=(e.address??await as({type:"text",name:"address",message:"Email address customers write to:",validate:w=>/^\S+@\S+\.\S+$/.test(w.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=yy(r),l=e.imapHost??a?.imapHost??await as({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),c=Number(e.imapPort??a?.imapPort??await as({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await as({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await as({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(c)||!Number.isInteger(d))&&Uo("Ports must be numbers.");let p=e.passwordEnv||by(i),f=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!f&&Uo(`${e.passwordEnv} is not set in the environment.`),f||(a?.imapHost==="imap.gmail.com"&&(console.log(Ot.dim(` Gmail needs an app password, not your account password: ${hy}`)),console.log(Ot.dim(" (2-step verification must be on for that page to show.)"))),f=(await as({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),f||Uo("Aborted");let g={agent:s,address:r,imapHost:l,imapPort:c,smtpHost:u,smtpPort:d,user:e.user,passwordEnv:p,allowFrom:e.allowFrom?.length?e.allowFrom:["*"],send:e.auto?"auto":"approve"};if(!e.skipCheck){process.stdout.write(" Logging in to IMAP and SMTP... ");let w=await VI(g,f);w&&(console.log(Ot.red("\u2717")),Uo(w)),console.log(Ot.green("\u2713"))}e.passwordEnv||(is(p,f),process.env[p]=f);let h=await pe(w=>{Ge(w,"channels.email.enabled",!0),Ge(w,`channels.email.accounts.${i}`,wy(g))},{configPath:e.configPath});h.success||Uo(`Config save failed: ${h.error}`),console.log(),console.log(Ot.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Ot.dim(` Password stored in .env as ${p}`)),console.log(Ot.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let y=QI(o.agents[s]?.tier,g.allowFrom);y&&console.log(Ot.yellow(` ${y}`)),console.log(g.send==="auto"?Ot.yellow(" Replies are sent as soon as the agent writes them."):Ot.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(Ot.dim(" Only mail that arrives from now on is answered.")),console.log(Ot.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as ZI}from"crypto";import Ze from"chalk";import tx from"prompts";var El="agentx-mesh:",Al="//join/";function eN(e){return Buffer.from(e,"utf-8").toString("base64url")}function tN(e){return Buffer.from(e,"base64url").toString("utf-8")}function oN(e){return`${El}${Al}${eN(JSON.stringify(e))}`}function nN(e){if(!e.startsWith(`${El}${Al}`))throw new Error(`Not a mesh invite link \u2014 expected ${El}${Al}\u2026`);let t=e.slice(El.length+Al.length),o=JSON.parse(tN(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 sN(){return ZI(32).toString("hex")}function rN(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function iN(e){return e?.node?.name||e?.node?.id||"node"}async function ox(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=Ku("MESH_TOKEN");i||(i=sN(),is("MESH_TOKEN",i),console.log(Ze.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||rN(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await tx({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:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});d||(console.log(Ze.red(" Aborted")),process.exit(1)),a=d}let c=await pe(d=>{Ge(d,"mesh.enabled",!0)},{configPath:e.configPath});c.success||(console.log(Ze.red(` \u2717 ${c.error}`)),process.exit(1));let u=oN({url:a,token:i,name:iN(r),version:1});console.log(),console.log(Ze.bold(" Mesh invite")),console.log(),console.log(` ${Ze.cyan(u)}`),console.log(),console.log(Ze.dim(" Run on the other node:")),console.log(Ze.dim(` agentx connect mesh join "${u}"`)),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 nx(e,t={}){let o;try{o=nN(e)}catch(r){console.log(Ze.red(` \u2717 ${r.message}`)),process.exit(1)}let n=Ku("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await tx({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))}is("MESH_TOKEN",o.token);let s=await pe(r=>{Ge(r,"mesh.enabled",!0);let i=js(r,"mesh.peers")||[],a=i.findIndex(c=>c.name===o.name),l={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=l:i.push(l),Ge(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 ls=new aN().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");ls.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 Vv({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});ls.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 Zv({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});ls.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 ex({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 sx=ls.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");sx.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 ox({url:e.url,configPath:e.config})});sx.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 nx(e,{configPath:t.config})});ls.action(()=>{console.log(),console.log(yr.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${yr.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${yr.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${yr.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${yr.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(yr.dim(" GitLab connect is the next slice.")),console.log()});Z();import{Command as lN}from"commander";import ce from"chalk";var cs=new lN().name("usage").description("token usage analysis and reporting");cs.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=O(),[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(ce.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ce.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${ce.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: ${ce.red(String(s.totalErrors))}`),console.log(),console.log(ce.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,l)=>l[1].total-a[1].total);for(let[a,l]of i){let c=r(l.total||l.input+l.output+l.cacheRead+l.cacheCreate),u=l.avgDuration?`${(l.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ce.cyan(a)}: ${c} tokens (${l.tasks} tasks) ${ce.dim(u)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${e.message}`))}});cs.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=O(),[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(p=>a(p.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:ce.dim(" No hold to lift.")),console.log();return}let l=i.now,c=new Set(i.holds.map(d=>d.window));console.log(ce.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(ce.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 p=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",g=Math.max(1,Math.round((d.resetsAt-l)/6e4)),h=d.resetsAt>l?g<60?`resets in ${g} min`:g<48*60?`resets in ${Math.round(g/60)} h`:`resets in ${Math.round(g/1440)} days`:"",y=c.has(d.window)?ce.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${p.padEnd(12)} ${[f,h,y].filter(Boolean).join(", ")}`)}console.log();let u=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${u(i.maxPerHour)} in the last hour, ${i.last5h}${u(i.maxPer5h)} in the last 5 hours`),c.size&&console.log(ce.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${t.message}`))}});cs.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(ce.red(` Script not found: ${s}`)),console.log(ce.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ce.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ce.red(" Analysis failed. Is Python 3 installed?"))}});cs.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=g=>/^\d{4}-\d{2}-\d{2}$/.test(g)&&!Number.isNaN(Date.parse(g));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(ce.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 l=null;if(e.baseline)try{l=JSON.parse(t(e.baseline,"utf-8"))}catch(g){console.log(ce.red(` Cannot read baseline ${e.baseline}: ${g.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(l?{baseline:l,current:a}:a,null,2));return}let c=g=>g===null?"-":`$${g.toFixed(g<10?3:2)}`,u=g=>`${(g/1e6).toFixed(1)}M`;console.log(),console.log(ce.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),l&&console.log(ce.dim(` Baseline: ${l.from} to ${l.to} (${l.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(ce.dim(l?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let f=[...new Set([...Object.keys(a.channels),...Object.keys(l?.channels||{})])].map(g=>[g,a.channels[g],l?.channels[g]]).sort((g,h)=>(h[1]?.cost||0)-(g[1]?.cost||0));f.push(["TOTAL",a.total,l?.total]);for(let[g,h,y]of f){let w=r(h),$=` ${g.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${u(h?.cacheRead||0).padStart(11)} ${u(h?.cacheCreate||0).padStart(11)} ${u(h?.output||0).padStart(8)} ${c(h?.cost||0).padStart(10)} ${c(w).padStart(9)}`;if(l){let S=r(y),v=w!==null&&S?`${((w-S)/S*100).toFixed(0)}%`:"-";$+=` ${c(S).padStart(9)} ${v.padStart(7)}`}console.log($)}console.log(),l&&console.log(ce.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(ce.dim(` Saved ${e.save}`)),console.log()});cs.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-Y23TE5AN.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-QUIOI4AU.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),l=[],c=(d,p)=>{for(let f of d.commands??[]){let g=p?`${p} ${f.name()}`:f.name();l.push(g),c(f,g)}};c(i,"");let u=l.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:u},null,2));return}console.log(),console.log(ce.bold(` Never used in the last ${e.days} days (${u.length}/${l.length})`)),console.log();for(let d of u)console.log(` ${ce.dim("\xB7")} ${d}`);console.log(),console.log(ce.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ce.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(ce.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ce.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ce.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(ce.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=ce.dim(`${r.days}d`);console.log(` ${ce.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(ce.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as cN}from"commander";import Ke from"chalk";import{readFileSync as dN}from"fs";import{resolve as uN}from"path";Z();var fn=new cN().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");fn.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{Nm(uN(process.cwd(),".env"))}catch{}let t=gN(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-MG7HVCKE.js");o(t)}catch(t){console.log(Ke.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Ke.dim(t.stack)),process.exit(1)}});function gN(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Ke.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Ke.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
612
612
  `)),{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}}}}fn.command("list").description("list configured boards").action(()=>{try{let e=O();if(!e.boards?.length){console.log(Ke.dim(`
613
613
  No boards configured.
614
614
  `));return}console.log();for(let t of e.boards){console.log(` ${Ke.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(Ke.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(Ke.dim(` primary label: ${t.primaryToolLabel}`)),console.log(Ke.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(Ke.red(` ${e.message}`)),process.exit(1)}});fn.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{bi(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(Ke.red(` ${o.message}`)),process.exit(1)}});fn.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{bi(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(Ke.red(` ${o.message}`)),process.exit(1)}});var Zu=fn.command("column").description("manage a board's columns (add / remove / edit / list)");Zu.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(dN("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(Ke.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(` ${Ke.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${Ke.dim(r)}`)}}catch(t){console.log(Ke.red(` ${t.message}`)),process.exit(1)}});Zu.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{bi(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(Ke.red(` ${n.message}`)),process.exit(1)}});Zu.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{bi(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(Ke.red(` ${o.message}`)),process.exit(1)}});fn.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{bi(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(Ke.red(` ${t.message}`)),process.exit(1)}});function bi(e){let{summary:t,backupPath:o}=Ut(n=>e(n));console.log(Ke.green(`
@@ -912,7 +912,7 @@ Restart the daemon to activate.
912
912
  dist/
913
913
  *.log
914
914
  .env
915
- `}import{Command as X_}from"commander";import ut from"chalk";import{writeFileSync as V_,mkdirSync as Q_,existsSync as tc,readFileSync as aS,appendFileSync as lS}from"fs";import{resolve as Rr,dirname as uS}from"path";import{homedir as qg}from"os";var gS=new X_().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-W6CGC2EO.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=tD(o);break;case"bash":s=iD(o);break;case"fish":s=aD(o);break;default:console.error(ut.red(`unsupported shell: ${n}`)),console.error(ut.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?Rr(String(e.output)):Z_(n);Q_(uS(r),{recursive:!0}),V_(r,s),console.log(ut.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),eD(n,r,!!e.yes)});function Z_(e){let t=qg();switch(e){case"zsh":return Rr(t,".zsh","completions","_agentx");case"bash":return Rr(t,".bash_completion.d","agentx.bash");case"fish":return Rr(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function eD(e,t,o){if(e==="zsh"){let n=Rr(qg(),".zshrc"),s=uS(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=tc(n)?aS(n,"utf-8"):"",l=!a.includes(s),c=!/autoload\s+-U\s+compinit/.test(a);if(!l&&!c){console.log(ut.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&tc(n)){let u=["","# agentx completion"];l&&u.push(r),c&&u.push(i),lS(n,u.join(`
915
+ `}import{Command as X_}from"commander";import ut from"chalk";import{writeFileSync as V_,mkdirSync as Q_,existsSync as tc,readFileSync as aS,appendFileSync as lS}from"fs";import{resolve as Rr,dirname as uS}from"path";import{homedir as qg}from"os";var gS=new X_().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-QUIOI4AU.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=tD(o);break;case"bash":s=iD(o);break;case"fish":s=aD(o);break;default:console.error(ut.red(`unsupported shell: ${n}`)),console.error(ut.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?Rr(String(e.output)):Z_(n);Q_(uS(r),{recursive:!0}),V_(r,s),console.log(ut.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),eD(n,r,!!e.yes)});function Z_(e){let t=qg();switch(e){case"zsh":return Rr(t,".zsh","completions","_agentx");case"bash":return Rr(t,".bash_completion.d","agentx.bash");case"fish":return Rr(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function eD(e,t,o){if(e==="zsh"){let n=Rr(qg(),".zshrc"),s=uS(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=tc(n)?aS(n,"utf-8"):"",l=!a.includes(s),c=!/autoload\s+-U\s+compinit/.test(a);if(!l&&!c){console.log(ut.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&tc(n)){let u=["","# agentx completion"];l&&u.push(r),c&&u.push(i),lS(n,u.join(`
916
916
  `)+`
917
917
  `),console.log(ut.green("\u2713 Patched ~/.zshrc")),console.log(ut.dim("Reload your shell: exec zsh"));return}console.log(ut.dim("Add this to ~/.zshrc if not already present:")),l&&console.log(ut.cyan(` ${r}`)),c&&console.log(ut.cyan(` ${i}`)),console.log(),console.log(ut.dim("Then reload: exec zsh")),console.log(ut.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Rr(qg(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((tc(n)?aS(n,"utf-8"):"").includes(t)){console.log(ut.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&tc(n)){lS(n,`
918
918
  # agentx completion
@@ -928,4 +928,4 @@ ${lD({...t,category:e.category})}`),u&&a.set(c.id,u)}let l=`https://github.com/$
928
928
  ${o.url}`)}catch(t){console.error(Cr.red(` ${t.message}`)),process.exitCode=1}});ji.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",Ug).action(async(e,t)=>{try{let o=await Jg(t.models);if(!Wg(t.model,o)){console.log(Bg(t.model,o)),process.exitCode=1;return}let n=e==="-"?await uD():await dD(e,"utf8"),s=JSON.parse(n),{version:r}=await ea(),i=hS({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(Cr.red(` ${o.message}`)),process.exitCode=1}});async function uD(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function V5(){let e=await ea(),t=new gD().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=ky(n);vy(s)&&$y("cli",s)});for(let o of[vb,Dw,_w,ls,Ws,yo,Wt,ty,zk,Kk,$o,La,qo,_n,ts,So,Fo,si,zv,pn,Ca,W0,dn,N$,j$,W$,gi,Z$,sk,C$,ak,lk,Ek,Ck,Ok,zt,cs,Y0,Xr,nn,gS,ji])t.addCommand(o);for(let o of wS)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=wS.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,mD(o,74," "),""].join(`
929
929
  `)}),t}var wS=[X,$r,Bo,lo,Qr,cr,rt,Wo,fn,es,ps,vr,wn,an,At,er,tl,hl,Qn,yl,wl,M0,F0,Lo,Ei,Jt,By,qn,Ii,Md,$n,xt,Qs,Ld,Jl,To,yg,Jo,eS,Er,tS,G0];function mD(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(`
930
930
  `)}export{V5 as buildProgram};
931
- //# sourceMappingURL=program-W6CGC2EO.js.map
931
+ //# sourceMappingURL=program-QUIOI4AU.js.map