agentix-cli 0.214.0 → 0.215.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/dist/{agent-KUCECPSZ.js → agent-KOKQSRAH.js} +2 -2
- package/dist/{board-dashboard-SHU4BWRO.js → board-dashboard-NVQUQSWI.js} +2 -2
- package/dist/{board-dashboard-SHU4BWRO.js.map → board-dashboard-NVQUQSWI.js.map} +1 -1
- package/dist/chunk-4BYJN2A3.js +4 -0
- package/dist/chunk-4BYJN2A3.js.map +1 -0
- package/dist/{chunk-SPXXLPAS.js → chunk-4DCQIHWU.js} +2 -2
- package/dist/{chunk-2KNI7ZRN.js → chunk-7AFXLWWW.js} +2 -2
- package/dist/chunk-7YOLZGB5.js +2 -0
- package/dist/chunk-7YOLZGB5.js.map +1 -0
- package/dist/chunk-GGAEFVXL.js +42 -0
- package/dist/chunk-GGAEFVXL.js.map +1 -0
- package/dist/chunk-HVMUYEQP.js +4 -0
- package/dist/chunk-HVMUYEQP.js.map +1 -0
- package/dist/{chunk-SBFMNAJG.js → chunk-JLH73NRM.js} +88 -88
- package/dist/chunk-JLH73NRM.js.map +1 -0
- package/dist/{chunk-C3O2ER6D.js → chunk-Q7Y5VQGX.js} +2 -2
- package/dist/{chunk-UNVZUWOY.js → chunk-QMICGPM6.js} +3 -3
- package/dist/{chunk-UNVZUWOY.js.map → chunk-QMICGPM6.js.map} +1 -1
- package/dist/{chunk-Z4WM7MKP.js → chunk-QOGZD6Z3.js} +268 -268
- package/dist/chunk-QOGZD6Z3.js.map +1 -0
- package/dist/chunk-Z5CMA4JN.js +6 -0
- package/dist/chunk-Z5CMA4JN.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/decision-approvals-SWZ4RWFI.js +2 -0
- package/dist/hub-V2AGLA7T.js +2 -0
- package/dist/index.d.ts +93 -0
- package/dist/index.js +1 -1
- package/dist/{program-L3BX5FJ3.js → program-WSGVQTFM.js} +153 -153
- package/dist/{program-L3BX5FJ3.js.map → program-WSGVQTFM.js.map} +1 -1
- package/dist/{query-runs-AENEZOM6.js → query-runs-2F6KHFBZ.js} +2 -2
- package/dist/{registry-D727ZQUP.js → registry-KRU6AWVW.js} +2 -2
- package/dist/timers-LAT4ZVXJ.js +2 -0
- package/dist/wiki-IDLRJ6WL.js +2 -0
- package/dist/wiki-enrich-XWLDJAZI.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-AFRHKA7B.js +0 -2
- package/dist/chunk-AFRHKA7B.js.map +0 -1
- package/dist/chunk-FR4DTMCA.js +0 -42
- package/dist/chunk-FR4DTMCA.js.map +0 -1
- package/dist/chunk-HPRLRD4P.js +0 -6
- package/dist/chunk-HPRLRD4P.js.map +0 -1
- package/dist/chunk-LIY5CHUV.js +0 -4
- package/dist/chunk-LIY5CHUV.js.map +0 -1
- package/dist/chunk-RMXG5GNW.js +0 -4
- package/dist/chunk-RMXG5GNW.js.map +0 -1
- package/dist/chunk-SBFMNAJG.js.map +0 -1
- package/dist/chunk-Z4WM7MKP.js.map +0 -1
- package/dist/decision-approvals-NJS2ARAF.js +0 -2
- package/dist/hub-PPQGFC35.js +0 -2
- package/dist/timers-KK7GF77Y.js +0 -2
- package/dist/wiki-FP4JMCYP.js +0 -2
- package/dist/wiki-enrich-3SPIVYSG.js +0 -2
- /package/dist/{agent-KUCECPSZ.js.map → agent-KOKQSRAH.js.map} +0 -0
- /package/dist/{chunk-SPXXLPAS.js.map → chunk-4DCQIHWU.js.map} +0 -0
- /package/dist/{chunk-2KNI7ZRN.js.map → chunk-7AFXLWWW.js.map} +0 -0
- /package/dist/{chunk-C3O2ER6D.js.map → chunk-Q7Y5VQGX.js.map} +0 -0
- /package/dist/{decision-approvals-NJS2ARAF.js.map → decision-approvals-SWZ4RWFI.js.map} +0 -0
- /package/dist/{hub-PPQGFC35.js.map → hub-V2AGLA7T.js.map} +0 -0
- /package/dist/{query-runs-AENEZOM6.js.map → query-runs-2F6KHFBZ.js.map} +0 -0
- /package/dist/{registry-D727ZQUP.js.map → registry-KRU6AWVW.js.map} +0 -0
- /package/dist/{timers-KK7GF77Y.js.map → timers-LAT4ZVXJ.js.map} +0 -0
- /package/dist/{wiki-FP4JMCYP.js.map → wiki-IDLRJ6WL.js.map} +0 -0
- /package/dist/{wiki-enrich-3SPIVYSG.js.map → wiki-enrich-XWLDJAZI.js.map} +0 -0
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import{a as fe}from"./chunk-7AB3QUGH.js";import{b as Ue}from"./chunk-7YOLZGB5.js";import{b as qt,c as Gt}from"./chunk-IH65GDJR.js";import{b as Ct,f as Ft,g as _t,j as Ht,l as Bt,m as Kt,s as zt}from"./chunk-CAH6TNC6.js";import{a as Lt}from"./chunk-GV7S5BAX.js";import{c as Ut}from"./chunk-SZDACK6O.js";import{b as Mt,d as Et,e as jt}from"./chunk-5ONH4ITT.js";import{e as Nt,g as Ot,h as Dt,i as Le}from"./chunk-JRAG37V5.js";import{a as Pt,b as Ce,d as Fe,e as Wt,f as _e}from"./chunk-BERWTVG2.js";import{a as ne,b as Tt}from"./chunk-A7JSRDJL.js";import{c as At,d as St}from"./chunk-AHWWJ7AF.js";import{y as xt,z as Tr}from"./chunk-MIUITI47.js";import{b as Rt,f as Wr}from"./chunk-72SZI2UW.js";import{Ia as Pr,wa as je}from"./chunk-KAM4ZWRE.js";import{j as Ee,r as xr}from"./chunk-N47Y5ADQ.js";import{existsSync as Nr,mkdirSync as Jt,readFileSync as Or,writeFileSync as Dr,renameSync as Mr}from"fs";import{resolve as Yt,dirname as Er}from"path";var Vt=class{filePath;log;constructor(e={}){let t=e.baseDir??Yt(process.cwd(),".agentx");this.filePath=Yt(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),Jt(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!Nr(this.filePath))return{version:1,overrides:{}};try{let e=Or(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){Jt(Er(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Dr(t,JSON.stringify(e,null,2)),Mr(t,this.filePath)}get(e,t,r){let s=this.load().overrides[this.key(e,t,r)];if(s&&!(s.expiresAt&&Date.parse(s.expiresAt)<Date.now()))return s}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),s=this.key(e,t,r);return s in o.overrides?(delete o.overrides[s],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),s=o.overrides[this.key(e,t,r)];if(!s||!s.summary||s.summaryConsumedAt)return;let i=s.summary;return s.summaryConsumedAt=new Date().toISOString(),this.save(o),i}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{readFileSync as tn,writeFileSync as He,appendFileSync as _r,mkdirSync as Lr,existsSync as nn,statSync as Ur}from"fs";import{resolve as ge}from"path";var Qt="[Agent Memory \u2014 persistent facts from past conversations]",jr=2400;function Zt(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function Cr(n,e=Date.now()){let t=Et(n,e),r=n.undated?"UNVERIFIED (never checked) ":Zt(t,Nt(n.verifiedAt,e));return{line:`- [wiki ${n.id}] ${r}${n.subject} \xB7 ${n.attribute}: ${n.value} (${n.source}, checked ${n.verifiedAt.slice(0,10)} by ${n.verifiedBy})`,unverified:t}}function Fr(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId;if(ne(n.content))return{line:`- [${n.category}] ${Tt}${n.content} (${r}, ${n.source.date})`,unverified:!0};let o=Dt(n,e);return{line:`- [${n.category}] ${Zt(o,Ot(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function Xt(n,e=[],t=Date.now()){let r=[],o=new Set,s=Qt.length,i=!1;for(let a of n){let d=e.length>0?jt(a.content,e):null,u,c,p=d&&Date.parse(a.createdAt)>Date.parse(d.verifiedAt)&&!a.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!p){if(o.has(d.id))continue;o.add(d.id),u=Cr(d,t),c=d.id}else u=Fr(a,t),d&&(u.line+=` [differs from wiki ${d.id}]`);let f=u.unverified&&!i?Le.length:0;if(s+f+u.line.length>jr)break;r.push({fact:a,...u,...c?{wikiRef:c}:{}}),s+=f+u.line.length,f&&(i=!0)}return r}function en(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[Le]:[];return[Qt,...e,...n.map(t=>t.line),"[End Memory]"].join(`
|
|
2
|
+
`)}var rn=200,Hr=7,on=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=ge(e,".agentx/memory"),this.ledger=new Mt(ge(e,".agentx/wiki")),nn(this.memoryDir)||Lr(this.memoryDir,{recursive:!0})}filePath(e){return ge(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||Ce(t.content)||ne(t.content))return!1;let r=t.source.trust??Pt(t.source.channel),o=t.review??Wt(r),s={...t,source:{...t.source,trust:r},...o?{review:o}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return _r(this.filePath(e),JSON.stringify(s)+`
|
|
3
|
+
`),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!nn(t))return[];try{let{mtimeMs:r,size:o}=Ur(t),s=this.parsedCache.get(t);if(s&&s.mtimeMs===r&&s.size===o)return s.facts.slice();let a=tn(t,"utf-8").split(`
|
|
4
|
+
`).filter(d=>d.trim()).map(d=>{try{return JSON.parse(d)}catch{return null}}).filter(d=>d!==null);return this.parsedCache.set(t,{mtimeMs:r,size:o,facts:a}),a.slice()}catch{return[]}}findRelevant(e,t,r=8){let o=this.getAll(t).filter(_e);if(o.length===0)return[];let s=o.map(g=>`${g.keywords.join(" ")} ${g.content}`),i=ge(this.memoryDir,`${t}_bm25_cache.json`),a=St(s,i),d=At(e,a),u=new Map(d.map(g=>[g.docIndex,g.score])),p=o.map((g,m)=>{let y=u.get(m)??0;return g.category==="commitment"&&(y+=1),{memory:g,score:y}}).filter(g=>g.score>0);if(p.length===0)return o.slice(-r);let f=p.sort((g,m)=>m.score-g.score).slice(0,r).map(g=>g.memory);if(f.length>0)try{this.recordAccess(t,f.map(g=>g.id))}catch{}return f}buildContext(e){return en(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return Xt(e,t)}recordAccess(e,t){if(t.length===0)return;let r=this.getAll(e),o=new Set(t),s=!1;for(let i of r)if(o.has(i.id)){i.accessCount=(i.accessCount||0)+1,i.lastAccessed=new Date().toISOString();let a=i.intervalDays||1;i.intervalDays=Math.min(a*2,30),i.nextReview=new Date(Date.now()+i.intervalDays*864e5).toISOString(),s=!0}s&&He(this.filePath(e),r.map(i=>JSON.stringify(i)).join(`
|
|
5
|
+
`)+`
|
|
6
|
+
`)}getDueForReview(e,t=5){let r=this.getAll(e).filter(_e),o=Date.now();return r.filter(s=>s.category==="task-state"||ne(s.content)?!1:s.nextReview?new Date(s.nextReview).getTime()<=o:!0).sort((s,i)=>!s.nextReview&&i.nextReview?-1:s.nextReview&&!i.nextReview?1:s.nextReview&&i.nextReview?new Date(s.nextReview).getTime()-new Date(i.nextReview).getTime():(s.accessCount||0)-(i.accessCount||0)).slice(0,t)}buildRecallContext(e){let t=this.getDueForReview(e,5);if(t.length===0)return"";let r=["[Memory Recall \u2014 facts due for review, verify they are still accurate]"];for(let o of t){let s=Math.round((Date.now()-new Date(o.createdAt).getTime())/864e5);r.push(`- [${o.category}] ${o.content} (${s}d old, accessed ${o.accessCount||0}x)`)}return r.push("[If any fact is outdated, note the correction. Otherwise, acknowledge recall.]"),r.join(`
|
|
7
|
+
`)}held(e){return this.getAll(e).filter(t=>t.review==="held"||t.review===void 0&&Fe(t)==="external")}review(e,t,r,o="operator"){let s=this.getAll(e),i=s.find(a=>a.id===t);return i?(i.review=r,i.reviewedBy=o,i.reviewedAt=new Date().toISOString(),this.rewrite(e,s),!0):!1}scrubSecrets(e,t=!1){let r=this.getAll(e),o=r.filter(i=>i.category!=="secret"&&!Ce(i.content)),s=r.length-o.length;return t&&s>0&&this.rewrite(e,o),s}trustSummary(e){let t={};for(let r of this.getAll(e)){let o=`${Fe(r)}${r.review?`/${r.review}`:""}`;t[o]=(t[o]??0)+1}return t}fileFor(e){return this.filePath(e)}rewrite(e,t){let r=[];try{r=tn(this.filePath(e),"utf-8").split(`
|
|
8
|
+
`).filter(s=>{if(!s.trim())return!1;try{return JSON.parse(s),!1}catch{return!0}})}catch{}let o=[...t.map(s=>JSON.stringify(s)),...r];He(this.filePath(e),o.join(`
|
|
9
|
+
`)+(o.length?`
|
|
10
|
+
`:""))}hasSimilar(e,t){let r=this.getAll(e),s=t.toLowerCase().split(/\s+/).filter(i=>i.length>3);return r.some(i=>{let a=i.content.toLowerCase();return s.filter(u=>a.includes(u)).length>=s.length*.7})}prune(e){let t=this.getAll(e);if(t.length===0)return;let r=Date.now(),o=Hr*24*60*60*1e3;t=t.filter(i=>i.category==="task-state"&&i.expiresAt?new Date(i.expiresAt).getTime()>r:i.category==="task-state"&&!i.expiresAt?r-new Date(i.createdAt).getTime()<o:!0),t.length>rn&&(t=t.slice(-rn));let s=this.filePath(e);He(s,t.map(i=>JSON.stringify(i)).join(`
|
|
11
|
+
`)+`
|
|
12
|
+
`)}};function sn(n){let e=(n||"").trim();for(let t=0;t<5;t++){let r=e;if(e=e.replace(/^Peer\s+"[^"]*"\s+\/task error:\s*\d{3}:\s*/i,"").replace(/^Peer\s+"[^"]*"\s+agent error:\s*/i,"").replace(/^mesh fallback failed:\s*/i,"").trim(),e===r)break}return e}var Br="__queued__";function qi(n,e){return`${Br}:${n}:${e}`}var Kr=/^__queued__(?::([A-Za-z-]+):(\d+))?$/;function qr(n){if(!n)return null;let e=Kr.exec(sn(n));return e?{mode:e[1]||"collect",pending:e[2]?Number(e[2]):1}:null}function Gi(n){return qr(n)!==null}var Gr=.8,J="fleet",Ke=n=>`project:${n}`,T={},M="",L=new Map,q=new Map,z=new Set,un=()=>null;function zr(n=Date.now()){return new Date(n).toISOString().slice(0,7)}function Yi(n=Date.now()){let e=new Date(n);return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),1)}function he(n){let e=zr(n);e!==M&&(M=e,L.clear(),q.clear(),z.clear())}function K(n){return typeof n?.monthlyUsd=="number"&&n.monthlyUsd>0?n.monthlyUsd:void 0}function we(n){let e=n?.warnRatio;return typeof e=="number"&&e>0&&e<=1?e:Gr}function qe(){let n=0;for(let e of L.values())n+=e;return n}function W(n){return`$${n<1?n.toFixed(4).replace(/0{1,2}$/,""):n.toFixed(2)}`}function Vi(n){T=n??{}}function Qi(n){un=n??(()=>null)}function Zi(n,e){return un(n,e)}function ln(n,e,t){let r=K(t);if(!r)return[];let o=[];return e>=r?o.push({kind:"cap",key:`${n}:cap:${r}`,cap:r}):e>=r*we(t)&&o.push({kind:"warn",key:`${n}:warn:${r}`,cap:r}),o}function an(n,e){e.clear();for(let[t,r]of Object.entries(n))Number.isFinite(r)&&r>0&&e.set(t,r)}function Xi(n,e=Date.now(),t={}){he(e),an(n,L),an(t,q);let r=(o,s,i)=>{for(let a of ln(o,s,i))z.add(a.key),a.kind==="cap"&&z.add(`${o}:warn:${a.cap}`)};for(let[o,s]of L)r(o,s,T.agents?.[o]);for(let[o,s]of q)r(Ke(o),s,T.projects?.[o]);r(J,qe(),T.fleet)}function me(n){return n===J?`the fleet cap on the ${fe}'s Cost page or budget.monthlyUsd in agentx.json`:n.startsWith("project:")?`the cap of project ${n.slice(8)} on the ${fe}'s Cost page or its budget.monthlyUsd under dashboard.wall.projects in agentx.json`:`the cap on the ${fe}'s Cost page or agents.${n}.budget.monthlyUsd in agentx.json`}function Jr(n,e,t,r,o){let s=e===J?"The fleet":e.startsWith("project:")?`Project ${e.slice(8)}`:`Agent ${e}`,i=me(e);if(n==="warn")return{kind:n,scope:e,month:M,spentUsd:t,capUsd:r,title:`${s} is near its monthly budget`,message:`${s} has spent ${W(t)} of its ${W(r)} budget for ${M} (${Math.round(t/r*100)}%, warning at ${Math.round(we(o)*100)}%). At ${W(r)} new runs stop until the month ends or you raise ${i}.`};let a=e===J?"Every agent is":e.startsWith("project:")?"Its work is":"It is";return{kind:n,scope:e,month:M,spentUsd:t,capUsd:r,title:`${s} reached its monthly budget`,message:`${s} has spent ${W(t)} of its ${W(r)} budget for ${M}. ${a} paused: new runs are refused until the month ends or you raise ${i} (applies on save).`}}function ea(n,e,t=Date.now(),r){if(he(t),typeof e!="number"||!Number.isFinite(e)||e<=0)return[];let o=(L.get(n)??0)+e;L.set(n,o);let s=[],i=(a,d,u)=>{for(let c of ln(a,d,u))z.has(c.key)||(z.add(c.key),c.kind==="cap"&&z.add(`${a}:warn:${c.cap}`),s.push(Jr(c.kind,a,d,c.cap,u)))};if(i(n,o,T.agents?.[n]),r){let a=(q.get(r)??0)+e;q.set(r,a),i(Ke(r),a,T.projects?.[r])}return i(J,qe(),T.fleet),s}function ta(n,e=Date.now(),t){he(e);let r=K(T.agents?.[n]),o=L.get(n)??0;if(r&&o>=r)return{abort:!0,reason:"agent_budget",message:`Monthly budget reached: agent ${n} has spent ${W(o)} of its ${W(r)} budget for ${M}. New runs are paused until the month ends. To resume now, raise ${me(n)} (applies on save).`};let s=t?K(T.projects?.[t]):void 0,i=t?q.get(t)??0:0;if(t&&s&&i>=s)return{abort:!0,reason:"project_budget",message:`Monthly project budget reached: project ${t} has spent ${W(i)} of its ${W(s)} budget for ${M}. New runs for it are paused until the month ends. To resume now, raise ${me(Ke(t))} (applies on save).`};let a=K(T.fleet),d=qe();return a&&d>=a?{abort:!0,reason:"fleet_budget",message:`Monthly fleet budget reached: all agents together have spent ${W(d)} of the ${W(a)} budget for ${M}. New runs are paused until the month ends. To resume now, raise ${me(J)} (applies on save).`}:null}function Yr(n,e){let t=K(e);return t?n>=t?"paused":n>=t*we(e)?"warn":"ok":"uncapped"}function Be(n,e){let t=K(e);return{spentUsd:n,capUsd:t,warnRatio:we(e),...t?{ratio:n/t}:{},state:Yr(n,e)}}var dn=n=>(e,t)=>(t.ratio??-1)-(e.ratio??-1)||t.spentUsd-e.spentUsd||n(e).localeCompare(n(t));function Vr(n,e,t,r={},o={}){let i=[...new Set([...Object.keys(e),...Object.keys(o).filter(c=>o[c]>0),...Object.entries(n.agents??{}).filter(([,c])=>K(c)).map(([c])=>c)])].map(c=>({agentId:c,...Be(e[c]??0,n.agents?.[c]),...o[c]>0?{unpricedRuns:o[c]}:{}})).sort(dn(c=>c.agentId)),a=Object.keys(n.projects??{}).map(c=>({name:c,...Be(r[c]??0,n.projects?.[c])})).sort(dn(c=>c.name)),d=Object.values(e).reduce((c,p)=>c+(p>0?p:0),0),u=Object.values(o).reduce((c,p)=>c+(p>0?p:0),0);return{month:t,agents:i,projects:a,fleet:{...Be(d,n.fleet),...u?{unpricedRuns:u}:{}}}}function na(n=Date.now()){return he(n),Vr(T,Object.fromEntries(L),M,Object.fromEntries(q))}function ra(n){let e={};for(let[r,o]of Object.entries(n.agents??{}))o?.budget&&(e[r]=o.budget);let t={};for(let r of n.dashboard?.wall?.projects??[])r.name in t||(t[r.name]=r.budget);return{agents:e,projects:t,fleet:n.budget}}import{mkdirSync as Qr,readFileSync as Zr,renameSync as Xr,statSync as eo,writeFileSync as to}from"fs";import{dirname as no,resolve as ro}from"path";function aa(){return process.cwd()}function cn(n){return ro(n,".agentx","agent-holds.json")}var Y=null;function Ge(n){let e=cn(n),t;try{t=eo(e).mtimeMs}catch{return{}}if(Y&&Y.path===e&&Y.mtimeMs===t)return Y.holds;let r={};try{r=JSON.parse(Zr(e,"utf-8"))??{}}catch{r={}}return Y={path:e,mtimeMs:t,holds:r},r}function pn(n,e){let t=cn(n);Qr(no(t),{recursive:!0});let r=`${t}.${process.pid}.tmp`;to(r,JSON.stringify(e,null,2)+`
|
|
13
|
+
`),Xr(r,t),Y=null}function oo(n,e,t,r,o=new Date){let s={...Ge(n)},i={kind:t,at:o.toISOString(),by:r};return s[e]=i,pn(n,s),i}function da(n,e,t){let r={...Ge(n)},o=r[e];return!o||t&&o.kind!==t?!1:(delete r[e],pn(n,r),!0)}function ua(n,e){let t=Ge(n)[e];return t?t.kind==="approval"?`Agent "${e}" was created by ${t.by} and waits for the owner's approval. It starts once the owner says yes in Approvals (agentx approvals approve agent:${e}).`:`Agent "${e}" is paused by ${t.by}. Resume it in the Org view, or with: agentx agent resume ${e}`:null}function so(n=process.env){return n.AGENTX_AGENT_ID?.trim()||void 0}function la(n,e,t=process.env){let r=so(t);if(r){for(let o of e)oo(n,o,"approval",r);return r}}import{basename as io,resolve as ao}from"path";function fn(n){return n?ao(n).replace(/\/+$/,""):null}function fa(n,e){return e?`${n||"?"}:${e}`:null}function ga(n,e){let t=new Set,r=n.filter(i=>t.has(i.runId)?!1:(t.add(i.runId),!0)).sort((i,a)=>i.startedAt-a.startedAt||i.runId.localeCompare(a.runId)),o=i=>i.endedAt??e,s=[];for(let i=0;i<r.length;i++){let a=r[i];for(let d=i+1;d<r.length;d++){let u=r[d];if(u.startedAt>=o(a))break;if(a.startedAt>=o(u))continue;let c=[];if(a.chat&&a.chat===u.chat&&c.push("chat"),a.worktree&&a.worktree===u.worktree&&a.agentId!==u.agentId&&c.push("worktree"),!c.length)continue;let p=a.endedAt===null,f=u.endedAt===null;s.push({on:c,chat:c.includes("chat")?a.chat:null,worktree:c.includes("worktree")?io(a.worktree):null,runs:[a.runId,u.runId],agents:[a.agentId,u.agentId],from:u.startedAt,to:p&&f?null:Math.min(o(a),o(u))})}}return s}Pr();import{homedir as uo}from"os";var lo=36e5;function mn(n){let e=n?.match(/^([^:\s]+\/[^:\s]+):(?:issue|merge_request|pull)(?::|$)/);return e?e[1]:null}var gn=n=>fn(n.startsWith("~/")?uo()+n.slice(1):n);function hn(n,e,t=()=>null){let r=n?.projects??[],o=n?.rhythmHours??e,s=new Map,i=new Map,a=[];for(let c of r){for(let p of c.repos??[])s.has(p.toLowerCase())||s.set(p.toLowerCase(),c);for(let p of c.agents??[])i.has(p)||i.set(p,c);for(let p of c.workspaces??[]){let f=gn(p);f&&a.push([f,c])}}let d=c=>{let p=t(c),f=p?gn(p):null;return f?a.find(([g])=>f===g||f.startsWith(`${g}/`))?.[1]??null:null},u=(c,p)=>{let f=(p?s.get(p.toLowerCase()):void 0)??c.map(g=>i.get(g)).find(Boolean)??c.map(d).find(Boolean);return f?{name:f.name,rhythmHours:f.rhythmHours??o}:null};return{names:[...new Set(r.map(c=>c.name))],claim:u,of:(c,p)=>u([...new Set([c.askedAgent??c.agentId,c.agentId])],p)??{name:r.length?null:p,rhythmHours:o}}}function co(n,e){return je.includes(n.state)&&e-n.lastMoveAt>2*n.rhythmHours*lo}function ka(n,e,t){let r=e?.claim([...new Set([n.owner,n.agentId])],n.repo??null);return r?{...n,project:r.name,rhythmHours:r.rhythmHours,stalled:co({state:n.state,lastMoveAt:n.lastMoveAt,rhythmHours:r.rhythmHours},t)}:n}function ba(n,e=[]){let t=new Map,r=s=>{let i=t.get(s);return i||t.set(s,i={project:s,open:0,inProgress:0,blocked:0,stalled:0}),i};for(let s of e)r(s);for(let s of n){if(!je.includes(s.state))continue;let i=r(s.project);i.open++,s.state==="in_progress"&&i.inProgress++,s.blocked&&i.blocked++,s.stalled&&i.stalled++}let o=new Map(e.map((s,i)=>[s,i]));return[...t.values()].sort((s,i)=>{if(s.project===null||i.project===null)return s.project===null?1:-1;let a=o.get(s.project)??1/0,d=o.get(i.project)??1/0;return a!==d?a-d:s.project.localeCompare(i.project)})}function $a(n){if(!n.dashboard?.wall?.projects?.length)return()=>null;let e=hn(n.dashboard.wall,24,t=>n.agents?.[t]?.workspace??null);return(t,r)=>e.claim([t],mn(r))?.name??null}function Aa(n,e){let t={};for(let r of n){let o=e(r.agentId,r.chatId??void 0);o&&r.usd>0&&(t[o]=(t[o]??0)+r.usd)}return t}import{existsSync as E,mkdirSync as Mo,readdirSync as be,readFileSync as xn,statSync as Eo,unlinkSync as ve,writeFileSync as Ve}from"fs";import{resolve as N,relative as Pn}from"path";import{z as l}from"zod";var po=l.enum(["trigger.channel","trigger.manual","trigger.cron","trigger.hook","trigger.form","trigger.poll","agent","transform","classify","branch","gateway.parallel","rule","action.send","action.createIssue","action.setLabel","action.readLabel","action.react","action.editMessage","action.logTime","action.callHTTP","action.run","action.builtin","subProcess","signal.emit","signal.wait","timer.boundary","owner.notify","owner.ask","person.message","person.wait","checkpoint","end"]),fo=l.enum(["equals","contains","matches","exists"]),ze=l.object({kind:fo,params:l.record(l.unknown()).default({})}),yn=l.object({maxAttempts:l.number().int().min(1).max(10).default(1),backoffMs:l.number().int().min(0).max(6e4).default(1e3)}).default({maxAttempts:1,backoffMs:1e3}),kn=l.object({id:l.string().min(1).regex(/^[a-zA-Z_][a-zA-Z0-9_-]*$/,"node id must be identifier-safe"),type:po,config:l.record(l.unknown()).default({}),retry:yn,position:l.object({x:l.number(),y:l.number()}).optional()}),bn=l.object({from:l.string(),fromPort:l.string().optional(),to:l.string(),toPort:l.string().optional(),label:l.string().optional()}),wn=l.union([l.string(),l.date().transform(n=>n.toISOString())]),x=l.object({id:l.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"workflow id must be lower-kebab"),version:l.literal(2).default(2),title:l.string().min(1),description:l.string().optional(),status:l.enum(["draft","review","active","deprecated"]).default("active"),tags:l.array(l.string()).default([]),project:l.string().optional(),entity:l.string().optional(),intentPath:l.array(l.string()).default([]),generatedFrom:l.string().optional(),sourceTaskIds:l.array(l.string()).default([]),confidence:l.number().min(0).max(1).optional(),workflowVersion:l.string().optional(),ownerAgent:l.string().optional(),lastMatchedAt:l.string().optional(),matchCount:l.number().int().min(0).default(0),state:l.enum(["active","disabled","quarantined"]).default("active"),priority:l.number().int().default(0),fanOut:l.boolean().default(!1),nodes:l.array(kn).refine(n=>n.length>0,{message:"workflow must have at least one node"}),edges:l.array(bn).default([]),envAllow:l.array(l.string()).default([]),retention:l.object({maxRuns:l.number().int().positive().default(500),maxDays:l.number().int().positive().default(90)}).default({maxRuns:500,maxDays:90}),maxChildDepth:l.number().int().positive().default(5),mesh:l.object({allowRemote:l.boolean().default(!1),peers:l.array(l.string()).optional()}).default({allowRemote:!1}),created:wn.optional(),updated:wn.optional(),autoStart:l.boolean().default(!1),approval:l.enum(["start","step"]).optional(),followUp:l.object({stallMinutes:l.number().positive().max(7*24*60).optional(),maxNudges:l.number().int().min(0).max(20).optional()}).optional()}),ye={"owner.ask":{main:"yes",other:["no","expired"]},"person.message":{main:"sent",other:["declined"]},"person.wait":{main:"reply",other:["timeout"]}};function re(n){let e=[],t=new Map(n.nodes.map(i=>[i.id,i])),r=n.nodes.filter(i=>i.type.startsWith("trigger."));r.length===0&&e.push("workflow must have exactly one trigger.* node (found 0)"),r.length>1&&e.push(`workflow has ${r.length} trigger.* nodes; v1 supports exactly one`);for(let i of n.edges)t.has(i.from)||e.push(`edge references missing node: from="${i.from}"`),t.has(i.to)||e.push(`edge references missing node: to="${i.to}"`);let o=r[0];if(o){let i=new Map;for(let u of n.edges)i.has(u.from)||i.set(u.from,[]),i.get(u.from).push(u.to);let a=new Set,d=[o.id];for(;d.length;){let u=d.pop();if(!a.has(u)){a.add(u);for(let c of i.get(u)??[])d.push(c)}}for(let u of n.nodes)a.has(u.id)||e.push(`node "${u.id}" is unreachable from trigger "${o.id}"`);n.nodes.some(u=>a.has(u.id)&&go(u.type))||e.push("no reachable `end`, `checkpoint`, `subProcess`, `signal.wait`, or `timer.boundary` node \u2014 the run cannot terminate or pause")}for(let i of n.nodes){if(i.type!=="branch"&&i.type!=="rule")continue;let a=i.type==="branch"?i.config.cases??[]:(i.config.rules??[]).filter(p=>typeof p.to=="string"),d=i.type==="branch"?i.config.default:i.config.default?.to,u=new Set(a.map(p=>p.to));d&&u.add(d);let c=n.edges.filter(p=>p.from===i.id);for(let p of c){let f=p.fromPort??"";u.has(f)||e.push(`${i.type} "${i.id}" has outgoing edge with port "${f}" not declared in cases or default`)}}let s=ho(n);for(let i of s)e.push(`cycle without agent/checkpoint: ${i.join(" -> ")}`);return e}function go(n){return n==="end"||n==="checkpoint"||n==="subProcess"||n==="signal.wait"||n==="timer.boundary"}function mo(n){return n==="agent"||n==="owner.ask"||n==="person.wait"||n==="checkpoint"||n==="subProcess"||n==="signal.wait"||n==="timer.boundary"}function ho(n){let e=new Map;for(let a of n.edges)e.has(a.from)||e.set(a.from,[]),e.get(a.from).push(a.to);let t=new Map(n.nodes.map(a=>[a.id,a])),r=[],o=new Map,s=[],i=a=>{if(o.get(a)===1){let d=s.indexOf(a);if(d>=0){let u=s.slice(d).concat(a);u.some(p=>{let f=t.get(p)?.type;return f?mo(f):!1})||r.push(u)}return}if(o.get(a)!==2){o.set(a,1),s.push(a);for(let d of e.get(a)??[])i(d);s.pop(),o.set(a,2)}};for(let a of n.nodes)o.get(a.id)!==2&&i(a.id);return r}var vn=l.enum(["running","paused","completed","failed","canceled"]),wo=l.enum(["ok","failed","timeout","skipped","paused","resumed"]),yo=l.object({at:l.string(),nodeId:l.string(),inputKeys:l.array(l.string()).default([]),status:wo,output:l.record(l.unknown()).optional(),idempotencyKey:l.string(),note:l.string().optional(),startedAt:l.string().optional(),durationMs:l.number().int().min(0).optional()}),ko=l.object({backend:l.string(),id:l.string()}),bo=l.discriminatedUnion("kind",[l.object({kind:l.literal("checkpoint"),nodeId:l.string(),checkpointName:l.string(),resumeMatch:l.record(l.unknown()).default({})}),l.object({kind:l.literal("subProcess"),nodeId:l.string(),childRunId:l.string(),childWorkflowId:l.string()}),l.object({kind:l.literal("signalWait"),nodeId:l.string(),signalName:l.string(),match:l.record(l.unknown()).default({}),scope:l.enum(["workflow","global"]).default("workflow")}),l.object({kind:l.literal("timerWait"),nodeId:l.string(),fireAt:l.string(),wake:l.object({on:l.array(l.enum(["note","label"])),refs:l.array(l.string()),minGapSec:l.number(),selfLabels:l.array(l.string()).optional()}).optional()}),l.object({kind:l.literal("ownerDecision"),nodeId:l.string(),cardId:l.string(),purpose:l.enum(["ask","send","start"]),message:l.object({channel:l.string(),chatId:l.string(),accountId:l.string().optional(),text:l.string(),to:l.string().optional()}).optional()}),l.object({kind:l.literal("replyWait"),nodeId:l.string(),channel:l.string(),chatId:l.string(),accountId:l.string().optional(),from:l.string().optional(),deadline:l.string(),nextRemindAt:l.string().optional(),remindEveryMs:l.number().optional(),reminders:l.number().int().default(0),maxReminders:l.number().int().default(0),reminds:l.string().optional()}),l.object({kind:l.literal("agentStep"),nodeId:l.string(),agentId:l.string(),nudges:l.number().int().default(0),maxNudges:l.number().int().default(0),stallMs:l.number(),nextNudgeAt:l.string().optional(),blocked:l.string().optional()}),l.object({kind:l.literal("agentStop"),nodeId:l.string(),agentId:l.string(),taskId:l.string().optional()})]),vo=l.object({id:l.string(),title:l.string()}),Io=l.object({at:l.string(),kind:l.enum(["plan","revise"]),reason:l.string().optional(),steps:l.array(l.string()),dropped:l.array(l.string()).default([])}),$o=l.object({steps:l.array(vo),current:l.object({id:l.string(),startedAt:l.string()}).optional(),revisions:l.array(Io).default([])}),Ao=l.object({title:l.string().optional(),tags:l.array(l.string()).default([]),startedBy:l.string().optional(),requestId:l.string().optional(),followUp:l.boolean().default(!1),approvedAtStart:l.boolean().default(!1),approved:l.record(l.string()).optional(),blocked:l.object({nodeId:l.string(),reason:l.string(),at:l.string()}).optional(),endNotifiedAt:l.string().optional(),wrap:l.object({agentId:l.string(),channel:l.string(),mode:l.enum(["linear","plan"]),taskId:l.string().optional()}).optional(),plan:$o.optional(),continues:l.string().optional(),lastWakeAt:l.string().optional()}),So=l.object({id:l.string(),workflowId:l.string(),workflowVersion:l.literal(2),homeNode:l.string(),status:vn,pausedAt:bo.optional(),context:l.record(l.record(l.unknown())).default({}),pending:l.array(l.string()).default([]),joinCounters:l.record(l.array(l.string())).default({}),entityRef:ko,history:l.array(yo).default([]),parentRunId:l.string().nullable().default(null),parentNodeId:l.string().nullable().default(null),rootRunId:l.string().nullable().default(null),depth:l.number().int().min(0).default(0),eventRootId:l.string().optional(),meta:Ao.optional(),createdAt:l.string(),updatedAt:l.string()});import $n from"js-yaml";var Ro=new Set(["branch","gateway.parallel","rule","signal.wait","subProcess","timer.boundary","checkpoint"]),A=class extends Error{constructor(t,r){super(t);this.mark=r;this.name="WorkflowYamlError"}};function Je(n,e={}){if(!n||n.trim()==="")throw new A(`${C(e)}empty file \u2014 workflow YAML must contain at least an id, version, title, and one node.`);let t;try{t=$n.loadAll(n)}catch(o){let s=o?.mark;throw new A(`${C(e)}YAML parse error: ${o?.reason??o?.message??o}`+(s?` (line ${s.line+1}, column ${s.column+1})`:""),s)}if(t.length===0||t.length===1&&t[0]==null)throw new A(`${C(e)}YAML produced no document.`);if(t.length>1)throw new A(`${C(e)}multi-document YAML is not supported in v1; one workflow per file.`);let r=t[0];if(typeof r!="object"||r===null||Array.isArray(r)){let o=Array.isArray(r)?"array":typeof r;throw new A(`${C(e)}top-level YAML must be a mapping (got ${o}).`)}return An(r,e)}function An(n,e={}){if(!("flow"in n))return n;let t=n.flow;if(t==null){let p={...n};return delete p.flow,p}if(!Array.isArray(t))throw new A(`${C(e)}flow must be an array of node ids (got ${typeof t}).`);for(let p of t)if(typeof p!="string")throw new A(`${C(e)}flow entries must be strings (got ${typeof p}).`);let r=t,o=Array.isArray(n.nodes)?n.nodes:[],s=new Map;for(let p of o)p&&typeof p=="object"&&typeof p.id=="string"&&typeof p.type=="string"&&s.set(p.id,p.type);for(let p of r){if(!s.has(p))throw new A(`${C(e)}flow references unknown node "${p}".`);let f=s.get(p);if(Ro.has(f))throw new A(`${C(e)}flow cannot include ${f} node "${p}"; use explicit edges for ${f} nodes.`)}let i=[];for(let p=0;p<r.length-1;p++)i.push({from:r[p],to:r[p+1]});let a=Array.isArray(n.edges)?n.edges:[],d=new Set,u=[];for(let p of a){if(!p||typeof p!="object")continue;let f=In(p.from,p.fromPort,p.to);f&&!d.has(f)?(d.add(f),u.push(p)):f||u.push(p)}for(let p of i){let f=In(p.from,void 0,p.to);f&&!d.has(f)&&(d.add(f),u.push(p))}let c={...n,edges:u};return delete c.flow,c}function In(n,e,t){return typeof n!="string"||typeof t!="string"?null:`${n}::${typeof e=="string"?e:""}::${t}`}function C(n){return n.filePath?`${n.filePath}: `:""}function xo(n){return $n.dump(n,{noRefs:!0,lineWidth:100,sortKeys:!1})}import{Document as Po,isMap as ke,isSeq as Wo,isScalar as Sn,parseDocument as To}from"yaml";function Rn(n,e){let t=To(n);if(!t.contents||!ke(t.contents)){let r=new Po(e);return t.commentBefore&&(r.commentBefore=t.commentBefore),String(r)}return Ye(t,t.contents,e),String(t)}function Ye(n,e,t){let r=Object.keys(t),o=new Set(r),s=new Map;for(let a of e.items){let d=Do(a);d!==null&&s.set(d,a)}let i=[];for(let a of r){let d=t[a],u=s.get(a);u?(No(n,u,d),i.push(u)):i.push(n.createPair(a,d))}e.items=i}function No(n,e,t){let r=e.value;if(t==null){e.value=n.createNode(null);return}if(typeof t!="object"){e.value=n.createNode(t);return}if(Array.isArray(t)){Wo(r)?Oo(n,r,t):e.value=n.createNode(t);return}ke(r)?Ye(n,r,t):e.value=n.createNode(t)}function Oo(n,e,t){if(!(t.length>0&&t.every(i=>i&&typeof i=="object"&&typeof i.id=="string"))){let i=n.createNode(t);e.items=i.items;return}let o=new Map;for(let i of e.items)if(ke(i)){let a=i.get("id",!0);Sn(a)&&typeof a.value=="string"&&o.set(a.value,i)}let s=[];for(let i of t){let a=i.id,d=o.get(a);d&&ke(d)?(Ye(n,d,i),s.push(d)):s.push(n.createNode(i))}e.items=s}function Do(n){let e=n.key;return Sn(e)&&typeof e.value=="string"?e.value:typeof e=="string"?e:null}var Wn=new Map,Qe=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??N(process.cwd(),".agentx/workflows"),Mo(this.baseDir,{recursive:!0})}pathFor(e){return this.pathForJson(e)}pathForJson(e){return N(this.baseDir,`${e}.json`)}pathForYaml(e){return N(this.baseDir,`${e}.yaml`)}isWorkflowFile(e){return e.startsWith("_")?!1:e.endsWith(".json")||e.endsWith(".yaml")||e.endsWith(".yml")}idFromFilename(e){return e.replace(/\.(json|ya?ml)$/,"")}readAndParse(e){let t=N(this.baseDir,e),r=xn(t,"utf-8");return e.endsWith(".json")?JSON.parse(r):Je(r,{filePath:e})}list(){if(!E(this.baseDir))return[];let e=new Map,t=[];for(let a of be(this.baseDir,{withFileTypes:!0})){if(!a.isFile()||!this.isWorkflowFile(a.name))continue;let d=this.idFromFilename(a.name),u=e.get(d)??[];u.push(a.name),e.set(d,u);try{let c=Eo(N(this.baseDir,a.name));t.push(`${a.name}:${c.mtimeMs}:${c.size}`)}catch{t.push(`${a.name}:?`)}}let r=t.sort().join("|"),o=Wn.get(this.baseDir);if(o&&o.signature===r)return o.workflows.slice();let s=[];for(let[,a]of e)if(!(a.length>1))try{let d=this.readAndParse(a[0]),u=x.safeParse(d);u.success&&s.push(u.data)}catch{}let i=s.sort((a,d)=>a.id.localeCompare(d.id));return Wn.set(this.baseDir,{signature:r,workflows:i}),i.slice()}validateAll(){let e=[];if(!E(this.baseDir))return e;let t=new Map;for(let r of be(this.baseDir,{withFileTypes:!0})){if(!r.isFile()||!this.isWorkflowFile(r.name))continue;let o=this.idFromFilename(r.name),s=t.get(o)??[];s.push(r.name),t.set(o,s)}for(let[r,o]of t){if(o.length>1){let p=[...o].sort();for(let f of p)e.push({id:r,path:Pn(this.baseDir,N(this.baseDir,f)),issues:[`duplicate workflow id "${r}" \u2014 found ${p.join(" and ")}; delete one to disambiguate`],isValid:!1});continue}let s=o[0],i=N(this.baseDir,s),a=Pn(this.baseDir,i),d;try{d=this.readAndParse(s)}catch(p){let f=p instanceof A?p.message:`parse error: ${p?.message??p}`;e.push({id:r,path:a,issues:[f],isValid:!1});continue}let u=x.safeParse(d);if(!u.success){let p=u.error.issues.map(f=>`${f.path.join(".")||"<root>"}: ${f.message}`);e.push({id:String(d?.id??r),path:a,issues:p,isValid:!1});continue}let c=re(u.data);e.push({workflow:u.data,issues:c,isValid:c.length===0})}return e}get(e){let t=this.readStored(e);if(!t)return null;let r=x.safeParse(t.raw);return r.success?r.data:null}getStored(e){let t=this.readStored(e);return!t||!x.safeParse(t.raw).success?null:t.raw}readStored(e){let t=[`${e}.json`,`${e}.yaml`,`${e}.yml`].filter(r=>E(N(this.baseDir,r)));if(t.includes(`${e}.json`)&&t.length>1)return null;if(t.length>0)try{return{name:t[0],raw:this.readAndParse(t[0])}}catch{return null}if(!E(this.baseDir))return null;for(let r of be(this.baseDir,{withFileTypes:!0}))if(!(!r.isFile()||!this.isWorkflowFile(r.name)||this.idFromFilename(r.name)===e))try{let s=this.readAndParse(r.name),i=x.safeParse(s);if(i.success&&i.data.id===e)return{name:r.name,raw:s}}catch{}return null}save(e,t={}){let r=new Date().toISOString().slice(0,10),o=x.parse({...e,created:e.created||r,updated:r});return this.write(o,o,t)}saveStored(e,t={}){return this.write(x.parse(e),e,t)}write(e,t,r){let o=this.pathForYaml(e.id),s=N(this.baseDir,`${e.id}.yml`),i=E(o)?o:E(s)?s:null;if(!i&&E(this.baseDir)){for(let a of be(this.baseDir,{withFileTypes:!0}))if(!(!a.isFile()||!this.isWorkflowFile(a.name))&&!a.name.endsWith(".json"))try{let d=this.readAndParse(a.name),u=x.safeParse(d);if(u.success&&u.data.id===e.id){i=N(this.baseDir,a.name);break}}catch{}}if(i&&r.convertFromYaml)return ve(i),Ve(this.pathForJson(e.id),JSON.stringify(t,null,2)+`
|
|
14
|
+
`),e;if(i){let a=xn(i,"utf-8");try{let d=Rn(a,t);return Ve(i,d),e}catch(d){let u=new Error(`yaml round-trip failed for "${e.id}" at ${i}: ${d?.message??d}`);throw u.yamlPath=i,u}}return Ve(this.pathForJson(e.id),JSON.stringify(t,null,2)+`
|
|
15
|
+
`),e}delete(e){let t=this.pathForJson(e),r=this.pathForYaml(e),o=N(this.baseDir,`${e}.yml`),s=!1;return E(t)&&(ve(t),s=!0),E(r)&&(ve(r),s=!0),E(o)&&(ve(o),s=!0),s}};import{createHash as Fo,randomUUID as _o}from"crypto";import{appendFileSync as Tn,existsSync as O,mkdirSync as Ze,readdirSync as oe,readFileSync as se,renameSync as Lo,statSync as Xe,unlinkSync as ie,writeFileSync as Nn}from"fs";import{resolve as $}from"path";var jo=/(token|secret|password|passwd|apikey|authorization)$/;function Co(n){return jo.test(n.toLowerCase().replace(/[_-]/g,""))}function j(n){if(Array.isArray(n))return n.map(j);if(n===null||typeof n!="object")return n;let e={};for(let[t,r]of Object.entries(n))typeof r=="string"&&Co(t)||(e[t]=j(r));return e}var U="task";function Uo(n){return n.replace(/[^a-zA-Z0-9._:#@-]/g,"_").slice(0,200)}function I(n,e,t){return Fo("sha1").update(`${n}|${e}|${t}`).digest("hex").slice(0,16)}var et=class{baseDir;runsDir;indexDir;tasksDir;nodeId;constructor(e){this.baseDir=e.baseDir??$(process.cwd(),".agentx/workflows"),this.runsDir=$(this.baseDir,"_runs"),this.indexDir=$(this.baseDir,"_index"),this.tasksDir=$(this.baseDir,"_tasks"),this.nodeId=e.nodeId,Ze(this.runsDir,{recursive:!0}),Ze(this.indexDir,{recursive:!0}),Ze(this.tasksDir,{recursive:!0})}runPath(e,t){if(t!==void 0&&t!==U)return $(this.runsDir,`${e}.jsonl`);if(t===U){let o=$(this.runsDir,`${e}.jsonl`);return O(o)?o:$(this.tasksDir,`${e}.jsonl`)}let r=$(this.tasksDir,`${e}.jsonl`);return O(r)?r:$(this.runsDir,`${e}.jsonl`)}indexPath(e){return $(this.indexDir,`${e.backend}__${Uo(e.id)}.json`)}create(e){let t=new Date().toISOString(),r=e.id??_o(),o={id:r,workflowId:e.workflowId,workflowVersion:2,homeNode:this.nodeId,status:"running",pausedAt:void 0,context:j(e.initialContext??{}),pending:e.initialPending,entityRef:e.entityRef,history:[],parentRunId:e.parentRunId??null,parentNodeId:e.parentNodeId??null,rootRunId:e.rootRunId??r,depth:e.depth??0,eventRootId:e.eventRootId??Ft()?.rootId,joinCounters:{},...e.meta?{meta:e.meta}:{},createdAt:t,updatedAt:t};return this.appendSnapshot(o),this.writeIndex(e.entityRef,o.id),o}get(e){return this.readRun(this.runPath(e))}readRun(e){let t;try{t=se(e,"utf-8").trim()}catch{return null}if(!t)return null;let r=null;for(let o of t.split(`
|
|
16
|
+
`)){let s;try{s=JSON.parse(o)}catch{continue}if(s.v===2){if(s.kind==="snapshot")r=s.run;else if(s.kind==="exec"&&r&&r.id===s.runId){let i=r;r={...i,history:[...i.history,s.entry],pending:s.pending,status:s.status??i.status,pausedAt:s.pausedAt===null?void 0:s.pausedAt??i.pausedAt,context:s.context??i.context,joinCounters:s.joinCounters??i.joinCounters,updatedAt:s.entry.at}}}}return r&&j(r)}getActiveByEntity(e){let t=this.indexPath(e);if(!O(t))return null;try{return JSON.parse(se(t,"utf-8")).runId}catch{return null}}getHomeNodeByEntity(e){let t=this.indexPath(e);if(!O(t))return null;try{return JSON.parse(se(t,"utf-8")).homeNode}catch{return null}}recordExecution(e){let t=this.get(e.runId);if(!t)return null;if(t.history.some(s=>s.idempotencyKey===e.entry.idempotencyKey))return t;let r={v:2,kind:"exec",runId:e.runId,entry:e.entry,pending:e.nextPending,status:e.status,pausedAt:e.pausedAt===null?null:e.pausedAt,context:e.context,joinCounters:e.joinCounters};Tn(this.runPath(e.runId,t.workflowId),JSON.stringify(j(r))+`
|
|
17
|
+
`);let o=e.status??t.status;return o==="completed"||o==="failed"||o==="canceled"?this.clearIndex(t.entityRef):this.writeIndex(t.entityRef,t.id),this.get(e.runId)}setStatus(e,t){let r=this.get(e);if(!r)return null;let o={...r,status:t,updatedAt:new Date().toISOString()};return this.appendSnapshot(o),t!=="running"&&t!=="paused"&&this.clearIndex(o.entityRef),o}setMeta(e,t){let r=this.get(e);if(!r)return null;let o={tags:[],followUp:!1,approvedAtStart:!1,...r.meta,...t},s={...r,meta:o,updatedAt:new Date().toISOString()};return this.appendSnapshot(s),s}patch(e,t){let r=this.get(e);if(!r)return null;let o={...r,...t.meta?{meta:{tags:[],followUp:!1,approvedAtStart:!1,...r.meta,...t.meta}}:{},...t.pending?{pending:t.pending}:{},...t.pausedAt?{pausedAt:t.pausedAt}:{},updatedAt:new Date().toISOString()};return this.appendSnapshot(o),o}discard(e){let t=this.get(e);if(!t)return!1;this.clearIndex(t.entityRef);try{return ie(this.runPath(e,t.workflowId)),!0}catch{return!1}}list(e={}){let t=e.tasks??(e.workflowId===U?"only":"exclude"),r=t==="only"?[this.tasksDir]:t==="include"?[this.runsDir,this.tasksDir]:[this.runsDir],o=[];for(let i of r)if(O(i))for(let a of oe(i)){if(!a.endsWith(".jsonl"))continue;let d=$(i,a),u;try{u=Xe(d).mtimeMs}catch{continue}e.since&&u<e.since||o.push({path:d,mtime:u})}o.sort((i,a)=>a.mtime-i.mtime);let s=[];for(let i of o){let a=this.readRun(i.path);if(a&&!(e.workflowId&&a.workflowId!==e.workflowId)&&!(t==="exclude"&&a.workflowId===U)&&!(e.before&&!(a.updatedAt<e.before))&&!(e.active&&a.status!=="running"&&a.status!=="paused")&&(s.push(a),e.limit&&s.length>=e.limit))break}return s}openTaskRunIds(){if(!O(this.indexDir))return[];let e=[];for(let t of oe(this.indexDir)){if(!t.startsWith("task__")||!t.endsWith(".json"))continue;let r=$(this.indexDir,t),o="";try{o=String(JSON.parse(se(r,"utf-8")).runId??"")}catch{}if(!(o?this.get(o):null)){try{ie(r)}catch{}continue}e.push(o)}return e}pruneTaskRuns(e){if(!(e>0)||!O(this.tasksDir))return 0;let t=Date.now()-e*24*60*60*1e3,r=0;for(let o of oe(this.tasksDir)){if(!o.endsWith(".jsonl"))continue;let s=$(this.tasksDir,o);try{if(Xe(s).mtimeMs>=t)continue}catch{continue}let i=this.readRun(s);if(!(i&&(i.status==="running"||i.status==="paused")))try{ie(s),r++}catch{}}return r}moveTaskRuns(){let e=$(this.tasksDir,".moved");if(O(e)||!O(this.runsDir))return 0;let t=0;for(let r of oe(this.runsDir)){if(!r.endsWith(".jsonl"))continue;let o=$(this.runsDir,r),s="";try{s=se(o,"utf-8").split(`
|
|
18
|
+
`,1)[0]}catch{continue}let i;try{i=JSON.parse(s).run?.workflowId}catch{continue}if(i===U)try{Lo(o,$(this.tasksDir,r)),t++}catch{}}return Nn(e,new Date().toISOString()+`
|
|
19
|
+
`),t}prune(e){if(!O(this.runsDir))return 0;let t=Date.now()-e.maxDays*24*60*60*1e3,r=[];for(let s of oe(this.runsDir)){if(!s.endsWith(".jsonl"))continue;let i=$(this.runsDir,s),a=Xe(i).mtimeMs,d=this.get(s.replace(/\.jsonl$/,""));d&&(d.status==="running"||d.status==="paused"||r.push({file:i,run:d,mtime:a}))}r.sort((s,i)=>i.mtime-s.mtime);let o=0;for(let s=0;s<r.length;s++){let i=r[s],a=i.mtime<t,d=s>=e.maxRuns;if(a||d)try{ie(i.file),o++}catch{}}return o}appendSnapshot(e){let t={v:2,kind:"snapshot",run:e};Tn(this.runPath(e.id,e.workflowId),JSON.stringify(j(t))+`
|
|
20
|
+
`)}writeIndex(e,t){Nn(this.indexPath(e),JSON.stringify({runId:t,homeNode:this.nodeId,updatedAt:new Date().toISOString()},null,2)+`
|
|
21
|
+
`)}clearIndex(e){let t=this.indexPath(e);if(O(t))try{ie(t)}catch{}}};import{existsSync as On,mkdirSync as Ho,readFileSync as Bo,unlinkSync as Ko,writeFileSync as qo}from"fs";import{resolve as tt}from"path";import{z as V}from"zod";var Dn=V.object({version:V.literal(1),nodes:V.record(V.object({x:V.number(),y:V.number()}))}),nt=class{baseDir;layoutsDir;constructor(e={}){this.baseDir=e.baseDir??tt(process.cwd(),".agentx/workflows"),this.layoutsDir=tt(this.baseDir,"_layouts"),Ho(this.layoutsDir,{recursive:!0})}pathFor(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return tt(this.layoutsDir,`${t}.json`)}get(e){let t=this.pathFor(e);if(!On(t))return null;try{let r=Dn.safeParse(JSON.parse(Bo(t,"utf-8")));return r.success?r.data:null}catch{return null}}save(e,t){let r=Dn.parse(t);return qo(this.pathFor(e),JSON.stringify(r,null,2)+`
|
|
22
|
+
`),r}sync(e,t){let r=this.get(e);if(!r)return null;let o={};for(let i of t)r.nodes[i]&&(o[i]=r.nodes[i]);let s={version:1,nodes:o};return this.save(e,s)}delete(e){let t=this.pathFor(e);return On(t)?(Ko(t),!0):!1}};function Mn(n){return new Set(n.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function Go(n,e){if(n.size===0||e.size===0)return 0;let t=0;for(let r of n)e.has(r)&&t++;return t/Math.max(n.size,e.size)}function zo(n,e){let t=Mn(n.message),r=e.filter(s=>s.state==="active"&&(s.status??"active")==="active"),o=null;for(let s of r){let i=0,a=[];if(s.ownerAgent&&s.ownerAgent===n.agentId&&(i+=.25,a.push("owner-agent")),n.channel&&s.tags.includes(n.channel)&&(i+=.15,a.push("channel-tag")),n.intentPath?.length&&s.intentPath.length){let p=n.intentPath.filter((f,g)=>s.intentPath[g]===f).length;p>0&&(i+=Math.min(.3,p*.1),a.push("intent-path"))}let d=[s.id,s.title,s.description??"",...s.tags].join(" "),u=Go(t,Mn(d));u>0&&(i+=Math.min(.35,u),a.push("text-similarity")),(s.matchCount??0)>0&&(i+=Math.min(.1,s.matchCount*.01),a.push("prior-matches"));let c=Math.max(0,Math.min(1,i));(!o||c>o.confidence)&&(o={workflow:s,confidence:c,reasons:a})}return o&&o.confidence>0?o:null}function Ie(n){let{workflow:e,fromNodeId:t,selectedPort:r}=n,o=e.nodes.find(d=>d.id===t);if(!o)return{nextPending:[]};let s=e.edges.filter(d=>d.from===t),i=ye[o.type];return{nextPending:(o.type==="branch"?s.filter(d=>(d.fromPort??"")===(r??"")):i?s.filter(d=>(d.fromPort??i.main)===(r??i.main)):s).map(d=>d.to)}}function rt(n,e){let t=n.config.cases??[],r=n.config.default??"";for(let o of t)if($e(o.when,e))return o.to;return r}function $e(n,e){let t=n.params??{},r=String(t.path??""),o=Q(e,r);switch(n.kind){case"equals":return o===t.value;case"contains":return typeof o=="string"?o.includes(String(t.value??"")):Array.isArray(o)?o.some(s=>s===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 Q(n,e){if(!e)return;let t=e.split("."),r=n;for(let o of t){if(r==null||typeof r!="object")return;r=r[o]}return r}function ae(n){let e=n.nodes.find(r=>r.type.startsWith("trigger."));if(!e)return null;let t=n.edges.filter(r=>r.from===e.id).map(r=>r.to);return{triggerId:e.id,pending:t}}function P(n,e){return n.nodes.find(t=>t.id===e)}import{randomUUID as Ds}from"crypto";Wr();Tr();function Jo(n,e,t){let r=n.split(".");if(r[0]==="env"){if(r.length!==2)return"";let s=r[1];if(!t.has(s))return"";let i=process.env[s];return typeof i=="string"?i:""}let o=e;for(let s of r){if(o==null||typeof o!="object")return"";o=o[s]}return o==null?"":typeof o=="object"?JSON.stringify(o):String(o)}function R(n,e,t={}){let r=new Set(t.envAllow||[]);return n.replace(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_.-]*)\s*\}\}/g,(o,s)=>Jo(s,e,r))}function v(n,e,t={}){let r={};for(let[o,s]of Object.entries(n))typeof s=="string"?r[o]=R(s,e,t):Array.isArray(s)?r[o]=s.map(i=>typeof i=="string"?R(i,e,t):i):s&&typeof s=="object"?r[o]=v(s,e,t):r[o]=s;return r}var En="workflow-classify",Ae="unsure",jn=async n=>{let e=n.node.config,t=n.run.context,r={envAllow:n.workflow.envAllow},o=R(String(e.input??""),t,r).trim();if(!o)return{error:`classify node "${n.node.id}" missing config.input`};let s=e.labels,i=Array.isArray(s)?Object.fromEntries(s.map(y=>[String(y),null])):typeof s=="object"&&s?Object.fromEntries(Object.entries(s).map(([y,b])=>[y,b==null?null:String(b)])):{},a=Object.keys(i);if(a.length<2)return{error:`classify node "${n.node.id}" needs at least two labels`};if(a.includes(Ae))return{error:`classify node "${n.node.id}": "${Ae}" is reserved for the low-confidence port`};let d=typeof e.minConfidence=="number"?e.minConfidence:.7,u=e.instructions?R(String(e.instructions),t,r):void 0,c={input:o};if(e.state&&typeof e.state=="object")for(let[y,b]of Object.entries(e.state)){let w=typeof b=="string"?R(b,t,r):b;(w===null||["string","number","boolean"].includes(typeof w))&&(c[y]=w)}let p=await xt(En,c,{label:Rt(i,u)},{features:{workflow:n.workflow.id,node:n.node.id}});if(!p)return{error:`classify node "${n.node.id}": decision seat unavailable (set decisions.seats.${En}.mode)`};let f=p.answers.label,g=f.confidence>=d,m=g?f.choice:Ae;return n.log(`[node:${n.node.id}] classify \u2192 ${f.choice} (${f.confidence.toFixed(2)})${g?"":` \u2014 below ${d}, routing to ${Ae}`}`),{output:{result:f.choice,label:f.choice,confidence:f.confidence,probabilities:f.probabilities,unsure:!g,port:m},port:m}};var ot=class{active=new Map;waiters=new Map;async acquire(e,t){let r=this.active.get(e)??0;if(r<t){this.active.set(e,r+1);return}return new Promise(o=>{let s=this.waiters.get(e)??[];s.push({resolve:()=>{this.active.set(e,(this.active.get(e)??0)+1),o()}}),this.waiters.set(e,s)})}release(e){let t=this.active.get(e)??0;this.active.set(e,Math.max(0,t-1));let r=this.waiters.get(e);r&&r.length>0&&r.shift().resolve()}stats(e){return{active:this.active.get(e)??0,waiting:this.waiters.get(e)?.length??0}}},Se=new ot;function Cn(n,e){return`${n}:${e}`}var st=["note","label"];var id="<!-- agentx:no-wake -->",Yo=/^[a-z0-9_.\-/]+[#!]\d+$/,Vo=/^(\S+)\s+([+-])\s*(\S.*)$/;function Qo(n){if(typeof n!="string")return null;let e=n.trim().match(Vo),t=e&&it(e[1]);return t?`${t} ${e[2]}${e[3].trim().toLowerCase()}`:null}var Fn=n=>Array.isArray(n)?n:typeof n=="string"?n.split(","):[];function it(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase();return Yo.test(e)?e:null}function _n(n){if(!n||typeof n!="object")return;let e=n,r=(Array.isArray(e.on)?e.on:[...st]).filter(a=>st.includes(a)),o=[...new Set(Fn(e.refs).map(it).filter(a=>!!a))];if(!r.length||!o.length)return;let s=Number(e.minGapSec),i=[...new Set(Fn(e.self).map(Qo).filter(a=>!!a))];return{on:r,refs:o,minGapSec:Number.isFinite(s)&&s>=0?s:60,...i.length?{selfLabels:i}:{}}}function Ln(n,e){if(e.on!=="label"||!e.byAgentx||!e.labels?.length||!n.selfLabels?.length)return null;let t=[...n.selfLabels];for(let r of e.labels){let o=t.indexOf(`${e.ref} ${r.toLowerCase()}`);if(o<0)return null;t.splice(o,1)}return t}function Un(n,e){return!!n&&n.on.includes(e.on)&&n.refs.includes(e.ref)}function Hn(n){let e=n.lastWakeAt?Date.parse(n.lastWakeAt):NaN,t=Number.isFinite(e)?e+n.minGapSec*1e3:-1/0,r=t>n.nowMs,o=r?t:n.nowMs,s=Date.parse(n.fireAt);return Number.isFinite(s)&&s<=o?null:{fireAt:new Date(o).toISOString(),result:r?"debounced":"woke"}}function ad(n){if(!n||typeof n!="object")return null;let e=n,t=it(e.ref);if(!t||!st.includes(e.on))return null;let r=Array.isArray(e.labels)?e.labels.filter(o=>typeof o=="string"&&/^[+-]./.test(o)):[];return{ref:t,on:e.on,selfMarked:e.selfMarked===!0,...r.length?{labels:r}:{},...e.byAgentx===!0?{byAgentx:!0}:{}}}var Re={stallMinutes:30,maxNudges:2,approval:"step"};var xe=n=>n.run.context;function Bn(n){if(typeof n=="number")return Number.isFinite(n)&&n>0?n*6e4:null;if(typeof n!="string"||!n.trim())return null;let e=n.trim(),t=/^(\d+(?:\.\d+)?)\s*(m|min|h|d)$/i.exec(e);if(t){let o=Number(t[1]),s=t[2].toLowerCase(),i=o*(s==="d"?864e5:s==="h"?36e5:6e4);return i>0?i:null}let r=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/i.exec(e);if(r){let o=(((Number(r[1]??0)*24+Number(r[2]??0))*60+Number(r[3]??0))*60+Number(r[4]??0))*1e3;return o>0?o:null}return/^\d+$/.test(e)&&Number(e)*6e4||null}function Zo(n){let e=n.followUp??Re,t=n.node.config,r=n.workflow.followUp??{},o=s=>typeof s=="number"&&Number.isFinite(s)&&s>=0?s:void 0;return{stallMinutes:o(t.stallMinutes)||r.stallMinutes||e.stallMinutes,maxNudges:o(t.maxNudges)??r.maxNudges??e.maxNudges,approval:n.workflow.approval??e.approval}}function Kn(n){let e=n.node.config.supervise;return typeof e=="boolean"?e:n.run.meta?.followUp===!0}function qn(n,e){return["",`[agentx:workflow-step run=${n.id} step=${e}]`,"This is one step of a workflow AgentX is following. When the step is finished, end your reply with a line `RESULT: done` and say what proves it (a link, an id, the text you checked).",`If it will finish later (a deploy still running, an answer still due), say so and report it when it is done with agentx_workflow: {action:"done", runId:"${n.id}", step:"${e}", evidence:"<proof>"}. You will be reminded if nothing happens.`,"If you cannot do it without the owner, end with `RESULT: blocked` and the reason in one line."].join(`
|
|
23
|
+
`)}function at(n){return n?["done","approved","skipped","ok","complete","completed"].includes(n)?"done":["blocked","failed","rejected","changes-requested"].includes(n)?"blocked":"wait":"wait"}function dt(n,e,t){let{stallMinutes:r,maxNudges:o}=Zo(n),s=r*6e4,i=d=>({kind:"agentStep",nodeId:n.node.id,agentId:e,nudges:0,maxNudges:o,stallMs:s,...d?{blocked:d}:{nextNudgeAt:new Date(Date.now()+s).toISOString()}}),a=t.error?"wait":at(t.result);if(a==="blocked"){let d=Xo(t.reply)||`${e} says the step is ${t.result}`;return{paused:!0,pausedAt:i(d),blocked:d,output:t.output}}return a==="done"?{output:t.output}:{paused:!0,pausedAt:i(),output:t.output}}function Xo(n){return n?(n.split(`
|
|
24
|
+
`).map(t=>t.trim()).filter(t=>t&&!/^RESULT:/i.test(t)).at(-1)??"").slice(0,300):""}function Gn(n,e,t,r,o){let s=Math.max(1,Math.round(o/6e4));return[`[agentx:workflow-nudge run=${n.id} step=${e} nudge=${t}/${r}]`,`Reminder ${t} of ${r}: the workflow step "${e}"${n.meta?.title?` of "${n.meta.title}"`:""} has shown no progress for ${s} minute(s).`,"Check where it stands and finish it now if you can.",`When it is done, end your reply with \`RESULT: done\` and the proof, or call agentx_workflow {action:"done", runId:"${n.id}", step:"${e}", evidence:"<proof>"}.`,"If you cannot finish it without the owner, end with `RESULT: blocked` and the reason.",t>=r?"This is the last reminder: after it the owner is told the step is blocked.":""].filter(Boolean).join(`
|
|
25
|
+
`)}var es=async n=>{let e=R(String(n.node.config.text??""),xe(n),{envAllow:n.workflow.envAllow}).trim();if(!e)return{error:`owner.notify "${n.node.id}" needs config.text`};if(!n.owner)return{error:`owner.notify "${n.node.id}": no owner to tell on this node`};try{await n.owner.notify(e,n.run)}catch(t){return{error:`owner.notify "${n.node.id}" failed: ${t?.message??t}`}}return{output:{text:e,sentAt:new Date().toISOString()}}},ts=async n=>{let e=v(n.node.config,xe(n),{envAllow:n.workflow.envAllow}),t=String(e.ask??e.question??"").trim();if(!t)return{error:`owner.ask "${n.node.id}" needs config.ask (the yes/no question)`};if(!n.owner)return{error:`owner.ask "${n.node.id}": no owner to ask on this node`};let r=Array.isArray(e.choices)?e.choices.map(String).filter(Boolean):void 0;try{let{cardId:o}=await n.owner.ask({title:G(String(e.title??n.run.meta?.title??n.workflow.title),120),ask:G(t,300),recommend:G(String(e.recommend??"Your call."),300),...typeof e.draft=="string"&&e.draft.trim()?{draft:e.draft}:{},...r?.length?{choices:r}:{},...typeof e.context=="string"&&e.context.trim()?{context:G(e.context,600)}:{},...typeof e.expires=="string"&&e.expires.trim()?{expires:e.expires}:{}},n.run,n.node.id);return{paused:!0,pausedAt:{kind:"ownerDecision",nodeId:n.node.id,cardId:o,purpose:"ask"}}}catch(o){return{error:`owner.ask "${n.node.id}": could not raise the card: ${o?.message??o}`}}};function ut(n){let e=v(n.node.config,xe(n),{envAllow:n.workflow.envAllow});return{channel:String(e.channel??"").trim(),chatId:String(e.chatId??"").trim(),...typeof e.accountId=="string"&&e.accountId?{accountId:e.accountId}:{},text:String(e.text??"").trim(),...typeof e.to=="string"&&e.to.trim()?{to:e.to.trim()}:{}}}var ns=async n=>{let e=ut(n);if(!e.channel||!e.chatId||!e.text)return{error:`person.message "${n.node.id}" needs channel, chatId and text`};if(n.run.meta?.approved?.[n.node.id]===lt(e)){let r=await Pe(n,e);return"error"in r?{error:r.error}:{output:{...e,messageId:r.messageId,approved:"start"},port:"sent"}}if(!n.owner)return{error:`person.message "${n.node.id}": no owner to approve it on this node`};let t=e.to?`${e.to} (${e.channel} ${e.chatId})`:`${e.channel} ${e.chatId}`;try{let{cardId:r}=await n.owner.ask({title:G(`Send to ${t}`,120),ask:G(`Send this message to ${t}?`,300),recommend:G(`It is step "${n.node.id}" of ${n.run.meta?.title?`"${n.run.meta.title}"`:`workflow ${n.workflow.id}`}. Edit it if needed, then say yes.`,300),draft:e.text},n.run,n.node.id);return{paused:!0,pausedAt:{kind:"ownerDecision",nodeId:n.node.id,cardId:r,purpose:"send",message:e}}}catch(r){return{error:`person.message "${n.node.id}": could not ask the owner: ${r?.message??r}`}}};function lt(n){return`${n.channel}
|
|
26
|
+
${n.chatId}
|
|
27
|
+
${n.text}`}async function Pe(n,e){let t=n.channels[e.channel],r={channel:e.channel,chatId:e.chatId,text:e.text,...e.accountId?{accountId:e.accountId}:{}};if(t?.send)try{return{messageId:await t.send(r)??null}}catch(o){return{error:`send on ${e.channel} failed: ${o?.message??o}`}}if(n.forwardChannelSend)try{return{messageId:(await n.forwardChannelSend(r)).messageId}}catch(o){return{error:`send on ${e.channel} via the mesh failed: ${o?.message??o}`}}return{error:`channel "${e.channel}" is not available here or on a peer`}}var rs=async n=>{let e=v(n.node.config,xe(n),{envAllow:n.workflow.envAllow}),t=typeof e.reminds=="string"&&e.reminds?e.reminds:void 0,r=t?n.run.context[t]:void 0,o=String(e.channel??r?.channel??"").trim(),s=String(e.chatId??r?.chatId??"").trim();if(!o||!s)return{error:`person.wait "${n.node.id}" needs channel and chatId (or reminds: a person.message step)`};let i=Bn(e.timeout??"P1D");if(!i)return{error:`person.wait "${n.node.id}": timeout must be minutes, "4h", "2d" or "P2D"`};let a=e.remindAfter===void 0?null:Bn(e.remindAfter);if(e.remindAfter!==void 0&&!a)return{error:`person.wait "${n.node.id}": remindAfter must be minutes, "4h", "2d" or "P2D"`};let d=typeof e.maxReminders=="number"?Math.max(0,Math.floor(e.maxReminders)):a?1:0,u=Date.now(),c=typeof e.accountId=="string"&&e.accountId?e.accountId:typeof r?.accountId=="string"&&r.accountId?r.accountId:void 0;return{paused:!0,pausedAt:{kind:"replyWait",nodeId:n.node.id,channel:o,chatId:s,...c?{accountId:c}:{},...typeof e.from=="string"&&e.from?{from:e.from}:{},deadline:new Date(u+i).toISOString(),...a&&d>0?{nextRemindAt:new Date(u+a).toISOString(),remindEveryMs:a}:{},reminders:0,maxReminders:d,...t?{reminds:t}:{}}}};function zn(n){if(n.kind==="replyWait"){let e=n.nextRemindAt&&n.reminders<n.maxReminders?n.nextRemindAt:null;return e&&Date.parse(e)<Date.parse(n.deadline)?e:n.deadline}return n.kind==="agentStep"?n.blocked?null:n.nextNudgeAt??null:null}var G=(n,e)=>{let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t},Jn={"owner.notify":es,"owner.ask":ts,"person.message":ns,"person.wait":rs};var Z=async n=>({output:n.run.context[n.node.id]??{}}),os=async n=>{let e=n.node.config,t=String(e.agentId??""),r=String(e.prompt??"");if(!t)return{error:`agent node "${n.node.id}" missing config.agentId`};let o=Kn(n),s=ss(n),i=(s?`${s}
|
|
28
|
+
|
|
29
|
+
`:"")+R(r,n.run.context,{envAllow:n.workflow.envAllow})+(o?qn(n.run,n.node.id):""),a=typeof e.timeoutMinutes=="number"?e.timeoutMinutes:void 0,d=e.autonomy===void 0||e.autonomy===null?void 0:String(e.autonomy);if(d!==void 0&&d!=="report"&&d!=="propose"&&d!=="act")return{error:`agent node "${n.node.id}" has invalid autonomy "${d}" (expected report, propose or act)`};let u=typeof e.maxConcurrent=="number"&&e.maxConcurrent>0?e.maxConcurrent:null,c=u?Cn(n.workflow.id,n.node.id):null;if(c&&u){let f=Se.stats(c);f.active>=u&&n.log(`[node:${n.node.id}] gated: ${f.active} active (cap ${u}), ${f.waiting+1} waiting`),await Se.acquire(c,u)}let p=Date.now();try{let f=await n.agents.execute({agentId:t,message:i,workflowRunId:n.run.id,timeoutMinutes:a,...d?{autonomy:d}:{}}),g=Date.now()-p;if(f.error&&f.errorKind==="stopped")return n.log(`[node:${n.node.id}] agent "${t}" stopped by a signal; run paused at this step`),{paused:!0,pausedAt:{kind:"agentStop",nodeId:n.node.id,agentId:t,...f.runTaskId?{taskId:f.runTaskId}:{}}};if(f.error){let w=f.errorKind??"unknown";return n.log(`[node:${n.node.id}] agent "${t}" failed (${w}): ${f.error}`),o?dt(n,t,{error:`[${w}] ${f.error}`,output:{error:`[${w}] ${f.error}`}}):{error:`[${w}] ${f.error}`}}let y=String(e.resultParser??"acme-result-token")==="json"?Ws(f.content):We(f.content),b={reply:f.content,result:y.result,json:y.json,taskId:f.taskId,durationMs:g,...f.autonomyBlocks?.length?{autonomyBlocks:f.autonomyBlocks}:{}};return o?dt(n,t,{output:b,result:y.result,reply:f.content}):{output:b}}catch(f){return n.log(`[node:${n.node.id}] agent "${t}" threw: ${f.message}`),{error:f.message}}finally{c&&Se.release(c)}};function ss(n){let e=[...n.run.history??[]].reverse().find(r=>r.nodeId===n.node.id),t=e?.status==="resumed"?e.output?.resumeNote:void 0;return typeof t=="string"&&t?t:void 0}var is=async n=>{let e=rt(n.node,n.run.context);return e?{output:{port:e},port:e}:(n.log(`[node:${n.node.id}] branch matched no case and no default port`),{output:{port:null}})},as=async n=>{let e=v(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??""),r=String(e.chatId??""),o=String(e.text??"");if(!t||!r){let a=String(n.node.config.chatId??""),d=String(n.node.config.channel??""),u=[];return t||u.push(`channel config="${d}" rendered=""`),r||u.push(`chatId config="${a}" rendered=""`),(/\{\{\s*env\./.test(a)||/\{\{\s*env\./.test(d))&&u.push("(env.* templates only resolve for names listed in workflow.envAllow and actually set in process.env)"),{error:`action.send "${n.node.id}" needs channel + chatId \u2014 ${u.join("; ")}`}}let s=pt(n,e.accountId),i=n.channels[t];if(i?.send)try{return{output:{messageId:await i.send({channel:t,chatId:r,text:o,...s?{accountId:s}:{}})??null}}}catch(a){return{error:`action.send failed: ${a.message}`}}if(n.forwardChannelSend)try{return{output:{messageId:(await n.forwardChannelSend({channel:t,chatId:r,text:o,accountId:s})).messageId,viaMesh:!0}}}catch(a){return n.log(`[node:${n.node.id}] mesh-forward of "${t}" send failed: ${a.message}`),{error:`action.send via mesh failed: ${a.message}`}}return n.log(`[node:${n.node.id}] adapter "${t}" not available locally and no mesh forwarder`),{error:`channel "${t}" not available (no local adapter, no mesh route)`}},ds=async n=>{let e=v(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??"gitlab"),r=String(e.project??""),o=String(e.title??""),s=String(e.description??""),i=Array.isArray(e.labels)?e.labels.map(String):[],a=Array.isArray(e.assignees)?e.assignees.map(String):[];if(!r||!o)return{error:`action.createIssue "${n.node.id}" needs project + title`};let d=ft(n),u=n.channels[t];if(!u?.createIssue)return{error:`channel "${t}" does not support createIssue`};try{let c=await u.createIssue({project:r,title:o,description:s,labels:i,assignees:a,agentId:d});return c?{output:{issue:{iid:c.iid,url:c.url,webUrl:c.url}}}:{error:"createIssue returned null (see adapter log)"}}catch(c){return{error:`action.createIssue failed: ${c.message}`}}},us=async()=>({output:{}}),ls=async n=>{let e=n.node.config,t=String(e.name??n.node.id),r=e.waitFor??{},o=e.resumeMatch??{};return{paused:!0,pausedAt:{kind:"checkpoint",nodeId:n.node.id,checkpointName:t,resumeMatch:{...r,...o}}}},cs=async n=>{let e=v(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??"gitlab"),r=String(e.project??""),o=String(e.iid??""),s=Array.isArray(e.add)?e.add.map(String):[],i=Array.isArray(e.remove)?e.remove.map(String):[];if(!r||!o)return{error:`action.setLabel "${n.node.id}" needs project + iid (try {{trigger.project}} / {{trigger.issue.iid}})`};if(s.length===0&&i.length===0)return{output:{skipped:!0,reason:"no labels to add or remove"}};let a=n.channels[t];if(!a?.setLabels)return{error:`channel "${t}" does not support setLabels`};let d=ft(n),u=e.kind==="merge_request"?"merge_request":"issue";try{let c=await a.setLabels({project:r,kind:u,iid:o,add:s,remove:i,agentId:d});return c?{output:{labels:c,add:s,remove:i}}:{error:"action.setLabel failed: the label change did not apply (see adapter log)"}}catch(c){return{error:`action.setLabel failed: ${c.message}`}}},ps=async n=>{let e=v(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??"gitlab"),r=String(e.project??""),o=String(e.iid??"");if(!r||!o)return{error:`action.readLabel "${n.node.id}" needs project + iid`};let s=n.channels[t];if(!s?.getLabels)return{error:`channel "${t}" does not support getLabels`};let i=e.kind==="merge_request"?"merge_request":"issue";return{output:{labels:await s.getLabels({project:r,kind:i,iid:o})??[]}}},fs=async n=>{let e=v(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??""),r=String(e.chatId??""),o=String(e.messageId??""),s=String(e.emoji??"\u{1F440}");if(!t||!r||!o)return{error:`action.react "${n.node.id}" needs channel + chatId + messageId`};let i=pt(n,e.accountId),a=n.channels[t];if(!a?.react)return{error:`channel "${t}" does not support react`};try{return await a.react(r,o,s,i),{output:{emoji:s}}}catch(d){return{error:`action.react failed: ${d.message}`}}},gs=async n=>{let e=v(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??""),r=String(e.chatId??""),o=String(e.messageId??""),s=String(e.text??""),i=e.parseMode?String(e.parseMode):void 0;if(!t||!r||!o||!s)return{error:`action.editMessage "${n.node.id}" needs channel + chatId + messageId + text`};let a=pt(n,e.accountId),d=n.channels[t];if(!d?.editMessage)return{error:`channel "${t}" does not support editMessage`};try{return{output:{edited:await d.editMessage(r,o,s,i,a)}}}catch(u){return{error:`action.editMessage failed: ${u.message}`}}},ms=async n=>{let e=v(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??"gitlab"),r=String(e.chatId??""),o=Number(e.durationMs??0);if(!r||!o)return{error:`action.logTime "${n.node.id}" needs chatId + durationMs`};let s=n.channels[t];if(!s?.logTimeSpent)return{error:`channel "${t}" does not support logTimeSpent`};let i=ft(n);try{return await s.logTimeSpent(r,o,i),{output:{durationMs:o}}}catch(a){return{error:`action.logTime failed: ${a.message}`}}},hs=async n=>{let e=v(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.url??"");if(!t)return{error:`action.callHTTP "${n.node.id}" needs url`};let r=String(e.method??"POST").toUpperCase(),o=e.headers&&typeof e.headers=="object"?e.headers:{"Content-Type":"application/json"},s;e.body!==void 0&&(s=typeof e.body=="string"?e.body:JSON.stringify(e.body));try{let i=await fetch(t,{method:r,headers:o,body:s}),a=await i.text(),d=a;try{d=JSON.parse(a)}catch{}return{output:{ok:i.ok,status:i.status,body:d}}}catch(i){return{error:`action.callHTTP failed: ${i.message}`}}},ws=async n=>{let e=v(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.actionId??e.id??"");if(!t)return{error:`action.run "${n.node.id}" needs actionId`};let r=e.inputs&&typeof e.inputs=="object"?e.inputs:{},{ActionStore:o}=await import("./store-TWQPEM5V.js"),{runAction:s}=await import("./runner-56G3N7M4.js"),i=new o().get(t);if(!i)return{error:`action.run "${n.node.id}": no action "${t}" in registry`};try{let a=await s(i,r),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}`}}},ys=async n=>{let e=v(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.name??"");if(!t)return{error:`action.builtin "${n.node.id}" needs a "name" (e.g. "http.fetch")`};let r=e.input&&typeof e.input=="object"?e.input:{},{runBuiltin:o,getBuiltin:s}=await import("./builtin-U5S2XCNJ.js");if(!s(t))return{error:`action.builtin "${n.node.id}": unknown built-in "${t}"`};try{return{output:await o(t,r)}}catch(i){let a=i?.name==="ZodError"?`validation: ${i.message}`:i?.message||String(i);return{error:`action.builtin "${t}" failed: ${a}`}}},ks=async n=>{let e=n.node.config,t=n.run.context;return typeof e.path=="string"&&e.path?{output:{value:Q(t,e.path)}}:e.template&&typeof e.template=="object"?{output:v(e.template,t,{envAllow:n.workflow.envAllow})}:{output:{}}};function bs(n){if(n!=null){if(typeof n=="number")return new Date(Date.now()+n*6e4).toISOString();if(typeof n=="object"&&n&&"minutes"in n){let e=Number(n.minutes);if(Number.isFinite(e))return new Date(Date.now()+e*6e4).toISOString()}if(typeof n=="string"){let e=/^P(?:([0-9]+)D)?(?:T(?:([0-9]+)H)?(?:([0-9]+)M)?(?:([0-9]+)S)?)?$/.exec(n);if(e){let t=Number(e[1]??0),r=Number(e[2]??0),o=Number(e[3]??0),s=Number(e[4]??0),i=((t*24+r)*60+o)*6e4+s*1e3;if(i>0)return new Date(Date.now()+i).toISOString()}}}}var vs=async n=>{let e=n.node.config,t=v(e,n.run.context,{envAllow:n.workflow.envAllow}),r=String(t.workflowId??"");if(!r)return{error:`subProcess "${n.node.id}" missing config.workflowId`};let o=n.run.depth??0,s=n.workflow.maxChildDepth??5;if(o+1>=s)return{error:`max child workflow depth ${s} exceeded at ${n.workflow.id} \u2192 ${r} (parent depth ${o})`};let i=e.inputMap,a={};if(i==="*")a={...n.run.context};else if(i&&typeof i=="object")for(let[d,u]of Object.entries(i))u&&typeof u=="object"&&!Array.isArray(u)?a[d]=v(u,n.run.context,{envAllow:n.workflow.envAllow}):typeof u=="string"&&(a[d]={value:R(u,n.run.context,{envAllow:n.workflow.envAllow})});return{paused:!0,pausedAt:{kind:"subProcess",nodeId:n.node.id,childRunId:"",childWorkflowId:r},spawnChild:{workflowId:r,input:a}}},Is=Z,$s=async n=>{let e=n.node.config,t=v(e,n.run.context,{envAllow:n.workflow.envAllow}),r=String(t.name??"");if(!r)return{error:`signal.emit "${n.node.id}" missing config.name`};let o=t.scope==="global"?"global":"workflow",s=t.payload&&typeof t.payload=="object"?t.payload:{};return{output:{emittedAt:new Date().toISOString(),name:r,scope:o,payload:s},emitSignal:{name:r,scope:o,payload:s}}},As=async n=>{let e=n.node.config,t=v(e,n.run.context,{envAllow:n.workflow.envAllow}),r=String(t.name??"");if(!r)return{error:`signal.wait "${n.node.id}" missing config.name`};let o=t.scope==="global"?"global":"workflow",s=e.match&&typeof e.match=="object"?e.match:{};return{paused:!0,pausedAt:{kind:"signalWait",nodeId:n.node.id,signalName:r,match:s,scope:o}}},Ss=async n=>{let e=n.node.config,t=v(e,n.run.context,{envAllow:n.workflow.envAllow}),r=bs(t.after??e.after);if(!r)return{error:`timer.boundary "${n.node.id}" needs config.after (duration or minutes)`};let o=_n(t.wake);return{paused:!0,pausedAt:{kind:"timerWait",nodeId:n.node.id,fireAt:r,...o?{wake:o}:{}}}},Rs=async()=>({output:{}}),xs=async n=>{let e=n.node.config,r=(Array.isArray(e.inputs)?e.inputs:[]).map(i=>typeof i=="string"?R(i,n.run.context,{envAllow:n.workflow.envAllow}):i),o=Array.isArray(e.rules)?e.rules:[];for(let i of o){let a=Array.isArray(i.when)?i.when:[];if(a.length!==r.length)continue;let d=!0;for(let u=0;u<a.length;u++)if(!Ps(a[u],r[u])){d=!1;break}if(d)return{output:{...i.output??{},matchedPort:i.to??""},port:i.to}}let s=e.default;return{output:{...s?.output??{},matchedPort:s?.to??""},port:s?.to}};function Ps(n,e){if(n==null||n==="*")return!0;let t=String(n),r=typeof e=="number"?e:String(e??""),o=/^(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/.exec(t);if(o){let s=o[1],i=Number(o[2]),a=typeof r=="number"?r:Number(r);if(Number.isNaN(a))return!1;switch(s){case">":return a>i;case"<":return a<i;case">=":return a>=i;case"<=":return a<=i}}if(t.startsWith("!="))return String(r)!==t.slice(2);if(t.startsWith("/")&&t.endsWith("/")&&t.length>2)try{return new RegExp(t.slice(1,-1)).test(String(r))}catch{return!1}return String(r)===t}var Yn={"trigger.channel":Z,"trigger.manual":Z,"trigger.cron":Z,"trigger.hook":Z,"trigger.form":Is,"trigger.poll":Z,agent:os,classify:jn,branch:is,transform:ks,"gateway.parallel":Rs,rule:xs,"action.send":as,"action.createIssue":ds,"action.setLabel":cs,"action.readLabel":ps,"action.react":fs,"action.editMessage":gs,"action.logTime":ms,"action.callHTTP":hs,"action.run":ws,"action.builtin":ys,subProcess:vs,"signal.emit":$s,"signal.wait":As,"timer.boundary":Ss,checkpoint:ls,end:us,...Jn};function ct(n){return Yn[n]}function pt(n,e){if(typeof e=="string"&&e)return e;let t=n.workflow.nodes.find(s=>s.type.startsWith("trigger."));if(!t)return;let o=n.run.context[t.id]?.accountId;return typeof o=="string"&&o?o:void 0}function ft(n){for(let e=n.run.history.length-1;e>=0;e--){let t=n.run.history[e],r=n.workflow.nodes.find(o=>o.id===t.nodeId);if(r?.type==="agent")return r.config.agentId??void 0}}function We(n){if(!n)return{};let e=n.match(/\bRESULT:\s*([a-z][a-z0-9_-]*)/i);if(e)return{result:e[1].toLowerCase()};let t=n.match(/\[(APPROVED|REJECTED|CHANGES[-_]REQUESTED|DONE|FAILED|SKIPPED)\]/i);return t?{result:t[1].toLowerCase().replace("_","-")}:{}}function Ws(n){let{result:e}=We(n);if(!n)return{result:e};let t=n.match(/```(?:json)?\s*([\s\S]*?)```/);if(!t)return{result:e};try{return{result:e,json:JSON.parse(t[1])}}catch{return{result:e}}}var de=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 Te(n,e){if(n.name!==e.name||n.scope==="workflow"&&n.workflowId!==e.workflowId)return!1;for(let[t,r]of Object.entries(n.match??{}))if(!(r===void 0||r===""||r==="*")&&e.payload[t]!==r)return!1;return!0}function Ts(n,e,t=Date.now){return{ts:t(),source:"workflow",sourceEventId:`${n.workflowId}:${n.eventId}`,project:n.project,subject:`workflow:${n.workflowId}:entity:${n.entityRef.backend}:${n.entityRef.id}`,intent:`workflow.${n.triggerSource}`,rawJson:e}}function Ns(n){return n.claimed&&n.runId?{agentId:`workflow-run:${n.runId}`,outcome:"dispatched",reason:n.reason??"claimed"}:n.claimed&&!n.runId?{agentId:null,outcome:"halted",reason:n.reason??"claimed-but-no-run"}:{agentId:null,outcome:"halted",reason:n.reason??"not-claimed"}}function Os(n){return{decidedBy:"workflow-dispatcher",decide:()=>({agentId:n.agentId,outcome:n.outcome==="deduped"?"halted":n.outcome,reason:n.outcome==="deduped"?`legacy-dedup: ${n.reason??""}`.trim():n.reason??null})}}function Vn(n,e,t,r,o=Date.now){let s=Ts(e,t,o),i=Ns(r),a=Os(i),d=Bt(n,s,a,o);return Kt(n,"workflow",d,i,o),d}xr();var gt=new Set(["completed","failed","canceled"]),Ms=4e3,Es=8,mt=class{store;runs;nodeId;forwarder;channels;agents;log;timers;signals;events;owner;followUpDefaults;onRunEnded;onBlocked;timerWaitRuns;replyWaiters=null;earlyDone=new Map;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 Ue({log:t=>this.log(t)}),this.signals=e.signals??new de,this.events=e.events,this.owner=e.owner,this.followUpDefaults=e.followUp??(()=>Re),this.onRunEnded=e.onRunEnded,this.onBlocked=e.onBlocked,this.timers.onFire(t=>this.resumeFromTimer(t)),this.timers.onSweep(()=>this.recoverOverdueTimers()),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 r of t){if(r.status!=="paused"||!r.pausedAt||r.pausedAt.kind!=="signalWait")continue;let o={name:r.pausedAt.signalName,scope:r.pausedAt.scope,workflowId:r.workflowId,match:r.pausedAt.match??{}};if(!Te(o,e))continue;let s=this.store.list().find(i=>i.id===r.workflowId);s&&(await this.commit(r.id,()=>{let i=this.runs.get(r.id);if(!i||i.status!=="paused"||!i.pausedAt||i.pausedAt.kind!=="signalWait"||!Te({name:i.pausedAt.signalName,scope:i.pausedAt.scope,workflowId:i.workflowId,match:i.pausedAt.match??{}},e))return;let a=P(s,i.pausedAt.nodeId),d=a?s.edges.filter(c=>c.from===a.id).map(c=>c.to):[],u={receivedAt:new Date().toISOString(),name:e.name,payload:e.payload};this.runs.recordExecution({runId:i.id,entry:{at:u.receivedAt,nodeId:i.pausedAt.nodeId,inputKeys:[],status:"resumed",output:u,idempotencyKey:I(i.id,i.pausedAt.nodeId,`signal:${e.name}:${e.emittedAt}`)},nextPending:d,status:"running",pausedAt:null,context:{...i.context,[i.pausedAt.nodeId]:u}}),this.log(`[workflow:${s.id}] run ${i.id} resumed from signal "${e.name}"`),this.emitRunEvent({runId:i.id,workflowId:s.id,nodeId:i.pausedAt.nodeId,phase:"resumed",status:"running",note:`signal:${e.name}`,rootId:i.eventRootId})}),this.walk(s,r.id,`signal:${e.name}`).catch(i=>this.log(`[workflow:${s.id}] walk-after-signal failed: ${i.message}`)))}}async wake(e){let t=[],r=new Set;for(let o of this.timers.list()){let s=`${o.runId}:${o.nodeId}`;if(o.cancelKey!==s||r.has(s))continue;r.add(s);let i=this.runs.get(o.runId),a=i?.pausedAt;if(!i||a?.kind!=="timerWait"||a.nodeId!==o.nodeId||!Un(a.wake,e))continue;let d=e.selfMarked?"self":await this.commit(i.id,()=>this.applyWake(i.id,o.nodeId,e));this.log(`[workflow:${i.workflowId}] wake run=${i.id} node=${o.nodeId} event=${e.on}:${e.ref} result=${d}`),t.push({runId:i.id,nodeId:o.nodeId,result:d})}return t.length||this.log(`[workflows] wake event=${e.on}:${e.ref} result=no-run`),t}applyWake(e,t,r){let o=this.runs.get(e),s=o?.pausedAt;if(!o||o.status!=="paused"||s?.kind!=="timerWait"||s.nodeId!==t||!s.wake)return"stale";let i=Ln(s.wake,r);if(i)return this.runs.patch(e,{pausedAt:{...s,wake:{...s.wake,selfLabels:i}}}),"self";let a=Date.now(),d=Hn({nowMs:a,lastWakeAt:o.meta?.lastWakeAt,minGapSec:s.wake.minGapSec,fireAt:s.fireAt});return d?this.timers.retime(`${e}:${t}`,d.fireAt)?(this.runs.patch(e,{pausedAt:{...s,fireAt:d.fireAt},...d.result==="woke"?{meta:{lastWakeAt:new Date(a).toISOString()}}:{}}),d.result):"stale":"debounced"}async resumeFromTimer(e){let t=this.runs.get(e.runId)?.workflowId,r=t?this.store.list().find(i=>i.id===t):void 0;if(!r){this.log(`[workflows] timer ${e.id} for run ${e.runId} dropped: ${t?`workflow "${t}" not loaded`:"run not found"}`);return}let o=this.runs.get(e.runId)?.pausedAt?.kind;if(o==="replyWait"||o==="agentStep"){await this.followUpTimer(r,e);return}await this.resumeTimerWait(r,e.runId,e.nodeId,e.fireAt,{key:`timer:${e.id}`,note:`timer:${e.id}`})&&this.walk(r,e.runId,`timer:${e.id}`).catch(i=>this.log(`[workflow:${r.id}] walk-after-timer failed: ${i.message}`))}async resumeTimerWait(e,t,r,o,s){return this.commit(t,()=>{let i=this.runs.get(t);if(!i||i.status!=="paused")return!1;let a=i.pausedAt;if(!a||a.kind!=="timerWait"||a.nodeId!==r||a.fireAt!==o)return!1;let d=P(e,r),u=d?e.edges.filter(f=>f.from===d.id).map(f=>f.to):[],c=new Date().toISOString(),p={firedAt:c,scheduledFor:o,...s.recovered?{recovered:!0}:{}};if(this.runs.recordExecution({runId:i.id,entry:{at:c,nodeId:r,inputKeys:[],status:"resumed",output:p,idempotencyKey:I(i.id,r,s.key),...s.recovered?{note:"timer-recovered"}:{}},nextPending:u,status:"running",pausedAt:null,context:{...i.context,[r]:p}}),s.recovered){this.timers.cancel({cancelKey:`${i.id}:${r}`});let f=Math.round((Date.parse(c)-Date.parse(o))/1e3);this.log(`[workflow:${e.id}] run ${i.id} timer-recovered on "${r}" (due ${o}, ${f}s overdue)`)}else this.log(`[workflow:${e.id}] run ${i.id} resumed from timer "${r}" (fired ${c})`);return this.emitRunEvent({runId:i.id,workflowId:e.id,nodeId:r,phase:"resumed",status:"running",note:s.note,rootId:i.eventRootId}),!0})}async recoverOverdueTimers(e=Date.now()){let t=2*this.timers.tickIntervalMs;if(!this.timerWaitRuns){let o=new Set;for(let s of this.runs.list({active:!0}))s.status==="paused"&&s.pausedAt?.kind==="timerWait"&&o.add(s.id);this.timerWaitRuns=o}let r=0;for(let o of[...this.timerWaitRuns]){let s=this.runs.get(o),i=s?.pausedAt;if(!s||s.status!=="paused"||!i||i.kind!=="timerWait"){this.timerWaitRuns.delete(o);continue}let a=Date.parse(i.fireAt);if(Number.isNaN(a)||e-a<=t)continue;let d=this.store.list().find(c=>c.id===s.workflowId);if(!d){this.log(`[workflows] run ${s.id} timer overdue on "${i.nodeId}" but workflow "${s.workflowId}" is not loaded \u2014 left paused`);continue}await this.resumeTimerWait(d,s.id,i.nodeId,i.fireAt,{key:`timer-recovered:${i.fireAt}`,note:"timer-recovered",recovered:!0})&&(r++,this.walk(d,s.id,`timer-recovered:${i.nodeId}:${i.fireAt}`).catch(c=>this.log(`[workflow:${d.id}] walk-after-timer-recovery failed: ${c.message}`)))}return r}async dispatchWorkflow(e){let t=this.store.list().find(d=>d.id===e.workflowId);if(!t)return this.log(`[workflows] dispatchWorkflow: workflow "${e.workflowId}" not found`),{claimed:!1,run:null};let r=this.runs.getActiveByEntity(e.entityRef),o=r?this.runs.get(r):null;if(o&&o.workflowId!==t.id)return this.log(`[workflow:${t.id}] entity ${e.entityRef.id} has run ${o.id} of workflow "${o.workflowId}" \u2014 not dispatching`),{claimed:!1,run:null};let i=t.nodes.find(d=>d.type.startsWith("trigger."))?.config??{},a={source:e.trigger?.source??i.source??"hook",project:e.trigger?.project,repo:e.trigger?.repo,chat:e.trigger?.chat,labels:e.trigger?.labels};return this.dispatchOne(t,e.entityRef,j(e.event),a)}startChannelAck(e,t){let r=String(t.channel??""),o=String(t.chatId??"");if(!r||!o)return;let s=this.channels[r];if(!s)return;let i=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&&s.react)try{Promise.resolve(s.react(o,d,"\u{1F440}",i)).catch(()=>{})}catch{}if(this.ackTypingTimers.has(e)||!s.sendTyping)return;let u=()=>{try{Promise.resolve(s.sendTyping(o,i)).catch(()=>{})}catch{}};u();let c=setInterval(u,Ms);this.ackTypingTimers.set(e,c)}stopChannelAck(e){let t=this.ackTypingTimers.get(e);t&&(clearInterval(t),this.ackTypingTimers.delete(e))}async dispatch(e){let t=j(e.event),r=this.matchByTrigger(e.trigger,e.fromRemote),s=r.some(d=>d.fanOut)?r:r.slice(0,1),i=[],a=[];for(let d of s){let u=await this.dispatchOne(d,e.entityRef,t,e.trigger);u.claimed&&i.push(d),u.run&&a.push(u.run)}return!e.fromRemote&&this.forwarder?.broadcastTrigger&&Promise.resolve(this.forwarder.broadcastTrigger({trigger:e.trigger,entityRef:e.entityRef,event:t})).catch(d=>this.log(`[mesh-broadcast] ${d?.message??d}`)),{claimed:i,runs:a}}matchByTrigger(e,t){let r=this.store.list(),o=[];for(let s of r){if(s.state&&s.state!=="active")continue;if(t){if(!s.mesh?.allowRemote)continue;let u=s.mesh.peers;if(u&&u.length>0&&!u.includes(t.peer))continue}let i=s.nodes.find(u=>u.type.startsWith("trigger."));if(!i)continue;let a=i.config;if(a.source!==e.source||s.project&&e.project&&s.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!=="*"&&H(e.source,d.chat)!==H(e.source,e.chat))continue;if(d.labels?.length){let u=new Set(e.labels??[]);if(!d.labels.some(p=>u.has(p)))continue}}o.push(s)}return o.sort((s,i)=>i.priority-s.priority||s.id.localeCompare(i.id))}async dispatchOne(e,t,r,o){let s=await this.dispatchOneLegacy(e,t,r,o);if(Ht("workflow")!=="off")try{Vn(Ct(),{workflowId:e.id,eventId:r.id,triggerSource:o.source,project:o.project??null,entityRef:t},JSON.stringify({event:r,trigger:o,entityRef:t}),{claimed:s.claimed,runId:s.run?.id??null})}catch(i){this.log(`[ledger] workflow ${e.id} run ${s.run?.id??"?"} record failed: ${i?.message??i}`)}return s}async dispatchOneLegacy(e,t,r,o){let s=this.runs.getActiveByEntity(t),i=s?this.runs.getHomeNodeByEntity(t):null;if(s&&i&&i!==this.nodeId){if(!this.forwarder)return this.log(`[workflow:${e.id}] run ${s} home'd on "${i}" but no forwarder \u2014 dropping`),{claimed:!1,run:null};try{await this.forwarder.forwardTransition(i,{workflowId:e.id,event:r,entityRef:t})}catch(d){this.log(`[workflow:${e.id}] forward to "${i}" failed: ${d.message}`)}return{claimed:!0,run:null}}let a=s?this.runs.get(s):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(!Cs(a.pausedAt.resumeMatch,o,r))return this.log(`[workflow:${e.id}] run ${a.id} paused but event doesn't match resumeMatch \u2014 dropping`),{claimed:!1,run:null};let d=P(e,a.pausedAt.nodeId),u=d?e.edges.filter(m=>m.from===d.id).map(m=>m.to):[],c={at:new Date().toISOString(),nodeId:a.pausedAt.nodeId,inputKeys:[],status:"resumed",output:{event:r.payload},idempotencyKey:I(a.id,a.pausedAt.nodeId,`resume:${r.id}`)},p={...a.context,[a.pausedAt.nodeId]:{event:r.payload}},f=a.pausedAt.checkpointName,g=this.runs.recordExecution({runId:a.id,entry:c,nextPending:u,status:"running",pausedAt:null,context:p});g&&(a=g),this.log(`[workflow:${e.id}] run ${a.id} resumed from checkpoint "${f}"`),o.source.endsWith("-message")&&this.startChannelAck(a.id,r.payload)}else return a.status==="running"?(this.log(`[workflow:${e.id}] run ${a.id} already running; dropping concurrent event ${r.id}`),{claimed:!0,run:null}):(this.log(`[workflow:${e.id}] run ${a.id} is ${a.status}; dropping event ${r.id}`),{claimed:!1,run:null});else{let d=ae(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]:r.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,r.payload)}return this.walk(e,a.id,r.id),{claimed:!0,run:a}}async walk(e,t,r){let o=this.runs.get(t)?.eventRootId,s=()=>this.walkInner(e,t,r);try{await(o?_t({rootId:o},s):s())}finally{this.stopChannelAck(t),await this.settle(t)}}async walkInner(e,t,r){let o=this.runs.get(t);if(o)for(;o.status==="running"&&o.pending.length>0;){let s=o.pending.slice(0,Es);await Promise.allSettled(s.map(a=>this.executeNodeAndCommit(e,t,a,r)));let i=this.runs.get(t);if(!i||(o=i,o.status!=="running"))return}}async executeNodeAndCommit(e,t,r,o){let s=I(t,r,o),i=await this.commit(t,()=>{let h=this.runs.get(t);if(!h)return{kind:"done"};if(h.status!=="running")return{kind:"done"};let S=P(e,r);if(!S)return this.log(`[workflow:${e.id}] missing node "${r}" \u2014 marking run failed`),this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:r,inputKeys:[],status:"failed",idempotencyKey:s,note:"node definition missing from workflow"},nextPending:h.pending.filter(D=>D!==r),status:"failed"}),{kind:"done"};let F=ct(S.type);return F?h.history.some(D=>D.idempotencyKey===s)?(this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:r,inputKeys:[],status:"skipped",idempotencyKey:s+"_dedup",note:"duplicate execution dropped"},nextPending:h.pending.filter(D=>D!==r)}),{kind:"done"}):{kind:"go",run:h,node:S,handler:F}:(this.log(`[workflow:${e.id}] no handler for node type "${S.type}"`),this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:r,inputKeys:[],status:"failed",idempotencyKey:s,note:`no handler for node type "${S.type}"`},nextPending:h.pending.filter(D=>D!==r),status:"failed"}),{kind:"done"})});if(i.kind==="done")return;let{run:a,node:d,handler:u}=i,c=e.edges.filter(h=>h.to===r).map(h=>h.from),p;if(d.type!=="agent"){let h=Ee();if(h)try{p=qt(h,{agentId:`workflow:${d.type}`,channel:"workflow",chatId:`${e.id}:${r}`,workflowRunId:t,workflowId:e.id,workflowNodeId:r,messagePreview:`${d.type} ${r}`})}catch{}}let f=d.retry??{maxAttempts:1,backoffMs:1e3},g={error:"retry-loop did not run"},m=0,y=Date.now(),b=()=>({startedAt:new Date(y).toISOString(),durationMs:Math.max(0,Date.now()-y)});for(;m<f.maxAttempts;){m++;try{g=await u({workflow:e,run:a,node:d,channels:this.channels,agents:this.agents,forwardChannelSend:this.forwarder?.forwardChannelSend?.bind(this.forwarder),log:this.log,owner:this.owner,followUp:this.followUpDefaults()})}catch(h){this.log(`[workflow:${e.id}] handler "${d.type}" threw: ${h.message}`),g={error:h.message}}if(!g.error||g.paused)break;if(m<f.maxAttempts){let h=f.backoffMs*Math.pow(2,m-1);this.log(`[workflow:${e.id}] node "${r}" failed (attempt ${m}/${f.maxAttempts}): ${g.error.slice(0,120)} \u2014 retrying in ${h}ms`),await new Promise(S=>setTimeout(S,h))}}let w=this.earlyDone.get(`${t}:${r}`);if(w&&(this.earlyDone.delete(`${t}:${r}`),g.paused&&g.pausedAt?.kind==="agentStep"&&!g.blocked&&(g={output:{...g.output??{},...w}})),p){let h=Ee();if(h)try{Gt(h,p,{status:g.error?"error":"ok",error:g.error??null})}catch{}}await this.commit(t,async()=>{let h=this.runs.get(t);if(!h)return;let S=new Date().toISOString(),F=h.pending.filter(k=>k!==r);if(g.error){let k=h.status==="running"?"failed":void 0;this.runs.recordExecution({runId:t,entry:{at:S,nodeId:r,inputKeys:c,status:"failed",idempotencyKey:s,note:g.error.slice(0,200),...b()},nextPending:F,status:k}),this.emitRunEvent({runId:t,workflowId:e.id,nodeId:r,phase:"failed",status:k??h.status,note:g.error.slice(0,200)});return}if(g.paused&&g.pausedAt&>.has(h.status)){this.runs.recordExecution({runId:t,entry:{at:S,nodeId:r,inputKeys:c,status:"skipped",idempotencyKey:s,note:`step ended after the run was ${h.status}`},nextPending:F});return}if(g.paused&&g.pausedAt){let k=g.pausedAt,_=null;if(g.spawnChild&&k.kind==="subProcess"){if(_=await this.spawnChild({parent:h,parentNodeId:r,childWorkflowId:g.spawnChild.workflowId,input:g.spawnChild.input}),!_){this.runs.recordExecution({runId:t,entry:{at:S,nodeId:r,inputKeys:c,status:"failed",idempotencyKey:s,note:`subProcess: child workflow "${g.spawnChild.workflowId}" not found`},nextPending:F,status:"failed"});return}k={...k,childRunId:_.id}}if(this.runs.recordExecution({runId:t,entry:{at:S,nodeId:r,inputKeys:c,status:"paused",idempotencyKey:s,...b(),...g.blocked?{note:`blocked: ${g.blocked}`.slice(0,200)}:{}},nextPending:F,status:"paused",pausedAt:k,...g.output?{context:{...h.context,[r]:g.output}}:{}}),this.emitRunEvent({runId:t,workflowId:e.id,nodeId:r,phase:"paused",status:"paused",note:k.kind}),this.scheduleWake(t,e.id,k),g.blocked&&this.markBlocked(t,e,r,g.blocked),_&&this.kickChildWalk(_),k.kind==="timerWait"){this.timerWaitRuns?.add(t);try{this.timers.schedule({runId:t,workflowId:e.id,nodeId:k.nodeId,fireAt:k.fireAt,cancelKey:`${t}:${k.nodeId}`})}catch($t){this.log(`[workflow:${e.id}] timer schedule failed: ${$t.message}`)}}return}let D=g.output??{},vr={...h.context,[r]:D},{nextPending:Ir}=Ie({workflow:e,fromNodeId:r,selectedPort:g.port}),Me=[],le={...h.joinCounters??{}};for(let k of Ir){let _=P(e,k);if(!(_?.type==="gateway.parallel"&&String(_.config?.mode??"fanOut")==="join")){Me.push(k);continue}let pe=le[k]??[];pe.includes(r)||pe.push(r),le[k]=pe;let Sr=e.edges.filter(Rr=>Rr.to===k).length;pe.length>=Sr&&(Me.push(k),delete le[k])}let $r=[...F,...Me],ce=d.type==="end",Ar=h.status==="running"?ce?String(d.config.status??"completed"):"running":void 0,B=this.runs.recordExecution({runId:t,entry:{at:S,nodeId:r,inputKeys:c,status:"ok",output:D,idempotencyKey:s,...b()},nextPending:ce?[]:$r,status:Ar,context:vr,joinCounters:le});this.emitRunEvent({runId:t,workflowId:e.id,nodeId:r,phase:ce?"completed":"ok",status:B?.status??h.status}),g.emitSignal&&this.emitSignal({name:g.emitSignal.name,scope:g.emitSignal.scope,workflowId:e.id,payload:g.emitSignal.payload}),ce&&B&&B.parentRunId&&B.parentNodeId&&this.resumeParent({parentRunId:B.parentRunId,parentNodeId:B.parentNodeId,childRun:B}).catch(k=>this.log(`[workflow:${e.id}] resumeParent failed: ${k.message}`))})}async startRun(e){let t=this.store.get(e.workflowId);if(!t)return{run:null,error:`workflow "${e.workflowId}" not found`};let r=ae(t);if(!r)return{run:null,error:`workflow "${t.id}" has no trigger node`};let o=e.entityRef??{backend:"follow-up",id:`${t.id}:${Ds()}`},s={tags:[],approvedAtStart:!1,...e.meta,followUp:e.meta?.followUp??!0},i=this.runs.create({workflowId:t.id,initialPending:r.pending,entityRef:o,initialContext:{[r.triggerId]:e.inputs??{}},meta:s});this.log(`[workflow:${t.id}] follow-up run ${i.id} started${s.startedBy?` by ${s.startedBy}`:""}`),this.emitRunEvent({runId:i.id,workflowId:t.id,phase:"created",status:i.status,homeNode:i.homeNode,rootId:i.eventRootId});let a=this.startMessages(t,i);if((t.approval??this.followUpDefaults().approval)==="start"&&a.some(u=>u.msg)&&!s.approvedAtStart){let u=async p=>(this.runs.setStatus(i.id,"failed"),await this.settle(i.id),{run:this.runs.get(i.id),error:p});if(!this.owner)return u("this workflow needs the owner's approval at start, and there is no owner to ask on this node");let c=a.map(({nodeId:p,msg:f})=>f?`- ${p} to ${f.to?`${f.to} `:""}(${f.channel} ${f.chatId}): ${f.text.replace(/\s+/g," ").slice(0,160)}`:`- ${p}: asked again before it is sent (it uses what an earlier step produces)`);try{let{cardId:p}=await this.owner.ask({title:(s.title??t.title).slice(0,120),ask:`Start "${t.title}" and let it send the message(s) below without asking again?`.slice(0,300),recommend:"Yes if the recipients and the text below are right.",context:c.join(`
|
|
30
|
+
`).slice(0,600)},i,r.triggerId);return this.runs.recordExecution({runId:i.id,entry:{at:new Date().toISOString(),nodeId:r.triggerId,inputKeys:[],status:"paused",idempotencyKey:I(i.id,r.triggerId,"start-approval"),note:"waiting for the owner's approval at start"},nextPending:r.pending,status:"paused",pausedAt:{kind:"ownerDecision",nodeId:r.triggerId,cardId:p,purpose:"start"}}),{run:this.runs.get(i.id),awaitingApproval:!0}}catch(p){return u(`could not ask the owner: ${p?.message??p}`)}}return this.walk(t,i.id,`start:${i.id}`).catch(u=>this.log(`[workflow:${t.id}] walk after start failed: ${u.message}`)),{run:i}}startMessages(e,t){let r=e.nodes.find(o=>o.type.startsWith("trigger."))?.id??"";return e.nodes.filter(o=>o.type==="person.message").map(o=>{let s=o.config;if([s.channel,s.chatId,s.text,s.to,s.accountId].flatMap(d=>typeof d=="string"?[...d.matchAll(/\{\{\s*([A-Za-z_][\w-]*)/g)].map(u=>u[1]):[]).some(d=>d!==r&&d!=="env"))return{nodeId:o.id,msg:null};let a=ut({node:o,run:t,workflow:e});return{nodeId:o.id,msg:a.channel&&a.chatId&&a.text?a:null}})}async resumeFromCard(e){let t=e.origin?.kind==="workflow"?e.origin.runId:void 0;if(!t||e.status==="pending")return!1;let r=this.runs.get(t),o=r?this.store.get(r.workflowId):null;if(!r||!o)return!1;let s=e.status==="decided"?e.verdict==="yes"?"yes":"no":"expired",i=!1,a=!1,d,u=r.pausedAt,c=null;return u?.kind==="ownerDecision"&&u.cardId===e.id&&u.purpose==="send"&&s==="yes"&&u.message&&(c=await Pe({channels:this.channels,forwardChannelSend:this.forwarder?.forwardChannelSend?.bind(this.forwarder)},{...u.message,text:e.text?.trim()||u.message.text})),await this.commit(t,()=>{let p=this.runs.get(t),f=p?.pausedAt;if(!p||p.status!=="paused"||f?.kind!=="ownerDecision"||f.cardId!==e.id)return;i=!0;let g=new Date().toISOString(),m=I(p.id,f.nodeId,`card:${e.id}`);if(f.purpose==="start"){if(s==="yes"){let b={};for(let{nodeId:w,msg:h}of this.startMessages(o,p))h&&(b[w]=lt(h));this.runs.setMeta(p.id,{approvedAtStart:!0,approved:b}),this.runs.recordExecution({runId:p.id,entry:{at:g,nodeId:f.nodeId,inputKeys:[],status:"resumed",idempotencyKey:m,note:"approved at start"},nextPending:p.pending,status:"running",pausedAt:null}),a=!0}else this.runs.recordExecution({runId:p.id,entry:{at:g,nodeId:f.nodeId,inputKeys:[],status:"failed",idempotencyKey:m,note:s==="no"?"the owner said no at start":"the owner did not answer before the start card expired"},nextPending:[],status:"canceled",pausedAt:null});return}let y={cardId:e.id,verdict:e.verdict??null,status:e.status,choice:e.choice??null,text:e.text??null,note:e.note??null};if(f.purpose==="send"){if(s==="yes"&&c&&"error"in c){d=c.error,this.runs.recordExecution({runId:p.id,entry:{at:g,nodeId:f.nodeId,inputKeys:[],status:"failed",idempotencyKey:m,note:c.error.slice(0,200)},nextPending:[],status:"failed",pausedAt:null});return}let b=s==="yes"?{...y,...f.message,text:e.text?.trim()||f.message?.text,messageId:c&&"messageId"in c?c.messageId:null,approved:"step"}:{...y,...f.message,declined:!0};a=this.resumeOn(o,p,f.nodeId,b,s==="yes"?"sent":"declined",m,s==="yes"?"sent after approval":`not sent: ${s==="no"?"the owner said no":"the card expired"}`);return}a=this.resumeOn(o,p,f.nodeId,y,s,m,`owner answered: ${s}`)}),d&&this.log(`[workflow:${o.id}] run ${t}: approved message not sent: ${d}`),a?this.walk(o,t,`card:${e.id}`).catch(p=>this.log(`[workflow:${o.id}] walk after card failed: ${p.message}`)):i&&await this.settle(t),i}async resumeFromReply(e){let t=`${e.channel}-message`;if(!this.replyWaiters){this.replyWaiters=new Map;for(let s of this.runs.list({limit:500}))s.status==="paused"&&s.pausedAt?.kind==="replyWait"&&this.noteReplyWaiter(s.id,s.pausedAt.channel)}let r=this.replyWaiters.get(e.channel);if(!r?.size)return null;let o=[...r].map(s=>this.runs.get(s)).filter(s=>s?.status==="paused"&&s.pausedAt?.kind==="replyWait"?!0:(s&&r.delete(s.id),!1)).filter(s=>{let i=s.pausedAt;return!(i.channel!==e.channel||H(t,i.chatId)!==H(t,e.chatId)||i.accountId&&e.accountId&&i.accountId!==e.accountId||i.from&&H(t,i.from)!==H(t,e.senderId??""))}).sort((s,i)=>s.createdAt.localeCompare(i.createdAt));for(let s of o){let i=this.store.get(s.workflowId);if(!i)continue;let a=!1;if(await this.commit(s.id,()=>{let d=this.runs.get(s.id),u=d?.pausedAt;if(!d||d.status!=="paused"||u?.kind!=="replyWait"||u.nodeId!==s.pausedAt.nodeId)return;a=!0;let c={text:e.text,from:e.senderId??null,fromName:e.senderName??null,media:e.media??null,channel:e.channel,chatId:e.chatId,at:new Date().toISOString(),reminders:u.reminders};this.timers.cancel({cancelKey:`${d.id}:${u.nodeId}`}),this.resumeOn(i,d,u.nodeId,c,"reply",I(d.id,u.nodeId,`reply:${e.messageId??c.at}`),"reply received")}),!!a)return r.delete(s.id),this.walk(i,s.id,`reply:${e.messageId??Date.now()}`).catch(d=>this.log(`[workflow:${i.id}] walk after reply failed: ${d.message}`)),s.id}return null}async stepDone(e){let t=this.runs.get(e.runId);if(!t)return{ok:!1,error:`no run "${e.runId}"`};let r=this.store.get(t.workflowId);if(!r)return{ok:!1,error:`workflow "${t.workflowId}" is gone`};let o,s=!1;return await this.commit(e.runId,()=>{let i=this.runs.get(e.runId),a=i?.pausedAt;if(i?.status==="running"&&!e.blocked){let u=e.nodeId??i.pending.find(f=>P(r,f)?.type==="agent"),c=u?P(r,u):void 0,p=c?String(c.config.agentId??""):"";if(c?.type==="agent"&&i.pending.includes(c.id)&&(!e.agentId||e.agentId===p||e.agentId===i.meta?.startedBy)){this.earlyDone.set(`${i.id}:${c.id}`,{...e.output??{},result:e.output?.result??"done",doneAt:new Date().toISOString()});return}}if(!i||i.status!=="paused"||a?.kind!=="agentStep"){o=`run ${e.runId} is not waiting on an agent step (it is ${i?.status??"gone"}${a?`, on ${a.kind} ${a.nodeId}`:""})`;return}if(e.nodeId&&e.nodeId!==a.nodeId){o=`run ${e.runId} waits on step "${a.nodeId}", not "${e.nodeId}"`;return}if(e.agentId&&e.agentId!==a.agentId&&e.agentId!==i.meta?.startedBy){o=`step "${a.nodeId}" belongs to ${a.agentId}`;return}if(e.blocked){a.blocked||this.blockStep(r,i,a,e.blocked);return}this.timers.cancel({cancelKey:`${i.id}:${a.nodeId}`}),i.meta?.blocked&&this.runs.setMeta(i.id,{blocked:void 0});let d={...i.context[a.nodeId]??{},...e.output??{},result:e.output?.result??"done",doneAt:new Date().toISOString()};s=this.resumeOn(r,this.runs.get(i.id),a.nodeId,d,void 0,I(i.id,a.nodeId,`done:${d.doneAt}`),"reported done")}),o?{ok:!1,error:o}:(s?this.walk(r,e.runId,`done:${e.runId}`).catch(i=>this.log(`[workflow:${r.id}] walk after step done failed: ${i.message}`)):await this.settle(e.runId),{ok:!0})}agentStepOf(e,t){let r=this.runs.get(e);if(!r)return{error:`no workflow run ${e}`};if(r.status!=="running")return{error:`workflow run ${e} is ${r.status}`};let o=this.store.get(r.workflowId);if(!o)return{error:`workflow "${r.workflowId}" is gone`};let s=r.pending.filter(i=>{let a=P(o,i);return a?.type==="agent"&&String(a.config.agentId??"")===t});return s.length!==1?{error:s.length?`workflow run ${e} runs ${t} in ${s.length} steps at once`:`workflow run ${e} is not on a step of ${t}`}:{workflowId:r.workflowId,nodeId:s[0]}}async resumeStoppedStep(e){let t=this.runs.get(e.runId);if(!t)return{ok:!1,error:`no workflow run ${e.runId}`};let r=this.store.get(t.workflowId);if(!r)return{ok:!1,error:`workflow "${t.workflowId}" is gone`};let o,s="";return await this.commit(e.runId,()=>{let i=this.runs.get(e.runId),a=i?.pausedAt;if(!i||i.status!=="paused"||a?.kind!=="agentStop"){o=`workflow run ${e.runId} is not paused by a stop (it is ${i?.status??"gone"}${a?`, on ${a.kind} ${a.nodeId}`:""})`;return}if(a.agentId!==e.agentId||e.taskId&&a.taskId&&a.taskId!==e.taskId){o=`workflow run ${e.runId} is paused at step "${a.nodeId}" of ${a.agentId}, not at this task`;return}s=a.nodeId;let d=new Date().toISOString();this.runs.recordExecution({runId:i.id,entry:{at:d,nodeId:s,inputKeys:[],status:"resumed",output:{resumeNote:e.note},idempotencyKey:I(i.id,s,`signal-resumed:${e.taskId??d}`),note:`resumed by ${e.by}`.slice(0,200)},nextPending:[s,...i.pending.filter(u=>u!==s)],status:"running",pausedAt:null}),this.emitRunEvent({runId:i.id,workflowId:r.id,nodeId:s,phase:"resumed",status:"running",note:`signal:resume by ${e.by}`,rootId:i.eventRootId})}),o?{ok:!1,error:o}:(this.log(`[workflow:${r.id}] run ${e.runId} resumed at step "${s}" by ${e.by}`),this.walk(r,e.runId,`signal-resume:${e.taskId??Date.now()}`).catch(i=>this.log(`[workflow:${r.id}] walk after resume failed: ${i.message}`)),{ok:!0,nodeId:s})}async cancelRun(e,t="canceled by the owner"){let r=!1;return await this.commit(e,()=>{let o=this.runs.get(e);if(!o||gt.has(o.status))return;let s=o.pausedAt?.nodeId??o.pending[0]??"run";this.timers.cancel({runId:e}),this.runs.recordExecution({runId:e,entry:{at:new Date().toISOString(),nodeId:s,inputKeys:[],status:"skipped",idempotencyKey:I(e,s,`cancel:${Date.now()}`),note:t.slice(0,200)},nextPending:[],status:"canceled",pausedAt:null}),r=!0}),r&&await this.settle(e),r}resumeOn(e,t,r,o,s,i,a){let d=P(e,r),{nextPending:u}=d?Ie({workflow:e,fromNodeId:r,selectedPort:s}):{nextPending:[]},c=d?ye[d.type]:void 0,p=!!c&&s!==void 0&&s!==c.main&&u.length===0,f=[...t.pending.filter(g=>g!==r),...u];return this.runs.recordExecution({runId:t.id,entry:{at:new Date().toISOString(),nodeId:r,inputKeys:[],status:p?"failed":"resumed",output:s?{...o,port:s}:o,idempotencyKey:i,note:p?`stopped: ${a}`:a},nextPending:p?[]:f,status:p?"failed":"running",pausedAt:null,context:{...t.context,[r]:s?{...o,port:s}:o}}),this.emitRunEvent({runId:t.id,workflowId:e.id,nodeId:r,phase:p?"failed":"resumed",status:p?"failed":"running",note:a,rootId:t.eventRootId}),!p}async followUpTimer(e,t){let r={};if(await this.commit(t.runId,()=>{let i=this.runs.get(t.runId),a=i?.pausedAt;if(!i||i.status!=="paused"||!a||a.nodeId!==t.nodeId)return;let d=Date.now(),u=new Date(d).toISOString();if(a.kind==="replyWait"){if(d>=Date.parse(a.deadline)){r.walk=this.resumeOn(e,i,a.nodeId,{timedOut:!0,reminders:a.reminders,deadline:a.deadline},"timeout",I(i.id,a.nodeId,`deadline:${a.deadline}`),"no reply before the deadline");return}if(!a.nextRemindAt||d<Date.parse(a.nextRemindAt)||a.reminders>=a.maxReminders){this.scheduleWake(i.id,e.id,a);return}let c=a.reminders+1,p={...a,reminders:c,...c<a.maxReminders&&a.remindEveryMs?{nextRemindAt:new Date(d+a.remindEveryMs).toISOString()}:{nextRemindAt:void 0}},f=a.reminds?i.context[a.reminds]:void 0,g=f&&typeof f.text=="string"&&f.text?{to:"person",msg:{channel:a.channel,chatId:a.chatId,...a.accountId?{accountId:a.accountId}:{},text:`Reminder: ${f.text}`}}:{to:"owner",text:`Still waiting for a reply on ${a.channel} (${a.chatId}) for step "${a.nodeId}" of ${i.meta?.title?`"${i.meta.title}"`:`workflow ${e.id}`}. Deadline: ${a.deadline.slice(0,16).replace("T"," ")} UTC.`};this.runs.recordExecution({runId:i.id,entry:{at:u,nodeId:a.nodeId,inputKeys:[],status:"paused",idempotencyKey:I(i.id,a.nodeId,`remind:${c}`),note:`reminder ${c}/${a.maxReminders} to ${g.to}`},nextPending:i.pending,status:"paused",pausedAt:p}),this.scheduleWake(i.id,e.id,p),r.reminder=g;return}if(a.kind==="agentStep"){if(a.blocked||!a.nextNudgeAt)return;if(d<Date.parse(a.nextNudgeAt)){this.scheduleWake(i.id,e.id,a);return}if(a.nudges>=a.maxNudges){this.blockStep(e,i,a,a.maxNudges?`no progress after ${a.maxNudges} reminder(s) to ${a.agentId}`:`no progress from ${a.agentId} for ${Math.round(a.stallMs/6e4)} minute(s)`);return}let c=a.nudges+1,p={...a,nudges:c,nextNudgeAt:new Date(d+a.stallMs).toISOString()};this.runs.recordExecution({runId:i.id,entry:{at:u,nodeId:a.nodeId,inputKeys:[],status:"paused",idempotencyKey:I(i.id,a.nodeId,`nudge:${c}`),note:`nudge ${c}/${a.maxNudges} to ${a.agentId}`},nextPending:i.pending,status:"paused",pausedAt:p}),this.scheduleWake(i.id,e.id,p),r.nudge={agentId:a.agentId,text:Gn(i,a.nodeId,c,a.maxNudges,a.stallMs*c)},this.log(`[workflow:${e.id}] run ${i.id}: nudge ${c}/${a.maxNudges} to ${a.agentId} on step "${a.nodeId}"`)}}),r.walk){this.walk(e,t.runId,`timer:${t.id}`).catch(i=>this.log(`[workflow:${e.id}] walk after deadline failed: ${i.message}`));return}await this.settle(t.runId);let o=r.reminder;if(o?.to==="person"){let i=await Pe({channels:this.channels,forwardChannelSend:this.forwarder?.forwardChannelSend?.bind(this.forwarder)},o.msg);"error"in i&&this.log(`[workflow:${e.id}] run ${t.runId}: reminder not sent: ${i.error}`)}else if(o?.to==="owner"){let i=this.runs.get(t.runId);i&&await this.owner?.notify(o.text,i).catch(a=>this.log(`[workflow:${e.id}] run ${t.runId}: reminder to the owner failed: ${a?.message??a}`))}let s=r.nudge;s&&this.agents.execute({agentId:s.agentId,message:s.text,workflowRunId:t.runId}).then(async i=>{if(i.error){this.log(`[workflow:${e.id}] run ${t.runId}: nudge turn on ${s.agentId} failed: ${i.error}`);return}let a=We(i.content).result,d=at(a);d==="blocked"?await this.stepDone({runId:t.runId,nodeId:t.nodeId,blocked:Fs(i.content)||`${s.agentId} says the step is ${a}`}):d==="done"&&await this.stepDone({runId:t.runId,nodeId:t.nodeId,output:{reply:i.content,result:a,via:"nudge"}})}).catch(i=>this.log(`[workflow:${e.id}] run ${t.runId}: nudge turn failed: ${i?.message??i}`))}blockStep(e,t,r,o){let s={...r,blocked:o.slice(0,300),nextNudgeAt:void 0};this.timers.cancel({cancelKey:`${t.id}:${r.nodeId}`}),this.runs.recordExecution({runId:t.id,entry:{at:new Date().toISOString(),nodeId:r.nodeId,inputKeys:[],status:"paused",idempotencyKey:I(t.id,r.nodeId,`blocked:${Date.now()}`),note:`blocked: ${o}`.slice(0,200)},nextPending:t.pending,status:"paused",pausedAt:s}),this.markBlocked(t.id,e,r.nodeId,o)}markBlocked(e,t,r,o){let s=this.runs.setMeta(e,{blocked:{nodeId:r,reason:o.slice(0,300),at:new Date().toISOString()}});this.log(`[workflow:${t.id}] run ${e} blocked on "${r}": ${o}`),!(!s||!this.onBlocked)&&Promise.resolve(this.onBlocked(s,t,r,o)).catch(i=>this.log(`[workflow:${t.id}] blocked notice failed: ${i?.message??i}`))}noteReplyWaiter(e,t){this.replyWaiters&&(this.replyWaiters.has(t)||this.replyWaiters.set(t,new Set),this.replyWaiters.get(t).add(e))}scheduleWake(e,t,r){r.kind==="replyWait"&&this.noteReplyWaiter(e,r.channel);let o=zn(r);if(o)try{this.timers.cancel({cancelKey:`${e}:${r.nodeId}`}),this.timers.schedule({runId:e,workflowId:t,nodeId:r.nodeId,fireAt:o,cancelKey:`${e}:${r.nodeId}`})}catch(s){this.log(`[workflow:${t}] timer schedule failed: ${s.message}`)}}async settle(e){let t=this.runs.get(e);if(t?.meta?.followUp&&(t.status==="running"&&t.pending.length===0&&(t=this.runs.setStatus(e,"completed")??t),!(!gt.has(t.status)||t.meta?.endNotifiedAt)&&(t=this.runs.setMeta(e,{endNotifiedAt:new Date().toISOString()})??t,this.timers.cancel({runId:e}),this.emitRunEvent({runId:e,workflowId:t.workflowId,phase:"ended",status:t.status,rootId:t.eventRootId}),!!this.onRunEnded)))try{await this.onRunEnded(t,this.store.get(t.workflowId))}catch(r){this.log(`[workflow:${t.workflowId}] end notice for ${e} failed: ${r?.message??r}`)}}async spawnChild(e){let t=this.store.list().find(a=>a.id===e.childWorkflowId);if(!t)return null;let r=ae(t);if(!r)return this.log(`[workflow:${t.id}] no trigger node \u2014 cannot spawn as child`),null;let o={...e.input};o[r.triggerId]={...o[r.triggerId]??{},parentRunId:e.parent.id,parentNodeId:e.parentNodeId};let s={backend:"agentx-internal",id:`subprocess:${e.parent.id}:${e.parentNodeId}`},i=this.runs.create({workflowId:t.id,initialPending:r.pending,entityRef:s,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 ${i.id} spawned from ${e.parent.id}/${e.parentNodeId} (depth ${i.depth})`),i}kickChildWalk(e){let t=this.store.list().find(r=>r.id===e.workflowId);t&&this.walk(t,e.id,`spawn:${e.parentRunId}:${e.parentNodeId}`).catch(r=>this.log(`[workflow:${t.id}] child walk failed: ${r.message}`))}async resumeParent(e){let t=this.runs.get(e.parentRunId);if(!t)return;let r=this.store.list().find(o=>o.id===t.workflowId);r&&(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 s=P(r,e.parentNodeId),i=s?r.edges.filter(d=>d.from===s.id).map(d=>d.to):[],a={childRunId:e.childRun.id,status:e.childRun.status,output:js(e.childRun)};this.runs.recordExecution({runId:o.id,entry:{at:new Date().toISOString(),nodeId:e.parentNodeId,inputKeys:[],status:"resumed",output:a,idempotencyKey:I(o.id,e.parentNodeId,`child:${e.childRun.id}`)},nextPending:i,status:"running",pausedAt:null,context:{...o.context,[e.parentNodeId]:a}}),this.log(`[workflow:${r.id}] parent run ${o.id} resumed from subProcess child ${e.childRun.id}`),this.emitRunEvent({runId:o.id,workflowId:r.id,nodeId:e.parentNodeId,phase:"resumed",status:"running",note:`child:${e.childRun.id}`,rootId:o.eventRootId})}),this.walk(r,e.parentRunId,`child:${e.childRun.id}`))}};function js(n){for(let e=n.history.length-1;e>=0;e--){let t=n.history[e];if(t.status==="ok"&&t.output&&Object.keys(t.output).length>0)return t.output}return{}}function Cs(n,e,t){let r=s=>{let i=n[s];if(i===void 0||i===""||i==="*")return!0;if(Array.isArray(i)){let a=new Set(e.labels??[]);return i.some(d=>a.has(String(d)))}return s==="chat"?H(e.source,String(i))===H(e.source,e.chat):e[s]===i};if(!r("source")||!r("project")||!r("repo")||!r("chat"))return!1;let o=n.eventIdLike;return!(typeof o=="string"&&o&&!t.id.includes(o))}function H(n,e){return e==null?"":n==="whatsapp-message"?e.replace(/@s\.whatsapp\.net$|@g\.us$/i,"").replace(/[\s+()]/g,""):e}function Fs(n){return n?(n.split(`
|
|
31
|
+
`).map(t=>t.trim()).filter(t=>t&&!/^RESULT:/i.test(t)).at(-1)??"").slice(0,300):""}function _s(n){return{"pre:channel-message":async e=>{let t=e.msg;if(!t)return{};let r=t.group?.id??t.sender.id,o=await n.resumeFromReply({channel:t.channel,chatId:r,accountId:t.accountId,senderId:t.sender.id,senderName:t.sender.name,text:t.text,media:t.media,messageId:t.id});if(o)return{blocked:!0,message:`reply taken by workflow run ${o}`};let s=Ls(t.channel);if(!s)return{};let i={backend:t.channel,id:`${t.channel}:${r}`},{claimed:a}=await n.dispatch({trigger:{source:s,chat:r},entityRef:i,event:{id:`${t.channel}:${t.accountId}:${t.id}`,payload:Us(t)}});return a.length===0?{}:a.every(u=>u.nodes.find(p=>p.type.startsWith("trigger."))?.config?.passthrough===!0)?{}:{blocked:!0,message:`handled by workflow${a.length>1?"s":""}: ${a.map(u=>u.id).join(", ")}`}},"on:gitlab-issue":async e=>{let t=e.project,r=e.iid,o=e.issueEvent;if(!t||r===void 0)return{};let s=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)??[],i=o?.assignees??o?.object_attributes?.assignee_ids??[],a={backend:"gitlab",id:`${t}#${r}`};return await n.dispatch({trigger:{source:"gitlab-issue",project:t,labels:s},entityRef:a,event:{id:`gitlab-issue:${t}:${r}:${o?.object_attributes?.updated_at||o?.object_attributes?.action||"evt"}`,payload:{issue:{iid:r,title:o?.object_attributes?.title,description:o?.object_attributes?.description,url:o?.object_attributes?.url,action:o?.object_attributes?.action,labels:s,assignees:i},project:t,channel:"gitlab",chatId:`${t}:issue:${r}`}}}),{}},"on:gitlab-mr":async e=>{let t=e.project,r=e.iid,o=e.mrEvent;if(!t||r===void 0)return{};let s=Array.isArray(e.labels)?e.labels:Array.isArray(o?.object_attributes?.labels)?o.object_attributes.labels.map(u=>typeof u=="string"?u:u?.title).filter(Boolean):[],i=o?.assignees??o?.object_attributes?.assignee_ids??[],a=o?.reviewers??[],d={backend:"gitlab",id:`${t}!${r}`};return await n.dispatch({trigger:{source:"gitlab-mr",project:t,labels:s},entityRef:d,event:{id:`gitlab-mr:${t}:${r}:${o?.object_attributes?.updated_at||o?.object_attributes?.action||"evt"}`,payload:{mr:{iid:r,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:s,assignees:i,reviewers:a},project:t,channel:"gitlab",chatId:`${t}:merge_request:${r}`,iid:r,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:s}}}),{}},"on:gitlab-note":async e=>{let t=e.project,r=e.noteId,o=e.noteableType,s=e.noteableIid,i=e.text,a=e.authorUsername,d=e.mentions??[];if(!t||!r||!o||!s)return{};let u=o==="merge_request"?{backend:"gitlab",id:`${t}!${s}`}:{backend:"gitlab",id:`${t}#${s}`};return await n.dispatch({trigger:{source:"gitlab-note",project:t},entityRef:u,event:{id:`gitlab-note:${t}:${o}:${s}:${r}`,payload:{note:{id:r,text:i,author:a,mentions:d,noteableType:o,noteableIid:s,noteableTitle:e.noteableTitle},project:t,channel:"gitlab",chatId:`${t}:${o}:${s}`,noteId:r,noteableType:o,noteableIid:s,text:i,author:a,mentions:d}}}),{}},"on:gitlab-pipeline":async e=>{let t=e.project,r=e.pipelineId,o=e.status,s=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 n.dispatch({trigger:{source:"gitlab-pipeline",project:t},entityRef:d,event:{id:`gitlab-pipeline:${t}:${r}:${o}`,payload:{pipeline:{id:r,status:o,ref:s},project:t,channel:"gitlab",chatId:`${t}:merge_request:${a}`}}}),{}}}}function Ls(n){switch(n){case"telegram":return"telegram-message";case"whatsapp":return"whatsapp-message";case"discord":return"discord-message";case"slack":return"slack-message";default:return null}}function Us(n){let e=n.group?.id??n.sender.id;return{channel:n.channel,chatId:e,accountId:n.accountId,text:n.text,fromJid:n.sender.id,sender:{id:n.sender.id,name:n.sender.name,username:n.sender.username},contact:n.channelMeta?.facts?{facts:n.channelMeta.facts}:void 0,group:n.group?{id:n.group.id,name:n.group.name}:void 0,channelMeta:n.channelMeta,replyTo:n.replyTo,replyToText:n.replyToText,media:n.media,event:{id:n.id,timestamp:n.timestamp?.toISOString?.()??new Date().toISOString()}}}var Ne=n=>n.trim().toLowerCase().replace(/^@/,"");function Hs(n){let e=typeof n.author=="string"?n.author:typeof n.authorUsername=="string"?n.authorUsername:void 0;if(e)return Ne(e);let r=n.payload?.sender?.login;return typeof r=="string"&&r?Ne(r):void 0}function Bs(n,e){let t=typeof e.project=="string"?e.project:"";if(n==="on:gitlab-issue"||n==="on:gitlab-mr")return!t||e.iid==null?void 0:`gitlab:${t}${n==="on:gitlab-issue"?"#":"!"}${String(e.iid)}`;if(n==="on:gitlab-note"){let r=e.noteableIid!=null?String(e.noteableIid):"",o=typeof e.noteableType=="string"?e.noteableType:"";return!t||!r||!o?void 0:`gitlab:${t}${o==="issue"?"#":"!"}${r}`}if(n==="on:github-issue"||n==="on:github-pr"){let r=e.payload??{},o=typeof e.repo=="string"?e.repo:r.repository?.full_name,s=e.number??r.issue?.number??r.pull_request?.number;return typeof o!="string"||!o||s==null?void 0:`github:${o}#${String(s)}`}}function Ks(n){let e=new Set;for(let t of n.nodes){let r=t.type==="agent"?t.config.agentId:void 0;typeof r=="string"&&r&&e.add(r)}return[...e]}var Oe=class{constructor(e=2e3){this.maxKeys=e}fires=new Map;tryFire(e,t,r,o=Date.now()){let s=(this.fires.get(e)??[]).filter(i=>o-i<r);if(s.length>=t)return this.fires.set(e,s),!1;for(s.push(o),this.fires.delete(e),this.fires.set(e,s);this.fires.size>this.maxKeys;){let i=this.fires.keys().next().value;if(i===void 0)break;this.fires.delete(i)}return!0}get size(){return this.fires.size}};function ht(n,e,t){let r=n.logged??(n.logged=new Set);r.has(e)||(r.add(e),n.log(t))}function Qn(n,e,t,r,o){let s=Hs(t);if(s&&Array.isArray(r?.ignoreAuthors)&&r.ignoreAuthors.length>0&&r.ignoreAuthors.map(Ne).includes(s))return{skip:!0,reason:"ignored-author",detail:`author @${s} is in filter.ignoreAuthors`};if(r?.skipSelfAuthored===!0){let a=Ks(n),d=typeof t.authorAgent=="string"?t.authorAgent:void 0;if(d&&a.includes(d))return{skip:!0,reason:"self-authored",detail:`author @${s??"?"} is agent "${d}" which this workflow runs`};if(s){let u=new Set(a.flatMap(c=>(o.forgeUsernames?.(c)??[]).map(Ne)));if(u.has(s))return{skip:!0,reason:"self-authored",detail:`author @${s} is this workflow's own bot identity`};a.length===0?ht(o,`noagents:${n.id}`,`[workflows] ${n.id} has no agent node \u2014 self-authored skip can't resolve a bot identity; only filter.ignoreAuthors applies`):u.size===0&&!("authorAgent"in t)&&ht(o,`noident:${n.id}:${e}`,`[workflows] ${n.id} no forge username known for agent(s) ${a.join(", ")} on ${e} \u2014 self-authored skip inactive; only filter.ignoreAuthors applies`)}}let i=r?.maxFiresPerTarget;if(i&&typeof i.count=="number"&&i.count>0){let a=Bs(e,t);if(a){let d=typeof i.windowMinutes=="number"&&i.windowMinutes>0?i.windowMinutes:60,u=o.now?.()??Date.now();if(!o.fireWindow.tryFire(`${n.id}|${a}`,i.count,d*6e4,u))return{skip:!0,reason:"chain-limit",detail:`${a} already fired ${i.count}x within ${d}m (filter.maxFiresPerTarget)`}}else ht(o,`notarget:${n.id}:${e}`,`[workflows] ${n.id} filter.maxFiresPerTarget has no target key for ${e} \u2014 limit not applied`)}return{skip:!1}}function qs(n){let e=n.store.list(),t={fireWindow:new Oe,log:n.log,forgeUsernames:n.forgeUsernames,logged:new Set},r=0,o=0;for(let s of e){if(s.state&&s.state!=="active"){n.log(`[workflows] ${s.id} state=${s.state} \u2014 skipping trigger registration`);continue}let i=s.nodes.find(a=>a.type.startsWith("trigger."));if(i){if(i.type==="trigger.cron"){let a=i.config;if(!a.spec){n.log(`[workflows] ${s.id} trigger.cron missing config.spec \u2014 skipping`);continue}zs({workflowId:s.id,triggerNodeId:i.id,spec:a.spec,timezone:a.timezone??"UTC"},n.dispatcher,n.log),r++}else if(i.type==="trigger.hook"){let a=i.config;if(!a.event||!a.event.startsWith("on:")){n.log(`[workflows] ${s.id} trigger.hook config.event must start with "on:" \u2014 skipping`);continue}n.hooks.registerHandler(a.event,`workflows:${s.id}`,async d=>{try{let u=typeof d.project=="string"?d.project:void 0;if(s.project&&u&&s.project!==u)return{};if(a.filter){if(Array.isArray(a.filter.topic)&&a.filter.topic.length>0){let m=typeof d.topic=="string"?d.topic.toLowerCase():void 0;if(!m||!a.filter.topic.map(y=>y.toLowerCase()).includes(m))return{}}if(Array.isArray(a.filter.action)&&a.filter.action.length>0){let m=typeof d.action=="string"?d.action:void 0;if(!m||!a.filter.action.includes(m))return{}}if(Array.isArray(a.filter.mentions)&&a.filter.mentions.length>0){let m=Array.isArray(d.mentions)?d.mentions.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.mentions.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>m.includes(w)))return{}}if(Array.isArray(a.filter.noteableType)&&a.filter.noteableType.length>0){let m=typeof d.noteableType=="string"?d.noteableType.toLowerCase():void 0,y=a.filter.noteableType.map(b=>b.toLowerCase());if(!m||!y.includes(m))return{}}if(Array.isArray(a.filter.assigneesAdded)&&a.filter.assigneesAdded.length>0){let m=Array.isArray(d.assigneesAdded)?d.assigneesAdded.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.assigneesAdded.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>m.includes(w)))return{}}if(Array.isArray(a.filter.reviewersAdded)&&a.filter.reviewersAdded.length>0){let m=Array.isArray(d.reviewersAdded)?d.reviewersAdded.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.reviewersAdded.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>m.includes(w)))return{}}if(Array.isArray(a.filter.labelsAdded)&&a.filter.labelsAdded.length>0){let m=Array.isArray(d.labelsAdded)?d.labelsAdded.map(w=>w.toLowerCase()):[];if(!a.filter.labelsAdded.map(w=>w.toLowerCase()).some(w=>m.includes(w)))return{}}}let c=Qn(s,a.event,d,a.filter,t);if(c.skip){if(n.log(`[workflows] ${s.id} skipping ${a.event} (${c.reason}): ${c.detail}`),a.passthrough)return{};let m=d.__workflowClaimed;return{modified:{__workflowClaimed:[...Array.isArray(m)?m:[],s.id]}}}let p=Gs(s.id,a.event,d);if(await n.dispatcher.dispatchWorkflow({workflowId:s.id,entityRef:{backend:"hook",id:p},event:{id:`hook:${a.event}:${Date.now().toString(36)}`,payload:{hookEvent:a.event,...d}}}),a.passthrough)return{};let f=d.__workflowClaimed;return{modified:{__workflowClaimed:[...Array.isArray(f)?f:[],s.id]}}}catch(u){return n.log(`[workflows] ${s.id} hook dispatch failed: ${u.message}`),{}}},60),o++}}}return{cronTimers:r,hookSubscribers:o}}function Gs(n,e,t){let r=typeof t.project=="string"?t.project:"",o=t.iid!=null?String(t.iid):"";if(e==="on:gitlab-issue"&&r&&o)return`${n}:${e}:${r}#${o}`;if(e==="on:gitlab-mr"&&r&&o)return`${n}:${e}:${r}!${o}`;if(e==="on:gitlab-pipeline"&&r){let s=t.pipelineId!=null?String(t.pipelineId):"";if(s)return`${n}:${e}:${r}@pipeline:${s}`}return`${n}:${e}:${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function zs(n,e,t){let r=()=>{let o;try{o=zt(n.spec,new Date,n.timezone)}catch(i){t(`[workflows] ${n.workflowId} cron spec invalid: ${i.message}`);return}let s=Math.max(1e3,o.getTime()-Date.now());setTimeout(()=>{(async()=>{let i=`cron:${n.workflowId}:${o.toISOString()}`;try{await e.dispatchWorkflow({workflowId:n.workflowId,trigger:{source:"cron"},entityRef:{backend:"cron",id:`${n.workflowId}@${o.toISOString()}`},event:{id:i,payload:{now:o.toISOString(),spec:n.spec,workflowId:n.workflowId}}})}catch(a){t(`[workflows] ${n.workflowId} cron dispatch failed: ${a.message}`)}finally{r()}})()},s)};r()}import{createHash as Js}from"crypto";import{existsSync as Ys,mkdirSync as Vs,readFileSync as Qs,renameSync as Zs,writeFileSync as Xs}from"fs";import{resolve as Zn}from"path";import{z as X}from"zod";var Xn=X.object({actionId:X.string().min(1),everySeconds:X.number().int().min(5).max(86400).default(60),key:X.string().min(1).default("id"),filter:X.array(ze).default([]),maxPerPoll:X.number().int().min(1).max(500).default(20)}),ei=5e3,ti=30;async function ni(n){let e=new Lt().get(n);if(!e)throw new Error(`no action "${n}" in registry`);return Ut(e)}function er(n,e){let t=[],r=0;for(let o of n.split(`
|
|
32
|
+
`)){let s=o.trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{r++;continue}if(!i||typeof i!="object"||Array.isArray(i)){r++;continue}let a=Q(i,e);if((typeof a!="string"||!a)&&typeof a!="number"){r++;continue}t.push({key:String(a),value:i})}return{items:t,skipped:r}}function ri(n,e){let t=`${n}:${e}`;return/^[a-zA-Z0-9._:@-]+$/.test(e)&&t.length<=200?t:`${n}:#${Js("sha256").update(e).digest("hex").slice(0,32)}`}var wt=class{constructor(e){this.opts=e;this.stateDir=Zn(e.store.baseDir,"_poll"),this.runAction=e.runAction??ni}timers=new Map;warned=new Map;stateDir;runAction;resync;start(){return this.resync??=setInterval(()=>{try{this.sync()}catch(e){this.opts.log(`[workflows] poll sync failed: ${e.message}`)}},ti*1e3),this.sync()}sync(){let e=new Map;for(let t of this.opts.store.list()){let r=this.configOf(t);r&&e.set(t.id,r)}for(let[t,r]of this.timers)e.has(t)||(clearTimeout(r),this.timers.delete(t),this.opts.log(`[workflows] ${t} poll stopped`));for(let[t,r]of e)this.timers.has(t)||(this.schedule(t,r.everySeconds),this.opts.log(`[workflows] ${t} polls action "${r.actionId}" every ${r.everySeconds}s`));return this.timers.size}stop(){this.resync&&clearInterval(this.resync),this.resync=void 0;for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}async pollOnce(e){let t=this.opts.store.get(e),r=t?this.configOf(t):null;if(!r)return 0;let o;try{o=await this.runAction(r.actionId)}catch(f){return this.warnOnce(e,`poll failed: ${f.message}`),0}if(!o.ok)return this.warnOnce(e,`poll failed (status=${o.status??"?"}): ${(o.errors??"").slice(0,200)}`),0;let{items:s,skipped:i}=er(o.output,r.key);this.warnOnce(e,i>0?`poll skipped ${i} line(s) that are not a JSON object with "${r.key}"`:"");let a=new Set(s.map(f=>f.key)),d=this.readState(e);if(!d||d.actionId!==r.actionId||d.key!==r.key)return this.writeState(e,{actionId:r.actionId,key:r.key,seen:[...a]},a),this.opts.log(`[workflows] ${e} poll baseline: ${a.size} existing item(s) recorded, no runs started`),0;let u=new Set(d.seen),c=0,p=!1;for(let f of s){if(u.has(f.key))continue;let g=r.filter.every(m=>$e(m,f.value));if(!(g&&c>=r.maxPerPoll)){if(u.add(f.key),d.seen.push(f.key),!g){p=!0;continue}this.writeState(e,d,a),p=!1;try{let{run:m}=await this.opts.dispatcher.dispatchWorkflow({workflowId:e,trigger:{source:"poll"},entityRef:{backend:"poll",id:ri(e,f.key)},event:{id:`poll:${e}:${f.key}`,payload:f.value}});m?c++:this.opts.log(`[workflows] ${e} poll item "${f.key}" started no run`)}catch(m){this.opts.log(`[workflows] ${e} poll dispatch failed for "${f.key}": ${m.message}`)}}}return p&&this.writeState(e,d,a),c}schedule(e,t){let r=setTimeout(()=>{(async()=>{try{await this.pollOnce(e)}catch(i){this.opts.log(`[workflows] ${e} poll failed: ${i.message}`)}if(this.timers.get(e)!==r)return;let o=this.opts.store.get(e),s=o?this.configOf(o):null;s?this.schedule(e,s.everySeconds):this.timers.delete(e)})()},t*1e3);this.timers.set(e,r)}configOf(e){if(e.state&&e.state!=="active")return null;let t=e.nodes.find(o=>o.type.startsWith("trigger."));if(!t||t.type!=="trigger.poll")return null;let r=Xn.safeParse(t.config);if(!r.success){let o=r.error.issues.map(s=>`${s.path.join(".")||"config"}: ${s.message}`).join("; ");return this.warnOnce(e.id,`trigger.poll config invalid, not polling (${o})`),null}return r.data}warnOnce(e,t){this.warned.get(e)!==t&&(this.warned.set(e,t),t&&this.opts.log(`[workflows] ${e} ${t}`))}statePath(e){return Zn(this.stateDir,`${e}.json`)}readState(e){let t=this.statePath(e);if(!Ys(t))return null;try{let r=JSON.parse(Qs(t,"utf-8"));return typeof r.actionId!="string"||typeof r.key!="string"||!Array.isArray(r.seen)?null:{actionId:r.actionId,key:r.key,seen:r.seen.map(String)}}catch{return null}}writeState(e,t,r){let o=t.seen.length-ei;o>0&&(t.seen=t.seen.filter(i=>r.has(i)||o--<=0)),Vs(this.stateDir,{recursive:!0});let s=this.statePath(e);Xs(`${s}.tmp`,JSON.stringify(t)),Zs(`${s}.tmp`,s)}};function tr(n){return n.nodes.find(r=>r.type.startsWith("trigger."))?.config?.inputSchema??null}function nr(n,e){if(!n||!e?.properties)return{};let t=n.match(/^([^:]+\/[^:]+):([^:]+):(.+)$/);if(!t)return{};let[,r,o,s]=t,i={};if(e.properties.project&&(i.project=r),o==="push"){let a=s.match(/^refs\/heads\/(.+)$/);a&&e.properties.ref&&(i.ref=a[1])}else{let a=Number(s);Number.isFinite(a)&&(e.properties.id&&(i.id=a),e.properties.iid&&(i.iid=a),e.properties.mrId&&(i.mrId=a),e.properties.issueId&&(i.issueId=a),e.properties.prId&&(i.prId=a))}return i}function rr(n,e){if(!n?.properties)return e;let t={...e};for(let[r,o]of Object.entries(n.properties))t[r]===void 0&&o&&"default"in o&&(t[r]=o.default);return t}function or(n,e){return!n?.required||!Array.isArray(n.required)?[]:n.required.filter(t=>{let r=e[t];return r===void 0||r===""||r===null})}function si(n,e){let t=tr(n);if(!t?.properties){let d={};for(let[u,c]of Object.entries(e))c!==void 0&&(d[u]=c);return{inputs:d,missing:[],filledFrom:{passthrough:Object.keys(d),chatId:[],defaults:[]}}}let r={};for(let d of["message","agentId","channel","chatId","senderId","senderUsername"])t.properties[d]&&e[d]!==void 0&&(r[d]=e[d]);let o=nr(e.chatId,t),s={...r,...o},i={...s};s=rr(t,s);let a=Object.keys(s).filter(d=>i[d]===void 0&&s[d]!==void 0);return{inputs:s,missing:or(t,s),filledFrom:{passthrough:Object.keys(r),chatId:Object.keys(o),defaults:a}}}var sr=new Set(["agent","owner.notify","owner.ask","person.message","person.wait","branch","transform","timer.boundary","end"]);function Tu(n){return[`[Saved workflow] This request looks like the saved workflow "${n.title}" (${n.id}).`,`If it is, start it with agentx_workflow {action:"start", workflowId:"${n.id}", title:"<the request in a few words>", tags:["client:<name>"]} instead of doing the steps by hand: AgentX then follows each step, reminds whoever is slow and tells the owner when it is done.`,n.autoStart?"It is marked to start without asking.":"AgentX tells the owner which workflow you chose when you start it."].join(" ")}function Nu(n){if(!Array.isArray(n.steps)||n.steps.length===0)return{ok:!1,error:"steps must be a non-empty list of {id, type, config}"};if(n.steps.length>40)return{ok:!1,error:"a workflow has at most 40 steps"};let e=[{id:"start",type:"trigger.manual",config:{}}];for(let[i,a]of n.steps.entries()){let d=typeof a?.id=="string"&&a.id?a.id:`step${i+1}`,u=typeof a?.type=="string"?a.type:"";if(!sr.has(u))return{ok:!1,error:`step "${d}": type "${u}" is not one an agent may use (${[...sr].join(", ")})`};if(d==="start"||e.some(c=>c.id===d))return{ok:!1,error:`step id "${d}" is used twice (or is "start")`};e.push({id:d,type:u,config:a.config&&typeof a.config=="object"&&!Array.isArray(a.config)?a.config:{}})}let t=!e.some(i=>i.type==="end");t&&e.push({id:"done",type:"end",config:{}});let r=n.edges;if(r===void 0)r=e.slice(0,-1).flatMap((i,a)=>i.type==="end"?[]:[{from:i.id,to:e[a+1].id}]);else if(Array.isArray(r)){let i=r,a=t?e.slice(1,-1).filter(d=>d.type!=="end"&&!i.some(u=>u?.from===d.id)):[];r=[{from:"start",to:e[1].id},...i,...a.map(d=>({from:d.id,to:"done"}))]}let o=x.safeParse({id:n.id,title:n.title,...n.description?{description:n.description}:{},nodes:e,edges:r,tags:n.tags??[],...n.ownerAgent?{ownerAgent:n.ownerAgent}:{},...n.approval==="start"||n.approval==="step"?{approval:n.approval}:{},autoStart:n.autoStart===!0});if(!o.success)return{ok:!1,error:o.error.issues.map(i=>`${i.path.join(".")||"workflow"}: ${i.message}`).join("; ").slice(0,600)};let s=re(o.data);return s.length?{ok:!1,error:s.join("; ").slice(0,600)}:{ok:!0,workflow:o.data}}function Ou(n,e="wf"){let t=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);return`${e}-${t||"run"}-${Date.now().toString(36)}`}function Du(n){let e=Array.isArray(n)?n:typeof n=="string"?n.split(","):[],t=[];for(let r of e){if(typeof r!="string")continue;let o=r.trim().toLowerCase().replace(/\s+/g,"-").slice(0,60);o&&!t.includes(o)&&t.push(o)}return t.slice(0,10)}function ii(n){if(n?.kind!=="ownerDecision"||!n.message)return n;let{text:e,...t}=n.message;return{...n,message:{...t,text:""}}}var ir=300;function Mu(n){return{id:n.id,workflowId:n.workflowId,workflowVersion:n.workflowVersion,homeNode:n.homeNode,status:n.status,pending:n.pending,entityRef:n.entityRef,history:(n.history||[]).slice(-5).map(e=>({at:e.at,nodeId:e.nodeId,status:e.status,...e.note?{note:e.note.length>ir?e.note.slice(0,ir)+"\u2026":e.note}:{},...e.startedAt?{startedAt:e.startedAt}:{},...typeof e.durationMs=="number"?{durationMs:e.durationMs}:{}})),parentRunId:n.parentRunId,parentNodeId:n.parentNodeId,rootRunId:n.rootRunId,depth:n.depth,...n.meta?{meta:n.meta}:{},...n.pausedAt?{pausedAt:ii(n.pausedAt)}:{},createdAt:n.createdAt,updatedAt:n.updatedAt}}function ai(n){let e=n.pausedAt;if(n.status==="running")return n.pending.length?`running ${n.pending.join(", ")}`:"finishing";if(n.status!=="paused"||!e)return n.status;switch(e.kind){case"ownerDecision":return e.purpose==="start"?"your approval to start":e.purpose==="send"?`your approval to send to ${e.message?.to??e.message?.chatId??"a person"}`:"your answer";case"replyWait":return`a reply on ${e.channel} (${e.chatId}) until ${e.deadline.slice(0,16).replace("T"," ")} UTC${e.reminders?`, ${e.reminders} reminder(s) sent`:""}`;case"agentStep":return e.blocked?`blocked: ${e.blocked}`:`${e.agentId} to finish${e.nudges?` (${e.nudges}/${e.maxNudges} reminder(s) sent)`:""}`;case"agentStop":return`a resume signal: ${e.agentId} was paused at this step`;case"timerWait":return`a timer until ${e.fireAt.slice(0,16).replace("T"," ")} UTC`;case"signalWait":return`the signal "${e.signalName}"`;case"subProcess":return`the child workflow ${e.childWorkflowId}`;case"checkpoint":return`an event at checkpoint ${e.checkpointName}`}}function di(n){return n.pausedAt?.nodeId??n.pending[0]??n.history.at(-1)?.nodeId??"-"}function Eu(n,e){let t=n.meta?.title??e?.title??n.workflowId,r=n.status==="completed"?"done":n.status==="canceled"?"stopped":"did not finish",o=[],s=new Set;for(let a of n.history){if(a.status!=="ok"&&a.status!=="resumed"&&a.status!=="failed"||s.has(a.nodeId)&&a.status!=="failed")continue;s.add(a.nodeId);let d=a.output&&typeof a.output.evidence=="string"?` (${a.output.evidence})`:"";o.push(`${a.status==="failed"?"\u2717":"\u2713"} ${a.nodeId}${d}${a.status==="failed"&&a.note?`: ${a.note}`:""}`)}let i=n.history.at(-1);return{title:`Workflow ${r}: ${t}`.slice(0,120),message:[`"${t}" is ${r}${n.meta?.startedBy?` (started by ${n.meta.startedBy})`:""}.`,...n.meta?.tags?.length?[`About: ${n.meta.tags.join(", ")}`]:[],...o.slice(-12),...n.status!=="completed"&&i?.note?[`Why: ${i.note}`]:[],`Run ${n.id}`].join(`
|
|
33
|
+
`)}}function ju(n){let e=n.history.map(t=>t.output&&typeof t.output.evidence=="string"?t.output.evidence:null).filter(t=>!!t);return e.length?e.join(" "):`workflow run ${n.id} (${n.workflowId}) completed`}function Cu(n,e,t,r){let o=n.meta?.title??e?.title??n.workflowId;return{title:`Workflow blocked: ${o}`.slice(0,120),message:[`Step "${t}" of "${o}" cannot go on without you.`,`Why: ${r}`,`When it is sorted, the agent can report it done, or you can stop it: agentx workflow cancel ${n.id}`].join(`
|
|
34
|
+
`)}}function Fu(n,e=()=>{}){let t=n.filter(o=>o.meta?.followUp&&(o.status==="running"||o.status==="paused")&&!o.parentRunId).sort((o,s)=>o.createdAt.localeCompare(s.createdAt)),r=new Map;for(let o of t){let s={runId:o.id,workflowId:o.workflowId,title:o.meta?.title??e(o.workflowId)??o.workflowId,status:o.status,step:di(o),waitingOn:ai(o),since:o.updatedAt,...o.meta?.startedBy?{startedBy:o.meta.startedBy}:{},blocked:!!o.meta?.blocked,tags:o.meta?.tags??[]},i=s.tags.length?s.tags:["untagged"];for(let a of i)r.has(a)||r.set(a,[]),r.get(a).push(s)}return[...r.entries()].sort(([o],[s])=>o==="untagged"?1:s==="untagged"?-1:o.localeCompare(s)).map(([o,s])=>({tag:o,rows:s}))}var te={start:"start",reply:"reply",done:"done"},Uu={enabled:!1,agents:{},exemptQuestions:!0,retentionDays:30};function Hu(n,e){if(!n?.enabled)return!1;let t=n.required;return t?.agents?.[e]??t?.enabled??!1}function Bu(n){return!n.workflowRunId&&n.context?.channel!=="workflow"}function Ku(n){return[`[Workflow run ${n}] This task runs inside a workflow run (workflows.required).`,`If it takes more than one step, write your plan first: agentx_workflow {action:"plan", runId:"${n}", steps:["\u2026","\u2026"]}.`,`Report each step: {action:"step", runId:"${n}", step:"<id>", status:"started"|"done"|"failed", note}.`,"If the plan changes, call plan again with the steps left and a reason; steps done stay.","A one-step task needs none of this: your reply is the run's one step."].join(" ")}var qu="plan / step: when your task names a [Workflow run <id>], write your plan first (runId, steps: short titles) and report each step (runId, step, status started|done|failed, note); call plan again with the steps left and a reason to change it.",ui=new Set(["Read","Grep","Glob","LS","NotebookRead","WebSearch","WebFetch","TodoWrite","TodoRead","ToolSearch","ListMcpResourcesTool","ReadMcpResourceTool"]),ar=/^(get|list|search|read|query|find|show|status|describe|fetch|view|lookup|recall|whoami|check)(_|-|$|[A-Z])/,li=new Set(["list","match","status"]),dr=/^(set|update|delete|clear|create|add|remove|send|post|put|patch|write|run|start|stop|cancel|edit|move|rename|reset|save|upload|merge|close|open|approve|reject|assign|mark)$/;function Gu(n,e){if(ui.has(n))return!0;let t=n.startsWith("mcp__")?n.split("__").slice(2).join("__"):n;if(t==="agentx_workflow")return li.has(String(e?.action??"list").toLowerCase());let r=t.replace(/^agentx_/,""),o=r.split(/[_-]/);if(dr.test(o[0].toLowerCase()))return!1;let s=r.split(/[_-]|(?<=[a-z0-9])(?=[A-Z])/).map(i=>i.toLowerCase());return s.some((i,a)=>a>0&&(s[a-1]==="or"||s[a-1]==="and")&&dr.test(i))?!1:ar.test(r)||o.length>1&&ar.test(o.at(-1)??"")}function zu(n){if(!n||typeof n!="object"||n.type!=="assistant")return[];let e=n.message?.content;return Array.isArray(e)?e.filter(t=>t?.type==="tool_use"&&typeof t.name=="string"&&t.name).map(t=>({name:t.name,input:t.input&&typeof t.input=="object"?t.input:void 0})):[]}function Ju(n,e){let t=e.message.replace(/\s+/g," ").trim().slice(0,80)||`${e.agentId} task`;return n.create({id:e.runId,workflowId:U,initialPending:[te.reply],entityRef:{backend:"task",id:e.runId},initialContext:{[te.start]:{agentId:e.agentId,channel:e.channel,...e.chatId?{chatId:e.chatId}:{},preview:e.message.slice(0,200)}},meta:{title:t,tags:[`agent:${e.agentId}`],startedBy:e.agentId,followUp:!1,approvedAtStart:!1,wrap:{agentId:e.agentId,channel:e.channel,mode:"linear",...e.taskId?{taskId:e.taskId}:{}},...e.continues?{continues:e.continues}:{}}})}var ci=500;function Yu(n,e){if(!e)return null;try{return n.list({workflowId:U,limit:ci}).find(t=>t.meta?.wrap?.taskId===e)?.id??null}catch{return null}}function ue(n){return new Set(n.history.filter(e=>e.status==="ok"||e.status==="failed").map(e=>e.nodeId))}function pi(n){if(typeof n=="string")return n.trim();if(n&&typeof n=="object"){let e=n;for(let t of["title","name","step","id"])if(typeof e[t]=="string"&&e[t].trim())return e[t].trim()}return""}function Vu(n,e,t){let r=n.get(e);if(!r?.meta?.wrap)return{ok:!1,error:`no wrapped task run "${e}"`};if(r.status!=="running")return{ok:!1,error:`run ${e} is ${r.status}`};if(!Array.isArray(t.steps)||t.steps.length===0)return{ok:!1,error:"plan needs steps: a list of short step titles"};if(t.steps.length>30)return{ok:!1,error:"a plan has at most 30 steps"};let o=t.steps.map(pi);if(o.some(g=>!g))return{ok:!1,error:"every step needs a title"};let s=r.meta.plan,i=ue(r),a=(s?.steps??[]).filter(g=>i.has(g.id)),d=(s?.steps??[]).reduce((g,m)=>Math.max(g,Number(m.id.replace(/^step/,""))||0),0),u=o.map(g=>({id:`step${++d}`,title:g.slice(0,160)})),c=(s?.steps??[]).filter(g=>!i.has(g.id)).map(g=>g.id),p={steps:[...a,...u],revisions:[...s?.revisions??[],{at:new Date().toISOString(),kind:s?"revise":"plan",...t.reason?{reason:String(t.reason).slice(0,300)}:{},steps:u.map(g=>g.id),dropped:c}]},f=n.patch(e,{meta:{plan:p,wrap:{...r.meta.wrap,mode:"plan"}},pending:u.map(g=>g.id)});return f?{ok:!0,run:f}:{ok:!1,error:`run ${e} vanished`}}function fi(n,e){let t=e.trim();return n.steps.find(r=>r.id===t)??n.steps.find(r=>r.title.toLowerCase()===t.toLowerCase())??(/^\d+$/.test(t)?n.steps[Number(t)-1]:void 0)}function yt(n,e){let t=n.meta?.plan?.current;return t?.id===e?t.startedAt:n.history.at(-1)?.at??n.createdAt}function ee(n,e,t,r,o={}){let s=new Date().toISOString();return{at:s,nodeId:e,inputKeys:[],status:t,startedAt:r,durationMs:Math.max(0,Date.parse(s)-Date.parse(r)),idempotencyKey:I(n.id,e,`wrap:${t}:${n.history.length}`),...o}}function Qu(n,e,t){let r=n.get(e);if(!r?.meta?.wrap)return{ok:!1,error:`no wrapped task run "${e}"`};if(r.status!=="running")return{ok:!1,error:`run ${e} is ${r.status}`};let o=r.meta.plan;if(!o)return{ok:!1,error:'write a plan first: {action:"plan", runId, steps:[\u2026]}'};let s=String(t.status??"done").toLowerCase();if(!["started","done","failed"].includes(s))return{ok:!1,error:"status is started, done or failed"};let i=typeof t.step=="string"||typeof t.step=="number"?String(t.step):"",a=i?fi(o,i):o.steps.find(f=>!ue(r).has(f.id));if(!a)return{ok:!1,error:`no step "${i}" in the plan (${o.steps.map(f=>`${f.id} ${f.title}`).join("; ")})`};let d=typeof t.note=="string"&&t.note.trim()?t.note.trim().slice(0,300):void 0;if(s==="started"){let f=[a.id,...r.pending.filter(m=>m!==a.id)],g=n.patch(e,{meta:{plan:{...o,current:{id:a.id,startedAt:new Date().toISOString()}}},pending:f});return g?{ok:!0,run:g}:{ok:!1,error:`run ${e} vanished`}}let u=ee(r,a.id,s==="done"?"ok":"failed",yt(r,a.id),d?{note:d}:{}),c=n.recordExecution({runId:e,entry:u,nextPending:r.pending.filter(f=>f!==a.id)});if(!c)return{ok:!1,error:`run ${e} vanished`};let p=o.current?.id===a.id?n.patch(e,{meta:{plan:{...o,current:void 0}}}):c;return p?{ok:!0,run:p}:{ok:!1,error:`run ${e} vanished`}}function gi(n,e,t){let r=n.get(e);if(!r?.meta?.wrap)return null;if(r.status!=="running")return r;let o=r.meta.plan;if(!o&&!t.error&&t.readOnly&&t.exemptQuestions)return n.discard(e),"discarded";let s={turnMs:t.durationMs,...t.inputTokens!==void 0?{inputTokens:t.inputTokens}:{},...t.outputTokens!==void 0?{outputTokens:t.outputTokens}:{}},i=t.error?t.error.slice(0,300):void 0,a=r;if(i&&t.canceled){let d=ue(a),u=o?o.steps.filter(p=>!d.has(p.id)).map(p=>p.id):[te.reply],c=o?.current&&u.includes(o.current.id)?o.current.id:u[0];for(let p of u){let f=p===c?`stopped: ${i}`:"not reached: the turn was stopped",g=ee(a,p,"skipped",p===c?yt(a,p):a.history.at(-1)?.at??a.createdAt,{note:f,...p===c&&!o?{output:s}:{}});a=n.recordExecution({runId:e,entry:g,nextPending:[]})??a}return n.setStatus(e,"canceled")??a}if(o){let d=ue(a),u=o.steps.filter(c=>!d.has(c.id));if(i){let c=(o.current&&u.find(p=>p.id===o.current.id))??u[0];if(c){let p=ee(a,c.id,"failed",yt(a,c.id),{note:i});a=n.recordExecution({runId:e,entry:p,nextPending:[]})??a}}for(let c of u){if(i&&ue(a).has(c.id))continue;let p=ee(a,c.id,"skipped",a.history.at(-1)?.at??a.createdAt,{note:i?"not reached: the turn failed":"not reported before the turn ended"});a=n.recordExecution({runId:e,entry:p,nextPending:[]})??a}i&&(a=n.setStatus(e,"failed")??a)}else{let d=ee(a,te.reply,i?"failed":"ok",a.createdAt,{output:s,...i?{note:i}:{}});a=n.recordExecution({runId:e,entry:d,nextPending:i?[]:[te.done],...i?{status:"failed"}:{}})??a}if(i)a.status==="running"&&(a=n.setStatus(e,"failed")??a);else{let d=ee(a,te.done,"ok",a.history.at(-1)?.at??a.createdAt,{output:s});a=n.recordExecution({runId:e,entry:d,nextPending:[],status:"completed"})??a}return n.get(e)??a}var mi=new Set(["stopped","cancelled","interrupted"]);function Zu(n){return typeof n=="string"&&mi.has(n)}function Xu(n,e="interrupted: the daemon stopped during the turn"){let t=0;for(let r of n.openTaskRunIds()){let o=n.get(r);if(!o||o.status!=="running"||!o.meta?.wrap)continue;let s=gi(n,o.id,{error:e,canceled:!0,durationMs:Math.max(0,Date.now()-Date.parse(o.createdAt)),readOnly:!1,exemptQuestions:!1});s&&s!=="discarded"&&t++}return t}var hi=new Set(["completed","failed","canceled"]);function el(n){let e=n.meta?.plan,t=new Map((e?.steps??[]).map(a=>[a.id,a.title])),r=[],o=n.createdAt;for(let a of n.history){if(a.status==="paused"||a.status==="resumed"){o=a.at;continue}let d=a.durationMs??Math.max(0,Date.parse(a.at)-Date.parse(o));r.push({id:a.nodeId,...t.has(a.nodeId)?{title:t.get(a.nodeId)}:{},status:a.status,startedAt:a.startedAt??o,durationMs:d,...a.note?{note:a.note.slice(0,200)}:{}}),o=a.at}let s=hi.has(n.status)?n.updatedAt:void 0,i=[...n.history].reverse().find(a=>a.output&&typeof a.output.turnMs=="number")?.output;return{v:1,runId:n.id,workflowId:n.workflowId,title:n.meta?.title??n.workflowId,mode:n.meta?.wrap?n.meta.wrap.mode:"workflow",...n.meta?.wrap?.agentId??n.meta?.startedBy?{agentId:n.meta?.wrap?.agentId??n.meta?.startedBy}:{},status:n.status,startedAt:n.createdAt,...s?{endedAt:s,durationMs:Math.max(0,Date.parse(s)-Date.parse(n.createdAt))}:{},steps:r,failedAt:r.find(a=>a.status==="failed"||a.status==="timeout")?.id??null,revisions:Math.max(0,(e?.revisions.length??0)-1),tags:n.meta?.tags??[],...n.meta?.continues?{continues:n.meta.continues}:{},...i&&(i.inputTokens!==void 0||i.outputTokens!==void 0)?{tokens:{...i.inputTokens!==void 0?{input:i.inputTokens}:{},...i.outputTokens!==void 0?{output:i.outputTokens}:{}}}:{}}}function tl(n){let e=n.meta?.plan,t=n.meta?.plan?.current?.id??n.pausedAt?.nodeId??n.pending[0]??n.history.at(-1)?.nodeId??"-";if(!e)return t;let r=e.steps.findIndex(o=>o.id===t);return r>=0?`${e.steps[r].title} (${r+1}/${e.steps.length})`:t}import{existsSync as kt,mkdirSync as ur,readFileSync as bt,renameSync as lr,writeFileSync as cr,appendFileSync as wi}from"fs";import{dirname as pr,resolve as fr}from"path";import{randomBytes as gr}from"crypto";var yi=".agentx/members.json",ki=".agentx/members-log.jsonl",mr=class{constructor(e=process.cwd(),t=Date.now,r=90){this.now=t;this.retentionDays=r;this.file=fr(e,yi),this.logFile=fr(e,ki)}file;logFile;prunedAt=0;devices(e){let t=this.load().devices;return e?t.filter(r=>r.personId===e):t}byToken(e){return this.load().devices.find(t=>t.tokenId===e)??null}add(e){let t=this.load();t.devices=t.devices.filter(r=>r.tokenId!==e.tokenId),t.devices.push(e),this.save(t)}update(e,t){let r=this.load(),o=r.devices.find(s=>s.tokenId===e);return o?(Object.assign(o,t),this.save(r),o):null}log(e){try{this.prune()}catch{}try{ur(pr(this.logFile),{recursive:!0}),wi(this.logFile,JSON.stringify({at:new Date(this.now()).toISOString(),...e})+`
|
|
35
|
+
`,{mode:384})}catch{}}prune(e=!1){let t=this.now();if(!e&&t-this.prunedAt<36e5||(this.prunedAt=t,!kt(this.logFile)))return 0;let r=t-this.retentionDays*864e5,o=bt(this.logFile,"utf-8").split(`
|
|
36
|
+
`).filter(Boolean),s=o.filter(a=>{try{return Date.parse(JSON.parse(a).at)>=r}catch{return!1}});if(s.length===o.length)return 0;let i=`${this.logFile}.${process.pid}.${gr(4).toString("hex")}.tmp`;return cr(i,s.length?s.join(`
|
|
37
|
+
`)+`
|
|
38
|
+
`:"",{encoding:"utf-8",mode:384}),lr(i,this.logFile),o.length-s.length}events(e,t=50){if(!kt(this.logFile))return[];let r=bt(this.logFile,"utf-8").split(`
|
|
39
|
+
`).filter(Boolean),o=[];for(let s=r.length-1;s>=0&&o.length<t;s--)try{let i=JSON.parse(r[s]);(!e||i.person===e)&&o.push(i)}catch{}return o}load(){if(kt(this.file))try{let e=JSON.parse(bt(this.file,"utf-8"));if(e&&Array.isArray(e.devices))return e}catch{}return{devices:[]}}save(e){ur(pr(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.${gr(4).toString("hex")}.tmp`;cr(t,JSON.stringify(e,null,2)+`
|
|
40
|
+
`,{encoding:"utf-8",mode:384}),lr(t,this.file)}};import{extname as bi}from"path";var hr=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,wr=/<agentx-artifact>[\s\S]*$/i;function dl(n,e=1/0,t=!1){let r=[],o=String(n??"");if(!/<agentx-artifact>/i.test(o))return{text:o,artifacts:r};let s=o.replace(hr,(i,a)=>{try{let d=JSON.parse(a.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&r.length<e){let u=d.mime,c=u.startsWith("image/")?"image":u==="application/pdf"?"pdf":u.startsWith("text/")?"text":"file";r.push({type:c,filename:d.filename,mime:u})}}catch{}return""});return{text:(t?s.replace(wr,""):s).trim(),artifacts:r}}function ul(n,e=!1){let t=String(n??""),r=t;if(/<agentx-artifact>/i.test(t)){let o=t.replace(hr,(s,i)=>{try{let a=JSON.parse(i.trim());return a&&typeof a.filename=="string"?a.filename:""}catch{return""}});r=(e?o.replace(wr,""):o).trim()}return r.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(o,s,i)=>s===void 0||i===void 0?o:`[${s||i}](${i})`)}var vi={".png":{mime:"image/png",kind:"image"},".jpg":{mime:"image/jpeg",kind:"image"},".jpeg":{mime:"image/jpeg",kind:"image"},".gif":{mime:"image/gif",kind:"image"},".webp":{mime:"image/webp",kind:"image"},".svg":{mime:"image/svg+xml",kind:"file"},".pdf":{mime:"application/pdf",kind:"file"},".txt":{mime:"text/plain; charset=utf-8",kind:"file"},".md":{mime:"text/markdown; charset=utf-8",kind:"file"},".csv":{mime:"text/csv; charset=utf-8",kind:"file"},".json":{mime:"application/json",kind:"file"},".mp3":{mime:"audio/mpeg",kind:"audio"},".m4a":{mime:"audio/mp4",kind:"audio"},".wav":{mime:"audio/wav",kind:"audio"},".mp4":{mime:"video/mp4",kind:"video"},".webm":{mime:"video/webm",kind:"video"}},ll={bytes:20*1024*1024,perMessage:20,pathChars:512};function cl(n){return vi[bi(n).toLowerCase()]??null}var Ii=["[Phone app: showing files]","To show the owner a file you created (a chart, a screenshot, a PDF, a recording), save or copy it into .agentx/outbox/ in your workspace and end your reply with one line per file:",'<agentx-artifact>{"filename":".agentx/outbox/<name.ext>","mime":"<mime/type>"}</agentx-artifact>',"Files outside your workspace (/tmp, your home folder) are refused. Outbox files are removed after 7 days.","The line is removed from the text. Images show in the reply, audio and video get a player, other files an Open link. Allowed: png, jpg, gif, webp, svg, pdf, txt, md, csv, json, mp3, m4a, wav, mp4, webm; up to 20 MB and 20 files per reply.","A picture already on the web can go inline as ."].join(`
|
|
41
|
+
`);function pl(n,e,t){return n==="app"&&e&&t!==!1?Ii:void 0}import{lstatSync as It,mkdirSync as $i,readdirSync as Ai,realpathSync as vt,unlinkSync as Si}from"fs";import{join as De,resolve as yr}from"path";var kr=".agentx/outbox",Ri=7*24*60*60*1e3;function xi(n,e){try{let t=vt(yr(e,n)),r=De(t,kr);return vt(r)===r&&It(r).isDirectory()?r:null}catch{return null}}function hl(n,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let o=vt(yr(t,n));It(De(o,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||$i(De(o,kr),{recursive:!0})}catch{return 0}let r=xi(n,t);return r?br(r,(e.now??Date.now())-(e.maxAgeMs??Ri)):0}function br(n,e){let t=0;for(let r of Ai(n)){let o=De(n,r);try{let s=It(o);s.isDirectory()?t+=br(o,e):Math.max(s.mtimeMs,s.ctimeMs)<e&&(Si(o),t++)}catch{}}return t}export{Vt as a,on as b,sn as c,qi as d,qr as e,Gi as f,zr as g,Yi as h,Vi as i,Qi as j,Zi as k,Xi as l,ea as m,ta as n,Vr as o,na as p,ra as q,aa as r,Ge as s,oo as t,da as u,ua as v,so as w,la as x,fn as y,fa as z,ga as A,mn as B,hn as C,co as D,ka as E,ba as F,$a as G,Aa as H,x as I,re as J,A as K,Je as L,xo as M,Qe as N,U as O,et as P,nt as Q,id as R,ad as S,mt as T,_s as U,qs as V,wt as W,zo as X,si as Y,Tu as Z,Nu as _,Ou as $,Du as aa,Mu as ba,ai as ca,di as da,Eu as ea,ju as fa,Cu as ga,Fu as ha,Uu as ia,Hu as ja,Bu as ka,Ku as la,qu as ma,Gu as na,zu as oa,Ju as pa,Yu as qa,Vu as ra,Qu as sa,gi as ta,Zu as ua,Xu as va,el as wa,tl as xa,mr as ya,dl as za,ul as Aa,ll as Ba,cl as Ca,pl as Da,kr as Ea,hl as Fa};
|
|
42
|
+
//# sourceMappingURL=chunk-GGAEFVXL.js.map
|