agentix-cli 0.226.3 → 0.226.4
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-NVHEWULT.js → chunk-ZFMUF3NU.js} +3 -3
- package/dist/{chunk-NVHEWULT.js.map → chunk-ZFMUF3NU.js.map} +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/{program-FZBZUK5X.js → program-W6CGC2EO.js} +4 -4
- package/package.json +1 -1
- /package/dist/{program-FZBZUK5X.js.map → program-W6CGC2EO.js.map} +0 -0
|
@@ -541,7 +541,7 @@ ${d}`)}let S={agentId:o,message:b,context:{channel:p,sender:y?"opencode":"openai
|
|
|
541
541
|
|
|
542
542
|
`)}}function ov(r){r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"})}function av(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}]})}
|
|
543
543
|
|
|
544
|
-
`)}function cv(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);Yd(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 Yd(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Is=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Is(`${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(Is.levelOrder[e]<Is.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)}},$s=Is;Yt($s,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as F_,statSync as U_}from"fs";var Ve={version:"0.226.
|
|
544
|
+
`)}function cv(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);Yd(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 Yd(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Is=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Is(`${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(Is.levelOrder[e]<Is.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)}},$s=Is;Yt($s,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as F_,statSync as U_}from"fs";var Ve={version:"0.226.4",commit:"1701b5f",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function q_(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 lv(){let r=null;try{r=U_(F_(process.argv[1])).mtimeMs}catch{}let e=vk().version;return q_(Ve,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{existsSync as uv,mkdirSync as G_,readFileSync as H_,statSync as B_,writeFileSync as X_}from"fs";import{homedir as hv}from"os";import{dirname as J_,join as Qd,resolve as Zd}from"path";var gv=(r=hv())=>Qd(r,".agentx","daemon-root");function pv(r,e=hv()){let t=gv(e);G_(J_(t),{recursive:!0}),X_(t,Zd(r)+`
|
|
545
545
|
`)}var V_=r=>uv(Qd(r,"agentx.json"))||uv(Qd(r,".agentx","config.json"));function K_(r){try{return B_(r).isDirectory()}catch{return!1}}function zB(r={}){let e=Zd(r.cwd??process.cwd()),t=r.env??process.env;if(t.AGENTX_ROOT?.trim())return Zd(t.AGENTX_ROOT.trim());if(V_(e))return e;let n="";try{n=H_(gv(r.home),"utf-8").trim()}catch{}return n&&K_(n)?n:e}import{randomUUID as z_}from"crypto";var Li=class{constructor(e=new Vp){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!Y_.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};Z_(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:z_(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=Q_(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}},Y_=["run","task","signal","mesh","channel","status"];function Q_(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 Z_(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 fv(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 ji,timingSafeEqual as mv}from"crypto";var Wi=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),d=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let w={};for(let[b,S]of Object.entries(e.headers))(b.startsWith("x-hubspot")||b.startsWith("x-hub")||b.startsWith("x-github")||b.startsWith("x-gitlab")||b.startsWith("stripe")||b.startsWith("sentry")||b.startsWith("x-vercel")||b.startsWith("x-odoo")||b.startsWith("x-webhook")||b==="user-agent"||b==="content-type"||b==="host"||b==="x-forwarded-host"||b==="x-forwarded-proto"||b==="x-forwarded-for")&&(w[b]=S);this.log(`Webhook [${d}] reqUrl=${e.url} headers: ${JSON.stringify(w)}`)}let l=this.validateSignature(e.headers,a,d,i,e.url);if(l){this.log(`Webhook [${d}] -> ${i}: REJECTED (${l})`),this.sendJson(t,401,{error:l});return}let u=this.buildSummary(d,c,e.headers);this.log(`Webhook [${d}] -> ${i}: ${u.slice(0,100)}`);let h=this.extractEventType(d,c,e.headers),g=this.webhookEntries.find(w=>w.enabled&&w.agentId===i&&w.source===d),y=h&&g?.triggers?.[h]||g?.defaultWorkflow||null;if(await this.fireHookSafe(d,h,i,c),y&&this.workflowDispatcher)try{let w=await this.workflowDispatcher.dispatchWorkflow({workflowId:y,entityRef:{kind:"webhook",id:`${d}:${i}:${h??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:d,eventType:h,payload:c},trigger:{source:d}});this.log(`Webhook [${d}/${h??"\u2014"}] -> workflow=${y} (claimed=${w.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:d,eventType:h,workflow:y,claimed:w.claimed});return}catch(w){this.log(`Workflow dispatch failed [${d}/${h}/${y}]: ${w.message}`)}let p=this.webhookEntries.find(w=>w.enabled&&w.node&&w.agentId===i&&w.source===d);if(p?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:d,node:p.node,status:"accepted"}),this.mesh.sendTask(p.node,u,i,{context:{channel:`webhook:${d}`,sender:`webhook:${d}`}}).then(w=>this.log(`Mesh-forwarded webhook [${d}] -> ${p.node}/${i}: ${w?.slice(0,100)||"ok"}`),w=>this.log(`Mesh forward failed [${d}] -> ${p.node}/${i}: ${w.message}`));return}try{let w=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${d}`,sender:`webhook:${d}`}});this.sendJson(t,w.error?500:200,{ok:!w.error,agent:i,source:d,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 l of t.commits.slice(0,3))s.push(` - ${l.message?.split(`
|
|
546
546
|
`)[0]||"no message"} (${l.author?.name||""})`)}let d=t.object_attributes;if(d?.title&&(s.push(`Title: ${d.title}`),s.push(`State: ${d.state||""}`),s.push(`Action: ${d.action||""}`),d.source_branch&&s.push(`Branch: ${d.source_branch} -> ${d.target_branch}`),d.url&&s.push(`URL: ${d.url}`)),d?.iid&&!d?.source_branch&&(s.push(`Issue #${d.iid}: ${d.title||""}`),d.description&&s.push(`Description: ${d.description.slice(0,200)}`)),t.object_kind==="pipeline"){let l=t.object_attributes;s.push(`Pipeline: ${l?.status||""} (${l?.ref||""})`),s.push(`Duration: ${l?.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(`
|
|
547
547
|
`)[0]||""} (${u.author?.name||""})`);let d=t.pull_request;d&&(s.push(`PR #${d.number}: ${d.title}`),s.push(`Action: ${t.action}`),s.push(`Branch: ${d.head?.ref} -> ${d.base?.ref}`));let l=t.issue;l&&(s.push(`Issue #${l.number}: ${l.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 d of a.slice(0,3)){let l=d.subscriptionType??"?",u=d.objectId??"?",h=d.changeFlag??d.changeSource??"";s.push(` - ${l} (object ${u}${h?`, ${h}`:""})`)}}else{let d=t.subscriptionType??"event",l=t.objectId??"?";s.push(`Event: ${d} (object ${l})`)}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(`
|
|
@@ -831,7 +831,7 @@ ${i}
|
|
|
831
831
|
|
|
832
832
|
${b.error}`,"error");return}h.edit={version:b.version,diff:b.diff,added:b.added,removed:b.removed,sources:b.sources},Ds(h,b.added+b.removed?w.summary:`${w.summary}
|
|
833
833
|
|
|
834
|
-
The page text did not change.`,"done")}catch(p){Ds(h,String(p?.message||p),"error")}})(),ue(t,200,{pending:!0,id:h.id,curator:d})}catch(i){return this.deps.log?.(`wiki curate: ${i?.message||i}`),ue(t,500,{error:String(i?.message||i)})}}page(e,t){let n=typeof e=="string"?e.trim():"",s=typeof t=="string"?t.trim():"";if(!n||!s)return{error:"agent and a page path are required",status:400};let i=this.deps.hub();if(!i.listAgents([]).includes(n))return{error:`no wiki for "${n}"`,status:404};let o=i.getAgentWiki(n);if(!yw(o.baseDir,s))return{error:"not a page path",status:400};let a=o.readArticle(s);return a?{agentId:n,path:s,store:o,article:a,readOnly:!!i.syncedFrom(n)}:{error:"no such page",status:404}}push(e,t,n){let s=Co(e,t),i=this.chats.get(s)??[],o={...n,id:++this.seq,at:new Date().toISOString()};for(i.push(o),i.length>tI&&i.splice(0,i.length-tI),this.chats.delete(s),this.chats.set(s,i);this.chats.size>XL;)this.chats.delete(this.chats.keys().next().value);return o}};function Ds(r,e,t){r.text=e.trim()||(t==="error"?"The agent failed without a message.":"Done."),r.status=t}function Co(r,e){return`${r}\0${e}`}function ue(r,e,t){return r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t)),!0}function JL(r){return new Promise((e,t)=>{let n="";r.on("data",s=>{n+=s,n.length>64e3&&(t(new Error("body too large")),r.destroy())}),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch{t(new Error("invalid JSON body"))}}),r.on("error",t)})}var su=/^\/mesh\/guest\//,sI=/^\/mesh\/guests(\/|$)/;async function rI(r,e,t,n,s){let i=r.toUpperCase(),o=s.log??(c=>console.log(c));if(e==="/mesh/guest/join"&&i==="POST"){let c=await ww(t??{},n.address,s);return c.status===200?{status:200,body:c.body,token:c.token}:{status:c.status,body:c.body}}if(su.test(e)){let c=bw(n.token,s);if(!c.ok)return{status:c.status,body:{error:c.error,..."waiting"in c&&c.waiting?{waiting:!0}:{},..."paused"in c&&c.paused?{paused:!0}:{}}};let{grant:d}=c;if(e==="/mesh/guest/me"&&i==="GET")return{status:200,body:Tw(d)};if(e==="/mesh/guest/task"&&i==="POST"){let l=typeof t?.message=="string"?t.message.trim():"";if(!l)return{status:400,body:{error:"message is required"}};if(l.length>2e4)return{status:413,body:{error:"message is longer than 20000 characters"}};s.guests.log({grant:d.id,event:"task",address:n.address,detail:l.slice(0,120)}),o(`[guests] ${d.id}: ${d.guest} asked ${d.agentId} (${d.level}): ${l.slice(0,80).replace(/\s+/g," ")}`);let u=await s.run(kw(d,l));return s.guests.used(d.id,u.tokensUsed??0),u.error?{status:502,body:{error:u.error,grant:d.id}}:{status:200,body:{content:u.content,grant:d.id,agentId:d.agentId}}}return{status:404,body:{error:"Not found"}}}if(e==="/mesh/guests"&&i==="GET")return{status:200,body:{grants:s.guests.grants().map(d=>nd(s,d)).sort((d,l)=>l.createdAt.localeCompare(d.createdAt)).map(d=>nI(s.guests,d,5))}};let a=e.match(/^\/mesh\/guests\/([^/]+)(?:\/(pause|resume|end|update))?$/);if(a){let c=decodeURIComponent(a[1]),d=a[2],l=s.guests.get(c);if(!l)return{status:404,body:{error:`no grant "${c}"`}};let u=nd(s,l);if(!d&&i==="GET")return{status:200,body:{grant:nI(s.guests,u,50)}};if(!d||i!=="POST")return{status:405,body:{error:"Method not allowed"}};if(d==="pause"){let g=vw(s,c);if(!g)return{status:409,body:{error:`grant "${c}" is ${u.state}, not active`}};let y=s.cancel?.(g)??0;return o(`[guests] ${c}: paused by the operator; ${y} running turn(s) stopped`),{status:200,body:{grant:g,stopped:y}}}if(d==="resume"){let g=Sw(s,c);return g?{status:200,body:{grant:g}}:{status:409,body:{error:`grant "${c}" is ${u.state}, not paused`}}}if(d==="end"){let g=$w(s,c);if(!g)return{status:409,body:{error:`grant "${c}" is already ended`}};let y=s.cancel?.(g)??0;return o(`[guests] ${c}: ended by the operator; ${y} running turn(s) stopped`),{status:200,body:{grant:g,stopped:y}}}let h=Iw(s,c,t??{});return h.ok?{status:200,body:{grant:h.grant}}:{status:400,body:{error:h.error}}}return{status:404,body:{error:"Not found"}}}function nI(r,e,t){return{...e,trail:r.events(e.id,t)}}var VL="there: ";var _o=class{constructor(e){this.deps=e}busy=!1;async remoteOf(e){if(!e.peer)return null;try{let t=await this.deps.fetchJob(e.peer,e.remoteId??e.id);if(t.status===404)return{peer:e.peer,error:"that node has no such job (it may not have started it yet, or runs an older version)"};let n=t.body;return t.status!==200||!n?.job||typeof n.job.id!="string"?{peer:e.peer,error:`that node answered ${t.status}`}:{peer:e.peer,job:n.job,runs:Array.isArray(n.runs)?n.runs:[],children:Array.isArray(n.children)?n.children:[]}}catch(t){return{peer:e.peer,error:`that node did not answer (${String(t?.message??t).slice(0,120)})`}}}async refresh(){if(this.busy)return 0;this.busy=!0;let e=0;try{for(let t of this.deps.jobs.openOnPeers()){let n=await this.remoteOf(t);if(
|
|
834
|
+
The page text did not change.`,"done")}catch(p){Ds(h,String(p?.message||p),"error")}})(),ue(t,200,{pending:!0,id:h.id,curator:d})}catch(i){return this.deps.log?.(`wiki curate: ${i?.message||i}`),ue(t,500,{error:String(i?.message||i)})}}page(e,t){let n=typeof e=="string"?e.trim():"",s=typeof t=="string"?t.trim():"";if(!n||!s)return{error:"agent and a page path are required",status:400};let i=this.deps.hub();if(!i.listAgents([]).includes(n))return{error:`no wiki for "${n}"`,status:404};let o=i.getAgentWiki(n);if(!yw(o.baseDir,s))return{error:"not a page path",status:400};let a=o.readArticle(s);return a?{agentId:n,path:s,store:o,article:a,readOnly:!!i.syncedFrom(n)}:{error:"no such page",status:404}}push(e,t,n){let s=Co(e,t),i=this.chats.get(s)??[],o={...n,id:++this.seq,at:new Date().toISOString()};for(i.push(o),i.length>tI&&i.splice(0,i.length-tI),this.chats.delete(s),this.chats.set(s,i);this.chats.size>XL;)this.chats.delete(this.chats.keys().next().value);return o}};function Ds(r,e,t){r.text=e.trim()||(t==="error"?"The agent failed without a message.":"Done."),r.status=t}function Co(r,e){return`${r}\0${e}`}function ue(r,e,t){return r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t)),!0}function JL(r){return new Promise((e,t)=>{let n="";r.on("data",s=>{n+=s,n.length>64e3&&(t(new Error("body too large")),r.destroy())}),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch{t(new Error("invalid JSON body"))}}),r.on("error",t)})}var su=/^\/mesh\/guest\//,sI=/^\/mesh\/guests(\/|$)/;async function rI(r,e,t,n,s){let i=r.toUpperCase(),o=s.log??(c=>console.log(c));if(e==="/mesh/guest/join"&&i==="POST"){let c=await ww(t??{},n.address,s);return c.status===200?{status:200,body:c.body,token:c.token}:{status:c.status,body:c.body}}if(su.test(e)){let c=bw(n.token,s);if(!c.ok)return{status:c.status,body:{error:c.error,..."waiting"in c&&c.waiting?{waiting:!0}:{},..."paused"in c&&c.paused?{paused:!0}:{}}};let{grant:d}=c;if(e==="/mesh/guest/me"&&i==="GET")return{status:200,body:Tw(d)};if(e==="/mesh/guest/task"&&i==="POST"){let l=typeof t?.message=="string"?t.message.trim():"";if(!l)return{status:400,body:{error:"message is required"}};if(l.length>2e4)return{status:413,body:{error:"message is longer than 20000 characters"}};s.guests.log({grant:d.id,event:"task",address:n.address,detail:l.slice(0,120)}),o(`[guests] ${d.id}: ${d.guest} asked ${d.agentId} (${d.level}): ${l.slice(0,80).replace(/\s+/g," ")}`);let u=await s.run(kw(d,l));return s.guests.used(d.id,u.tokensUsed??0),u.error?{status:502,body:{error:u.error,grant:d.id}}:{status:200,body:{content:u.content,grant:d.id,agentId:d.agentId}}}return{status:404,body:{error:"Not found"}}}if(e==="/mesh/guests"&&i==="GET")return{status:200,body:{grants:s.guests.grants().map(d=>nd(s,d)).sort((d,l)=>l.createdAt.localeCompare(d.createdAt)).map(d=>nI(s.guests,d,5))}};let a=e.match(/^\/mesh\/guests\/([^/]+)(?:\/(pause|resume|end|update))?$/);if(a){let c=decodeURIComponent(a[1]),d=a[2],l=s.guests.get(c);if(!l)return{status:404,body:{error:`no grant "${c}"`}};let u=nd(s,l);if(!d&&i==="GET")return{status:200,body:{grant:nI(s.guests,u,50)}};if(!d||i!=="POST")return{status:405,body:{error:"Method not allowed"}};if(d==="pause"){let g=vw(s,c);if(!g)return{status:409,body:{error:`grant "${c}" is ${u.state}, not active`}};let y=s.cancel?.(g)??0;return o(`[guests] ${c}: paused by the operator; ${y} running turn(s) stopped`),{status:200,body:{grant:g,stopped:y}}}if(d==="resume"){let g=Sw(s,c);return g?{status:200,body:{grant:g}}:{status:409,body:{error:`grant "${c}" is ${u.state}, not paused`}}}if(d==="end"){let g=$w(s,c);if(!g)return{status:409,body:{error:`grant "${c}" is already ended`}};let y=s.cancel?.(g)??0;return o(`[guests] ${c}: ended by the operator; ${y} running turn(s) stopped`),{status:200,body:{grant:g,stopped:y}}}let h=Iw(s,c,t??{});return h.ok?{status:200,body:{grant:h.grant}}:{status:400,body:{error:h.error}}}return{status:404,body:{error:"Not found"}}}function nI(r,e,t){return{...e,trail:r.events(e.id,t)}}var VL="there: ";var _o=class{constructor(e){this.deps=e}busy=!1;async remoteOf(e){if(!e.peer)return null;try{let t=await this.deps.fetchJob(e.peer,e.remoteId??e.id);if(t.status===404)return{peer:e.peer,unknown:!0,error:"that node has no such job (it may not have started it yet, or runs an older version)"};let n=t.body;return t.status!==200||!n?.job||typeof n.job.id!="string"?{peer:e.peer,error:`that node answered ${t.status}`}:{peer:e.peer,job:n.job,runs:Array.isArray(n.runs)?n.runs:[],children:Array.isArray(n.children)?n.children:[]}}catch(t){return{peer:e.peer,error:`that node did not answer (${String(t?.message??t).slice(0,120)})`}}}async refresh(){if(this.busy)return 0;this.busy=!0;let e=0;try{for(let t of this.deps.jobs.openOnPeers()){let n=await this.remoteOf(t);if(n?.unknown&&this.stallUnknown(t),!n?.job)continue;let s=`${VL}${String(n.job.status??n.job.state).replace(/\s+/g," ").trim().slice(0,300)}`;(t.note!==s||t.remoteId!==n.job.id)&&this.deps.jobs.setRemote(t.id,n.job.id,s),e++}}catch(t){this.deps.log(`[jobs] reading other nodes failed: ${t?.message??t}`)}finally{this.busy=!1}return e}stallUnknown(e){let t=this.deps.now?.()??Date.now();if(t-e.updatedAt<216e5)return;let n=Math.floor((t-e.updatedAt)/36e5),s=`${e.peer} has no record of this job ${n} h after it was handed there: the hand-off did not start there, or was lost`;this.deps.jobs.markStalled(e.id,s,t)&&this.deps.log(`[jobs] ${e.id} stalled: ${s}`)}};fc();Za();jE();Za();var KL=String.raw`(?:clos(?:e|es|ed|ing)|fix(?:|es|ed|ing)|resolv(?:e|es|ed|ing)|implement(?:|s|ed|ing))`,ru=String.raw`(?:https?:\/\/[^\s<>()\[\]]+\/(?:-\/)?issues\/\d+|(?:[\w.-]+\/)+[\w.-]+#\d+|(?<![\w&])#\d+)`,iI=new RegExp(ru,"gi"),zL=new RegExp(String.raw`\b${KL}\b:?\s+(?:issues?\s+)?(${ru}(?:\s*(?:,|\band\b|&)\s*${ru})*)`,"gi"),YL=/^(\d+)-[\w.-]/;function oI(r,e,t){let n=t.match(/^#(\d+)$/);if(n)return{project:e,number:Number(n[1])};let s=Jn(r,t.replace(/[.,;:]+$/,""));return s&&!s.mr?{project:s.project,number:s.number}:null}function aI(r,e,t){let n=`${t.title??""}
|
|
835
835
|
${t.description??""}`,s=new Map,i=(a,c)=>{if(!a||!Number.isSafeInteger(a.number)||a.number<=0)return;let d=`${a.project.toLowerCase()}#${a.number}`,l=s.get(d);s.set(d,{...a,closes:c||!!l?.closes})};for(let a of n.matchAll(zL))for(let c of a[1].matchAll(iI))i(oI(r,e,c[0]),!0);for(let a of n.matchAll(iI))i(oI(r,e,a[0]),!1);let o=t.branch?.match(YL);return o&&!s.has(`${e.toLowerCase()}#${Number(o[1])}`)&&i({project:e,number:Number(o[1])},!0),[...s.values()].sort((a,c)=>Number(c.closes)-Number(a.closes))}var cI=r=>`${r.project}#${r.number}`;var QL={enabled:!0,checkEveryMinutes:30,lookbackDays:7,projects:[],liveField:"commit",labels:{todo:["To Do","Status::To Do"],doing:["Doing","Status::Doing"],review:["Review","Status::Review"],done:["Done","Status::Done"]},doneNotLiveAfterHours:24,write:!1,writeProjects:[]},ZL=5e3,ej=864e5,dI=["done","review","doing","todo"];function tj(r,e){let t=r.labels??[],n=t.filter(s=>dI.some(i=>e[i].some(o=>o.toLowerCase()===s.toLowerCase())));for(let s of dI){let i=t.find(o=>e[s].some(a=>a.toLowerCase()===o.toLowerCase()));if(i)return{status:s,label:i,all:n}}return{status:r.state==="open"?"open":"closed",label:null,all:n}}var lI=r=>r?r.slice(0,8):"?",iu=r=>new Date(r).toISOString().slice(0,16).replace("T"," ")+" UTC",Mo=r=>r.statusLabel??r.status;function nj(r){let e=r.changes.map(n=>`${n.ref} (${lI(n.commit)}, merged ${iu(n.mergedAt)})`).join(", "),t=r.live.filter(n=>n.commit).map(n=>`${lI(n.commit)} on ${n.source}`).join(", ");switch(r.kind){case"live-not-done":return`${r.issue} is live (${e} in ${t}), still ${Mo(r)}: expected Done`;case"merged-not-review":return`${r.issue} merged in ${e}, still ${Mo(r)}: expected Review`;case"done-not-live":return`${r.issue} says ${Mo(r)} but ${e} is not live yet (${t})`}}async function uI(r,e){let t=e.now??Date.now(),n={project:r,merged:0,issues:0,live:[],drifts:[],errors:[]},s=await e.forge.merged(r.provider,r.project,t-e.settings.lookbackDays*ej);if("error"in s)return n.errors.push(`${r.project}: merged changes: ${s.error}`),n;n.merged=s.length,n.live=await Promise.all(r.live.map(l=>e.liveCommit(l)));for(let l of n.live)l.commit||n.errors.push(`${r.project}: live ${l.source}: ${l.error??"no commit"}`);if(n.live.some(l=>!l.commit))return n;let i=async l=>{if(!l.commit||!n.live.length)return"unknown";let u=!0;for(let h of n.live){if(!h.commit){u=!1;continue}let g=await sj(r,l.commit,h.commit,e);if(g===!1)return"not-live";g!==!0&&(u=!1)}return u?"live":"unknown"},o=new Set([r.project,...(e.settings.projects??[]).filter(l=>l.provider===r.provider).map(l=>l.project)].map(l=>l.toLowerCase())),a=new Map;for(let l of s)for(let u of aI(r.provider,r.project,l)){if(!u.closes||!o.has(u.project.toLowerCase()))continue;let h=cI(u).toLowerCase(),g=a.get(h)??{project:u.project,number:u.number,changes:[]};g.changes.push(l),a.set(h,g)}let c=new Map;for(let{changes:l}of a.values())for(let u of l)c.has(u)||c.set(u,await i(u));let d=(e.settings.doneNotLiveAfterHours??QL.doneNotLiveAfterHours)*36e5;for(let{project:l,number:u,changes:h}of a.values()){let g=await e.readIssue(r.provider,{project:l,number:u,mr:!1},{notes:!1});if("error"in g){n.errors.push(`${l}#${u}: ${g.error}`);continue}n.issues++;let{status:y,label:p,all:w}=tj(g,e.settings.labels),b=h.map(T=>c.get(T)??"unknown"),S=b.includes("not-live")?"not-live":b.every(T=>T==="live")?"live":"unknown",v=S==="live"&&y!=="done"&&y!=="closed"?"live-not-done":S==="not-live"&&(y==="done"||y==="closed")?"done-not-live":S!=="live"&&(y==="todo"||y==="doing")?"merged-not-review":null;if(!v)continue;let A=v==="done-not-live"?h.filter(T=>c.get(T)==="not-live"):h;if(v==="live-not-done"&&e.forge.reopenedAt){let T=await e.forge.reopenedAt(r.provider,l,u);if(T!==null&&typeof T=="object"){n.errors.push(`${l}#${u}: reopened: ${T.error}`);continue}if(T!==null&&(A=A.filter(R=>R.mergedAt>T)),!A.length)continue}if(v==="done-not-live"&&!A.some(T=>t-T.mergedAt>=d))continue;let P={kind:v,provider:r.provider,issue:`${l}#${u}`,project:l,number:u,issueUrl:g.url,status:y,statusLabel:p,statusLabels:w,changes:A,live:v==="merged-not-review"?[]:n.live,checkedAt:t};n.drifts.push({...P,line:nj(P)})}return n}async function sj(r,e,t,n){let s=`${r.provider}:${r.project.toLowerCase()}:${e.toLowerCase()}:${t.toLowerCase()}`,i=n.liveCache?.get(s);if(i!==void 0)return i;let o;if(r.repo&&n.checkers){let a=await Ag({kind:"git-ancestor",repo:r.repo,commit:e,ref:t},{settings:{...n.checkers},git:n.git});o=a.verdict==="met"?!0:a.verdict==="not_met"?!1:null}else o=await n.forge.contains(r.provider,r.project,e,t);return o!==null&&n.liveCache&&(n.liveCache.size>=ZL&&n.liveCache.clear(),n.liveCache.set(s,o)),o}function hI(r,e){let t=r.changes.map(s=>`${s.url||s.ref} (merge commit \`${s.commit}\`, merged ${iu(s.mergedAt)})`),n=r.live.filter(s=>s.commit).map(s=>`\`${s.commit}\` on ${s.source}`);return[`Status set to **${e}** by AgentX: the work is live.`,"",`- Merged: ${t.join("; ")}`,`- Running: ${n.join("; ")}`,`- Checked: ${iu(r.checkedAt)}`,"",`Was: ${Mo(r)}. The issue is not closed by this.`,$i].join(`
|
|
836
836
|
`)}var ij=r=>`${r.provider}:${r.issue.toLowerCase()}:${r.kind}:${r.changes.map(e=>e.commit??e.ref).sort().join(",")}`;async function gI(r){let{settings:e,store:t,log:n}=r,s=r.now??Date.now(),i={projects:0,drifts:0,told:0,written:0,errors:[]};if(!e.enabled)return i;let o=[];for(let a of e.projects){i.projects++;let c=await uI(a,{...r,now:s});i.errors.push(...c.errors);for(let d of c.errors)n(`[status-drift] ${d}`);for(let d of c.drifts){i.drifts++;let l=ij(d),u=t.see(l,d.issue,d.kind,d.line,s);u.toldAt===null&&(n(`[status-drift] ${d.line}`),o.push({key:l,drift:d})),e.write&&d.kind==="live-not-done"&&e.writeProjects.some(g=>g.toLowerCase()===d.project.toLowerCase())&&r.writeIssue&&u.writtenAt===null&&u.writeTries<3&&await aj(d,l,r,s)&&i.written++}}if(o.length){for(let a of o)t.told(a.key,s);if(r.tell){let a=o.length;try{await r.tell(`Status drift: ${a} issue${a===1?"":"s"} not where the work is`,o.map(c=>c.drift.line).join(`
|
|
837
837
|
`)),i.told=a}catch(c){for(let d of o)t.told(d.key,null);n(`[status-drift] couldn't tell the owner, will try again: ${c?.message??c}`)}}else i.told=o.length}try{t.prune(s)}catch(a){n(`[status-drift] retention failed: ${a?.message??a}`)}return i}var ou=6e4;function oj(r,e){let t=r.statusLabels.some(n=>n.includes("::"));return e.find(n=>n.includes("::")===t)??e[0]}async function aj(r,e,t,n){let s=oj(r,t.settings.labels.done);if(!s)return!1;let i={addLabels:[s],removeLabels:r.statusLabels.filter(o=>o.toLowerCase()!==s.toLowerCase()),note:hI(r,s)};try{let o,a=await Promise.race([t.writeIssue({provider:r.provider,project:r.project,number:r.number,url:r.issueUrl},i),new Promise(d=>{o=setTimeout(()=>d("timeout"),ou)})]).finally(()=>clearTimeout(o));if(a==="timeout")return t.store.writeUnknown(e,`no answer in ${ou/1e3} s, not tried again`),t.log(`[status-drift] ${r.issue}: no answer in ${ou/1e3} s moving it to ${s}; not tried again, check it by hand`),!1;if(a.attempts.some(d=>/^(PUT|PATCH) issue$/.test(d.kind)&&d.ok))return t.store.written(e,n),a.ok||t.log(`[status-drift] ${r.issue}: label moved, its note failed: ${JSON.stringify(a.attempts)}`),t.log(`[status-drift] ${r.issue} moved to ${s}${i.removeLabels.length?` (removed ${i.removeLabels.join(", ")})`:""}`),!0;t.store.writeFailed(e,a.error??"the write failed"),t.log(`[status-drift] ${r.issue}: could not move it to ${s}: ${a.error??JSON.stringify(a.attempts)}`)}catch(o){t.store.writeFailed(e,String(o?.message??o)),t.log(`[status-drift] ${r.issue}: could not move it to ${s}: ${o?.message??o}`)}return!1}function fI(r,e=fetch){let t=async(o,a)=>{let c;try{c=await e(o,{headers:a,signal:AbortSignal.timeout(15e3)})}catch(d){return{ok:!1,error:`could not be reached: ${String(d?.message??d).slice(0,200)}`}}return c.ok?{ok:!0,body:await c.json().catch(()=>null)}:{ok:!1,status:c.status,error:c.status===404?"not found (or not visible to the connector)":`HTTP ${c.status}`}},n=()=>{let o=r.github;return o?{api:o.apiUrl.replace(/\/$/,""),headers:{Accept:"application/vnd.github+json",...o.token?{Authorization:`Bearer ${o.token}`}:{}}}:null},s=o=>{let a=r.gitlab;return a?{base:`${a.url.replace(/\/$/,"")}/api/v4/projects/${encodeURIComponent(o)}`,headers:a.token?{"PRIVATE-TOKEN":a.token}:{}}:null},i=async(o,a)=>{let c=await t(o,a);return c.ok&&typeof c.body?.default_branch=="string"&&c.body.default_branch?c.body.default_branch:null};return{async merged(o,a,c){let d=[];if(o==="gitlab"){let l=s(a);if(!l)return{error:"no gitlab connector on this node"};let u=encodeURIComponent(new Date(c).toISOString()),h=await i(`${l.base}`,l.headers);for(let g=1;g<=3;g++){let y=await t(`${l.base}/merge_requests?state=merged&updated_after=${u}&order_by=updated_at&sort=desc&per_page=100&page=${g}`,l.headers);if(!y.ok)return{error:y.error};let p=Array.isArray(y.body)?y.body:[];for(let w of p){let b=Date.parse(w?.merged_at??"");b>=c&&(h&&w?.target_branch!==h||d.push({ref:`${a}!${w.iid}`,url:String(w.web_url??""),title:String(w.title??""),description:String(w.description??""),branch:String(w.source_branch??""),commit:w.merge_commit_sha||w.squash_commit_sha||w.sha||null,mergedAt:b}))}if(p.length<100)break}}else{let l=n();if(!l)return{error:"no github connector on this node"};let u=await i(`${l.api}/repos/${a}`,l.headers);e:for(let h=1;h<=3;h++){let g=await t(`${l.api}/repos/${a}/pulls?state=closed&sort=updated&direction=desc&per_page=100&page=${h}`,l.headers);if(!g.ok)return{error:g.error};let y=Array.isArray(g.body)?g.body:[];for(let p of y){if(Date.parse(p?.updated_at??"")<c)break e;let w=Date.parse(p?.merged_at??"");w>=c&&(u&&p?.base?.ref!==u||d.push({ref:`${a}#${p.number}`,url:String(p.html_url??""),title:String(p.title??""),description:String(p.body??""),branch:String(p.head?.ref??""),commit:p.merge_commit_sha||null,mergedAt:w}))}if(y.length<100)break}}return d.sort((l,u)=>u.mergedAt-l.mergedAt)},async contains(o,a,c,d){if(pI(c,d))return!0;if(o==="gitlab"){let g=s(a);if(!g)return null;let y=await t(`${g.base}/repository/merge_base?refs[]=${encodeURIComponent(c)}&refs[]=${encodeURIComponent(d)}`,g.headers);return!y.ok||typeof y.body?.id!="string"?null:pI(y.body.id,c)}let l=n();if(!l)return null;let u=await t(`${l.api}/repos/${a}/compare/${encodeURIComponent(c)}...${encodeURIComponent(d)}`,l.headers);if(!u.ok)return null;let h=u.body?.status;return h==="ahead"||h==="identical"?!0:h==="behind"||h==="diverged"?!1:null},async reopenedAt(o,a,c){let d=null;for(let l=1;l<=3;l++){let u,h;if(o==="gitlab"){let y=s(a);if(!y)return{error:"no gitlab connector on this node"};u=await t(`${y.base}/issues/${c}/resource_state_events?per_page=100&page=${l}`,y.headers),h=p=>p?.state==="reopened"}else{let y=n();if(!y)return{error:"no github connector on this node"};u=await t(`${y.api}/repos/${a}/issues/${c}/events?per_page=100&page=${l}`,y.headers),h=p=>p?.event==="reopened"}if(!u.ok)return{error:u.error};let g=Array.isArray(u.body)?u.body:[];for(let y of g){let p=Date.parse(y?.created_at??"");h(y)&&p>(d??0)&&(d=p)}if(g.length<100)return d}return{error:`more than ${3*100} events, the last reopen is not known`}}}}function pI(r,e){let t=r.trim().toLowerCase(),n=e.trim().toLowerCase();return t.length>=7&&n.length>=7&&(t.startsWith(n)||n.startsWith(t))}rc();import{randomUUID as cj}from"crypto";var mI=new Set(["gitlab","github"]),dj=/:(issue|merge_request|pull):\d+$/,au=5,lj=12e4,yI=864e5,wI=6e4,Oo=r=>r.toLowerCase().split("@")[0],cu=class{constructor(e,t,n){this.store=e;this.settings=t;this.deps=n;this.now=n.now??Date.now,this.bootAt=this.now();for(let s of e.open())s.state!=="queued"&&!s.turnLive||(this.orphans.add(s.id),s.turnLive&&e.set(s.id,{turnLive:!1},this.bootAt))}now;bootAt;orphans=new Set;writes=new Map;on(e,t){return mI.has(Oo(e))&&!dj.test(t)?!1:this.settings().channels.map(Oo).includes(Oo(e))}guard(e,t){try{t()}catch(n){this.deps.log(`[status] ${e} failed: ${n?.message??n}`)}}change(e,t){this.store.set(e,t,this.now()),this.orphans.delete(e),this.push(e)}queued(e){this.guard("queued",()=>{if(!e.humanRoot||!this.on(e.channel,e.chatId)||this.store.inChat(e.agentId,e.channel,e.chatId,"queued"))return;let t=`req-q-${cj()}`;this.store.add({id:t,channel:e.channel,chatId:e.chatId,agentId:e.agentId,senderId:e.sender?.id??e.sender?.username??null,state:"queued",now:this.now()}),this.push(t)})}taskStarted(e){e.taskId&&this.guard("start",()=>{let t=e.resumedFrom?this.store.byRef("run",e.resumedFrom):null;if(t){this.store.ref(t.id,"run",e.taskId),Ft.includes(t.state)||this.change(t.id,{state:t.pending>0?"waiting":"working",turnLive:!0});return}if(!this.on(e.channel,e.chatId))return;let n=this.store.inChat(e.agentId,e.channel,e.chatId,"queued");if(n){this.store.ref(n.id,"run",e.taskId),this.change(n.id,{state:"working",turnLive:!0});return}if(!e.humanRoot)return;let s=`req-${e.taskId}`;this.store.add({id:s,channel:e.channel,chatId:e.chatId,agentId:e.agentId,senderId:e.sender?.id??e.sender?.username??null,state:"working",now:this.now()}),this.store.ref(s,"run",e.taskId),this.push(s)})}queueEnded(e){this.guard("queue end",()=>{let t=this.store.inChat(e.agentId,e.channel,e.chatId,"queued");t&&t.createdAt<=e.flushedAt&&this.change(t.id,{state:"failed"})})}taskCompleted(e){e.taskId&&this.guard("end",()=>{let t=this.store.byRef("run",e.taskId);if(!t||Ft.includes(t.state)||e.interrupted)return;let n;e.error?n=e.errorKind==="cancelled"||e.errorKind==="stopped"||e.stopped?"stopped":/\btimed? ?out\b|timeout/i.test(e.error)?"timed_out":"failed":n=t.pending>0?"waiting":"done",this.change(t.id,{state:n,turnLive:!1})})}delegationStarted(e){this.guard("delegation start",()=>{let t=this.store.inChat(e.caller,e.origin.channel,e.origin.chatId,"live");t&&(this.store.ref(t.id,"delegation",e.id),this.change(t.id,{state:"waiting",waitingOn:e.callee,pending:t.pending+1}))})}delegationDone(e,t,n){this.guard("delegation end",()=>{let s=this.store.byRef("delegation",e.id);if(t==="waiting"){if(!s||Ft.includes(s.state))return;let i=this.settings(),o=n??this.now()+(i.waitDefaultMinutes??120)*wI;this.store.wait(e.id,s.id,o+(i.waitGraceMinutes??30)*wI),this.change(s.id,{state:"waiting",waitingOn:e.callee});return}this.handedBack(s,t)})}waitEnded(e,t){this.guard("wait end",()=>{this.store.endWait(e)&&this.handedBack(this.store.byRef("delegation",e),t)})}cardRaised(e,t){t&&this.guard("card",()=>{let n=this.store.inChat(e.raised_by,t.channel,t.chatId,"live");n&&(this.store.ref(n.id,"card",e.id),this.change(n.id,{state:"waiting",waitingOn:"an answer from the owner",pending:n.pending+1}))})}cardResolved(e){this.guard("card result",()=>{let t=e.status==="decided"||e.status==="resolved";this.handedBack(this.store.byRef("card",e.id),t?"done":"timeout")})}handedBack(e,t){if(!e||Ft.includes(e.state))return;let n=e.pending-1;if(n>0){this.change(e.id,{pending:n});return}if(e.turnLive){this.change(e.id,{state:"working",pending:n});return}let s={done:"done",error:"failed",timeout:"timed_out",lost:"restart"}[t];this.change(e.id,{state:s,pending:n})}resumeOutcome(e){this.guard("restart",()=>{if(e.decision!=="reported"&&e.decision!=="resume-failed")return;let t=this.store.byRef("run",e.taskId);t&&!Ft.includes(t.state)&&this.change(t.id,{state:"restart",turnLive:!1})})}sweep(){let e=this.now();this.guard("restart check",()=>{if(!(this.orphans.size===0||e-this.bootAt<lj)){for(let t of[...this.orphans]){let n=this.store.get(t);n&&!n.turnLive&&(n.state==="queued"||n.state==="working")&&this.change(t,{state:"restart"})}this.orphans.clear()}}),this.guard("waits",()=>{for(let t of this.store.overdueWaits(e))this.waitEnded(t,"timeout")}),this.guard("catch up",()=>{for(let t of this.store.changedSince(e-yI))t.shown!==Ud(t)&&t.writeFails<au&&this.push(t.id)}),this.guard("retention",()=>{this.store.prune(e-this.settings().retentionDays*yI)})}async idle(){for(;this.writes.size;)await Promise.all(this.writes.values())}push(e){let t=(this.writes.get(e)??Promise.resolve()).then(()=>this.write(e)).catch(n=>this.deps.log(`[status] comment for ${e} failed: ${n?.message??n}`)).finally(()=>{this.writes.get(e)===t&&this.writes.delete(e)});this.writes.set(e,t)}async write(e){let t=this.store.get(e);if(!t||!mI.has(Oo(t.channel)))return;let n=Ud(t);if(n===t.shown)return;let s="";try{t.commentRef?await this.deps.edit(t,t.commentRef,n)&&(s=t.commentRef):s=await this.deps.post(t,n)}catch(i){this.deps.log(`[status] comment for ${e} failed: ${i?.message??i}`)}if(s){this.store.posted(e,s,n);return}this.store.writeFailed(e)===au&&this.deps.log(`[status] comment for ${e} on ${t.channel} ${t.chatId} could not be written ${au} times; not retried until its state changes`)}};function bI(r,e,t){let n=new cu(new Si(r),e,t),s=B(),i=n.queued.bind(n),o=n.taskStarted.bind(n),a=n.taskCompleted.bind(n),c=n.queueEnded.bind(n);return s.on("task:queued",i),s.on("task:queue-ended",c),s.on("task:started",o),s.on("task:completed",a),{board:n,detach:()=>{s.off("task:queued",i),s.off("task:queue-ended",c),s.off("task:started",o),s.off("task:completed",a)}}}import{mkdirSync as uj,readFileSync as hj,renameSync as gj,writeFileSync as pj}from"fs";import{dirname as fj,resolve as mj}from"path";function Do(r){return mj(r,".agentx","reminders","claims.json")}function No(r){try{let e=JSON.parse(hj(r,"utf-8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function kI(r,e){uj(fj(r),{recursive:!0});let t=`${r}.${process.pid}.tmp`;pj(t,JSON.stringify(e,null,2)+`
|
|
@@ -1394,4 +1394,4 @@ data: ${JSON.stringify(F)}
|
|
|
1394
1394
|
`)}catch{}},G=setInterval(()=>{try{t.write(`: ping
|
|
1395
1395
|
|
|
1396
1396
|
`)}catch{}},15e3);G.unref?.();let K=new AbortController;t.on("close",()=>{t.writableEnded||K.abort()});try{for await(let Y of this.mesh.sendTaskStream(f.peer,f.message,f.agent,{context:f.context,signal:K.signal,vouchOwner:x}))U(Y.event,Y.data)}catch(Y){U("error",{error:Y?.message??String(Y)})}finally{clearInterval(G);try{t.end()}catch{}}break}let _=f.context,O=typeof f.senderAgentId=="string"?f.senderAgentId:void 0;if(fh(f,!0)==="callback"){let U=this.delegationGate(e,f,{callee:f.agent,peer:f.peer,message:f.message,calleeContext:_});if(!("track"in U)){let G=Ca(U);this.json(t,G.status,G.body);break}}if(f.async===!0){let U=_?.channel,G=_?.chatId;if(!U||!G){this.json(t,400,{error:"async requires context.channel and context.chatId \u2014 there is no route back otherwise"});return}let K=`mesh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;this.json(t,202,{accepted:!0,taskId:K,deliverTo:`${U}:${G}`,note:"result will be delivered to the originating chat when the peer finishes"});let Y=f.peer,F=f.agent,z=this.mesh;(async()=>{let te=Date.now(),Q;try{Q=await z.sendTask(Y,f.message,F,{vouchOwner:x,context:_,senderAgentId:O}),this.log(`[mesh/task async ${K}] ${Y}/${F??"default"} finished in ${Date.now()-te}ms`)}catch(me){Q=`Delegation to ${Y}/${F??"default"} failed: ${me?.message??me}`,this.log(`[mesh/task async ${K}] failed: ${me?.message??me}`)}try{await this.router.sendOutbound({channel:U,chatId:G,text:Q,agentId:_?.agentId??O,accountId:_?.accountId})}catch(me){this.log(`[mesh/task async ${K}] delivery failed: ${me?.message??me}`)}})();break}let j=await this.mesh.sendTask(f.peer,f.message,f.agent,{context:_,senderAgentId:O,vouchOwner:x});this.json(t,200,{response:j});break}case"POST /webrtc/signal/out":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let m=await q(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 q(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 f=await q(e),m=f.callId,k=f.target,$=f.agentId||this.config.channels.webrtc?.bot.defaultAgentId;if(!m||!k||!$){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:$});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 f=this.config.channels.webrtc;if(!f?.enabled){this.json(t,404,{error:"WebRTC signaling not enabled"});return}this.json(t,200,{localName:this.config.node.name,iceServers:[...f.stunServers.map(m=>({urls:m})),...f.turnServers],peers:this.mesh?.directory().map(m=>({name:m.peer,healthy:m.healthy}))||[],camera:f.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(f=>{let m=this.config.agents[f.id]||{},k=typeof m.description=="string"&&m.description.trim()||vq(m.systemPrompt)||`Agent "${f.name}" (${f.tier})`,$=Array.isArray(m.mentions)?m.mentions.slice(0,4):[];return{id:f.id,name:f.name,description:k,tags:[f.tier,...$],color:Se(f.id,m).color}}),channels:this.router.getChannelNames(),githubLogins:this.github?.postingAccounts()??[],defaultInputModes:["text"],defaultOutputModes:["text"]});break;case"GET /wiki/agents":{let f=this.registry.getWikiHub();this.json(t,200,{nodeId:this.config.node.id,agents:f.summary()});break}case"GET /wiki/entries":{let f=this.registry.getWikiHub(),m=n.searchParams.get("agent")||void 0,k=n.searchParams.get("after")||void 0,$=m?f.getAgentEntries(m):f.getSharedStore().listEntries({after:k});this.json(t,200,{nodeId:this.config.node.id,count:$.length,entries:$.map(I=>({id:I.id,date:I.date,agentId:I.agentId,source:I.source,sourceContext:I.sourceContext,content:I.content}))});break}case"GET /wiki/articles":{let f=this.registry.getWikiHub(),m=n.searchParams.get("agent");if(!m){this.json(t,400,{error:"?agent= required"});break}let $=f.getAgentWiki(m).rebuildIndex();this.json(t,200,{nodeId:this.config.node.id,agentId:m,articles:$.articles});break}case"GET /wiki/article":{let f=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=f.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:f}=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 f(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:f,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 $=await q(e),I=m({...$,to:k.inbox});if("error"in I){this.json(t,400,{error:I.error});break}let x=I.note;if(this.registry.getAgent(k.inbox)){try{let{note:_,added:O}=new f(this.registry.getWikiHub().getBaseDir()).add(x);this.json(t,O?201:200,{ok:!0,added:O,note:_,node:this.config.node.id})}catch(_){this.json(t,507,{error:_?.message??String(_)})}break}if($.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 L=this.mesh.directory().find(_=>_.peer===D.peer)?.peerUrl;if(!D.healthy||!L){this.json(t,503,{error:`the node hosting "${k.inbox}" (${D.peer}) is unreachable; try again later`});break}try{let _=await fetch(`${L.replace(/\/$/,"")}/wiki/notes`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(D.peer)},body:JSON.stringify({...x,fromNode:x.fromNode||this.config.node.id,forwarded:!0}),signal:AbortSignal.timeout(1e4)}),O=await _.json().catch(()=>({}));this.json(t,_.status,{...O,peer:D.peer})}catch(_){this.json(t,502,{error:`forward to ${D.peer} failed: ${_?.message??_}`,peer:D.peer})}break}case"GET /graph/schema":{let f=this.registry.getGraphStore();if(!f){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,schema:f.loadSchema()});break}case"GET /graph/nodes":{let f=this.registry.getGraphStore();if(!f){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,...f.loadNodes()});break}case"GET /graph/classifications":{let f=this.registry.getGraphStore();if(!f){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)),$=f.listByStatus(m,k);this.json(t,200,{nodeId:this.config.node.id,status:m,count:$.length,classifications:$});break}default:this.json(t,404,{error:"Not found",endpoints:["GET /health","GET /agents","GET /crons","GET /routines \u2014 schedules + cron/hook workflows with staleness flags","GET /mesh","GET /wiki/agents","GET /wiki/entries[?agent=X&after=YYYY-MM-DD]","GET /wiki/articles?agent=X","GET /wiki/notes[?status=waiting|open|patched|rejected|deferred|expired|all&limit=N]","POST /wiki/notes { from, change, source, date? } \u2014 a note for the wiki observe/sweep run","GET /graph/schema","GET /graph/nodes","GET /graph/classifications[?status=approved|pending|rejected&limit=N]","POST /task { agent, message, context?, freshSession?: bool }","GET /agents/:id \u2014 resolved agent config (permission, tier, model, persistentProcess, toolUseRequired)","POST /agents/:id/selftest { message? } \u2014 canary probe; runs a fresh-session task and reports {ok, durationMs, tokens, billedModel}","GET /traces[?agentId=&channel=&chatId=&workflowRunId=&status=&since=&until=&limit=]","GET /traces/:taskId \u2014 full per-task execution trace (steps + tokens)","GET /voice/history[?agent=&limit=&before=] \u2014 past voice exchanges, bounded summaries","GET /voice/history/:id \u2014 one voice exchange in full; POST /voice/history/:id/replay","GET /api/processes \u2014 live persistent claude processes (JSON)","POST /api/processes/kill { agentId, channel, chatId, reason? }","GET /api/actions/builtin \u2014 list shipped built-in typed actions","POST /api/actions/builtin/:name \u2014 run a built-in with JSON body input","POST /mesh/task { peer, message }","POST /webhook/:agentId[/:source] \u2014 webhook callback","POST /reload \u2014 re-read agentx.json (hot-swaps crons)","GET /usage/plan \u2014 Claude plan windows, cold-dispatch counters, active holds","POST /usage/plan/lift \u2014 drop the active Claude plan holds","GET /daemon/restart \u2014 in-flight count, service manager, pending restart","POST /daemon/restart \u2014 restart when idle { timeoutMinutes?, onTimeout? }","POST /daemon/restart/cancel","GET /.well-known/agent-card.json","GET /call \u2014 browser UI for P2P A/V calls (requires channels.webrtc.enabled)","GET /webrtc/config \u2014 ICE servers + peer directory for the call page","GET /webrtc/events?callId=&as= \u2014 SSE stream of signaling events","POST /webrtc/signal/out \u2014 browser-originated signal, forwarded to remote peer","POST /webrtc/signal \u2014 remote-peer-originated signal, fanned out to local browser","POST /webrtc/bot/invite { callId, target, agentId } \u2014 spawn a transcribing bot peer for a call","GET /webrtc/bots \u2014 active bot sessions","POST /webrtc/camera/watch { callId, agentId } \u2014 an agent watches the phone camera share","GET /webrtc/camera/watch \u2014 agents watching a camera now","POST /webrtc/camera/watch/:id/look { note? } \u2014 ask the watching agent what it sees","POST /webrtc/camera/watch/:id/stream { seconds, note? } \u2014 the agent keeps watching for a while (0 stops)","POST /webrtc/camera/look { agentId } \u2014 from an agent's run: the newest frame as a PNG path"]})}}catch(i){this.json(t,500,{error:i.message})}}async handleOpenAICompat(e,t,n){let s=await q(e);await dv(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 d=this.registry.list().find(l=>l.id===i)?.runningTasks.filter(l=>l.channel===o&&l.chatId===a)||[];for(let l of d)this.registry.cancelRunningTask(l.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){return cp(this.config,e)}resolveTodayUsage(){let e=Hv();if(e==="json")return this.registry.getTodayUsage();let t=Gv(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||!Fn(n)))try{let s=ne(n,".claude","skills");TE(s,{recursive:!0});let i=ne(s,LT);if(!Fn(i))Oh(i,Su(e)),this.log(` memory-skill: installed remember.md \u2192 ${t.id}`);else{let o=WT(sr(i,"utf-8"),e);o&&(Oh(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||!Fn(n))continue;let s=this.config.workflows.enabled&&(this.config.workflows.followUp.enabled&&(this.config.workflows.followUp.agents[e]??!0)||cm(this.config.workflows,e)),i=kf(gp(t),this.config.requests.enabled||Gt(this.config.requests)||s?bf():null);try{switch(vf(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 dT(e,t,n,s,{mem:this.agentMemory,workspaceFor:i=>this.workspaceFor(i),runningTaskOwner:i=>this.registry.runningTaskOwner(i),indexMaxChars:()=>this.config.session.memoryIndexMaxChars})}async wakeWorkflows(e){try{await this.workflowDispatcher?.wake(e)}catch(n){this.log(`[workflows] wake failed: ${n.message}`)}let t=this.mesh?.directory().filter(n=>n.healthy)??[];await Promise.allSettled(t.map(async n=>{try{let s=await fetch(`${n.peerUrl}/workflow/event`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(n.peer)},body:JSON.stringify({kind:"wake",fromPeer:this.config.node.id,wake:e}),signal:AbortSignal.timeout(5e3)});s.ok||this.log(`[workflows/mesh] wake ${n.peer} -> ${s.status}`)}catch(s){this.log(`[workflows/mesh] wake ${n.peer} failed: ${s.message}`)}}))}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 ie(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}if(n?.kind==="wake"){let c=Tf(n.wake);if(!c){this.json(t,400,{error:"invalid wake"});return}let d=await this.workflowDispatcher.wake(c);this.json(t,202,{ok:!0,mode:"wake",results:d});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 g=await this.workflowDispatcher.dispatch({trigger:s.trigger,entityRef:o,event:i,fromRemote:{peer:h}});this.log(`[workflows/mesh] dispatched broadcast: matched=${g.claimed.length} ${g.claimed.length?`(${g.claimed.map(y=>y.id).join(", ")})`:"[none \u2014 no workflow with mesh.allowRemote matched]"}`),this.json(t,202,{ok:!0,mode:"trigger-broadcast",matched:g.claimed.map(y=>y.id)});return}let l=(s.workflowId?this.workflowStore?.get(s.workflowId):null)?.nodes.find(h=>h.type.startsWith("trigger."))?.config??{},u={source:String(l.source??"hook"),project:l.filter?.project,repo:l.filter?.repo,chat:l.filter?.chat,labels:l.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 ie(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let{handlePushBridge:s,pushOrigin:i}=await import("./push-bridge-T5HZZRA2.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 Gy(String(e.headers.authorization||""),this.config.mesh.peers,process.env.MESH_TOKEN)}async handleChannelSend(e,t){let n;try{n=await ie(e)}catch(d){this.json(t,400,{error:"invalid JSON body",message:d.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 d=this.pushBridgeCaller(e);if("origin"in d)c=d.origin;else if(i!=="default"){this.json(t,403,{error:d.error});return}}if(s==="push"&&i.includes(":")){let{scopedPushTarget:d}=await import("./push-bridge-T5HZZRA2.js"),l=d(i,this.pushBridgeCaller(e));if("error"in l){this.json(t,403,{error:l.error});return}}try{let d=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,open:typeof n.open=="string"&&n.open.startsWith("/")?n.open: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:d??null})}catch(d){this.log(`[mesh] /channel/send "${s}" failed: ${d.message}`),this.json(t,500,{error:d.message})}}async handleChannelChats(e,t,n={}){let s=new Set,i=[],o=[],a=(d,l)=>{let u=0;for(let h of d)!h.id||s.has(h.id)||(s.add(h.id),i.push({...h,source:l}),u++);u>0&&o.push(`${l}:${u}`)},c=this.router.getChannel(t);if(c?.listKnownChats)try{a(c.listKnownChats(),"local")}catch{}else if(c?.listChats)try{a(c.listChats().map(d=>({id:d.jid,name:d.name,kind:d.isGroup?"group":"dm"})),"local")}catch{}if(!n.localOnly&&this.mesh){let d=this.mesh.directory().filter(l=>l.healthy&&l.channels?.includes(t));await Promise.allSettled(d.map(async l=>{try{let u=await fetch(`${l.peerUrl}/channels/${encodeURIComponent(t)}/chats?local=1`,{headers:this.mesh.authHeaders(l.peer),signal:AbortSignal.timeout(5e3)});if(!u.ok)return;let h=await u.json();Array.isArray(h.chats)&&a(h.chats.map(g=>({id:g.id,name:g.name,kind:g.kind??"dm",accountId:g.accountId})),`mesh:${l.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 ie(e)}catch{s={}}try{let i=await NT({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})}}},Dh=Nh;Yt(Dh,"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 vq(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 ie(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 Sq(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 q(r){return new Promise((e,t)=>{let n="";r.on("data",s=>n+=s.toString()),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch{e({})}}),r.on("error",t)})}function AE(r){let e=r.business;return JSON.stringify([e?.roles,e?.orgChart,e?.relations,e?.projects,(r.people??[]).map(t=>t.id),[...Vn(r)]])}xE();function Vne(r){typeof r=="string"&&(or.error(r),process.exit(1)),r instanceof Error&&(or.error(r.message),process.exit(1)),or.error("Something went wrong. Please try again."),process.exit(1)}export{Uq as a,Sd as b,Ot as c,gs as d,fs as e,Lt as f,mi as g,vk as h,zB as i,Ev as j,lM as k,uM as l,Ov as m,Ne as n,jv as o,Wv as p,Ui as q,nX as r,sX as s,no as t,NJ as u,_D as v,MD as w,Al as x,r0 as y,LJ as z,p0 as A,DD as B,f0 as C,m0 as D,y0 as E,jJ as F,WJ as G,FJ as H,co as I,_l as J,B0 as K,je as L,y3 as M,cL as N,J$ as O,V$ as P,QL as Q,uI as R,fI as S,Fj as T,pu as U,IK as V,TK as W,AK as X,wT as Y,vW as Z,PK as _,_K as $,PT as aa,js as ba,Pn as ca,Ws as da,m5 as ea,Pu as fa,CF as ga,PF as ha,dz as ia,Qo as ja,Lu as ka,ju as la,sa as ma,Se as na,ZA as oa,Bs as pa,OU as qa,gx as ra,NU as sa,yx as ta,la as ua,Vs as va,pa as wa,ma as xa,$x as ya,eh as za,Cx as Aa,kt as Ba,Ce as Ca,dh as Da,Nx as Ea,Lx as Fa,jx as Ga,Wx as Ha,ja as Ia,NR as Ja,Th as Ka,jR as La,I2 as Ma,F9 as Na,Dh as Oa,Vne as Pa};
|
|
1397
|
-
//# sourceMappingURL=chunk-
|
|
1397
|
+
//# sourceMappingURL=chunk-ZFMUF3NU.js.map
|