agentix-cli 0.189.1 → 0.190.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -531,7 +531,7 @@ ${l}`)}let S={agentId:o,message:w,context:{channel:g,sender:y?"opencode":"openai
531
531
 
532
532
  `)}}function Hy(r){r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"})}function By(r,e,t,n,s,i){r.write(`data: ${JSON.stringify({id:e,object:"chat.completion.chunk",created:t,model:n,choices:[{index:0,delta:s,finish_reason:i}]})}
533
533
 
534
- `)}function qy(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);Ec(r,200,{id:e,object:"chat.completion",created:t,model:n,choices:[{index:0,message:{role:"assistant",content:s},finish_reason:"stop"}],usage:{prompt_tokens:o,completion_tokens:a,total_tokens:o+a}})}function Ec(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Kn=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Kn(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(Kn.levelOrder[e]<Kn.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",o=`[${this.module}]`,a=i?`${o} ${i}: ${t}`:`${o} ${t}`;console.error(a)}},Jn=Kn;jt(Jn,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as eR,statSync as tR}from"fs";var nt={version:"0.189.1",commit:"6e4d99e",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function nR(r,e){let t=e.mtimeMs!==null&&e.mtimeMs>Date.parse(r.startedAt),n=!!e.version&&!!r.version&&e.version!==r.version;return{newer:t||n,changedAt:e.mtimeMs===null?null:new Date(e.mtimeMs).toISOString(),version:e.version}}function Vy(){let r=null;try{r=tR(eR(process.argv[1])).mtimeMs}catch{}let e=fy().version;return nR(nt,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as sR}from"crypto";var Dr=class{constructor(e=new Rh){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!rR.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};oR(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:sR(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=iR(t);this.core.publish({id:t.id,at:t.at,kind:t.kind,type:n,summary:s,ref:i,agentId:o,rootId:typeof e.rootId=="string"?e.rootId:void 0,data:t})}get size(){return this.count}},rR=["run","task","signal","mesh","channel","status"];function iR(r){switch(r.kind){case"run":return{type:r.phase,ref:r.runId,summary:[r.workflowId,r.nodeId,r.phase,r.note].filter(Boolean).join(" ")};case"task":return{type:r.phase,ref:r.taskId,summary:`${r.title??r.taskId} ${r.phase}`};case"signal":return{type:"emitted",summary:`signal ${r.name} (${r.scope})`};case"mesh":return{type:r.delta,summary:`peer ${r.peer} ${r.delta}`};case"channel":return{type:r.direction,ref:r.messageId,agentId:r.agentId,summary:`${r.channel} ${r.direction==="in"?"inbound":"outbound"}`};case"status":return{type:"status",summary:r.message}}}function oR(r,e){return!(r.kinds&&r.kinds.length>0&&!r.kinds.includes(e.kind)||r.workflowId&&(e.kind==="run"&&e.workflowId!==r.workflowId||e.kind==="task"&&e.workflowId!==r.workflowId||e.kind==="signal"&&e.workflowId&&e.workflowId!==r.workflowId)||r.runId&&(e.kind==="run"&&e.runId!==r.runId||e.kind==="task"&&e.runId!==r.runId)||r.actor&&(e.kind!=="task"||!(e.assignedTo?.includes(r.actor)||e.submittedBy===r.actor))||r.channel&&(e.kind!=="channel"||e.channel!==r.channel))}function Jy(r){if(!r)return;let e=["run","task","signal","mesh","channel","status"],n=r.split(",").map(s=>s.trim()).filter(Boolean).filter(s=>e.includes(s));return n.length?n:void 0}import{createHmac as Nr,timingSafeEqual as Ky}from"crypto";var Lr=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),l=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let b={};for(let[w,S]of Object.entries(e.headers))(w.startsWith("x-hubspot")||w.startsWith("x-hub")||w.startsWith("x-github")||w.startsWith("x-gitlab")||w.startsWith("stripe")||w.startsWith("sentry")||w.startsWith("x-vercel")||w.startsWith("x-odoo")||w.startsWith("x-webhook")||w==="user-agent"||w==="content-type"||w==="host"||w==="x-forwarded-host"||w==="x-forwarded-proto"||w==="x-forwarded-for")&&(b[w]=S);this.log(`Webhook [${l}] reqUrl=${e.url} headers: ${JSON.stringify(b)}`)}let d=this.validateSignature(e.headers,a,l,i,e.url);if(d){this.log(`Webhook [${l}] -> ${i}: REJECTED (${d})`),this.sendJson(t,401,{error:d});return}let u=this.buildSummary(l,c,e.headers);this.log(`Webhook [${l}] -> ${i}: ${u.slice(0,100)}`);let h=this.extractEventType(l,c,e.headers),f=this.webhookEntries.find(b=>b.enabled&&b.agentId===i&&b.source===l),y=h&&f?.triggers?.[h]||f?.defaultWorkflow||null;if(await this.fireHookSafe(l,h,i,c),y&&this.workflowDispatcher)try{let b=await this.workflowDispatcher.dispatchWorkflow({workflowId:y,entityRef:{kind:"webhook",id:`${l}:${i}:${h??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:h,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${h??"\u2014"}] -> workflow=${y} (claimed=${b.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:h,workflow:y,claimed:b.claimed});return}catch(b){this.log(`Workflow dispatch failed [${l}/${h}/${y}]: ${b.message}`)}let g=this.webhookEntries.find(b=>b.enabled&&b.node&&b.agentId===i&&b.source===l);if(g?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:g.node,status:"accepted"}),this.mesh.sendTask(g.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(b=>this.log(`Mesh-forwarded webhook [${l}] -> ${g.node}/${i}: ${b?.slice(0,100)||"ok"}`),b=>this.log(`Mesh forward failed [${l}] -> ${g.node}/${i}: ${b.message}`));return}try{let b=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${l}`,sender:`webhook:${l}`}});this.sendJson(t,b.error?500:200,{ok:!b.error,agent:i,source:l,response:b.content?.slice(0,500),error:b.error,duration:b.duration})}catch(b){this.sendJson(t,500,{error:b.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let d of t.commits.slice(0,3))s.push(` - ${d.message?.split(`
534
+ `)}function qy(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);Ec(r,200,{id:e,object:"chat.completion",created:t,model:n,choices:[{index:0,message:{role:"assistant",content:s},finish_reason:"stop"}],usage:{prompt_tokens:o,completion_tokens:a,total_tokens:o+a}})}function Ec(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Kn=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Kn(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(Kn.levelOrder[e]<Kn.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",o=`[${this.module}]`,a=i?`${o} ${i}: ${t}`:`${o} ${t}`;console.error(a)}},Jn=Kn;jt(Jn,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as eR,statSync as tR}from"fs";var nt={version:"0.190.0",commit:"529a0d2",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function nR(r,e){let t=e.mtimeMs!==null&&e.mtimeMs>Date.parse(r.startedAt),n=!!e.version&&!!r.version&&e.version!==r.version;return{newer:t||n,changedAt:e.mtimeMs===null?null:new Date(e.mtimeMs).toISOString(),version:e.version}}function Vy(){let r=null;try{r=tR(eR(process.argv[1])).mtimeMs}catch{}let e=fy().version;return nR(nt,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as sR}from"crypto";var Dr=class{constructor(e=new Rh){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!rR.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};oR(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:sR(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=iR(t);this.core.publish({id:t.id,at:t.at,kind:t.kind,type:n,summary:s,ref:i,agentId:o,rootId:typeof e.rootId=="string"?e.rootId:void 0,data:t})}get size(){return this.count}},rR=["run","task","signal","mesh","channel","status"];function iR(r){switch(r.kind){case"run":return{type:r.phase,ref:r.runId,summary:[r.workflowId,r.nodeId,r.phase,r.note].filter(Boolean).join(" ")};case"task":return{type:r.phase,ref:r.taskId,summary:`${r.title??r.taskId} ${r.phase}`};case"signal":return{type:"emitted",summary:`signal ${r.name} (${r.scope})`};case"mesh":return{type:r.delta,summary:`peer ${r.peer} ${r.delta}`};case"channel":return{type:r.direction,ref:r.messageId,agentId:r.agentId,summary:`${r.channel} ${r.direction==="in"?"inbound":"outbound"}`};case"status":return{type:"status",summary:r.message}}}function oR(r,e){return!(r.kinds&&r.kinds.length>0&&!r.kinds.includes(e.kind)||r.workflowId&&(e.kind==="run"&&e.workflowId!==r.workflowId||e.kind==="task"&&e.workflowId!==r.workflowId||e.kind==="signal"&&e.workflowId&&e.workflowId!==r.workflowId)||r.runId&&(e.kind==="run"&&e.runId!==r.runId||e.kind==="task"&&e.runId!==r.runId)||r.actor&&(e.kind!=="task"||!(e.assignedTo?.includes(r.actor)||e.submittedBy===r.actor))||r.channel&&(e.kind!=="channel"||e.channel!==r.channel))}function Jy(r){if(!r)return;let e=["run","task","signal","mesh","channel","status"],n=r.split(",").map(s=>s.trim()).filter(Boolean).filter(s=>e.includes(s));return n.length?n:void 0}import{createHmac as Nr,timingSafeEqual as Ky}from"crypto";var Lr=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),l=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let b={};for(let[w,S]of Object.entries(e.headers))(w.startsWith("x-hubspot")||w.startsWith("x-hub")||w.startsWith("x-github")||w.startsWith("x-gitlab")||w.startsWith("stripe")||w.startsWith("sentry")||w.startsWith("x-vercel")||w.startsWith("x-odoo")||w.startsWith("x-webhook")||w==="user-agent"||w==="content-type"||w==="host"||w==="x-forwarded-host"||w==="x-forwarded-proto"||w==="x-forwarded-for")&&(b[w]=S);this.log(`Webhook [${l}] reqUrl=${e.url} headers: ${JSON.stringify(b)}`)}let d=this.validateSignature(e.headers,a,l,i,e.url);if(d){this.log(`Webhook [${l}] -> ${i}: REJECTED (${d})`),this.sendJson(t,401,{error:d});return}let u=this.buildSummary(l,c,e.headers);this.log(`Webhook [${l}] -> ${i}: ${u.slice(0,100)}`);let h=this.extractEventType(l,c,e.headers),f=this.webhookEntries.find(b=>b.enabled&&b.agentId===i&&b.source===l),y=h&&f?.triggers?.[h]||f?.defaultWorkflow||null;if(await this.fireHookSafe(l,h,i,c),y&&this.workflowDispatcher)try{let b=await this.workflowDispatcher.dispatchWorkflow({workflowId:y,entityRef:{kind:"webhook",id:`${l}:${i}:${h??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:h,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${h??"\u2014"}] -> workflow=${y} (claimed=${b.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:h,workflow:y,claimed:b.claimed});return}catch(b){this.log(`Workflow dispatch failed [${l}/${h}/${y}]: ${b.message}`)}let g=this.webhookEntries.find(b=>b.enabled&&b.node&&b.agentId===i&&b.source===l);if(g?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:g.node,status:"accepted"}),this.mesh.sendTask(g.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(b=>this.log(`Mesh-forwarded webhook [${l}] -> ${g.node}/${i}: ${b?.slice(0,100)||"ok"}`),b=>this.log(`Mesh forward failed [${l}] -> ${g.node}/${i}: ${b.message}`));return}try{let b=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${l}`,sender:`webhook:${l}`}});this.sendJson(t,b.error?500:200,{ok:!b.error,agent:i,source:l,response:b.content?.slice(0,500),error:b.error,duration:b.duration})}catch(b){this.sendJson(t,500,{error:b.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let d of t.commits.slice(0,3))s.push(` - ${d.message?.split(`
535
535
  `)[0]||"no message"} (${d.author?.name||""})`)}let l=t.object_attributes;if(l?.title&&(s.push(`Title: ${l.title}`),s.push(`State: ${l.state||""}`),s.push(`Action: ${l.action||""}`),l.source_branch&&s.push(`Branch: ${l.source_branch} -> ${l.target_branch}`),l.url&&s.push(`URL: ${l.url}`)),l?.iid&&!l?.source_branch&&(s.push(`Issue #${l.iid}: ${l.title||""}`),l.description&&s.push(`Description: ${l.description.slice(0,200)}`)),t.object_kind==="pipeline"){let d=t.object_attributes;s.push(`Pipeline: ${d?.status||""} (${d?.ref||""})`),s.push(`Duration: ${d?.duration||0}s`)}break}case"github":{let o=n["x-github-event"]||"event",a=t.repository?.full_name||"",c=t.sender?.login||"";if(s.push(`Event: ${o}`),a&&s.push(`Repository: ${a}`),c&&s.push(`Sender: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits))for(let u of t.commits.slice(0,3))s.push(` - ${u.message?.split(`
536
536
  `)[0]||""} (${u.author?.name||""})`);let l=t.pull_request;l&&(s.push(`PR #${l.number}: ${l.title}`),s.push(`Action: ${t.action}`),s.push(`Branch: ${l.head?.ref} -> ${l.base?.ref}`));let d=t.issue;d&&(s.push(`Issue #${d.number}: ${d.title}`),s.push(`Action: ${t.action}`));break}case"stripe":{let o=t.type||"event",a=t.data?.object||{};s.push(`Event: ${o}`),a.amount&&s.push(`Amount: ${(a.amount/100).toFixed(2)} ${a.currency?.toUpperCase()||""}`),a.customer_email&&s.push(`Customer: ${a.customer_email}`),a.description&&s.push(`Description: ${a.description}`),a.status&&s.push(`Status: ${a.status}`);break}case"sentry":{let o=n["sentry-hook-resource"]||"event";s.push(`Resource: ${o}`);let a=t.data||t;a.error?.title&&s.push(`Error: ${a.error.title}`),a.error?.culprit&&s.push(`Culprit: ${a.error.culprit}`),a.error?.metadata?.value&&s.push(`Message: ${a.error.metadata.value}`),t.url&&s.push(`URL: ${t.url}`);break}case"hubspot":{let o=Array.isArray(t)?t:null,a=o||null;if(a&&a.length){s.push(`Events: ${a.length}`);for(let l of a.slice(0,3)){let d=l.subscriptionType??"?",u=l.objectId??"?",h=l.changeFlag??l.changeSource??"";s.push(` - ${d} (object ${u}${h?`, ${h}`:""})`)}}else{let l=t.subscriptionType??"event",d=t.objectId??"?";s.push(`Event: ${l} (object ${d})`)}let c=a?.[0]?.portalId??t.portalId;c!=null&&s.push(`Portal: ${c}`);break}case"odoo":{let o=typeof t.event=="string"&&t.event||typeof t.subscriptionType=="string"&&t.subscriptionType||typeof t.model=="string"&&(typeof t.action=="string"?`${t.model}.${t.action}`:t.model)||"event";s.push(`Event: ${o}`);let a=n["x-odoo-database"]||(typeof t.database=="string"?t.database:"");a&&s.push(`Database: ${a}`);let c=t.record||t;c?.id&&s.push(`Record id: ${c.id}`),c?.name&&s.push(`Name: ${String(c.name).slice(0,200)}`),c?.partner_id?.[1]&&s.push(`Partner: ${c.partner_id[1]}`),c?.email&&s.push(`Email: ${c.email}`),c?.amount_total!=null&&s.push(`Amount: ${c.amount_total}`),c?.state&&s.push(`State: ${c.state}`);break}default:s.push(`Headers: ${JSON.stringify(Object.keys(n).filter(o=>o.startsWith("x-")).slice(0,5))}`),s.push(`Payload keys: ${Object.keys(t).slice(0,10).join(", ")}`);let i=JSON.stringify(t).slice(0,500);s.push(`Body: ${i}`)}return s.join(`
537
537
  `)}async readBody(e){return new Promise(t=>{let n="";e.on("data",s=>n+=s.toString()),e.on("end",()=>{let s;try{s=n?JSON.parse(n):{}}catch{s={raw:n}}t({raw:n,parsed:s})}),e.on("error",()=>t({raw:"",parsed:{}}))})}validateSignature(e,t,n,s,i){let o=this.webhookEntries.find(d=>d.enabled&&d.agentId===s&&d.source===n);if(!o?.secretEnv)return null;let a=process.env[o.secretEnv];if(!a)return`webhook entry "${o.id}" expects env ${o.secretEnv} but it is unset`;let c=d=>{let u=e[d.toLowerCase()];return Array.isArray(u)?u[0]:u};if(n==="github"){let d=c("x-hub-signature-256");if(!d)return"missing X-Hub-Signature-256";let u="sha256="+Nr("sha256",a).update(t).digest("hex");return en(u,d)}if(n==="gitlab"){let d=c("x-gitlab-token");return d?en(a,d):"missing X-Gitlab-Token"}if(n==="stripe"){let d=c("stripe-signature");if(!d)return"missing Stripe-Signature";let u=Object.fromEntries(d.split(",").map(f=>f.split("=")));if(!u.t||!u.v1)return"malformed Stripe-Signature";let h=Nr("sha256",a).update(`${u.t}.${t}`).digest("hex");return en(h,u.v1)}if(n==="hubspot"){let d=c("x-hubspot-signature-v3"),u=c("x-hubspot-request-timestamp");if(!d)return"missing X-HubSpot-Signature-v3";if(!u)return"missing X-HubSpot-Request-Timestamp";let h=parseInt(u,10);if(!Number.isFinite(h))return"malformed X-HubSpot-Request-Timestamp";let f=Date.now()-h;if(f>5*6e4)return`HubSpot webhook is ${Math.floor(f/1e3)}s old (>5min replay window)`;let y="POST",g=i||e["x-original-uri"]||e["x-forwarded-path"]||"",b=e["x-forwarded-host"],w=e.host,S=e["x-forwarded-proto"]||"https",k=new Set;b&&g&&k.add(`${S}://${b}${g}`),w&&g&&k.add(`https://${w}${g}`),w&&g&&k.add(`http://${w}${g}`),g&&k.add(g),k.add("");for(let x of k){let E=Nr("sha256",a).update(`${y}${x}${t}${u}`).digest("base64");if(d.length===E.length&&Ky(Buffer.from(d),Buffer.from(E)))return null}return`signature mismatch (tried ${k.size} URI variants)`}if(n==="odoo"){let d=c("x-odoo-signature");if(d){let h=Nr("sha256",a).update(t).digest("hex"),f=d.startsWith("sha256=")?d.slice(7):d;return en(h,f)}let u=c("x-odoo-webhook-token")??c("x-webhook-secret");return u?en(a,u):"missing X-Odoo-Signature or X-Odoo-Webhook-Token"}let l=c("x-webhook-secret");return l?en(a,l):"missing X-Webhook-Secret"}sendJson(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}};function en(r,e){if(r.length!==e.length)return"signature mismatch";let t=Buffer.from(r),n=Buffer.from(e);return Ky(t,n)?null:"signature mismatch"}Iu();zd();wu();wT();function aR(r){return{insertTaskHistory:r.prepare(`
@@ -1336,4 +1336,4 @@ data: ${JSON.stringify(z)}
1336
1336
  `)}catch{}},L=setInterval(()=>{try{t.write(`: ping
1337
1337
 
1338
1338
  `)}catch{}},15e3);L.unref?.();let H=new AbortController;t.on("close",()=>{t.writableEnded||H.abort()});try{for await(let W of this.mesh.sendTaskStream(p.peer,p.message,p.agent,{context:p.context,signal:H.signal,vouchOwner:$}))C(W.event,W.data)}catch(W){C("error",{error:W?.message??String(W)})}finally{clearInterval(L);try{t.end()}catch{}}break}let _=p.context,M=typeof p.senderAgentId=="string"?p.senderAgentId:void 0;if(z$(p,!0)==="callback"){let C=this.delegationGate(e,p,{callee:p.agent,peer:p.peer,message:p.message,calleeContext:_});if(!("track"in C)){let L=So(C);this.json(t,L.status,L.body);break}}if(p.async===!0){let C=_?.channel,L=_?.chatId;if(!C||!L){this.json(t,400,{error:"async requires context.channel and context.chatId \u2014 there is no route back otherwise"});return}let H=`mesh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;this.json(t,202,{accepted:!0,taskId:H,deliverTo:`${C}:${L}`,note:"result will be delivered to the originating chat when the peer finishes"});let W=p.peer,z=p.agent,Se=this.mesh;(async()=>{let J=Date.now(),Y;try{Y=await Se.sendTask(W,p.message,z,{vouchOwner:$,context:_,senderAgentId:M}),this.log(`[mesh/task async ${H}] ${W}/${z??"default"} finished in ${Date.now()-J}ms`)}catch(K){Y=`Delegation to ${W}/${z??"default"} failed: ${K?.message??K}`,this.log(`[mesh/task async ${H}] failed: ${K?.message??K}`)}try{await this.router.sendOutbound({channel:C,chatId:L,text:Y,agentId:_?.agentId??M,accountId:_?.accountId})}catch(K){this.log(`[mesh/task async ${H}] delivery failed: ${K?.message??K}`)}})();break}let N=await this.mesh.sendTask(p.peer,p.message,p.agent,{context:_,senderAgentId:M,vouchOwner:$});this.json(t,200,{response:N});break}case"POST /webrtc/signal/out":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let m=await U(e);if(!m.kind||!m.callId||!m.from||!m.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let v=await this.webrtc.handleOutgoing(m);this.json(t,v.ok?200:400,v);break}case"POST /webrtc/signal":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let m=await U(e);if(!m.kind||!m.callId||!m.from||!m.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let v=this.webrtc.handleIncoming(m);this.json(t,v.ok?200:400,v);break}case"POST /webrtc/bot/invite":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled (channels.webrtc.bot.enabled=false)"});return}let p=await U(e),m=p.callId,v=p.target,$=p.agentId||this.config.channels.webrtc?.bot.defaultAgentId;if(!m||!v||!$){this.json(t,400,{error:"Missing: callId, target, agentId (or defaultAgentId in config)"});return}let I=await this.botManager.invite({callId:m,target:v,agentId:$});this.json(t,I.ok?200:500,I);break}case"GET /webrtc/bots":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active()});break}case"GET /webrtc/history":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active(),history:this.botManager.history()});break}case"GET /webrtc/config":{let p=this.config.channels.webrtc;if(!p?.enabled){this.json(t,404,{error:"WebRTC signaling not enabled"});return}this.json(t,200,{localName:this.config.node.name,iceServers:[...p.stunServers.map(m=>({urls:m})),...p.turnServers],peers:this.mesh?.directory().map(m=>({name:m.peer,healthy:m.healthy}))||[],camera:p.camera,agents:this.registry.list().map(m=>({id:m.id,name:m.name}))});break}case"GET /.well-known/agent-card.json":this.json(t,200,{name:this.config.node.name,description:`AgentX daemon node "${this.config.node.name}"`,url:`http://${this.config.node.bind}`,version:"1.0.0",capabilities:{streaming:!1,pushNotifications:!1,stateTransitionHistory:!1},skills:this.registry.list().map(p=>{let m=this.config.agents[p.id]||{},v=typeof m.description=="string"&&m.description.trim()||hj(m.systemPrompt)||`Agent "${p.name}" (${p.tier})`,$=Array.isArray(m.mentions)?m.mentions.slice(0,4):[];return{id:p.id,name:p.name,description:v,tags:[p.tier,...$],color:we(p.id,m).color}}),channels:this.router.getChannelNames(),githubLogins:this.github?.postingAccounts()??[],defaultInputModes:["text"],defaultOutputModes:["text"]});break;case"GET /wiki/agents":{let p=this.registry.getWikiHub();this.json(t,200,{nodeId:this.config.node.id,agents:p.summary()});break}case"GET /wiki/entries":{let p=this.registry.getWikiHub(),m=n.searchParams.get("agent")||void 0,v=n.searchParams.get("after")||void 0,$=m?p.getAgentEntries(m):p.getSharedStore().listEntries({after:v});this.json(t,200,{nodeId:this.config.node.id,count:$.length,entries:$.map(I=>({id:I.id,date:I.date,agentId:I.agentId,source:I.source,sourceContext:I.sourceContext,content:I.content}))});break}case"GET /wiki/articles":{let p=this.registry.getWikiHub(),m=n.searchParams.get("agent");if(!m){this.json(t,400,{error:"?agent= required"});break}let $=p.getAgentWiki(m).rebuildIndex();this.json(t,200,{nodeId:this.config.node.id,agentId:m,articles:$.articles});break}case"GET /wiki/article":{let p=this.registry.getWikiHub(),m=n.searchParams.get("agent"),v=n.searchParams.get("path");if(!m||!v){this.json(t,400,{error:"?agent= and ?path= required"});break}let I=p.getAgentWiki(m).readArticle(v);if(!I){this.json(t,404,{error:"Article not found"});break}this.json(t,200,{nodeId:this.config.node.id,agentId:m,path:I.path,title:I.meta.title,tags:I.meta.tags,owner:I.meta.owner,created:I.meta.created,lastUpdated:I.meta.lastUpdated,sources:I.meta.sources,content:I.content});break}case"GET /wiki/notes":{let{NoteStore:p}=await import("./notes-WJJEJ4CJ.js"),m=n.searchParams.get("status")||"waiting";if(!["waiting","open","patched","rejected","deferred","expired","all"].includes(m)){this.json(t,400,{error:"status must be waiting, open, patched, rejected, deferred, expired or all"});break}let v=Math.max(1,Math.min(200,parseInt(n.searchParams.get("limit")||"50",10)||50)),I=new p(this.registry.getWikiHub().getBaseDir()).list(m==="all"?void 0:m);this.json(t,200,{nodeId:this.config.node.id,enabled:this.config.wikiNotes.enabled,inbox:this.config.wikiNotes.inbox??null,crons:this.config.wikiNotes.crons,absorbAgent:this.config.wikiNotes.absorbAgent??null,total:I.length,notes:I.slice(-v).reverse()});break}case"POST /wiki/notes":{let{NoteStore:p,validateNote:m}=await import("./notes-WJJEJ4CJ.js"),v=this.config.wikiNotes;if(!v.enabled||!v.inbox){this.json(t,409,{error:"wiki notes are off on this node: set wikiNotes.enabled and wikiNotes.inbox"});break}let $=await U(e),I=m({...$,to:v.inbox});if("error"in I){this.json(t,400,{error:I.error});break}let R=I.note;if(this.registry.getAgent(v.inbox)){try{let{note:N,added:C}=new p(this.registry.getWikiHub().getBaseDir()).add(R);this.json(t,C?201:200,{ok:!0,added:C,note:N,node:this.config.node.id})}catch(N){this.json(t,507,{error:N?.message??String(N)})}break}if($.forwarded===!0){this.json(t,404,{error:`inbox agent "${v.inbox}" is not on this node`});break}let _=this.mesh?.findAgentPeer(v.inbox);if(!_){this.json(t,404,{error:`inbox agent "${v.inbox}" is not on this node or any known peer`});break}let M=this.mesh.directory().find(N=>N.peer===_.peer)?.peerUrl;if(!_.healthy||!M){this.json(t,503,{error:`the node hosting "${v.inbox}" (${_.peer}) is unreachable; try again later`});break}try{let N=await fetch(`${M.replace(/\/$/,"")}/wiki/notes`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(_.peer)},body:JSON.stringify({...R,fromNode:R.fromNode||this.config.node.id,forwarded:!0}),signal:AbortSignal.timeout(1e4)}),C=await N.json().catch(()=>({}));this.json(t,N.status,{...C,peer:_.peer})}catch(N){this.json(t,502,{error:`forward to ${_.peer} failed: ${N?.message??N}`,peer:_.peer})}break}case"GET /graph/schema":{let p=this.registry.getGraphStore();if(!p){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,schema:p.loadSchema()});break}case"GET /graph/nodes":{let p=this.registry.getGraphStore();if(!p){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,...p.loadNodes()});break}case"GET /graph/classifications":{let p=this.registry.getGraphStore();if(!p){this.json(t,404,{error:"graph disabled on this node"});break}let m=n.searchParams.get("status")||"approved",v=Math.max(1,Math.min(1e3,parseInt(n.searchParams.get("limit")||"200",10)||200)),$=p.listByStatus(m,v);this.json(t,200,{nodeId:this.config.node.id,status:m,count:$.length,classifications:$});break}default:this.json(t,404,{error:"Not found",endpoints:["GET /health","GET /agents","GET /crons","GET /routines \u2014 schedules + cron/hook workflows with staleness flags","GET /mesh","GET /wiki/agents","GET /wiki/entries[?agent=X&after=YYYY-MM-DD]","GET /wiki/articles?agent=X","GET /wiki/notes[?status=waiting|open|patched|rejected|deferred|expired|all&limit=N]","POST /wiki/notes { from, change, source, date? } \u2014 a note for the wiki observe/sweep run","GET /graph/schema","GET /graph/nodes","GET /graph/classifications[?status=approved|pending|rejected&limit=N]","POST /task { agent, message, context?, freshSession?: bool }","GET /agents/:id \u2014 resolved agent config (permission, tier, model, persistentProcess, toolUseRequired)","POST /agents/:id/selftest { message? } \u2014 canary probe; runs a fresh-session task and reports {ok, durationMs, tokens, billedModel}","GET /traces[?agentId=&channel=&chatId=&workflowRunId=&status=&since=&until=&limit=]","GET /traces/:taskId \u2014 full per-task execution trace (steps + tokens)","GET /voice/history[?agent=&limit=&before=] \u2014 past voice exchanges, bounded summaries","GET /voice/history/:id \u2014 one voice exchange in full; POST /voice/history/:id/replay","GET /api/processes \u2014 live persistent claude processes (JSON)","POST /api/processes/kill { agentId, channel, chatId, reason? }","GET /api/actions/builtin \u2014 list shipped built-in typed actions","POST /api/actions/builtin/:name \u2014 run a built-in with JSON body input","POST /mesh/task { peer, message }","POST /webhook/:agentId[/:source] \u2014 webhook callback","POST /reload \u2014 re-read agentx.json (hot-swaps crons)","GET /usage/plan \u2014 Claude plan windows, cold-dispatch counters, active holds","POST /usage/plan/lift \u2014 drop the active Claude plan holds","GET /daemon/restart \u2014 in-flight count, service manager, pending restart","POST /daemon/restart \u2014 restart when idle { timeoutMinutes?, onTimeout? }","POST /daemon/restart/cancel","GET /.well-known/agent-card.json","GET /call \u2014 browser UI for P2P A/V calls (requires channels.webrtc.enabled)","GET /webrtc/config \u2014 ICE servers + peer directory for the call page","GET /webrtc/events?callId=&as= \u2014 SSE stream of signaling events","POST /webrtc/signal/out \u2014 browser-originated signal, forwarded to remote peer","POST /webrtc/signal \u2014 remote-peer-originated signal, fanned out to local browser","POST /webrtc/bot/invite { callId, target, agentId } \u2014 spawn a transcribing bot peer for a call","GET /webrtc/bots \u2014 active bot sessions","POST /webrtc/camera/watch { callId, agentId } \u2014 an agent watches the phone camera share","GET /webrtc/camera/watch \u2014 agents watching a camera now","POST /webrtc/camera/watch/:id/look { note? } \u2014 ask the watching agent what it sees","POST /webrtc/camera/watch/:id/stream { seconds, note? } \u2014 the agent keeps watching for a while (0 stops)","POST /webrtc/camera/look { agentId } \u2014 from an agent's run: the newest frame as a PNG path"]})}}catch(i){this.json(t,500,{error:i.message})}}async handleOpenAICompat(e,t,n){let s=await U(e);await Xy(e,t,n,s,{execute:(i,o,a,c)=>this.registry.execute(i,o,a,c),agentIds:Object.keys(this.config.agents),cancel:(i,o,a,c)=>{let l=this.registry.list().find(d=>d.id===i)?.runningTasks.filter(d=>d.channel===o&&d.chatId===a)||[];for(let d of l)this.registry.cancelRunningTask(d.id,c)},log:i=>this.log(i)})}json(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}resolveGitlabTokenForAgent(e){if(!e)return{token:this.config.channels.gitlab?.token,source:"global"};let t=(this.config.channels.gitlab?.agentMappings||[]).find(s=>s.agentId===e);if(t?.token)return{token:t.token,source:"agentMappings"};let n=cf(this.config,e,"gitlab-user","tokenEnv");return n.status==="ok"&&n.value?{token:n.value,source:`integrations(${n.envVar})`}:this.config.channels.gitlab?.token?{token:this.config.channels.gitlab.token,source:"global"}:{token:void 0,source:n.status}}resolveTodayUsage(){let e=vw();if(e==="json")return this.registry.getTodayUsage();let t=kw(this.db);return e==="sqlite"||Object.keys(t.agents).length>0?t:this.registry.getTodayUsage()}installAgentMemorySurface(){let e=parseInt(this.config.node.bind.split(":")[1]||"18800",10);for(let t of this.registry.list()){let n=t.workspace;if(!(!n||!vn(n)))try{let s=te(n,".claude","skills");aT(s,{recursive:!0});let i=te(s,RS);if(!vn(i))Ud(i,Nl(e)),this.log(` memory-skill: installed remember.md \u2192 ${t.id}`);else{let o=CS(Ts(i,"utf-8"),e);o&&(Ud(i,o),this.log(` memory-skill: updated remember.md \u2192 ${t.id}`))}this.agentMemory.syncToWorkspace(t.id,n,this.config.session.memoryIndexMaxChars)}catch(s){this.log(` memory-skill: ${t.id} install failed \u2014 ${s?.message??s}`)}}}installAgentMcpConfig(){for(let[e,t]of Object.entries(this.config.agents)){let n=t.workspace;if(!n||!vn(n))continue;let s=this.config.workflows.enabled&&(this.config.workflows.followUp.enabled&&(this.config.workflows.followUp.agents[e]??!0)||Dg(this.config.workflows,e)),i=Qh(ah(t),this.config.requests.enabled||s?Yh():null);try{switch(Zh(n,i)){case"installed":this.log(` mcp: installed ${Object.keys(i).length} server(s) \u2192 ${e}`);break;case"updated":this.log(` mcp: updated .mcp.json (${Object.keys(i).length} server(s)) \u2192 ${e}`);break;case"removed":this.log(` mcp: removed managed .mcp.json (config now empty) \u2192 ${e}`);break;case"skipped-operator-owned":Object.keys(i).length>0&&this.log(` mcp: ${e} has operator-owned .mcp.json \u2014 skipping (delete file or marker to let agentx manage)`);break;case"noop":break}}catch(o){this.log(` mcp: ${e} install failed \u2014 ${o?.message??o}`)}}}workspaceFor(e){for(let t of this.registry.list())if(t.id===e)return t.workspace;return null}handleMemoryApi(e,t,n,s){return aS(e,t,n,s,{mem:this.agentMemory,workspaceFor:i=>this.workspaceFor(i),runningTaskOwner:i=>this.registry.runningTaskOwner(i),indexMaxChars:()=>this.config.session.memoryIndexMaxChars})}async handleWorkflowEvent(e,t){if(!this.workflowDispatcher){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let n;try{n=await se(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let s=n?.payload??n,i=s?.event,o=s?.entityRef;if(!i?.id||!o?.backend||!o?.id){this.json(t,400,{error:"missing event or entityRef"});return}let a=n?.kind;try{if(a==="trigger"&&s.trigger){let h=typeof n?.fromPeer=="string"?n.fromPeer:"unknown";this.log(`[workflows/mesh] received trigger from "${h}" source="${s.trigger.source}" chat="${s.trigger.chat??"*"}"`);let f=await this.workflowDispatcher.dispatch({trigger:s.trigger,entityRef:o,event:i,fromRemote:{peer:h}});this.log(`[workflows/mesh] dispatched broadcast: matched=${f.claimed.length} ${f.claimed.length?`(${f.claimed.map(y=>y.id).join(", ")})`:"[none \u2014 no workflow with mesh.allowRemote matched]"}`),this.json(t,202,{ok:!0,mode:"trigger-broadcast",matched:f.claimed.map(y=>y.id)});return}let d=(s.workflowId?this.workflowStore?.get(s.workflowId):null)?.nodes.find(h=>h.type.startsWith("trigger."))?.config??{},u={source:String(d.source??"hook"),project:d.filter?.project,repo:d.filter?.repo,chat:d.filter?.chat,labels:d.filter?.labels};await this.workflowDispatcher.dispatch({trigger:u,entityRef:o,event:i}),this.json(t,202,{ok:!0})}catch(c){this.log(`[workflows] /workflow/event failed: ${c.message}`),this.json(t,500,{error:c.message})}}async postToPushHost(e,t,n){let s=e.toLowerCase(),i=this.mesh?.directory().find(c=>c.peer.toLowerCase()===s);if(!i)throw new Error(`push: channels.push.relayTo "${e}" is not a mesh peer of this node`);let o=await fetch(`${i.peerUrl}${t}`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(i.peer)},body:JSON.stringify(n),signal:AbortSignal.timeout(15e3)});if(!o.ok)throw new Error(`push: ${i.peer} ${t} -> ${o.status} ${(await o.text().catch(()=>"")).slice(0,200)}`);let a=await o.json().catch(()=>({}));if(t==="/channel/send")return a.messageId??void 0;if(typeof a.status!="number")throw new Error(`push: ${i.peer} ${t} gave no answer`);return{status:a.status,body:a.body??{}}}async handlePushApp(e,t){let n;try{n=await se(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let{handlePushBridge:s,pushOrigin:i}=await import("./push-bridge-NR7SLHGX.js"),o=this.config.channels.push;if(!o?.enabled){this.json(t,200,{status:503,body:{error:`Notifications are off on ${this.config.node.name}.`}});return}if(o.relayTo){if(n?.origin!==void 0){this.json(t,200,{status:409,body:{error:`${this.config.node.name} relays its notifications too (channels.push.relayTo = ${o.relayTo})`}});return}if(n?.op!=="app"){this.json(t,400,{error:"op must be app"});return}try{this.json(t,200,await this.postToPushHost(o.relayTo,"/push/app",{op:"app",origin:i(this.config.node.name),call:n.call}))}catch(c){this.log(`[push] /push/app to ${o.relayTo} failed: ${c.message}`),this.json(t,502,{error:c.message})}return}let a=this.pushBridgeCaller(e);"error"in a&&n?.op!=="roster"&&this.log(`[push] /push/app from ${e.socket?.remoteAddress||"?"} refused: ${a.error}`),this.json(t,200,s(n,a,this.pushHost??null,this.pushHost?void 0:`Notifications are not running on ${this.config.node.name}. Check channels.push.subject and the database there.`))}pushBridgeCaller(e){return Up(String(e.headers.authorization||""),this.config.mesh.peers,process.env.MESH_TOKEN)}async handleChannelSend(e,t){let n;try{n=await se(e)}catch(l){this.json(t,400,{error:"invalid JSON body",message:l.message});return}let s=String(n?.channel??""),i=String(n?.chatId??""),o=String(n?.text??"");if(!s||!i||!o){this.json(t,400,{error:"channel, chatId, and text are required"});return}if(!this.router.getChannel(s)){this.json(t,404,{error:`channel "${s}" not hosted on this node`});return}let c;if(n.relayed===!0&&n.origin!==void 0){let l=this.pushBridgeCaller(e);if("origin"in l)c=l.origin;else if(i!=="default"){this.json(t,403,{error:l.error});return}}if(s==="push"&&i.includes(":")){let{scopedPushTarget:l}=await import("./push-bridge-NR7SLHGX.js"),d=l(i,this.pushBridgeCaller(e));if("error"in d){this.json(t,403,{error:d.error});return}}try{let l=await this.router.sendOutbound({channel:s,chatId:i,text:o,accountId:typeof n.accountId=="string"?n.accountId:void 0,parseMode:typeof n.parseMode=="string"?n.parseMode:void 0,replyTo:typeof n.replyTo=="string"?n.replyTo:void 0,buttons:Array.isArray(n.buttons)?n.buttons:void 0,agentId:typeof n.agentId=="string"?n.agentId:void 0,relayed:n.relayed===!0?!0:void 0,...n.relayed===!0?{told:{passed:!0}}:{},origin:c},{recordInSession:!1});this.json(t,200,{ok:!0,messageId:l??null})}catch(l){this.log(`[mesh] /channel/send "${s}" failed: ${l.message}`),this.json(t,500,{error:l.message})}}async handleChannelChats(e,t,n={}){let s=new Set,i=[],o=[],a=(l,d)=>{let u=0;for(let h of l)!h.id||s.has(h.id)||(s.add(h.id),i.push({...h,source:d}),u++);u>0&&o.push(`${d}:${u}`)},c=this.router.getChannel(t);if(c?.listKnownChats)try{a(c.listKnownChats(),"local")}catch{}else if(c?.listChats)try{a(c.listChats().map(l=>({id:l.jid,name:l.name,kind:l.isGroup?"group":"dm"})),"local")}catch{}if(!n.localOnly&&this.mesh){let l=this.mesh.directory().filter(d=>d.healthy&&d.channels?.includes(t));await Promise.allSettled(l.map(async d=>{try{let u=await fetch(`${d.peerUrl}/channels/${encodeURIComponent(t)}/chats?local=1`,{headers:this.mesh.authHeaders(d.peer),signal:AbortSignal.timeout(5e3)});if(!u.ok)return;let h=await u.json();Array.isArray(h.chats)&&a(h.chats.map(f=>({id:f.id,name:f.name,kind:f.kind??"dm",accountId:f.accountId})),`mesh:${d.peer}`)}catch{}}))}this.json(e,200,{channel:t,source:o.join(", ")||"none",chats:i})}async handleWorkflowManualRun(e,t,n){if(!this.workflowDispatcher||!this.workflowStore){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let s;try{s=await se(e)}catch{s={}}try{let i=await AS({get:o=>this.workflowStore.get(o),dispatchWorkflow:o=>this.workflowDispatcher.dispatchWorkflow(o),startRun:o=>this.workflowDispatcher.startRun(o)},n,s);this.json(t,i.status,i.body)}catch(i){this.log(`[workflows] manual run "${n}" failed: ${i.message}`),this.json(t,500,{error:i.message})}}},Gd=Hd;jt(Gd,"MESH_PROTECTED_PATHS",new Set(["/task","/ask","/mesh/task","/mesh/inbox/send","/workflow/event","/workflow/transition","/channel/send","/push/app","/webrtc/signal","/gitlab/react","/gitlab/send-note","/gitlab/log-time","/channel/edit-comment","/github/send-comment"]));function hj(r){if(typeof r!="string")return"";let e=r.trim();if(!e)return"";let t=e.match(/^[^.!?\n]+[.!?]?/),n=(t?t[0]:e).trim();return n.length>140?n.slice(0,137)+"\u2026":n}function se(r){return new Promise((e,t)=>{let n="";r.setEncoding("utf8"),r.on("data",s=>{n+=s}),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch(s){t(s)}}),r.on("error",t)})}function gj(r,e){let t=["model","workspace","tier","permissionMode","mcpServers"],n=new Set,s=new Set([...Object.keys(r),...Object.keys(e)]);for(let i of s){let o=r[i],a=e[i];if(!o||!a){n.add("add/remove");continue}for(let c of t)JSON.stringify(o[c])!==JSON.stringify(a[c])&&n.add(`${i}.${c}`)}return Array.from(n).slice(0,6)}async function U(r){return new Promise((e,t)=>{let n="";r.on("data",s=>n+=s.toString()),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch{e({})}}),r.on("error",t)})}function cT(r){let e=r.business;return JSON.stringify([e?.roles,e?.orgChart,e?.relations,e?.projects,(r.people??[]).map(t=>t.id)])}dT();function rY(r){typeof r=="string"&&(As.error(r),process.exit(1)),r instanceof Error&&(As.error(r.message),process.exit(1)),As.error("Something went wrong. Please try again."),process.exit(1)}export{Pj as a,ic as b,It as c,Wn as d,Gn as e,At as f,wr as g,fy as h,cw as i,yR as j,wR as k,gw as l,Te as m,mw as n,yw as o,Fr as p,I2 as q,T2 as r,Zr as s,GU as t,PC as u,_C as v,Zc as w,gb as x,HU as y,$b as z,OC as A,Ib as B,Tb as C,xb as D,BU as E,qU as F,XU as G,oi as H,eP as I,je as J,tH as K,DP as L,qk as M,Xk as N,S_ as O,lv as P,gv as Q,dM as R,El as S,JB as T,KB as U,zB as V,mS as W,GM as X,t4 as Y,n4 as Z,as as _,un as $,cs as aa,A4 as ba,VS as ca,PO as da,bq as ea,Xi as fa,Kl as ga,zl as ha,Yi as ia,we as ja,j0 as ka,to as la,CD as ma,Y0 as na,_D as oa,t$ as pa,ro as qa,ms as ra,co as sa,uo as ta,a$ as ua,dd as va,p$ as wa,dt as xa,Ee as ya,b$ as za,k$ as Aa,v$ as Ba,S$ as Ca,Co as Da,wI as Ea,_d as Fa,kI as Ga,mL as Ha,U3 as Ia,Gd as Ja,rY as Ka};
1339
- //# sourceMappingURL=chunk-IXUG76KI.js.map
1339
+ //# sourceMappingURL=chunk-UU77SLIS.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-UQUMJH2Q.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-5LBTVRBW.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{Ja as Tt,Ka 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-IXUG76KI.js";import"./chunk-7BA4KCRW.js";import"./chunk-GTJIKXDB.js";import"./chunk-JE5KSD6Z.js";import"./chunk-ZVP6GB4G.js";import"./chunk-J522P3Z3.js";import"./chunk-IMLAPB7G.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-H7VI7OTS.js";import"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-BIYEGA7Q.js";import"./chunk-XPZSEDE3.js";import"./chunk-PPUN7YHA.js";import"./chunk-A5GYG56I.js";import"./chunk-EGKOB3ZM.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import"./chunk-MNG2AMKZ.js";import"./chunk-RX5O5637.js";import"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import"./chunk-QPABR72X.js";import"./chunk-WXJ25XH2.js";import"./chunk-AJ5HMDRW.js";import"./chunk-KP7KDLZ2.js";import{m as lt,n as ct,o as dt,p as mt,q as pt,ya as yt}from"./chunk-POK4IPY3.js";import"./chunk-BSQIPD6F.js";import"./chunk-MEFPXHQJ.js";import{a as L}from"./chunk-BAXGL6TY.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-WILRVP4X.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import"./chunk-SZDACK6O.js";import"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-VJVXEVZ7.js";import{t as ut}from"./chunk-C5OCJCDC.js";import"./chunk-2MFBCDWL.js";import"./chunk-3UOTLMXD.js";import"./chunk-BE64IJWM.js";import"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import"./chunk-ZJNEJRUU.js";import{a as ht}from"./chunk-ZYZ4VQUD.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QBR6TGRW.js";import"./chunk-JTFCU5LH.js";import{f as gt,g as ft}from"./chunk-URWRA3EO.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-YHRQQ4DB.js";import{j as it,k as rt,l as at}from"./chunk-SOVWD6TL.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-QUFIUXMQ.js";import"./chunk-AV7T3SYT.js";import"./chunk-LE3BXIUF.js";import"./chunk-BERWTVG2.js";import"./chunk-AHWWJ7AF.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{Gb as nt,vb as tt,xb as st,zb as ot}from"./chunk-XIGFRLU5.js";import"./chunk-VJ5HC63R.js";import"./chunk-UEEB3UTU.js";import"./chunk-VQRY4IDI.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
1
+ import{Ja as Tt,Ka 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-UU77SLIS.js";import"./chunk-7BA4KCRW.js";import"./chunk-GTJIKXDB.js";import"./chunk-JE5KSD6Z.js";import"./chunk-ZVP6GB4G.js";import"./chunk-J522P3Z3.js";import"./chunk-IMLAPB7G.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-H7VI7OTS.js";import"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-BIYEGA7Q.js";import"./chunk-XPZSEDE3.js";import"./chunk-PPUN7YHA.js";import"./chunk-A5GYG56I.js";import"./chunk-EGKOB3ZM.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import"./chunk-MNG2AMKZ.js";import"./chunk-RX5O5637.js";import"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import"./chunk-QPABR72X.js";import"./chunk-WXJ25XH2.js";import"./chunk-AJ5HMDRW.js";import"./chunk-KP7KDLZ2.js";import{m as lt,n as ct,o as dt,p as mt,q as pt,ya as yt}from"./chunk-POK4IPY3.js";import"./chunk-BSQIPD6F.js";import"./chunk-MEFPXHQJ.js";import{a as L}from"./chunk-BAXGL6TY.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-WILRVP4X.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import"./chunk-SZDACK6O.js";import"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-VJVXEVZ7.js";import{t as ut}from"./chunk-C5OCJCDC.js";import"./chunk-2MFBCDWL.js";import"./chunk-3UOTLMXD.js";import"./chunk-BE64IJWM.js";import"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import"./chunk-ZJNEJRUU.js";import{a as ht}from"./chunk-ZYZ4VQUD.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QBR6TGRW.js";import"./chunk-JTFCU5LH.js";import{f as gt,g as ft}from"./chunk-URWRA3EO.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-YHRQQ4DB.js";import{j as it,k as rt,l as at}from"./chunk-SOVWD6TL.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-QUFIUXMQ.js";import"./chunk-AV7T3SYT.js";import"./chunk-LE3BXIUF.js";import"./chunk-BERWTVG2.js";import"./chunk-AHWWJ7AF.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{Gb as nt,vb as tt,xb as st,zb as ot}from"./chunk-XIGFRLU5.js";import"./chunk-VJ5HC63R.js";import"./chunk-UEEB3UTU.js";import"./chunk-VQRY4IDI.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
2
2
  `)}
3
3
 
4
4
  ${t}`}async function It(o){let{loadLocalSkills:e}=await import("./loader-YFVSSYSL.js");return e(o)}async function Ot(o,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
@@ -1,4 +1,4 @@
1
- import{a as kh,b as Vi,g as vh}from"./chunk-Z55PWDYH.js";import{b as yh}from"./chunk-YJDQK22T.js";import{$ as oh,A as Df,B as Mf,C as Lf,E as lo,G as Uf,H as Wf,I as Gf,J as zf,L as Yf,M as Kf,N as Xf,O as bl,P as Vf,U as Qf,V as Zf,W as $l,X as eh,_ as th,aa as nh,ba as sh,ca as ch,da as lh,ea as dh,ga as kl,ha as uh,ja as gh,ka as mh,l as Cf,la as ph,m as Tf,q as Of,r as If,t as Nf,v as Rs,w as Cs,x as jf,y as _f,z as Pf}from"./chunk-FM5VBO3D.js";import{n as vl}from"./chunk-A5KZSTYI.js";import{a as fh,b as hh,d as xr,e as wh}from"./chunk-OBVLO6FV.js";import{a as bh,b as $h}from"./chunk-YLCMN4OA.js";import"./chunk-EFGAPAYZ.js";import{d as Bf,e as yl,h as Jf,i as Hf}from"./chunk-CTN4KYE6.js";import{a as rh,c as ih,d as ah}from"./chunk-TADIDWYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{a as _t}from"./chunk-U2OGZDAN.js";import{a as qf,c as Ff}from"./chunk-FKT34MQ7.js";import{a as hl}from"./chunk-LNY6N73E.js";import{a as _m,b as Kc}from"./chunk-CZMVJP7O.js";import{a as Jc,b as fm}from"./chunk-RKPAVWXF.js";import{$ as ef,A as Rp,Aa as vr,B as ol,Ba as ml,C as Cp,Ca as vf,D as Tp,Da as Sf,E as Op,Ea as fl,F as Ip,Fa as Ef,G as Np,Ga as Ki,H as jp,Ha as Es,I as nl,Ia as Xi,J as Ui,Ja as wl,K as _p,Ka as Rf,L as sl,M as Pp,N as Dp,O as Mp,P as Lp,Q as qp,R as Wi,S as Jp,T as zp,U as Yp,V as Kp,W as Xp,X as Vp,Y as il,Z as Qp,_ as Zp,a as Pm,aa as tf,b as Dm,ba as of,ca as nf,da as sf,ea as rf,fa as mf,ga as Hi,h as Ri,ha as Co,i as Fm,ia as Jo,j as yr,ja as xs,k as Ci,ka as Gi,l as Wm,la as zi,m as Jm,ma as gl,n as op,na as pf,o as np,oa as ff,p as _i,pa as hf,q as Zc,qa as wf,r as dp,ra as yf,s as kp,sa as bf,t as vp,ta as Ss,u as xp,ua as As,v as Sp,va as $f,w as Fi,wa as kr,x as Ap,xa as kf,y as Ep,ya as ut,z as tl,za as Yi}from"./chunk-IXUG76KI.js";import{$a as cf,Gb as xf,Hb as pl,Oa as br,Q as hp,Ra as al,S as Li,Sa as Bi,T as wp,Ta as af,Vb as co,W as yp,X as qi,Xb as Af,_a as Bo,ab as cl,cb as ll,ea as Fp,eb as lf,fa as Up,fb as df,ga as Wp,gb as $r,ha as rl,ka as Bp,kb as Ji,nb as uf,ob as gf,pb as dl,v as Bm,wb as ul}from"./chunk-7BA4KCRW.js";import"./chunk-GTJIKXDB.js";import{a as Mm,c as Xc,e as Lm,f as qm}from"./chunk-JE5KSD6Z.js";import"./chunk-ZVP6GB4G.js";import{F as Ii,G as ep,H as tp,L as bp,M as $p,a as Wc,b as lm,e as dm,f as um,n as Ti,o as Oi,p as Hm,q as Gm,r as zm,t as Ym,u as Km,w as Xm,x as Vm,y as Qm,z as Zm}from"./chunk-J522P3Z3.js";import"./chunk-IMLAPB7G.js";import"./chunk-VZLIBDLH.js";import{a as Hp,b as Gp}from"./chunk-EKJG63EJ.js";import"./chunk-H7VI7OTS.js";import{c as sp}from"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import{b as Qc}from"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import{c as rp,e as Ni,g as ji}from"./chunk-LQE73AZR.js";import{a as ip,b as ap,c as cp,d as lp}from"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-BIYEGA7Q.js";import{d as up,e as $n,f as gp,g as Pi,j as mp,k as pp,m as fp,n as el,q as Di,r as Ro,s as Mi}from"./chunk-XPZSEDE3.js";import"./chunk-PPUN7YHA.js";import"./chunk-A5GYG56I.js";import{a as Vc,p as Um}from"./chunk-EGKOB3ZM.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as jt}from"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import{a as ao}from"./chunk-MNG2AMKZ.js";import{a as xm,b as Sm,c as Am,d as Em,e as Gc,f as Rm,g as zc,h as Yc,l as Cm,m as Tm}from"./chunk-RX5O5637.js";import{f as Om,i as Im,l as Nm,m as jm}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{a as Bc,d as gm,e as Ei}from"./chunk-QPABR72X.js";import{a as wr,e as hm,f as wm,g as Hc,i as ym,j as bm,l as $m,m as km,n as vm}from"./chunk-WXJ25XH2.js";import{b as vs,e as pm}from"./chunk-AJ5HMDRW.js";import{c as mm}from"./chunk-KP7KDLZ2.js";import{B as Mc,C as Bg,O as Wo,U as sm,X as im,Y as am,g as Pg,r as Dg,ya as cm}from"./chunk-POK4IPY3.js";import{I as ws,J as Si,K as Ai,L as ys,M as Hg,N as Fo,P as Uo,b as hs,fa as om,r as Ao,s as Lc,t as Jg,u as qc,ua as nm,w as Eo,wa as rm,x as xi}from"./chunk-BSQIPD6F.js";import{b as yn}from"./chunk-MEFPXHQJ.js";import"./chunk-WILRVP4X.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{c as zg}from"./chunk-SZDACK6O.js";import{f as Yg,g as Kg,h as Fc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as Vg,f as bn,k as $s}from"./chunk-VJVXEVZ7.js";import{a as Ug,k as Xg,n as tm}from"./chunk-C5OCJCDC.js";import{a as wt,b as me,c as Ue,d as ks,e as Qg}from"./chunk-2MFBCDWL.js";import{a as Zg,b as Uc,h as em}from"./chunk-3UOTLMXD.js";import{i as Lg,j as qg}from"./chunk-BE64IJWM.js";import"./chunk-PE5V2LI7.js";import{a as Dc,b as Fg}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Wg}from"./chunk-X5C5W3E4.js";import{a as bs}from"./chunk-GV7S5BAX.js";import{e as Gg}from"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import{a as Pc}from"./chunk-ZJNEJRUU.js";import"./chunk-ZYZ4VQUD.js";import{c as Mg}from"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QBR6TGRW.js";import"./chunk-JTFCU5LH.js";import{g as qo,i as vi}from"./chunk-URWRA3EO.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-YHRQQ4DB.js";import{a as Cc,b as sg,c as Dx,d as pi,e as rg,f as Rg,g as Hx,h as Cg,i as Gx,m as fs,n as Og,q as Ig,u as Ng,y as io,z as hr}from"./chunk-SOVWD6TL.js";import{a as So,b as ps,e as Sg,f as fr}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as ki,b as Tg}from"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import{h as Lo,j as jg}from"./chunk-QUFIUXMQ.js";import{n as _g}from"./chunk-AV7T3SYT.js";import"./chunk-LE3BXIUF.js";import"./chunk-BERWTVG2.js";import"./chunk-AHWWJ7AF.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as ro,b as Px}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as yi,$a as _c,Da as $g,F as Oc,G as Fx,Gb as te,Ha as Wx,Qa as kg,Ra as wn,Ta as Nc,U as pg,V as Ux,_ as wi,_a as jc,bb as vg,c as fi,ca as fg,cb as Bx,d as ig,da as hg,e as fn,ea as ms,f as Tc,fa as Ic,h as ag,hb as xg,i as hi,j as Mx,ma as wg,oa as yg,pa as bg,r as lg,s as dg,t as ug,u as gg,v as mg,vb as bi,w as qx,wb as pr,xb as O,zb as $i}from"./chunk-XIGFRLU5.js";import"./chunk-VJ5HC63R.js";import{j as dt,r as hn}from"./chunk-UEEB3UTU.js";import{a as cg,e as Lx}from"./chunk-VQRY4IDI.js";import{g as Ag,k as Eg,l as Jx}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as zx}from"commander";var xh=new zx().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 Dm({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()});te();import{Command as Yx}from"commander";import{execFileSync as Jt}from"node:child_process";import{cpSync as Sh,existsSync as Al,mkdirSync as xl,mkdtempSync as Kx,readdirSync as Xx,rmSync as Ah,writeFileSync as Eh}from"node:fs";import{dirname as Rh,join as gt}from"node:path";import{homedir as Qi,release as Vx,tmpdir as Qx}from"node:os";import{setTimeout as Zx}from"node:timers/promises";function Zi(){let e=Hm(process.platform,process.arch,Vx());if(e)throw new Error(e)}function ea(){let e=gt(Qi(),"Library/LaunchAgents"),t=[];try{t=Xx(e).filter(Ym)}catch{}let o=t.flatMap(n=>{let s=gt(e,n);try{return[{file:s,plist:Jt("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Km(e,o)}function Sr(e){return`gui/${process.getuid()}/${e.label}`}async function Sl(e){try{Jt("launchctl",["bootout",Sr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{Jt("launchctl",["print",Sr(e)],{stdio:"pipe"})}catch{return}await Zx(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Ch(e){if(!Al(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{Jt("launchctl",["print",Sr(e)],{stdio:"pipe"})}catch{t=!1}t||Jt("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),Jt("launchctl",["kickstart",Sr(e)],{stdio:"pipe"})}function e0(){let e=Zm();if(e&&Al(gt(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 Ts=new Yx("desktop").description("install and control the macOS desktop assistant");Ts.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=>{Zi();let t=O(),o=Gm(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=e0(),i=gt(Qi(),"Applications"),{keep:a,remove:c}=ea();if(console.log(`Desktop assistant \u2192 ${gt(i,Ti)}
1
+ import{a as kh,b as Vi,g as vh}from"./chunk-Z55PWDYH.js";import{b as yh}from"./chunk-YJDQK22T.js";import{$ as oh,A as Df,B as Mf,C as Lf,E as lo,G as Uf,H as Wf,I as Gf,J as zf,L as Yf,M as Kf,N as Xf,O as bl,P as Vf,U as Qf,V as Zf,W as $l,X as eh,_ as th,aa as nh,ba as sh,ca as ch,da as lh,ea as dh,ga as kl,ha as uh,ja as gh,ka as mh,l as Cf,la as ph,m as Tf,q as Of,r as If,t as Nf,v as Rs,w as Cs,x as jf,y as _f,z as Pf}from"./chunk-FM5VBO3D.js";import{n as vl}from"./chunk-A5KZSTYI.js";import{a as fh,b as hh,d as xr,e as wh}from"./chunk-OBVLO6FV.js";import{a as bh,b as $h}from"./chunk-YLCMN4OA.js";import"./chunk-EFGAPAYZ.js";import{d as Bf,e as yl,h as Jf,i as Hf}from"./chunk-CTN4KYE6.js";import{a as rh,c as ih,d as ah}from"./chunk-TADIDWYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{a as _t}from"./chunk-U2OGZDAN.js";import{a as qf,c as Ff}from"./chunk-FKT34MQ7.js";import{a as hl}from"./chunk-LNY6N73E.js";import{a as _m,b as Kc}from"./chunk-CZMVJP7O.js";import{a as Jc,b as fm}from"./chunk-RKPAVWXF.js";import{$ as ef,A as Rp,Aa as vr,B as ol,Ba as ml,C as Cp,Ca as vf,D as Tp,Da as Sf,E as Op,Ea as fl,F as Ip,Fa as Ef,G as Np,Ga as Ki,H as jp,Ha as Es,I as nl,Ia as Xi,J as Ui,Ja as wl,K as _p,Ka as Rf,L as sl,M as Pp,N as Dp,O as Mp,P as Lp,Q as qp,R as Wi,S as Jp,T as zp,U as Yp,V as Kp,W as Xp,X as Vp,Y as il,Z as Qp,_ as Zp,a as Pm,aa as tf,b as Dm,ba as of,ca as nf,da as sf,ea as rf,fa as mf,ga as Hi,h as Ri,ha as Co,i as Fm,ia as Jo,j as yr,ja as xs,k as Ci,ka as Gi,l as Wm,la as zi,m as Jm,ma as gl,n as op,na as pf,o as np,oa as ff,p as _i,pa as hf,q as Zc,qa as wf,r as dp,ra as yf,s as kp,sa as bf,t as vp,ta as Ss,u as xp,ua as As,v as Sp,va as $f,w as Fi,wa as kr,x as Ap,xa as kf,y as Ep,ya as ut,z as tl,za as Yi}from"./chunk-UU77SLIS.js";import{$a as cf,Gb as xf,Hb as pl,Oa as br,Q as hp,Ra as al,S as Li,Sa as Bi,T as wp,Ta as af,Vb as co,W as yp,X as qi,Xb as Af,_a as Bo,ab as cl,cb as ll,ea as Fp,eb as lf,fa as Up,fb as df,ga as Wp,gb as $r,ha as rl,ka as Bp,kb as Ji,nb as uf,ob as gf,pb as dl,v as Bm,wb as ul}from"./chunk-7BA4KCRW.js";import"./chunk-GTJIKXDB.js";import{a as Mm,c as Xc,e as Lm,f as qm}from"./chunk-JE5KSD6Z.js";import"./chunk-ZVP6GB4G.js";import{F as Ii,G as ep,H as tp,L as bp,M as $p,a as Wc,b as lm,e as dm,f as um,n as Ti,o as Oi,p as Hm,q as Gm,r as zm,t as Ym,u as Km,w as Xm,x as Vm,y as Qm,z as Zm}from"./chunk-J522P3Z3.js";import"./chunk-IMLAPB7G.js";import"./chunk-VZLIBDLH.js";import{a as Hp,b as Gp}from"./chunk-EKJG63EJ.js";import"./chunk-H7VI7OTS.js";import{c as sp}from"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import{b as Qc}from"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import{c as rp,e as Ni,g as ji}from"./chunk-LQE73AZR.js";import{a as ip,b as ap,c as cp,d as lp}from"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-BIYEGA7Q.js";import{d as up,e as $n,f as gp,g as Pi,j as mp,k as pp,m as fp,n as el,q as Di,r as Ro,s as Mi}from"./chunk-XPZSEDE3.js";import"./chunk-PPUN7YHA.js";import"./chunk-A5GYG56I.js";import{a as Vc,p as Um}from"./chunk-EGKOB3ZM.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as jt}from"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import{a as ao}from"./chunk-MNG2AMKZ.js";import{a as xm,b as Sm,c as Am,d as Em,e as Gc,f as Rm,g as zc,h as Yc,l as Cm,m as Tm}from"./chunk-RX5O5637.js";import{f as Om,i as Im,l as Nm,m as jm}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{a as Bc,d as gm,e as Ei}from"./chunk-QPABR72X.js";import{a as wr,e as hm,f as wm,g as Hc,i as ym,j as bm,l as $m,m as km,n as vm}from"./chunk-WXJ25XH2.js";import{b as vs,e as pm}from"./chunk-AJ5HMDRW.js";import{c as mm}from"./chunk-KP7KDLZ2.js";import{B as Mc,C as Bg,O as Wo,U as sm,X as im,Y as am,g as Pg,r as Dg,ya as cm}from"./chunk-POK4IPY3.js";import{I as ws,J as Si,K as Ai,L as ys,M as Hg,N as Fo,P as Uo,b as hs,fa as om,r as Ao,s as Lc,t as Jg,u as qc,ua as nm,w as Eo,wa as rm,x as xi}from"./chunk-BSQIPD6F.js";import{b as yn}from"./chunk-MEFPXHQJ.js";import"./chunk-WILRVP4X.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{c as zg}from"./chunk-SZDACK6O.js";import{f as Yg,g as Kg,h as Fc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as Vg,f as bn,k as $s}from"./chunk-VJVXEVZ7.js";import{a as Ug,k as Xg,n as tm}from"./chunk-C5OCJCDC.js";import{a as wt,b as me,c as Ue,d as ks,e as Qg}from"./chunk-2MFBCDWL.js";import{a as Zg,b as Uc,h as em}from"./chunk-3UOTLMXD.js";import{i as Lg,j as qg}from"./chunk-BE64IJWM.js";import"./chunk-PE5V2LI7.js";import{a as Dc,b as Fg}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Wg}from"./chunk-X5C5W3E4.js";import{a as bs}from"./chunk-GV7S5BAX.js";import{e as Gg}from"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import{a as Pc}from"./chunk-ZJNEJRUU.js";import"./chunk-ZYZ4VQUD.js";import{c as Mg}from"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QBR6TGRW.js";import"./chunk-JTFCU5LH.js";import{g as qo,i as vi}from"./chunk-URWRA3EO.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-YHRQQ4DB.js";import{a as Cc,b as sg,c as Dx,d as pi,e as rg,f as Rg,g as Hx,h as Cg,i as Gx,m as fs,n as Og,q as Ig,u as Ng,y as io,z as hr}from"./chunk-SOVWD6TL.js";import{a as So,b as ps,e as Sg,f as fr}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as ki,b as Tg}from"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import{h as Lo,j as jg}from"./chunk-QUFIUXMQ.js";import{n as _g}from"./chunk-AV7T3SYT.js";import"./chunk-LE3BXIUF.js";import"./chunk-BERWTVG2.js";import"./chunk-AHWWJ7AF.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as ro,b as Px}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as yi,$a as _c,Da as $g,F as Oc,G as Fx,Gb as te,Ha as Wx,Qa as kg,Ra as wn,Ta as Nc,U as pg,V as Ux,_ as wi,_a as jc,bb as vg,c as fi,ca as fg,cb as Bx,d as ig,da as hg,e as fn,ea as ms,f as Tc,fa as Ic,h as ag,hb as xg,i as hi,j as Mx,ma as wg,oa as yg,pa as bg,r as lg,s as dg,t as ug,u as gg,v as mg,vb as bi,w as qx,wb as pr,xb as O,zb as $i}from"./chunk-XIGFRLU5.js";import"./chunk-VJ5HC63R.js";import{j as dt,r as hn}from"./chunk-UEEB3UTU.js";import{a as cg,e as Lx}from"./chunk-VQRY4IDI.js";import{g as Ag,k as Eg,l as Jx}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as zx}from"commander";var xh=new zx().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 Dm({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()});te();import{Command as Yx}from"commander";import{execFileSync as Jt}from"node:child_process";import{cpSync as Sh,existsSync as Al,mkdirSync as xl,mkdtempSync as Kx,readdirSync as Xx,rmSync as Ah,writeFileSync as Eh}from"node:fs";import{dirname as Rh,join as gt}from"node:path";import{homedir as Qi,release as Vx,tmpdir as Qx}from"node:os";import{setTimeout as Zx}from"node:timers/promises";function Zi(){let e=Hm(process.platform,process.arch,Vx());if(e)throw new Error(e)}function ea(){let e=gt(Qi(),"Library/LaunchAgents"),t=[];try{t=Xx(e).filter(Ym)}catch{}let o=t.flatMap(n=>{let s=gt(e,n);try{return[{file:s,plist:Jt("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Km(e,o)}function Sr(e){return`gui/${process.getuid()}/${e.label}`}async function Sl(e){try{Jt("launchctl",["bootout",Sr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{Jt("launchctl",["print",Sr(e)],{stdio:"pipe"})}catch{return}await Zx(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Ch(e){if(!Al(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{Jt("launchctl",["print",Sr(e)],{stdio:"pipe"})}catch{t=!1}t||Jt("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),Jt("launchctl",["kickstart",Sr(e)],{stdio:"pipe"})}function e0(){let e=Zm();if(e&&Al(gt(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 Ts=new Yx("desktop").description("install and control the macOS desktop assistant");Ts.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=>{Zi();let t=O(),o=Gm(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=e0(),i=gt(Qi(),"Applications"),{keep:a,remove:c}=ea();if(console.log(`Desktop assistant \u2192 ${gt(i,Ti)}
2
2
  Computer-use helper \u2192 ${gt(i,Oi)}
3
3
  Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
4
4
  Daemon \u2192 ${s}
@@ -564,7 +564,7 @@ ${oe.text}`));T.delivery.reached.of++,ie&&T.delivery.reached.n++;let j=P[0]??Q[0
564
564
  Plan ${q.dim(`[${r.state}] by ${r.createdBy}, ${Vn(r.createdAt)}`)}`),ak(s.steps(e)),console.log(`
565
565
  Log`);for(let i of s.events(e))console.log(q.dim(` ${Vn(i.at)} ${i.step?`step ${i.step} `:""}${i.kind}: ${i.detail}`))}});sn.command("step <id> <step>").description("move a step of a request's plan on: --retry, --skip or --done").option("--retry","hand the step to its agent again, with a fresh count of nudges (approves a message whose card expired)").option("--skip","leave the step out; the plan goes on with the next one").option("--done","mark the step done yourself").option("--note <text>","why, or the evidence for --done").action((e,t,o)=>{let n=["retry","skip","done"].filter(c=>o[c]);if(n.length!==1){console.error(q.red(" give one of --retry, --skip or --done")),process.exitCode=1;return}let s=Kr();if(!s)return;let r=Va();if(!r){process.exitCode=1;return}let i=Number(t),a=_p(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)")),ak(r.steps(e))});function ck(e,t,o,n){let s=sn.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=Kr();if(!a)return;let c=e==="done"?i.evidence??(i.reason?`closed by owner: ${i.reason}`:void 0):i.reason??"dropped by the owner";if(!c){console.error(q.red(` ${n}`)),process.exitCode=1;return}let l=a.get(r);if(!l||l.state==="candidate"){console.error(q.red(` no request "${r}"`)),process.exitCode=1;return}if(!a.close(r,e==="done"?"done":"dropped",c,Date.now())){console.error(q.red(` ${r} is already closed (${su[l.state]??l.state})`)),process.exitCode=1;return}console.log(q.green(` \u2713 ${r} ${e==="done"?"closed as done":"dropped"}`))})}ck("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>");ck("drop","drop a request you no longer want","--reason <text>","");sn.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 (${wi.join(", ")}); "none" to turn them all off`).option("--check-every <minutes>","how often each open loop's check runs").action(async e=>{let t={};try{let l=(g,h)=>{if(h===void 0)return;let w=Number(h);if(!(w>0))throw new Error(`${g} must be a positive number`);return w},u=(g,h)=>g===void 0?void 0:g===h?[]:g.split(",").map(w=>w.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");t.enabled=e.enabled==="on"}if(t.from=u(e.from,"none"),t.channels=u(e.channels,"all"),t.staleAfterHours=l("--stale-hours",e.staleHours),t.retentionDays=l("--retention-days",e.retentionDays),e.headlines!==void 0){if(e.headlines!=="on"&&e.headlines!=="off")throw new Error("--headlines takes on or off");t.headlines={enabled:e.headlines==="on"}}if(e.catch!==void 0||e.catchCap!==void 0){if(e.catch!==void 0&&e.catch!=="on"&&e.catch!=="off")throw new Error("--catch takes on or off");let g=l("--catch-cap",e.catchCap);if(g!==void 0&&!Number.isInteger(g))throw new Error("--catch-cap must be a whole number");t.catchPromises={...e.catch!==void 0?{enabled:e.catch==="on"}:{},...g!==void 0?{dailyCap:g}:{}}}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 d={};if(e.plans!==void 0){if(e.plans!=="on"&&e.plans!=="off")throw new Error("--plans takes on or off");d.enabled=e.plans==="on"}if(d.stallMinutes=l("--stall-minutes",e.stallMinutes),e.maxNudges!==void 0){let g=Number(e.maxNudges);if(!Number.isInteger(g)||g<0)throw new Error("--max-nudges must be a whole number, 0 or more");d.maxNudges=g}if(d.approveKinds=u(e.approveKinds,"none"),d.disabledAgents=u(e.plansOffFor,"none"),d.requireForWork=u(e.planFor,"none"),e.planOver!==void 0){let g=Number(e.planOver);if(!(g>=0))throw new Error("--plan-over must be a number of minutes, 0 or more");d.requireOverMinutes=g}Object.values(d).some(g=>g!==void 0)&&(t.plans=d);let f={},p=u(e.checks,"none");if(p){let g=p.filter(h=>!wi.includes(h));if(g.length)throw new Error(`unknown check ${g.join(", ")}: use ${wi.join(", ")}`);f.enabled=p}f.checkEveryMinutes=l("--check-every",e.checkEvery),Object.values(f).some(g=>g!==void 0)&&(t.checkers=f)}catch(l){console.error(q.red(` ${l.message}`)),process.exitCode=1;return}if(Object.values(t).some(l=>l!==void 0)){let l=await wp(t);if(!l.success){console.error(q.red(` ${l.error}`)),process.exitCode=1;return}console.log(q.green(" \u2713 saved")+(l.reloaded?q.dim(" (daemon reloaded)"):""))}let o=Li();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??Ui;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??Ui.requireOverMinutes,i=s.requireForWork??Ui.requireForWork;console.log(` Plan before starting ${[i.length?`${i.join(", ")} work`:"",r>0?`work over ${r} minute(s)`:""].filter(Boolean).join("; ")||"never required"}`);let a=o.checkers??yi;console.log(` Loop checks ${a.enabled.length?a.enabled.join(", "):"off"}, every ${a.checkEveryMinutes} minute(s)`);let c=Object.keys(a.repos);console.log(` Repos for git-ancestor ${c.length?c.join(", "):"none (requests.checkers.repos in agentx.json)"}`)});import{Command as yO}from"commander";import er from"chalk";te();var lk=new yO("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",$l.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(er.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await me(r=>{n=eh(r,e,t==="on")});s.success||(console.error(er.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(er.green(`\u2713 ${n}`)),s.reloaded&&console.log(er.dim(" daemon hot-reloaded"))}let o=O().requestStatus.channels.map(n=>n.toLowerCase());for(let n of $l)console.log(` ${n.padEnd(8)} ${o.includes(n)?er.green("on"):er.dim("off")}`)});import{Command as zO}from"commander";import tr from"chalk";import ve from"chalk";import Xr from"prompts";import{readFileSync as bO,writeFileSync as $O,existsSync as kO}from"fs";import{resolve as dk}from"path";var vO=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function xO(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function iu(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function uk(e=".env"){let t=dk(e);if(!kO(t))return[];let o=bO(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(vO);r?n.push({kind:"kv",key:r[1],value:xO(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function SO(e){return e.map(t=>t.kind==="kv"?`${t.key}=${iu(t.value)}`:t.raw).join(`
566
566
  `)+`
567
- `}function Qn(e,t,o=".env"){let n=dk(o),s=uk(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${iu(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${iu(t)}`})),$O(n,SO(s))}function au(e,t=".env"){return uk(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var gk="https://t.me/BotFather";async function AO(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 EO(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 mk(e={}){console.log(),console.log(ve.bold(" Connect Telegram")),console.log(),console.log(ve.dim(` 1. Open ${gk}`)),console.log(ve.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ve.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await Xr({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&To(gk);let{token:o}=await Xr({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:S=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(S.trim())||"That doesn't look like a Telegram token"});o||(console.log(ve.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await AO(o.trim());n||(console.log(ve.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ve.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(ve.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(ve.red(" No agents configured. Run: agentx agent add")),process.exit(1));let u=e.agent;u||(u=(await Xr({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(x=>({title:x,value:x})),initial:0})).agent),u||(console.log(ve.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||u;d[f]&&d[f].agentBinding!==u&&(f=(await Xr({type:"text",name:"account",message:`Account "${f}" 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),f||(console.log(ve.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Qn(p,o.trim()),process.env[p]=o.trim();let g=await me(S=>{Ue(S,"channels.telegram.enabled",!0),Ue(S,`channels.telegram.accounts.${f}`,{token:`\${${p}}`,agentBinding:u});let x=ks(S,`agents.${u}.mentions`)||[],k=`@${n.username}`;x.includes(k)||(x.push(k),Ue(S,`agents.${u}.mentions`,x))},{configPath:e.configPath});if(g.success||(console.log(ve.red(` \u2717 ${g.error}`)),process.exit(1)),console.log(),console.log(ve.green(` \u2713 Bot @${n.username} bound to agent "${u}"`)),console.log(ve.dim(` Token stored in .env as ${p}`)),console.log(ve.dim(` Mentions updated to include @${n.username}`)),g.reloaded?console.log(ve.dim(" Daemon hot-reloaded.")):console.log(ve.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Xr({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(ve.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ve.dim(" Waiting up to 90s..."));let w=await EO(o.trim(),9e4);if(!w){console.log(ve.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ve.dim(" agentx config set notifications.destination.channel telegram")),console.log(ve.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ve.dim(` agentx config set notifications.destination.accountId ${f}`));return}let y={channel:"telegram",chatId:String(w.chatId),accountId:f},$=[],v=await me(S=>{Ue(S,"notifications.destination",y),$=ca(S,y)},{configPath:e.configPath});if(!v.success){console.log(ve.red(` \u2717 failed to save destination: ${v.error}`));return}console.log(ve.green(" \u2713 Default --notify target set")),console.log(ve.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ve.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(ve.dim(` Schedules that now report here: ${$.join(", ")}`)),v.reloaded&&console.log(ve.dim(" Daemon hot-reloaded."))}import Me from"chalk";import cu from"prompts";import{existsSync as du,mkdirSync as RO,readdirSync as CO,readFileSync as pk}from"fs";import{resolve as lu}from"path";var TO=".agentx/whatsapp-sessions";function OO(){let e=lu(process.cwd(),".agentx/daemon.pid");if(!du(e))return!1;try{let t=parseInt(pk(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function IO(e){if(!du(e))return!1;try{return CO(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function NO(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Me.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Me.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;RO(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(u=>{let f=setTimeout(()=>{t(Me.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}u(!1)},12e4);l.ev.on("connection.update",async p=>{if(p.qr){t(Me.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:g}=await import("qrcode-terminal");g.generate(p.qr,{small:!0})}catch{t(` QR: ${p.qr}`)}t("")}if(p.connection==="open"){clearTimeout(f),t(Me.green(" \u2713 Paired"));try{l.end(void 0)}catch{}u(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(Me.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function fk(e={}){if(console.log(),console.log(Me.bold(" Connect WhatsApp")),console.log(),OO()){console.log(Me.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Me.dim(" agentx daemon stop")),console.log();let{cont:l}=await cu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Me.red(" Aborted")),process.exit(1))}let t=e.configPath||lu(process.cwd(),"agentx.json");du(t)||(console.log(Me.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(pk(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||TO,s=lu(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Me.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await cu({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(u=>({title:u,value:u})),initial:0})).agent),i||(console.log(Me.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(IO(s)&&a){let{keep:l}=await cu({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(Me.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await NO(s,u=>console.log(u))||(console.log(Me.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await me(l=>{Ue(l,"channels.whatsapp.enabled",!0),Ue(l,"channels.whatsapp.sessionDir",n),Ue(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(Me.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Me.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Me.dim(` Session: ${n}`)),console.log(Me.dim(" Start the daemon to begin receiving:")),console.log(Me.dim(" agentx daemon start")),console.log(Me.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Me.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Me.dim(" Add routes later with:")),console.log(Me.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import Rt from"chalk";import jO from"prompts";import{existsSync as _O,readFileSync as PO}from"fs";import{resolve as DO}from"path";async function MO(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 LO(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 jo(e){console.log(Rt.red(` ${e}`)),process.exit(1)}async function Zn(e){return(await jO(e,{onCancel:()=>jo("Aborted")}))[e.name]}async function hk(e={}){console.log(),console.log(Rt.bold(" Connect email")),console.log();let t=e.configPath||DO(process.cwd(),"agentx.json");_O(t)||jo(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(PO(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&jo("No agents configured. Run: agentx agent add");let s=e.agent??await Zn({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(y=>({title:y,value:y}))});o.agents?.[s]||jo(`No agent "${s}" in ${t}`);let r=(e.address??await Zn({type:"text",name:"address",message:"Email address customers write to:",validate:y=>/^\S+@\S+\.\S+$/.test(y.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=oh(r),c=e.imapHost??a?.imapHost??await Zn({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),l=Number(e.imapPort??a?.imapPort??await Zn({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await Zn({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await Zn({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(l)||!Number.isInteger(d))&&jo("Ports must be numbers.");let f=e.passwordEnv||sh(i),p=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!p&&jo(`${e.passwordEnv} is not set in the environment.`),p||(a?.imapHost==="imap.gmail.com"&&(console.log(Rt.dim(` Gmail needs an app password, not your account password: ${th}`)),console.log(Rt.dim(" (2-step verification must be on for that page to show.)"))),p=(await Zn({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),p||jo("Aborted");let g={agent:s,address:r,imapHost:c,imapPort:l,smtpHost:u,smtpPort:d,user:e.user,passwordEnv:f,allowFrom:e.allowFrom?.length?e.allowFrom:["*"],send:e.auto?"auto":"approve"};if(!e.skipCheck){process.stdout.write(" Logging in to IMAP and SMTP... ");let y=await MO(g,p);y&&(console.log(Rt.red("\u2717")),jo(y)),console.log(Rt.green("\u2713"))}e.passwordEnv||(Qn(f,p),process.env[f]=p);let h=await me(y=>{Ue(y,"channels.email.enabled",!0),Ue(y,`channels.email.accounts.${i}`,nh(g))},{configPath:e.configPath});h.success||jo(`Config save failed: ${h.error}`),console.log(),console.log(Rt.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Rt.dim(` Password stored in .env as ${f}`)),console.log(Rt.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let w=LO(o.agents[s]?.tier,g.allowFrom);w&&console.log(Rt.yellow(` ${w}`)),console.log(g.send==="auto"?Rt.yellow(" Replies are sent as soon as the agent writes them."):Rt.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(Rt.dim(" Only mail that arrives from now on is answered.")),console.log(Rt.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as qO}from"crypto";import Ke from"chalk";import wk from"prompts";var Qa="agentx-mesh:",Za="//join/";function FO(e){return Buffer.from(e,"utf-8").toString("base64url")}function UO(e){return Buffer.from(e,"base64url").toString("utf-8")}function WO(e){return`${Qa}${Za}${FO(JSON.stringify(e))}`}function BO(e){if(!e.startsWith(`${Qa}${Za}`))throw new Error(`Not a mesh invite link \u2014 expected ${Qa}${Za}\u2026`);let t=e.slice(Qa.length+Za.length),o=JSON.parse(UO(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 JO(){return qO(32).toString("hex")}function HO(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function GO(e){return e?.node?.name||e?.node?.id||"node"}async function yk(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(Ke.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=au("MESH_TOKEN");i||(i=JO(),Qn("MESH_TOKEN",i),console.log(Ke.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||HO(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await wk({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:f=>/^https?:\/\//.test(f)||"must start with http:// or https://"});d||(console.log(Ke.red(" Aborted")),process.exit(1)),a=d}let l=await me(d=>{Ue(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ke.red(` \u2717 ${l.error}`)),process.exit(1));let u=WO({url:a,token:i,name:GO(r),version:1});console.log(),console.log(Ke.bold(" Mesh invite")),console.log(),console.log(` ${Ke.cyan(u)}`),console.log(),console.log(Ke.dim(" Run on the other node:")),console.log(Ke.dim(` agentx connect mesh join "${u}"`)),console.log(),console.log(Ke.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function bk(e,t={}){let o;try{o=BO(e)}catch(r){console.log(Ke.red(` \u2717 ${r.message}`)),process.exit(1)}let n=au("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await wk({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Ke.red(" Aborted (keeping existing .env)")),process.exit(1))}Qn("MESH_TOKEN",o.token);let s=await me(r=>{Ue(r,"mesh.enabled",!0);let i=ks(r,"mesh.peers")||[],a=i.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=c:i.push(c),Ue(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Ke.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ke.green(" \u2713 Joined mesh")),console.log(Ke.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ke.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ke.dim(" Daemon hot-reloaded.")):console.log(Ke.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let 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(Ke.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ke.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Ke.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var es=new zO().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");es.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 mk({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});es.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 fk({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});es.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 hk({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 $k=es.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");$k.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 yk({url:e.url,configPath:e.config})});$k.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 bk(e,{configPath:t.config})});es.action(()=>{console.log(),console.log(tr.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${tr.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${tr.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${tr.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${tr.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(tr.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as YO}from"commander";import ce from"chalk";var ts=new YO().name("usage").description("token usage analysis and reporting");ts.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,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),u=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ce.cyan(a)}: ${l} tokens (${c.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}`))}});ts.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(f=>a(f.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 c=i.now,l=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 f=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,p=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",g=Math.max(1,Math.round((d.resetsAt-c)/6e4)),h=d.resetsAt>c?g<60?`resets in ${g} min`:g<48*60?`resets in ${Math.round(g/60)} h`:`resets in ${Math.round(g/1440)} days`:"",w=l.has(d.window)?ce.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[p,h,w].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`),l.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}`))}});ts.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?"))}});ts.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 c=null;if(e.baseline)try{c=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(c?{baseline:c,current:a}:a,null,2));return}let l=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)`)),c&&console.log(ce.dim(` Baseline: ${c.from} to ${c.to} (${c.days} day(s) with data)`)),console.log();let d=` ${"channel".padEnd(14)} ${"tasks".padStart(6)} ${"cache read".padStart(11)} ${"cache write".padStart(11)} ${"output".padStart(8)} ${"cost".padStart(10)} ${"per task".padStart(9)}`;console.log(ce.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let p=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(g=>[g,a.channels[g],c?.channels[g]]).sort((g,h)=>(h[1]?.cost||0)-(g[1]?.cost||0));p.push(["TOTAL",a.total,c?.total]);for(let[g,h,w]of p){let y=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)} ${l(h?.cost||0).padStart(10)} ${l(y).padStart(9)}`;if(c){let v=r(w),S=y!==null&&v?`${((y-v)/v*100).toFixed(0)}%`:"-";$+=` ${l(v).padStart(9)} ${S.padStart(7)}`}console.log($)}console.log(),c&&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()});ts.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-Y7D5W52I.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:r}=await import("./program-UQUMJH2Q.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,f)=>{for(let p of d.commands??[]){let g=f?`${f} ${p.name()}`:p.name();c.push(g),l(p,g)}};l(i,"");let u=c.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}/${c.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 KO}from"commander";import Je from"chalk";import{readFileSync as XO}from"fs";import{resolve as VO}from"path";te();var rn=new KO().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");rn.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{jg(VO(process.cwd(),".env"))}catch{}let t=QO(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-WCRDEXEC.js");o(t)}catch(t){console.log(Je.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Je.dim(t.stack)),process.exit(1)}});function QO(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Je.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Je.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
567
+ `}function Qn(e,t,o=".env"){let n=dk(o),s=uk(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${iu(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${iu(t)}`})),$O(n,SO(s))}function au(e,t=".env"){return uk(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var gk="https://t.me/BotFather";async function AO(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 EO(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 mk(e={}){console.log(),console.log(ve.bold(" Connect Telegram")),console.log(),console.log(ve.dim(` 1. Open ${gk}`)),console.log(ve.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ve.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await Xr({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&To(gk);let{token:o}=await Xr({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:S=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(S.trim())||"That doesn't look like a Telegram token"});o||(console.log(ve.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await AO(o.trim());n||(console.log(ve.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ve.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(ve.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(ve.red(" No agents configured. Run: agentx agent add")),process.exit(1));let u=e.agent;u||(u=(await Xr({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(x=>({title:x,value:x})),initial:0})).agent),u||(console.log(ve.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||u;d[f]&&d[f].agentBinding!==u&&(f=(await Xr({type:"text",name:"account",message:`Account "${f}" 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),f||(console.log(ve.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Qn(p,o.trim()),process.env[p]=o.trim();let g=await me(S=>{Ue(S,"channels.telegram.enabled",!0),Ue(S,`channels.telegram.accounts.${f}`,{token:`\${${p}}`,agentBinding:u});let x=ks(S,`agents.${u}.mentions`)||[],k=`@${n.username}`;x.includes(k)||(x.push(k),Ue(S,`agents.${u}.mentions`,x))},{configPath:e.configPath});if(g.success||(console.log(ve.red(` \u2717 ${g.error}`)),process.exit(1)),console.log(),console.log(ve.green(` \u2713 Bot @${n.username} bound to agent "${u}"`)),console.log(ve.dim(` Token stored in .env as ${p}`)),console.log(ve.dim(` Mentions updated to include @${n.username}`)),g.reloaded?console.log(ve.dim(" Daemon hot-reloaded.")):console.log(ve.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Xr({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(ve.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ve.dim(" Waiting up to 90s..."));let w=await EO(o.trim(),9e4);if(!w){console.log(ve.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ve.dim(" agentx config set notifications.destination.channel telegram")),console.log(ve.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ve.dim(` agentx config set notifications.destination.accountId ${f}`));return}let y={channel:"telegram",chatId:String(w.chatId),accountId:f},$=[],v=await me(S=>{Ue(S,"notifications.destination",y),$=ca(S,y)},{configPath:e.configPath});if(!v.success){console.log(ve.red(` \u2717 failed to save destination: ${v.error}`));return}console.log(ve.green(" \u2713 Default --notify target set")),console.log(ve.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ve.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(ve.dim(` Schedules that now report here: ${$.join(", ")}`)),v.reloaded&&console.log(ve.dim(" Daemon hot-reloaded."))}import Me from"chalk";import cu from"prompts";import{existsSync as du,mkdirSync as RO,readdirSync as CO,readFileSync as pk}from"fs";import{resolve as lu}from"path";var TO=".agentx/whatsapp-sessions";function OO(){let e=lu(process.cwd(),".agentx/daemon.pid");if(!du(e))return!1;try{let t=parseInt(pk(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function IO(e){if(!du(e))return!1;try{return CO(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function NO(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Me.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Me.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;RO(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(u=>{let f=setTimeout(()=>{t(Me.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}u(!1)},12e4);l.ev.on("connection.update",async p=>{if(p.qr){t(Me.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:g}=await import("qrcode-terminal");g.generate(p.qr,{small:!0})}catch{t(` QR: ${p.qr}`)}t("")}if(p.connection==="open"){clearTimeout(f),t(Me.green(" \u2713 Paired"));try{l.end(void 0)}catch{}u(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(Me.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function fk(e={}){if(console.log(),console.log(Me.bold(" Connect WhatsApp")),console.log(),OO()){console.log(Me.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Me.dim(" agentx daemon stop")),console.log();let{cont:l}=await cu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Me.red(" Aborted")),process.exit(1))}let t=e.configPath||lu(process.cwd(),"agentx.json");du(t)||(console.log(Me.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(pk(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||TO,s=lu(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Me.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await cu({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(u=>({title:u,value:u})),initial:0})).agent),i||(console.log(Me.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(IO(s)&&a){let{keep:l}=await cu({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(Me.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await NO(s,u=>console.log(u))||(console.log(Me.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await me(l=>{Ue(l,"channels.whatsapp.enabled",!0),Ue(l,"channels.whatsapp.sessionDir",n),Ue(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(Me.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Me.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Me.dim(` Session: ${n}`)),console.log(Me.dim(" Start the daemon to begin receiving:")),console.log(Me.dim(" agentx daemon start")),console.log(Me.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Me.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Me.dim(" Add routes later with:")),console.log(Me.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import Rt from"chalk";import jO from"prompts";import{existsSync as _O,readFileSync as PO}from"fs";import{resolve as DO}from"path";async function MO(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 LO(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 jo(e){console.log(Rt.red(` ${e}`)),process.exit(1)}async function Zn(e){return(await jO(e,{onCancel:()=>jo("Aborted")}))[e.name]}async function hk(e={}){console.log(),console.log(Rt.bold(" Connect email")),console.log();let t=e.configPath||DO(process.cwd(),"agentx.json");_O(t)||jo(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(PO(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&jo("No agents configured. Run: agentx agent add");let s=e.agent??await Zn({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(y=>({title:y,value:y}))});o.agents?.[s]||jo(`No agent "${s}" in ${t}`);let r=(e.address??await Zn({type:"text",name:"address",message:"Email address customers write to:",validate:y=>/^\S+@\S+\.\S+$/.test(y.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=oh(r),c=e.imapHost??a?.imapHost??await Zn({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),l=Number(e.imapPort??a?.imapPort??await Zn({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await Zn({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await Zn({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(l)||!Number.isInteger(d))&&jo("Ports must be numbers.");let f=e.passwordEnv||sh(i),p=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!p&&jo(`${e.passwordEnv} is not set in the environment.`),p||(a?.imapHost==="imap.gmail.com"&&(console.log(Rt.dim(` Gmail needs an app password, not your account password: ${th}`)),console.log(Rt.dim(" (2-step verification must be on for that page to show.)"))),p=(await Zn({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),p||jo("Aborted");let g={agent:s,address:r,imapHost:c,imapPort:l,smtpHost:u,smtpPort:d,user:e.user,passwordEnv:f,allowFrom:e.allowFrom?.length?e.allowFrom:["*"],send:e.auto?"auto":"approve"};if(!e.skipCheck){process.stdout.write(" Logging in to IMAP and SMTP... ");let y=await MO(g,p);y&&(console.log(Rt.red("\u2717")),jo(y)),console.log(Rt.green("\u2713"))}e.passwordEnv||(Qn(f,p),process.env[f]=p);let h=await me(y=>{Ue(y,"channels.email.enabled",!0),Ue(y,`channels.email.accounts.${i}`,nh(g))},{configPath:e.configPath});h.success||jo(`Config save failed: ${h.error}`),console.log(),console.log(Rt.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Rt.dim(` Password stored in .env as ${f}`)),console.log(Rt.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let w=LO(o.agents[s]?.tier,g.allowFrom);w&&console.log(Rt.yellow(` ${w}`)),console.log(g.send==="auto"?Rt.yellow(" Replies are sent as soon as the agent writes them."):Rt.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(Rt.dim(" Only mail that arrives from now on is answered.")),console.log(Rt.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as qO}from"crypto";import Ke from"chalk";import wk from"prompts";var Qa="agentx-mesh:",Za="//join/";function FO(e){return Buffer.from(e,"utf-8").toString("base64url")}function UO(e){return Buffer.from(e,"base64url").toString("utf-8")}function WO(e){return`${Qa}${Za}${FO(JSON.stringify(e))}`}function BO(e){if(!e.startsWith(`${Qa}${Za}`))throw new Error(`Not a mesh invite link \u2014 expected ${Qa}${Za}\u2026`);let t=e.slice(Qa.length+Za.length),o=JSON.parse(UO(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 JO(){return qO(32).toString("hex")}function HO(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function GO(e){return e?.node?.name||e?.node?.id||"node"}async function yk(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(Ke.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=au("MESH_TOKEN");i||(i=JO(),Qn("MESH_TOKEN",i),console.log(Ke.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||HO(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await wk({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:f=>/^https?:\/\//.test(f)||"must start with http:// or https://"});d||(console.log(Ke.red(" Aborted")),process.exit(1)),a=d}let l=await me(d=>{Ue(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ke.red(` \u2717 ${l.error}`)),process.exit(1));let u=WO({url:a,token:i,name:GO(r),version:1});console.log(),console.log(Ke.bold(" Mesh invite")),console.log(),console.log(` ${Ke.cyan(u)}`),console.log(),console.log(Ke.dim(" Run on the other node:")),console.log(Ke.dim(` agentx connect mesh join "${u}"`)),console.log(),console.log(Ke.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function bk(e,t={}){let o;try{o=BO(e)}catch(r){console.log(Ke.red(` \u2717 ${r.message}`)),process.exit(1)}let n=au("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await wk({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Ke.red(" Aborted (keeping existing .env)")),process.exit(1))}Qn("MESH_TOKEN",o.token);let s=await me(r=>{Ue(r,"mesh.enabled",!0);let i=ks(r,"mesh.peers")||[],a=i.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=c:i.push(c),Ue(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Ke.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ke.green(" \u2713 Joined mesh")),console.log(Ke.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ke.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ke.dim(" Daemon hot-reloaded.")):console.log(Ke.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let 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(Ke.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ke.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Ke.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var es=new zO().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");es.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 mk({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});es.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 fk({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});es.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 hk({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 $k=es.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");$k.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 yk({url:e.url,configPath:e.config})});$k.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 bk(e,{configPath:t.config})});es.action(()=>{console.log(),console.log(tr.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${tr.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${tr.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${tr.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${tr.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(tr.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as YO}from"commander";import ce from"chalk";var ts=new YO().name("usage").description("token usage analysis and reporting");ts.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,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),u=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ce.cyan(a)}: ${l} tokens (${c.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}`))}});ts.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(f=>a(f.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 c=i.now,l=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 f=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,p=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",g=Math.max(1,Math.round((d.resetsAt-c)/6e4)),h=d.resetsAt>c?g<60?`resets in ${g} min`:g<48*60?`resets in ${Math.round(g/60)} h`:`resets in ${Math.round(g/1440)} days`:"",w=l.has(d.window)?ce.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[p,h,w].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`),l.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}`))}});ts.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?"))}});ts.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 c=null;if(e.baseline)try{c=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(c?{baseline:c,current:a}:a,null,2));return}let l=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)`)),c&&console.log(ce.dim(` Baseline: ${c.from} to ${c.to} (${c.days} day(s) with data)`)),console.log();let d=` ${"channel".padEnd(14)} ${"tasks".padStart(6)} ${"cache read".padStart(11)} ${"cache write".padStart(11)} ${"output".padStart(8)} ${"cost".padStart(10)} ${"per task".padStart(9)}`;console.log(ce.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let p=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(g=>[g,a.channels[g],c?.channels[g]]).sort((g,h)=>(h[1]?.cost||0)-(g[1]?.cost||0));p.push(["TOTAL",a.total,c?.total]);for(let[g,h,w]of p){let y=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)} ${l(h?.cost||0).padStart(10)} ${l(y).padStart(9)}`;if(c){let v=r(w),S=y!==null&&v?`${((y-v)/v*100).toFixed(0)}%`:"-";$+=` ${l(v).padStart(9)} ${S.padStart(7)}`}console.log($)}console.log(),c&&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()});ts.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-Y7D5W52I.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:r}=await import("./program-5LBTVRBW.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,f)=>{for(let p of d.commands??[]){let g=f?`${f} ${p.name()}`:p.name();c.push(g),l(p,g)}};l(i,"");let u=c.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}/${c.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 KO}from"commander";import Je from"chalk";import{readFileSync as XO}from"fs";import{resolve as VO}from"path";te();var rn=new KO().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");rn.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{jg(VO(process.cwd(),".env"))}catch{}let t=QO(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-3CNZ3R6T.js");o(t)}catch(t){console.log(Je.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Je.dim(t.stack)),process.exit(1)}});function QO(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Je.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Je.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
568
568
  `)),{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}}}}rn.command("list").description("list configured boards").action(()=>{try{let e=O();if(!e.boards?.length){console.log(Je.dim(`
569
569
  No boards configured.
570
570
  `));return}console.log();for(let t of e.boards){console.log(` ${Je.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(Je.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(Je.dim(` primary label: ${t.primaryToolLabel}`)),console.log(Je.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(Je.red(` ${e.message}`)),process.exit(1)}});rn.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{Vr(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(Je.red(` ${o.message}`)),process.exit(1)}});rn.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{Vr(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(Je.red(` ${o.message}`)),process.exit(1)}});var uu=rn.command("column").description("manage a board's columns (add / remove / edit / list)");uu.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(XO("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(Je.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(` ${Je.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${Je.dim(r)}`)}}catch(t){console.log(Je.red(` ${t.message}`)),process.exit(1)}});uu.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{Vr(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(Je.red(` ${n.message}`)),process.exit(1)}});uu.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{Vr(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(Je.red(` ${o.message}`)),process.exit(1)}});rn.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Vr(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(Je.red(` ${t.message}`)),process.exit(1)}});function Vr(e){let{summary:t,backupPath:o}=_t(n=>e(n));console.log(Je.green(`
@@ -866,7 +866,7 @@ Restart the daemon to activate.
866
866
  dist/
867
867
  *.log
868
868
  .env
869
- `}import{Command as TN}from"commander";import it from"chalk";import{writeFileSync as ON,mkdirSync as IN,existsSync as Sc,readFileSync as $x,appendFileSync as kx}from"fs";import{resolve as ur,dirname as Sx}from"path";import{homedir as Vu}from"os";var Ax=new TN().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-UQUMJH2Q.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=_N(o);break;case"bash":s=qN(o);break;case"fish":s=FN(o);break;default:console.error(it.red(`unsupported shell: ${n}`)),console.error(it.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?ur(String(e.output)):NN(n);IN(Sx(r),{recursive:!0}),ON(r,s),console.log(it.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),jN(n,r,!!e.yes)});function NN(e){let t=Vu();switch(e){case"zsh":return ur(t,".zsh","completions","_agentx");case"bash":return ur(t,".bash_completion.d","agentx.bash");case"fish":return ur(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function jN(e,t,o){if(e==="zsh"){let n=ur(Vu(),".zshrc"),s=Sx(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=Sc(n)?$x(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(it.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&Sc(n)){let u=["","# agentx completion"];c&&u.push(r),l&&u.push(i),kx(n,u.join(`
869
+ `}import{Command as TN}from"commander";import it from"chalk";import{writeFileSync as ON,mkdirSync as IN,existsSync as Sc,readFileSync as $x,appendFileSync as kx}from"fs";import{resolve as ur,dirname as Sx}from"path";import{homedir as Vu}from"os";var Ax=new TN().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-5LBTVRBW.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=_N(o);break;case"bash":s=qN(o);break;case"fish":s=FN(o);break;default:console.error(it.red(`unsupported shell: ${n}`)),console.error(it.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?ur(String(e.output)):NN(n);IN(Sx(r),{recursive:!0}),ON(r,s),console.log(it.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),jN(n,r,!!e.yes)});function NN(e){let t=Vu();switch(e){case"zsh":return ur(t,".zsh","completions","_agentx");case"bash":return ur(t,".bash_completion.d","agentx.bash");case"fish":return ur(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function jN(e,t,o){if(e==="zsh"){let n=ur(Vu(),".zshrc"),s=Sx(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=Sc(n)?$x(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(it.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&Sc(n)){let u=["","# agentx completion"];c&&u.push(r),l&&u.push(i),kx(n,u.join(`
870
870
  `)+`
871
871
  `),console.log(it.green("\u2713 Patched ~/.zshrc")),console.log(it.dim("Reload your shell: exec zsh"));return}console.log(it.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(it.cyan(` ${r}`)),l&&console.log(it.cyan(` ${i}`)),console.log(),console.log(it.dim("Then reload: exec zsh")),console.log(it.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=ur(Vu(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((Sc(n)?$x(n,"utf-8"):"").includes(t)){console.log(it.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&Sc(n)){kx(n,`
872
872
  # agentx completion
@@ -882,4 +882,4 @@ ${UN({...t,category:e.category})}`),u&&a.set(l.id,u)}let c=`https://github.com/$
882
882
  ${o.url}`)}catch(t){console.error(mr.red(` ${t.message}`)),process.exitCode=1}});gi.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",Zu).action(async(e,t)=>{try{let o=await og(t.models);if(!eg(t.model,o)){console.log(tg(t.model,o)),process.exitCode=1;return}let n=e==="-"?await JN():await BN(e,"utf8"),s=JSON.parse(n),{version:r}=await Ri(),i=Tx({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(mr.red(` ${o.message}`)),process.exitCode=1}});async function JN(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function n6(){let e=await Ri(),t=new HN().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=ih(n);ah(s)&&rh("cli",s)});for(let o of[ty,pw,mw,es,Ts,uo,Pt,Ff,u$,po,pa,Io,En,zn,yo,sn,lk,nn,ra,tx,Zo,Xy,Vy,ib,Br,wb,vb,zy,Ab,Eb,Bb,zb,Yb,Ft,ts,ax,Nr,Yo,Ax,gi])t.addCommand(o);for(let o of Ix)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=Ix.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,GN(o,74," "),""].join(`
883
883
  `)}),t}var Ix=[X,sr,Po,oo,Pr,Ks,et,_o,rn,Gn,is,ir,Vo,xt,Us,Ra,Ba,Jn,Ja,Ha,Xv,Zv,Oo,si,Mt,xh,In,di,ed,dn,$t,qs,td,mc,ko,Do,mx,lr,px,rx];function GN(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(`
884
884
  `)}export{n6 as buildProgram};
885
- //# sourceMappingURL=program-UQUMJH2Q.js.map
885
+ //# sourceMappingURL=program-5LBTVRBW.js.map