agentix-cli 0.168.0 → 0.169.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/{board-dashboard-ESAX2ZFV.js → board-dashboard-NEYLE6NJ.js} +317 -288
- package/dist/board-dashboard-NEYLE6NJ.js.map +1 -0
- package/dist/{chunk-HRN4WKSJ.js → chunk-6VKWJQOX.js} +3 -3
- package/dist/{chunk-HRN4WKSJ.js.map → chunk-6VKWJQOX.js.map} +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/{program-7W2LJKDN.js → program-URGH65VO.js} +4 -4
- package/dist/web/activity-graph.global.js +12 -12
- package/dist/web/activity-graph.global.js.map +1 -1
- package/package.json +1 -1
- package/dist/board-dashboard-ESAX2ZFV.js.map +0 -1
- /package/dist/{program-7W2LJKDN.js.map → program-URGH65VO.js.map} +0 -0
|
@@ -531,7 +531,7 @@ ${l}`)}let $={agentId:o,message:w,context:{channel:g,sender:y?"opencode":"openai
|
|
|
531
531
|
|
|
532
532
|
`)}}function yy(r){r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"})}function wy(r,e,t,n,s,i){r.write(`data: ${JSON.stringify({id:e,object:"chat.completion.chunk",created:t,model:n,choices:[{index:0,delta:s,finish_reason:i}]})}
|
|
533
533
|
|
|
534
|
-
`)}function by(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);fc(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 fc(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Hn=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Hn(`${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(Hn.levelOrder[e]<Hn.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)}},Gn=Hn;Ot(Gn,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as rA,statSync as iA}from"fs";var et={version:"0.
|
|
534
|
+
`)}function by(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);fc(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 fc(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Hn=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Hn(`${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(Hn.levelOrder[e]<Hn.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)}},Gn=Hn;Ot(Gn,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as rA,statSync as iA}from"fs";var et={version:"0.169.0",commit:"ce20476",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function oA(r,e){let t=e.mtimeMs!==null&&e.mtimeMs>Date.parse(r.startedAt),n=!!e.version&&!!r.version&&e.version!==r.version;return{newer:t||n,changedAt:e.mtimeMs===null?null:new Date(e.mtimeMs).toISOString(),version:e.version}}function vy(){let r=null;try{r=iA(rA(process.argv[1])).mtimeMs}catch{}let e=Hm().version;return oA(et,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as aA}from"crypto";var Tr=class{constructor(e=new ih){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!cA.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};dA(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:aA(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=lA(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}},cA=["run","task","signal","mesh","channel","status"];function lA(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 dA(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 Sy(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 xr,timingSafeEqual as $y}from"crypto";var Ar=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),l=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let b={};for(let[w,$]of Object.entries(e.headers))(w.startsWith("x-hubspot")||w.startsWith("x-hub")||w.startsWith("x-github")||w.startsWith("x-gitlab")||w.startsWith("stripe")||w.startsWith("sentry")||w.startsWith("x-vercel")||w.startsWith("x-odoo")||w.startsWith("x-webhook")||w==="user-agent"||w==="content-type"||w==="host"||w==="x-forwarded-host"||w==="x-forwarded-proto"||w==="x-forwarded-for")&&(b[w]=$);this.log(`Webhook [${l}] reqUrl=${e.url} headers: ${JSON.stringify(b)}`)}let d=this.validateSignature(e.headers,a,l,i,e.url);if(d){this.log(`Webhook [${l}] -> ${i}: REJECTED (${d})`),this.sendJson(t,401,{error:d});return}let u=this.buildSummary(l,c,e.headers);this.log(`Webhook [${l}] -> ${i}: ${u.slice(0,100)}`);let h=this.extractEventType(l,c,e.headers),f=this.webhookEntries.find(b=>b.enabled&&b.agentId===i&&b.source===l),y=h&&f?.triggers?.[h]||f?.defaultWorkflow||null;if(await this.fireHookSafe(l,h,i,c),y&&this.workflowDispatcher)try{let b=await this.workflowDispatcher.dispatchWorkflow({workflowId:y,entityRef:{kind:"webhook",id:`${l}:${i}:${h??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:h,payload:c},trigger:{source:l}});this.log(`Webhook [${l}/${h??"\u2014"}] -> workflow=${y} (claimed=${b.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:h,workflow:y,claimed:b.claimed});return}catch(b){this.log(`Workflow dispatch failed [${l}/${h}/${y}]: ${b.message}`)}let g=this.webhookEntries.find(b=>b.enabled&&b.node&&b.agentId===i&&b.source===l);if(g?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:g.node,status:"accepted"}),this.mesh.sendTask(g.node,u,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(b=>this.log(`Mesh-forwarded webhook [${l}] -> ${g.node}/${i}: ${b?.slice(0,100)||"ok"}`),b=>this.log(`Mesh forward failed [${l}] -> ${g.node}/${i}: ${b.message}`));return}try{let b=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${l}`,sender:`webhook:${l}`}});this.sendJson(t,b.error?500:200,{ok:!b.error,agent:i,source:l,response:b.content?.slice(0,500),error:b.error,duration:b.duration})}catch(b){this.sendJson(t,500,{error:b.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let d of t.commits.slice(0,3))s.push(` - ${d.message?.split(`
|
|
535
535
|
`)[0]||"no message"} (${d.author?.name||""})`)}let l=t.object_attributes;if(l?.title&&(s.push(`Title: ${l.title}`),s.push(`State: ${l.state||""}`),s.push(`Action: ${l.action||""}`),l.source_branch&&s.push(`Branch: ${l.source_branch} -> ${l.target_branch}`),l.url&&s.push(`URL: ${l.url}`)),l?.iid&&!l?.source_branch&&(s.push(`Issue #${l.iid}: ${l.title||""}`),l.description&&s.push(`Description: ${l.description.slice(0,200)}`)),t.object_kind==="pipeline"){let d=t.object_attributes;s.push(`Pipeline: ${d?.status||""} (${d?.ref||""})`),s.push(`Duration: ${d?.duration||0}s`)}break}case"github":{let o=n["x-github-event"]||"event",a=t.repository?.full_name||"",c=t.sender?.login||"";if(s.push(`Event: ${o}`),a&&s.push(`Repository: ${a}`),c&&s.push(`Sender: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits))for(let u of t.commits.slice(0,3))s.push(` - ${u.message?.split(`
|
|
536
536
|
`)[0]||""} (${u.author?.name||""})`);let l=t.pull_request;l&&(s.push(`PR #${l.number}: ${l.title}`),s.push(`Action: ${t.action}`),s.push(`Branch: ${l.head?.ref} -> ${l.base?.ref}`));let d=t.issue;d&&(s.push(`Issue #${d.number}: ${d.title}`),s.push(`Action: ${t.action}`));break}case"stripe":{let o=t.type||"event",a=t.data?.object||{};s.push(`Event: ${o}`),a.amount&&s.push(`Amount: ${(a.amount/100).toFixed(2)} ${a.currency?.toUpperCase()||""}`),a.customer_email&&s.push(`Customer: ${a.customer_email}`),a.description&&s.push(`Description: ${a.description}`),a.status&&s.push(`Status: ${a.status}`);break}case"sentry":{let o=n["sentry-hook-resource"]||"event";s.push(`Resource: ${o}`);let a=t.data||t;a.error?.title&&s.push(`Error: ${a.error.title}`),a.error?.culprit&&s.push(`Culprit: ${a.error.culprit}`),a.error?.metadata?.value&&s.push(`Message: ${a.error.metadata.value}`),t.url&&s.push(`URL: ${t.url}`);break}case"hubspot":{let o=Array.isArray(t)?t:null,a=o||null;if(a&&a.length){s.push(`Events: ${a.length}`);for(let l of a.slice(0,3)){let d=l.subscriptionType??"?",u=l.objectId??"?",h=l.changeFlag??l.changeSource??"";s.push(` - ${d} (object ${u}${h?`, ${h}`:""})`)}}else{let l=t.subscriptionType??"event",d=t.objectId??"?";s.push(`Event: ${l} (object ${d})`)}let c=a?.[0]?.portalId??t.portalId;c!=null&&s.push(`Portal: ${c}`);break}case"odoo":{let o=typeof t.event=="string"&&t.event||typeof t.subscriptionType=="string"&&t.subscriptionType||typeof t.model=="string"&&(typeof t.action=="string"?`${t.model}.${t.action}`:t.model)||"event";s.push(`Event: ${o}`);let a=n["x-odoo-database"]||(typeof t.database=="string"?t.database:"");a&&s.push(`Database: ${a}`);let c=t.record||t;c?.id&&s.push(`Record id: ${c.id}`),c?.name&&s.push(`Name: ${String(c.name).slice(0,200)}`),c?.partner_id?.[1]&&s.push(`Partner: ${c.partner_id[1]}`),c?.email&&s.push(`Email: ${c.email}`),c?.amount_total!=null&&s.push(`Amount: ${c.amount_total}`),c?.state&&s.push(`State: ${c.state}`);break}default:s.push(`Headers: ${JSON.stringify(Object.keys(n).filter(o=>o.startsWith("x-")).slice(0,5))}`),s.push(`Payload keys: ${Object.keys(t).slice(0,10).join(", ")}`);let i=JSON.stringify(t).slice(0,500);s.push(`Body: ${i}`)}return s.join(`
|
|
537
537
|
`)}async readBody(e){return new Promise(t=>{let n="";e.on("data",s=>n+=s.toString()),e.on("end",()=>{let s;try{s=n?JSON.parse(n):{}}catch{s={raw:n}}t({raw:n,parsed:s})}),e.on("error",()=>t({raw:"",parsed:{}}))})}validateSignature(e,t,n,s,i){let o=this.webhookEntries.find(d=>d.enabled&&d.agentId===s&&d.source===n);if(!o?.secretEnv)return null;let a=process.env[o.secretEnv];if(!a)return`webhook entry "${o.id}" expects env ${o.secretEnv} but it is unset`;let c=d=>{let u=e[d.toLowerCase()];return Array.isArray(u)?u[0]:u};if(n==="github"){let d=c("x-hub-signature-256");if(!d)return"missing X-Hub-Signature-256";let u="sha256="+xr("sha256",a).update(t).digest("hex");return Yt(u,d)}if(n==="gitlab"){let d=c("x-gitlab-token");return d?Yt(a,d):"missing X-Gitlab-Token"}if(n==="stripe"){let d=c("stripe-signature");if(!d)return"missing Stripe-Signature";let u=Object.fromEntries(d.split(",").map(f=>f.split("=")));if(!u.t||!u.v1)return"malformed Stripe-Signature";let h=xr("sha256",a).update(`${u.t}.${t}`).digest("hex");return Yt(h,u.v1)}if(n==="hubspot"){let d=c("x-hubspot-signature-v3"),u=c("x-hubspot-request-timestamp");if(!d)return"missing X-HubSpot-Signature-v3";if(!u)return"missing X-HubSpot-Request-Timestamp";let h=parseInt(u,10);if(!Number.isFinite(h))return"malformed X-HubSpot-Request-Timestamp";let f=Date.now()-h;if(f>5*6e4)return`HubSpot webhook is ${Math.floor(f/1e3)}s old (>5min replay window)`;let y="POST",g=i||e["x-original-uri"]||e["x-forwarded-path"]||"",b=e["x-forwarded-host"],w=e.host,$=e["x-forwarded-proto"]||"https",v=new Set;b&&g&&v.add(`${$}://${b}${g}`),w&&g&&v.add(`https://${w}${g}`),w&&g&&v.add(`http://${w}${g}`),g&&v.add(g),v.add("");for(let x of v){let E=xr("sha256",a).update(`${y}${x}${t}${u}`).digest("base64");if(d.length===E.length&&$y(Buffer.from(d),Buffer.from(E)))return null}return`signature mismatch (tried ${v.size} URI variants)`}if(n==="odoo"){let d=c("x-odoo-signature");if(d){let h=xr("sha256",a).update(t).digest("hex"),f=d.startsWith("sha256=")?d.slice(7):d;return Yt(h,f)}let u=c("x-odoo-webhook-token")??c("x-webhook-secret");return u?Yt(a,u):"missing X-Odoo-Signature or X-Odoo-Webhook-Token"}let l=c("x-webhook-secret");return l?Yt(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 Yt(r,e){if(r.length!==e.length)return"signature mismatch";let t=Buffer.from(r),n=Buffer.from(e);return $y(t,n)?null:"signature mismatch"}nu();Pd();zd();SI();function uA(r){return{insertTaskHistory:r.prepare(`
|
|
@@ -642,7 +642,7 @@ ${o||"(empty)"}`}function lR(r){return(r??"").toLowerCase().split("@")[0]}functi
|
|
|
642
642
|
`)}var uw=35e3,Dr=class{constructor(e){this.deps=e;this.now=e.now??Date.now,this.budget=new _r(this.now)}budget;resuming=new Set;now;list(e={}){return this.deps.store.list({...e,now:this.now()})}windDownMs(){return uw+this.deps.settings().windDownSeconds*1e3+5e3}get(e){return this.deps.store.get(e)}async stop(e,t,n,s){let i=this.deps.findRunning(t);if(!i)return{ok:!1,status:404,error:"no running task matches (it may have finished already)"};let o;if(i.workflowRunId){let y=this.deps.workflowStep?.(i.workflowRunId,i.agentId)??{error:"the workflow engine is not running on this node"};if("error"in y)return{ok:!1,status:409,error:`this task is a step of workflow run ${i.workflowRunId}, which cannot pause here (${y.error}). Cancel the workflow run instead`};o={runId:i.workflowRunId,workflowId:y.workflowId,nodeId:y.nodeId}}let a=this.deps.settings(),c=Mr(e,{agentId:i.agentId,sender:i.sender},a);if(!c.ok)return{ok:!1,status:403,error:c.reason};let l=i.rootId||i.taskId;if(e.kind!=="owner"&&!this.budget.take(l,a.maxPerRoot))return{ok:!1,status:429,error:`this task's root already carried ${a.maxPerRoot} signals today (signals.maxPerRoot)`};let d=Qt(e),u=n?.trim().slice(0,500)||void 0,h={id:i.taskId,traceId:i.traceId,agentId:i.agentId,channel:i.channel,chatId:i.chatId,sender:i.sender,rootId:l,originalMessage:i.originalMessage,origin:i.origin,...o?{workflow:o}:{},...s?{stopAll:{orderId:s.orderId}}:{},stoppedAt:new Date(this.now()).toISOString(),stoppedBy:d,reason:u,state:"winding-down"};if(!this.deps.stopRun(i.taskId,`stopped by ${d}${u?`: ${u}`:""}`))return{ok:!1,status:404,error:"the task finished before it could be stopped"};this.save(h),this.deps.publish({type:"signal:stop",agentId:i.agentId,rootId:l,ref:i.taskId,summary:`stop sent to ${i.agentId} by ${d}${u?`: ${u}`:""}`}),this.deps.log(`[signals] ${i.agentId} task ${i.taskId} stopped by ${d}${u?` (${u})`:""}; winding down`);let f=this.windDown(h,a.windDownSeconds*1e3);return{ok:!0,record:h,done:f}}async stopAll(e,t){if(e.kind==="agent")return{ok:!1,status:403,error:"only the owner or a mesh peer may stop every task"};let n=this.deps.settings();if(!n.enabled)return{ok:!1,status:403,error:"signals are turned off on this node (signals.enabled)"};if(e.kind==="peer"&&!n.allowPeers.map(l=>l.toLowerCase()).includes(e.peer.toLowerCase()))return{ok:!1,status:403,error:`mesh peer "${e.peer}" is not in signals.allowPeers`};let s=`stop-all-${new Date(this.now()).toISOString().replace(/[^0-9]/g,"").slice(0,14)}`,i=t?.trim()?`stop-all: ${t.trim()}`:"stop-all",o=[],a=[];for(let l of this.deps.listRunning?.()??[]){let d=await this.stop(e,{taskId:l.taskId},i,{orderId:s});if(!d.ok){if(d.status===404)continue;o.push({id:l.taskId,agentId:l.agentId,state:"refused",error:d.error});continue}o.push({id:d.record.id,agentId:d.record.agentId,state:d.record.state}),d.done&&a.push(d.done.then(u=>({id:u.id,agentId:u.agentId,state:u.state,plan:u.plan?.author})))}this.deps.log(`[signals] stop-all ${s} by ${Qt(e)}: ${a.length} stopped, ${o.length-a.length} refused`),this.deps.publish({type:"signal:stop-all",agentId:"*",rootId:s,ref:s,summary:`stop-all by ${Qt(e)}: ${a.length} task(s) stopped`});let c=Promise.all(a).then(l=>o.map(d=>l.find(u=>u.id===d.id)??d));return{ok:!0,orderId:s,tasks:o,done:c}}stopAllOwner(e){return this.deps.store.list({limit:200,now:this.now()}).find(n=>n.stopAll&&(n.traceId===e||n.id===e))?.stopAll?.orderId??null}async resumeStopAll(e={}){let t=[],n=this.deps.store.list({state:"stopped",limit:200,now:this.now()}).filter(s=>s.stopAll).sort((s,i)=>s.stoppedAt.localeCompare(i.stoppedAt));for(let s of n){let i=s.stopAll;if(i.reported)continue;if(i.attemptedAt){this.save({...s,stopAll:{...i,reported:!0}}),t.push({id:s.id,agentId:s.agentId,decision:"skipped",reason:`already tried at ${i.attemptedAt}${i.error?`: ${i.error}`:""}`});continue}if(!s.origin&&!s.workflow){this.save({...s,stopAll:{...i,reported:!0}}),t.push({id:s.id,agentId:s.agentId,decision:"skipped",reason:"no record of how to re-enter it"});continue}t.some(c=>c.decision!=="skipped")&&e.staggerMs&&await new Promise(c=>setTimeout(c,e.staggerMs));let o=new Date(this.now()).toISOString();this.save({...s,stopAll:{...i,attemptedAt:o}});let a;try{a=await this.resume({kind:"owner",name:"stop-all restart"},s.id,`resumed after ${i.orderId}`)}catch(c){a={ok:!1,status:500,error:String(c?.message??c)}}if(a.ok)t.push({id:s.id,agentId:s.agentId,decision:"resumed",reason:`answer goes to ${a.delivery??"its origin"}`});else{let c=this.deps.store.get(s.id);c?.state==="stopped"&&this.save({...c,stopAll:{...i,attemptedAt:o,error:a.error.slice(0,300),reported:!0}}),t.push({id:s.id,agentId:s.agentId,decision:"resume-failed",reason:a.error})}}return t}async resume(e,t,n){let s=this.deps.store.get(t);if(!s)return{ok:!1,status:404,error:`no stopped task ${t}`};if(s.state==="winding-down")return{ok:!1,status:409,error:"the task is still writing its resume plan; try again in a moment"};if(s.state==="resumed"||this.resuming.has(t))return{ok:!1,status:409,error:"the task was already resumed"};if(!s.origin&&!s.workflow)return{ok:!1,status:409,error:"no record of how to re-enter this task"};if(s.workflow&&!this.deps.resumeWorkflowStep)return{ok:!1,status:409,error:`this task is a step of workflow run ${s.workflow.runId}, and the workflow engine is not running on this node`};let i=this.deps.settings(),o=Mr(e,{agentId:s.agentId,sender:s.sender},i);if(!o.ok)return{ok:!1,status:403,error:o.reason};if(e.kind!=="owner"&&!this.budget.take(s.rootId,i.maxPerRoot))return{ok:!1,status:429,error:`this task's root already carried ${i.maxPerRoot} signals today (signals.maxPerRoot)`};if(!this.deps.store.claim(t))return{ok:!1,status:409,error:"the task was already resumed"};let a=Qt(e),c=s.plan??Rt({toolCalls:this.deps.toolCalls(s.traceId),note:"no plan was saved"}),l=dw({stoppedAt:s.stoppedAt,stoppedBy:s.stoppedBy,reason:s.reason,plan:c,resumedBy:a});this.resuming.add(t);try{let d={...s,state:"resumed",resumedAt:new Date(this.now()).toISOString(),resumedBy:a};this.save(d),this.deps.publish({type:"signal:resume",agentId:s.agentId,rootId:s.rootId,ref:s.id,summary:`resume sent to ${s.agentId} by ${a}${n?`: ${n.trim().slice(0,200)}`:""}`});try{s.workflow?await this.deps.resumeWorkflowStep({record:d,note:l,by:a}):await this.deps.resume({record:d,note:l})}catch(h){this.save(s),this.deps.store.release(t);let f=`resume failed: ${h?.message??h}`;return this.deps.log(`[signals] ${s.agentId} task ${t}: ${f}`),this.deps.publish({type:"signal:resume-failed",agentId:s.agentId,rootId:s.rootId,ref:t,summary:f}),{ok:!1,status:500,error:f}}let u=yR(s.origin,s.workflow);return this.deps.log(`[signals] ${s.agentId} task ${t} resumed by ${a}; answer goes to ${u}`),{ok:!0,record:d,delivery:u}}finally{this.resuming.delete(t)}}drop(e,t){let n=this.deps.store.get(t);if(!n)return{ok:!1,status:404,error:`no stopped task ${t}`};if(n.state==="winding-down")return{ok:!1,status:409,error:"the task is still writing its resume plan; try again in a moment"};if(this.resuming.has(t))return{ok:!1,status:409,error:"the task is being resumed"};let s=Mr(e,{agentId:n.agentId,sender:n.sender},this.deps.settings());if(!s.ok)return{ok:!1,status:403,error:s.reason};if(!this.deps.store.remove(t))return{ok:!1,status:500,error:`couldn't remove ${t}`};let i=Qt(e);return this.deps.publish({type:"signal:dropped",agentId:n.agentId,rootId:n.rootId,ref:t,summary:`stopped task of ${n.agentId} dropped by ${i}`}),this.deps.log(`[signals] ${n.agentId} task ${t} dropped by ${i}`),{ok:!0,record:n}}recover(){let e=this.deps.store.dropStaleClaims();e&&this.deps.log(`[signals] removed ${e} resume claim(s) a restart left on tasks never resumed`);let t=0;for(let n of this.deps.store.list({state:"winding-down",limit:200,now:this.now()})){let s=Rt({toolCalls:this.deps.toolCalls(n.traceId),note:"a restart cut off the wind-down"});this.save({...n,state:"stopped",plan:s}),this.deps.log(`[signals] ${n.agentId} task ${n.id}: wind-down cut off by a restart; plan built from its trace`),t++}return t}async windDown(e,t){let n;try{await this.deps.whenRunEnds(e.id,uw);let i=this.deps.toolCalls(e.traceId),o=cw({by:e.stoppedBy,reason:e.reason,originalMessage:e.originalMessage,toolCalls:i}),a,c=new Promise(u=>{a=setTimeout(()=>u("timeout"),t+5e3),a.unref?.()}),l=await Promise.race([this.deps.windDown({id:e.id,agentId:e.agentId,rootId:e.rootId,message:o,timeoutMs:t}).catch(u=>({error:String(u?.message??u)})),c]);a&&clearTimeout(a);let d=Math.round(t/1e3);l==="timeout"||l.error&&/timed out/i.test(l.error)?n=Rt({toolCalls:i,note:`the agent wrote no plan within ${d}s`}):l.error?n=Rt({toolCalls:i,note:`the wind-down turn failed: ${l.error.slice(0,200)}`}):n=lw(l.content)??Rt({toolCalls:i,note:"the agent answered with an empty plan"})}catch(i){n=Rt({toolCalls:[],note:`wind-down failed: ${i?.message??i}`})}let s={...e,state:"stopped",plan:n};return this.save(s),this.deps.publish({type:"signal:stopped",agentId:e.agentId,rootId:e.rootId,ref:e.id,summary:`${e.agentId} stopped; resume plan ${n.author==="agent"?"written by the agent":`written by AgentX (${n.note})`}`}),this.deps.log(`[signals] ${e.agentId} task ${e.id}: resume plan saved (${n.author})`),!e.workflow&&e.origin&&e.origin.kind!=="direct"&&this.deps.tell&&await this.deps.tell(e.origin,`Paused: ${e.stoppedBy} stopped this task${e.reason?` (${e.reason})`:""}. Where it got to is saved, and it can be resumed later.`).catch(i=>this.deps.log(`[signals] couldn't tell the chat: ${i?.message??i}`)),s}save(e){try{this.deps.store.save(e)}catch(t){this.deps.log(`[signals] couldn't save ${e.id}: ${t?.message??t}`)}}};import{closeSync as wR,existsSync as qn,mkdirSync as gw,openSync as bR,readdirSync as pw,readFileSync as Cc,renameSync as kR,unlinkSync as Or,writeFileSync as vR}from"fs";import{resolve as Nr}from"path";var SR=7*24*60*60*1e3,$R=200,Lr=class{constructor(e){this.dir=e}file(e){return Nr(this.dir,`${e.replace(/[^A-Za-z0-9._-]/g,"_")}.json`)}save(e){qn(this.dir)||gw(this.dir,{recursive:!0});let t=this.file(e.id),n=`${t}.tmp`;vR(n,JSON.stringify(e,null,2),"utf-8"),kR(n,t)}get(e){try{let t=this.file(e);return qn(t)?JSON.parse(Cc(t,"utf-8")):null}catch{return null}}claim(e){try{return qn(this.dir)||gw(this.dir,{recursive:!0}),wR(bR(`${this.file(e)}.claim`,"wx")),!0}catch{return!1}}release(e){try{Or(`${this.file(e)}.claim`)}catch{}}remove(e){this.release(e);try{return Or(this.file(e)),!0}catch{return!1}}dropStaleClaims(){if(!qn(this.dir))return 0;let e=0;for(let t of pw(this.dir)){if(!t.endsWith(".json.claim"))continue;let n=Nr(this.dir,t),s;try{s=JSON.parse(Cc(n.slice(0,-6),"utf-8")).state}catch{}if(s!=="resumed")try{Or(n),e++}catch{}}return e}list(e={}){if(!qn(this.dir))return[];let t=e.now??Date.now(),n=[];for(let s of pw(this.dir)){if(!s.endsWith(".json"))continue;let i;try{i=JSON.parse(Cc(Nr(this.dir,s),"utf-8"))}catch{continue}if(i.state==="resumed"&&i.resumedAt&&t-Date.parse(i.resumedAt)>SR){try{Or(Nr(this.dir,s))}catch{}this.release(i.id);continue}e.state&&i.state!==e.state||e.agentId&&i.agentId!==e.agentId||n.push(i)}return n.sort((s,i)=>i.stoppedAt.localeCompare(s.stoppedAt)),n.slice(0,Math.min(e.limit??50,$R))}};function fw(r){let e=(t,n)=>{let s=t.replace(/\s+/g," ").trim();return s.length<=n?s:s.slice(0,n-1)+"\u2026"};return{id:r.id,agentId:r.agentId,channel:r.channel,chatId:r.chatId,rootId:r.rootId,state:r.state,stoppedAt:r.stoppedAt,stoppedBy:r.stoppedBy,reason:r.reason,request:e(r.originalMessage,200),plan:r.plan?{author:r.plan.author,text:r.plan.text.slice(0,1200),note:r.plan.note}:void 0,resumable:r.state==="stopped"&&(!!r.origin||!!r.workflow),...r.workflow?{workflow:r.workflow}:{},...r.stopAll?{stopAll:r.stopAll}:{},resumedAt:r.resumedAt,resumedBy:r.resumedBy}}var Xn="signals";function mw(r){if(r.proofGiven)return r.provenTurn?r.provenTurn.channel===Xn?{error:"a wind-down turn cannot send signals"}:{kind:"agent",agentId:r.provenTurn.agentId}:{error:"the running task named by the caller headers was not found"};if(r.via&&typeof r.via=="object"){let e=typeof r.via.node=="string"?r.via.node.trim():"",t=r.tokenPeer??e;if(!t)return{error:"a forwarded signal must name its node (via.node)"};let n=typeof r.via.agentId=="string"&&r.via.agentId.trim()?r.via.agentId.trim():void 0;return n?{kind:"agent",agentId:n,peer:t}:{kind:"peer",peer:t}}return r.tokenPeer?{kind:"peer",peer:r.tokenPeer}:{kind:"owner"}}function jr(r,e,t){let n=/^bearer /i.test(r??"")?r.slice(7).trim():"";if(!n||t&&n===t)return null;let s=[...new Set(e.filter(i=>i.token===n).map(i=>i.name))];return s.length===1?s[0]:null}var fe=r=>typeof r=="string"&&r.trim()?r.trim():void 0;function yw(r){return r==="/api/signals/stop"||r==="/api/signals/stop-all"||r==="/api/signals/resume"||r==="/api/signals/drop"||r==="/api/signals/stopped"||/^\/api\/signals\/stopped\/[^/]+$/.test(r)}async function ww(r,e,t,n,s){let i=fe(r==="GET"?t.get("node"):n.node);if(i&&i.toLowerCase()!==s.selfNode.toLowerCase()){if("error"in s.sender)return{status:403,body:{error:s.sender.error}};if(s.sender.kind!=="owner"&&s.sender.kind!=="agent")return{status:400,body:{error:"a forwarded signal cannot be forwarded again"}};if(s.sender.kind==="agent"&&s.sender.peer)return{status:400,body:{error:"a forwarded signal cannot be forwarded again"}};let a={node:s.selfNode,...s.sender.kind==="agent"?{agentId:s.sender.agentId}:{}},c=new URLSearchParams(t);c.delete("node");let l=r==="GET"?`${e}${c.toString()?`?${c}`:""}`:e,{node:d,...u}=n,h=e==="/api/signals/stop-all"&&n.wait===!0?s.service.windDownMs()+bw:void 0;return await s.forward(i,r==="GET"?"GET":"POST",l,r==="GET"?void 0:{...u,via:a},h)??{status:404,body:{error:`no healthy mesh peer named "${i}"`}}}if(r==="GET"&&e==="/api/signals/stopped"){let a=fe(t.get("state")),c=Number(t.get("limit")??"")||void 0,l=s.service.list({state:a==="stopped"||a==="resumed"||a==="winding-down"?a:void 0,agentId:fe(t.get("agent")),limit:c});return{status:200,body:{node:s.selfNode,tasks:l.map(fw)}}}let o=r==="GET"&&e.match(/^\/api\/signals\/stopped\/([^/]+)$/);if(o){let a=s.service.get(decodeURIComponent(o[1]));return a?{status:200,body:{node:s.selfNode,task:a}}:{status:404,body:{error:"no such stopped task"}}}if(r!=="POST")return{status:405,body:{error:"method not allowed"}};if("error"in s.sender)return{status:403,body:{error:s.sender.error}};if(e==="/api/signals/stop"){let a=fe(n.taskId),c=fe(n.agentId),l=fe(n.channel),d=fe(n.chatId);if(!a&&!(c&&l&&d))return{status:400,body:{error:"send { taskId } or { agentId, channel, chatId }"}};let u=await s.service.stop(s.sender,{taskId:a,agentId:c,channel:l,chatId:d},fe(n.reason));return u.ok?{status:202,body:{ok:!0,node:s.selfNode,id:u.record.id,agentId:u.record.agentId,rootId:u.record.rootId,state:u.record.state,message:"Stopped. The agent is writing its resume plan; GET /api/signals/stopped/<id> shows it once saved."}}:{status:u.status,body:{error:u.error}}}if(e==="/api/signals/stop-all")return IR(n,s);if(e==="/api/signals/resume"){let a=fe(n.id);if(!a)return{status:400,body:{error:"send { id } of a stopped task"}};let c=await s.service.resume(s.sender,a,fe(n.reason));return c.ok?{status:200,body:{ok:!0,node:s.selfNode,id:c.record.id,agentId:c.record.agentId,rootId:c.record.rootId,state:c.record.state,delivery:c.delivery}}:{status:c.status,body:{error:c.error}}}if(e==="/api/signals/drop"){let a=fe(n.id);if(!a)return{status:400,body:{error:"send { id } of a stopped task"}};let c=s.service.drop(s.sender,a);return c.ok?{status:200,body:{ok:!0,node:s.selfNode,id:c.record.id,agentId:c.record.agentId,rootId:c.record.rootId,dropped:!0}}:{status:c.status,body:{error:c.error}}}return{status:404,body:{error:"not found"}}}var bw=9e4;async function IR(r,e){let t=e.sender,n=r.wait===!0,s=fe(r.reason),i=await e.service.stopAll(t,s);if(!i.ok)return{status:i.status,body:{error:i.error}};let o=r.mesh===!0&&t.kind==="owner",a=e.service.windDownMs()+bw,c=o?Promise.all((e.peers?.()??[]).map(async y=>{try{let g=await e.forward(y,"POST","/api/signals/stop-all",{reason:s,wait:n,via:{node:e.selfNode}},n?a:void 0);return g?g.status>=400?{node:y,ok:!1,error:String(g.body.error??`HTTP ${g.status}`)}:{node:y,ok:!0,...g.body}:{node:y,ok:!1,error:"not reachable"}}catch(g){return{node:y,ok:!1,error:/abort|timeout/i.test(String(g?.name??g))?"no answer in time; its plans may still be saving":String(g?.message??g)}}})):Promise.resolve(void 0),l=n?await i.done:i.tasks,d=await c,u=l.every(y=>y.state!=="winding-down"&&y.state!=="refused"),h=l.filter(y=>y.state==="refused").map(y=>y.id),f=!d||d.every(y=>y.ok&&y.safeToRestart===!0);return{status:n?200:202,body:{ok:!0,node:e.selfNode,orderId:i.orderId,tasks:l,...d?{peers:d}:{},...n?{safeToRestart:u&&f}:{},message:n?u&&f?"Every task stopped and its plan is saved. Safe to restart; each task resumes from its plan on start.":h.length?`Not safe to restart: ${h.join(", ")} could not be stopped and is still running; see tasks and peers.`:"Not every plan is confirmed saved; see tasks and peers.":"Stopping. Each agent is writing its resume plan; GET /api/signals/stopped shows them once saved."}}}function TR(r,e){let t=e.filter(n=>n.healthy);if(r.node){let n=r.node.toLowerCase(),s=t.find(i=>i.node?.toLowerCase()===n||i.peer.toLowerCase()===n);if(s)return s}return t.find(n=>n.channels.includes(r.channel))??null}function kw(r){let e=n=>{let s=TR(n,r.peers());if(!s)throw new Error(`no healthy mesh peer can deliver to "${n.channel}"`);return s},t=(n,s)=>({channel:n.channel,chatId:n.chatId,text:s,replyTo:n.replyTo,accountId:n.accountId,agentId:n.agentId});return{resume:async({origin:n,note:s,attempt:i,run:o})=>{if(n.kind!=="mesh")throw new Error("not a mesh run");e(n),r.execute({agentId:o.agentId,message:`${s}
|
|
643
643
|
${o.originalMessage??""}`,origin:n,attempt:i,resumedFrom:o.taskId}).then(async a=>{if(a.error||!a.content){r.log(`[resume] ${o.taskId} finished without an answer: ${a.error??"empty"}`);return}await r.send(e(n),t(n,a.content))}).catch(a=>r.log(`[resume] ${o.taskId} failed: ${a?.message??a}`))},tell:async(n,s)=>{n.kind==="mesh"&&await r.send(e(n),t(n,s))}}}function vw(r,e){let t=r.replyVia,n=r.context;if(!t||typeof t!="object"||!n||typeof n.channel!="string"||typeof n.chatId!="string")return;let s=i=>typeof i=="string"&&i?i:void 0;return{kind:"mesh",node:s(t.node),channel:n.channel,chatId:n.chatId,agentId:e,replyTo:s(t.messageId),accountId:s(t.accountId),context:n}}function Sw(r,e){return!e||r.errorKind!=="interrupted"?r:{...r,error:rh("resuming",1)}}var $w=100,xR="Decisions are made by the operator only: `agentx approvals approve|reject <key>`, or the Approvals page in the dashboard.";function Iw(r,e,t,n,s){let i=r.toUpperCase();if(e==="/approvals"){if(i==="GET"){let c=Gp(s.ctx,{includeSnoozed:n.get("all")==="1"});return{status:200,body:{count:c.items.length,snoozed:c.snoozed,items:c.items.slice(0,$w),truncated:c.items.length>$w,errors:c.errors}}}if(i==="POST"){let c=t??{},l=typeof c.raised_by=="string"?c.raised_by.trim():"",d=typeof c.node=="string"?c.node.trim():"",u=d&&s.hasPeer?.(d)&&(!s.hasAgent(l)||s.tokenPeerIs?.(d))?d:void 0;if(l&&!s.hasAgent(l)&&!u)return{status:400,body:{error:d?`unknown node "${d}": node must be one of this node's mesh peers`:`unknown agent "${l}": raised_by must be an agent on this node`}};let h=Me(s.ctx.root,c,{now:s.ctx.now,settings:s.settings,node:u});return h.ok?{status:201,body:{card:h.card}}:{status:400,body:{error:h.error}}}return{status:405,body:{error:"Method not allowed"}}}if(e==="/approvals/checkin"&&i==="POST"){if(!s.runCheckin)return{status:503,body:{error:"check-ins need macOS"}};let c=t?.daily===!0?"daily":"check";return s.runCheckin(c),{status:202,body:{started:c}}}let o=e.match(/^\/approvals\/([^/]+)\/resolve$/);if(o&&i==="POST"){let c=decodeURIComponent(o[1]),l=typeof t?.raised_by=="string"&&t.raised_by.trim()?t.raised_by.trim():void 0,d=typeof t?.node=="string"&&t.node.trim()?t.node.trim():void 0,u,h;if(d){if(!s.tokenPeerIs?.(d))return{status:403,body:{error:`closing a card in the name of node "${d}" needs that peer's own mesh token`}};if(!l)return{status:400,body:{error:"raised_by must be the agent that raised the card"}};u=l,h=d}else{let y=s.provenAgent?.(l)??null;if(!y)return{status:403,body:{error:"only the agent that raised the card can close it, from one of its running turns (X-AgentX-Task, or X-AgentX-Channel and X-AgentX-Chat)"}};if(l&&l!==y)return{status:403,body:{error:`the calling turn is ${y}'s, not ${l}'s`}};u=y}if(typeof t?.reason!="string"||!t.reason.trim())return{status:400,body:{error:"reason is required: say where the owner answered and what you did"}};let f=Rp(s.ctx.root,c,{by:u,reason:t.reason,node:h,now:s.ctx.now});return f.ok?{status:200,body:{card:f.card}}:{status:f.status,body:{error:f.error}}}let a=e.match(/^\/approvals\/([^/]+)$/);if(a&&i==="GET"){let c=decodeURIComponent(a[1]),l=Hs(c)?wt(s.ctx.root,c):null;return l?{status:200,body:{card:l}}:{status:404,body:{error:`no card "${c}"`}}}return i!=="GET"&&i!=="HEAD"?{status:403,body:{error:xR}}:{status:404,body:{error:"Not found"}}}var AR="Only the owner publishes: `agentx approvals approve content:<id>`, or the Approvals page in the dashboard.",Tw=r=>typeof r=="string"?r.trim():"";function xw(r,e,t,n,s){let i=r.toUpperCase(),o=c=>{let l=Tw(c);if(!l)return{status:400,body:{error:"agent is required: your agent id"}};let d=s.workspaceOf(l);return d?{agent:l,workspace:d}:{status:400,body:{error:`unknown agent "${l}": it must be an agent on this node`}}};if(e==="/content/drafts"&&i==="POST"){let c=o(t?.agent);if("status"in c)return c;let l=qg(s.root,{...c,platform:t?.platform,text:t?.text,samples:t?.samples,topic:t?.topic,date:t?.date},s.now);return l.ok?{status:201,body:{draft:l.draft}}:{status:400,body:{error:l.error}}}let a=e.match(/^\/content\/drafts\/([^/]+)$/);if(a&&i==="GET"){let c=decodeURIComponent(a[1]),l=Bg(c)?Xg(s.root,c):null;if(!l)return{status:404,body:{error:`no content draft "${c}"`}};let d=Tw(n.get("agent"));return d&&l.agent!==d?{status:403,body:{error:`draft "${c}" was raised by another agent`}}:{status:200,body:{draft:l}}}if(e==="/content/voice"&&i==="GET"){let c=o(n.get("agent"));if("status"in c)return c;let l=Math.min(10,Math.max(1,Number(n.get("n"))||3));return{status:200,body:{total:Gg(c.workspace).length,samples:Hg(c.workspace,n.get("topic")??"",l)}}}if(e==="/content/calendar"&&i==="GET"){let c=o(n.get("agent"));if("status"in c)return c;let l=Wg(c.workspace);return l?{status:200,body:{exists:!0,entries:Ug(l,new Date(s.now??Date.now()),14)}}:{status:200,body:{exists:!1,entries:[]}}}return i!=="GET"&&i!=="HEAD"?{status:403,body:{error:AR}}:{status:404,body:{error:"Not found"}}}function tt(r,e){let t=new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(new Date(r)),n=i=>t.find(o=>o.type===i)?.value??"00",s=Number(n("hour"))%24;return{date:`${n("year")}-${n("month")}-${n("day")}`,minutes:s*60+Number(n("minute"))}}function Pc(r,e,t){let{date:n,minutes:s}=tt(t,r.timezone),[i,o]=r.time.split(":").map(Number);return{due:e!==n&&s>=i*60+o,date:n}}function RR(r,e,t){let n=r.items[0],s=r.later?` (and ${r.later} you put off for later)`:"",i=r.count||r.later||!t?[`${r.count} waiting for you on the Desk${s}.`]:[];if(n){let o=n.expires?` Expires ${n.expires.slice(0,16).replace("T"," ")} UTC${n.ifSilent?`, then: ${n.ifSilent}`:""}.`:"",a=n.ask??n.need;i.push(`Most urgent: ${n.title}${a?`: ${a}`:""}${o}`)}return t&&i.push(t),i.push(e?`Open ${e.replace(/\/$/,"")}/approvals, or run: agentx approvals list`:"Open Approvals in the dashboard, or run: agentx approvals list"),i.join(`
|
|
644
644
|
`)}var ER=24*36e5;async function CR(r,e,t){let{ctx:n,settings:s,log:i}=e,o=()=>{$a(n.root,r.id,t);try{e.onCardResult?.(r)}catch(a){i(`[approvals] ${r.id}: result listener failed: ${a?.message??a}`)}};if(!s.notifyAgent||!e.tellPeer)return o(),!1;try{return await e.tellPeer(r.node,r),o(),!0}catch(a){let c=Date.parse(r.decided_at??r.created_at),l=Number.isFinite(c)&&t-c>ER;return i(`[approvals] couldn't send ${r.id}'s result to ${r.node} for ${r.raised_by}: ${a?.message??a}${l?"; giving up":"; will retry"}`),l&&o(),!1}}async function Aw(r){let{ctx:e,settings:t,log:n}=r,s=e.now??Date.now(),i={expired:0,notified:0,digest:"not-due"};try{for(let o of Ep(e.root,s))i.expired++,n(`[approvals] ${o.id} from ${o.raised_by} expired; default applied: ${o.if_silent}`)}catch(o){n(`[approvals] expiry failed: ${o?.message??o}`)}try{for(let o of Cp(e.root)){if(o.node){await CR(o,r,s)&&i.notified++;continue}$a(e.root,o.id,s);try{r.onCardResult?.(o)}catch(a){n(`[approvals] ${o.id}: result listener failed: ${a?.message??a}`)}if(o.origin?.kind!=="workflow"&&o.origin?.kind!=="plan-step"&&o.origin?.kind!=="merge-policy"&&!(!t.notifyAgent||!r.tellAgent)){if(r.hasAgent&&!r.hasAgent(o.raised_by)){n(`[approvals] ${o.id}: agent "${o.raised_by}" isn't on this node; result not delivered`);continue}try{await r.tellAgent(o.raised_by,Bs(o),o),i.notified++}catch(a){n(`[approvals] couldn't tell ${o.raised_by} about ${o.id}: ${a?.message??a}`)}}}}catch(o){n(`[approvals] agent notices failed: ${o?.message??o}`)}try{if(!t.digest.enabled)return i.digest="disabled",i;let{due:o,date:a}=Pc(t.digest,Np(e.root).lastDigest,s);if(!o)return i;let c=t.digest.destination??r.fallbackDestination;if(!c||!r.sendDigest)return i.digest="no-destination",i;let l=qs(e,r.node??{url:"",name:"this computer"}),d=null;try{d=r.nags?.line()??null}catch(u){n(`[approvals] digest: nags not read: ${u?.message??u}`)}if(l.count===0&&l.later===0&&!d)return i.digest="empty",i;Lp(e.root,a);try{await r.sendDigest(c,RR(l,r.dashboardUrl,d?.line)),d&&r.nags.done(d.ids),i.digest="sent",n(`[approvals] digest sent: ${l.count} waiting, ${l.later} later${d?`, ${d.ids.length} nags`:""}`)}catch(u){i.digest="failed",n(`[approvals] digest failed: ${u?.message??u}`)}}catch(o){i.digest="failed",n(`[approvals] digest failed: ${o?.message??o}`)}return i}import{existsSync as PR,mkdirSync as _R,readFileSync as MR,writeFileSync as DR}from"fs";import{dirname as OR,resolve as NR}from"path";var LR=7*24*36e5,Rw=24*36e5,jR=5*6e4,FR=6e4,_c=10,WR=3e3;function UR(r,e,t,n){let s=null,i=new Date(t);try{for(let o=0;o<WR;o++){let a=Zh(r,i,e);if(a.getTime()>n)break;s=a,i=a}}catch{return s}return s}function GR(r){return(r.command?.trim()?r.timeout:Qh(r.timeout))*1e3+jR}async function HR(r,e){if(r.length===0)return[];let t=await $r({perJob:1,runsDir:e.runsDir,jobIds:r.map(s=>s.id)}),n=[];for(let s of r){let i=t.get(s.id)?.[0],o=i?Date.parse(i.startedAt):NaN;if(i&&i.status!=="success"&&o>=e.since){let c=i.errorSummary?.split(`
|
|
645
|
-
`)[0]?.slice(0,160)||(i.status==="timeout"?"timed out":"failed");n.push({jobId:s.id,agent:s.agent,kind:"failed",at:i.startedAt,detail:`${i.status==="timeout"?"timed out":"failed"}: ${c}${s.enabled?"":" (now switched off)"}`});continue}if(!s.enabled||!i)continue;let a=UR(s.schedule,s.timezone,e.since,e.now-GR(s));a&&o<a.getTime()-FR&&n.push({jobId:s.id,agent:s.agent,kind:"missed",at:a.toISOString(),detail:"did not run"})}return n.sort((s,i)=>s.at.localeCompare(i.at)||s.jobId.localeCompare(i.jobId))}function BR(r,e,t){let n=[];for(let s of r){let i=Pg(s,e,t);if(!i)continue;let o=(s.headline??s.text).replace(/\s+/g," ").trim();n.push({id:s.id,agentId:s.agentId,title:o.length>80?`${o.slice(0,79)}\u2026`:o,why:i,updatedAt:s.updatedAt})}return n.sort((s,i)=>s.updatedAt-i.updatedAt).map(({updatedAt:s,...i})=>i)}function qR(r){let e=n=>`$${n.toFixed(2)}`,t=[];r.fleet.state==="paused"&&r.fleet.capUsd&&t.push({agentId:"every agent",why:`fleet budget used (${e(r.fleet.spentUsd)} of ${e(r.fleet.capUsd)})`});for(let n of r.agents)n.state!=="paused"||!n.capUsd||t.push({agentId:n.agentId,why:`monthly budget used (${e(n.spentUsd)} of ${e(n.capUsd)})`});return t}function XR(r){return r.schedules.length===0&&r.requests.length===0&&r.agents.length===0}function Mc(r,e,t){if(e.length===0)return[];let n=[`${r} (${e.length})`,...e.slice(0,_c).map(s=>`- ${t(s)}`)];return e.length>_c&&n.push(`- and ${e.length-_c} more`),n}function VR(r,e={}){if(XR(r))return null;let t=[`Needs a look${e.node?` on ${e.node}`:""}:`];return t.push(...Mc("Schedules",r.schedules,n=>n.kind==="missed"?`${n.jobId} (${n.agent}): due ${Rn(Date.parse(n.at))}, did not run`:`${n.jobId} (${n.agent}): ${Rn(Date.parse(n.at))}, ${n.detail}`)),t.push(...Mc("Stuck requests",r.requests,n=>`${n.title} (${n.agentId}): ${n.why}`)),t.push(...Mc("Paused agents",r.agents,n=>`${n.agentId}: ${n.why}`)),t.push(e.dashboardUrl?`Details: ${e.dashboardUrl.replace(/\/$/,"")} (Operations), or run: agentx schedule list`:"Details: Operations in the dashboard, or run: agentx schedule list"),t.join(`
|
|
645
|
+
`)[0]?.slice(0,160)||(i.status==="timeout"?"timed out":"failed");n.push({jobId:s.id,agent:s.agent,kind:"failed",at:i.startedAt,detail:`${i.status==="timeout"?"timed out":"failed"}: ${c}${s.enabled?"":" (now switched off)"}`});continue}if(!s.enabled||!i)continue;let a=UR(s.schedule,s.timezone,e.since,e.now-GR(s));a&&o<a.getTime()-FR&&n.push({jobId:s.id,agent:s.agent,kind:"missed",at:a.toISOString(),detail:"did not run"})}return n.sort((s,i)=>s.at.localeCompare(i.at)||s.jobId.localeCompare(i.jobId))}function BR(r,e,t){let n=[];for(let s of r){let i=Pg(s,e,t);if(!i)continue;let o=(s.headline??s.text).replace(/\s+/g," ").trim();n.push({id:s.id,agentId:s.agentId,title:o.length>80?`${o.slice(0,79)}\u2026`:o,why:i,updatedAt:s.updatedAt})}return n.sort((s,i)=>s.updatedAt-i.updatedAt).map(({updatedAt:s,...i})=>i)}function qR(r){let e=n=>`$${n.toFixed(2)}`,t=[];r.fleet.state==="paused"&&r.fleet.capUsd&&t.push({agentId:"every agent",why:`fleet budget used (${e(r.fleet.spentUsd)} of ${e(r.fleet.capUsd)})`});for(let n of r.projects??[])n.state!=="paused"||!n.capUsd||t.push({agentId:`project ${n.name}`,why:`project budget used (${e(n.spentUsd)} of ${e(n.capUsd)})`});for(let n of r.agents)n.state!=="paused"||!n.capUsd||t.push({agentId:n.agentId,why:`monthly budget used (${e(n.spentUsd)} of ${e(n.capUsd)})`});return t}function XR(r){return r.schedules.length===0&&r.requests.length===0&&r.agents.length===0}function Mc(r,e,t){if(e.length===0)return[];let n=[`${r} (${e.length})`,...e.slice(0,_c).map(s=>`- ${t(s)}`)];return e.length>_c&&n.push(`- and ${e.length-_c} more`),n}function VR(r,e={}){if(XR(r))return null;let t=[`Needs a look${e.node?` on ${e.node}`:""}:`];return t.push(...Mc("Schedules",r.schedules,n=>n.kind==="missed"?`${n.jobId} (${n.agent}): due ${Rn(Date.parse(n.at))}, did not run`:`${n.jobId} (${n.agent}): ${Rn(Date.parse(n.at))}, ${n.detail}`)),t.push(...Mc("Stuck requests",r.requests,n=>`${n.title} (${n.agentId}): ${n.why}`)),t.push(...Mc("Paused agents",r.agents,n=>`${n.agentId}: ${n.why}`)),t.push(e.dashboardUrl?`Details: ${e.dashboardUrl.replace(/\/$/,"")} (Operations), or run: agentx schedule list`:"Details: Operations in the dashboard, or run: agentx schedule list"),t.join(`
|
|
646
646
|
`)}function JR(r){return NR(r,".agentx/cron/exceptions-digest.json")}function KR(r){try{if(!PR(r))return{};let e=JSON.parse(MR(r,"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}function zR(r,e){_R(OR(r),{recursive:!0}),DR(r,JSON.stringify(e,null,2))}function YR(r,e){let t=r?Date.parse(r):NaN,n=Number.isFinite(t)?Math.min(t,e-Rw):e-Rw;return Math.max(n,e-LR)}async function QR(r,e,t){let n={schedules:[],requests:[],agents:[]};try{n.schedules=await HR(r.jobs(),{since:e,now:t,runsDir:r.runsDir})}catch(s){r.log(`[exceptions] schedules not read: ${s?.message??s}`)}try{let s=r.requests?.();s&&(n.requests=BR(s.items,s.staleAfterHours,t))}catch(s){r.log(`[exceptions] requests not read: ${s?.message??s}`)}try{let s=r.budget?.();s&&(n.agents=qR(s))}catch(s){r.log(`[exceptions] budgets not read: ${s?.message??s}`)}return n}async function Ew(r){let{settings:e,log:t}=r;if(!e.enabled)return"disabled";let n=r.now??Date.now(),s=JR(r.root),i=KR(s),{due:o,date:a}=Pc(e,i.lastDigest,n);if(!o)return"not-due";let c=e.destination??r.fallbackDestination;if(!c)return"no-destination";let l=await QR(r,YR(i.checkedAt,n),n);zR(s,{lastDigest:a,checkedAt:new Date(n).toISOString()});let d=VR(l,{node:r.node,dashboardUrl:r.dashboardUrl});if(!d)return t("[exceptions] digest: nothing wrong, nothing sent"),"empty";try{return await r.send(c,d),t(`[exceptions] digest sent: ${l.schedules.length} schedule(s), ${l.requests.length} request(s), ${l.agents.length} agent(s)`),"sent"}catch(u){return t(`[exceptions] digest failed: ${u?.message??u}`),"failed"}}import{execFile as ZR}from"child_process";import{mkdirSync as _w,readFileSync as Ur,readdirSync as eE,renameSync as tE,writeFileSync as Mw}from"fs";import{dirname as Dw,resolve as Zt}from"path";var Et=864e5,Ow=36e5;function Fr(r){let e=new Date(`${r}T00:00:00Z`),t=(e.getUTCDay()+6)%7,n=new Date(e.getTime()+(3-t)*Et),s=n.getUTCFullYear(),i=new Date(Date.UTC(s,0,4)),o=i.getTime()-(i.getUTCDay()+6)%7*Et,a=Math.floor((n.getTime()-o)/(7*Et))+1;return`${s}-W${String(a).padStart(2,"0")}`}function nt(r){let e=/^(\d{4})-W(\d{2})$/.exec(r);if(!e)throw new Error(`not an ISO week: ${r}`);let t=new Date(Date.UTC(Number(e[1]),0,4)),n=t.getTime()-(t.getUTCDay()+6)%7*Et+(Number(e[2])-1)*7*Et,s=i=>new Date(i).toISOString().slice(0,10);return{from:s(n),to:s(n+6*Et)}}function Wr(r,e){return new Date(Date.parse(`${r}T00:00:00Z`)+e*Et).toISOString().slice(0,10)}function Nw(r,e){let t=[],n=Wr(nt(r).from,7),s=nt(e).from;for(;n<s&&t.length<520;)t.push(Fr(n)),n=Wr(n,7);return t}function nE(r,e,t){let{date:n,minutes:s}=tt(t,r.timezone),i=Fr(Wr(n,-7)),[o,a]=r.time.split(":").map(Number),l=!(nt(Fr(n)).from===n)||s>=o*60+a,d=e.lastPosted===i,u=e.failure?.week===i&&t-Date.parse(e.failure.at)<Ow,h=e.lastPosted&&e.lastPosted<i?Nw(e.lastPosted,i):[];return{due:l&&!d&&!u,week:i,skipped:h}}function sE(r,e){let{from:t,to:n}=nt(e);return r.since>n?"off":r.until&&r.until<t?`off since ${r.until}`:r.until&&r.until<=n?`on ${r.since}, off ${r.until}`:r.since>=t?`on from ${r.since}`:`on (since ${r.since})`}function X2(r,e,t){let n=r.map(i=>i.since).sort()[0];if(!n)return[];let s=Fr(n);return s>t?[]:[s,...Nw(s,t),...s<t?[t]:[]].filter(i=>!e.comments?.[i])}function rE(r){let e=r.map(t=>t.since).sort()[0];return e?Wr(e,20):void 0}var iE=/[$€£¥]\s?\d|\d\s?(?:USD|EUR|GBP|usd|eur|gbp|dollars?|euros?)\b/,oE=/(^|[^\w`/.-])@[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\b/m,aE=/[\w.+-]+@[\w-]+\.[\w.]+/;function cE(r){let e=iE.exec(r);if(e)return`contains a cost amount ("${e[0]}"); the public report gives cost as a percentage change only`;if(aE.test(r))return"contains an email address";let t=oE.exec(r);if(t)return`contains a name ("${t[0].trim()}")`}var Lw=r=>`<!-- agentx:quality-report week=${r} -->`,lE="<!-- agentx:quality-verdict -->";function jw(r){let e=Math.max(0,...(r.match(/`+/g)??[]).map(n=>n.length)),t="`".repeat(Math.max(3,e+1));return`${t}text
|
|
647
647
|
${r.replace(/^\n+|\s+$/g,"")}
|
|
648
648
|
${t}`}function dE(r){let{from:e,to:t}=nt(r.week),n=[Lw(r.week),`## Quality report, ${r.week} (${e} to ${t})`,""];if(n.push("### Gates this week",""),!r.gates.length)n.push("No gates were on. This week counts as baseline.","");else{n.push("| Gate | State |","|---|---|");for(let s of r.gates)n.push(`| ${s.label??s.id} | ${sE(s,r.week)} |`);n.push("")}return n.push("### Numbers","",jw(r.report),""),r.failed?.length&&n.push(`> No report was posted for ${r.failed.join(", ")}: every try failed (see \`[quality]\` in the daemon log). Run \`agentx quality weekly --week <week>\` to post one.`,""),r.skipped?.length&&n.push(`> No report was posted for ${r.skipped.join(", ")}: the daemon was not running when it was due. Run \`agentx quality weekly --week <week>\` to post one.`,""),r.verdictDue&&n.push("> Week 3 with the gates on is over. The keep / tune / switch-off verdict per gate is due: `agentx quality verdict`.",""),n.push("_Posted by the AgentX daemon every Monday. Cost is shown as a percentage change only._"),n.join(`
|
|
@@ -1322,4 +1322,4 @@ data: ${JSON.stringify(K)}
|
|
|
1322
1322
|
`)}catch{}},L=setInterval(()=>{try{t.write(`: ping
|
|
1323
1323
|
|
|
1324
1324
|
`)}catch{}},15e3);L.unref?.();let H=new AbortController;t.on("close",()=>{t.writableEnded||H.abort()});try{for await(let W of this.mesh.sendTaskStream(p.peer,p.message,p.agent,{context:p.context,signal:H.signal,vouchOwner:S}))C(W.event,W.data)}catch(W){C("error",{error:W?.message??String(W)})}finally{clearInterval(L);try{t.end()}catch{}}break}let D=p.context,M=typeof p.senderAgentId=="string"?p.senderAgentId:void 0;if(d$(p,!0)==="callback"){let C=this.delegationGate(e,p,{callee:p.agent,peer:p.peer,message:p.message,calleeContext:D});if(!("track"in C)){let L=oo(C);this.json(t,L.status,L.body);break}}if(p.async===!0){let C=D?.channel,L=D?.chatId;if(!C||!L){this.json(t,400,{error:"async requires context.channel and context.chatId \u2014 there is no route back otherwise"});return}let H=`mesh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;this.json(t,202,{accepted:!0,taskId:H,deliverTo:`${C}:${L}`,note:"result will be delivered to the originating chat when the peer finishes"});let W=p.peer,K=p.agent,he=this.mesh;(async()=>{let X=Date.now(),z;try{z=await he.sendTask(W,p.message,K,{vouchOwner:S,context:D,senderAgentId:M}),this.log(`[mesh/task async ${H}] ${W}/${K??"default"} finished in ${Date.now()-X}ms`)}catch(Y){z=`Delegation to ${W}/${K??"default"} failed: ${Y?.message??Y}`,this.log(`[mesh/task async ${H}] failed: ${Y?.message??Y}`)}try{await this.router.sendOutbound({channel:C,chatId:L,text:z,agentId:D?.agentId??M,accountId:D?.accountId})}catch(Y){this.log(`[mesh/task async ${H}] delivery failed: ${Y?.message??Y}`)}})();break}let N=await this.mesh.sendTask(p.peer,p.message,p.agent,{context:D,senderAgentId:M,vouchOwner:S});this.json(t,200,{response:N});break}case"POST /webrtc/signal/out":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let m=await U(e);if(!m.kind||!m.callId||!m.from||!m.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let k=await this.webrtc.handleOutgoing(m);this.json(t,k.ok?200:400,k);break}case"POST /webrtc/signal":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let m=await U(e);if(!m.kind||!m.callId||!m.from||!m.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let k=this.webrtc.handleIncoming(m);this.json(t,k.ok?200:400,k);break}case"POST /webrtc/bot/invite":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled (channels.webrtc.bot.enabled=false)"});return}let p=await U(e),m=p.callId,k=p.target,S=p.agentId||this.config.channels.webrtc?.bot.defaultAgentId;if(!m||!k||!S){this.json(t,400,{error:"Missing: callId, target, agentId (or defaultAgentId in config)"});return}let I=await this.botManager.invite({callId:m,target:k,agentId:S});this.json(t,I.ok?200:500,I);break}case"GET /webrtc/bots":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active()});break}case"GET /webrtc/history":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active(),history:this.botManager.history()});break}case"GET /webrtc/config":{let p=this.config.channels.webrtc;if(!p?.enabled){this.json(t,404,{error:"WebRTC signaling not enabled"});return}this.json(t,200,{localName:this.config.node.name,iceServers:[...p.stunServers.map(m=>({urls:m})),...p.turnServers],peers:this.mesh?.directory().map(m=>({name:m.peer,healthy:m.healthy}))||[],camera:p.camera,agents:this.registry.list().map(m=>({id:m.id,name:m.name}))});break}case"GET /.well-known/agent-card.json":this.json(t,200,{name:this.config.node.name,description:`AgentX daemon node "${this.config.node.name}"`,url:`http://${this.config.node.bind}`,version:"1.0.0",capabilities:{streaming:!1,pushNotifications:!1,stateTransitionHistory:!1},skills:this.registry.list().map(p=>{let m=this.config.agents[p.id]||{},k=typeof m.description=="string"&&m.description.trim()||RN(m.systemPrompt)||`Agent "${p.name}" (${p.tier})`,S=Array.isArray(m.mentions)?m.mentions.slice(0,4):[];return{id:p.id,name:p.name,description:k,tags:[p.tier,...S],color:be(p.id,m).color}}),channels:this.router.getChannelNames(),githubLogins:this.github?.postingAccounts()??[],defaultInputModes:["text"],defaultOutputModes:["text"]});break;case"GET /wiki/agents":{let p=this.registry.getWikiHub();this.json(t,200,{nodeId:this.config.node.id,agents:p.summary()});break}case"GET /wiki/entries":{let p=this.registry.getWikiHub(),m=n.searchParams.get("agent")||void 0,k=n.searchParams.get("after")||void 0,S=m?p.getAgentEntries(m):p.getSharedStore().listEntries({after:k});this.json(t,200,{nodeId:this.config.node.id,count:S.length,entries:S.map(I=>({id:I.id,date:I.date,agentId:I.agentId,source:I.source,sourceContext:I.sourceContext,content:I.content}))});break}case"GET /wiki/articles":{let p=this.registry.getWikiHub(),m=n.searchParams.get("agent");if(!m){this.json(t,400,{error:"?agent= required"});break}let S=p.getAgentWiki(m).rebuildIndex();this.json(t,200,{nodeId:this.config.node.id,agentId:m,articles:S.articles});break}case"GET /wiki/article":{let p=this.registry.getWikiHub(),m=n.searchParams.get("agent"),k=n.searchParams.get("path");if(!m||!k){this.json(t,400,{error:"?agent= and ?path= required"});break}let I=p.getAgentWiki(m).readArticle(k);if(!I){this.json(t,404,{error:"Article not found"});break}this.json(t,200,{nodeId:this.config.node.id,agentId:m,path:I.path,title:I.meta.title,tags:I.meta.tags,owner:I.meta.owner,created:I.meta.created,lastUpdated:I.meta.lastUpdated,sources:I.meta.sources,content:I.content});break}case"GET /wiki/notes":{let{NoteStore:p}=await import("./notes-WJJEJ4CJ.js"),m=n.searchParams.get("status")||"waiting";if(!["waiting","open","patched","rejected","deferred","expired","all"].includes(m)){this.json(t,400,{error:"status must be waiting, open, patched, rejected, deferred, expired or all"});break}let k=Math.max(1,Math.min(200,parseInt(n.searchParams.get("limit")||"50",10)||50)),I=new p(this.registry.getWikiHub().getBaseDir()).list(m==="all"?void 0:m);this.json(t,200,{nodeId:this.config.node.id,enabled:this.config.wikiNotes.enabled,inbox:this.config.wikiNotes.inbox??null,crons:this.config.wikiNotes.crons,absorbAgent:this.config.wikiNotes.absorbAgent??null,total:I.length,notes:I.slice(-k).reverse()});break}case"POST /wiki/notes":{let{NoteStore:p,validateNote:m}=await import("./notes-WJJEJ4CJ.js"),k=this.config.wikiNotes;if(!k.enabled||!k.inbox){this.json(t,409,{error:"wiki notes are off on this node: set wikiNotes.enabled and wikiNotes.inbox"});break}let S=await U(e),I=m({...S,to:k.inbox});if("error"in I){this.json(t,400,{error:I.error});break}let R=I.note;if(this.registry.getAgent(k.inbox)){try{let{note:N,added:C}=new p(this.registry.getWikiHub().getBaseDir()).add(R);this.json(t,C?201:200,{ok:!0,added:C,note:N,node:this.config.node.id})}catch(N){this.json(t,507,{error:N?.message??String(N)})}break}if(S.forwarded===!0){this.json(t,404,{error:`inbox agent "${k.inbox}" is not on this node`});break}let D=this.mesh?.findAgentPeer(k.inbox);if(!D){this.json(t,404,{error:`inbox agent "${k.inbox}" is not on this node or any known peer`});break}let M=this.mesh.directory().find(N=>N.peer===D.peer)?.peerUrl;if(!D.healthy||!M){this.json(t,503,{error:`the node hosting "${k.inbox}" (${D.peer}) is unreachable; try again later`});break}try{let N=await fetch(`${M.replace(/\/$/,"")}/wiki/notes`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(D.peer)},body:JSON.stringify({...R,fromNode:R.fromNode||this.config.node.id,forwarded:!0}),signal:AbortSignal.timeout(1e4)}),C=await N.json().catch(()=>({}));this.json(t,N.status,{...C,peer:D.peer})}catch(N){this.json(t,502,{error:`forward to ${D.peer} failed: ${N?.message??N}`,peer:D.peer})}break}case"GET /graph/schema":{let p=this.registry.getGraphStore();if(!p){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,schema:p.loadSchema()});break}case"GET /graph/nodes":{let p=this.registry.getGraphStore();if(!p){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,...p.loadNodes()});break}case"GET /graph/classifications":{let p=this.registry.getGraphStore();if(!p){this.json(t,404,{error:"graph disabled on this node"});break}let m=n.searchParams.get("status")||"approved",k=Math.max(1,Math.min(1e3,parseInt(n.searchParams.get("limit")||"200",10)||200)),S=p.listByStatus(m,k);this.json(t,200,{nodeId:this.config.node.id,status:m,count:S.length,classifications:S});break}default:this.json(t,404,{error:"Not found",endpoints:["GET /health","GET /agents","GET /crons","GET /routines \u2014 schedules + cron/hook workflows with staleness flags","GET /mesh","GET /wiki/agents","GET /wiki/entries[?agent=X&after=YYYY-MM-DD]","GET /wiki/articles?agent=X","GET /wiki/notes[?status=waiting|open|patched|rejected|deferred|expired|all&limit=N]","POST /wiki/notes { from, change, source, date? } \u2014 a note for the wiki observe/sweep run","GET /graph/schema","GET /graph/nodes","GET /graph/classifications[?status=approved|pending|rejected&limit=N]","POST /task { agent, message, context?, freshSession?: bool }","GET /agents/:id \u2014 resolved agent config (permission, tier, model, persistentProcess, toolUseRequired)","POST /agents/:id/selftest { message? } \u2014 canary probe; runs a fresh-session task and reports {ok, durationMs, tokens, billedModel}","GET /traces[?agentId=&channel=&chatId=&workflowRunId=&status=&since=&until=&limit=]","GET /traces/:taskId \u2014 full per-task execution trace (steps + tokens)","GET /voice/history[?agent=&limit=&before=] \u2014 past voice exchanges, bounded summaries","GET /voice/history/:id \u2014 one voice exchange in full; POST /voice/history/:id/replay","GET /api/processes \u2014 live persistent claude processes (JSON)","POST /api/processes/kill { agentId, channel, chatId, reason? }","GET /api/actions/builtin \u2014 list shipped built-in typed actions","POST /api/actions/builtin/:name \u2014 run a built-in with JSON body input","POST /mesh/task { peer, message }","POST /webhook/:agentId[/:source] \u2014 webhook callback","POST /reload \u2014 re-read agentx.json (hot-swaps crons)","GET /usage/plan \u2014 Claude plan windows, cold-dispatch counters, active holds","POST /usage/plan/lift \u2014 drop the active Claude plan holds","GET /daemon/restart \u2014 in-flight count, service manager, pending restart","POST /daemon/restart \u2014 restart when idle { timeoutMinutes?, onTimeout? }","POST /daemon/restart/cancel","GET /.well-known/agent-card.json","GET /call \u2014 browser UI for P2P A/V calls (requires channels.webrtc.enabled)","GET /webrtc/config \u2014 ICE servers + peer directory for the call page","GET /webrtc/events?callId=&as= \u2014 SSE stream of signaling events","POST /webrtc/signal/out \u2014 browser-originated signal, forwarded to remote peer","POST /webrtc/signal \u2014 remote-peer-originated signal, fanned out to local browser","POST /webrtc/bot/invite { callId, target, agentId } \u2014 spawn a transcribing bot peer for a call","GET /webrtc/bots \u2014 active bot sessions","POST /webrtc/camera/watch { callId, agentId } \u2014 an agent watches the phone camera share","GET /webrtc/camera/watch \u2014 agents watching a camera now","POST /webrtc/camera/watch/:id/look { note? } \u2014 ask the watching agent what it sees","POST /webrtc/camera/watch/:id/stream { seconds, note? } \u2014 the agent keeps watching for a while (0 stops)","POST /webrtc/camera/look { agentId } \u2014 from an agent's run: the newest frame as a PNG path"]})}}catch(i){this.json(t,500,{error:i.message})}}async handleOpenAICompat(e,t,n){let s=await U(e);await ky(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=Op(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=Ky();if(e==="json")return this.registry.getTodayUsage();let t=Jy(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||!mn(n)))try{let s=ne(n,".claude","skills");gI(s,{recursive:!0});let i=ne(s,Hv);if(!mn(i))Sd(i,yl(e)),this.log(` memory-skill: installed remember.md \u2192 ${t.id}`);else{let o=qv(ws(i,"utf-8"),e);o&&(Sd(i,o),this.log(` memory-skill: updated remember.md \u2192 ${t.id}`))}this.agentMemory.syncToWorkspace(t.id,n,this.config.session.memoryIndexMaxChars)}catch(s){this.log(` memory-skill: ${t.id} install failed \u2014 ${s?.message??s}`)}}}installAgentMcpConfig(){for(let[e,t]of Object.entries(this.config.agents)){let n=t.workspace;if(!n||!mn(n))continue;let s=this.config.workflows.enabled&&(this.config.workflows.followUp.enabled&&(this.config.workflows.followUp.agents[e]??!0)||hg(this.config.workflows,e)),i=Eh(ju(t),this.config.requests.enabled||s?Rh():null);try{switch(Ch(n,i)){case"installed":this.log(` mcp: installed ${Object.keys(i).length} server(s) \u2192 ${e}`);break;case"updated":this.log(` mcp: updated .mcp.json (${Object.keys(i).length} server(s)) \u2192 ${e}`);break;case"removed":this.log(` mcp: removed managed .mcp.json (config now empty) \u2192 ${e}`);break;case"skipped-operator-owned":Object.keys(i).length>0&&this.log(` mcp: ${e} has operator-owned .mcp.json \u2014 skipping (delete file or marker to let agentx manage)`);break;case"noop":break}}catch(o){this.log(` mcp: ${e} install failed \u2014 ${o?.message??o}`)}}}workspaceFor(e){for(let t of this.registry.list())if(t.id===e)return t.workspace;return null}handleMemoryApi(e,t,n,s){return Sv(e,t,n,s,{mem:this.agentMemory,workspaceFor:i=>this.workspaceFor(i),runningTaskOwner:i=>this.registry.runningTaskOwner(i),indexMaxChars:()=>this.config.session.memoryIndexMaxChars})}async handleWorkflowEvent(e,t){if(!this.workflowDispatcher){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let n;try{n=await se(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let s=n?.payload??n,i=s?.event,o=s?.entityRef;if(!i?.id||!o?.backend||!o?.id){this.json(t,400,{error:"missing event or entityRef"});return}let a=n?.kind;try{if(a==="trigger"&&s.trigger){let h=typeof n?.fromPeer=="string"?n.fromPeer:"unknown";this.log(`[workflows/mesh] received trigger from "${h}" source="${s.trigger.source}" chat="${s.trigger.chat??"*"}"`);let f=await this.workflowDispatcher.dispatch({trigger:s.trigger,entityRef:o,event:i,fromRemote:{peer:h}});this.log(`[workflows/mesh] dispatched broadcast: matched=${f.claimed.length} ${f.claimed.length?`(${f.claimed.map(y=>y.id).join(", ")})`:"[none \u2014 no workflow with mesh.allowRemote matched]"}`),this.json(t,202,{ok:!0,mode:"trigger-broadcast",matched:f.claimed.map(y=>y.id)});return}let d=(s.workflowId?this.workflowStore?.get(s.workflowId):null)?.nodes.find(h=>h.type.startsWith("trigger."))?.config??{},u={source:String(d.source??"hook"),project:d.filter?.project,repo:d.filter?.repo,chat:d.filter?.chat,labels:d.filter?.labels};await this.workflowDispatcher.dispatch({trigger:u,entityRef:o,event:i}),this.json(t,202,{ok:!0})}catch(c){this.log(`[workflows] /workflow/event failed: ${c.message}`),this.json(t,500,{error:c.message})}}async postToPushHost(e,t,n){let s=e.toLowerCase(),i=this.mesh?.directory().find(c=>c.peer.toLowerCase()===s);if(!i)throw new Error(`push: channels.push.relayTo "${e}" is not a mesh peer of this node`);let o=await fetch(`${i.peerUrl}${t}`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(i.peer)},body:JSON.stringify(n),signal:AbortSignal.timeout(15e3)});if(!o.ok)throw new Error(`push: ${i.peer} ${t} -> ${o.status} ${(await o.text().catch(()=>"")).slice(0,200)}`);let a=await o.json().catch(()=>({}));if(t==="/channel/send")return a.messageId??void 0;if(typeof a.status!="number")throw new Error(`push: ${i.peer} ${t} gave no answer`);return{status:a.status,body:a.body??{}}}async handlePushApp(e,t){let n;try{n=await se(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let{handlePushBridge:s,pushOrigin:i}=await import("./push-bridge-NR7SLHGX.js"),o=this.config.channels.push;if(!o?.enabled){this.json(t,200,{status:503,body:{error:`Notifications are off on ${this.config.node.name}.`}});return}if(o.relayTo){if(n?.origin!==void 0){this.json(t,200,{status:409,body:{error:`${this.config.node.name} relays its notifications too (channels.push.relayTo = ${o.relayTo})`}});return}if(n?.op!=="app"){this.json(t,400,{error:"op must be app"});return}try{this.json(t,200,await this.postToPushHost(o.relayTo,"/push/app",{op:"app",origin:i(this.config.node.name),call:n.call}))}catch(c){this.log(`[push] /push/app to ${o.relayTo} failed: ${c.message}`),this.json(t,502,{error:c.message})}return}let a=this.pushBridgeCaller(e);"error"in a&&n?.op!=="roster"&&this.log(`[push] /push/app from ${e.socket?.remoteAddress||"?"} refused: ${a.error}`),this.json(t,200,s(n,a,this.pushHost??null,this.pushHost?void 0:`Notifications are not running on ${this.config.node.name}. Check channels.push.subject and the database there.`))}pushBridgeCaller(e){return fp(String(e.headers.authorization||""),this.config.mesh.peers,process.env.MESH_TOKEN)}async handleChannelSend(e,t){let n;try{n=await se(e)}catch(l){this.json(t,400,{error:"invalid JSON body",message:l.message});return}let s=String(n?.channel??""),i=String(n?.chatId??""),o=String(n?.text??"");if(!s||!i||!o){this.json(t,400,{error:"channel, chatId, and text are required"});return}if(!this.router.getChannel(s)){this.json(t,404,{error:`channel "${s}" not hosted on this node`});return}let c;if(n.relayed===!0&&n.origin!==void 0){let l=this.pushBridgeCaller(e);if("origin"in l)c=l.origin;else if(i!=="default"){this.json(t,403,{error:l.error});return}}if(s==="push"&&i.includes(":")){let{scopedPushTarget:l}=await import("./push-bridge-NR7SLHGX.js"),d=l(i,this.pushBridgeCaller(e));if("error"in d){this.json(t,403,{error:d.error});return}}try{let l=await this.router.sendOutbound({channel:s,chatId:i,text:o,accountId:typeof n.accountId=="string"?n.accountId:void 0,parseMode:typeof n.parseMode=="string"?n.parseMode:void 0,replyTo:typeof n.replyTo=="string"?n.replyTo:void 0,buttons:Array.isArray(n.buttons)?n.buttons:void 0,agentId:typeof n.agentId=="string"?n.agentId:void 0,relayed:n.relayed===!0?!0:void 0,...n.relayed===!0?{told:{passed:!0}}:{},origin:c},{recordInSession:!1});this.json(t,200,{ok:!0,messageId:l??null})}catch(l){this.log(`[mesh] /channel/send "${s}" failed: ${l.message}`),this.json(t,500,{error:l.message})}}async handleChannelChats(e,t,n={}){let s=new Set,i=[],o=[],a=(l,d)=>{let u=0;for(let h of l)!h.id||s.has(h.id)||(s.add(h.id),i.push({...h,source:d}),u++);u>0&&o.push(`${d}:${u}`)},c=this.router.getChannel(t);if(c?.listKnownChats)try{a(c.listKnownChats(),"local")}catch{}else if(c?.listChats)try{a(c.listChats().map(l=>({id:l.jid,name:l.name,kind:l.isGroup?"group":"dm"})),"local")}catch{}if(!n.localOnly&&this.mesh){let l=this.mesh.directory().filter(d=>d.healthy&&d.channels?.includes(t));await Promise.allSettled(l.map(async d=>{try{let u=await fetch(`${d.peerUrl}/channels/${encodeURIComponent(t)}/chats?local=1`,{headers:this.mesh.authHeaders(d.peer),signal:AbortSignal.timeout(5e3)});if(!u.ok)return;let h=await u.json();Array.isArray(h.chats)&&a(h.chats.map(f=>({id:f.id,name:f.name,kind:f.kind??"dm",accountId:f.accountId})),`mesh:${d.peer}`)}catch{}}))}this.json(e,200,{channel:t,source:o.join(", ")||"none",chats:i})}async handleWorkflowManualRun(e,t,n){if(!this.workflowDispatcher||!this.workflowStore){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let s;try{s=await se(e)}catch{s={}}try{let i=await Gv({get:o=>this.workflowStore.get(o),dispatchWorkflow:o=>this.workflowDispatcher.dispatchWorkflow(o),startRun:o=>this.workflowDispatcher.startRun(o)},n,s);this.json(t,i.status,i.body)}catch(i){this.log(`[workflows] manual run "${n}" failed: ${i.message}`),this.json(t,500,{error:i.message})}}},$d=Id;Ot($d,"MESH_PROTECTED_PATHS",new Set(["/task","/ask","/mesh/task","/mesh/inbox/send","/workflow/event","/workflow/transition","/channel/send","/push/app","/webrtc/signal","/gitlab/react","/gitlab/send-note","/gitlab/log-time","/channel/edit-comment","/github/send-comment"]));function RN(r){if(typeof r!="string")return"";let e=r.trim();if(!e)return"";let t=e.match(/^[^.!?\n]+[.!?]?/),n=(t?t[0]:e).trim();return n.length>140?n.slice(0,137)+"\u2026":n}function se(r){return new Promise((e,t)=>{let n="";r.setEncoding("utf8"),r.on("data",s=>{n+=s}),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch(s){t(s)}}),r.on("error",t)})}function EN(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)})}fI();function q6(r){typeof r=="string"&&(ks.error(r),process.exit(1)),r instanceof Error&&(ks.error(r.message),process.exit(1)),ks.error("Something went wrong. Please try again."),process.exit(1)}export{VN as a,qa as b,St as c,Dn as d,Nn as e,Tt as f,cr as g,Hm as h,Ny as i,vA as j,SA as k,Uy as l,Te as m,By as n,qy as o,Er as p,WF as q,UF as r,Fr as s,X2 as t,cE as u,lE as v,Dc as w,Cw as x,V2 as y,Ww as z,uE as A,Uw as B,Gw as C,Hw as D,J2 as E,K2 as F,z2 as G,Xr as H,Le as I,nU as J,lC as K,ok as L,ak as M,zC as N,Ik as O,Rk as P,jP as Q,dl as R,KG as S,zG as T,YG as U,Pv as V,m_ as W,nH as X,sH as Y,ts as Z,an as _,ns as $,RH as aa,cS as ba,iM as ca,kB as da,_i as ea,Cl as fa,Pl as ga,Li as ha,be as ia,ZS as ja,Ui as ka,nD as la,h0 as ma,rD as na,m0 as oa,Bi as pa,ds as qa,Ji as ra,zi as sa,S0 as ta,ql as ua,R0 as va,at as wa,Ee as xa,M0 as ya,D0 as za,O0 as Aa,N0 as Ba,mo as Ca,P$ as Da,gd as Ea,M$ as Fa,LO as Ga,UX as Ha,$d as Ia,q6 as Ja};
|
|
1325
|
-
//# sourceMappingURL=chunk-
|
|
1325
|
+
//# sourceMappingURL=chunk-6VKWJQOX.js.map
|