agentix-cli 0.79.0 → 0.79.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-DTKTEQPC.js → chunk-QJM2D22B.js} +2 -2
- package/dist/{chunk-YX5S4FHR.js → chunk-Y4EWOE4N.js} +4 -4
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/{program-N3AVBQMK.js → program-TSFYLHMZ.js} +2 -2
- package/package.json +1 -1
- /package/dist/{chunk-DTKTEQPC.js.map → chunk-QJM2D22B.js.map} +0 -0
- /package/dist/{chunk-YX5S4FHR.js.map → chunk-Y4EWOE4N.js.map} +0 -0
- /package/dist/{program-N3AVBQMK.js.map → program-TSFYLHMZ.js.map} +0 -0
|
@@ -490,7 +490,7 @@ ${l}`)}let S={agentId:o,message:v,context:{channel:y,sender:f?"opencode":"openai
|
|
|
490
490
|
|
|
491
491
|
`)}}function Od(r){r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"})}function Dd(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}]})}
|
|
492
492
|
|
|
493
|
-
`)}function Nd(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);Xr(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 Xr(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Mt=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Mt(`${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(Mt.levelOrder[e]<Mt.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)}},Et=Mt;Ke(Et,"levelOrder",{debug:0,info:1,warn:2,error:3});var Bn={version:"0.79.
|
|
493
|
+
`)}function Nd(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);Xr(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 Xr(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Mt=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Mt(`${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(Mt.levelOrder[e]<Mt.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)}},Et=Mt;Ke(Et,"levelOrder",{debug:0,info:1,warn:2,error:3});var Bn={version:"0.79.1",commit:"f7d9fa3",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};import{randomUUID as _y}from"crypto";var Gn=class{constructor(e=new qo){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!Oy.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};Ny(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:_y(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=Dy(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}},Oy=["run","task","signal","mesh","channel","status"];function Dy(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 Ny(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 Ld(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 Hn,timingSafeEqual as Fd}from"crypto";var Wn=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 w={};for(let[v,S]of Object.entries(e.headers))(v.startsWith("x-hubspot")||v.startsWith("x-hub")||v.startsWith("x-github")||v.startsWith("x-gitlab")||v.startsWith("stripe")||v.startsWith("sentry")||v.startsWith("x-vercel")||v.startsWith("x-odoo")||v.startsWith("x-webhook")||v==="user-agent"||v==="content-type"||v==="host"||v==="x-forwarded-host"||v==="x-forwarded-proto"||v==="x-forwarded-for")&&(w[v]=S);this.log(`Webhook [${l}] reqUrl=${e.url} headers: ${JSON.stringify(w)}`)}let d=this.validateSignature(e.headers,a,l,i,e.url);if(d){this.log(`Webhook [${l}] -> ${i}: REJECTED (${d})`),this.sendJson(t,401,{error:d});return}let u=this.buildSummary(l,c,e.headers);this.log(`Webhook [${l}] -> ${i}: ${u.slice(0,100)}`);let h=this.extractEventType(l,c,e.headers),m=this.webhookEntries.find(w=>w.enabled&&w.agentId===i&&w.source===l),f=h&&m?.triggers?.[h]||m?.defaultWorkflow||null;if(await this.fireHookSafe(l,h,i,c),f&&this.workflowDispatcher)try{let w=await this.workflowDispatcher.dispatchWorkflow({workflowId:f,entityRef:{kind:"webhook",id:`${l}:${i}:${h??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:h,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${h??"\u2014"}] -> workflow=${f} (claimed=${w.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:h,workflow:f,claimed:w.claimed});return}catch(w){this.log(`Workflow dispatch failed [${l}/${h}/${f}]: ${w.message}`)}let y=this.webhookEntries.find(w=>w.enabled&&w.node&&w.agentId===i&&w.source===l);if(y?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:y.node,status:"accepted"}),this.mesh.sendTask(y.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(w=>this.log(`Mesh-forwarded webhook [${l}] -> ${y.node}/${i}: ${w?.slice(0,100)||"ok"}`),w=>this.log(`Mesh forward failed [${l}] -> ${y.node}/${i}: ${w.message}`));return}try{let w=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${l}`,sender:`webhook:${l}`}});this.sendJson(t,w.error?500:200,{ok:!w.error,agent:i,source:l,response:w.content?.slice(0,500),error:w.error,duration:w.duration})}catch(w){this.sendJson(t,500,{error:w.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(`
|
|
494
494
|
`)[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(`
|
|
495
495
|
`)[0]||""} (${u.author?.name||""})`);let l=t.pull_request;l&&(s.push(`PR #${l.number}: ${l.title}`),s.push(`Action: ${t.action}`),s.push(`Branch: ${l.head?.ref} -> ${l.base?.ref}`));let d=t.issue;d&&(s.push(`Issue #${d.number}: ${d.title}`),s.push(`Action: ${t.action}`));break}case"stripe":{let o=t.type||"event",a=t.data?.object||{};s.push(`Event: ${o}`),a.amount&&s.push(`Amount: ${(a.amount/100).toFixed(2)} ${a.currency?.toUpperCase()||""}`),a.customer_email&&s.push(`Customer: ${a.customer_email}`),a.description&&s.push(`Description: ${a.description}`),a.status&&s.push(`Status: ${a.status}`);break}case"sentry":{let o=n["sentry-hook-resource"]||"event";s.push(`Resource: ${o}`);let a=t.data||t;a.error?.title&&s.push(`Error: ${a.error.title}`),a.error?.culprit&&s.push(`Culprit: ${a.error.culprit}`),a.error?.metadata?.value&&s.push(`Message: ${a.error.metadata.value}`),t.url&&s.push(`URL: ${t.url}`);break}case"hubspot":{let o=Array.isArray(t)?t:null,a=o||null;if(a&&a.length){s.push(`Events: ${a.length}`);for(let l of a.slice(0,3)){let d=l.subscriptionType??"?",u=l.objectId??"?",h=l.changeFlag??l.changeSource??"";s.push(` - ${d} (object ${u}${h?`, ${h}`:""})`)}}else{let l=t.subscriptionType??"event",d=t.objectId??"?";s.push(`Event: ${l} (object ${d})`)}let c=a?.[0]?.portalId??t.portalId;c!=null&&s.push(`Portal: ${c}`);break}case"odoo":{let o=typeof t.event=="string"&&t.event||typeof t.subscriptionType=="string"&&t.subscriptionType||typeof t.model=="string"&&(typeof t.action=="string"?`${t.model}.${t.action}`:t.model)||"event";s.push(`Event: ${o}`);let a=n["x-odoo-database"]||(typeof t.database=="string"?t.database:"");a&&s.push(`Database: ${a}`);let c=t.record||t;c?.id&&s.push(`Record id: ${c.id}`),c?.name&&s.push(`Name: ${String(c.name).slice(0,200)}`),c?.partner_id?.[1]&&s.push(`Partner: ${c.partner_id[1]}`),c?.email&&s.push(`Email: ${c.email}`),c?.amount_total!=null&&s.push(`Amount: ${c.amount_total}`),c?.state&&s.push(`State: ${c.state}`);break}default:s.push(`Headers: ${JSON.stringify(Object.keys(n).filter(o=>o.startsWith("x-")).slice(0,5))}`),s.push(`Payload keys: ${Object.keys(t).slice(0,10).join(", ")}`);let i=JSON.stringify(t).slice(0,500);s.push(`Body: ${i}`)}return s.join(`
|
|
496
496
|
`)}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="+Hn("sha256",a).update(t).digest("hex");return ct(u,d)}if(n==="gitlab"){let d=c("x-gitlab-token");return d?ct(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(m=>m.split("=")));if(!u.t||!u.v1)return"malformed Stripe-Signature";let h=Hn("sha256",a).update(`${u.t}.${t}`).digest("hex");return ct(h,u.v1)}if(n==="hubspot"){let d=c("x-hubspot-signature-v3"),u=c("x-hubspot-request-timestamp");if(!d)return"missing X-HubSpot-Signature-v3";if(!u)return"missing X-HubSpot-Request-Timestamp";let h=parseInt(u,10);if(!Number.isFinite(h))return"malformed X-HubSpot-Request-Timestamp";let m=Date.now()-h;if(m>5*6e4)return`HubSpot webhook is ${Math.floor(m/1e3)}s old (>5min replay window)`;let f="POST",y=i||e["x-original-uri"]||e["x-forwarded-path"]||"",w=e["x-forwarded-host"],v=e.host,S=e["x-forwarded-proto"]||"https",I=new Set;w&&y&&I.add(`${S}://${w}${y}`),v&&y&&I.add(`https://${v}${y}`),v&&y&&I.add(`http://${v}${y}`),y&&I.add(y),I.add("");for(let A of I){let D=Hn("sha256",a).update(`${f}${A}${t}${u}`).digest("base64");if(d.length===D.length&&Fd(Buffer.from(d),Buffer.from(D)))return null}return`signature mismatch (tried ${I.size} URI variants)`}if(n==="odoo"){let d=c("x-odoo-signature");if(d){let h=Hn("sha256",a).update(t).digest("hex"),m=d.startsWith("sha256=")?d.slice(7):d;return ct(h,m)}let u=c("x-odoo-webhook-token")??c("x-webhook-secret");return u?ct(a,u):"missing X-Odoo-Signature or X-Odoo-Webhook-Token"}let l=c("x-webhook-secret");return l?ct(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 ct(r,e){if(r.length!==e.length)return"signature mismatch";let t=Buffer.from(r),n=Buffer.from(e);return Fd(t,n)?null:"signature mismatch"}gm();function jy(r){return{insertTaskHistory:r.prepare(`
|
|
@@ -1382,4 +1382,4 @@ data: ${JSON.stringify(O)}
|
|
|
1382
1382
|
`)}catch{}},M=setInterval(()=>{try{t.write(`: ping
|
|
1383
1383
|
|
|
1384
1384
|
`)}catch{}},15e3);M.unref?.();let C=new AbortController;t.on("close",()=>{t.writableEnded||C.abort()});try{for await(let T of this.mesh.sendTaskStream(g.peer,g.message,g.agent,{context:g.context,signal:C.signal}))P(T.event,T.data)}catch(T){P("error",{error:T?.message??String(T)})}finally{clearInterval(M);try{t.end()}catch{}}break}let k=g.context,x=typeof g.senderAgentId=="string"?g.senderAgentId:void 0;if(Hp(g,!0)==="callback"){let P=this.delegationGate(e,g,{callee:g.agent,peer:g.peer,message:g.message,calleeContext:k});if(!("track"in P)){let M=js(P);this.json(t,M.status,M.body);break}}if(g.async===!0){let P=k?.channel,M=k?.chatId;if(!P||!M){this.json(t,400,{error:"async requires context.channel and context.chatId \u2014 there is no route back otherwise"});return}let C=`mesh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;this.json(t,202,{accepted:!0,taskId:C,deliverTo:`${P}:${M}`,note:"result will be delivered to the originating chat when the peer finishes"});let T=g.peer,O=g.agent,L=this.mesh;(async()=>{let N=Date.now(),W;try{W=await L.sendTask(T,g.message,O,{context:k,senderAgentId:x}),this.log(`[mesh/task async ${C}] ${T}/${O??"default"} finished in ${Date.now()-N}ms`)}catch(z){W=`Delegation to ${T}/${O??"default"} failed: ${z?.message??z}`,this.log(`[mesh/task async ${C}] failed: ${z?.message??z}`)}try{await this.router.sendOutbound({channel:P,chatId:M,text:W,agentId:k?.agentId??x,accountId:k?.accountId})}catch(z){this.log(`[mesh/task async ${C}] delivery failed: ${z?.message??z}`)}})();break}let $=await this.mesh.sendTask(g.peer,g.message,g.agent,{context:k,senderAgentId:x});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 p=await U(e);if(!p.kind||!p.callId||!p.from||!p.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let b=await this.webrtc.handleOutgoing(p);this.json(t,b.ok?200:400,b);break}case"POST /webrtc/signal":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let p=await U(e);if(!p.kind||!p.callId||!p.from||!p.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let b=this.webrtc.handleIncoming(p);this.json(t,b.ok?200:400,b);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 g=await U(e),p=g.callId,b=g.target,k=g.agentId||this.config.channels.webrtc?.bot.defaultAgentId;if(!p||!b||!k){this.json(t,400,{error:"Missing: callId, target, agentId (or defaultAgentId in config)"});return}let x=await this.botManager.invite({callId:p,target:b,agentId:k});this.json(t,x.ok?200:500,x);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 g=this.config.channels.webrtc;if(!g?.enabled){this.json(t,404,{error:"WebRTC signaling not enabled"});return}this.json(t,200,{localName:this.config.node.name,iceServers:[...g.stunServers.map(p=>({urls:p})),...g.turnServers],peers:this.mesh?.directory().map(p=>({name:p.peer,healthy:p.healthy}))||[],camera:g.camera,agents:this.registry.list().map(p=>({id:p.id,name:p.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(g=>{let p=this.config.agents[g.id]||{},b=typeof p.description=="string"&&p.description.trim()||y0(p.systemPrompt)||`Agent "${g.name}" (${g.tier})`,k=Array.isArray(p.mentions)?p.mentions.slice(0,4):[];return{id:g.id,name:g.name,description:b,tags:[g.tier,...k],color:se(g.id,p).color}}),channels:this.router.getChannelNames(),defaultInputModes:["text"],defaultOutputModes:["text"]});break;case"GET /wiki/agents":{let g=this.registry.getWikiHub();this.json(t,200,{nodeId:this.config.node.id,agents:g.summary()});break}case"GET /wiki/entries":{let g=this.registry.getWikiHub(),p=n.searchParams.get("agent")||void 0,b=n.searchParams.get("after")||void 0,k=p?g.getAgentEntries(p):g.getSharedStore().listEntries({after:b});this.json(t,200,{nodeId:this.config.node.id,count:k.length,entries:k.map(x=>({id:x.id,date:x.date,agentId:x.agentId,source:x.source,sourceContext:x.sourceContext,content:x.content}))});break}case"GET /wiki/articles":{let g=this.registry.getWikiHub(),p=n.searchParams.get("agent");if(!p){this.json(t,400,{error:"?agent= required"});break}let k=g.getAgentWiki(p).rebuildIndex();this.json(t,200,{nodeId:this.config.node.id,agentId:p,articles:k.articles});break}case"GET /wiki/article":{let g=this.registry.getWikiHub(),p=n.searchParams.get("agent"),b=n.searchParams.get("path");if(!p||!b){this.json(t,400,{error:"?agent= and ?path= required"});break}let x=g.getAgentWiki(p).readArticle(b);if(!x){this.json(t,404,{error:"Article not found"});break}this.json(t,200,{nodeId:this.config.node.id,agentId:p,path:x.path,title:x.meta.title,tags:x.meta.tags,owner:x.meta.owner,created:x.meta.created,lastUpdated:x.meta.lastUpdated,sources:x.meta.sources,content:x.content});break}case"GET /graph/schema":{let g=this.registry.getGraphStore();if(!g){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,schema:g.loadSchema()});break}case"GET /graph/nodes":{let g=this.registry.getGraphStore();if(!g){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,...g.loadNodes()});break}case"GET /graph/classifications":{let g=this.registry.getGraphStore();if(!g){this.json(t,404,{error:"graph disabled on this node"});break}let p=n.searchParams.get("status")||"approved",b=Math.max(1,Math.min(1e3,parseInt(n.searchParams.get("limit")||"200",10)||200)),k=g.listByStatus(p,b);this.json(t,200,{nodeId:this.config.node.id,status:p,count:k.length,classifications:k});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 /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/look { agentId } \u2014 from an agent's run: the newest frame as a PNG path"]})}}catch(i){this.json(t,500,{error:i.message})}}async handleOpenAICompat(e,t,n){let s=await U(e);await jd(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=Oh(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=lu();if(e==="json")return this.registry.getTodayUsage();let t=cu(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||!ft(n)))try{let s=ne(n,".claude","skills");lm(s,{recursive:!0});let i=ne(s,jh);if(!ft(i))go(i,ki(e)),this.log(` memory-skill: installed remember.md \u2192 ${t.id}`);else{let o=Fh(Xt(i,"utf-8"),e);o&&(go(i,o),this.log(` memory-skill: updated remember.md \u2192 ${t.id}`))}this.agentMemory.syncToWorkspace(t.id,n)}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||!ft(n))continue;let s=_o(t);try{switch(Nh(n,s)){case"installed":this.log(` mcp: installed ${Object.keys(s).length} server(s) \u2192 ${e}`);break;case"updated":this.log(` mcp: updated .mcp.json (${Object.keys(s).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(s).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(i){this.log(` mcp: ${e} install failed \u2014 ${i?.message??i}`)}}}workspaceFor(e){for(let t of this.registry.list())if(t.id===e)return t.workspace;return null}handleMemoryApi(e,t,n,s){return mh(e,t,n,s,{mem:this.agentMemory,workspaceFor:i=>this.workspaceFor(i),runningTaskOwner:i=>this.registry.runningTaskOwner(i)})}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 Z(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let s=n?.payload??n,i=s?.event,o=s?.entityRef;if(!i?.id||!o?.backend||!o?.id){this.json(t,400,{error:"missing event or entityRef"});return}let a=n?.kind;try{if(a==="trigger"&&s.trigger){let h=typeof n?.fromPeer=="string"?n.fromPeer:"unknown";this.log(`[workflows/mesh] received trigger from "${h}" source="${s.trigger.source}" chat="${s.trigger.chat??"*"}"`);let m=await this.workflowDispatcher.dispatch({trigger:s.trigger,entityRef:o,event:i,fromRemote:{peer:h}});this.log(`[workflows/mesh] dispatched broadcast: matched=${m.claimed.length} ${m.claimed.length?`(${m.claimed.map(f=>f.id).join(", ")})`:"[none \u2014 no workflow with mesh.allowRemote matched]"}`),this.json(t,202,{ok:!0,mode:"trigger-broadcast",matched:m.claimed.map(f=>f.id)});return}let d=(s.workflowId?this.workflowStore?.get(s.workflowId):null)?.nodes.find(h=>h.type.startsWith("trigger."))?.config??{},u={source:String(d.source??"hook"),project:d.filter?.project,repo:d.filter?.repo,chat:d.filter?.chat,labels:d.filter?.labels};await this.workflowDispatcher.dispatch({trigger:u,entityRef:o,event:i}),this.json(t,202,{ok:!0})}catch(c){this.log(`[workflows] /workflow/event failed: ${c.message}`),this.json(t,500,{error:c.message})}}async relayPush(e,t){let n=e.toLowerCase(),s=this.mesh?.directory().find(a=>a.peer.toLowerCase()===n);if(!s)throw new Error(`push: channels.push.relayTo "${e}" is not a mesh peer of this node`);let i=await fetch(`${s.peerUrl}/channel/send`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(s.peer)},body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)});if(!i.ok)throw new Error(`push: ${s.peer} /channel/send -> ${i.status} ${(await i.text().catch(()=>"")).slice(0,200)}`);return(await i.json().catch(()=>({}))).messageId??void 0}async handleChannelSend(e,t){let n;try{n=await Z(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.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}try{let c=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},{recordInSession:!1});this.json(t,200,{ok:!0,messageId:c??null})}catch(c){this.log(`[mesh] /channel/send "${s}" failed: ${c.message}`),this.json(t,500,{error:c.message})}}async handleChannelChats(e,t,n={}){let s=new Set,i=[],o=[],a=(l,d)=>{let u=0;for(let h of l)!h.id||s.has(h.id)||(s.add(h.id),i.push({...h,source:d}),u++);u>0&&o.push(`${d}:${u}`)},c=this.router.getChannel(t);if(c?.listKnownChats)try{a(c.listKnownChats(),"local")}catch{}else if(c?.listChats)try{a(c.listChats().map(l=>({id:l.jid,name:l.name,kind:l.isGroup?"group":"dm"})),"local")}catch{}if(!n.localOnly&&this.mesh){let l=this.mesh.directory().filter(d=>d.healthy&&d.channels?.includes(t));await Promise.allSettled(l.map(async d=>{try{let u=await fetch(`${d.peerUrl}/channels/${encodeURIComponent(t)}/chats?local=1`,{headers:this.mesh.authHeaders(d.peer),signal:AbortSignal.timeout(5e3)});if(!u.ok)return;let h=await u.json();Array.isArray(h.chats)&&a(h.chats.map(m=>({id:m.id,name:m.name,kind:m.kind??"dm",accountId:m.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 Z(e)}catch{s={}}try{let i=await _h({get:o=>this.workflowStore.get(o),dispatchWorkflow:o=>this.workflowDispatcher.dispatchWorkflow(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})}}},po=mo;Ke(po,"MESH_PROTECTED_PATHS",new Set(["/task","/ask","/mesh/task","/mesh/inbox/send","/workflow/event","/workflow/transition","/channel/send","/webrtc/signal","/gitlab/react","/gitlab/send-note","/gitlab/log-time","/github/send-comment"]));function y0(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 Z(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 w0(r,e){let t=["model","workspace","tier","permissionMode","mcpServers"],n=new Set,s=new Set([...Object.keys(r),...Object.keys(e)]);for(let i of s){let o=r[i],a=e[i];if(!o||!a){n.add("add/remove");continue}for(let c of t)JSON.stringify(o[c])!==JSON.stringify(a[c])&&n.add(`${i}.${c}`)}return Array.from(n).slice(0,6)}async function U(r){return new Promise((e,t)=>{let n="";r.on("data",s=>n+=s.toString()),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch{e({})}}),r.on("error",t)})}hm();function WD(r){typeof r=="string"&&(zt.error(r),process.exit(1)),r instanceof Error&&(zt.error(r.message),process.exit(1)),zt.error("Something went wrong. Please try again."),process.exit(1)}export{pe as a,me as b,yn as c,F0 as d,Ir as e,Ge as f,$t as g,At as h,Je as i,An as j,R$ as k,Qd as l,Xy as m,zy as n,su as o,Pe as p,Jn as q,ou as r,Xn as s,vT as t,ST as u,_u as v,gi as w,hR as x,gR as y,pR as z,$h as A,Kb as B,bR as C,kR as D,ls as E,Dt as F,eg as G,zk as H,DC as I,gs as J,se as K,fs as L,Ov as M,zg as N,Dv as O,Qg as P,bs as Q,Bt as R,xs as S,Is as T,ip as U,Xi as V,Te as W,be as X,gp as Y,pp as Z,mp as _,fp as $,Ws as aa,em as ba,lo as ca,nm as da,r0 as ea,VP as fa,po as ga,WD as ha};
|
|
1385
|
-
//# sourceMappingURL=chunk-
|
|
1385
|
+
//# sourceMappingURL=chunk-QJM2D22B.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as fl,b as us,g as hl}from"./chunk-TQT4XDNN.js";import{a as rl,c as al}from"./chunk-2WRWBPDL.js";import{a as Qe,b as tl,f as nl,g as sl,h as il,i as jt,j as cl,k as ll,l as Ii,m as pl,o as ul}from"./chunk-2XSVV3M3.js";import{a as dl,c as gl,d as ml}from"./chunk-Z3IP66SL.js";import{a as yi,b as Ra}from"./chunk-RKPAVWXF.js";import{$ as Yc,A as Ac,B as Tc,C as bi,D as Oc,E as jc,F as Cc,G as Ic,H as Nc,I as Rc,J as Fc,K as Et,L as ds,M as Ei,N as qc,O as Wc,P as Bc,Q as Jc,R as Hc,S as Gc,T as At,U as Tt,V as zc,W as Vc,X as _e,Y as gs,Z as wn,_ as Ai,a as Ia,aa as Qc,b as Na,ba as ji,c as un,ca as el,d as qa,da as ms,e as Wa,ea as Ot,fa as ps,ga as Ci,ha as ol,k as os,l as Ga,m as fn,n as ts,o as Ya,p as Ka,q as cc,r as lc,s as rs,t as $i,u as uc,v as $c,w as bc,x as xc,y as Sc,z as Ec}from"./chunk-
|
|
1
|
+
import{a as fl,b as us,g as hl}from"./chunk-TQT4XDNN.js";import{a as rl,c as al}from"./chunk-2WRWBPDL.js";import{a as Qe,b as tl,f as nl,g as sl,h as il,i as jt,j as cl,k as ll,l as Ii,m as pl,o as ul}from"./chunk-2XSVV3M3.js";import{a as dl,c as gl,d as ml}from"./chunk-Z3IP66SL.js";import{a as yi,b as Ra}from"./chunk-RKPAVWXF.js";import{$ as Yc,A as Ac,B as Tc,C as bi,D as Oc,E as jc,F as Cc,G as Ic,H as Nc,I as Rc,J as Fc,K as Et,L as ds,M as Ei,N as qc,O as Wc,P as Bc,Q as Jc,R as Hc,S as Gc,T as At,U as Tt,V as zc,W as Vc,X as _e,Y as gs,Z as wn,_ as Ai,a as Ia,aa as Qc,b as Na,ba as ji,c as un,ca as el,d as qa,da as ms,e as Wa,ea as Ot,fa as ps,ga as Ci,ha as ol,k as os,l as Ga,m as fn,n as ts,o as Ya,p as Ka,q as cc,r as lc,s as rs,t as $i,u as uc,v as $c,w as bc,x as xc,y as Sc,z as Ec}from"./chunk-QJM2D22B.js";import{Aa as Si,L as wc,M as as,Qa as Kc,Ra as Ti,Sa as Xc,Ta as Oi,Z as hn,aa as ki,ba as cs,ca as _c,fb as po,hb as Zc,ja as Ro,ka as Dc,la as vi,na as xi,p as No,pa as Pc,qa as Mc,ra as yn,t as fc,va as ls,w as hc,y as yc,ya as Lc,za as Uc}from"./chunk-EOBFJGTV.js";import{a as Ba,d as Ja,e as Ha}from"./chunk-IXWPA6WM.js";import{a as ns,b as ss,c as Xa,d as Qa,e as Za,g as ec,h as oc,j as tc,k as nc,l as sc,m as ic,p as is,s as rc,t as ac}from"./chunk-S2GAEH2F.js";import{a as za,p as Va}from"./chunk-3OIFSKSR.js";import{a as dc,b as gc,c as mc,d as pc}from"./chunk-2D3RYIDU.js";import{a as kc,b as vc}from"./chunk-EKJG63EJ.js";import{C as Io,I as ja,T as Ca,g as ua,p as fa,w as ui,x as $a}from"./chunk-SYXAEWFN.js";import{b as $t,g as kt,h as Zn,i as es,j as vt,k as ba,l as Xo,m as pn}from"./chunk-2YIWQ57T.js";import{e as Aa,f as hi,k as Ta}from"./chunk-WP6KLXTP.js";import{a as Xn}from"./chunk-N6EWZGIX.js";import{b as bt}from"./chunk-DP7RTNDM.js";import{a as wi,e as _a,f as Da,h as Pa,i as Ma,k as La,l as Ua,m as Fa}from"./chunk-IWQURDYO.js";import{c as va}from"./chunk-SZDACK6O.js";import{f as xa,g as Sa,h as fi}from"./chunk-76Z4VHDX.js";import{a as ya,k as Ea}from"./chunk-B5VRY4NI.js";import{b as pe,c as je,d as St,e as Oa}from"./chunk-N2A3KIVY.js";import{a as mi}from"./chunk-P5KHF46N.js";import{a as pi,b as ha}from"./chunk-GQ76J72O.js";import{j as wa}from"./chunk-X5C5W3E4.js";import{a as xt}from"./chunk-GV7S5BAX.js";import{e as ka}from"./chunk-GSX4NK2N.js";import{h as pa}from"./chunk-DWADWDMU.js";import{g as Co,i as Qn}from"./chunk-VIUCCUJ4.js";import{b as wt,d as ma}from"./chunk-2GIDVZ4H.js";import{a as gi,b as Kr,c as Lm,d as Yn,e as Xr,f as ra,g as qm,h as aa,i as Wm,m as yt,n as la,o as da,s as ga,v as mo,w as mn}from"./chunk-QAKL2D7O.js";import{a as ca,b as Bm}from"./chunk-FX3D7YON.js";import{a as bo,b as ht,e as na,f as gn}from"./chunk-72SZI2UW.js";import{a as $o,b as Mm}from"./chunk-7I7IEX4S.js";import{C as oa,D as ta,E as C,F as Kn,H as ne,m as Qr,n as Zr,p as ea,q as Um}from"./chunk-KH4PKJGD.js";import{g as sa,k as ia,l as Fm}from"./chunk-RGDKHYY2.js";import{Command as Jm}from"commander";var yl=new Jm().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 Wa({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()});ne();import{Command as Hm}from"commander";import{execFileSync as eo}from"node:child_process";import{cpSync as wl,existsSync as _i,mkdirSync as Ni,mkdtempSync as Gm,readdirSync as zm,rmSync as $l,writeFileSync as bl}from"node:fs";import{dirname as kl,join as Pe}from"node:path";import{homedir as fs,release as Vm,tmpdir as Ym}from"node:os";import{setTimeout as Km}from"node:timers/promises";function hs(){let e=Xa(process.platform,process.arch,Vm());if(e)throw new Error(e)}function ys(){let e=Pe(fs(),"Library/LaunchAgents"),o=[];try{o=zm(e).filter(ec)}catch{}let t=o.flatMap(n=>{let s=Pe(e,n);try{return[{file:s,plist:eo("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return oc(e,t)}function $n(e){return`gui/${process.getuid()}/${e.label}`}async function Ri(e){try{eo("launchctl",["bootout",$n(e)],{stdio:"pipe"})}catch{}for(let o=0;o<30;o++){try{eo("launchctl",["print",$n(e)],{stdio:"pipe"})}catch{return}await Km(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function vl(e){if(!_i(e.file))throw new Error("Run agentx desktop install first.");let o=!0;try{eo("launchctl",["print",$n(e)],{stdio:"pipe"})}catch{o=!1}o||eo("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),eo("launchctl",["kickstart",$n(e)],{stdio:"pipe"})}function Xm(){let e=ic();if(e&&_i(Pe(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 Ct=new Hm("desktop").description("install and control the macOS desktop assistant");Ct.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=>{hs();let o=C(),t=Qa(o.agents,e.agent),n=e.agent,s=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=Xm(),r=Pe(fs(),"Applications"),{keep:a,remove:c}=ys();if(console.log(`Desktop assistant \u2192 ${Pe(r,ns)}
|
|
2
2
|
Computer-use helper \u2192 ${Pe(r,ss)}
|
|
3
3
|
Agent \u2192 ${n?`${t} (pinned)`:"picked from the menu-bar icon"}
|
|
4
4
|
Daemon \u2192 ${s}
|
|
@@ -409,7 +409,7 @@ return aid ?? null`}function Bf(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
|
|
|
409
409
|
settings \u2014 without this an attached production identity would be less
|
|
410
410
|
guarded than a spawned one.)`))):console.log(N.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${N.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(N.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Jo.command("uninstall").description("remove the attach hooks from ~/.claude/settings.json").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--remove-guard","also remove the PreToolUse guard hook").action(e=>{try{let o=Tl({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${N.green("\u2713")} Removed attach hooks from ${N.gray(o.path)} (${o.events.join(", ")})`:`${N.gray("Nothing to remove.")}`),e.removeGuard||console.log(N.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(N.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});ne();import{Command as Eh}from"commander";import we from"chalk";var qs=new Eh().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function pg(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=C(e.config);o||(o=n.dashboard?.daemonUrl||""),t||(t=n.dashboard?.token||"")}catch{}return o||(o="http://localhost:18800"),{baseUrl:o.replace(/\/+$/,""),token:t}}function ug(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function mg(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s`:o<3600?`${Math.round(o/60)}m`:o<86400?`${Math.round(o/3600)}h`:`${Math.round(o/86400)}d`}function Ah(e){return e==="busy"?we.magenta:e==="warm-hot"?we.green:e==="warm-cold"?we.cyan:e==="idle"?we.yellow:e==="dead"?we.red:we.dim}qs.command("list").description("list every live persistent claude process").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("--json","emit JSON").action(async e=>{let{baseUrl:o,token:t}=pg(e),n;try{n=await fetch(`${o}/api/processes`,{headers:ug(t)})}catch(r){console.log(we.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(we.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(we.red(` HTTP ${n.status} from ${o}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(we.dim(" (no processes)"));return}for(let r of i){let a=Ah(r.state)(r.state.padEnd(9)),c=mg(r.spawnedAt),l=r.lastTurnAt?mg(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?we.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?we.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):we.dim("sess=\u2014"),u=r.pendingTaskId?we.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${we.bold(r.key.agentId)}${we.dim(":"+r.key.channel+":"+r.key.chatId)} ${we.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${u}`),r.deadReason&&console.log(` ${we.red("dead:")} ${r.deadReason}`)}});qs.command("kill <agentId> <channel> <chatId>").description("force-kill one persistent process (the next dispatch will spawn fresh)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("-r, --reason <reason>","kill reason (recorded on the dead-process snapshot)","operator-cli").action(async(e,o,t,n)=>{let{baseUrl:s,token:i}=pg(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:ug(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(we.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(we.dim(" daemon has no persistent-process registry"));return}if(!r.ok){let a=`HTTP ${r.status}`;try{let c=await r.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(we.red(` ${a}`)),process.exit(1)}console.log(we.green(` killed ${e}:${o}:${t}`))});import{Command as Th}from"commander";import Le from"chalk";import{existsSync as mr,rmSync as Oh}from"fs";import{resolve as pr}from"path";var Jt=new Th().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Jt.command("add <agentId>").description("build or refresh an agent's lexical index from one or more globs").argument("<globs...>","glob patterns relative to cwd (e.g. './docs/**/*.md')").option("-v, --verbose","log each indexed file").action(async(e,o,t)=>{o.length===0&&(console.log(Le.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await xa(e,o,{verbose:n}),r=Date.now()-s;console.log(Le.green(` \u2713 indexed ${i.docs} doc(s) for ${Le.bold(e)} in ${r}ms`)),console.log(Le.dim(` \u2192 ${i.path}`))});Jt.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=pr(e.cwd,".agentx","rag");if(!mr(o)){console.log(Le.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>mr(pr(o,s,"index.json")));if(n.length===0){console.log(Le.dim(" (no indexes)"));return}for(let s of n.sort()){let i=fi(s);console.log(` ${Le.bold(s)} ${i.docs} doc(s) ${Le.dim(i.path)}`)}});Jt.command("search <agentId> <query>").description("query an agent's index \u2014 useful for debugging recall before the agent calls rag.lexical").option("-k, --k <n>","top-k results","5").option("--json","emit JSON").action((e,o,t)=>{let n=parseInt(t.k,10)||5,s=Sa(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=fi(e);i.exists?console.log(Le.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Le.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Le.bold(i.title)} ${Le.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Le.dim(i.path)}`),console.log(` ${Le.dim(i.snippet.slice(0,200))}`)});Jt.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=pr(process.cwd(),".agentx","rag",e);if(!mr(o)){console.log(Le.dim(` no index for ${e} \u2014 nothing to clear`));return}Oh(o,{recursive:!0,force:!0}),console.log(Le.green(` \u2713 cleared index for ${e}`))});ne();import{Command as jh}from"commander";import Q from"chalk";import Ht from"prompts";var dt=new jh().name("backlog").description("manage the local backlog used by business workSource=backlog");function Rn(e){let o=C(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new Kc(n)}}function Ch(e){return e?Q.cyan(`${e.type}:${e.project}#${e.iid}`):Q.dim("manual")}function Ih(e){return{todo:Q.gray("todo"),doing:Q.yellow("doing"),blocked:Q.red("blocked"),done:Q.green("done")}[e]}dt.command("list",{isDefault:!0}).description("list backlog items").option("--status <status>","filter by status (todo|doing|blocked|done)").option("--assignee <agent>","filter by assignee").option("--source <type>","filter by source.type (gitlab|github|manual)").option("-c, --config <path>","config path").action(async e=>{let{store:o}=Rn(e.config),t=o.list();if(e.status&&(t=t.filter(n=>n.status===e.status)),e.assignee&&(t=t.filter(n=>n.assignee===e.assignee)),e.source&&(t=t.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!t.length){console.log(Q.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?Q.magenta(`@${n.assignee}`):Q.dim("unassigned");console.log(` ${Ih(n.status).padEnd(7)} ${Ch(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(Q.dim(` ${n.source.url}`))}console.log(),console.log(Q.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});dt.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,o,t)=>{let n=Rn(t.config);n.store.findById(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(Q.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=Xc([o],i.source,n.config),a=await Oi(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(Q.dim(" sync:"),...c));console.log(a.ok?Q.dim(` synced -> ${a.url??i.source.type}`):Q.yellow(` sync failed: ${a.error}`))}});dt.command("done <id>").description("mark an item as done; closes the upstream issue if linked").option("--note <text>","comment to post upstream").option("--close","also close the upstream issue (default: only labels change)",!1).option("-c, --config <path>","config path").action(async(e,o)=>{let t=Rn(o.config);t.store.findById(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(Q.green(` done: ${s.title}`)),s.source){let i=await Oi(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(Q.dim(" sync:"),...r));console.log(i.ok?Q.dim(` synced -> ${i.url??s.source.type}`):Q.yellow(` sync failed: ${i.error}`))}});dt.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,o)=>{let{store:t}=Rn(o.config);t.remove(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1)),console.log(Q.green(` removed ${e}`))});dt.command("import").description("import open issues from gitlab/github into the backlog (interactive)").option("--source <type>","source type (gitlab|github)").option("--project <id>","project id (group/repo for gitlab, owner/repo for github)").option("--assignee <agent>","assign all imported items to this agentId").option("-c, --config <path>","config path").action(async e=>{let o=Rn(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(Q.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let w=[t&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Ht({type:"select",name:"source",message:"Source",choices:w})).source,!s)return}s==="gitlab"&&!t&&(console.error(Q.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(Q.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let w=s==="gitlab"?Rh(o.config):_h(o.config);w.length?(i=(await Ht({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...w.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await Ht({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Ht({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Ht({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(Q.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await Dh(o.config,i,a):await Ph(o.config,i,a);if(!c.length){console.log(Q.yellow(" no open issues matched"));return}console.log(Q.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(o.store.list().map(w=>w.id)),d=c.map(w=>{let k=Ti({type:s,project:l,iid:w.iid,url:w.url}),b=g.has(k),$=w.labels.length?` [${w.labels.slice(0,3).join(",")}]`:"";return{title:`#${w.iid} ${w.title}${$}${b?Q.dim(" (already imported)"):""}`,value:w,disabled:b}}),f=(await Ht({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!f.length){console.log(Q.dim(" nothing selected"));return}let p=f.map(w=>{let k={type:s,host:s==="gitlab"?Nh(o.config):void 0,project:l,iid:w.iid,url:w.url};return{id:Ti(k),title:w.title,description:w.description,assignee:e.assignee||w.assignee,labels:w.labels,milestone:w.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),h=o.store.addMany(p);console.log(Q.green(` imported ${h.length} item${h.length===1?"":"s"}`));for(let w of h)console.log(Q.dim(` ${w.id} \u2014 ${w.title}`))});function Nh(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Rh(e){let o=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&o.add(n.project);let t=e.business?.workSource;if(t?.type==="gitlab")for(let n of t.projects??[])o.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&o.add(n.id);return[...o].sort()}function _h(e){let o=new Set;for(let t of e.channels.github?.routes??[])t.repo&&t.repo!=="*"&&o.add(t.repo);return[...o].sort()}async function Dh(e,o,t){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});t&&s.set("search",t);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(o)}/issues?${s}`,{headers:{"PRIVATE-TOKEN":n.token}});if(!i.ok)throw new Error(`GitLab ${i.status}: ${await i.text().catch(()=>"")}`);let r=await i.json();return Array.isArray(r)?r.map(a=>({iid:a.iid,title:a.title,description:a.description||void 0,labels:Array.isArray(a.labels)?a.labels.map(c=>typeof c=="string"?c:c.name):[],milestone:a.milestone?.title||void 0,assignee:a.assignee?.username||a.assignees?.[0]?.username||void 0,url:a.web_url})):[]}async function Ph(e,o,t){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(t){let c=`repo:${o} is:issue is:open ${t}`;i=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let l=await fetch(i,{headers:s});if(!l.ok)throw new Error(`GitHub ${l.status}: ${await l.text().catch(()=>"")}`);return((await l.json()).items??[]).map(fg)}i=`https://api.github.com/repos/${o}/issues?state=open&per_page=100&sort=updated&direction=desc`;let r=await fetch(i,{headers:s});if(!r.ok)throw new Error(`GitHub ${r.status}: ${await r.text().catch(()=>"")}`);let a=await r.json();return Array.isArray(a)?a.filter(c=>!c.pull_request).map(fg):[]}function fg(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(o=>typeof o=="string"?o:o.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as Mh}from"commander";import W from"chalk";import{existsSync as Lh,readFileSync as Uh}from"fs";import{resolve as Fh}from"path";import qh from"prompts";ne();function hg(e){let o=e||Fh(process.cwd(),"agentx.json");return Lh(o)||(console.log(W.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Uh(o,"utf-8"))}async function Wh(e,o){if(!e)return;if(e==="me"){let n=o?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(W.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await qh([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let t=e.split(":");if(t.length>=2)return{channel:t[0],chatId:t[1],accountId:t[2]};console.log(W.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var xo=new Mh().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');xo.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>",`IANA timezone (default: ${wi})`,wi).option("--timeout <seconds>","max run time","600").option("--model <model>","override model").option("--disabled","create but leave disabled").option("--dry-run","print what would be written without writing").action(async(e,o)=>{if(!e){xo.help();return}o.agent||(console.log(W.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(W.red(' --do "<prompt>" is required')),process.exit(1));let t=yi(e);t||(console.log(W.red(` Couldn't parse: "${e}"`)),console.log(W.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(W.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(W.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=hg(o.config),s=ta(n);n.agents?.[o.agent]||(console.log(W.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(W.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await Wh(o.notify,s),r=o.id||Ra(t.matched,o.agent),a=Da({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:_a(o.onError),enabled:!o.disabled}),c=a.onError,l=await pe(d=>je(d,`crons.${r}`,a),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(W.red(` \u2717 ${l.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(W.green(` \u2713 ${g} cron ${W.cyan(r)}`)),console.log(W.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(W.dim(` Agent: ${o.agent}`)),i&&console.log(W.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(W.dim(` On error: ${c.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});xo.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async e=>{let t=hg(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(W.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?W.yellow("\u25D0"):i.enabled?W.green("\u25CF"):W.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${W.cyan(s.padEnd(32))} ${W.dim(i.schedule.padEnd(14))} ${W.dim("\u2192")} ${i.agent}`),console.log(W.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(W.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(W.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=Ma(Pa(i.schedule,c),c);console.log(W.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(W.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,o]of[["on",!0],["off",!1]])xo.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await Fa(t,o);n.success||(console.log(W.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});xo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await pe(t=>{if(!St(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);Oa(t,`crons.${e}`)});o.success||(console.log(W.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});for(let[e,o,t]of[["approve",La,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",Ua,"reject an agent's pending create/delete request (drops the request)"]])xo.command(`${e} <id>`).description(t).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await o(n,{configPath:s.config});i.success||(console.log(W.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(W.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});xo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=yi(o);t||(console.log(W.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(W.green(` "${o}"`)),console.log(W.dim(` \u2192 ${t.cron}`)),console.log(W.dim(` \u2192 ${t.human}`))});import{Command as Bh}from"commander";import $e from"chalk";import So from"chalk";function yg(e=Date.now()){return{id:"sample",title:"New meeting date for Sam",context:"He wrote: \u201CNo problem, pick the time that suits you and tell me.\u201D",ask:"Which date should I offer him?",recommend:"Thursday 14:00: your calendar is free and it is before his weekend",choices:["Thursday 14:00","Sunday 11:00","Monday 16:00"],draft:"Thanks Sam. Could we meet on {choice}? If that doesn't suit you, tell me what does.",say:"Sam is waiting for a new meeting date. Pick one.",if_silent:"keep",expires:new Date(e+2*864e5).toISOString(),raised_by:"assistant",created_at:new Date(e-12*6e4).toISOString(),status:"pending",origin:{kind:"reminder",id:"sample",title:"Reply to Sam about the meeting"}}}var wg=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");function $g(e){e.command("popup").description("show a card on this Mac now and record your answer (macOS)").argument("[key]","card key from `agentx approvals list`, e.g. card:2026-01-05-new-meeting-date-ab12").option("--sample","show a sample card; nothing is recorded").option("--pick <n>","start with option n picked (previews)").option("--theme <system|light|dark>","override approvals.popup.theme").option("--capture <file.png>","save a picture of the card window").option("--timeout <seconds>","override approvals.popup.timeoutSeconds").action(async(o,t)=>{if(process.platform!=="darwin"){console.error(So.red(" the popup needs macOS")),process.exitCode=1;return}let n=o?.startsWith("card:")?o.slice(5):o,s=t.sample?yg():n?hc(process.cwd(),n):null;if(!s||s.status!=="pending"){console.error(So.red(o?` no card waiting for "${o}"`:" give a card key, or --sample")),process.exitCode=1;return}let i={...jt().popup};(t.theme==="system"||t.theme==="light"||t.theme==="dark")&&(i.theme=t.theme),t.timeout&&(i.timeoutSeconds=Number(t.timeout));let r=await $c(s,i,{from:t.sample?"Assistant":void 0,capture:t.capture,pick:Number(t.pick)||void 0});if(t.capture&&console.log(So.dim(` picture saved to ${t.capture}`)),t.sample){console.log(` answer (not recorded): ${JSON.stringify(r)}`);return}if(r.action==="dismiss"){console.log(So.dim(" not answered; the card is still waiting"));return}let a=await as({root:process.cwd()},`card:${s.id}`,r.action,{by:"operator (popup)",...r.action==="yes"?{choice:r.choice,text:r.text}:{}});if(!a.ok){console.error(So.red(` ${a.error}`)),process.exitCode=1;return}console.log(So.green(` \u2713 ${a.message}`))}),e.command("checkin").description("run a check-in now: waiting cards come back, open reminders get cards (daemon, macOS)").option("--daily","the daily pass: every open reminder, not only those due soon").action(async o=>{let t={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(t.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let n=await fetch(`${wg()}/approvals/checkin`,{method:"POST",headers:t,body:JSON.stringify({daily:!!o.daily})}),s=await n.json().catch(()=>({}));if(!n.ok){console.error(So.red(` ${s.error??n.status}`)),process.exitCode=1;return}console.log(So.green(` \u2713 ${s.started} pass started; agents are writing cards. Watch: agentx approvals list`))}catch(n){console.error(So.red(` couldn't reach the daemon at ${wg()}: ${n?.message??n}`)),process.exitCode=1}})}var Eo=new Bh("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals, WhatsApp replies)"),Jh={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki",whatsapp:"whatsapp"};function bg(){return{root:process.cwd()}}function ur(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function Hh(e){console.log(` ${$e.cyan(e.key)} ${$e.dim(`[${Jh[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?$e.dim(` (later: until ${ur(e.snoozed_until)})`):""}`),console.log(` ${$e.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${$e.green("Recommends:")} ${e.recommend}`),e.choices?.forEach((o,t)=>console.log(` ${$e.magenta(`${t+1}.`)} ${o}`)),e.expires&&console.log($e.yellow(` Expires ${ur(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log($e.dim(` ${e.detail}`)),e.source&&console.log($e.dim(` ${e.source}`)),console.log($e.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}Eo.command("list",{isDefault:!0}).alias("ls").description("what is waiting, most urgent first").option("--all","include items you put off with `later`").option("--json","machine-readable output").action(e=>{let o=wc(bg(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(o,null,2));return}for(let t of o.errors)console.log($e.red(` couldn't read ${t.kind}: ${t.error}`));if(o.items.length===0){console.log($e.dim(` nothing waiting${o.snoozed?` (${o.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let t of o.items)Hh(t),console.log();console.log($e.dim(` ${o.items.length} waiting${o.snoozed?`, ${o.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function fr(e,o,t){let n=jt(),s=t.hours?Number(t.hours):n.laterHours;if(o==="later"&&!(s>0)){console.error($e.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await as(bg(),e,o,{force:t.force,note:t.note,laterHours:s,choice:t.choice,text:t.text});if(!i.ok){console.error($e.red(` ${i.error}`)),process.exitCode=1;return}console.log($e.green(` \u2713 ${i.message}`))}Eo.command("approve").alias("yes").description("say yes: enables the schedule, lets the fact be used, writes the wiki article, or tells the agent yes").argument("<key>","item key from `agentx approvals list`, e.g. card:2026-01-05-publish-draft-ab12").option("--force","wiki: approve even if the article changed since the proposal").option("--note <text>","cards: a note passed to the agent with your answer").option("--choice <n>","cards with choices: which one, by number or label").option("--text <message>","cards with a suggested message: the message as you want it sent").action((e,o)=>fr(e,"yes",o));Eo.command("reject").alias("no").description("say no: drops the request, keeps the fact out, declines the article, or tells the agent no").argument("<key>","item key from `agentx approvals list`").option("--note <text>","why; kept with cards and wiki proposals").action((e,o)=>fr(e,"no",o));Eo.command("later").description("put an item off; it leaves the list and comes back later (a card still expires on time)").argument("<key>","item key from `agentx approvals list`").option("--hours <n>","how long (default: approvals.laterHours, 24)").action((e,o)=>fr(e,"later",o));Eo.command("request").description("raise a decision card yourself, for example to test the inbox (agents use the agentx_approval tool)").requiredOption("--agent <id>","the agent the card is from; it gets the result").requiredOption("--title <text>","what it is, in one line").requiredOption("--ask <text>","the yes/no question").requiredOption("--recommend <text>","the advice and why, in one line").requiredOption("--if-silent <value>",`what applies if nobody answers: ${fc.join(", ")}`).option("--expires <when>","ISO date or time, or like 12h / 3d (default: approvals.defaultExpiryDays)").option("--source <link>","link to the draft, PR or issue").option("--choice <label>","a ready-made answer; repeat for up to 5",(e,o=[])=>[...o,e]).option("--draft <message>","a suggested message; {choice} is replaced by the pick").option("--say <line>","the short line the Mac popup speaks (default: the title)").option("--context <text>","a few lines of background, shown above the question").action(e=>{let o=jt(),t=yc(process.cwd(),{raised_by:e.agent,title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.ifSilent,expires:e.expires,source:e.source,choices:e.choice,draft:e.draft,say:e.say,context:e.context},{settings:o});if(!t.ok){console.error($e.red(` ${t.error}`)),process.exitCode=1;return}console.log($e.green(` \u2713 card:${t.card.id} raised; expires ${ur(t.card.expires)}, then: ${t.card.if_silent}`))});$g(Eo);Eo.command("settings").description('show or change expiry, "later" and digest settings (approvals in agentx.json)').option("--expiry-days <n>","days a card gets when it doesn't say").option("--max-expiry-days <n>","longest a card may wait").option("--later-hours <n>","how long `later` hides an item").option("--notify-agent <on|off>","tell the agent that raised a card its result").option("--digest <on|off>","the daily message about what is waiting").option("--digest-time <HH:MM>","when the digest goes out, 24-hour local time").option("--digest-timezone <zone>",`IANA timezone for --digest-time; "local" for this machine's`).option("--digest-to <channel:chatId>",'where the digest goes; "default" for notifications.destination').option("--popup <on|off>","Mac popup for new cards (macOS)").option("--popup-speak <on|off>","the popup speaks a short line").option("--popup-voice <name>",'voice for the spoken line; "default" for the system voice').option("--popup-sound <name>",'system sound, like Glass; "none" for silence').option("--popup-timeout <seconds>","how long the popup waits for you").option("--popup-style <card|dialog>","the web card, or plain macOS dialogs").option("--popup-theme <system|light|dark>","the card's colours").option("--checkin <on|off>","check-ins: waiting cards and open reminders, a few times a day (macOS)").option("--checkin-times <HH:MM,...>","local times of the normal passes").option("--checkin-daily <HH:MM>","local time of the daily pass").option("--checkin-lists <list,...>","your Reminders lists to look at").option("--checkin-agent <id>",'agent that writes cards for reminders no agent owns; "none" to clear').action(async e=>{let o={},t=(l,g)=>{if(g===void 0)return;let d=Number(g);if(!(d>0))throw new Error(`${l} must be a positive number`);return d},n=(l,g)=>{if(g!==void 0){if(g==="on")return!0;if(g==="off")return!1;throw new Error(`${l} takes on or off`)}};try{o.defaultExpiryDays=t("--expiry-days",e.expiryDays),o.maxExpiryDays=t("--max-expiry-days",e.maxExpiryDays),o.laterHours=t("--later-hours",e.laterHours),o.notifyAgent=n("--notify-agent",e.notifyAgent),o.digestEnabled=n("--digest",e.digest),o.popupEnabled=n("--popup",e.popup),o.popupSpeak=n("--popup-speak",e.popupSpeak),e.popupVoice!==void 0&&(o.popupVoice=e.popupVoice==="default"?null:e.popupVoice),e.popupSound!==void 0&&(o.popupSound=e.popupSound==="none"?"":e.popupSound),o.popupTimeoutSeconds=t("--popup-timeout",e.popupTimeout),e.popupStyle!==void 0&&(o.popupStyle=e.popupStyle),e.popupTheme!==void 0&&(o.popupTheme=e.popupTheme),o.checkinEnabled=n("--checkin",e.checkin);let l=g=>g?.split(",").map(d=>d.trim()).filter(Boolean);if(o.checkinTimes=l(e.checkinTimes),e.checkinDaily!==void 0&&(o.checkinDailyAt=e.checkinDaily),o.checkinLists=l(e.checkinLists),e.checkinAgent!==void 0&&(o.checkinAgent=e.checkinAgent==="none"?null:e.checkinAgent),e.digestTime!==void 0&&(o.digestTime=e.digestTime),e.digestTimezone!==void 0&&(o.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")o.destination=null;else{let g=cl(e.digestTo);if(!g)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");o.destination=g}}catch(l){console.error($e.red(` ${l.message}`)),process.exitCode=1;return}if(Object.values(o).some(l=>l!==void 0)){let l=await ll(o);if(!l.success){console.error($e.red(` ${l.error}`)),process.exitCode=1;return}console.log($e.green(" \u2713 saved")+(l.reloaded?$e.dim(" (daemon reloaded)"):""))}let i=jt(),r=i.digest.destination;console.log(` Cards expire after ${i.defaultExpiryDays} day(s) unless they say (at most ${i.maxExpiryDays})`),console.log(` "Later" hides an item ${i.laterHours} hour(s)`),console.log(` Tell the agent ${i.notifyAgent?"on":"off"}`),console.log(` Daily digest ${i.digest.enabled?`on, at ${i.digest.time}${i.digest.timezone?` (${i.digest.timezone})`:" (this machine's time)"}`:"off"}`),console.log(` Digest goes to ${r?`${r.channel} ${r.chatId}`:"notifications.destination"}`);let a=i.popup;console.log(` Mac popup ${a.enabled?`on: ${a.style}, sound ${a.sound||"none"}, ${a.speak?`speaks${a.voice?` (${a.voice})`:""}`:"silent"}, waits ${a.timeoutSeconds}s`:"off"}`);let c=i.checkin;console.log(` Check-ins ${c.enabled?`on: daily ${c.dailyAt}, then ${c.times.join(", ")}; lists ${c.lists.join(", ")}; agent ${c.agent??"none"}`:"off"}`)});import{Command as uy}from"commander";import Gt from"chalk";import ie from"chalk";import Dn from"prompts";import{readFileSync as Gh,writeFileSync as zh,existsSync as Vh}from"fs";import{resolve as kg}from"path";var Yh=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Kh(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function hr(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function vg(e=".env"){let o=kg(e);if(!Vh(o))return[];let t=Gh(o,"utf-8"),n=[];for(let s of t.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let i=s.match(Yh);i?n.push({kind:"kv",key:i[1],value:Kh(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Xh(e){return e.map(o=>o.kind==="kv"?`${o.key}=${hr(o.value)}`:o.raw).join(`
|
|
411
411
|
`)+`
|
|
412
|
-
`}function _n(e,o,t=".env"){let n=kg(t),s=vg(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${hr(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${hr(o)}`})),zh(n,Xh(s))}function yr(e,o=".env"){return vg(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var xg="https://t.me/BotFather";async function Qh(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function Zh(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function Sg(e={}){console.log(),console.log(ie.bold(" Connect Telegram")),console.log(),console.log(ie.dim(` 1. Open ${xg}`)),console.log(ie.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ie.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await Dn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),$=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b($,[xg],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Dn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(ie.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Qh(t.trim());n||(console.log(ie.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ie.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(ie.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(ie.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Dn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ie.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Dn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ie.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;_n(f,t.trim()),process.env[f]=t.trim();let p=await pe(b=>{je(b,"channels.telegram.enabled",!0),je(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=St(b,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),je(b,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ie.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ie.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ie.dim(` Token stored in .env as ${f}`)),console.log(ie.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ie.dim(" Daemon hot-reloaded.")):console.log(ie.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Dn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(ie.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ie.dim(" Waiting up to 90s..."));let w=await Zh(t.trim(),9e4);if(!w){console.log(ie.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ie.dim(" agentx config set notifications.destination.channel telegram")),console.log(ie.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ie.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await pe(b=>{je(b,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ie.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ie.green(" \u2713 Default --notify target set")),console.log(ie.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ie.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ie.dim(" Daemon hot-reloaded."))}import be from"chalk";import wr from"prompts";import{existsSync as br,mkdirSync as ey,readdirSync as oy,readFileSync as Eg}from"fs";import{resolve as $r}from"path";var ty=".agentx/whatsapp-sessions";function ny(){let e=$r(process.cwd(),".agentx/daemon.pid");if(!br(e))return!1;try{let o=parseInt(Eg(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function sy(e){if(!br(e))return!1;try{return oy(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function iy(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(be.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(be.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;ey(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(be.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(be.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(be.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(be.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Ag(e={}){if(console.log(),console.log(be.bold(" Connect WhatsApp")),console.log(),ny()){console.log(be.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(be.dim(" agentx daemon stop")),console.log();let{cont:l}=await wr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(be.red(" Aborted")),process.exit(1))}let o=e.configPath||$r(process.cwd(),"agentx.json");br(o)||(console.log(be.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Eg(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||ty,s=$r(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(be.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await wr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(be.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(sy(s)&&a){let{keep:l}=await wr({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(be.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await iy(s,g=>console.log(g))||(console.log(be.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await pe(l=>{je(l,"channels.whatsapp.enabled",!0),je(l,"channels.whatsapp.sessionDir",n),je(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(be.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(be.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(be.dim(` Session: ${n}`)),console.log(be.dim(" Start the daemon to begin receiving:")),console.log(be.dim(" agentx daemon start")),console.log(be.dim(" Add routes later with:")),console.log(be.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as ry}from"crypto";import Ae from"chalk";import Tg from"prompts";var Ws="agentx-mesh:",Bs="//join/";function ay(e){return Buffer.from(e,"utf-8").toString("base64url")}function cy(e){return Buffer.from(e,"base64url").toString("utf-8")}function ly(e){return`${Ws}${Bs}${ay(JSON.stringify(e))}`}function dy(e){if(!e.startsWith(`${Ws}${Bs}`))throw new Error(`Not a mesh invite link \u2014 expected ${Ws}${Bs}\u2026`);let o=e.slice(Ws.length+Bs.length),t=JSON.parse(cy(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function gy(){return ry(32).toString("hex")}function my(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function py(e){return e?.node?.name||e?.node?.id||"node"}async function Og(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(Ae.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=yr("MESH_TOKEN");r||(r=gy(),_n("MESH_TOKEN",r),console.log(Ae.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||my(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Tg({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(Ae.red(" Aborted")),process.exit(1)),a=d}let l=await pe(d=>{je(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ae.red(` \u2717 ${l.error}`)),process.exit(1));let g=ly({url:a,token:r,name:py(i),version:1});console.log(),console.log(Ae.bold(" Mesh invite")),console.log(),console.log(` ${Ae.cyan(g)}`),console.log(),console.log(Ae.dim(" Run on the other node:")),console.log(Ae.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Ae.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function jg(e,o={}){let t;try{t=dy(e)}catch(i){console.log(Ae.red(` \u2717 ${i.message}`)),process.exit(1)}let n=yr("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Tg({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Ae.red(" Aborted (keeping existing .env)")),process.exit(1))}_n("MESH_TOKEN",t.token);let s=await pe(i=>{je(i,"mesh.enabled",!0);let r=St(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),je(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(Ae.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ae.green(" \u2713 Joined mesh")),console.log(Ae.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(Ae.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ae.dim(" Daemon hot-reloaded.")):console.log(Ae.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(Ae.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(Ae.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Ae.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var zt=new uy().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");zt.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 Sg({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});zt.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 Ag({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Cg=zt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Cg.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 Og({url:e.url,configPath:e.config})});Cg.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await jg(e,{configPath:o.config})});zt.action(()=>{console.log(),console.log(Gt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Gt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Gt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Gt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Gt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Gt.dim(" GitLab connect is the next slice.")),console.log()});ne();import{Command as fy}from"commander";import fe from"chalk";var Pn=new fy().name("usage").description("token usage analysis and reporting");Pn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=C(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(fe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(fe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${fe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${fe.red(String(s.totalErrors))}`),console.log(),console.log(fe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${fe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${fe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(fe.red(" Daemon not running. Start with: agentx daemon start")):console.log(fe.red(` ${e.message}`))}});Pn.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(fe.red(` Script not found: ${s}`)),console.log(fe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(fe.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(fe.red(" Analysis failed. Is Python 3 installed?"))}});Pn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:o}=await import("./surface-usage-HVVP22SA.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-N3AVBQMK.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(fe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${fe.dim("\xB7")} ${d}`);console.log(),console.log(fe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(fe.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(fe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(fe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(fe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(fe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=fe.dim(`${i.days}d`);console.log(` ${fe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(fe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as hy}from"commander";import ke from"chalk";import{readFileSync as yy}from"fs";import{resolve as wy}from"path";ne();var Ho=new hy().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Ho.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{ma(wy(process.cwd(),".env"))}catch{}let o=$y(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-SI5GP3XR.js");t(o)}catch(o){console.log(ke.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(ke.dim(o.stack)),process.exit(1)}});function $y(e,o){try{let t=C();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(ke.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(ke.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
412
|
+
`}function _n(e,o,t=".env"){let n=kg(t),s=vg(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${hr(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${hr(o)}`})),zh(n,Xh(s))}function yr(e,o=".env"){return vg(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var xg="https://t.me/BotFather";async function Qh(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function Zh(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function Sg(e={}){console.log(),console.log(ie.bold(" Connect Telegram")),console.log(),console.log(ie.dim(` 1. Open ${xg}`)),console.log(ie.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ie.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await Dn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),$=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b($,[xg],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Dn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(ie.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Qh(t.trim());n||(console.log(ie.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ie.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(ie.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(ie.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Dn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ie.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Dn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ie.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;_n(f,t.trim()),process.env[f]=t.trim();let p=await pe(b=>{je(b,"channels.telegram.enabled",!0),je(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=St(b,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),je(b,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ie.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ie.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ie.dim(` Token stored in .env as ${f}`)),console.log(ie.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ie.dim(" Daemon hot-reloaded.")):console.log(ie.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Dn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(ie.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ie.dim(" Waiting up to 90s..."));let w=await Zh(t.trim(),9e4);if(!w){console.log(ie.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ie.dim(" agentx config set notifications.destination.channel telegram")),console.log(ie.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ie.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await pe(b=>{je(b,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ie.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ie.green(" \u2713 Default --notify target set")),console.log(ie.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ie.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ie.dim(" Daemon hot-reloaded."))}import be from"chalk";import wr from"prompts";import{existsSync as br,mkdirSync as ey,readdirSync as oy,readFileSync as Eg}from"fs";import{resolve as $r}from"path";var ty=".agentx/whatsapp-sessions";function ny(){let e=$r(process.cwd(),".agentx/daemon.pid");if(!br(e))return!1;try{let o=parseInt(Eg(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function sy(e){if(!br(e))return!1;try{return oy(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function iy(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(be.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(be.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;ey(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(be.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(be.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(be.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(be.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Ag(e={}){if(console.log(),console.log(be.bold(" Connect WhatsApp")),console.log(),ny()){console.log(be.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(be.dim(" agentx daemon stop")),console.log();let{cont:l}=await wr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(be.red(" Aborted")),process.exit(1))}let o=e.configPath||$r(process.cwd(),"agentx.json");br(o)||(console.log(be.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Eg(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||ty,s=$r(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(be.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await wr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(be.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(sy(s)&&a){let{keep:l}=await wr({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(be.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await iy(s,g=>console.log(g))||(console.log(be.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await pe(l=>{je(l,"channels.whatsapp.enabled",!0),je(l,"channels.whatsapp.sessionDir",n),je(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(be.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(be.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(be.dim(` Session: ${n}`)),console.log(be.dim(" Start the daemon to begin receiving:")),console.log(be.dim(" agentx daemon start")),console.log(be.dim(" Add routes later with:")),console.log(be.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as ry}from"crypto";import Ae from"chalk";import Tg from"prompts";var Ws="agentx-mesh:",Bs="//join/";function ay(e){return Buffer.from(e,"utf-8").toString("base64url")}function cy(e){return Buffer.from(e,"base64url").toString("utf-8")}function ly(e){return`${Ws}${Bs}${ay(JSON.stringify(e))}`}function dy(e){if(!e.startsWith(`${Ws}${Bs}`))throw new Error(`Not a mesh invite link \u2014 expected ${Ws}${Bs}\u2026`);let o=e.slice(Ws.length+Bs.length),t=JSON.parse(cy(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function gy(){return ry(32).toString("hex")}function my(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function py(e){return e?.node?.name||e?.node?.id||"node"}async function Og(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(Ae.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=yr("MESH_TOKEN");r||(r=gy(),_n("MESH_TOKEN",r),console.log(Ae.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||my(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Tg({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(Ae.red(" Aborted")),process.exit(1)),a=d}let l=await pe(d=>{je(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ae.red(` \u2717 ${l.error}`)),process.exit(1));let g=ly({url:a,token:r,name:py(i),version:1});console.log(),console.log(Ae.bold(" Mesh invite")),console.log(),console.log(` ${Ae.cyan(g)}`),console.log(),console.log(Ae.dim(" Run on the other node:")),console.log(Ae.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Ae.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function jg(e,o={}){let t;try{t=dy(e)}catch(i){console.log(Ae.red(` \u2717 ${i.message}`)),process.exit(1)}let n=yr("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Tg({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Ae.red(" Aborted (keeping existing .env)")),process.exit(1))}_n("MESH_TOKEN",t.token);let s=await pe(i=>{je(i,"mesh.enabled",!0);let r=St(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),je(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(Ae.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ae.green(" \u2713 Joined mesh")),console.log(Ae.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(Ae.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ae.dim(" Daemon hot-reloaded.")):console.log(Ae.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(Ae.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(Ae.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Ae.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var zt=new uy().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");zt.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 Sg({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});zt.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 Ag({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Cg=zt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Cg.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 Og({url:e.url,configPath:e.config})});Cg.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await jg(e,{configPath:o.config})});zt.action(()=>{console.log(),console.log(Gt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Gt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Gt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Gt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Gt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Gt.dim(" GitLab connect is the next slice.")),console.log()});ne();import{Command as fy}from"commander";import fe from"chalk";var Pn=new fy().name("usage").description("token usage analysis and reporting");Pn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=C(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(fe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(fe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${fe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${fe.red(String(s.totalErrors))}`),console.log(),console.log(fe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${fe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${fe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(fe.red(" Daemon not running. Start with: agentx daemon start")):console.log(fe.red(` ${e.message}`))}});Pn.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(fe.red(` Script not found: ${s}`)),console.log(fe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(fe.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(fe.red(" Analysis failed. Is Python 3 installed?"))}});Pn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:o}=await import("./surface-usage-HVVP22SA.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-TSFYLHMZ.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(fe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${fe.dim("\xB7")} ${d}`);console.log(),console.log(fe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(fe.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(fe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(fe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(fe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(fe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=fe.dim(`${i.days}d`);console.log(` ${fe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(fe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as hy}from"commander";import ke from"chalk";import{readFileSync as yy}from"fs";import{resolve as wy}from"path";ne();var Ho=new hy().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Ho.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{ma(wy(process.cwd(),".env"))}catch{}let o=$y(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-SI5GP3XR.js");t(o)}catch(o){console.log(ke.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(ke.dim(o.stack)),process.exit(1)}});function $y(e,o){try{let t=C();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(ke.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(ke.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
413
413
|
`)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:o||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}Ho.command("list").description("list configured boards").action(()=>{try{let e=C();if(!e.boards?.length){console.log(ke.dim(`
|
|
414
414
|
No boards configured.
|
|
415
415
|
`));return}console.log();for(let o of e.boards){console.log(` ${ke.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(ke.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(ke.dim(` primary label: ${o.primaryToolLabel}`)),console.log(ke.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(ke.red(` ${e.message}`)),process.exit(1)}});Ho.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,o)=>{try{Mn(t=>{if(Array.isArray(t.boards)||(t.boards=[]),t.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(o.projects).split(",").map(i=>i.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:o.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(o.days,10)||30,closedWindowDays:parseInt(o.closedDays,10)||30};return o.label&&(s.primaryToolLabel=o.label),t.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(t){console.log(ke.red(` ${t.message}`)),process.exit(1)}});Ho.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,o)=>{try{Mn(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(o.name&&(s.name=o.name,i.push(`name="${o.name}"`)),o.projects){let r=String(o.projects).split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:r},i.push(`projects=${r.length}`)}if(o.label!==void 0&&(o.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=o.label,i.push(`label="${o.label}"`))),o.days&&(s.timeRangeDays=parseInt(o.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),o.closedDays&&(s.closedWindowDays=parseInt(o.closedDays,10)||s.closedWindowDays,i.push(`closed-days=${s.closedWindowDays}`)),i.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${i.join(", ")})`})}catch(t){console.log(ke.red(` ${t.message}`)),process.exit(1)}});var kr=Ho.command("column").description("manage a board's columns (add / remove / edit / list)");kr.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(yy("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!t)throw new Error(`board "${e}" not found`);let n=t.columns||[];if(n.length===0){console.log(ke.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let i=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${ke.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${ke.dim(i)}`)}}catch(o){console.log(ke.red(` ${o.message}`)),process.exit(1)}});kr.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,o,t)=>{try{Mn(n=>{let i=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!i)throw new Error(`board "${e}" not found`);if(i.columns=i.columns||[],i.columns.find(a=>a.id===o))throw new Error(`column "${o}" already exists on board "${e}"`);let r={id:o,title:t.title,kind:t.kind,scopedPrefix:t.scopedPrefix};if(t.kind==="scoped-label"){if(!t.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=t.scoped}if(t.kind==="label"){if(!t.label)throw new Error("--label required for kind=label");r.mapsToLabel=t.label}return t.accent&&(r.accent=t.accent),i.columns.push(r),`column "${o}" added to board "${e}"`})}catch(n){console.log(ke.red(` ${n.message}`)),process.exit(1)}});kr.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{Mn(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(r=>r.id!==o),s.columns.length===i)throw new Error(`column "${o}" not found`);return`column "${o}" removed from board "${e}"`})}catch(t){console.log(ke.red(` ${t.message}`)),process.exit(1)}});Ho.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Mn(o=>{if(!Array.isArray(o.boards)||o.boards.length===0)throw new Error("no boards configured");let t=o.boards.length;if(o.boards=o.boards.filter(n=>n.id!==e),o.boards.length===t)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(o){console.log(ke.red(` ${o.message}`)),process.exit(1)}});function Mn(e){let{summary:o,backupPath:t}=Qe(n=>e(n));console.log(ke.green(`
|
|
@@ -636,7 +636,7 @@ Restart the daemon to activate.
|
|
|
636
636
|
dist/
|
|
637
637
|
*.log
|
|
638
638
|
.env
|
|
639
|
-
`}import{Command as d$}from"commander";import Re from"chalk";import{writeFileSync as g$,mkdirSync as m$,existsSync as ri,readFileSync as Em,appendFileSync as Am}from"fs";import{resolve as an,dirname as jm}from"path";import{homedir as Jr}from"os";var Cm=new d$().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:o}=await import("./program-
|
|
639
|
+
`}import{Command as d$}from"commander";import Re from"chalk";import{writeFileSync as g$,mkdirSync as m$,existsSync as ri,readFileSync as Em,appendFileSync as Am}from"fs";import{resolve as an,dirname as jm}from"path";import{homedir as Jr}from"os";var Cm=new d$().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:o}=await import("./program-TSFYLHMZ.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=f$(t);break;case"bash":s=b$(t);break;case"fish":s=k$(t);break;default:console.error(Re.red(`unsupported shell: ${n}`)),console.error(Re.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?an(String(e.output)):p$(n);m$(jm(i),{recursive:!0}),g$(i,s),console.log(Re.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),u$(n,i,!!e.yes)});function p$(e){let o=Jr();switch(e){case"zsh":return an(o,".zsh","completions","_agentx");case"bash":return an(o,".bash_completion.d","agentx.bash");case"fish":return an(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function u$(e,o,t){if(e==="zsh"){let n=an(Jr(),".zshrc"),s=jm(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=ri(n)?Em(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Re.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&ri(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Am(n,g.join(`
|
|
640
640
|
`)+`
|
|
641
641
|
`),console.log(Re.green("\u2713 Patched ~/.zshrc")),console.log(Re.dim("Reload your shell: exec zsh"));return}console.log(Re.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Re.cyan(` ${i}`)),l&&console.log(Re.cyan(` ${r}`)),console.log(),console.log(Re.dim("Then reload: exec zsh")),console.log(Re.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=an(Jr(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((ri(n)?Em(n,"utf-8"):"").includes(o)){console.log(Re.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&ri(n)){Am(n,`
|
|
642
642
|
# agentx completion
|
|
@@ -652,4 +652,4 @@ ${v$({...o,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
|
|
|
652
652
|
${t.url}`)}catch(o){console.error(ln.red(` ${o.message}`)),process.exitCode=1}});Vn.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",Gr).action(async(e,o)=>{try{let t=await Yr(o.models);if(!zr(o.model,t)){console.log(Vr(o.model,t)),process.exitCode=1;return}let n=e==="-"?await E$():await S$(e,"utf8"),s=JSON.parse(n),{version:i}=await os(),r=_m({...s,fields:s.fields??{}},{model:o.model,version:i??"unknown"});console.log(r)}catch(t){console.error(ln.red(` ${t.message}`)),process.exitCode=1}});async function E$(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf8")}async function lj(){let e=await os(),o=new A$().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");o.hook("preAction",(t,n)=>{let s=gl(n);ml(s)&&dl("cli",s)});for(let t of[Fl,Ml,zt,Ct,Rt,oo,al,et,xs,xo,Eo,Jo,vs,sm,qo,rd,fd,Cn,Ad,Cd,Rd,Pd,Md,eg,sg,ig,Bt,Pn,lm,xn,Po,Cm,Vn])o.addCommand(t);for(let t of Pm)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Pm.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,T$(t,74," "),""].join(`
|
|
653
653
|
`)}),o}var Pm=[ee,Kt,Vo,go,En,Jt,Ve,To,Ho,dt,en,on,Uo,Je,Mt,qs,om,tm,ko,ot,yl,tt,Gn,Ji,zo,Dt,Hi,Zs,wo,Oo,wm,bm,cm];function T$(e,o,t){let n=[],s="";for(let i of e)s&&s.length+i.length+2>o&&(n.push(t+s),s=""),s+=(s?", ":"")+i;return s&&n.push(t+s),n.join(`
|
|
654
654
|
`)}export{lj as a};
|
|
655
|
-
//# sourceMappingURL=chunk-
|
|
655
|
+
//# sourceMappingURL=chunk-Y4EWOE4N.js.map
|
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as n}from"./chunk-
|
|
2
|
+
import{a as n}from"./chunk-Y4EWOE4N.js";import"./chunk-TQT4XDNN.js";import"./chunk-2WRWBPDL.js";import"./chunk-2XSVV3M3.js";import"./chunk-Z3IP66SL.js";import"./chunk-O5U5NVLR.js";import"./chunk-RKPAVWXF.js";import"./chunk-QJM2D22B.js";import"./chunk-EOBFJGTV.js";import"./chunk-IXWPA6WM.js";import"./chunk-S2GAEH2F.js";import"./chunk-7XB2CVC3.js";import"./chunk-CL53UVOF.js";import"./chunk-ZVP6GB4G.js";import"./chunk-3OIFSKSR.js";import"./chunk-AQASR6KR.js";import"./chunk-2D3RYIDU.js";import"./chunk-EKJG63EJ.js";import"./chunk-SYXAEWFN.js";import"./chunk-2YIWQ57T.js";import"./chunk-WP6KLXTP.js";import"./chunk-N6EWZGIX.js";import"./chunk-DP7RTNDM.js";import"./chunk-ZBRZ5T2G.js";import"./chunk-SFQUP3BP.js";import"./chunk-Y4CYQV7G.js";import"./chunk-IWQURDYO.js";import"./chunk-2AXFYDWF.js";import"./chunk-SZDACK6O.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-B5VRY4NI.js";import"./chunk-N2A3KIVY.js";import"./chunk-VWTBHLMX.js";import"./chunk-P5KHF46N.js";import"./chunk-PF5ZXMEG.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-QIMIARFO.js";import"./chunk-MYVHVJWZ.js";import"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-3AFZBXNX.js";import"./chunk-VIUCCUJ4.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import"./chunk-QAKL2D7O.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import"./chunk-KH4PKJGD.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";var r=["SIGINT","SIGTERM"];function o(t=process){for(let i of r)t.on(i,()=>{t.listenerCount(i)<=1&&t.exit(0)})}o();async function s(){let t=await n();if(process.argv.slice(2).length===0){t.outputHelp();return}t.parse()}s();
|
|
3
3
|
//# sourceMappingURL=cli.js.map
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as L}from"./chunk-C245D4BZ.js";import{d as St,e as kt,f as vt,g as xt,ga as Tt,h as $t,ha as Mt,i as Ct,j as Pt,k as bt}from"./chunk-
|
|
1
|
+
import{a as L}from"./chunk-C245D4BZ.js";import{d as St,e as kt,f as vt,g as xt,ga as Tt,h as $t,ha as Mt,i as Ct,j as Pt,k as bt}from"./chunk-QJM2D22B.js";import"./chunk-EOBFJGTV.js";import"./chunk-IXWPA6WM.js";import"./chunk-S2GAEH2F.js";import"./chunk-7XB2CVC3.js";import"./chunk-CL53UVOF.js";import"./chunk-ZVP6GB4G.js";import"./chunk-3OIFSKSR.js";import"./chunk-AQASR6KR.js";import"./chunk-2D3RYIDU.js";import"./chunk-EKJG63EJ.js";import{T as yt,k as lt,l as ct,m as dt,n as mt,o as pt}from"./chunk-SYXAEWFN.js";import"./chunk-2YIWQ57T.js";import"./chunk-WP6KLXTP.js";import"./chunk-N6EWZGIX.js";import"./chunk-DP7RTNDM.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-ZBRZ5T2G.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-Y4CYQV7G.js";import"./chunk-IWQURDYO.js";import"./chunk-2AXFYDWF.js";import"./chunk-SZDACK6O.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{s as ut}from"./chunk-B5VRY4NI.js";import"./chunk-N2A3KIVY.js";import"./chunk-VWTBHLMX.js";import"./chunk-P5KHF46N.js";import{a as ht}from"./chunk-PF5ZXMEG.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-QIMIARFO.js";import"./chunk-MYVHVJWZ.js";import"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-3AFZBXNX.js";import{f as gt,g as ft}from"./chunk-VIUCCUJ4.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import{j as it,k as rt,l as at}from"./chunk-QAKL2D7O.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-5MUJZODV.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{C as tt,E as st,F as ot,H as nt}from"./chunk-KH4PKJGD.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,2 +1,2 @@
|
|
|
1
|
-
import{a}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=program-
|
|
1
|
+
import{a}from"./chunk-Y4EWOE4N.js";import"./chunk-TQT4XDNN.js";import"./chunk-2WRWBPDL.js";import"./chunk-2XSVV3M3.js";import"./chunk-Z3IP66SL.js";import"./chunk-O5U5NVLR.js";import"./chunk-RKPAVWXF.js";import"./chunk-QJM2D22B.js";import"./chunk-EOBFJGTV.js";import"./chunk-IXWPA6WM.js";import"./chunk-S2GAEH2F.js";import"./chunk-7XB2CVC3.js";import"./chunk-CL53UVOF.js";import"./chunk-ZVP6GB4G.js";import"./chunk-3OIFSKSR.js";import"./chunk-AQASR6KR.js";import"./chunk-2D3RYIDU.js";import"./chunk-EKJG63EJ.js";import"./chunk-SYXAEWFN.js";import"./chunk-2YIWQ57T.js";import"./chunk-WP6KLXTP.js";import"./chunk-N6EWZGIX.js";import"./chunk-DP7RTNDM.js";import"./chunk-ZBRZ5T2G.js";import"./chunk-SFQUP3BP.js";import"./chunk-Y4CYQV7G.js";import"./chunk-IWQURDYO.js";import"./chunk-2AXFYDWF.js";import"./chunk-SZDACK6O.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-B5VRY4NI.js";import"./chunk-N2A3KIVY.js";import"./chunk-VWTBHLMX.js";import"./chunk-P5KHF46N.js";import"./chunk-PF5ZXMEG.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-QIMIARFO.js";import"./chunk-MYVHVJWZ.js";import"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-3AFZBXNX.js";import"./chunk-VIUCCUJ4.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import"./chunk-QAKL2D7O.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import"./chunk-KH4PKJGD.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{a as buildProgram};
|
|
2
|
+
//# sourceMappingURL=program-TSFYLHMZ.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentix-cli",
|
|
3
|
-
"version": "0.79.
|
|
3
|
+
"version": "0.79.1",
|
|
4
4
|
"description": "AI operations layer for small and medium businesses. Routes Telegram, WhatsApp, GitLab, GitHub, crons, webhooks, and mesh tasks to AI agents. Web wizard for operators, CLI for engineers. Self-hosted.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|
|
File without changes
|
|
File without changes
|
|
File without changes
|