agentix-cli 0.126.1 → 0.126.2

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.
@@ -521,7 +521,7 @@ ${l}`)}let S={agentId:o,message:k,context:{channel:b,sender:g?"opencode":"openai
521
521
 
522
522
  `)}}function Dh(r){r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"})}function Nh(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}]})}
523
523
 
524
- `)}function jh(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);zi(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 zi(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Zt=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Zt(`${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(Zt.levelOrder[e]<Zt.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)}},Qt=Zt;dt(Qt,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as Mk,statSync as _k}from"fs";var It={version:"0.126.1",commit:"09ed3da",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function Ok(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 Fh(){let r=null;try{r=_k(Mk(process.argv[1])).mtimeMs}catch{}let e=oh().version;return Ok(It,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as Dk}from"crypto";var bs=class{constructor(e=new _c){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!Nk.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};Lk(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:Dk(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=jk(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}},Nk=["run","task","signal","mesh","channel","status"];function jk(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 Lk(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 Uh(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 ks,timingSafeEqual as Gh}from"crypto";var vs=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),l=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let y={};for(let[k,S]of Object.entries(e.headers))(k.startsWith("x-hubspot")||k.startsWith("x-hub")||k.startsWith("x-github")||k.startsWith("x-gitlab")||k.startsWith("stripe")||k.startsWith("sentry")||k.startsWith("x-vercel")||k.startsWith("x-odoo")||k.startsWith("x-webhook")||k==="user-agent"||k==="content-type"||k==="host"||k==="x-forwarded-host"||k==="x-forwarded-proto"||k==="x-forwarded-for")&&(y[k]=S);this.log(`Webhook [${l}] reqUrl=${e.url} headers: ${JSON.stringify(y)}`)}let d=this.validateSignature(e.headers,a,l,i,e.url);if(d){this.log(`Webhook [${l}] -> ${i}: REJECTED (${d})`),this.sendJson(t,401,{error:d});return}let u=this.buildSummary(l,c,e.headers);this.log(`Webhook [${l}] -> ${i}: ${u.slice(0,100)}`);let p=this.extractEventType(l,c,e.headers),f=this.webhookEntries.find(y=>y.enabled&&y.agentId===i&&y.source===l),g=p&&f?.triggers?.[p]||f?.defaultWorkflow||null;if(await this.fireHookSafe(l,p,i,c),g&&this.workflowDispatcher)try{let y=await this.workflowDispatcher.dispatchWorkflow({workflowId:g,entityRef:{kind:"webhook",id:`${l}:${i}:${p??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:p,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${p??"\u2014"}] -> workflow=${g} (claimed=${y.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:p,workflow:g,claimed:y.claimed});return}catch(y){this.log(`Workflow dispatch failed [${l}/${p}/${g}]: ${y.message}`)}let b=this.webhookEntries.find(y=>y.enabled&&y.node&&y.agentId===i&&y.source===l);if(b?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:b.node,status:"accepted"}),this.mesh.sendTask(b.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(y=>this.log(`Mesh-forwarded webhook [${l}] -> ${b.node}/${i}: ${y?.slice(0,100)||"ok"}`),y=>this.log(`Mesh forward failed [${l}] -> ${b.node}/${i}: ${y.message}`));return}try{let y=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${l}`,sender:`webhook:${l}`}});this.sendJson(t,y.error?500:200,{ok:!y.error,agent:i,source:l,response:y.content?.slice(0,500),error:y.error,duration:y.duration})}catch(y){this.sendJson(t,500,{error:y.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let d of t.commits.slice(0,3))s.push(` - ${d.message?.split(`
524
+ `)}function jh(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);zi(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 zi(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Zt=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Zt(`${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(Zt.levelOrder[e]<Zt.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)}},Qt=Zt;dt(Qt,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as Mk,statSync as _k}from"fs";var It={version:"0.126.2",commit:"1e41256",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function Ok(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 Fh(){let r=null;try{r=_k(Mk(process.argv[1])).mtimeMs}catch{}let e=oh().version;return Ok(It,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as Dk}from"crypto";var bs=class{constructor(e=new _c){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!Nk.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};Lk(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:Dk(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=jk(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}},Nk=["run","task","signal","mesh","channel","status"];function jk(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 Lk(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 Uh(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 ks,timingSafeEqual as Gh}from"crypto";var vs=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),l=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let y={};for(let[k,S]of Object.entries(e.headers))(k.startsWith("x-hubspot")||k.startsWith("x-hub")||k.startsWith("x-github")||k.startsWith("x-gitlab")||k.startsWith("stripe")||k.startsWith("sentry")||k.startsWith("x-vercel")||k.startsWith("x-odoo")||k.startsWith("x-webhook")||k==="user-agent"||k==="content-type"||k==="host"||k==="x-forwarded-host"||k==="x-forwarded-proto"||k==="x-forwarded-for")&&(y[k]=S);this.log(`Webhook [${l}] reqUrl=${e.url} headers: ${JSON.stringify(y)}`)}let d=this.validateSignature(e.headers,a,l,i,e.url);if(d){this.log(`Webhook [${l}] -> ${i}: REJECTED (${d})`),this.sendJson(t,401,{error:d});return}let u=this.buildSummary(l,c,e.headers);this.log(`Webhook [${l}] -> ${i}: ${u.slice(0,100)}`);let p=this.extractEventType(l,c,e.headers),f=this.webhookEntries.find(y=>y.enabled&&y.agentId===i&&y.source===l),g=p&&f?.triggers?.[p]||f?.defaultWorkflow||null;if(await this.fireHookSafe(l,p,i,c),g&&this.workflowDispatcher)try{let y=await this.workflowDispatcher.dispatchWorkflow({workflowId:g,entityRef:{kind:"webhook",id:`${l}:${i}:${p??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:p,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${p??"\u2014"}] -> workflow=${g} (claimed=${y.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:p,workflow:g,claimed:y.claimed});return}catch(y){this.log(`Workflow dispatch failed [${l}/${p}/${g}]: ${y.message}`)}let b=this.webhookEntries.find(y=>y.enabled&&y.node&&y.agentId===i&&y.source===l);if(b?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:b.node,status:"accepted"}),this.mesh.sendTask(b.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(y=>this.log(`Mesh-forwarded webhook [${l}] -> ${b.node}/${i}: ${y?.slice(0,100)||"ok"}`),y=>this.log(`Mesh forward failed [${l}] -> ${b.node}/${i}: ${y.message}`));return}try{let y=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${l}`,sender:`webhook:${l}`}});this.sendJson(t,y.error?500:200,{ok:!y.error,agent:i,source:l,response:y.content?.slice(0,500),error:y.error,duration:y.duration})}catch(y){this.sendJson(t,500,{error:y.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let d of t.commits.slice(0,3))s.push(` - ${d.message?.split(`
525
525
  `)[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(`
526
526
  `)[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??"?",p=l.changeFlag??l.changeSource??"";s.push(` - ${d} (object ${u}${p?`, ${p}`:""})`)}}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(`
527
527
  `)}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="+ks("sha256",a).update(t).digest("hex");return Tt(u,d)}if(n==="gitlab"){let d=c("x-gitlab-token");return d?Tt(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 p=ks("sha256",a).update(`${u.t}.${t}`).digest("hex");return Tt(p,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 p=parseInt(u,10);if(!Number.isFinite(p))return"malformed X-HubSpot-Request-Timestamp";let f=Date.now()-p;if(f>5*6e4)return`HubSpot webhook is ${Math.floor(f/1e3)}s old (>5min replay window)`;let g="POST",b=i||e["x-original-uri"]||e["x-forwarded-path"]||"",y=e["x-forwarded-host"],k=e.host,S=e["x-forwarded-proto"]||"https",$=new Set;y&&b&&$.add(`${S}://${y}${b}`),k&&b&&$.add(`https://${k}${b}`),k&&b&&$.add(`http://${k}${b}`),b&&$.add(b),$.add("");for(let P of $){let D=ks("sha256",a).update(`${g}${P}${t}${u}`).digest("base64");if(d.length===D.length&&Gh(Buffer.from(d),Buffer.from(D)))return null}return`signature mismatch (tried ${$.size} URI variants)`}if(n==="odoo"){let d=c("x-odoo-signature");if(d){let p=ks("sha256",a).update(t).digest("hex"),f=d.startsWith("sha256=")?d.slice(7):d;return Tt(p,f)}let u=c("x-odoo-webhook-token")??c("x-webhook-secret");return u?Tt(a,u):"missing X-Odoo-Signature or X-Odoo-Webhook-Token"}let l=c("x-webhook-secret");return l?Tt(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 Tt(r,e){if(r.length!==e.length)return"signature mismatch";let t=Buffer.from(r),n=Buffer.from(e);return Gh(t,n)?null:"signature mismatch"}aw();tw();qa();function Fk(r){return{insertTaskHistory:r.prepare(`
@@ -1151,4 +1151,4 @@ data: ${JSON.stringify(V)}
1151
1151
  `)}catch{}},j=setInterval(()=>{try{t.write(`: ping
1152
1152
 
1153
1153
  `)}catch{}},15e3);j.unref?.();let L=new AbortController;t.on("close",()=>{t.writableEnded||L.abort()});try{for await(let U of this.mesh.sendTaskStream(h.peer,h.message,h.agent,{context:h.context,signal:L.signal,vouchOwner:v}))E(U.event,U.data)}catch(U){E("error",{error:U?.message??String(U)})}finally{clearInterval(j);try{t.end()}catch{}}break}let A=h.context,M=typeof h.senderAgentId=="string"?h.senderAgentId:void 0;if(Py(h,!0)==="callback"){let E=this.delegationGate(e,h,{callee:h.agent,peer:h.peer,message:h.message,calleeContext:A});if(!("track"in E)){let j=br(E);this.json(t,j.status,j.body);break}}if(h.async===!0){let E=A?.channel,j=A?.chatId;if(!E||!j){this.json(t,400,{error:"async requires context.channel and context.chatId \u2014 there is no route back otherwise"});return}let L=`mesh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;this.json(t,202,{accepted:!0,taskId:L,deliverTo:`${E}:${j}`,note:"result will be delivered to the originating chat when the peer finishes"});let U=h.peer,V=h.agent,ye=this.mesh;(async()=>{let H=Date.now(),q;try{q=await ye.sendTask(U,h.message,V,{vouchOwner:v,context:A,senderAgentId:M}),this.log(`[mesh/task async ${L}] ${U}/${V??"default"} finished in ${Date.now()-H}ms`)}catch(Y){q=`Delegation to ${U}/${V??"default"} failed: ${Y?.message??Y}`,this.log(`[mesh/task async ${L}] failed: ${Y?.message??Y}`)}try{await this.router.sendOutbound({channel:E,chatId:j,text:q,agentId:A?.agentId??M,accountId:A?.accountId})}catch(Y){this.log(`[mesh/task async ${L}] delivery failed: ${Y?.message??Y}`)}})();break}let _=await this.mesh.sendTask(h.peer,h.message,h.agent,{context:A,senderAgentId:M,vouchOwner:v});this.json(t,200,{response:_});break}case"POST /webrtc/signal/out":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let m=await W(e);if(!m.kind||!m.callId||!m.from||!m.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let w=await this.webrtc.handleOutgoing(m);this.json(t,w.ok?200:400,w);break}case"POST /webrtc/signal":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let m=await W(e);if(!m.kind||!m.callId||!m.from||!m.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let w=this.webrtc.handleIncoming(m);this.json(t,w.ok?200:400,w);break}case"POST /webrtc/bot/invite":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled (channels.webrtc.bot.enabled=false)"});return}let h=await W(e),m=h.callId,w=h.target,v=h.agentId||this.config.channels.webrtc?.bot.defaultAgentId;if(!m||!w||!v){this.json(t,400,{error:"Missing: callId, target, agentId (or defaultAgentId in config)"});return}let I=await this.botManager.invite({callId:m,target:w,agentId:v});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 h=this.config.channels.webrtc;if(!h?.enabled){this.json(t,404,{error:"WebRTC signaling not enabled"});return}this.json(t,200,{localName:this.config.node.name,iceServers:[...h.stunServers.map(m=>({urls:m})),...h.turnServers],peers:this.mesh?.directory().map(m=>({name:m.peer,healthy:m.healthy}))||[],camera:h.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(h=>{let m=this.config.agents[h.id]||{},w=typeof m.description=="string"&&m.description.trim()||xT(m.systemPrompt)||`Agent "${h.name}" (${h.tier})`,v=Array.isArray(m.mentions)?m.mentions.slice(0,4):[];return{id:h.id,name:h.name,description:w,tags:[h.tier,...v],color:he(h.id,m).color}}),channels:this.router.getChannelNames(),githubLogins:this.github?.postingAccounts()??[],defaultInputModes:["text"],defaultOutputModes:["text"]});break;case"GET /wiki/agents":{let h=this.registry.getWikiHub();this.json(t,200,{nodeId:this.config.node.id,agents:h.summary()});break}case"GET /wiki/entries":{let h=this.registry.getWikiHub(),m=n.searchParams.get("agent")||void 0,w=n.searchParams.get("after")||void 0,v=m?h.getAgentEntries(m):h.getSharedStore().listEntries({after:w});this.json(t,200,{nodeId:this.config.node.id,count:v.length,entries:v.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 h=this.registry.getWikiHub(),m=n.searchParams.get("agent");if(!m){this.json(t,400,{error:"?agent= required"});break}let v=h.getAgentWiki(m).rebuildIndex();this.json(t,200,{nodeId:this.config.node.id,agentId:m,articles:v.articles});break}case"GET /wiki/article":{let h=this.registry.getWikiHub(),m=n.searchParams.get("agent"),w=n.searchParams.get("path");if(!m||!w){this.json(t,400,{error:"?agent= and ?path= required"});break}let I=h.getAgentWiki(m).readArticle(w);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 /graph/schema":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,schema:h.loadSchema()});break}case"GET /graph/nodes":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,...h.loadNodes()});break}case"GET /graph/classifications":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}let m=n.searchParams.get("status")||"approved",w=Math.max(1,Math.min(1e3,parseInt(n.searchParams.get("limit")||"200",10)||200)),v=h.listByStatus(m,w);this.json(t,200,{nodeId:this.config.node.id,status:m,count:v.length,classifications:v});break}default:this.json(t,404,{error:"Not found",endpoints:["GET /health","GET /agents","GET /crons","GET /routines \u2014 schedules + cron/hook workflows with staleness flags","GET /mesh","GET /wiki/agents","GET /wiki/entries[?agent=X&after=YYYY-MM-DD]","GET /wiki/articles?agent=X","GET /graph/schema","GET /graph/nodes","GET /graph/classifications[?status=approved|pending|rejected&limit=N]","POST /task { agent, message, context?, freshSession?: bool }","GET /agents/:id \u2014 resolved agent config (permission, tier, model, persistentProcess, toolUseRequired)","POST /agents/:id/selftest { message? } \u2014 canary probe; runs a fresh-session task and reports {ok, durationMs, tokens, billedModel}","GET /traces[?agentId=&channel=&chatId=&workflowRunId=&status=&since=&until=&limit=]","GET /traces/:taskId \u2014 full per-task execution trace (steps + tokens)","GET /voice/history[?agent=&limit=&before=] \u2014 past voice exchanges, bounded summaries","GET /voice/history/:id \u2014 one voice exchange in full; POST /voice/history/:id/replay","GET /api/processes \u2014 live persistent claude processes (JSON)","POST /api/processes/kill { agentId, channel, chatId, reason? }","GET /api/actions/builtin \u2014 list shipped built-in typed actions","POST /api/actions/builtin/:name \u2014 run a built-in with JSON body input","POST /mesh/task { peer, message }","POST /webhook/:agentId[/:source] \u2014 webhook callback","POST /reload \u2014 re-read agentx.json (hot-swaps crons)","GET /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 W(e);await Lh(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=pm(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=ug();if(e==="json")return this.registry.getTodayUsage();let t=dg(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||!Nt(n)))try{let s=te(n,".claude","skills");Qy(s,{recursive:!0});let i=te(s,mm);if(!Nt(i))xa(i,Eo(e)),this.log(` memory-skill: installed remember.md \u2192 ${t.id}`);else{let o=ym(kn(i,"utf-8"),e);o&&(xa(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||!Nt(n))continue;let s=this.config.workflows.enabled&&this.config.workflows.followUp.enabled&&(this.config.workflows.followUp.agents[e]??!0),i=Kc(fc(t),this.config.requests.enabled||s?Xc():null);try{switch(zc(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 Jp(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 ne(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 p=typeof n?.fromPeer=="string"?n.fromPeer:"unknown";this.log(`[workflows/mesh] received trigger from "${p}" source="${s.trigger.source}" chat="${s.trigger.chat??"*"}"`);let f=await this.workflowDispatcher.dispatch({trigger:s.trigger,entityRef:o,event:i,fromRemote:{peer:p}});this.log(`[workflows/mesh] dispatched broadcast: matched=${f.claimed.length} ${f.claimed.length?`(${f.claimed.map(g=>g.id).join(", ")})`:"[none \u2014 no workflow with mesh.allowRemote matched]"}`),this.json(t,202,{ok:!0,mode:"trigger-broadcast",matched:f.claimed.map(g=>g.id)});return}let d=(s.workflowId?this.workflowStore?.get(s.workflowId):null)?.nodes.find(p=>p.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 ne(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let{handlePushBridge:s,pushOrigin:i}=await import("./push-bridge-325SXDGN.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 nd(String(e.headers.authorization||""),this.config.mesh.peers,process.env.MESH_TOKEN)}async handleChannelSend(e,t){let n;try{n=await ne(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-325SXDGN.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,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 p of l)!p.id||s.has(p.id)||(s.add(p.id),i.push({...p,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 p=await u.json();Array.isArray(p.chats)&&a(p.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 ne(e)}catch{s={}}try{let i=await gm({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})}}},Aa=Ra;dt(Aa,"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 xT(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 ne(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 AT(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 W(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)})}ew();function K2(r){typeof r=="string"&&(vn.error(r),process.exit(1)),r instanceof Error&&(vn.error(r.message),process.exit(1)),vn.error("Something went wrong. Please try again."),process.exit(1)}export{UT as a,xi as b,et as c,qt as d,Xt as e,rt as f,ns as g,oh as h,eg as i,Kk as j,zk as k,ig as l,We as m,ot as n,cg as o,at as p,AE as q,RE as r,Is as s,mC as t,$S as u,So as v,RP as w,EP as x,CP as y,nm as z,t0 as A,DP as B,NP as C,rn as D,Ct as E,on as F,cM as G,Om as H,V0 as I,e_ as J,Bs as K,Wo as L,Ho as M,Ks as N,he as O,If as P,Qs as Q,H$ as R,jf as S,q$ as T,Gf as U,tr as V,pn as W,ir as X,ar as Y,Jf as Z,sa as _,qe as $,Ie as aa,ty as ba,ny as ca,sy as da,ry as ea,Ar as fa,Hy as ga,$a as ha,qy as ia,pT as ja,wN as ka,Aa as la,K2 as ma};
1154
- //# sourceMappingURL=chunk-4VUGJB5S.js.map
1154
+ //# sourceMappingURL=chunk-UUVFH7BO.js.map
package/dist/cli.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var s=o(process.versions.node);s&&(console.error(s),process.exit(1));var{buildProgram:r}=await import("./program-EYGICEXY.js"),{installCliSignalExit:i}=await import("./signal-exit-WL7G3EEZ.js");i();var e=await r();process.argv.slice(2).length===0?e.outputHelp():e.parse();
2
+ import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var s=o(process.versions.node);s&&(console.error(s),process.exit(1));var{buildProgram:r}=await import("./program-LGCT7FFJ.js"),{installCliSignalExit:i}=await import("./signal-exit-WL7G3EEZ.js");i();var e=await r();process.argv.slice(2).length===0?e.outputHelp():e.parse();
3
3
  //# sourceMappingURL=cli.js.map
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt,la as Tt,ma as Mt}from"./chunk-4VUGJB5S.js";import"./chunk-O4XEQTEN.js";import"./chunk-JIXNSA67.js";import"./chunk-GTJIKXDB.js";import"./chunk-ZVP6GB4G.js";import"./chunk-S2GAEH2F.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-BGG3ZSMW.js";import"./chunk-XGOBZCYC.js";import"./chunk-WCXXXAHV.js";import"./chunk-JWDJMFU6.js";import"./chunk-GRMCAO3Q.js";import"./chunk-KZKDVIOE.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-WEPON4FP.js";import"./chunk-AKLZ4YO2.js";import"./chunk-PPUN7YHA.js";import"./chunk-Y4CYQV7G.js";import"./chunk-LLNPKE7H.js";import"./chunk-SHEUCITK.js";import"./chunk-QQYXYJOG.js";import"./chunk-GUQDPA6R.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-EMGB23H5.js";import{ca as yt,m as lt,n as ct,o as dt,p as mt,q as pt}from"./chunk-D6SWAB5J.js";import"./chunk-LVV7JBHM.js";import"./chunk-GLQLCBJS.js";import"./chunk-6W74CHNW.js";import{a as L}from"./chunk-UG2OF2EI.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-WUDVBPQV.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-SZDACK6O.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{s as ut}from"./chunk-5DFUUYEA.js";import"./chunk-WMTGAVPW.js";import"./chunk-VWTBHLMX.js";import"./chunk-YNA5T43U.js";import{a as ht}from"./chunk-ZQWWMAMJ.js";import"./chunk-3PGPN323.js";import"./chunk-2C3X6DVD.js";import"./chunk-56KNKUFF.js";import{f as gt,g as ft}from"./chunk-VXKNB4AW.js";import"./chunk-WPNRDEHW.js";import"./chunk-36AXN6ZB.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-FVG2BADS.js";import{j as it,k as rt,l as at}from"./chunk-JUIL2EW3.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import"./chunk-4VVHGR7H.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-2PJKGZWP.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{ma as tt,oa as st,pa as ot,ra as nt}from"./chunk-46JKX6CT.js";import"./chunk-UIBUZ2N3.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.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{a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt,la as Tt,ma as Mt}from"./chunk-UUVFH7BO.js";import"./chunk-O4XEQTEN.js";import"./chunk-JIXNSA67.js";import"./chunk-GTJIKXDB.js";import"./chunk-ZVP6GB4G.js";import"./chunk-S2GAEH2F.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-BGG3ZSMW.js";import"./chunk-XGOBZCYC.js";import"./chunk-WCXXXAHV.js";import"./chunk-JWDJMFU6.js";import"./chunk-GRMCAO3Q.js";import"./chunk-KZKDVIOE.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-WEPON4FP.js";import"./chunk-AKLZ4YO2.js";import"./chunk-PPUN7YHA.js";import"./chunk-Y4CYQV7G.js";import"./chunk-LLNPKE7H.js";import"./chunk-SHEUCITK.js";import"./chunk-QQYXYJOG.js";import"./chunk-GUQDPA6R.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-EMGB23H5.js";import{ca as yt,m as lt,n as ct,o as dt,p as mt,q as pt}from"./chunk-D6SWAB5J.js";import"./chunk-LVV7JBHM.js";import"./chunk-GLQLCBJS.js";import"./chunk-6W74CHNW.js";import{a as L}from"./chunk-UG2OF2EI.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-WUDVBPQV.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-SZDACK6O.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{s as ut}from"./chunk-5DFUUYEA.js";import"./chunk-WMTGAVPW.js";import"./chunk-VWTBHLMX.js";import"./chunk-YNA5T43U.js";import{a as ht}from"./chunk-ZQWWMAMJ.js";import"./chunk-3PGPN323.js";import"./chunk-2C3X6DVD.js";import"./chunk-56KNKUFF.js";import{f as gt,g as ft}from"./chunk-VXKNB4AW.js";import"./chunk-WPNRDEHW.js";import"./chunk-36AXN6ZB.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-FVG2BADS.js";import{j as it,k as rt,l as at}from"./chunk-JUIL2EW3.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import"./chunk-4VVHGR7H.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-2PJKGZWP.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{ma as tt,oa as st,pa as ot,ra as nt}from"./chunk-46JKX6CT.js";import"./chunk-UIBUZ2N3.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.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 Tg,b as dr,g as Cg}from"./chunk-FHBPKMCF.js";import{d as rg,e as zi,h as ig,i as ag}from"./chunk-AD4QZZVN.js";import{A as Ki,B as bg,D as kg,a as ut,b as eg,f as Dt,g as ng,h as sg,i as cg,j as lg,l as dg,m as gg,n as mg,o as Yi,p as pg,u as ug,v as fg,w as Vi,x as hg}from"./chunk-Z7XXUYBB.js";import{a as yg,c as wg,d as $g}from"./chunk-5NTWGUSJ.js";import"./chunk-EO4DEEXL.js";import"./chunk-QX2B4TJU.js";import{a as vg,b as xg,c as Sg,d as Eg,r as Ag}from"./chunk-2W3X6H7Z.js";import{a as tg,c as og}from"./chunk-6GLJIA25.js";import{a as Gi}from"./chunk-LNY6N73E.js";import"./chunk-SCJ5ZXEN.js";import{a as Ti,b as xl}from"./chunk-RKPAVWXF.js";import{$ as Hd,A as xd,B as Di,C as Sd,D as Ed,E as Ad,F as Td,G as Cd,H as Od,I as Id,J as Rd,K as Ld,L as sr,M as Ht,N as so,O as ln,P as rr,Q as ir,R as Ui,S as Fd,T as Ud,U as qd,V as Wd,W as Bd,X as Jd,Y as dn,Z as gn,_ as Gd,a as Rl,aa as Ge,b as jl,ba as ar,ca as os,da as qi,ea as zd,fa as Kd,ga as Ji,h as Js,ha as Qd,i as Pl,ia as cr,j as Zn,ja as mn,k as Gs,ka as lr,l as Ll,la as Hi,m as Fl,ma as Zd,n as Xl,o as Ql,p as Xs,q as ji,r as rd,s as md,t as pd,u as fd,v as hd,w as $d,x as bd,y as kd,z as vd}from"./chunk-4VUGJB5S.js";import{$ as or,A as dd,D as gd,E as tr,I as ud,Oa as Yd,Pa as Wi,Qa as Vd,Ra as Bi,X as es,_ as Pi,aa as jd,db as _t,fb as Xd,ha as no,ia as Nd,ja as Mi,la as Li,na as _d,oa as Dd,pa as ts,ta as nr,wa as Pd,x as ld,xa as Md,ya as Fi,z as _i}from"./chunk-O4XEQTEN.js";import{a as Nl,c as Oi,e as _l,f as Dl}from"./chunk-JIXNSA67.js";import"./chunk-GTJIKXDB.js";import"./chunk-ZVP6GB4G.js";import{a as Hs,b as zs,c as Ul,d as ql,e as Wl,g as Bl,h as Jl,j as Gl,k as Hl,l as zl,m as Yl,p as Ys,s as Vl,t as Kl}from"./chunk-S2GAEH2F.js";import"./chunk-VZLIBDLH.js";import{a as yd,b as wd}from"./chunk-EKJG63EJ.js";import"./chunk-BGG3ZSMW.js";import{c as Zl}from"./chunk-XGOBZCYC.js";import"./chunk-WCXXXAHV.js";import"./chunk-JWDJMFU6.js";import{b as Ri}from"./chunk-GRMCAO3Q.js";import"./chunk-KZKDVIOE.js";import{c as ed,e as Vs,g as Ks}from"./chunk-LQE73AZR.js";import{a as td,b as od,c as nd,d as sd}from"./chunk-2D3RYIDU.js";import"./chunk-WEPON4FP.js";import{a as id,b as To,c as ad,d as Qs,e as cd,f as Ni,i as Zs,j as Co,k as er}from"./chunk-AKLZ4YO2.js";import"./chunk-PPUN7YHA.js";import{a as Gt}from"./chunk-Y4CYQV7G.js";import{b as Qn}from"./chunk-LLNPKE7H.js";import{a as kl,b as vl}from"./chunk-SHEUCITK.js";import{a as Ci,e as Sl,f as El,h as Al,i as Tl,k as Cl,l as Ol,m as Il}from"./chunk-QQYXYJOG.js";import{a as Ii,p as Ml}from"./chunk-GUQDPA6R.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as pt}from"./chunk-EMGB23H5.js";import{L as oo,R as wl,ca as bl,g as nl,r as sl,y as Ei,z as cl}from"./chunk-D6SWAB5J.js";import{E as yl,F as $l,b as en,g as on,h as qs,i as Ws,j as nn,k as ll,l as to,m as sn}from"./chunk-LVV7JBHM.js";import{e as fl,f as Ao,k as an}from"./chunk-GLQLCBJS.js";import{b as tn}from"./chunk-6W74CHNW.js";import"./chunk-WUDVBPQV.js";import"./chunk-SFQUP3BP.js";import{j as al}from"./chunk-X5C5W3E4.js";import{a as rn}from"./chunk-GV7S5BAX.js";import{e as dl}from"./chunk-GSX4NK2N.js";import{c as gl}from"./chunk-SZDACK6O.js";import{f as ml,g as pl,h as Ai}from"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{a as il,k as ul}from"./chunk-5DFUUYEA.js";import{a as Bs,b as de,c as Me,d as cn,e as hl}from"./chunk-WMTGAVPW.js";import"./chunk-VWTBHLMX.js";import{a as xi}from"./chunk-YNA5T43U.js";import"./chunk-ZQWWMAMJ.js";import"./chunk-3PGPN323.js";import"./chunk-2C3X6DVD.js";import{c as Eo,e as tl}from"./chunk-56KNKUFF.js";import{g as eo,i as Us}from"./chunk-VXKNB4AW.js";import"./chunk-WPNRDEHW.js";import"./chunk-36AXN6ZB.js";import"./chunk-KA2UIZXG.js";import{a as Si,b as rl}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-FVG2BADS.js";import{a as $i,b as Dc,c as Wf,d as Ps,e as Pc,f as Vc,g as Yf,h as Kc,i as Vf,m as Zo,n as Qc,q as Zc,u as el,y as Nt,z as Xn}from"./chunk-JUIL2EW3.js";import{a as Jt,b as Qo,e as Hc,f as Kn}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as Fs,b as Xc}from"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import{n as ol}from"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import"./chunk-4VVHGR7H.js";import"./chunk-JXF54PT7.js";import"./chunk-2PJKGZWP.js";import{a as jt,b as qf}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{A as Wc,B as Jf,P as Bc,Q as bi,S as ki,Z as Gf,_ as vi,aa as Jc,ba as Hf,h as Mc,i as Lc,j as Fc,k as Uc,l as qc,m as Bf,ma as Gc,na as Ms,oa as T,pa as Ls,ra as ae}from"./chunk-46JKX6CT.js";import{f as mt,n as Vn}from"./chunk-UIBUZ2N3.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import{g as zc,k as Yc,l as zf}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Kf}from"commander";var Og=new Kf().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 jl({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()});ae();import{Command as Xf}from"commander";import{execFileSync as bt}from"node:child_process";import{cpSync as Ig,existsSync as Zi,mkdirSync as Xi,mkdtempSync as Qf,readdirSync as Zf,rmSync as Rg,writeFileSync as jg}from"node:fs";import{dirname as Ng,join as He}from"node:path";import{homedir as gr,release as eh,tmpdir as th}from"node:os";import{setTimeout as oh}from"node:timers/promises";function mr(){let e=Ul(process.platform,process.arch,eh());if(e)throw new Error(e)}function pr(){let e=He(gr(),"Library/LaunchAgents"),t=[];try{t=Zf(e).filter(Bl)}catch{}let o=t.flatMap(n=>{let s=He(e,n);try{return[{file:s,plist:bt("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Jl(e,o)}function ns(e){return`gui/${process.getuid()}/${e.label}`}async function Qi(e){try{bt("launchctl",["bootout",ns(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{bt("launchctl",["print",ns(e)],{stdio:"pipe"})}catch{return}await oh(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function _g(e){if(!Zi(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{bt("launchctl",["print",ns(e)],{stdio:"pipe"})}catch{t=!1}t||bt("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),bt("launchctl",["kickstart",ns(e)],{stdio:"pipe"})}function nh(){let e=Yl();if(e&&Zi(He(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 pn=new Xf("desktop").description("install and control the macOS desktop assistant");pn.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=>{mr();let t=T(),o=ql(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=nh(),i=He(gr(),"Applications"),{keep:a,remove:c}=pr();if(console.log(`Desktop assistant \u2192 ${He(i,Hs)}
1
+ import{a as Tg,b as dr,g as Cg}from"./chunk-FHBPKMCF.js";import{d as rg,e as zi,h as ig,i as ag}from"./chunk-AD4QZZVN.js";import{A as Ki,B as bg,D as kg,a as ut,b as eg,f as Dt,g as ng,h as sg,i as cg,j as lg,l as dg,m as gg,n as mg,o as Yi,p as pg,u as ug,v as fg,w as Vi,x as hg}from"./chunk-Z7XXUYBB.js";import{a as yg,c as wg,d as $g}from"./chunk-5NTWGUSJ.js";import"./chunk-EO4DEEXL.js";import"./chunk-QX2B4TJU.js";import{a as vg,b as xg,c as Sg,d as Eg,r as Ag}from"./chunk-2W3X6H7Z.js";import{a as tg,c as og}from"./chunk-6GLJIA25.js";import{a as Gi}from"./chunk-LNY6N73E.js";import"./chunk-SCJ5ZXEN.js";import{a as Ti,b as xl}from"./chunk-RKPAVWXF.js";import{$ as Hd,A as xd,B as Di,C as Sd,D as Ed,E as Ad,F as Td,G as Cd,H as Od,I as Id,J as Rd,K as Ld,L as sr,M as Ht,N as so,O as ln,P as rr,Q as ir,R as Ui,S as Fd,T as Ud,U as qd,V as Wd,W as Bd,X as Jd,Y as dn,Z as gn,_ as Gd,a as Rl,aa as Ge,b as jl,ba as ar,ca as os,da as qi,ea as zd,fa as Kd,ga as Ji,h as Js,ha as Qd,i as Pl,ia as cr,j as Zn,ja as mn,k as Gs,ka as lr,l as Ll,la as Hi,m as Fl,ma as Zd,n as Xl,o as Ql,p as Xs,q as ji,r as rd,s as md,t as pd,u as fd,v as hd,w as $d,x as bd,y as kd,z as vd}from"./chunk-UUVFH7BO.js";import{$ as or,A as dd,D as gd,E as tr,I as ud,Oa as Yd,Pa as Wi,Qa as Vd,Ra as Bi,X as es,_ as Pi,aa as jd,db as _t,fb as Xd,ha as no,ia as Nd,ja as Mi,la as Li,na as _d,oa as Dd,pa as ts,ta as nr,wa as Pd,x as ld,xa as Md,ya as Fi,z as _i}from"./chunk-O4XEQTEN.js";import{a as Nl,c as Oi,e as _l,f as Dl}from"./chunk-JIXNSA67.js";import"./chunk-GTJIKXDB.js";import"./chunk-ZVP6GB4G.js";import{a as Hs,b as zs,c as Ul,d as ql,e as Wl,g as Bl,h as Jl,j as Gl,k as Hl,l as zl,m as Yl,p as Ys,s as Vl,t as Kl}from"./chunk-S2GAEH2F.js";import"./chunk-VZLIBDLH.js";import{a as yd,b as wd}from"./chunk-EKJG63EJ.js";import"./chunk-BGG3ZSMW.js";import{c as Zl}from"./chunk-XGOBZCYC.js";import"./chunk-WCXXXAHV.js";import"./chunk-JWDJMFU6.js";import{b as Ri}from"./chunk-GRMCAO3Q.js";import"./chunk-KZKDVIOE.js";import{c as ed,e as Vs,g as Ks}from"./chunk-LQE73AZR.js";import{a as td,b as od,c as nd,d as sd}from"./chunk-2D3RYIDU.js";import"./chunk-WEPON4FP.js";import{a as id,b as To,c as ad,d as Qs,e as cd,f as Ni,i as Zs,j as Co,k as er}from"./chunk-AKLZ4YO2.js";import"./chunk-PPUN7YHA.js";import{a as Gt}from"./chunk-Y4CYQV7G.js";import{b as Qn}from"./chunk-LLNPKE7H.js";import{a as kl,b as vl}from"./chunk-SHEUCITK.js";import{a as Ci,e as Sl,f as El,h as Al,i as Tl,k as Cl,l as Ol,m as Il}from"./chunk-QQYXYJOG.js";import{a as Ii,p as Ml}from"./chunk-GUQDPA6R.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as pt}from"./chunk-EMGB23H5.js";import{L as oo,R as wl,ca as bl,g as nl,r as sl,y as Ei,z as cl}from"./chunk-D6SWAB5J.js";import{E as yl,F as $l,b as en,g as on,h as qs,i as Ws,j as nn,k as ll,l as to,m as sn}from"./chunk-LVV7JBHM.js";import{e as fl,f as Ao,k as an}from"./chunk-GLQLCBJS.js";import{b as tn}from"./chunk-6W74CHNW.js";import"./chunk-WUDVBPQV.js";import"./chunk-SFQUP3BP.js";import{j as al}from"./chunk-X5C5W3E4.js";import{a as rn}from"./chunk-GV7S5BAX.js";import{e as dl}from"./chunk-GSX4NK2N.js";import{c as gl}from"./chunk-SZDACK6O.js";import{f as ml,g as pl,h as Ai}from"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{a as il,k as ul}from"./chunk-5DFUUYEA.js";import{a as Bs,b as de,c as Me,d as cn,e as hl}from"./chunk-WMTGAVPW.js";import"./chunk-VWTBHLMX.js";import{a as xi}from"./chunk-YNA5T43U.js";import"./chunk-ZQWWMAMJ.js";import"./chunk-3PGPN323.js";import"./chunk-2C3X6DVD.js";import{c as Eo,e as tl}from"./chunk-56KNKUFF.js";import{g as eo,i as Us}from"./chunk-VXKNB4AW.js";import"./chunk-WPNRDEHW.js";import"./chunk-36AXN6ZB.js";import"./chunk-KA2UIZXG.js";import{a as Si,b as rl}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-FVG2BADS.js";import{a as $i,b as Dc,c as Wf,d as Ps,e as Pc,f as Vc,g as Yf,h as Kc,i as Vf,m as Zo,n as Qc,q as Zc,u as el,y as Nt,z as Xn}from"./chunk-JUIL2EW3.js";import{a as Jt,b as Qo,e as Hc,f as Kn}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as Fs,b as Xc}from"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import{n as ol}from"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import"./chunk-4VVHGR7H.js";import"./chunk-JXF54PT7.js";import"./chunk-2PJKGZWP.js";import{a as jt,b as qf}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{A as Wc,B as Jf,P as Bc,Q as bi,S as ki,Z as Gf,_ as vi,aa as Jc,ba as Hf,h as Mc,i as Lc,j as Fc,k as Uc,l as qc,m as Bf,ma as Gc,na as Ms,oa as T,pa as Ls,ra as ae}from"./chunk-46JKX6CT.js";import{f as mt,n as Vn}from"./chunk-UIBUZ2N3.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import{g as zc,k as Yc,l as zf}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Kf}from"commander";var Og=new Kf().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 jl({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()});ae();import{Command as Xf}from"commander";import{execFileSync as bt}from"node:child_process";import{cpSync as Ig,existsSync as Zi,mkdirSync as Xi,mkdtempSync as Qf,readdirSync as Zf,rmSync as Rg,writeFileSync as jg}from"node:fs";import{dirname as Ng,join as He}from"node:path";import{homedir as gr,release as eh,tmpdir as th}from"node:os";import{setTimeout as oh}from"node:timers/promises";function mr(){let e=Ul(process.platform,process.arch,eh());if(e)throw new Error(e)}function pr(){let e=He(gr(),"Library/LaunchAgents"),t=[];try{t=Zf(e).filter(Bl)}catch{}let o=t.flatMap(n=>{let s=He(e,n);try{return[{file:s,plist:bt("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Jl(e,o)}function ns(e){return`gui/${process.getuid()}/${e.label}`}async function Qi(e){try{bt("launchctl",["bootout",ns(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{bt("launchctl",["print",ns(e)],{stdio:"pipe"})}catch{return}await oh(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function _g(e){if(!Zi(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{bt("launchctl",["print",ns(e)],{stdio:"pipe"})}catch{t=!1}t||bt("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),bt("launchctl",["kickstart",ns(e)],{stdio:"pipe"})}function nh(){let e=Yl();if(e&&Zi(He(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 pn=new Xf("desktop").description("install and control the macOS desktop assistant");pn.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=>{mr();let t=T(),o=ql(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=nh(),i=He(gr(),"Applications"),{keep:a,remove:c}=pr();if(console.log(`Desktop assistant \u2192 ${He(i,Hs)}
2
2
  Computer-use helper \u2192 ${He(i,zs)}
3
3
  Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
4
4
  Daemon \u2192 ${s}
@@ -488,7 +488,7 @@ return aid ?? null`}function L$(e,t){if(e.kind==="path"){let s=e.pts,r=s[Math.fl
488
488
  Plan ${Y.dim(`[${s.state}] by ${s.createdBy}, ${In(s.createdAt)}`)}`),gu(n.steps(e)),console.log(`
489
489
  Log`);for(let r of n.events(e))console.log(Y.dim(` ${In(r.at)} ${r.step?`step ${r.step} `:""}${r.kind}: ${r.detail}`))}});Go.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(Y.red(" give one of --retry, --skip or --done")),process.exitCode=1;return}let s=Vr();if(!s)return;let r=du();if(!r){process.exitCode=1;return}let i=Number(t),a=pd(s,r,{requestId:e,step:i,action:n[0],detail:o.note},Date.now());if(a){console.error(Y.red(` ${a}`)),process.exitCode=1;return}console.log(Y.green(` \u2713 step ${i} of ${e}: ${n[0]==="retry"?"handed over again":n[0]==="skip"?"skipped":"done"}`)+Y.dim(" (the daemon goes on within a minute)")),gu(r.steps(e))});function pu(e,t,o,n){Go.command(`${e} <id>`).description(t).option(o,e==="done"?"link to the proof: PR, issue, message, deploy":"why it is dropped").action((s,r)=>{let i=Vr();if(!i)return;let a=e==="done"?r.evidence:r.reason??"dropped by the owner";if(!a){console.error(Y.red(` ${n}`)),process.exitCode=1;return}let c=i.get(s);if(!c||c.state==="candidate"){console.error(Y.red(` no request "${s}"`)),process.exitCode=1;return}if(!i.close(s,e==="done"?"done":"dropped",a,Date.now())){console.error(Y.red(` ${s} is already closed (${lu[c.state]??c.state})`)),process.exitCode=1;return}console.log(Y.green(` \u2713 ${s} ${e==="done"?"closed as done":"dropped"}`))})}pu("done","close a request as finished, with a link to the evidence","--evidence <link>","a finished request needs --evidence <link>");pu("drop","drop a request you no longer want","--reason <text>","");Go.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("--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').action(async e=>{let t={};try{let s=(a,c)=>{if(c===void 0)return;let l=Number(c);if(!(l>0))throw new Error(`${a} must be a positive number`);return l},r=(a,c)=>a===void 0?void 0:a===c?[]:a.split(",").map(l=>l.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"}t.from=r(e.from,"none"),t.channels=r(e.channels,"all"),t.staleAfterHours=s("--stale-hours",e.staleHours),t.retentionDays=s("--retention-days",e.retentionDays);let i={};if(e.plans!==void 0){if(e.plans!=="on"&&e.plans!=="off")throw new Error("--plans takes on or off");i.enabled=e.plans==="on"}if(i.stallMinutes=s("--stall-minutes",e.stallMinutes),e.maxNudges!==void 0){let a=Number(e.maxNudges);if(!Number.isInteger(a)||a<0)throw new Error("--max-nudges must be a whole number, 0 or more");i.maxNudges=a}i.approveKinds=r(e.approveKinds,"none"),i.disabledAgents=r(e.plansOffFor,"none"),Object.values(i).some(a=>a!==void 0)&&(t.plans=i)}catch(s){console.error(Y.red(` ${s.message}`)),process.exitCode=1;return}if(Object.values(t).some(s=>s!==void 0)){let s=await dd(t);if(!s.success){console.error(Y.red(` ${s.error}`)),process.exitCode=1;return}console.log(Y.green(" \u2713 saved")+(s.reloaded?Y.dim(" (daemon reloaded)"):""))}let o=_i();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)`);let n=o.plans??md;console.log(` Plans ${n.enabled?"on":"off"}`),console.log(` Nudge a quiet step after ${n.stallMinutes} minute(s), up to ${n.maxNudges} time(s)`),console.log(` You approve up front ${n.approveKinds.length?n.approveKinds.join(", "):"nothing"}`),console.log(` Plans off for ${n.disabledAgents.length?n.disabledAgents.join(", "):"no agent"}`)});import{Command as rk}from"commander";import Rn from"chalk";ae();var uu=new rk("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",Vi.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(Rn.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await de(r=>{n=hg(r,e,t==="on")});s.success||(console.error(Rn.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(Rn.green(`\u2713 ${n}`)),s.reloaded&&console.log(Rn.dim(" daemon hot-reloaded"))}let o=T().requestStatus.channels.map(n=>n.toLowerCase());for(let n of Vi)console.log(` ${n.padEnd(8)} ${o.includes(n)?Rn.green("on"):Rn.dim("off")}`)});import{Command as Ck}from"commander";import jn from"chalk";import he from"chalk";import Ss from"prompts";import{readFileSync as ik,writeFileSync as ak,existsSync as ck}from"fs";import{resolve as fu}from"path";var lk=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function dk(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Za(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function hu(e=".env"){let t=fu(e);if(!ck(t))return[];let o=ik(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(lk);r?n.push({kind:"kv",key:r[1],value:dk(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function gk(e){return e.map(t=>t.kind==="kv"?`${t.key}=${Za(t.value)}`:t.raw).join(`
490
490
  `)+`
491
- `}function xs(e,t,o=".env"){let n=fu(o),s=hu(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Za(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Za(t)}`})),ak(n,gk(s))}function ec(e,t=".env"){return hu(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var yu="https://t.me/BotFather";async function mk(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 pk(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 wu(e={}){console.log(),console.log(he.bold(" Connect Telegram")),console.log(),console.log(he.dim(` 1. Open ${yu}`)),console.log(he.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(he.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await Ss({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&Ro(yu);let{token:o}=await Ss({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:$=>/^\d+:[A-Za-z0-9_-]{20,}$/.test($.trim())||"That doesn't look like a Telegram token"});o||(console.log(he.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await mk(o.trim());n||(console.log(he.red("\u2717 invalid or revoked")),process.exit(1)),console.log(he.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(he.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(he.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Ss({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(he.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||g;d[f]&&d[f].agentBinding!==g&&(f=(await Ss({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(he.red(" Aborted")),process.exit(1));let u=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;xs(u,o.trim()),process.env[u]=o.trim();let p=await de($=>{Me($,"channels.telegram.enabled",!0),Me($,`channels.telegram.accounts.${f}`,{token:`\${${u}}`,agentBinding:g});let v=cn($,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),Me($,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(p.success||(console.log(he.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(he.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(he.dim(` Token stored in .env as ${u}`)),console.log(he.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(he.dim(" Daemon hot-reloaded.")):console.log(he.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await Ss({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!y)return;console.log(),console.log(he.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(he.dim(" Waiting up to 90s..."));let w=await pk(o.trim(),9e4);if(!w){console.log(he.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(he.dim(" agentx config set notifications.destination.channel telegram")),console.log(he.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(he.dim(` agentx config set notifications.destination.accountId ${f}`));return}let k=await de($=>{Me($,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:f})},{configPath:e.configPath});if(!k.success){console.log(he.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(he.green(" \u2713 Default --notify target set")),console.log(he.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(he.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(he.dim(" Daemon hot-reloaded."))}import Te from"chalk";import tc from"prompts";import{existsSync as nc,mkdirSync as uk,readdirSync as fk,readFileSync as $u}from"fs";import{resolve as oc}from"path";var hk=".agentx/whatsapp-sessions";function yk(){let e=oc(process.cwd(),".agentx/daemon.pid");if(!nc(e))return!1;try{let t=parseInt($u(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function wk(e){if(!nc(e))return!1;try{return fk(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function $k(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Te.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Te.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;uk(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(g=>{let f=setTimeout(()=>{t(Te.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async u=>{if(u.qr){t(Te.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:p}=await import("qrcode-terminal");p.generate(u.qr,{small:!0})}catch{t(` QR: ${u.qr}`)}t("")}if(u.connection==="open"){clearTimeout(f),t(Te.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}u.connection==="close"&&!u.qr&&u.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(Te.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function bu(e={}){if(console.log(),console.log(Te.bold(" Connect WhatsApp")),console.log(),yk()){console.log(Te.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Te.dim(" agentx daemon stop")),console.log();let{cont:l}=await tc({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Te.red(" Aborted")),process.exit(1))}let t=e.configPath||oc(process.cwd(),"agentx.json");nc(t)||(console.log(Te.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse($u(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||hk,s=oc(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Te.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await tc({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(g=>({title:g,value:g})),initial:0})).agent),i||(console.log(Te.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(wk(s)&&a){let{keep:l}=await tc({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(Te.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await $k(s,g=>console.log(g))||(console.log(Te.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await de(l=>{Me(l,"channels.whatsapp.enabled",!0),Me(l,"channels.whatsapp.sessionDir",n),Me(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(Te.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Te.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Te.dim(` Session: ${n}`)),console.log(Te.dim(" Start the daemon to begin receiving:")),console.log(Te.dim(" agentx daemon start")),console.log(Te.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Te.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Te.dim(" Add routes later with:")),console.log(Te.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import{randomBytes as bk}from"crypto";import Pe from"chalk";import ku from"prompts";var Kr="agentx-mesh:",Xr="//join/";function kk(e){return Buffer.from(e,"utf-8").toString("base64url")}function vk(e){return Buffer.from(e,"base64url").toString("utf-8")}function xk(e){return`${Kr}${Xr}${kk(JSON.stringify(e))}`}function Sk(e){if(!e.startsWith(`${Kr}${Xr}`))throw new Error(`Not a mesh invite link \u2014 expected ${Kr}${Xr}\u2026`);let t=e.slice(Kr.length+Xr.length),o=JSON.parse(vk(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 Ek(){return bk(32).toString("hex")}function Ak(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function Tk(e){return e?.node?.name||e?.node?.id||"node"}async function vu(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(Pe.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=ec("MESH_TOKEN");i||(i=Ek(),xs("MESH_TOKEN",i),console.log(Pe.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Ak(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await ku({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(Pe.red(" Aborted")),process.exit(1)),a=d}let l=await de(d=>{Me(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Pe.red(` \u2717 ${l.error}`)),process.exit(1));let g=xk({url:a,token:i,name:Tk(r),version:1});console.log(),console.log(Pe.bold(" Mesh invite")),console.log(),console.log(` ${Pe.cyan(g)}`),console.log(),console.log(Pe.dim(" Run on the other node:")),console.log(Pe.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Pe.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function xu(e,t={}){let o;try{o=Sk(e)}catch(r){console.log(Pe.red(` \u2717 ${r.message}`)),process.exit(1)}let n=ec("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await ku({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Pe.red(" Aborted (keeping existing .env)")),process.exit(1))}xs("MESH_TOKEN",o.token);let s=await de(r=>{Me(r,"mesh.enabled",!0);let i=cn(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),Me(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Pe.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Pe.green(" \u2713 Joined mesh")),console.log(Pe.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Pe.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Pe.dim(" Daemon hot-reloaded.")):console.log(Pe.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(Pe.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Pe.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Pe.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Nn=new Ck().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Nn.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 wu({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Nn.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 bu({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Su=Nn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Su.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 vu({url:e.url,configPath:e.config})});Su.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 xu(e,{configPath:t.config})});Nn.action(()=>{console.log(),console.log(jn.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${jn.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${jn.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${jn.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${jn.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(jn.dim(" GitLab connect is the next slice.")),console.log()});ae();import{Command as Ok}from"commander";import Q from"chalk";var Ho=new Ok().name("usage").description("token usage analysis and reporting");Ho.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(Q.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(Q.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${Q.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: ${Q.red(String(s.totalErrors))}`),console.log(),console.log(Q.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${Q.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${Q.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(Q.red(" Daemon not running. Start with: agentx daemon start")):console.log(Q.red(` ${e.message}`))}});Ho.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let t=T(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(f=>a(f.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:Q.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(Q.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(Q.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,u=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",p=Math.max(1,Math.round((d.resetsAt-c)/6e4)),y=d.resetsAt>c?p<60?`resets in ${p} min`:p<48*60?`resets in ${Math.round(p/60)} h`:`resets in ${Math.round(p/1440)} days`:"",w=l.has(d.window)?Q.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[u,y,w].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${g(i.maxPerHour)} in the last hour, ${i.last5h}${g(i.maxPer5h)} in the last 5 hours`),l.size&&console.log(Q.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(Q.red(" Daemon not running. Start with: agentx daemon start")):console.log(Q.red(` ${t.message}`))}});Ho.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(Q.red(` Script not found: ${s}`)),console.log(Q.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(Q.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(Q.red(" Analysis failed. Is Python 3 installed?"))}});Ho.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-W7DFDEFN.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=p=>/^\d{4}-\d{2}-\d{2}$/.test(p)&&!Number.isNaN(Date.parse(p));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(Q.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(p){console.log(Q.red(` Cannot read baseline ${e.baseline}: ${p.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=p=>p===null?"-":`$${p.toFixed(p<10?3:2)}`,g=p=>`${(p/1e6).toFixed(1)}M`;console.log(),console.log(Q.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(Q.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(Q.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let u=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(p=>[p,a.channels[p],c?.channels[p]]).sort((p,y)=>(y[1]?.cost||0)-(p[1]?.cost||0));u.push(["TOTAL",a.total,c?.total]);for(let[p,y,w]of u){let k=r(y),$=` ${p.padEnd(14)} ${String(y?.tasks||0).padStart(6)} ${g(y?.cacheRead||0).padStart(11)} ${g(y?.cacheCreate||0).padStart(11)} ${g(y?.output||0).padStart(8)} ${l(y?.cost||0).padStart(10)} ${l(k).padStart(9)}`;if(c){let v=r(w),A=k!==null&&v?`${((k-v)/v*100).toFixed(0)}%`:"-";$+=` ${l(v).padStart(9)} ${A.padStart(7)}`}console.log($)}console.log(),c&&console.log(Q.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(Q.dim(` Saved ${e.save}`)),console.log()});Ho.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-WSY4SHHL.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-EYGICEXY.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,f)=>{for(let u of d.commands??[]){let p=f?`${f} ${u.name()}`:u.name();c.push(p),l(u,p)}};l(i,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(Q.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${Q.dim("\xB7")} ${d}`);console.log(),console.log(Q.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(Q.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(Q.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(Q.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(Q.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(Q.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=Q.dim(`${r.days}d`);console.log(` ${Q.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(Q.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Ik}from"commander";import je from"chalk";import{readFileSync as Rk}from"fs";import{resolve as jk}from"path";ae();var wo=new Ik().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");wo.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{tl(jk(process.cwd(),".env"))}catch{}let t=Nk(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-DQR2OSV7.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 Nk(e,t){try{let o=T();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.
491
+ `}function xs(e,t,o=".env"){let n=fu(o),s=hu(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Za(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Za(t)}`})),ak(n,gk(s))}function ec(e,t=".env"){return hu(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var yu="https://t.me/BotFather";async function mk(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 pk(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 wu(e={}){console.log(),console.log(he.bold(" Connect Telegram")),console.log(),console.log(he.dim(` 1. Open ${yu}`)),console.log(he.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(he.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await Ss({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&Ro(yu);let{token:o}=await Ss({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:$=>/^\d+:[A-Za-z0-9_-]{20,}$/.test($.trim())||"That doesn't look like a Telegram token"});o||(console.log(he.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await mk(o.trim());n||(console.log(he.red("\u2717 invalid or revoked")),process.exit(1)),console.log(he.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(he.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(he.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Ss({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(he.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||g;d[f]&&d[f].agentBinding!==g&&(f=(await Ss({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(he.red(" Aborted")),process.exit(1));let u=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;xs(u,o.trim()),process.env[u]=o.trim();let p=await de($=>{Me($,"channels.telegram.enabled",!0),Me($,`channels.telegram.accounts.${f}`,{token:`\${${u}}`,agentBinding:g});let v=cn($,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),Me($,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(p.success||(console.log(he.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(he.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(he.dim(` Token stored in .env as ${u}`)),console.log(he.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(he.dim(" Daemon hot-reloaded.")):console.log(he.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await Ss({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!y)return;console.log(),console.log(he.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(he.dim(" Waiting up to 90s..."));let w=await pk(o.trim(),9e4);if(!w){console.log(he.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(he.dim(" agentx config set notifications.destination.channel telegram")),console.log(he.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(he.dim(` agentx config set notifications.destination.accountId ${f}`));return}let k=await de($=>{Me($,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:f})},{configPath:e.configPath});if(!k.success){console.log(he.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(he.green(" \u2713 Default --notify target set")),console.log(he.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(he.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(he.dim(" Daemon hot-reloaded."))}import Te from"chalk";import tc from"prompts";import{existsSync as nc,mkdirSync as uk,readdirSync as fk,readFileSync as $u}from"fs";import{resolve as oc}from"path";var hk=".agentx/whatsapp-sessions";function yk(){let e=oc(process.cwd(),".agentx/daemon.pid");if(!nc(e))return!1;try{let t=parseInt($u(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function wk(e){if(!nc(e))return!1;try{return fk(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function $k(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Te.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Te.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;uk(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(g=>{let f=setTimeout(()=>{t(Te.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async u=>{if(u.qr){t(Te.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:p}=await import("qrcode-terminal");p.generate(u.qr,{small:!0})}catch{t(` QR: ${u.qr}`)}t("")}if(u.connection==="open"){clearTimeout(f),t(Te.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}u.connection==="close"&&!u.qr&&u.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(Te.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function bu(e={}){if(console.log(),console.log(Te.bold(" Connect WhatsApp")),console.log(),yk()){console.log(Te.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Te.dim(" agentx daemon stop")),console.log();let{cont:l}=await tc({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Te.red(" Aborted")),process.exit(1))}let t=e.configPath||oc(process.cwd(),"agentx.json");nc(t)||(console.log(Te.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse($u(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||hk,s=oc(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Te.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await tc({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(g=>({title:g,value:g})),initial:0})).agent),i||(console.log(Te.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(wk(s)&&a){let{keep:l}=await tc({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(Te.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await $k(s,g=>console.log(g))||(console.log(Te.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await de(l=>{Me(l,"channels.whatsapp.enabled",!0),Me(l,"channels.whatsapp.sessionDir",n),Me(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(Te.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Te.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Te.dim(` Session: ${n}`)),console.log(Te.dim(" Start the daemon to begin receiving:")),console.log(Te.dim(" agentx daemon start")),console.log(Te.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Te.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Te.dim(" Add routes later with:")),console.log(Te.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import{randomBytes as bk}from"crypto";import Pe from"chalk";import ku from"prompts";var Kr="agentx-mesh:",Xr="//join/";function kk(e){return Buffer.from(e,"utf-8").toString("base64url")}function vk(e){return Buffer.from(e,"base64url").toString("utf-8")}function xk(e){return`${Kr}${Xr}${kk(JSON.stringify(e))}`}function Sk(e){if(!e.startsWith(`${Kr}${Xr}`))throw new Error(`Not a mesh invite link \u2014 expected ${Kr}${Xr}\u2026`);let t=e.slice(Kr.length+Xr.length),o=JSON.parse(vk(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 Ek(){return bk(32).toString("hex")}function Ak(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function Tk(e){return e?.node?.name||e?.node?.id||"node"}async function vu(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(Pe.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=ec("MESH_TOKEN");i||(i=Ek(),xs("MESH_TOKEN",i),console.log(Pe.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Ak(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await ku({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(Pe.red(" Aborted")),process.exit(1)),a=d}let l=await de(d=>{Me(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Pe.red(` \u2717 ${l.error}`)),process.exit(1));let g=xk({url:a,token:i,name:Tk(r),version:1});console.log(),console.log(Pe.bold(" Mesh invite")),console.log(),console.log(` ${Pe.cyan(g)}`),console.log(),console.log(Pe.dim(" Run on the other node:")),console.log(Pe.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Pe.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function xu(e,t={}){let o;try{o=Sk(e)}catch(r){console.log(Pe.red(` \u2717 ${r.message}`)),process.exit(1)}let n=ec("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await ku({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Pe.red(" Aborted (keeping existing .env)")),process.exit(1))}xs("MESH_TOKEN",o.token);let s=await de(r=>{Me(r,"mesh.enabled",!0);let i=cn(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),Me(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Pe.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Pe.green(" \u2713 Joined mesh")),console.log(Pe.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Pe.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Pe.dim(" Daemon hot-reloaded.")):console.log(Pe.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(Pe.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Pe.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Pe.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Nn=new Ck().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Nn.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 wu({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Nn.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 bu({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Su=Nn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Su.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 vu({url:e.url,configPath:e.config})});Su.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 xu(e,{configPath:t.config})});Nn.action(()=>{console.log(),console.log(jn.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${jn.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${jn.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${jn.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${jn.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(jn.dim(" GitLab connect is the next slice.")),console.log()});ae();import{Command as Ok}from"commander";import Q from"chalk";var Ho=new Ok().name("usage").description("token usage analysis and reporting");Ho.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(Q.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(Q.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${Q.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: ${Q.red(String(s.totalErrors))}`),console.log(),console.log(Q.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${Q.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${Q.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(Q.red(" Daemon not running. Start with: agentx daemon start")):console.log(Q.red(` ${e.message}`))}});Ho.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let t=T(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(f=>a(f.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:Q.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(Q.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(Q.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,u=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",p=Math.max(1,Math.round((d.resetsAt-c)/6e4)),y=d.resetsAt>c?p<60?`resets in ${p} min`:p<48*60?`resets in ${Math.round(p/60)} h`:`resets in ${Math.round(p/1440)} days`:"",w=l.has(d.window)?Q.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[u,y,w].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${g(i.maxPerHour)} in the last hour, ${i.last5h}${g(i.maxPer5h)} in the last 5 hours`),l.size&&console.log(Q.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(Q.red(" Daemon not running. Start with: agentx daemon start")):console.log(Q.red(` ${t.message}`))}});Ho.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(Q.red(` Script not found: ${s}`)),console.log(Q.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(Q.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(Q.red(" Analysis failed. Is Python 3 installed?"))}});Ho.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-W7DFDEFN.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=p=>/^\d{4}-\d{2}-\d{2}$/.test(p)&&!Number.isNaN(Date.parse(p));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(Q.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(p){console.log(Q.red(` Cannot read baseline ${e.baseline}: ${p.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=p=>p===null?"-":`$${p.toFixed(p<10?3:2)}`,g=p=>`${(p/1e6).toFixed(1)}M`;console.log(),console.log(Q.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(Q.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(Q.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let u=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(p=>[p,a.channels[p],c?.channels[p]]).sort((p,y)=>(y[1]?.cost||0)-(p[1]?.cost||0));u.push(["TOTAL",a.total,c?.total]);for(let[p,y,w]of u){let k=r(y),$=` ${p.padEnd(14)} ${String(y?.tasks||0).padStart(6)} ${g(y?.cacheRead||0).padStart(11)} ${g(y?.cacheCreate||0).padStart(11)} ${g(y?.output||0).padStart(8)} ${l(y?.cost||0).padStart(10)} ${l(k).padStart(9)}`;if(c){let v=r(w),A=k!==null&&v?`${((k-v)/v*100).toFixed(0)}%`:"-";$+=` ${l(v).padStart(9)} ${A.padStart(7)}`}console.log($)}console.log(),c&&console.log(Q.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(Q.dim(` Saved ${e.save}`)),console.log()});Ho.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-WSY4SHHL.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-LGCT7FFJ.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,f)=>{for(let u of d.commands??[]){let p=f?`${f} ${u.name()}`:u.name();c.push(p),l(u,p)}};l(i,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(Q.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${Q.dim("\xB7")} ${d}`);console.log(),console.log(Q.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(Q.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(Q.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(Q.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(Q.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(Q.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=Q.dim(`${r.days}d`);console.log(` ${Q.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(Q.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Ik}from"commander";import je from"chalk";import{readFileSync as Rk}from"fs";import{resolve as jk}from"path";ae();var wo=new Ik().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");wo.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{tl(jk(process.cwd(),".env"))}catch{}let t=Nk(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-DQR2OSV7.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 Nk(e,t){try{let o=T();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.
492
492
  `)),{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}}}}wo.command("list").description("list configured boards").action(()=>{try{let e=T();if(!e.boards?.length){console.log(je.dim(`
493
493
  No boards configured.
494
494
  `));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)}});wo.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{Es(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)}});wo.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{Es(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 sc=wo.command("column").description("manage a board's columns (add / remove / edit / list)");sc.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(Rk("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)}});sc.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{Es(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)}});sc.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{Es(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)}});wo.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Es(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 Es(e){let{summary:t,backupPath:o}=ut(n=>e(n));console.log(je.green(`
@@ -501,7 +501,7 @@ ${P.content}
501
501
  --- END ENTRY ---`).join(`
502
502
 
503
503
  `),M="";if(e.facts!==!1){let{extractHints:P,resolveFacts:we,mergeRecords:te,renderFactsBlock:O,installPrompts:me,defaultSources:De,recordsFromEntries:Ze}=await import("./facts-ROUMKS7I.js");if(!l){let ie=new Set;for(let dt of n.listAgents())for(let Bt of n.getAgentWiki(dt).listArticles(dt))Bt.meta.type==="person"&&ie.add(Bt.meta.title);l=[...ie]}let $e=P(b.map(ie=>({context:ie.sourceContext,content:ie.content,sender:typeof ie.meta?.sender=="string"?ie.meta.sender:void 0})),{known:l}),L=Ze(b);if($e.length>0||L.length>0){let ie=De(),{records:dt,results:Bt}=$e.length>0?await we($e,{sources:ie}):{records:[],results:[]},gt=te([...L,...dt]);M=O(gt);let Ko=[...L.length>0?[`entries:${L.length}`]:[],...Bt.filter($t=>$t.records.length>0).map($t=>`${$t.source}:${$t.records.length}`)];console.log(m.dim(` Facts: ${$e.length} entities \u2192 ${gt.length} resolved${Ko.length?` (${Ko.join(" ")})`:""}`));for(let $t of me(Bt,ie))console.log(m.yellow(` ! ${$t.source} ${$t.kind} \u2014 would supply ${$t.provides.join(", ")}`)),console.log(m.dim(` ${$t.hint}`))}}let z=N.articles.filter(P=>P.path&&!P.path.includes("/_versions/")),W=await vg(b,x,$,z);W.length>0&&console.log(m.dim(` Existing: ${W.map(P=>P.path).join(", ")}`));let K=xg(W),Ce=Ii(t,$,j,N.articles,I,b.length,M,K);console.log(m.dim(` Mode: ${cc(t)}`));let le=q(x.baseDir,"_tmp");qt(le,{recursive:!0});let Je=q(le,"absorb-prompt.txt");Ut(Je,Ce),console.log(m.dim(` Compiling with Claude (${o})...`));let ve={kind:"call",at:"",label:y,agent:$,model:o,entries:b.length,articles:0,refused:0,failed:!0,wallMs:0,promptChars:Ce.length,promptParts:{entries:I.length,catalog:Ce.length-Ii(t,$,j,[],I,b.length,M,K).length,catalogArticles:N.articles.length,covering:K.length,facts:M.length,worldview:j.length}},D=Date.now();ve.prepMs=D-v;try{let P,we=!1;try{P=zo(`cat '${Je}' | claude -p - --output-format json --max-turns 3 --model '${o}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Eo(),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(L){if(P=L.stdout||"",!P)throw L;we=!0}let te=P;try{let L=JSON.parse(P);Object.assign(ve,Ag(L)),L.is_error===!0&&(we=!0),te=L.result||L.content||"",te||(console.log(m.dim(` Claude envelope keys: ${Object.keys(L).join(", ")}`)),console.log(m.dim(` is_error: ${L.is_error}, stop_reason: ${L.stop_reason}`)))}catch{}let O=Eu(te);if("error"in O){console.log(m.red(` ${O.error}`)),console.log(m.dim(` First 500 chars: ${te.slice(0,500)}`));continue}let{articles:me,gaps:De}=O,Ze=new Set,$e=new Set;for(let L of me){let ie=new Date().toISOString().slice(0,10),dt=Array.isArray(L.sources)?L.sources:[],Bt=Eg(L,z);Bt!==L.path&&(console.log(m.dim(` ~ ${L.path} \u2192 ${Bt} (an article with this title exists)`)),L.path=Bt);let gt=x.readArticle(L.path);if(gt){let Xo=Sg(gt.content,String(L.content??""));if(Xo.length>0){console.log(m.yellow(` ! refused ${L.path}: the rewrite drops ${Xo.length} fact(s) the article has`)),console.log(m.dim(` ${Xo.slice(0,8).join("; ")}${Xo.length>8?"; \u2026":""}`));for(let Uf of dt)Ze.add(Uf);ve.refused++;continue}}let Ko=d(dt,b)??gt?.meta.graphPath;x.writeArticle(L.path,{title:L.title,type:L.type,related:Array.isArray(L.related)?L.related:void 0,tags:L.tags||[],owner:$,access:gt?.meta.access??"public",sharedWith:gt?.meta.sharedWith?.length?gt.meta.sharedWith:void 0,created:gt?.meta.created||ie,lastUpdated:ie,sources:[...new Set([...gt?.meta.sources??[],...dt])],graphPath:Ko},L.content,$);let $t=L.type?m.magenta(`[${L.type}]`)+" ":"",Ff=Array.isArray(L.related)&&L.related.length?` \u2192 ${L.related.slice(0,3).join(", ")}${L.related.length>3?", \u2026":""}`:"";console.log(` ${m.green(gt?"~":"+")} ${$t}${L.path}: ${L.title}${m.dim(Ff)}`);let _c=(L.tags||[]).slice(0,4).join(", ");_c&&console.log(m.dim(` tags: ${_c}`)),Ko?.length&&(console.log(m.dim(` graphPath: ${Ko.join(" \u203A ")}`)),u++),f++,ve.articles++;for(let Xo of dt)$e.add(Xo)}if(ve.failed=we,ve.heldCited=[...Ze].filter(L=>$e.has(L)).length,we)console.log(m.yellow(` Run reported an error \u2014 ${b.length} entries stay queued`));else{let L=b.map(ie=>ie.id).filter(ie=>!Ze.has(ie));Ze.size>0&&console.log(m.yellow(` ${b.length-L.length} entries stay queued behind refused saves`)),n.markProcessed($,L,me.flatMap(ie=>ie.sources||[]).filter(ie=>!Ze.has(ie)))}if(De.length>0){console.log(),console.log(m.yellow(` Gaps detected (${De.length} missing pieces):`));for(let L of De)console.log(m.yellow(` ? ${L}`));try{let{QuestionStore:L}=await import("./questions-ZATLU5AW.js"),ie=new L(bo(e.dir)).add(De.map(dt=>({kind:"article",agentId:$,path:"",subject:String(dt).slice(0,120),question:`No article yet for: ${String(dt).slice(0,160)}`})));ie.added>0&&console.log(m.dim(` queued ${ie.added} for follow-up (agentx wiki questions)`))}catch{}}x.rebuildIndex()}catch(P){console.log(m.red(` Absorb failed: ${P.message?.slice(0,200)}`)),P.stderr&&console.log(m.dim(String(P.stderr).slice(0,300))),P.stdout&&console.log(m.dim("stdout: "+String(P.stdout).slice(0,300)))}finally{ve.at=new Date().toISOString(),ve.wallMs=Date.now()-D,w(ve)}}if(w({kind:"run",label:y,startedAt:k,endedAt:new Date().toISOString(),max:i,model:o}),console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(f>0&&(console.log(m.green(` ${f} articles compiled across ${r.length} agent(s)`)),a)){let $=f>0?Math.round(u/f*100):0;console.log(m.dim(` ${u}/${f} carry graphPath (${$}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});se.command("absorb-eval").description("score absorbed articles against the entries they cite").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's articles").option("--since <date>","only articles last updated on or after YYYY-MM-DD").option("--changed-after <time>","only articles whose file changed after this time (ISO, e.g. 2026-10-07T20:05:00Z)").option("--n <n>","articles in the sample","40").option("--seed <seed>","sample seed; the same seed picks the same articles","absorb-eval").option("--sample <file>","reuse the sample saved in this file, or save it there on first use").option("--judge","also ask a model to check each article's claims (one call per article)").option("--judge-model <model>","model for --judge","sonnet").option("--out <file>","write the scorecard as Markdown to this file").option("--json","print the scorecard and every article's checks as JSON").action(async e=>{let{pickSample:t,checkArticle:o,findDuplicates:n,buildJudgePrompt:s,parseJudgeReply:r,buildScorecard:i,renderScorecard:a,uncitedWithFacts:c}=await import("./absorb-eval-5Y5IZWW2.js"),{extractJson:l}=await import("./extract-json-7775Q7KO.js"),g=_e(e.dir,e.mode),d=e.agent?[e.agent]:g.listAgents(),f=typeof e.since=="string"?e.since.trim():"",u=typeof e.changedAfter=="string"&&e.changedAfter.trim()?new Date(e.changedAfter.trim()):null;if(u&&Number.isNaN(u.getTime())){console.log(m.red(` not a time: ${e.changedAfter}`)),process.exitCode=1;return}let p=u?u.toISOString().slice(0,19):f,y=new Map;for(let D of g.getSharedStore().listEntries())y.set(D.id,{id:D.id,date:D.date,content:D.content});let w=[];for(let D of d)for(let P of g.getAgentWiki(D).listArticles(D))w.push({key:`${D}/${P.path}`,agent:D,article:P});let k=new Map;for(let D of w)for(let P of D.article.meta.sources??[]){let we=k.get(P);we?we.push(D.article.content):k.set(P,[D.article.content])}let $=D=>{if(!u)return!0;try{return qk(q(g.getAgentWiki(D.agent).baseDir,D.article.path)).mtimeMs>u.getTime()}catch{return!1}},v=w.filter(D=>!f||(D.article.meta.lastUpdated??"")>=f.slice(0,10)).filter($),A=String(e.seed),S;if(e.sample&&Ve(e.sample)){let D=JSON.parse(Xt(e.sample,"utf-8"));A=D.seed??A;let P=new Map(w.map(te=>[te.key,te]));S=D.keys.map(te=>P.get(te)).filter(te=>!!te);let we=D.keys.length-S.length;we>0&&console.error(m.yellow(` ${we} sampled article(s) no longer exist`))}else S=t(v.map(D=>({...D,path:D.key})),parseInt(e.n),A),e.sample&&(Ut(e.sample,`${JSON.stringify({seed:A,since:p||void 0,keys:S.map(D=>D.key)},null,2)}
504
- `),console.error(m.dim(` sample saved to ${e.sample}`)));if(S.length===0){console.log(m.yellow(` no articles${p?` changed since ${p}`:""} to score`));return}let b=D=>D.replace(/^---\n[\s\S]*?\n---\n?/,""),x=D=>{let P=g.getAgentWiki(D.agent).getVersions(D.article.path),we=p?P.filter(O=>O.timestamp>=p):P.slice(0,1),te=we[we.length-1];if(te)try{return b(Xt(te.path,"utf-8"))}catch{return}},N=S.map(D=>({path:D.key,title:D.article.meta.title,type:D.article.meta.type,content:D.article.content,sources:D.article.meta.sources??[],lastUpdated:D.article.meta.lastUpdated,previous:x(D)})),j=N.map(D=>o(D,y,P=>k.get(P)??[])),I=new Set(S.map(D=>D.key)),M=d.flatMap(D=>n(w.filter(P=>P.agent===D).map(P=>({path:P.key,title:P.article.meta.title,type:P.article.meta.type,sources:P.article.meta.sources})),I)),z=[];if(e.judge){let D;try{D=rc(e.judgeModel)}catch(te){console.log(m.red(` ${te.message}`)),process.exitCode=1;return}let P=q(g.getBaseDir(),"_tmp");qt(P,{recursive:!0});let we=N.map((te,O)=>({a:te,i:O}));await Promise.all(Array.from({length:Math.min(3,we.length)},async()=>{for(let te=we.shift();te;te=we.shift()){let{a:O,i:me}=te,De=O.sources.map($e=>y.get($e)).filter($e=>!!$e),Ze=q(P,`absorb-eval-${me}.txt`);Ut(Ze,s(O,De));try{let{stdout:$e}=await Bk(`cat '${Ze}' | claude -p - --output-format json --max-turns 1 --model '${D}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Eo(),encoding:"utf-8",timeout:3e5,maxBuffer:4194304}),L=$e;try{L=JSON.parse($e).result??$e}catch{}let ie=r(l(L));ie?z.push({path:O.path,verdict:ie}):console.error(m.yellow(` judge reply for ${O.path} was not usable`))}catch($e){console.error(m.yellow(` judge failed for ${O.path}: ${String($e?.message??$e).slice(0,160)}`))}finally{ju(Ze,{force:!0})}}})),z.sort((te,O)=>te.path.localeCompare(O.path))}let W=new Set(w.flatMap(D=>D.article.meta.sources??[])),K=[];for(let D of d){let P=q(g.getBaseDir(),"agents",D,"_absorbed.json");if(!Ve(P))continue;let we={};try{we=JSON.parse(Xt(P,"utf-8")).entries??{}}catch{continue}for(let[te,O]of Object.entries(we)){if(W.has(te)||p&&String(O.at??"")<p)continue;let me=y.get(te);me&&K.push(me)}}let Ce=w.map(D=>D.article.content).join(`
504
+ `),console.error(m.dim(` sample saved to ${e.sample}`)));if(S.length===0){console.log(m.yellow(` no articles${p?` changed since ${p}`:""} to score`));return}let b=D=>D.replace(/^---\n[\s\S]*?\n---\n?/,""),x=D=>{let P=g.getAgentWiki(D.agent).getVersions(D.article.path),we=p?P.filter(O=>O.timestamp>=p):P.slice(0,1),te=we[we.length-1];if(te)try{return b(Xt(te.path,"utf-8"))}catch{return}},N=S.map(D=>({path:D.key,title:D.article.meta.title,type:D.article.meta.type,content:D.article.content,sources:D.article.meta.sources??[],lastUpdated:D.article.meta.lastUpdated,previous:x(D)})),j=N.map(D=>o(D,y,P=>k.get(P)??[])),I=new Set(S.map(D=>D.key)),M=d.flatMap(D=>n(w.filter(P=>P.agent===D).map(P=>({path:P.key,title:P.article.meta.title,type:P.article.meta.type,sources:P.article.meta.sources})),I)),z=[];if(e.judge){let D;try{D=rc(e.judgeModel)}catch(te){console.log(m.red(` ${te.message}`)),process.exitCode=1;return}let P=q(g.getBaseDir(),"_tmp");qt(P,{recursive:!0});let we=N.map((te,O)=>({a:te,i:O}));await Promise.all(Array.from({length:Math.min(3,we.length)},async()=>{for(let te=we.shift();te;te=we.shift()){let{a:O,i:me}=te,De=O.sources.map($e=>y.get($e)).filter($e=>!!$e),Ze=q(P,`absorb-eval-${process.pid}-${me}.txt`);Ut(Ze,s(O,De));try{let{stdout:$e}=await Bk(`cat '${Ze}' | claude -p - --output-format json --max-turns 1 --model '${D}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Eo(),encoding:"utf-8",timeout:3e5,maxBuffer:4194304}),L=$e;try{L=JSON.parse($e).result??$e}catch{}let ie=r(l(L));ie?z.push({path:O.path,verdict:ie}):console.error(m.yellow(` judge reply for ${O.path} was not usable`))}catch($e){console.error(m.yellow(` judge failed for ${O.path}: ${String($e?.message??$e).slice(0,160)}`))}finally{ju(Ze,{force:!0})}}})),z.sort((te,O)=>te.path.localeCompare(O.path))}let W=new Set(w.flatMap(D=>D.article.meta.sources??[])),K=[];for(let D of d){let P=q(g.getBaseDir(),"agents",D,"_absorbed.json");if(!Ve(P))continue;let we={};try{we=JSON.parse(Xt(P,"utf-8")).entries??{}}catch{continue}for(let[te,O]of Object.entries(we)){if(W.has(te)||p&&String(O.at??"")<p)continue;let me=y.get(te);me&&K.push(me)}}let Ce=w.map(D=>D.article.content).join(`
505
505
  `),le=c(K,Ce),Je=i(j,M,{seed:A,since:p||void 0},z,5,{entries:K.length,lost:le}),ve=a(Je);e.out&&Ut(e.out,ve),e.json?console.log(JSON.stringify({card:Je,checks:j},null,2)):e.out?console.log(m.green(` scorecard written to ${e.out}`)):console.log(ve)});se.command("absorb-runs").description("time, cost and throughput of absorb runs, grouped by --run-label").option("--dir <path>","wiki directory").option("--label <label>","only this run label").option("--json","print the summary as JSON").action(async e=>{let{summariseRuns:t}=await import("./absorb-eval-5Y5IZWW2.js"),o=q(bo(e.dir),"_absorb-runs.jsonl");if(!Ve(o)){console.log(m.yellow(` no absorb runs recorded yet (${o})`));return}let n=Xt(o,"utf-8").split(`
506
506
  `).filter(Boolean).flatMap(c=>{try{return[JSON.parse(c)]}catch{return[]}}).filter(c=>!e.label||(c.label||"(none)")===e.label),s=t(n);if(e.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){console.log(m.yellow(" no matching runs"));return}let r=[["label",c=>c.label],["calls",c=>`${c.calls}${c.failed?` (${c.failed} failed)`:""}`],["entries",c=>String(c.entries)],["articles",c=>`${c.articles}${c.refused?` (${c.refused} refused${c.heldCited?`, ${c.heldCited} held entries lost`:""})`:""}`],["wall",c=>`${(c.wallMs/6e4).toFixed(1)} min`],["call p50/p95",c=>`${Math.round(c.callMsP50/1e3)}/${Math.round(c.callMsP95/1e3)} s`],["entries/min",c=>c.entriesPerMinute.toFixed(1)],["prep",c=>`${(c.prepMs/6e4).toFixed(1)} min`],["cost",c=>`$${c.costUsd.toFixed(2)}`],["$/entry",c=>`$${c.costPerEntry.toFixed(3)}`]],i=s.map(c=>r.map(([,l])=>l(c))),a=r.map(([c],l)=>Math.max(c.length,...i.map(g=>g[l].length)));console.log(),console.log(m.bold(r.map(([c],l)=>c.padEnd(a[l])).join(" ")));for(let c of i)console.log(c.map((l,g)=>l.padEnd(a[g])).join(" "));console.log()});se.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--failures","also propose lessons from failures that recur across sessions").option("--min-sessions <n>","sessions a failure must recur in for --failures","3").option("--commit","judge and write proposals for review (default: dry-run)",!1).option("--budget <tokens>","max estimated tokens for the judge prompt","60000").action(async e=>{let t=Jk(e.since),o=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=o.find(a=>!n.includes(a));s&&(console.log(m.red(` Invalid memory type "${s}". Valid: ${n.join(", ")}`)),process.exit(1)),e.commit&&!e.via&&!e.model&&(console.log(m.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1)),console.log(),console.log(m.bold(" Memory \u2192 Wiki Promotion")),console.log();let r=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-XRBAMRBH.js"),{default:c}=await import("better-sqlite3"),l=q(process.cwd(),".agentx/db.sqlite");if(!Ve(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(t??6048e5));r=a(d,{kinds:String(e.reviewKinds).split(",").map(p=>p.trim()).filter(Boolean)});let f=r.filter(p=>(p.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${r.length} candidate finding(s), ${f} seen in more than one session`));let u=r[0];u&&(u.occurrences??1)>1&&console.log(m.dim(` most recurrent (${u.occurrences} sessions): ${u.memory.description.slice(0,84)}`))}finally{g.close()}}}if(e.failures){let a=Number(e.minSessions);(!Number.isInteger(a)||a<2)&&(console.log(m.red(` Invalid --min-sessions "${e.minSessions}". Use a whole number of 2 or more.`)),process.exit(1));let{loadFailedTraces:c,failuresToCandidates:l}=await import("./failure-candidates-JNGUVBDG.js"),{default:g}=await import("better-sqlite3"),d=q(process.cwd(),".agentx/db.sqlite");if(!Ve(d))console.log(m.yellow(` --failures: no ${d}`));else{let f=new g(d,{readonly:!0});try{let u=c(f,{since:Date.now()-(t??6048e5)}),p=l(u,{minSessions:a});console.log(m.dim(` ${u.length} failed run(s) in window \u2192 ${p.length} failure(s) seen in ${a}+ sessions`));let y=p[0];y&&console.log(m.dim(` most recurrent (${y.occurrences} sessions, ${y.failure.runs} runs): ${y.memory.description.slice(0,84)}`)),r=[...r,...p]}finally{f.close()}}}let i=await Ml({extraCandidates:r,wikiDir:e.dir?q(e.dir):void 0,memoryRoot:e.memoryDir?q(e.memoryDir):void 0,sinceMs:t,agentFilter:e.agent,types:o,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,budgetTokens:Number(e.budget)||void 0,log:a=>console.log(m.dim(` ${a}`))});if(i.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${i.candidates.length} candidate(s) in ${i.clusters.length} cluster(s):`);for(let a of i.clusters){let c=a.candidates[0],l=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${l} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${c.memory.description}`))}if(console.log(),i.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to judge and propose")),console.log();return}for(let a of i.proposed){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=`${a.agents.length} agent(s)${a.occurrences>1?`, seen in ${a.occurrences} sessions`:""}`;console.log(` ${m.green("?")} ${c}${a.path}: ${a.title} ${m.dim(`(${l})`)}`),console.log(m.dim(` proposal ${a.id}`))}for(let a of i.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(i.gaps.length){console.log(),console.log(m.yellow(` Gaps (${i.gaps.length}):`));for(let a of i.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of i.warnings)console.log(m.dim(` ! ${a}`));for(let a of i.errors)console.log(m.red(` x ${a}`));console.log(),console.log(i.errors.length?m.red(` ${i.proposed.length} proposed, ${i.errors.length} error(s)`):m.green(` ${i.proposed.length} proposed, ${i.skipped.length} skipped`)),i.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),i.errors.length&&process.exit(1)});var ei=se.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function ti(e){return e?q(e):q(process.cwd(),".agentx","wiki")}ei.command("list").description("list proposals (pending by default)").option("--all","include approved and rejected").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async e=>{let{listProposals:t}=await import("./proposals-O4B5LD5T.js"),o=t(ti(e.dir),e.all?void 0:"pending");if(o.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of o){let s=n.evidence,r=s.sources.some(l=>l.kind==="failure")?" \xB7 from a recurring failure":"",i=`${s.agents.join(", ")}${s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:""} \xB7 ${s.sources.length} source(s)${r}`,a=n.status==="pending"?"":m.dim(` [${n.status}]`),c=n.replaces?m.yellow("update"):m.green("new");console.log(` ${m.cyan(n.id)}${a}`),console.log(` ${c} ${n.article.path}: ${n.article.title}`),console.log(m.dim(` ${i}`))}});ei.command("show").description("the proposed article and the evidence behind it").argument("<id>","proposal id").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{readProposal:o}=await import("./proposals-O4B5LD5T.js"),n=o(ti(t.dir),e);if(!n){console.error(m.red(` no proposal "${e}"`)),process.exitCode=1;return}console.log(m.bold(` ${n.article.title}`)+m.dim(` \u2192 ${n.article.path} (${n.replaces?"updates an existing article":"new article"}, ${n.status})`)),console.log(),console.log(n.article.content.split(`
507
507
  `).map(s=>` ${s}`).join(`
@@ -720,7 +720,7 @@ Restart the daemon to activate.
720
720
  dist/
721
721
  *.log
722
722
  .env
723
- `}import{Command as jx}from"commander";import We from"chalk";import{writeFileSync as Nx,mkdirSync as _x,existsSync as hi,readFileSync as Tf,appendFileSync as Cf}from"fs";import{resolve as Hn,dirname as Rf}from"path";import{homedir as Cc}from"os";var jf=new jx().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-EYGICEXY.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Mx(o);break;case"bash":s=Wx(o);break;case"fish":s=Bx(o);break;default:console.error(We.red(`unsupported shell: ${n}`)),console.error(We.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?Hn(String(e.output)):Dx(n);_x(Rf(r),{recursive:!0}),Nx(r,s),console.log(We.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),Px(n,r,!!e.yes)});function Dx(e){let t=Cc();switch(e){case"zsh":return Hn(t,".zsh","completions","_agentx");case"bash":return Hn(t,".bash_completion.d","agentx.bash");case"fish":return Hn(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Px(e,t,o){if(e==="zsh"){let n=Hn(Cc(),".zshrc"),s=Rf(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=hi(n)?Tf(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(We.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&hi(n)){let g=["","# agentx completion"];c&&g.push(r),l&&g.push(i),Cf(n,g.join(`
723
+ `}import{Command as jx}from"commander";import We from"chalk";import{writeFileSync as Nx,mkdirSync as _x,existsSync as hi,readFileSync as Tf,appendFileSync as Cf}from"fs";import{resolve as Hn,dirname as Rf}from"path";import{homedir as Cc}from"os";var jf=new jx().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-LGCT7FFJ.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Mx(o);break;case"bash":s=Wx(o);break;case"fish":s=Bx(o);break;default:console.error(We.red(`unsupported shell: ${n}`)),console.error(We.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?Hn(String(e.output)):Dx(n);_x(Rf(r),{recursive:!0}),Nx(r,s),console.log(We.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),Px(n,r,!!e.yes)});function Dx(e){let t=Cc();switch(e){case"zsh":return Hn(t,".zsh","completions","_agentx");case"bash":return Hn(t,".bash_completion.d","agentx.bash");case"fish":return Hn(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Px(e,t,o){if(e==="zsh"){let n=Hn(Cc(),".zshrc"),s=Rf(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=hi(n)?Tf(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(We.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&hi(n)){let g=["","# agentx completion"];c&&g.push(r),l&&g.push(i),Cf(n,g.join(`
724
724
  `)+`
725
725
  `),console.log(We.green("\u2713 Patched ~/.zshrc")),console.log(We.dim("Reload your shell: exec zsh"));return}console.log(We.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(We.cyan(` ${r}`)),l&&console.log(We.cyan(` ${i}`)),console.log(),console.log(We.dim("Then reload: exec zsh")),console.log(We.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Hn(Cc(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((hi(n)?Tf(n,"utf-8"):"").includes(t)){console.log(We.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&hi(n)){Cf(n,`
726
726
  # agentx completion
@@ -736,4 +736,4 @@ ${Jx({...t,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
736
736
  ${o.url}`)}catch(t){console.error(Yn.red(` ${t.message}`)),process.exitCode=1}});Ds.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",Ic).action(async(e,t)=>{try{let o=await Nc(t.models);if(!Rc(t.model,o)){console.log(jc(t.model,o)),process.exitCode=1;return}let n=e==="-"?await zx():await Hx(e,"utf8"),s=JSON.parse(n),{version:r}=await Js(),i=Pf({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(Yn.red(` ${o.message}`)),process.exitCode=1}});async function zx(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function TD(){let e=await Js(),t=new Yx().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=wg(n);$g(s)&&yg("cli",s)});for(let o of[em,Zg,Nn,pn,jo,kt,og,No,$r,Yt,Kt,Go,uu,yo,wr,nf,po,Um,qm,Km,bs,ap,gp,Lm,up,fp,jp,Pp,Mp,wt,Ho,lf,cs,ao,jf,Ds])t.addCommand(o);for(let o of Lf)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=Lf.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Vx(o,74," "),""].join(`
737
737
  `)}),t}var Lf=[se,Pn,xo,Rt,gs,Tn,Ke,Qt,wo,Bo,Un,qn,go,nt,$n,jr,zr,ef,tf,zt,ft,Og,Do,Ns,ga,vo,ct,yn,ma,li,Wt,Zt,kf,vf,cf];function Vx(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(`
738
738
  `)}export{TD as buildProgram};
739
- //# sourceMappingURL=program-EYGICEXY.js.map
739
+ //# sourceMappingURL=program-LGCT7FFJ.js.map