agentix-cli 0.53.0 → 0.55.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/apps/mac-voice/Sources/AgentXVoice/AgentClient.swift +26 -0
- package/apps/mac-voice/Sources/AgentXVoice/StatusMenu.swift +55 -3
- package/apps/mac-voice/Sources/AgentXVoice/main.swift +136 -13
- package/dist/{App-R62ZQVSF.js → App-4EM7IPB3.js} +2 -2
- package/dist/{ChatApp-AS567EFE.js → ChatApp-FYTEEGSU.js} +2 -2
- package/dist/{agent-H4NB4BUA.js → agent-RZ46ZB4W.js} +2 -2
- package/dist/{board-dashboard-E3MUVNVQ.js → board-dashboard-NRRYCDZW.js} +1097 -215
- package/dist/board-dashboard-NRRYCDZW.js.map +1 -0
- package/dist/chunk-2D3RYIDU.js +3 -0
- package/dist/chunk-2D3RYIDU.js.map +1 -0
- package/dist/{chunk-KB7YIM3W.js → chunk-4HEVSWO3.js} +2 -2
- package/dist/{chunk-7DPKPBRJ.js → chunk-6AK6WKE5.js} +2 -2
- package/dist/{chunk-TH5KNJLA.js → chunk-723K4SAW.js} +2 -2
- package/dist/{chunk-OMTRHHZJ.js → chunk-76AHNHWC.js} +44 -45
- package/dist/chunk-76AHNHWC.js.map +1 -0
- package/dist/{chunk-KJWBQZT7.js → chunk-C3VRBEJ7.js} +2 -2
- package/dist/{chunk-C5JXPMTW.js → chunk-CELYD5QW.js} +2 -2
- package/dist/{chunk-FSZXY53Z.js → chunk-D3LSPFHK.js} +2 -2
- package/dist/chunk-EJ5ISSWW.js +151 -0
- package/dist/chunk-EJ5ISSWW.js.map +1 -0
- package/dist/{chunk-FS4WBYY3.js → chunk-EZN2YXRY.js} +2 -2
- package/dist/{chunk-QU6ZUKAD.js → chunk-GSOL2LW6.js} +2 -2
- package/dist/{chunk-7OWXFLAM.js → chunk-JC5Q5MPI.js} +171 -164
- package/dist/chunk-JC5Q5MPI.js.map +1 -0
- package/dist/{chunk-SABOPOYX.js → chunk-K4RDE6YU.js} +211 -197
- package/dist/chunk-K4RDE6YU.js.map +1 -0
- package/dist/{ntfy-ZY2NPGBA.js → chunk-KZKDVIOE.js} +3 -3
- package/dist/chunk-KZKDVIOE.js.map +1 -0
- package/dist/{chunk-VD4TMPJI.js → chunk-LKJSPO3S.js} +2 -2
- package/dist/{chunk-NF52Q3TV.js → chunk-M4AG2YNX.js} +2 -2
- package/dist/{chunk-WKTFP3SK.js → chunk-NO2HOK4B.js} +2 -2
- package/dist/{chunk-KFG6WWFS.js → chunk-O3XG2NVR.js} +18 -18
- package/dist/{chunk-KFG6WWFS.js.map → chunk-O3XG2NVR.js.map} +1 -1
- package/dist/chunk-QD6IICK7.js +2 -0
- package/dist/chunk-QD6IICK7.js.map +1 -0
- package/dist/{chunk-PGJL5V6Y.js → chunk-SA23V7WX.js} +2 -2
- package/dist/chunk-U4H35SJS.js +15 -0
- package/dist/chunk-U4H35SJS.js.map +1 -0
- package/dist/chunk-UIVHSYCN.js +29 -0
- package/dist/chunk-UIVHSYCN.js.map +1 -0
- package/dist/{chunk-6OOK7Y4S.js → chunk-W4YMMWJL.js} +2 -2
- package/dist/chunk-WOMQ2VGA.js +5 -0
- package/dist/{chunk-OV35MJKS.js.map → chunk-WOMQ2VGA.js.map} +1 -1
- package/dist/chunk-WWMFNLKD.js +10 -0
- package/dist/chunk-WWMFNLKD.js.map +1 -0
- package/dist/chunk-X5C5W3E4.js +3 -0
- package/dist/chunk-X5C5W3E4.js.map +1 -0
- package/dist/{chunk-CCMM5TP4.js → chunk-XEOAKD5C.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/client-IA7ZPE56.js +2 -0
- package/dist/{compaction-NWPBPWY2.js → compaction-H5U32UU6.js} +2 -2
- package/dist/config-HPN2F7LH.js +2 -0
- package/dist/config-mutator-7GPTMTVB.js +2 -0
- package/dist/doctor-IBWQVQV4.js +2 -0
- package/dist/index.d.ts +273 -19
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/memory-extract-F76BE6KA.js +2 -0
- package/dist/ntfy-52EXHVMD.js +2 -0
- package/dist/program-D5TAPSIH.js +2 -0
- package/dist/{promote-DJFMTLRC.js → promote-T4UJROEH.js} +2 -2
- package/dist/push-HEDA6P3B.js +2 -0
- package/dist/push-HEDA6P3B.js.map +1 -0
- package/dist/push-keys-2DTD7YNQ.js +2 -0
- package/dist/push-store-LXTYULUF.js +2 -0
- package/dist/query-VUJC4Y5O.js +2 -0
- package/dist/registry-DX2RI7I7.js +2 -0
- package/dist/{request-planner-2H7HCUCZ.js → request-planner-B7DE7VJR.js} +2 -2
- package/dist/{review-candidates-U7R64OCS.js → review-candidates-4YJHIBAF.js} +2 -2
- package/dist/routing-MZG3UODH.js +2 -0
- package/dist/schedule-tool-A4OFQ4YZ.js +2 -0
- package/dist/scheduler-RHJW2V4M.js +2 -0
- package/dist/scheduler-RHJW2V4M.js.map +1 -0
- package/dist/seat-2PEI7JRX.js +2 -0
- package/dist/seat-2PEI7JRX.js.map +1 -0
- package/dist/{select-XGK27RPP.js → select-4KIUR27O.js} +2 -2
- package/dist/{set-enabled-7YGN2FAZ.js → set-enabled-SE7HQKPF.js} +2 -2
- package/dist/subscriptions-RYVPHVIV.js +2 -0
- package/dist/subscriptions-RYVPHVIV.js.map +1 -0
- package/dist/{tool-HKDIZ6I4.js → tool-5VMD7IE4.js} +2 -2
- package/dist/wiki-2QFLAH4U.js +2 -0
- package/dist/wiki-2QFLAH4U.js.map +1 -0
- package/package.json +3 -1
- package/dist/board-dashboard-E3MUVNVQ.js.map +0 -1
- package/dist/chunk-47EEUZBK.js +0 -15
- package/dist/chunk-47EEUZBK.js.map +0 -1
- package/dist/chunk-7OWXFLAM.js.map +0 -1
- package/dist/chunk-D4HAR3L3.js +0 -28
- package/dist/chunk-D4HAR3L3.js.map +0 -1
- package/dist/chunk-HRBKSZ34.js +0 -2
- package/dist/chunk-HRBKSZ34.js.map +0 -1
- package/dist/chunk-IDYP7G7Z.js +0 -150
- package/dist/chunk-IDYP7G7Z.js.map +0 -1
- package/dist/chunk-OMTRHHZJ.js.map +0 -1
- package/dist/chunk-OV35MJKS.js +0 -5
- package/dist/chunk-SABOPOYX.js.map +0 -1
- package/dist/client-XTQDYMOX.js +0 -2
- package/dist/config-3SW4V44Z.js +0 -2
- package/dist/config-mutator-H32FXUYJ.js +0 -2
- package/dist/doctor-J6RCHFVE.js +0 -2
- package/dist/memory-extract-MGGXIZTE.js +0 -2
- package/dist/ntfy-ZY2NPGBA.js.map +0 -1
- package/dist/program-SQTOPCQW.js +0 -2
- package/dist/query-UAZUMU4N.js +0 -2
- package/dist/registry-4OUBA2TY.js +0 -2
- package/dist/routing-LVQH6WOJ.js +0 -2
- package/dist/schedule-tool-2BONJVCJ.js +0 -2
- package/dist/scheduler-7CEXDECA.js +0 -2
- package/dist/seat-2KGFNCIW.js +0 -2
- package/dist/wiki-6YT7B5HU.js +0 -2
- /package/dist/{App-R62ZQVSF.js.map → App-4EM7IPB3.js.map} +0 -0
- /package/dist/{ChatApp-AS567EFE.js.map → ChatApp-FYTEEGSU.js.map} +0 -0
- /package/dist/{agent-H4NB4BUA.js.map → agent-RZ46ZB4W.js.map} +0 -0
- /package/dist/{chunk-KB7YIM3W.js.map → chunk-4HEVSWO3.js.map} +0 -0
- /package/dist/{chunk-7DPKPBRJ.js.map → chunk-6AK6WKE5.js.map} +0 -0
- /package/dist/{chunk-TH5KNJLA.js.map → chunk-723K4SAW.js.map} +0 -0
- /package/dist/{chunk-KJWBQZT7.js.map → chunk-C3VRBEJ7.js.map} +0 -0
- /package/dist/{chunk-C5JXPMTW.js.map → chunk-CELYD5QW.js.map} +0 -0
- /package/dist/{chunk-FSZXY53Z.js.map → chunk-D3LSPFHK.js.map} +0 -0
- /package/dist/{chunk-FS4WBYY3.js.map → chunk-EZN2YXRY.js.map} +0 -0
- /package/dist/{chunk-QU6ZUKAD.js.map → chunk-GSOL2LW6.js.map} +0 -0
- /package/dist/{chunk-VD4TMPJI.js.map → chunk-LKJSPO3S.js.map} +0 -0
- /package/dist/{chunk-NF52Q3TV.js.map → chunk-M4AG2YNX.js.map} +0 -0
- /package/dist/{chunk-WKTFP3SK.js.map → chunk-NO2HOK4B.js.map} +0 -0
- /package/dist/{chunk-PGJL5V6Y.js.map → chunk-SA23V7WX.js.map} +0 -0
- /package/dist/{chunk-6OOK7Y4S.js.map → chunk-W4YMMWJL.js.map} +0 -0
- /package/dist/{chunk-CCMM5TP4.js.map → chunk-XEOAKD5C.js.map} +0 -0
- /package/dist/{client-XTQDYMOX.js.map → client-IA7ZPE56.js.map} +0 -0
- /package/dist/{compaction-NWPBPWY2.js.map → compaction-H5U32UU6.js.map} +0 -0
- /package/dist/{config-3SW4V44Z.js.map → config-HPN2F7LH.js.map} +0 -0
- /package/dist/{config-mutator-H32FXUYJ.js.map → config-mutator-7GPTMTVB.js.map} +0 -0
- /package/dist/{doctor-J6RCHFVE.js.map → doctor-IBWQVQV4.js.map} +0 -0
- /package/dist/{memory-extract-MGGXIZTE.js.map → memory-extract-F76BE6KA.js.map} +0 -0
- /package/dist/{program-SQTOPCQW.js.map → ntfy-52EXHVMD.js.map} +0 -0
- /package/dist/{promote-DJFMTLRC.js.map → program-D5TAPSIH.js.map} +0 -0
- /package/dist/{query-UAZUMU4N.js.map → promote-T4UJROEH.js.map} +0 -0
- /package/dist/{registry-4OUBA2TY.js.map → push-keys-2DTD7YNQ.js.map} +0 -0
- /package/dist/{routing-LVQH6WOJ.js.map → push-store-LXTYULUF.js.map} +0 -0
- /package/dist/{schedule-tool-2BONJVCJ.js.map → query-VUJC4Y5O.js.map} +0 -0
- /package/dist/{scheduler-7CEXDECA.js.map → registry-DX2RI7I7.js.map} +0 -0
- /package/dist/{request-planner-2H7HCUCZ.js.map → request-planner-B7DE7VJR.js.map} +0 -0
- /package/dist/{review-candidates-U7R64OCS.js.map → review-candidates-4YJHIBAF.js.map} +0 -0
- /package/dist/{seat-2KGFNCIW.js.map → routing-MZG3UODH.js.map} +0 -0
- /package/dist/{wiki-6YT7B5HU.js.map → schedule-tool-A4OFQ4YZ.js.map} +0 -0
- /package/dist/{select-XGK27RPP.js.map → select-4KIUR27O.js.map} +0 -0
- /package/dist/{set-enabled-7YGN2FAZ.js.map → set-enabled-SE7HQKPF.js.map} +0 -0
- /package/dist/{tool-HKDIZ6I4.js.map → tool-5VMD7IE4.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{b as Ce,c as Me}from"./chunk-WP6KLXTP.js";import{a as ee}from"./chunk-N6EWZGIX.js";import{b as Oe,e as We,f as je,i as Ee,k as Fe,l as De,q as _e}from"./chunk-O3XG2NVR.js";import{b as oe}from"./chunk-AFRHKA7B.js";import{a as xe,b as te,c as ne,d as Ne,e as re}from"./chunk-QD6IICK7.js";import{v as Te,w as Tt}from"./chunk-M4AG2YNX.js";import{b as Pe,f as Pt}from"./chunk-72SZI2UW.js";import{c as Re,d as $e}from"./chunk-QOYAX2FT.js";import{existsSync as xt,mkdirSync as Le,readFileSync as Nt,writeFileSync as Ot,renameSync as Wt}from"fs";import{resolve as He,dirname as jt}from"path";var Ue=class{filePath;log;constructor(e={}){let t=e.baseDir??He(process.cwd(),".agentx");this.filePath=He(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),Le(t,{recursive:!0})}key(e,t,n){return`${e}::${t}::${n||"-"}`}load(){if(!xt(this.filePath))return{version:1,overrides:{}};try{let e=Nt(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){Le(jt(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Ot(t,JSON.stringify(e,null,2)),Wt(t,this.filePath)}get(e,t,n){let i=this.load().overrides[this.key(e,t,n)];if(i&&!(i.expiresAt&&Date.parse(i.expiresAt)<Date.now()))return i}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),n={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(n.channel,n.chatId,n.accountId)]=n,this.save(t),n}remove(e,t,n){let o=this.load(),i=this.key(e,t,n);return i in o.overrides?(delete o.overrides[i],this.save(o),!0):!1}consumeSummary(e,t,n){let o=this.load(),i=o.overrides[this.key(e,t,n)];if(!i||!i.summary||i.summaryConsumedAt)return;let s=i.summary;return i.summaryConsumedAt=new Date().toISOString(),this.save(o),s}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(n=>!n.expiresAt||Date.parse(n.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(n=>n.toAgent===e),outgoing:t.filter(n=>n.fromAgent===e)}}};import{readFileSync as Et,writeFileSync as ie,appendFileSync as Ft,mkdirSync as Dt,existsSync as Ke}from"fs";import{resolve as se}from"path";var Be=200,Ct=7,ze=class{memoryDir;constructor(e=process.cwd()){this.memoryDir=se(e,".agentx/memory"),Ke(this.memoryDir)||Dt(this.memoryDir,{recursive:!0})}filePath(e){return se(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||te(t.content))return!1;let n=t.source.trust??xe(t.source.channel),o=t.review??Ne(n),i={...t,source:{...t.source,trust:n},...o?{review:o}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return Ft(this.filePath(e),JSON.stringify(i)+`
|
|
2
2
|
`),!0}getAll(e){let t=this.filePath(e);if(!Ke(t))return[];try{return Et(t,"utf-8").split(`
|
|
3
3
|
`).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return[]}}findRelevant(e,t,n=8){let o=this.getAll(t).filter(re);if(o.length===0)return[];let i=o.map(f=>`${f.keywords.join(" ")} ${f.content}`),s=se(this.memoryDir,`${t}_bm25_cache.json`),a=$e(i,s),d=Re(e,a),c=new Map(d.map(f=>[f.docIndex,f.score])),p=o.map((f,h)=>{let m=c.get(h)??0;return f.category==="commitment"&&(m+=1),{memory:f,score:m}}).filter(f=>f.score>0);if(p.length===0)return o.slice(-n);let g=p.sort((f,h)=>h.score-f.score).slice(0,n).map(f=>f.memory);if(g.length>0)try{this.recordAccess(t,g.map(f=>f.id))}catch{}return g}buildContext(e){let t=this.contextLines(e).map(n=>n.line);return t.length===0?"":["[Agent Memory \u2014 persistent facts from past conversations]",...t,"[End Memory]"].join(`
|
|
4
4
|
`)}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[],n=57;for(let o of e){let s=!o.source.chatId.startsWith("-")&&/^\d+$/.test(o.source.chatId)?"DM":o.source.chatId,a=`- [${o.category}] ${o.content} (${s}, ${o.source.date})`;if(n+a.length>2400)break;t.push({fact:o,line:a}),n+=a.length}return t}recordAccess(e,t){if(t.length===0)return;let n=this.getAll(e),o=new Set(t),i=!1;for(let s of n)if(o.has(s.id)){s.accessCount=(s.accessCount||0)+1,s.lastAccessed=new Date().toISOString();let a=s.intervalDays||1;s.intervalDays=Math.min(a*2,30),s.nextReview=new Date(Date.now()+s.intervalDays*864e5).toISOString(),i=!0}i&&ie(this.filePath(e),n.map(s=>JSON.stringify(s)).join(`
|
|
@@ -16,4 +16,4 @@ import{a as ee}from"./chunk-N6EWZGIX.js";import{b as Ce,c as Me}from"./chunk-WP6
|
|
|
16
16
|
`)}writeIndex(e,t){an(this.indexPath(e),JSON.stringify({runId:t,homeNode:this.nodeId,updatedAt:new Date().toISOString()},null,2)+`
|
|
17
17
|
`)}clearIndex(e){let t=this.indexPath(e);if(j(t))try{st(t)}catch{}}};import{existsSync as at,mkdirSync as cn,readFileSync as un,unlinkSync as ln,writeFileSync as pn}from"fs";import{resolve as ge}from"path";import{z as E}from"zod";var dt=E.object({version:E.literal(1),nodes:E.record(E.object({x:E.number(),y:E.number()}))}),me=class{baseDir;layoutsDir;constructor(e={}){this.baseDir=e.baseDir??ge(process.cwd(),".agentx/workflows"),this.layoutsDir=ge(this.baseDir,"_layouts"),cn(this.layoutsDir,{recursive:!0})}pathFor(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return ge(this.layoutsDir,`${t}.json`)}get(e){let t=this.pathFor(e);if(!at(t))return null;try{let n=dt.safeParse(JSON.parse(un(t,"utf-8")));return n.success?n.data:null}catch{return null}}save(e,t){let n=dt.parse(t);return pn(this.pathFor(e),JSON.stringify(n,null,2)+`
|
|
18
18
|
`),n}sync(e,t){let n=this.get(e);if(!n)return null;let o={};for(let s of t)n.nodes[s]&&(o[s]=n.nodes[s]);let i={version:1,nodes:o};return this.save(e,i)}delete(e){let t=this.pathFor(e);return at(t)?(ln(t),!0):!1}};function ct(r){return new Set(r.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function fn(r,e){if(r.size===0||e.size===0)return 0;let t=0;for(let n of r)e.has(n)&&t++;return t/Math.max(r.size,e.size)}function gn(r,e){let t=ct(r.message),n=e.filter(i=>i.state==="active"&&(i.status??"active")==="active"),o=null;for(let i of n){let s=0,a=[];if(i.ownerAgent&&i.ownerAgent===r.agentId&&(s+=.25,a.push("owner-agent")),r.channel&&i.tags.includes(r.channel)&&(s+=.15,a.push("channel-tag")),r.intentPath?.length&&i.intentPath.length){let p=r.intentPath.filter((g,f)=>i.intentPath[f]===g).length;p>0&&(s+=Math.min(.3,p*.1),a.push("intent-path"))}let d=[i.id,i.title,i.description??"",...i.tags].join(" "),c=fn(t,ct(d));c>0&&(s+=Math.min(.35,c),a.push("text-similarity")),(i.matchCount??0)>0&&(s+=Math.min(.1,i.matchCount*.01),a.push("prior-matches"));let l=Math.max(0,Math.min(1,s));(!o||l>o.confidence)&&(o={workflow:i,confidence:l,reasons:a})}return o&&o.confidence>0?o:null}function he(r){let{workflow:e,fromNodeId:t,selectedPort:n}=r,o=e.nodes.find(a=>a.id===t);if(!o)return{nextPending:[]};let i=e.edges.filter(a=>a.from===t);return{nextPending:(o.type==="branch"?i.filter(a=>(a.fromPort??"")===(n??"")):i).map(a=>a.to)}}function we(r,e){let t=r.config.cases??[],n=r.config.default??"";for(let o of t)if(mn(o.when,e))return o.to;return n}function mn(r,e){let t=r.params??{},n=String(t.path??""),o=z(e,n);switch(r.kind){case"equals":return o===t.value;case"contains":return typeof o=="string"?o.includes(String(t.value??"")):Array.isArray(o)?o.some(i=>i===t.value):!1;case"matches":{if(typeof o!="string")return!1;try{return new RegExp(String(t.regex??"")).test(o)}catch{return!1}}case"exists":return o!=null&&o!=="";default:return!1}}function z(r,e){if(!e)return;let t=e.split("."),n=r;for(let o of t){if(n==null||typeof n!="object")return;n=n[o]}return n}function q(r){let e=r.nodes.find(n=>n.type.startsWith("trigger."));if(!e)return null;let t=r.edges.filter(n=>n.from===e.id).map(n=>n.to);return{triggerId:e.id,pending:t}}function N(r,e){return r.nodes.find(t=>t.id===e)}Pt();Tt();function hn(r,e,t){let n=r.split(".");if(n[0]==="env"){if(n.length!==2)return"";let i=n[1];if(!t.has(i))return"";let s=process.env[i];return typeof s=="string"?s:""}let o=e;for(let i of n){if(o==null||typeof o!="object")return"";o=o[i]}return o==null?"":typeof o=="object"?JSON.stringify(o):String(o)}function S(r,e,t={}){let n=new Set(t.envAllow||[]);return r.replace(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_.-]*)\s*\}\}/g,(o,i)=>hn(i,e,n))}function b(r,e,t={}){let n={};for(let[o,i]of Object.entries(r))typeof i=="string"?n[o]=S(i,e,t):Array.isArray(i)?n[o]=i.map(s=>typeof s=="string"?S(s,e,t):s):i&&typeof i=="object"?n[o]=b(i,e,t):n[o]=i;return n}var ut="workflow-classify",J="unsure",lt=async r=>{let e=r.node.config,t=r.run.context,n={envAllow:r.workflow.envAllow},o=S(String(e.input??""),t,n).trim();if(!o)return{error:`classify node "${r.node.id}" missing config.input`};let i=e.labels,s=Array.isArray(i)?Object.fromEntries(i.map(m=>[String(m),null])):typeof i=="object"&&i?Object.fromEntries(Object.entries(i).map(([m,y])=>[m,y==null?null:String(y)])):{},a=Object.keys(s);if(a.length<2)return{error:`classify node "${r.node.id}" needs at least two labels`};if(a.includes(J))return{error:`classify node "${r.node.id}": "${J}" is reserved for the low-confidence port`};let d=typeof e.minConfidence=="number"?e.minConfidence:.7,c=e.instructions?S(String(e.instructions),t,n):void 0,l={input:o};if(e.state&&typeof e.state=="object")for(let[m,y]of Object.entries(e.state)){let w=typeof y=="string"?S(y,t,n):y;(w===null||["string","number","boolean"].includes(typeof w))&&(l[m]=w)}let p=await Te(ut,l,{label:Pe(s,c)},{features:{workflow:r.workflow.id,node:r.node.id}});if(!p)return{error:`classify node "${r.node.id}": decision seat unavailable (set decisions.seats.${ut}.mode)`};let g=p.answers.label,f=g.confidence>=d,h=f?g.choice:J;return r.log(`[node:${r.node.id}] classify \u2192 ${g.choice} (${g.confidence.toFixed(2)})${f?"":` \u2014 below ${d}, routing to ${J}`}`),{output:{result:g.choice,label:g.choice,confidence:g.confidence,probabilities:g.probabilities,unsure:!f,port:h},port:h}};var ye=class{active=new Map;waiters=new Map;async acquire(e,t){let n=this.active.get(e)??0;if(n<t){this.active.set(e,n+1);return}return new Promise(o=>{let i=this.waiters.get(e)??[];i.push({resolve:()=>{this.active.set(e,(this.active.get(e)??0)+1),o()}}),this.waiters.set(e,i)})}release(e){let t=this.active.get(e)??0;this.active.set(e,Math.max(0,t-1));let n=this.waiters.get(e);n&&n.length>0&&n.shift().resolve()}stats(e){return{active:this.active.get(e)??0,waiting:this.waiters.get(e)?.length??0}}},Y=new ye;function pt(r,e){return`${r}:${e}`}var F=async r=>({output:r.run.context[r.node.id]??{}}),wn=async r=>{let e=r.node.config,t=String(e.agentId??""),n=String(e.prompt??"");if(!t)return{error:`agent node "${r.node.id}" missing config.agentId`};let o=S(n,r.run.context,{envAllow:r.workflow.envAllow}),i=typeof e.timeoutMinutes=="number"?e.timeoutMinutes:void 0,s=e.autonomy===void 0||e.autonomy===null?void 0:String(e.autonomy);if(s!==void 0&&s!=="report"&&s!=="propose"&&s!=="act")return{error:`agent node "${r.node.id}" has invalid autonomy "${s}" (expected report, propose or act)`};let a=typeof e.maxConcurrent=="number"&&e.maxConcurrent>0?e.maxConcurrent:null,d=a?pt(r.workflow.id,r.node.id):null;if(d&&a){let l=Y.stats(d);l.active>=a&&r.log(`[node:${r.node.id}] gated: ${l.active} active (cap ${a}), ${l.waiting+1} waiting`),await Y.acquire(d,a)}let c=Date.now();try{let l=await r.agents.execute({agentId:t,message:o,workflowRunId:r.run.id,timeoutMinutes:i,...s?{autonomy:s}:{}}),p=Date.now()-c;if(l.error){let h=l.errorKind??"unknown";return r.log(`[node:${r.node.id}] agent "${t}" failed (${h}): ${l.error}`),{error:`[${h}] ${l.error}`}}let f=String(e.resultParser??"acme-result-token")==="json"?Hn(l.content):gt(l.content);return{output:{reply:l.content,result:f.result,json:f.json,taskId:l.taskId,durationMs:p,...l.autonomyBlocks?.length?{autonomyBlocks:l.autonomyBlocks}:{}}}}catch(l){return r.log(`[node:${r.node.id}] agent "${t}" threw: ${l.message}`),{error:l.message}}finally{d&&Y.release(d)}},yn=async r=>{let e=we(r.node,r.run.context);return e?{output:{port:e},port:e}:(r.log(`[node:${r.node.id}] branch matched no case and no default port`),{output:{port:null}})},kn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??""),n=String(e.chatId??""),o=String(e.text??"");if(!t||!n){let a=String(r.node.config.chatId??""),d=String(r.node.config.channel??""),c=[];return t||c.push(`channel config="${d}" rendered=""`),n||c.push(`chatId config="${a}" rendered=""`),(/\{\{\s*env\./.test(a)||/\{\{\s*env\./.test(d))&&c.push("(env.* templates only resolve for names listed in workflow.envAllow and actually set in process.env)"),{error:`action.send "${r.node.id}" needs channel + chatId \u2014 ${c.join("; ")}`}}let i=be(r,e.accountId),s=r.channels[t];if(s?.send)try{return{output:{messageId:await s.send({channel:t,chatId:n,text:o,...i?{accountId:i}:{}})??null}}}catch(a){return{error:`action.send failed: ${a.message}`}}if(r.forwardChannelSend)try{return{output:{messageId:(await r.forwardChannelSend({channel:t,chatId:n,text:o,accountId:i})).messageId,viaMesh:!0}}}catch(a){return r.log(`[node:${r.node.id}] mesh-forward of "${t}" send failed: ${a.message}`),{error:`action.send via mesh failed: ${a.message}`}}return r.log(`[node:${r.node.id}] adapter "${t}" not available locally and no mesh forwarder`),{error:`channel "${t}" not available (no local adapter, no mesh route)`}},bn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??"gitlab"),n=String(e.project??""),o=String(e.title??""),i=String(e.description??""),s=Array.isArray(e.labels)?e.labels.map(String):[],a=Array.isArray(e.assignees)?e.assignees.map(String):[];if(!n||!o)return{error:`action.createIssue "${r.node.id}" needs project + title`};let d=ve(r),c=r.channels[t];if(!c?.createIssue)return{error:`channel "${t}" does not support createIssue`};try{let l=await c.createIssue({project:n,title:o,description:i,labels:s,assignees:a,agentId:d});return l?{output:{issue:{iid:l.iid,url:l.url,webUrl:l.url}}}:{error:"createIssue returned null (see adapter log)"}}catch(l){return{error:`action.createIssue failed: ${l.message}`}}},vn=async()=>({output:{}}),In=async r=>{let e=r.node.config,t=String(e.name??r.node.id),n=e.waitFor??{},o=e.resumeMatch??{};return{paused:!0,pausedAt:{kind:"checkpoint",nodeId:r.node.id,checkpointName:t,resumeMatch:{...n,...o}}}},Sn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??"gitlab"),n=String(e.project??""),o=String(e.iid??""),i=Array.isArray(e.add)?e.add.map(String):[],s=Array.isArray(e.remove)?e.remove.map(String):[];if(!n||!o)return{error:`action.setLabel "${r.node.id}" needs project + iid (try {{trigger.project}} / {{trigger.issue.iid}})`};if(i.length===0&&s.length===0)return{output:{skipped:!0,reason:"no labels to add or remove"}};let a=r.channels[t];if(!a?.setLabels)return{error:`channel "${t}" does not support setLabels`};let d=ve(r),c=e.kind==="merge_request"?"merge_request":"issue";return{output:{labels:await a.setLabels({project:n,kind:c,iid:o,add:i,remove:s,agentId:d})??[],add:i,remove:s}}},An=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??"gitlab"),n=String(e.project??""),o=String(e.iid??"");if(!n||!o)return{error:`action.readLabel "${r.node.id}" needs project + iid`};let i=r.channels[t];if(!i?.getLabels)return{error:`channel "${t}" does not support getLabels`};let s=e.kind==="merge_request"?"merge_request":"issue";return{output:{labels:await i.getLabels({project:n,kind:s,iid:o})??[]}}},Rn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??""),n=String(e.chatId??""),o=String(e.messageId??""),i=String(e.emoji??"\u{1F440}");if(!t||!n||!o)return{error:`action.react "${r.node.id}" needs channel + chatId + messageId`};let s=be(r,e.accountId),a=r.channels[t];if(!a?.react)return{error:`channel "${t}" does not support react`};try{return await a.react(n,o,i,s),{output:{emoji:i}}}catch(d){return{error:`action.react failed: ${d.message}`}}},$n=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??""),n=String(e.chatId??""),o=String(e.messageId??""),i=String(e.text??""),s=e.parseMode?String(e.parseMode):void 0;if(!t||!n||!o||!i)return{error:`action.editMessage "${r.node.id}" needs channel + chatId + messageId + text`};let a=be(r,e.accountId),d=r.channels[t];if(!d?.editMessage)return{error:`channel "${t}" does not support editMessage`};try{return{output:{edited:await d.editMessage(n,o,i,s,a)}}}catch(c){return{error:`action.editMessage failed: ${c.message}`}}},Pn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??"gitlab"),n=String(e.chatId??""),o=Number(e.durationMs??0);if(!n||!o)return{error:`action.logTime "${r.node.id}" needs chatId + durationMs`};let i=r.channels[t];if(!i?.logTimeSpent)return{error:`channel "${t}" does not support logTimeSpent`};let s=ve(r);try{return await i.logTimeSpent(n,o,s),{output:{durationMs:o}}}catch(a){return{error:`action.logTime failed: ${a.message}`}}},Tn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.url??"");if(!t)return{error:`action.callHTTP "${r.node.id}" needs url`};let n=String(e.method??"POST").toUpperCase(),o=e.headers&&typeof e.headers=="object"?e.headers:{"Content-Type":"application/json"},i;e.body!==void 0&&(i=typeof e.body=="string"?e.body:JSON.stringify(e.body));try{let s=await fetch(t,{method:n,headers:o,body:i}),a=await s.text(),d=a;try{d=JSON.parse(a)}catch{}return{output:{ok:s.ok,status:s.status,body:d}}}catch(s){return{error:`action.callHTTP failed: ${s.message}`}}},xn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.actionId??e.id??"");if(!t)return{error:`action.run "${r.node.id}" needs actionId`};let n=e.inputs&&typeof e.inputs=="object"?e.inputs:{},{ActionStore:o}=await import("./store-TWQPEM5V.js"),{runAction:i}=await import("./runner-56G3N7M4.js"),s=new o().get(t);if(!s)return{error:`action.run "${r.node.id}": no action "${t}" in registry`};try{let a=await i(s,n),d={ok:a.ok,output:a.output,status:a.status,durationMs:a.durationMs};return a.errors!==void 0&&(d.errors=a.errors),a.ok?{output:d}:{output:d,error:`action "${t}" failed (status=${a.status})`}}catch(a){return{error:`action.run failed: ${a.message}`}}},Nn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.name??"");if(!t)return{error:`action.builtin "${r.node.id}" needs a "name" (e.g. "http.fetch")`};let n=e.input&&typeof e.input=="object"?e.input:{},{runBuiltin:o,getBuiltin:i}=await import("./builtin-W6KNX7RS.js");if(!i(t))return{error:`action.builtin "${r.node.id}": unknown built-in "${t}"`};try{return{output:await o(t,n)}}catch(s){let a=s?.name==="ZodError"?`validation: ${s.message}`:s?.message||String(s);return{error:`action.builtin "${t}" failed: ${a}`}}},On=async r=>{let e=r.node.config,t=r.run.context;return typeof e.path=="string"&&e.path?{output:{value:z(t,e.path)}}:e.template&&typeof e.template=="object"?{output:b(e.template,t,{envAllow:r.workflow.envAllow})}:{output:{}}};function Wn(r){if(r!=null){if(typeof r=="number")return new Date(Date.now()+r*6e4).toISOString();if(typeof r=="object"&&r&&"minutes"in r){let e=Number(r.minutes);if(Number.isFinite(e))return new Date(Date.now()+e*6e4).toISOString()}if(typeof r=="string"){let e=/^P(?:([0-9]+)D)?(?:T(?:([0-9]+)H)?(?:([0-9]+)M)?(?:([0-9]+)S)?)?$/.exec(r);if(e){let t=Number(e[1]??0),n=Number(e[2]??0),o=Number(e[3]??0),i=Number(e[4]??0),s=((t*24+n)*60+o)*6e4+i*1e3;if(s>0)return new Date(Date.now()+s).toISOString()}}}}var jn=async r=>{let e=r.node.config,t=b(e,r.run.context,{envAllow:r.workflow.envAllow}),n=String(t.workflowId??"");if(!n)return{error:`subProcess "${r.node.id}" missing config.workflowId`};let o=r.run.depth??0,i=r.workflow.maxChildDepth??5;if(o+1>=i)return{error:`max child workflow depth ${i} exceeded at ${r.workflow.id} \u2192 ${n} (parent depth ${o})`};let s=e.inputMap,a={};if(s==="*")a={...r.run.context};else if(s&&typeof s=="object")for(let[d,c]of Object.entries(s))c&&typeof c=="object"&&!Array.isArray(c)?a[d]=b(c,r.run.context,{envAllow:r.workflow.envAllow}):typeof c=="string"&&(a[d]={value:S(c,r.run.context,{envAllow:r.workflow.envAllow})});return{paused:!0,pausedAt:{kind:"subProcess",nodeId:r.node.id,childRunId:"",childWorkflowId:n},spawnChild:{workflowId:n,input:a}}},En=F,Fn=async r=>{let e=r.node.config,t=b(e,r.run.context,{envAllow:r.workflow.envAllow}),n=String(t.name??"");if(!n)return{error:`signal.emit "${r.node.id}" missing config.name`};let o=t.scope==="global"?"global":"workflow",i=t.payload&&typeof t.payload=="object"?t.payload:{};return{output:{emittedAt:new Date().toISOString(),name:n,scope:o,payload:i},emitSignal:{name:n,scope:o,payload:i}}},Dn=async r=>{let e=r.node.config,t=b(e,r.run.context,{envAllow:r.workflow.envAllow}),n=String(t.name??"");if(!n)return{error:`signal.wait "${r.node.id}" missing config.name`};let o=t.scope==="global"?"global":"workflow",i=e.match&&typeof e.match=="object"?e.match:{};return{paused:!0,pausedAt:{kind:"signalWait",nodeId:r.node.id,signalName:n,match:i,scope:o}}},Cn=async r=>{let e=r.node.config,t=b(e,r.run.context,{envAllow:r.workflow.envAllow}),n=Wn(t.after??e.after);return n?{paused:!0,pausedAt:{kind:"timerWait",nodeId:r.node.id,fireAt:n}}:{error:`timer.boundary "${r.node.id}" needs config.after (duration or minutes)`}},Mn=async()=>({output:{}}),_n=async r=>{let e=r.node.config,n=(Array.isArray(e.inputs)?e.inputs:[]).map(s=>typeof s=="string"?S(s,r.run.context,{envAllow:r.workflow.envAllow}):s),o=Array.isArray(e.rules)?e.rules:[];for(let s of o){let a=Array.isArray(s.when)?s.when:[];if(a.length!==n.length)continue;let d=!0;for(let c=0;c<a.length;c++)if(!Ln(a[c],n[c])){d=!1;break}if(d)return{output:{...s.output??{},matchedPort:s.to??""},port:s.to}}let i=e.default;return{output:{...i?.output??{},matchedPort:i?.to??""},port:i?.to}};function Ln(r,e){if(r==null||r==="*")return!0;let t=String(r),n=typeof e=="number"?e:String(e??""),o=/^(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/.exec(t);if(o){let i=o[1],s=Number(o[2]),a=typeof n=="number"?n:Number(n);if(Number.isNaN(a))return!1;switch(i){case">":return a>s;case"<":return a<s;case">=":return a>=s;case"<=":return a<=s}}if(t.startsWith("!="))return String(n)!==t.slice(2);if(t.startsWith("/")&&t.endsWith("/")&&t.length>2)try{return new RegExp(t.slice(1,-1)).test(String(n))}catch{return!1}return String(n)===t}var ft={"trigger.channel":F,"trigger.manual":F,"trigger.cron":F,"trigger.hook":F,"trigger.form":En,agent:wn,classify:lt,branch:yn,transform:On,"gateway.parallel":Mn,rule:_n,"action.send":kn,"action.createIssue":bn,"action.setLabel":Sn,"action.readLabel":An,"action.react":Rn,"action.editMessage":$n,"action.logTime":Pn,"action.callHTTP":Tn,"action.run":xn,"action.builtin":Nn,subProcess:jn,"signal.emit":Fn,"signal.wait":Dn,"timer.boundary":Cn,checkpoint:In,end:vn};function ke(r){return ft[r]}function be(r,e){if(typeof e=="string"&&e)return e;let t=r.workflow.nodes.find(i=>i.type.startsWith("trigger."));if(!t)return;let o=r.run.context[t.id]?.accountId;return typeof o=="string"&&o?o:void 0}function ve(r){for(let e=r.run.history.length-1;e>=0;e--){let t=r.run.history[e],n=r.workflow.nodes.find(o=>o.id===t.nodeId);if(n?.type==="agent")return n.config.agentId??void 0}}function gt(r){if(!r)return{};let e=r.match(/\bRESULT:\s*([a-z][a-z0-9_-]*)/i);if(e)return{result:e[1].toLowerCase()};let t=r.match(/\[(APPROVED|REJECTED|CHANGES[-_]REQUESTED|DONE|FAILED|SKIPPED)\]/i);return t?{result:t[1].toLowerCase().replace("_","-")}:{}}function Hn(r){let{result:e}=gt(r);if(!r)return{result:e};let t=r.match(/```(?:json)?\s*([\s\S]*?)```/);if(!t)return{result:e};try{return{result:e,json:JSON.parse(t[1])}}catch{return{result:e}}}var D=class{handlers=new Set;subscribe(e){return this.handlers.add(e),()=>this.handlers.delete(e)}emit(e){for(let t of this.handlers)try{Promise.resolve(t(e)).catch(()=>{})}catch{}}};function G(r,e){if(r.name!==e.name||r.scope==="workflow"&&r.workflowId!==e.workflowId)return!1;for(let[t,n]of Object.entries(r.match??{}))if(!(n===void 0||n===""||n==="*")&&e.payload[t]!==n)return!1;return!0}function Un(r,e,t=Date.now){return{ts:t(),source:"workflow",sourceEventId:`${r.workflowId}:${r.eventId}`,project:r.project,subject:`workflow:${r.workflowId}:entity:${r.entityRef.backend}:${r.entityRef.id}`,intent:`workflow.${r.triggerSource}`,rawJson:e}}function Kn(r){return r.claimed&&r.runId?{agentId:`workflow-run:${r.runId}`,outcome:"dispatched",reason:r.reason??"claimed"}:r.claimed&&!r.runId?{agentId:null,outcome:"halted",reason:r.reason??"claimed-but-no-run"}:{agentId:null,outcome:"halted",reason:r.reason??"not-claimed"}}function Bn(r){return{decidedBy:"workflow-dispatcher",decide:()=>({agentId:r.agentId,outcome:r.outcome==="deduped"?"halted":r.outcome,reason:r.outcome==="deduped"?`legacy-dedup: ${r.reason??""}`.trim():r.reason??null})}}function mt(r,e,t,n,o=Date.now){let i=Un(e,t,o),s=Kn(n),a=Bn(s),d=Fe(r,i,a,o);return De(r,"workflow",d,s,o),d}var zn=4e3,qn=8,Ie=class{store;runs;nodeId;forwarder;channels;agents;log;timers;signals;events;ackTypingTimers=new Map;commitChains=new Map;constructor(e){this.store=e.store,this.runs=e.runs,this.nodeId=e.nodeId,this.forwarder=e.forwarder,this.channels=e.channels,this.agents=e.agents,this.log=e.log??(()=>{}),this.timers=e.timers??new oe({log:t=>this.log(t)}),this.signals=e.signals??new D,this.events=e.events,this.timers.onFire(t=>this.resumeFromTimer(t)),this.signals.subscribe(t=>this.resumeFromSignal(t))}emitRunEvent(e){if(this.events)try{this.events.publish({kind:"run",runId:e.runId,workflowId:e.workflowId,nodeId:e.nodeId,phase:e.phase,status:e.status,note:e.note,homeNode:e.homeNode,rootId:e.rootId})}catch{}}async commit(e,t){let o=(this.commitChains.get(e)??Promise.resolve()).then(()=>t(),()=>t());return this.commitChains.set(e,o.then(()=>{},()=>{})),o}emitSignal(e){let t={name:e.name,scope:e.scope??"global",workflowId:e.workflowId??"",payload:e.payload??{},emittedAt:new Date().toISOString()};if(this.signals.emit(t),this.events)try{this.events.publish({kind:"signal",name:t.name,scope:t.scope,workflowId:t.workflowId||void 0,payload:t.payload})}catch{}return t}async resumeFromSignal(e){let t=this.runs.list({limit:500});for(let n of t){if(n.status!=="paused"||!n.pausedAt||n.pausedAt.kind!=="signalWait")continue;let o={name:n.pausedAt.signalName,scope:n.pausedAt.scope,workflowId:n.workflowId,match:n.pausedAt.match??{}};if(!G(o,e))continue;let i=this.store.list().find(s=>s.id===n.workflowId);i&&(await this.commit(n.id,()=>{let s=this.runs.get(n.id);if(!s||s.status!=="paused"||!s.pausedAt||s.pausedAt.kind!=="signalWait"||!G({name:s.pausedAt.signalName,scope:s.pausedAt.scope,workflowId:s.workflowId,match:s.pausedAt.match??{}},e))return;let a=N(i,s.pausedAt.nodeId),d=a?i.edges.filter(l=>l.from===a.id).map(l=>l.to):[],c={receivedAt:new Date().toISOString(),name:e.name,payload:e.payload};this.runs.recordExecution({runId:s.id,entry:{at:c.receivedAt,nodeId:s.pausedAt.nodeId,inputKeys:[],status:"resumed",output:c,idempotencyKey:x(s.id,s.pausedAt.nodeId,`signal:${e.name}:${e.emittedAt}`)},nextPending:d,status:"running",pausedAt:null,context:{...s.context,[s.pausedAt.nodeId]:c}}),this.log(`[workflow:${i.id}] run ${s.id} resumed from signal "${e.name}"`),this.emitRunEvent({runId:s.id,workflowId:i.id,nodeId:s.pausedAt.nodeId,phase:"resumed",status:"running",note:`signal:${e.name}`,rootId:s.eventRootId})}),this.walk(i,n.id,`signal:${e.name}`).catch(s=>this.log(`[workflow:${i.id}] walk-after-signal failed: ${s.message}`)))}}async resumeFromTimer(e){let t=this.store.list().find(n=>n.id===(this.runs.get(e.runId)?.workflowId??""));t&&(await this.commit(e.runId,()=>{let n=this.runs.get(e.runId);if(!n||n.status!=="paused"||!n.pausedAt||n.pausedAt.kind!=="timerWait"||n.pausedAt.nodeId!==e.nodeId)return;let o=N(t,e.nodeId),i=o?t.edges.filter(d=>d.from===o.id).map(d=>d.to):[],s=new Date().toISOString(),a={firedAt:s,scheduledFor:e.fireAt};this.runs.recordExecution({runId:n.id,entry:{at:s,nodeId:e.nodeId,inputKeys:[],status:"resumed",output:a,idempotencyKey:x(n.id,e.nodeId,`timer:${e.id}`)},nextPending:i,status:"running",pausedAt:null,context:{...n.context,[e.nodeId]:a}}),this.log(`[workflow:${t.id}] run ${n.id} resumed from timer "${e.nodeId}" (fired ${s})`),this.emitRunEvent({runId:n.id,workflowId:t.id,nodeId:e.nodeId,phase:"resumed",status:"running",note:`timer:${e.id}`,rootId:n.eventRootId})}),this.walk(t,e.runId,`timer:${e.id}`).catch(n=>this.log(`[workflow:${t.id}] walk-after-timer failed: ${n.message}`)))}async dispatchWorkflow(e){let t=this.store.list().find(s=>s.id===e.workflowId);if(!t)return this.log(`[workflows] dispatchWorkflow: workflow "${e.workflowId}" not found`),{claimed:!1,run:null};let o=t.nodes.find(s=>s.type.startsWith("trigger."))?.config??{},i={source:e.trigger?.source??o.source??"hook",project:e.trigger?.project,repo:e.trigger?.repo,chat:e.trigger?.chat,labels:e.trigger?.labels};return this.dispatchOne(t,e.entityRef,e.event,i)}startChannelAck(e,t){let n=String(t.channel??""),o=String(t.chatId??"");if(!n||!o)return;let i=this.channels[n];if(!i)return;let s=typeof t.accountId=="string"?t.accountId:void 0,a=t.event,d=typeof a?.id=="string"?a.id:a?.id!=null?String(a.id):void 0;if(d&&i.react)try{Promise.resolve(i.react(o,d,"\u{1F440}",s)).catch(()=>{})}catch{}if(this.ackTypingTimers.has(e)||!i.sendTyping)return;let c=()=>{try{Promise.resolve(i.sendTyping(o,s)).catch(()=>{})}catch{}};c();let l=setInterval(c,zn);this.ackTypingTimers.set(e,l)}stopChannelAck(e){let t=this.ackTypingTimers.get(e);t&&(clearInterval(t),this.ackTypingTimers.delete(e))}async dispatch(e){let t=this.matchByTrigger(e.trigger,e.fromRemote),o=t.some(a=>a.fanOut)?t:t.slice(0,1),i=[],s=[];for(let a of o){let d=await this.dispatchOne(a,e.entityRef,e.event,e.trigger);d.claimed&&i.push(a),d.run&&s.push(d.run)}return!e.fromRemote&&this.forwarder?.broadcastTrigger&&Promise.resolve(this.forwarder.broadcastTrigger({trigger:e.trigger,entityRef:e.entityRef,event:e.event})).catch(a=>this.log(`[mesh-broadcast] ${a?.message??a}`)),{claimed:i,runs:s}}matchByTrigger(e,t){let n=this.store.list(),o=[];for(let i of n){if(i.state&&i.state!=="active")continue;if(t){if(!i.mesh?.allowRemote)continue;let c=i.mesh.peers;if(c&&c.length>0&&!c.includes(t.peer))continue}let s=i.nodes.find(c=>c.type.startsWith("trigger."));if(!s)continue;let a=s.config;if(a.source!==e.source||i.project&&e.project&&i.project!==e.project)continue;let d=a.filter;if(d){if(d.project&&d.project!=="*"&&d.project!==e.project||d.repo&&d.repo!=="*"&&d.repo!==e.repo||d.chat&&d.chat!=="*"&&V(e.source,d.chat)!==V(e.source,e.chat))continue;if(d.labels?.length){let c=new Set(e.labels??[]);if(!d.labels.some(p=>c.has(p)))continue}}o.push(i)}return o.sort((i,s)=>s.priority-i.priority||i.id.localeCompare(s.id))}async dispatchOne(e,t,n,o){let i=await this.dispatchOneLegacy(e,t,n,o);if(Ee("workflow")!=="off")try{mt(Oe(),{workflowId:e.id,eventId:n.id,triggerSource:o.source,project:o.project??null,entityRef:t},JSON.stringify({event:n,trigger:o,entityRef:t}),{claimed:i.claimed,runId:i.run?.id??null})}catch(s){this.log(`[ledger] workflow ${e.id} run ${i.run?.id??"?"} record failed: ${s?.message??s}`)}return i}async dispatchOneLegacy(e,t,n,o){let i=this.runs.getActiveByEntity(t),s=i?this.runs.getHomeNodeByEntity(t):null;if(i&&s&&s!==this.nodeId){if(!this.forwarder)return this.log(`[workflow:${e.id}] run ${i} home'd on "${s}" but no forwarder \u2014 dropping`),{claimed:!1,run:null};try{await this.forwarder.forwardTransition(s,{workflowId:e.id,event:n,entityRef:t})}catch(d){this.log(`[workflow:${e.id}] forward to "${s}" failed: ${d.message}`)}return{claimed:!0,run:null}}let a=i?this.runs.get(i):null;if(a)if(a.status==="paused"&&a.pausedAt){if(a.pausedAt.kind!=="checkpoint")return this.log(`[workflow:${e.id}] run ${a.id} paused on ${a.pausedAt.kind} \u2014 channel event bypasses workflow`),{claimed:!1,run:null};if(!Yn(a.pausedAt.resumeMatch,o,n))return this.log(`[workflow:${e.id}] run ${a.id} paused but event doesn't match resumeMatch \u2014 dropping`),{claimed:!1,run:null};let d=N(e,a.pausedAt.nodeId),c=d?e.edges.filter(h=>h.from===d.id).map(h=>h.to):[],l={at:new Date().toISOString(),nodeId:a.pausedAt.nodeId,inputKeys:[],status:"resumed",output:{event:n.payload},idempotencyKey:x(a.id,a.pausedAt.nodeId,`resume:${n.id}`)},p={...a.context,[a.pausedAt.nodeId]:{event:n.payload}},g=a.pausedAt.checkpointName,f=this.runs.recordExecution({runId:a.id,entry:l,nextPending:c,status:"running",pausedAt:null,context:p});f&&(a=f),this.log(`[workflow:${e.id}] run ${a.id} resumed from checkpoint "${g}"`),o.source.endsWith("-message")&&this.startChannelAck(a.id,n.payload)}else return a.status==="running"?(this.log(`[workflow:${e.id}] run ${a.id} already running; dropping concurrent event ${n.id}`),{claimed:!0,run:null}):(this.log(`[workflow:${e.id}] run ${a.id} is ${a.status}; dropping event ${n.id}`),{claimed:!1,run:null});else{let d=q(e);if(!d)return this.log(`[workflow:${e.id}] no trigger node found`),{claimed:!1,run:null};a=this.runs.create({workflowId:e.id,initialPending:d.pending,entityRef:t,initialContext:{[d.triggerId]:n.payload}}),this.log(`[workflow:${e.id}] run ${a.id} created from trigger "${d.triggerId}" for ${t.id}`),this.emitRunEvent({runId:a.id,workflowId:e.id,phase:"created",status:a.status,homeNode:a.homeNode,rootId:a.eventRootId}),o.source.endsWith("-message")&&this.startChannelAck(a.id,n.payload)}return this.walk(e,a.id,n.id),{claimed:!0,run:a}}async walk(e,t,n){let o=this.runs.get(t)?.eventRootId,i=()=>this.walkInner(e,t,n);try{await(o?je({rootId:o},i):i())}finally{this.stopChannelAck(t)}}async walkInner(e,t,n){let o=this.runs.get(t);if(o)for(;o.status==="running"&&o.pending.length>0;){let i=o.pending.slice(0,qn);await Promise.allSettled(i.map(a=>this.executeNodeAndCommit(e,t,a,n)));let s=this.runs.get(t);if(!s||(o=s,o.status!=="running"))return}}async executeNodeAndCommit(e,t,n,o){let i=x(t,n,o),s=await this.commit(t,()=>{let m=this.runs.get(t);if(!m)return{kind:"done"};if(m.status!=="running")return{kind:"done"};let y=N(e,n);if(!y)return this.log(`[workflow:${e.id}] missing node "${n}" \u2014 marking run failed`),this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:n,inputKeys:[],status:"failed",idempotencyKey:i,note:"node definition missing from workflow"},nextPending:m.pending.filter(A=>A!==n),status:"failed"}),{kind:"done"};let w=ke(y.type);return w?m.history.some(A=>A.idempotencyKey===i)?(this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:n,inputKeys:[],status:"skipped",idempotencyKey:i+"_dedup",note:"duplicate execution dropped"},nextPending:m.pending.filter(A=>A!==n)}),{kind:"done"}):{kind:"go",run:m,node:y,handler:w}:(this.log(`[workflow:${e.id}] no handler for node type "${y.type}"`),this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:n,inputKeys:[],status:"failed",idempotencyKey:i,note:`no handler for node type "${y.type}"`},nextPending:m.pending.filter(A=>A!==n),status:"failed"}),{kind:"done"})});if(s.kind==="done")return;let{run:a,node:d,handler:c}=s,l=e.edges.filter(m=>m.to===n).map(m=>m.from),p;if(d.type!=="agent"){let m=ee();if(m)try{p=Ce(m,{agentId:`workflow:${d.type}`,channel:"workflow",chatId:`${e.id}:${n}`,workflowRunId:t,workflowId:e.id,workflowNodeId:n,messagePreview:`${d.type} ${n}`})}catch{}}let g=d.retry??{maxAttempts:1,backoffMs:1e3},f={error:"retry-loop did not run"},h=0;for(;h<g.maxAttempts;){h++;try{f=await c({workflow:e,run:a,node:d,channels:this.channels,agents:this.agents,forwardChannelSend:this.forwarder?.forwardChannelSend?.bind(this.forwarder),log:this.log})}catch(m){this.log(`[workflow:${e.id}] handler "${d.type}" threw: ${m.message}`),f={error:m.message}}if(!f.error||f.paused)break;if(h<g.maxAttempts){let m=g.backoffMs*Math.pow(2,h-1);this.log(`[workflow:${e.id}] node "${n}" failed (attempt ${h}/${g.maxAttempts}): ${f.error.slice(0,120)} \u2014 retrying in ${m}ms`),await new Promise(y=>setTimeout(y,m))}}if(p){let m=ee();if(m)try{Me(m,p,{status:f.error?"error":"ok",error:f.error??null})}catch{}}await this.commit(t,async()=>{let m=this.runs.get(t);if(!m)return;let y=new Date().toISOString(),w=m.pending.filter(k=>k!==n);if(f.error){let k=m.status==="running"?"failed":void 0;this.runs.recordExecution({runId:t,entry:{at:y,nodeId:n,inputKeys:l,status:"failed",idempotencyKey:i,note:f.error.slice(0,200)},nextPending:w,status:k}),this.emitRunEvent({runId:t,workflowId:e.id,nodeId:n,phase:"failed",status:k??m.status,note:f.error.slice(0,200)});return}if(f.paused&&f.pausedAt){let k=f.pausedAt,T=null;if(f.spawnChild&&k.kind==="subProcess"){if(T=await this.spawnChild({parent:m,parentNodeId:n,childWorkflowId:f.spawnChild.workflowId,input:f.spawnChild.input}),!T){this.runs.recordExecution({runId:t,entry:{at:y,nodeId:n,inputKeys:l,status:"failed",idempotencyKey:i,note:`subProcess: child workflow "${f.spawnChild.workflowId}" not found`},nextPending:w,status:"failed"});return}k={...k,childRunId:T.id}}if(this.runs.recordExecution({runId:t,entry:{at:y,nodeId:n,inputKeys:l,status:"paused",idempotencyKey:i},nextPending:w,status:"paused",pausedAt:k}),this.emitRunEvent({runId:t,workflowId:e.id,nodeId:n,phase:"paused",status:"paused",note:k.kind}),T&&this.kickChildWalk(T),k.kind==="timerWait")try{this.timers.schedule({runId:t,workflowId:e.id,nodeId:k.nodeId,fireAt:k.fireAt,cancelKey:`${t}:${k.nodeId}`})}catch(Ae){this.log(`[workflow:${e.id}] timer schedule failed: ${Ae.message}`)}return}let A=f.output??{},vt={...m.context,[n]:A},{nextPending:It}=he({workflow:e,fromNodeId:n,selectedPort:f.port}),Q=[],C={...m.joinCounters??{}};for(let k of It){let T=N(e,k);if(!(T?.type==="gateway.parallel"&&String(T.config?.mode??"fanOut")==="join")){Q.push(k);continue}let _=C[k]??[];_.includes(n)||_.push(n),C[k]=_;let Rt=e.edges.filter($t=>$t.to===k).length;_.length>=Rt&&(Q.push(k),delete C[k])}let St=[...w,...Q],M=d.type==="end",At=m.status==="running"?M?String(d.config.status??"completed"):"running":void 0,O=this.runs.recordExecution({runId:t,entry:{at:y,nodeId:n,inputKeys:l,status:"ok",output:A,idempotencyKey:i},nextPending:M?[]:St,status:At,context:vt,joinCounters:C});this.emitRunEvent({runId:t,workflowId:e.id,nodeId:n,phase:M?"completed":"ok",status:O?.status??m.status}),f.emitSignal&&this.emitSignal({name:f.emitSignal.name,scope:f.emitSignal.scope,workflowId:e.id,payload:f.emitSignal.payload}),M&&O&&O.parentRunId&&O.parentNodeId&&this.resumeParent({parentRunId:O.parentRunId,parentNodeId:O.parentNodeId,childRun:O}).catch(k=>this.log(`[workflow:${e.id}] resumeParent failed: ${k.message}`))})}async spawnChild(e){let t=this.store.list().find(a=>a.id===e.childWorkflowId);if(!t)return null;let n=q(t);if(!n)return this.log(`[workflow:${t.id}] no trigger node \u2014 cannot spawn as child`),null;let o={...e.input};o[n.triggerId]={...o[n.triggerId]??{},parentRunId:e.parent.id,parentNodeId:e.parentNodeId};let i={backend:"agentx-internal",id:`subprocess:${e.parent.id}:${e.parentNodeId}`},s=this.runs.create({workflowId:t.id,initialPending:n.pending,entityRef:i,initialContext:o,parentRunId:e.parent.id,parentNodeId:e.parentNodeId,rootRunId:e.parent.rootRunId??e.parent.id,depth:(e.parent.depth??0)+1});return this.log(`[workflow:${t.id}] child run ${s.id} spawned from ${e.parent.id}/${e.parentNodeId} (depth ${s.depth})`),s}kickChildWalk(e){let t=this.store.list().find(n=>n.id===e.workflowId);t&&this.walk(t,e.id,`spawn:${e.parentRunId}:${e.parentNodeId}`).catch(n=>this.log(`[workflow:${t.id}] child walk failed: ${n.message}`))}async resumeParent(e){let t=this.runs.get(e.parentRunId);if(!t)return;let n=this.store.list().find(o=>o.id===t.workflowId);n&&(await this.commit(e.parentRunId,()=>{let o=this.runs.get(e.parentRunId);if(!o||o.status!=="paused"||!o.pausedAt||o.pausedAt.kind!=="subProcess"||o.pausedAt.nodeId!==e.parentNodeId||o.pausedAt.childRunId!==e.childRun.id)return;let i=N(n,e.parentNodeId),s=i?n.edges.filter(d=>d.from===i.id).map(d=>d.to):[],a={childRunId:e.childRun.id,status:e.childRun.status,output:Jn(e.childRun)};this.runs.recordExecution({runId:o.id,entry:{at:new Date().toISOString(),nodeId:e.parentNodeId,inputKeys:[],status:"resumed",output:a,idempotencyKey:x(o.id,e.parentNodeId,`child:${e.childRun.id}`)},nextPending:s,status:"running",pausedAt:null,context:{...o.context,[e.parentNodeId]:a}}),this.log(`[workflow:${n.id}] parent run ${o.id} resumed from subProcess child ${e.childRun.id}`),this.emitRunEvent({runId:o.id,workflowId:n.id,nodeId:e.parentNodeId,phase:"resumed",status:"running",note:`child:${e.childRun.id}`,rootId:o.eventRootId})}),this.walk(n,e.parentRunId,`child:${e.childRun.id}`))}};function Jn(r){for(let e=r.history.length-1;e>=0;e--){let t=r.history[e];if(t.status==="ok"&&t.output&&Object.keys(t.output).length>0)return t.output}return{}}function Yn(r,e,t){let n=i=>{let s=r[i];if(s===void 0||s===""||s==="*")return!0;if(Array.isArray(s)){let a=new Set(e.labels??[]);return s.some(d=>a.has(String(d)))}return i==="chat"?V(e.source,String(s))===V(e.source,e.chat):e[i]===s};if(!n("source")||!n("project")||!n("repo")||!n("chat"))return!1;let o=r.eventIdLike;return!(typeof o=="string"&&o&&!t.id.includes(o))}function V(r,e){return e==null?"":r==="whatsapp-message"?e.replace(/@s\.whatsapp\.net$|@g\.us$/i,"").replace(/[\s+()]/g,""):e}function Gn(r){return{"pre:channel-message":async e=>{let t=e.msg;if(!t)return{};let n=Vn(t.channel);if(!n)return{};let o=t.group?.id??t.sender.id,i={backend:t.channel,id:`${t.channel}:${o}`},{claimed:s}=await r.dispatch({trigger:{source:n,chat:o},entityRef:i,event:{id:`${t.channel}:${t.accountId}:${t.id}`,payload:Zn(t)}});return s.length===0?{}:s.every(d=>d.nodes.find(l=>l.type.startsWith("trigger."))?.config?.passthrough===!0)?{}:{blocked:!0,message:`handled by workflow${s.length>1?"s":""}: ${s.map(d=>d.id).join(", ")}`}},"on:gitlab-issue":async e=>{let t=e.project,n=e.iid,o=e.issueEvent;if(!t||n===void 0)return{};let i=Array.isArray(o?.object_attributes?.labels)?o.object_attributes.labels.map(d=>typeof d=="string"?d:d?.title).filter(Boolean):o?.labels?.map(d=>d?.title)??[],s=o?.assignees??o?.object_attributes?.assignee_ids??[],a={backend:"gitlab",id:`${t}#${n}`};return await r.dispatch({trigger:{source:"gitlab-issue",project:t,labels:i},entityRef:a,event:{id:`gitlab-issue:${t}:${n}:${o?.object_attributes?.updated_at||o?.object_attributes?.action||"evt"}`,payload:{issue:{iid:n,title:o?.object_attributes?.title,description:o?.object_attributes?.description,url:o?.object_attributes?.url,action:o?.object_attributes?.action,labels:i,assignees:s},project:t,channel:"gitlab",chatId:`${t}:issue:${n}`}}}),{}},"on:gitlab-mr":async e=>{let t=e.project,n=e.iid,o=e.mrEvent;if(!t||n===void 0)return{};let i=Array.isArray(e.labels)?e.labels:Array.isArray(o?.object_attributes?.labels)?o.object_attributes.labels.map(c=>typeof c=="string"?c:c?.title).filter(Boolean):[],s=o?.assignees??o?.object_attributes?.assignee_ids??[],a=o?.reviewers??[],d={backend:"gitlab",id:`${t}!${n}`};return await r.dispatch({trigger:{source:"gitlab-mr",project:t,labels:i},entityRef:d,event:{id:`gitlab-mr:${t}:${n}:${o?.object_attributes?.updated_at||o?.object_attributes?.action||"evt"}`,payload:{mr:{iid:n,title:e.title,description:e.description,url:e.url,action:e.action,state:e.state,source_branch:e.source_branch,target_branch:e.target_branch,labels:i,assignees:s,reviewers:a},project:t,channel:"gitlab",chatId:`${t}:merge_request:${n}`,iid:n,title:e.title,description:e.description,url:e.url,action:e.action,state:e.state,source_branch:e.source_branch,target_branch:e.target_branch,labels:i}}}),{}},"on:gitlab-note":async e=>{let t=e.project,n=e.noteId,o=e.noteableType,i=e.noteableIid,s=e.text,a=e.authorUsername,d=e.mentions??[];if(!t||!n||!o||!i)return{};let c=o==="merge_request"?{backend:"gitlab",id:`${t}!${i}`}:{backend:"gitlab",id:`${t}#${i}`};return await r.dispatch({trigger:{source:"gitlab-note",project:t},entityRef:c,event:{id:`gitlab-note:${t}:${o}:${i}:${n}`,payload:{note:{id:n,text:s,author:a,mentions:d,noteableType:o,noteableIid:i,noteableTitle:e.noteableTitle},project:t,channel:"gitlab",chatId:`${t}:${o}:${i}`,noteId:n,noteableType:o,noteableIid:i,text:s,author:a,mentions:d}}}),{}},"on:gitlab-pipeline":async e=>{let t=e.project,n=e.pipelineId,o=e.status,i=e.ref;if(!t||!o)return{};let a=e.raw?.merge_request?.iid;if(!a)return{};let d={backend:"gitlab",id:`${t}!${a}`};return await r.dispatch({trigger:{source:"gitlab-pipeline",project:t},entityRef:d,event:{id:`gitlab-pipeline:${t}:${n}:${o}`,payload:{pipeline:{id:n,status:o,ref:i},project:t,channel:"gitlab",chatId:`${t}:merge_request:${a}`}}}),{}}}}function Vn(r){switch(r){case"telegram":return"telegram-message";case"whatsapp":return"whatsapp-message";case"discord":return"discord-message";case"slack":return"slack-message";default:return null}}function Zn(r){let e=r.group?.id??r.sender.id;return{channel:r.channel,chatId:e,accountId:r.accountId,text:r.text,fromJid:r.sender.id,sender:{id:r.sender.id,name:r.sender.name,username:r.sender.username},contact:r.channelMeta?.facts?{facts:r.channelMeta.facts}:void 0,group:r.group?{id:r.group.id,name:r.group.name}:void 0,channelMeta:r.channelMeta,replyTo:r.replyTo,replyToText:r.replyToText,media:r.media,event:{id:r.id,timestamp:r.timestamp?.toISOString?.()??new Date().toISOString()}}}var Z=r=>r.trim().toLowerCase().replace(/^@/,"");function Xn(r){let e=typeof r.author=="string"?r.author:typeof r.authorUsername=="string"?r.authorUsername:void 0;if(e)return Z(e);let n=r.payload?.sender?.login;return typeof n=="string"&&n?Z(n):void 0}function Qn(r,e){let t=typeof e.project=="string"?e.project:"";if(r==="on:gitlab-issue"||r==="on:gitlab-mr")return!t||e.iid==null?void 0:`gitlab:${t}${r==="on:gitlab-issue"?"#":"!"}${String(e.iid)}`;if(r==="on:gitlab-note"){let n=e.noteableIid!=null?String(e.noteableIid):"",o=typeof e.noteableType=="string"?e.noteableType:"";return!t||!n||!o?void 0:`gitlab:${t}${o==="issue"?"#":"!"}${n}`}if(r==="on:github-issue"||r==="on:github-pr"){let n=e.payload??{},o=typeof e.repo=="string"?e.repo:n.repository?.full_name,i=e.number??n.issue?.number??n.pull_request?.number;return typeof o!="string"||!o||i==null?void 0:`github:${o}#${String(i)}`}}function er(r){let e=new Set;for(let t of r.nodes){let n=t.type==="agent"?t.config.agentId:void 0;typeof n=="string"&&n&&e.add(n)}return[...e]}var X=class{constructor(e=2e3){this.maxKeys=e}fires=new Map;tryFire(e,t,n,o=Date.now()){let i=(this.fires.get(e)??[]).filter(s=>o-s<n);if(i.length>=t)return this.fires.set(e,i),!1;for(i.push(o),this.fires.delete(e),this.fires.set(e,i);this.fires.size>this.maxKeys;){let s=this.fires.keys().next().value;if(s===void 0)break;this.fires.delete(s)}return!0}get size(){return this.fires.size}};function Se(r,e,t){let n=r.logged??(r.logged=new Set);n.has(e)||(n.add(e),r.log(t))}function ht(r,e,t,n,o){let i=Xn(t);if(i&&Array.isArray(n?.ignoreAuthors)&&n.ignoreAuthors.length>0&&n.ignoreAuthors.map(Z).includes(i))return{skip:!0,reason:"ignored-author",detail:`author @${i} is in filter.ignoreAuthors`};if(n?.skipSelfAuthored===!0){let a=er(r),d=typeof t.authorAgent=="string"?t.authorAgent:void 0;if(d&&a.includes(d))return{skip:!0,reason:"self-authored",detail:`author @${i??"?"} is agent "${d}" which this workflow runs`};if(i){let c=new Set(a.flatMap(l=>(o.forgeUsernames?.(l)??[]).map(Z)));if(c.has(i))return{skip:!0,reason:"self-authored",detail:`author @${i} is this workflow's own bot identity`};a.length===0?Se(o,`noagents:${r.id}`,`[workflows] ${r.id} has no agent node \u2014 self-authored skip can't resolve a bot identity; only filter.ignoreAuthors applies`):c.size===0&&!("authorAgent"in t)&&Se(o,`noident:${r.id}:${e}`,`[workflows] ${r.id} no forge username known for agent(s) ${a.join(", ")} on ${e} \u2014 self-authored skip inactive; only filter.ignoreAuthors applies`)}}let s=n?.maxFiresPerTarget;if(s&&typeof s.count=="number"&&s.count>0){let a=Qn(e,t);if(a){let d=typeof s.windowMinutes=="number"&&s.windowMinutes>0?s.windowMinutes:60,c=o.now?.()??Date.now();if(!o.fireWindow.tryFire(`${r.id}|${a}`,s.count,d*6e4,c))return{skip:!0,reason:"chain-limit",detail:`${a} already fired ${s.count}x within ${d}m (filter.maxFiresPerTarget)`}}else Se(o,`notarget:${r.id}:${e}`,`[workflows] ${r.id} filter.maxFiresPerTarget has no target key for ${e} \u2014 limit not applied`)}return{skip:!1}}function tr(r){let e=r.store.list(),t={fireWindow:new X,log:r.log,forgeUsernames:r.forgeUsernames,logged:new Set},n=0,o=0;for(let i of e){if(i.state&&i.state!=="active"){r.log(`[workflows] ${i.id} state=${i.state} \u2014 skipping trigger registration`);continue}let s=i.nodes.find(a=>a.type.startsWith("trigger."));if(s){if(s.type==="trigger.cron"){let a=s.config;if(!a.spec){r.log(`[workflows] ${i.id} trigger.cron missing config.spec \u2014 skipping`);continue}rr({workflowId:i.id,triggerNodeId:s.id,spec:a.spec,timezone:a.timezone??"UTC"},r.dispatcher,r.log),n++}else if(s.type==="trigger.hook"){let a=s.config;if(!a.event||!a.event.startsWith("on:")){r.log(`[workflows] ${i.id} trigger.hook config.event must start with "on:" \u2014 skipping`);continue}r.hooks.registerHandler(a.event,`workflows:${i.id}`,async d=>{try{let c=typeof d.project=="string"?d.project:void 0;if(i.project&&c&&i.project!==c)return{};if(a.filter){if(Array.isArray(a.filter.topic)&&a.filter.topic.length>0){let h=typeof d.topic=="string"?d.topic.toLowerCase():void 0;if(!h||!a.filter.topic.map(m=>m.toLowerCase()).includes(h))return{}}if(Array.isArray(a.filter.action)&&a.filter.action.length>0){let h=typeof d.action=="string"?d.action:void 0;if(!h||!a.filter.action.includes(h))return{}}if(Array.isArray(a.filter.mentions)&&a.filter.mentions.length>0){let h=Array.isArray(d.mentions)?d.mentions.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.mentions.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>h.includes(w)))return{}}if(Array.isArray(a.filter.noteableType)&&a.filter.noteableType.length>0){let h=typeof d.noteableType=="string"?d.noteableType.toLowerCase():void 0,m=a.filter.noteableType.map(y=>y.toLowerCase());if(!h||!m.includes(h))return{}}if(Array.isArray(a.filter.assigneesAdded)&&a.filter.assigneesAdded.length>0){let h=Array.isArray(d.assigneesAdded)?d.assigneesAdded.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.assigneesAdded.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>h.includes(w)))return{}}if(Array.isArray(a.filter.reviewersAdded)&&a.filter.reviewersAdded.length>0){let h=Array.isArray(d.reviewersAdded)?d.reviewersAdded.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.reviewersAdded.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>h.includes(w)))return{}}if(Array.isArray(a.filter.labelsAdded)&&a.filter.labelsAdded.length>0){let h=Array.isArray(d.labelsAdded)?d.labelsAdded.map(w=>w.toLowerCase()):[];if(!a.filter.labelsAdded.map(w=>w.toLowerCase()).some(w=>h.includes(w)))return{}}}let l=ht(i,a.event,d,a.filter,t);if(l.skip){if(r.log(`[workflows] ${i.id} skipping ${a.event} (${l.reason}): ${l.detail}`),a.passthrough)return{};let h=d.__workflowClaimed;return{modified:{__workflowClaimed:[...Array.isArray(h)?h:[],i.id]}}}let p=nr(i.id,a.event,d);if(await r.dispatcher.dispatchWorkflow({workflowId:i.id,entityRef:{backend:"hook",id:p},event:{id:`hook:${a.event}:${Date.now().toString(36)}`,payload:{hookEvent:a.event,...d}}}),a.passthrough)return{};let g=d.__workflowClaimed;return{modified:{__workflowClaimed:[...Array.isArray(g)?g:[],i.id]}}}catch(c){return r.log(`[workflows] ${i.id} hook dispatch failed: ${c.message}`),{}}},60),o++}}}return{cronTimers:n,hookSubscribers:o}}function nr(r,e,t){let n=typeof t.project=="string"?t.project:"",o=t.iid!=null?String(t.iid):"";if(e==="on:gitlab-issue"&&n&&o)return`${r}:${e}:${n}#${o}`;if(e==="on:gitlab-mr"&&n&&o)return`${r}:${e}:${n}!${o}`;if(e==="on:gitlab-pipeline"&&n){let i=t.pipelineId!=null?String(t.pipelineId):"";if(i)return`${r}:${e}:${n}@pipeline:${i}`}return`${r}:${e}:${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function rr(r,e,t){let n=()=>{let o;try{o=_e(r.spec,new Date,r.timezone)}catch(s){t(`[workflows] ${r.workflowId} cron spec invalid: ${s.message}`);return}let i=Math.max(1e3,o.getTime()-Date.now());setTimeout(()=>{(async()=>{let s=`cron:${r.workflowId}:${o.toISOString()}`;try{await e.dispatchWorkflow({workflowId:r.workflowId,trigger:{source:"cron"},entityRef:{backend:"cron",id:`${r.workflowId}@${o.toISOString()}`},event:{id:s,payload:{now:o.toISOString(),spec:r.spec,workflowId:r.workflowId}}})}catch(a){t(`[workflows] ${r.workflowId} cron dispatch failed: ${a.message}`)}finally{n()}})()},i)};n()}function wt(r){return r.nodes.find(n=>n.type.startsWith("trigger."))?.config?.inputSchema??null}function yt(r,e){if(!r||!e?.properties)return{};let t=r.match(/^([^:]+\/[^:]+):([^:]+):(.+)$/);if(!t)return{};let[,n,o,i]=t,s={};if(e.properties.project&&(s.project=n),o==="push"){let a=i.match(/^refs\/heads\/(.+)$/);a&&e.properties.ref&&(s.ref=a[1])}else{let a=Number(i);Number.isFinite(a)&&(e.properties.id&&(s.id=a),e.properties.iid&&(s.iid=a),e.properties.mrId&&(s.mrId=a),e.properties.issueId&&(s.issueId=a),e.properties.prId&&(s.prId=a))}return s}function kt(r,e){if(!r?.properties)return e;let t={...e};for(let[n,o]of Object.entries(r.properties))t[n]===void 0&&o&&"default"in o&&(t[n]=o.default);return t}function bt(r,e){return!r?.required||!Array.isArray(r.required)?[]:r.required.filter(t=>{let n=e[t];return n===void 0||n===""||n===null})}function ir(r,e){let t=wt(r);if(!t?.properties){let d={};for(let[c,l]of Object.entries(e))l!==void 0&&(d[c]=l);return{inputs:d,missing:[],filledFrom:{passthrough:Object.keys(d),chatId:[],defaults:[]}}}let n={};for(let d of["message","agentId","channel","chatId","senderId","senderUsername"])t.properties[d]&&e[d]!==void 0&&(n[d]=e[d]);let o=yt(e.chatId,t),i={...n,...o},s={...i};i=kt(t,i);let a=Object.keys(i).filter(d=>s[d]===void 0&&i[d]!==void 0);return{inputs:i,missing:bt(t,i),filledFrom:{passthrough:Object.keys(n),chatId:Object.keys(o),defaults:a}}}export{Ue as a,ze as b,$ as c,ae as d,v as e,L as f,Vt as g,le as h,fe as i,me as j,Ie as k,Gn as l,tr as m,gn as n,ir as o};
|
|
19
|
-
//# sourceMappingURL=chunk-
|
|
19
|
+
//# sourceMappingURL=chunk-CELYD5QW.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{g as j,h as x,o as O,p as I}from"./chunk-S7CVSKOX.js";import{
|
|
1
|
+
import{g as j,h as x,o as O,p as I}from"./chunk-S7CVSKOX.js";import{n as S,q as L}from"./chunk-U4H35SJS.js";L();import{Command as z}from"commander";import f from"chalk";import{execFileSync as h}from"child_process";import{accessSync as E,constants as T,existsSync as y,readFileSync as b,readdirSync as $,statSync as B}from"fs";import{join as P,resolve as m}from"path";import{homedir as M}from"os";import{createRequire as X}from"module";import{execFile as _}from"child_process";var q=(n,t)=>new Promise(e=>{try{_(n,t,{timeout:5e3},(i,s)=>e(i?null:String(s)))}catch{e(null)}}),R="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function N(n={}){if((n.platform??process.platform)!=="darwin")return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let t=n.helper===void 0?I():n.helper;if(!t)return{state:"missing",message:"AgentX Helper is not installed, so banners come from Script Editor and show its icon.",fix:'Run agentx desktop install, then run agentx notify "Hello" --title "Test" and click Allow.'};let e=await(n.run??q)(t,["notify-status"]),i=null;try{i=e?JSON.parse(e):null}catch{i=null}return i?i.authorization==="notDetermined"?{state:"not-asked",path:t,message:"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.",fix:'Run agentx notify "Hello" --title "Test" and click Allow when macOS asks.'}:i.authorization==="denied"?{state:"not-allowed",path:t,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:R}:i.alertStyle==="none"?{state:"hidden",path:t,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:R}:{state:"ready",path:t,message:"AgentX Helper posts banners with the AgentX icon."}:{state:"outdated",path:t,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}}async function J(n={}){let t=[];await G(t),V(t);let e=K(t);return e&&U(t,e),e&&Q(t,e),e&&Y(t,e),e&&ee(t,e),e&&ne(t,e),e&&await F(t,e),e&&Z(t,e),n.running!==!1&&e&&await te(t,e),{checks:t,summary:W(t)}}var we=new z().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async n=>{let{checks:t,summary:e}=await J({running:n.running!==!1});n.json?process.stdout.write(JSON.stringify({checks:t,summary:e},null,2)+`
|
|
2
2
|
`):ie(t),process.exit(e.errors>0?1:0)});async function F(n,t,e=N){if(!O(t.notifications?.local).banner)return;let i=await e();i.state!=="unsupported"&&n.push({severity:i.state==="ready"?"ok":"warn",group:"Notifications",title:i.message,detail:i.path,fix:i.fix})}function Z(n,t,e=process.platform,i=s=>{try{return E(s,T.X_OK),!0}catch{return!1}}){let s=t.reminders;if(!s?.enabled)return;if(e!=="darwin"){n.push({severity:"warn",group:"Reminders",title:"Reminders hand-back unavailable on this machine",detail:"reminders.enabled is set, but Apple Reminders exists only on macOS. The daemon starts without it.",fix:"Set reminders.enabled to false here, or enable it on the Mac node instead."});return}let r=s.command||"remindctl",a=r.includes("/")?i(r)?r:null:x(r,process.env.PATH||"",i);n.push(a?{severity:"ok",group:"Reminders",title:`Watching ${(s.lists||[]).join(", ")} for due reminders`,detail:a}:{severity:"fail",group:"Reminders",title:`${r} not found`,detail:"The daemon reads Apple Reminders through remindctl.",fix:"brew install steipete/tap/remindctl, or set reminders.command to its full path."})}async function G(n){let t=Number(process.versions.node.split(".")[0]);n.push({severity:t==22?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:t==22?void 0:"AgentX requires Node 22.x.",fix:t==22?void 0:"Install Node 22 (nvm install 22 && nvm use 22)"});let e=l=>{try{return h(process.platform==="win32"?"where":"which",[l],{encoding:"utf-8"}).trim().split(`
|
|
3
3
|
`)[0]}catch{return null}},i=e("npm");n.push({severity:i?"ok":"fail",group:"Environment",title:i?"npm on PATH":"npm not found",detail:i||void 0});let s=e("claude");if(s){let l;try{l=h("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"Environment",title:`claude CLI ${l||"installed"}`,detail:s})}else n.push({severity:"warn",group:"Environment",title:"claude CLI not on PATH",detail:"Only required for agents on the claude-code tier.",fix:"See https://docs.anthropic.com/en/docs/claude-code"});let r=e("codex");if(r){let l;try{l=h("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"Environment",title:`codex CLI ${l||"installed"}`,detail:r})}else n.push({severity:"warn",group:"Environment",title:"codex CLI not on PATH",detail:"Only required for agents on the codex-cli tier.",fix:"Install with `npm i -g @openai/codex`."});let a=e("opencode");if(a){let l;try{l=h("opencode",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"Environment",title:`opencode CLI ${l||"installed"}`,detail:a})}else n.push({severity:"warn",group:"Environment",title:"opencode CLI not on PATH",detail:"Only required for agents on the opencode tier.",fix:"Install from https://opencode.ai/docs/."});try{X(import.meta.url)("better-sqlite3"),n.push({severity:"ok",group:"Environment",title:`better-sqlite3 loads for Node ${process.version}`,detail:`NODE_MODULE_VERSION ${process.versions.modules}`})}catch(l){n.push({severity:"fail",group:"Environment",title:"better-sqlite3 native binding does not load",detail:l?.message??String(l),fix:`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`})}}function V(n){if(process.platform!=="darwin")return;let t=P(M(),"Library/LaunchAgents"),e=[];try{e=$(t).filter(s=>/agentx\.voice.*\.plist$/.test(s))}catch{return}let i=s=>{try{return E(s,T.X_OK),!0}catch{return!1}};for(let s of e){let r=j(b(P(t,s),"utf-8")),a=x("ffmpeg",r,i);n.push(a?{severity:"ok",group:"Desktop",title:"ffmpeg reachable by the desktop app",detail:`${a} (${s})`}:{severity:"warn",group:"Desktop",title:"ffmpeg not reachable by the desktop app",detail:`Local Whisper transcription fails without it. ${s} sets PATH to ${r}.`,fix:"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install."})}}function K(n){let t=m(process.cwd(),"agentx.json");if(!y(t))return n.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${t}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let e;try{e=JSON.parse(b(t,"utf-8"))}catch(a){return n.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:a.message}),null}try{S(t),n.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(e.agents||{}).length} agents, ${Object.keys(e.crons||{}).length} schedules)`})}catch(a){n.push({severity:"fail",group:"Config",title:"agentx.json failed schema validation",detail:a.message,fix:"Open /admin \u2192 Advanced tab to edit and re-save."})}let i=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="claude-code");i.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["claude"],{stdio:"ignore"}),!0}catch{return!1}})()||n.push({severity:"fail",group:"Config",title:`${i.length} agent(s) use claude-code tier but claude CLI is missing`,detail:i.map(([l])=>l).join(", "),fix:"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk."}));let s=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="codex-cli");s.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["codex"],{stdio:"ignore"}),!0}catch{return!1}})()||n.push({severity:"fail",group:"Config",title:`${s.length} agent(s) use codex-cli tier but codex CLI is missing`,detail:s.map(([l])=>l).join(", "),fix:"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code."}));let r=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="opencode");return r.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||n.push({severity:"fail",group:"Config",title:`${r.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:r.map(([l])=>l).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function U(n,t){let e=new Set;if(C(t,e),e.size===0){n.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let i=m(process.cwd(),".env"),s={};if(y(i))for(let l of b(i,"utf-8").split(/\r?\n/)){let u=l.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);u&&(s[u[1]]=u[2])}let r=[],a=[];for(let l of e){let u=process.env[l]??s[l];u===void 0?r.push(l):(!u.trim()||/^["']?\s*["']?$/.test(u))&&a.push(l)}r.length===0&&a.length===0?n.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(r.length>0&&n.push({severity:"fail",group:"Secrets",title:`${r.length} env var(s) referenced in agentx.json but missing`,detail:r.join(", "),fix:`Add to .env \u2014 e.g. ${r[0]}=<value>`}),a.length>0&&n.push({severity:"warn",group:"Secrets",title:`${a.length} env var(s) set but empty`,detail:a.join(", ")}))}function C(n,t){if(typeof n=="string")for(let e of n.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))t.add(e[1]);else if(Array.isArray(n))for(let e of n)C(e,t);else if(n&&typeof n=="object")for(let e of Object.values(n))C(e,t)}function Q(n,t){let e=[];for(let[i,s]of Object.entries(t.agents||{})){if(!s.workspace)continue;let r=s.workspace.startsWith("/")?s.workspace:m(process.cwd(),s.workspace);try{B(r).isDirectory()||e.push(`${i}: ${r} (exists but not a directory)`)}catch{e.push(`${i}: ${r}`)}}e.length===0?n.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):n.push({severity:"warn",group:"Workspaces",title:`${e.length} agent workspace(s) missing`,detail:e.join(`
|
|
4
4
|
`),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}function Y(n,t){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[s,r]of Object.entries(t.agents||{})){if(!r.workspace)continue;let a=r.workspace.startsWith("/")?r.workspace:m(process.cwd(),r.workspace);for(let l of["settings.json","settings.local.json"]){let u=m(a,".claude",l);if(!y(u))continue;let w;try{w=JSON.parse(b(u,"utf-8"))}catch(d){i.push({severity:"fail",agent:s,msg:`${l}: JSON parse error \u2014 ${d.message}`});continue}let k=w.env||{};for(let[d,p]of Object.entries(k)){if(typeof p!="string")continue;let g=p.match(e);g&&i.push({severity:"fail",agent:s,msg:`${l} env.${d} contains unexpanded ${[...new Set(g)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let o=k.PATH;if(typeof o=="string"){let d=o.split(":").filter(Boolean);d.includes("/usr/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),d.includes("/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /bin \u2014 ls/cp/mv will fail`})}let c=w.permissions;if(c&&typeof c=="object"&&"allow"in c){let d=c.allow,p=c.deny;Array.isArray(d)&&d.length===0&&Array.isArray(p)&&p.length>0&&i.push({severity:"warn",agent:s,msg:`${l} permissions.allow is explicitly [] with ${p.length} deny rules \u2014 agent may be locked out (omit the key to use defaults instead)`})}}}if(i.length===0){n.push({severity:"ok",group:"Workspace settings",title:`All ${Object.keys(t.agents||{}).length} agent .claude/settings.json files clean`});return}for(let s of i)n.push({severity:s.severity,group:"Workspace settings",title:`${s.agent}: ${s.msg}`,fix:s.severity==="fail"?"Edit .claude/settings.json \u2014 replace ${VAR} with the literal value or omit the key to inherit.":"Either remove the empty allow list or populate it."})}function ee(n,t){let e=t.webhooks??[],i=[],s=m(process.cwd(),t.workflows?.dir||".agentx/workflows"),r=new Set;try{if(y(s))for(let o of $(s))o.endsWith(".json")&&!o.startsWith("_")&&!o.endsWith(".disabled.json")&&r.add(o.replace(/\.json$/,""))}catch{}let a=new Set(["github","gitlab"]);for(let o of e){if(!o.enabled||!a.has(o.source))continue;!(o.triggers&&Object.keys(o.triggers).length>0)&&!o.defaultWorkflow&&i.push({severity:"warn",title:`webhook "${o.id}" (${o.source} -> ${o.agentId}) has no triggers map; every event-type collapses to the bound agent`,fix:'Add a triggers map: { "issues.opened": "wf-id", "pull_request.synchronize": "wf-id" } \u2014 or set defaultWorkflow.'})}for(let o of e)if(!(!o.enabled||!o.triggers)){for(let[c,d]of Object.entries(o.triggers))r.size>0&&!r.has(d)&&i.push({severity:"fail",title:`webhook "${o.id}".triggers["${c}"] -> "${d}" \u2014 no such workflow under ${t.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});o.defaultWorkflow&&r.size>0&&!r.has(o.defaultWorkflow)&&i.push({severity:"fail",title:`webhook "${o.id}".defaultWorkflow -> "${o.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}try{if(y(s)){for(let o of $(s))if(!(!o.endsWith(".json")||o.startsWith("_")||o.endsWith(".disabled.json")))try{let c=JSON.parse(b(m(s,o),"utf-8"));c?.status==="active"&&c?.state==="quarantined"&&i.push({severity:"warn",title:`workflow "${c.id??o}" is status=active but state=quarantined \u2014 it looks live but will never dispatch`,fix:'Resolve the conflict the detector flagged, then set state back to "active" (or set status to "review" while parked).'})}catch{}}}catch{}let l=new Set((t.mesh?.peers??[]).map(o=>o.name));for(let o of e)!o.enabled||!o.node||l.has(o.node)||i.push({severity:"fail",title:`webhook "${o.id}" routes to mesh peer "${o.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or remove the node field on the webhook."});let u=new Map;for(let o of e){if(!o.enabled)continue;let c=`${o.source}:${o.agentId}`,d=u.get(c);d?i.push({severity:"warn",title:`webhook entries "${d}" and "${o.id}" both enabled for ${o.source} -> ${o.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):u.set(c,o.id)}let w=new Set(Object.keys(t.agents??{}));for(let o of t.channels?.gitlab?.agentMappings??[])if(o?.agentId){if(o.node){l.has(o.node)||i.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${o.agentId}" routes to mesh peer "${o.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or drop the node field on the mapping."});continue}w.has(o.agentId)||i.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${o.agentId}" \u2014 no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,fix:'Add the agent to agents.*, set node:"<peer>" if the agent lives remotely, or remove the mapping.'})}for(let[o,c]of Object.entries(t.channels?.telegram?.accounts??{}))c.agentBinding?w.has(c.agentBinding)||i.push({severity:"fail",title:`telegram account "${o}".agentBinding -> "${c.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):i.push({severity:"fail",title:`telegram account "${o}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});let k=new Set(["telegram-bot","whatsapp","slack-bot","discord-bot","gitlab-user","github-user","gmail","hotmail","smtp","hubspot","salesforce","pipedrive","odoo","trello","linear","asana","jira","notion","stripe","sentry","vercel","twilio","custom"]);for(let[o,c]of Object.entries(t.agents??{})){let d=c.integrations??[];if(!d.length)continue;let p=new Set;for(let g of d){let A=`${g.kind}::${g.label}`;p.has(A)&&i.push({severity:"warn",title:`agents.${o}.integrations: duplicate (${g.kind}, ${g.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),p.add(A),k.has(g.kind)||i.push({severity:"warn",title:`agents.${o}.integrations: unknown kind "${g.kind}" on integration "${g.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let H=g.credentials||{};for(let[D,v]of Object.entries(H))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&i.push({severity:"warn",title:`agents.${o}.integrations[${g.kind}/${g.label}].${D} -> $${v} but env var is unset (in this shell)`,fix:`Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`})}}if(i.length===0){n.push({severity:"ok",group:"Routing",title:`${e.length} webhook(s), ${Object.keys(t.channels?.telegram?.accounts??{}).length} telegram account(s) \u2014 all routing references resolve`});return}for(let o of i)n.push({severity:o.severity,group:"Routing",title:o.title,fix:o.fix})}async function te(n,t){let e=t.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",i={};t.dashboard?.token&&(i.Authorization=`Bearer ${t.dashboard.token}`);try{let s=new AbortController,r=setTimeout(()=>s.abort(),2e3),a=await fetch(e+"/health",{headers:i,signal:s.signal});if(clearTimeout(r),!a.ok){n.push({severity:"warn",group:"Runtime",title:`Daemon responded ${a.status}`,detail:e});return}let l=await a.json();n.push({severity:"ok",group:"Runtime",title:`Daemon healthy \u2014 ${l.agents?.length??0} agents live, uptime ${Math.round((l.uptime??0)/60)}m`,detail:e})}catch{n.push({severity:"warn",group:"Runtime",title:"Daemon not reachable (not running?)",detail:e,fix:"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`."})}}function ne(n,t){let e=Object.entries(t.agents||{}).filter(([,s])=>s?.codegraph===!0&&(s.tier==="claude-code"||s.tier==="codex-cli"));if(e.length===0)return;let i=null;try{i=h(process.platform==="win32"?"where":"which",["codegraph"],{encoding:"utf-8"}).trim().split(`
|
|
5
5
|
`)[0]||null}catch{i=null}if(i){let s;try{s=h("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${s||"installed"}`,detail:i})}else n.push({severity:"fail",group:"CodeGraph",title:"codegraph CLI not on PATH",detail:`${e.length} agent(s) have codegraph:true but the binary isn't available.`,fix:"Install with `npm i -g @colbymchenry/codegraph`."});for(let[s,r]of e){if(!r.workspace||!y(r.workspace)){n.push({severity:"warn",group:"CodeGraph",title:`${s}: workspace missing`,detail:`Workspace path ${r.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let a=m(r.workspace,".codegraph","codegraph.db");y(a)?n.push({severity:"ok",group:"CodeGraph",title:`${s}: index present`,detail:a}):n.push({severity:"warn",group:"CodeGraph",title:`${s}: index not built yet`,detail:".codegraph/ missing \u2014 daemon will background-index this workspace on next boot.",fix:`Run \`codegraph init --index ${r.workspace}\` to build it now.`})}}function W(n){return{errors:n.filter(t=>t.severity==="fail").length,warnings:n.filter(t=>t.severity==="warn").length,ok:n.filter(t=>t.severity==="ok").length}}function ie(n){console.log(),console.log(f.bold(" agentx doctor")),console.log();let t=new Map;for(let i of n)t.has(i.group)||t.set(i.group,[]),t.get(i.group).push(i);for(let[i,s]of t){console.log(f.bold(" "+i));for(let r of s){let a=r.severity==="ok"?f.green("\u2713"):r.severity==="warn"?f.yellow("!"):f.red("\u2717");console.log(` ${a} ${r.title}`),r.detail&&console.log(f.dim(" "+r.detail.replace(/\n/g,`
|
|
6
6
|
`))),r.fix&&console.log(f.dim(" \u2192 "+r.fix))}console.log()}let e=W(n);e.errors>0?console.log(f.red.bold(` ${e.errors} error${e.errors===1?"":"s"}`)+(e.warnings?f.yellow(`, ${e.warnings} warning${e.warnings===1?"":"s"}`):"")+`. Fix the error${e.errors===1?"":"s"} and rerun.`):e.warnings>0?console.log(f.yellow.bold(` ${e.warnings} warning${e.warnings===1?"":"s"}.`)+f.dim(" Review but not blocking.")):console.log(f.green.bold(` All checks passed (${e.ok}).`)),console.log()}export{N as a,J as b,we as c,F as d,Z as e};
|
|
7
|
-
//# sourceMappingURL=chunk-
|
|
7
|
+
//# sourceMappingURL=chunk-D3LSPFHK.js.map
|