agentix-cli 0.63.0 → 0.65.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-D2BHFDUA.js → agent-HUKCS3AK.js} +2 -2
- package/dist/{board-dashboard-SMCZBJKO.js → board-dashboard-S4V4WR2N.js} +382 -213
- package/dist/board-dashboard-S4V4WR2N.js.map +1 -0
- package/dist/{chunk-GUJB53QU.js → chunk-62EJKQFX.js} +2 -2
- package/dist/{chunk-TX3ZOO22.js → chunk-AVDWFQZ5.js} +2 -2
- package/dist/{chunk-KAFO5QZR.js → chunk-C4CDVE2E.js} +28 -28
- package/dist/chunk-C4CDVE2E.js.map +1 -0
- package/dist/chunk-ECBKTFTL.js +20 -0
- package/dist/chunk-ECBKTFTL.js.map +1 -0
- package/dist/chunk-EOKOGQZG.js +131 -0
- package/dist/chunk-EOKOGQZG.js.map +1 -0
- package/dist/{chunk-ZGWW6FZF.js → chunk-HSJRI3NW.js} +184 -184
- package/dist/chunk-HSJRI3NW.js.map +1 -0
- package/dist/{chunk-7LETLAIH.js → chunk-LEFRNHZF.js} +4 -4
- package/dist/{chunk-7LETLAIH.js.map → chunk-LEFRNHZF.js.map} +1 -1
- package/dist/{chunk-JZMKKDT3.js → chunk-OTTAKMGC.js} +54 -54
- package/dist/chunk-OTTAKMGC.js.map +1 -0
- package/dist/{chunk-33YJIUYL.js → chunk-WMDDQVCI.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/processes-TGFDGQYY.js +2 -0
- package/dist/{program-NPPLJAQ7.js → program-DZCKFNHD.js} +2 -2
- package/dist/registry-P7IAAFCX.js +2 -0
- package/package.json +1 -1
- package/dist/board-dashboard-SMCZBJKO.js.map +0 -1
- package/dist/chunk-5UYXEO3I.js +0 -131
- package/dist/chunk-5UYXEO3I.js.map +0 -1
- package/dist/chunk-JZMKKDT3.js.map +0 -1
- package/dist/chunk-KAFO5QZR.js.map +0 -1
- package/dist/chunk-PMGPGMBZ.js +0 -19
- package/dist/chunk-PMGPGMBZ.js.map +0 -1
- package/dist/chunk-ZGWW6FZF.js.map +0 -1
- package/dist/processes-NNXSRQSV.js +0 -2
- package/dist/registry-MRMQBYE4.js +0 -2
- /package/dist/{agent-D2BHFDUA.js.map → agent-HUKCS3AK.js.map} +0 -0
- /package/dist/{chunk-GUJB53QU.js.map → chunk-62EJKQFX.js.map} +0 -0
- /package/dist/{chunk-TX3ZOO22.js.map → chunk-AVDWFQZ5.js.map} +0 -0
- /package/dist/{chunk-33YJIUYL.js.map → chunk-WMDDQVCI.js.map} +0 -0
- /package/dist/{processes-NNXSRQSV.js.map → processes-TGFDGQYY.js.map} +0 -0
- /package/dist/{program-NPPLJAQ7.js.map → program-DZCKFNHD.js.map} +0 -0
- /package/dist/{registry-MRMQBYE4.js.map → registry-P7IAAFCX.js.map} +0 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import{b as Le,c as He}from"./chunk-WP6KLXTP.js";import{a as te}from"./chunk-N6EWZGIX.js";import{b as De,e as Ee,f as Fe,i as Ce,k as Me,l as _e,q as Ue}from"./chunk-BHE5TJSN.js";import{b as ie}from"./chunk-AFRHKA7B.js";import{a as We,b as ne,c as re,d as je,e as oe}from"./chunk-QD6IICK7.js";import{v as Oe,w as Ft}from"./chunk-PTB2TPOC.js";import{b as Ne,f as Et}from"./chunk-72SZI2UW.js";import{c as Pe,d as Te}from"./chunk-QOYAX2FT.js";import{existsSync as Ct,mkdirSync as Ke,readFileSync as Mt,writeFileSync as _t,renameSync as Lt}from"fs";import{resolve as Be,dirname as Ht}from"path";var ze=class{filePath;log;constructor(e={}){let t=e.baseDir??Be(process.cwd(),".agentx");this.filePath=Be(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),Ke(t,{recursive:!0})}key(e,t,n){return`${e}::${t}::${n||"-"}`}load(){if(!Ct(this.filePath))return{version:1,overrides:{}};try{let e=Mt(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){Ke(Ht(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;_t(t,JSON.stringify(e,null,2)),Lt(t,this.filePath)}get(e,t,n){let i=this.load().overrides[this.key(e,t,n)];if(i&&!(i.expiresAt&&Date.parse(i.expiresAt)<Date.now()))return i}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),n={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(n.channel,n.chatId,n.accountId)]=n,this.save(t),n}remove(e,t,n){let o=this.load(),i=this.key(e,t,n);return i in o.overrides?(delete o.overrides[i],this.save(o),!0):!1}consumeSummary(e,t,n){let o=this.load(),i=o.overrides[this.key(e,t,n)];if(!i||!i.summary||i.summaryConsumedAt)return;let s=i.summary;return i.summaryConsumedAt=new Date().toISOString(),this.save(o),s}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(n=>!n.expiresAt||Date.parse(n.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(n=>n.toAgent===e),outgoing:t.filter(n=>n.fromAgent===e)}}};import{readFileSync as Ut,writeFileSync as se,appendFileSync as Kt,mkdirSync as Bt,existsSync as Je}from"fs";import{resolve as ae}from"path";var qe=200,zt=7,Ye=class{memoryDir;constructor(e=process.cwd()){this.memoryDir=ae(e,".agentx/memory"),Je(this.memoryDir)||Bt(this.memoryDir,{recursive:!0})}filePath(e){return ae(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||ne(t.content))return!1;let n=t.source.trust??We(t.source.channel),o=t.review??je(n),i={...t,source:{...t.source,trust:n},...o?{review:o}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return Kt(this.filePath(e),JSON.stringify(i)+`
|
|
2
|
+
`),!0}getAll(e){let t=this.filePath(e);if(!Je(t))return[];try{return Ut(t,"utf-8").split(`
|
|
3
|
+
`).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return[]}}findRelevant(e,t,n=8){let o=this.getAll(t).filter(oe);if(o.length===0)return[];let i=o.map(f=>`${f.keywords.join(" ")} ${f.content}`),s=ae(this.memoryDir,`${t}_bm25_cache.json`),a=Te(i,s),d=Pe(e,a),c=new Map(d.map(f=>[f.docIndex,f.score])),p=o.map((f,h)=>{let m=c.get(h)??0;return f.category==="commitment"&&(m+=1),{memory:f,score:m}}).filter(f=>f.score>0);if(p.length===0)return o.slice(-n);let g=p.sort((f,h)=>h.score-f.score).slice(0,n).map(f=>f.memory);if(g.length>0)try{this.recordAccess(t,g.map(f=>f.id))}catch{}return g}buildContext(e){let t=this.contextLines(e).map(n=>n.line);return t.length===0?"":["[Agent Memory \u2014 persistent facts from past conversations]",...t,"[End Memory]"].join(`
|
|
4
|
+
`)}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[],n=57;for(let o of e){let s=!o.source.chatId.startsWith("-")&&/^\d+$/.test(o.source.chatId)?"DM":o.source.chatId,a=`- [${o.category}] ${o.content} (${s}, ${o.source.date})`;if(n+a.length>2400)break;t.push({fact:o,line:a}),n+=a.length}return t}recordAccess(e,t){if(t.length===0)return;let n=this.getAll(e),o=new Set(t),i=!1;for(let s of n)if(o.has(s.id)){s.accessCount=(s.accessCount||0)+1,s.lastAccessed=new Date().toISOString();let a=s.intervalDays||1;s.intervalDays=Math.min(a*2,30),s.nextReview=new Date(Date.now()+s.intervalDays*864e5).toISOString(),i=!0}i&&se(this.filePath(e),n.map(s=>JSON.stringify(s)).join(`
|
|
5
|
+
`)+`
|
|
6
|
+
`)}getDueForReview(e,t=5){let n=this.getAll(e).filter(oe),o=Date.now();return n.filter(i=>i.category==="task-state"?!1:i.nextReview?new Date(i.nextReview).getTime()<=o:!0).sort((i,s)=>!i.nextReview&&s.nextReview?-1:i.nextReview&&!s.nextReview?1:i.nextReview&&s.nextReview?new Date(i.nextReview).getTime()-new Date(s.nextReview).getTime():(i.accessCount||0)-(s.accessCount||0)).slice(0,t)}buildRecallContext(e){let t=this.getDueForReview(e,5);if(t.length===0)return"";let n=["[Memory Recall \u2014 facts due for review, verify they are still accurate]"];for(let o of t){let i=Math.round((Date.now()-new Date(o.createdAt).getTime())/864e5);n.push(`- [${o.category}] ${o.content} (${i}d old, accessed ${o.accessCount||0}x)`)}return n.push("[If any fact is outdated, note the correction. Otherwise, acknowledge recall.]"),n.join(`
|
|
7
|
+
`)}held(e){return this.getAll(e).filter(t=>t.review==="held"||t.review===void 0&&re(t)==="external")}review(e,t,n,o="operator"){let i=this.getAll(e),s=i.find(a=>a.id===t);return s?(s.review=n,s.reviewedBy=o,s.reviewedAt=new Date().toISOString(),this.rewrite(e,i),!0):!1}scrubSecrets(e,t=!1){let n=this.getAll(e),o=n.filter(s=>s.category!=="secret"&&!ne(s.content)),i=n.length-o.length;return t&&i>0&&this.rewrite(e,o),i}trustSummary(e){let t={};for(let n of this.getAll(e)){let o=`${re(n)}${n.review?`/${n.review}`:""}`;t[o]=(t[o]??0)+1}return t}rewrite(e,t){se(this.filePath(e),t.map(n=>JSON.stringify(n)).join(`
|
|
8
|
+
`)+(t.length?`
|
|
9
|
+
`:""))}hasSimilar(e,t){let n=this.getAll(e),i=t.toLowerCase().split(/\s+/).filter(s=>s.length>3);return n.some(s=>{let a=s.content.toLowerCase();return i.filter(c=>a.includes(c)).length>=i.length*.7})}prune(e){let t=this.getAll(e);if(t.length===0)return;let n=Date.now(),o=zt*24*60*60*1e3;t=t.filter(s=>s.category==="task-state"&&s.expiresAt?new Date(s.expiresAt).getTime()>n:s.category==="task-state"&&!s.expiresAt?n-new Date(s.createdAt).getTime()<o:!0),t.length>qe&&(t=t.slice(-qe));let i=this.filePath(e);se(i,t.map(s=>JSON.stringify(s)).join(`
|
|
10
|
+
`)+`
|
|
11
|
+
`)}};import{existsSync as I,mkdirSync as pn,readdirSync as U,readFileSync as K,unlinkSync as B,writeFileSync as le}from"fs";import{resolve as R,relative as ue}from"path";import{z as l}from"zod";var Jt=l.enum(["trigger.channel","trigger.manual","trigger.cron","trigger.hook","trigger.form","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","checkpoint","end"]),qt=l.enum(["equals","contains","matches","exists"]),Yt=l.object({kind:qt,params:l.record(l.unknown()).default({})}),Ve=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}),Ze=l.object({id:l.string().min(1).regex(/^[a-zA-Z_][a-zA-Z0-9_-]*$/,"node id must be identifier-safe"),type:Jt,config:l.record(l.unknown()).default({}),retry:Ve,position:l.object({x:l.number(),y:l.number()}).optional()}),Xe=l.object({from:l.string(),fromPort:l.string().optional(),to:l.string(),toPort:l.string().optional(),label:l.string().optional()}),Ge=l.union([l.string(),l.date().transform(r=>r.toISOString())]),$=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(Ze).refine(r=>r.length>0,{message:"workflow must have at least one node"}),edges:l.array(Xe).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:Ge.optional(),updated:Ge.optional()});function de(r){let e=[],t=new Map(r.nodes.map(s=>[s.id,s])),n=r.nodes.filter(s=>s.type.startsWith("trigger."));n.length===0&&e.push("workflow must have exactly one trigger.* node (found 0)"),n.length>1&&e.push(`workflow has ${n.length} trigger.* nodes; v1 supports exactly one`);for(let s of r.edges)t.has(s.from)||e.push(`edge references missing node: from="${s.from}"`),t.has(s.to)||e.push(`edge references missing node: to="${s.to}"`);let o=n[0];if(o){let s=new Map;for(let c of r.edges)s.has(c.from)||s.set(c.from,[]),s.get(c.from).push(c.to);let a=new Set,d=[o.id];for(;d.length;){let c=d.pop();if(!a.has(c)){a.add(c);for(let u of s.get(c)??[])d.push(u)}}for(let c of r.nodes)a.has(c.id)||e.push(`node "${c.id}" is unreachable from trigger "${o.id}"`);r.nodes.some(c=>a.has(c.id)&&Gt(c.type))||e.push("no reachable `end`, `checkpoint`, `subProcess`, `signal.wait`, or `timer.boundary` node \u2014 the run cannot terminate or pause")}for(let s of r.nodes){if(s.type!=="branch"&&s.type!=="rule")continue;let a=s.type==="branch"?s.config.cases??[]:(s.config.rules??[]).filter(p=>typeof p.to=="string"),d=s.type==="branch"?s.config.default:s.config.default?.to,c=new Set(a.map(p=>p.to));d&&c.add(d);let u=r.edges.filter(p=>p.from===s.id);for(let p of u){let g=p.fromPort??"";c.has(g)||e.push(`${s.type} "${s.id}" has outgoing edge with port "${g}" not declared in cases or default`)}}let i=Zt(r);for(let s of i)e.push(`cycle without agent/checkpoint: ${s.join(" -> ")}`);return e}function Gt(r){return r==="end"||r==="checkpoint"||r==="subProcess"||r==="signal.wait"||r==="timer.boundary"}function Vt(r){return r==="agent"||r==="checkpoint"||r==="subProcess"||r==="signal.wait"||r==="timer.boundary"}function Zt(r){let e=new Map;for(let a of r.edges)e.has(a.from)||e.set(a.from,[]),e.get(a.from).push(a.to);let t=new Map(r.nodes.map(a=>[a.id,a])),n=[],o=new Map,i=[],s=a=>{if(o.get(a)===1){let d=i.indexOf(a);if(d>=0){let c=i.slice(d).concat(a);c.some(p=>{let g=t.get(p)?.type;return g?Vt(g):!1})||n.push(c)}return}if(o.get(a)!==2){o.set(a,1),i.push(a);for(let d of e.get(a)??[])s(d);i.pop(),o.set(a,2)}};for(let a of r.nodes)o.get(a.id)!==2&&s(a.id);return n}var Qe=l.enum(["running","paused","completed","failed","canceled"]),Xt=l.enum(["ok","failed","timeout","skipped","paused","resumed"]),Qt=l.object({at:l.string(),nodeId:l.string(),inputKeys:l.array(l.string()).default([]),status:Xt,output:l.record(l.unknown()).optional(),idempotencyKey:l.string(),note:l.string().optional()}),en=l.object({backend:l.string(),id:l.string()}),tn=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()})]),nn=l.object({id:l.string(),workflowId:l.string(),workflowVersion:l.literal(2),homeNode:l.string(),status:Qe,pausedAt:tn.optional(),context:l.record(l.record(l.unknown())).default({}),pending:l.array(l.string()).default([]),joinCounters:l.record(l.array(l.string())).default({}),entityRef:en,history:l.array(Qt).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(),createdAt:l.string(),updatedAt:l.string()});import tt from"js-yaml";var rn=new Set(["branch","gateway.parallel","rule","signal.wait","subProcess","timer.boundary","checkpoint"]),v=class extends Error{constructor(t,n){super(t);this.mark=n;this.name="WorkflowYamlError"}};function L(r,e={}){if(!r||r.trim()==="")throw new v(`${x(e)}empty file \u2014 workflow YAML must contain at least an id, version, title, and one node.`);let t;try{t=tt.loadAll(r)}catch(o){let i=o?.mark;throw new v(`${x(e)}YAML parse error: ${o?.reason??o?.message??o}`+(i?` (line ${i.line+1}, column ${i.column+1})`:""),i)}if(t.length===0||t.length===1&&t[0]==null)throw new v(`${x(e)}YAML produced no document.`);if(t.length>1)throw new v(`${x(e)}multi-document YAML is not supported in v1; one workflow per file.`);let n=t[0];if(typeof n!="object"||n===null||Array.isArray(n)){let o=Array.isArray(n)?"array":typeof n;throw new v(`${x(e)}top-level YAML must be a mapping (got ${o}).`)}return nt(n,e)}function nt(r,e={}){if(!("flow"in r))return r;let t=r.flow;if(t==null){let p={...r};return delete p.flow,p}if(!Array.isArray(t))throw new v(`${x(e)}flow must be an array of node ids (got ${typeof t}).`);for(let p of t)if(typeof p!="string")throw new v(`${x(e)}flow entries must be strings (got ${typeof p}).`);let n=t,o=Array.isArray(r.nodes)?r.nodes:[],i=new Map;for(let p of o)p&&typeof p=="object"&&typeof p.id=="string"&&typeof p.type=="string"&&i.set(p.id,p.type);for(let p of n){if(!i.has(p))throw new v(`${x(e)}flow references unknown node "${p}".`);let g=i.get(p);if(rn.has(g))throw new v(`${x(e)}flow cannot include ${g} node "${p}"; use explicit edges for ${g} nodes.`)}let s=[];for(let p=0;p<n.length-1;p++)s.push({from:n[p],to:n[p+1]});let a=Array.isArray(r.edges)?r.edges:[],d=new Set,c=[];for(let p of a){if(!p||typeof p!="object")continue;let g=et(p.from,p.fromPort,p.to);g&&!d.has(g)?(d.add(g),c.push(p)):g||c.push(p)}for(let p of s){let g=et(p.from,void 0,p.to);g&&!d.has(g)&&(d.add(g),c.push(p))}let u={...r,edges:c};return delete u.flow,u}function et(r,e,t){return typeof r!="string"||typeof t!="string"?null:`${r}::${typeof e=="string"?e:""}::${t}`}function x(r){return r.filePath?`${r.filePath}: `:""}function on(r){return tt.dump(r,{noRefs:!0,lineWidth:100,sortKeys:!1})}import{Document as sn,isMap as H,isSeq as an,isScalar as rt,parseDocument as dn}from"yaml";function ot(r,e){let t=dn(r);if(!t.contents||!H(t.contents)){let n=new sn(e);return t.commentBefore&&(n.commentBefore=t.commentBefore),String(n)}return ce(t,t.contents,e),String(t)}function ce(r,e,t){let n=Object.keys(t),o=new Set(n),i=new Map;for(let a of e.items){let d=un(a);d!==null&&i.set(d,a)}let s=[];for(let a of n){let d=t[a],c=i.get(a);c?(cn(r,c,d),s.push(c)):s.push(r.createPair(a,d))}e.items=s}function cn(r,e,t){let n=e.value;if(t==null){e.value=r.createNode(null);return}if(typeof t!="object"){e.value=r.createNode(t);return}if(Array.isArray(t)){an(n)?ln(r,n,t):e.value=r.createNode(t);return}H(n)?ce(r,n,t):e.value=r.createNode(t)}function ln(r,e,t){if(!(t.length>0&&t.every(s=>s&&typeof s=="object"&&typeof s.id=="string"))){let s=r.createNode(t);e.items=s.items;return}let o=new Map;for(let s of e.items)if(H(s)){let a=s.get("id",!0);rt(a)&&typeof a.value=="string"&&o.set(a.value,s)}let i=[];for(let s of t){let a=s.id,d=o.get(a);d&&H(d)?(ce(r,d,s),i.push(d)):i.push(r.createNode(s))}e.items=i}function un(r){let e=r.key;return rt(e)&&typeof e.value=="string"?e.value:typeof e=="string"?e:null}var pe=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??R(process.cwd(),".agentx/workflows"),pn(this.baseDir,{recursive:!0})}pathFor(e){return this.pathForJson(e)}pathForJson(e){return R(this.baseDir,`${e}.json`)}pathForYaml(e){return R(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=R(this.baseDir,e),n=K(t,"utf-8");return e.endsWith(".json")?JSON.parse(n):L(n,{filePath:e})}list(){if(!I(this.baseDir))return[];let e=new Map;for(let n of U(this.baseDir,{withFileTypes:!0})){if(!n.isFile()||!this.isWorkflowFile(n.name))continue;let o=this.idFromFilename(n.name),i=e.get(o)??[];i.push(n.name),e.set(o,i)}let t=[];for(let[,n]of e)if(!(n.length>1))try{let o=this.readAndParse(n[0]),i=$.safeParse(o);i.success&&t.push(i.data)}catch{}return t.sort((n,o)=>n.id.localeCompare(o.id))}validateAll(){let e=[];if(!I(this.baseDir))return e;let t=new Map;for(let n of U(this.baseDir,{withFileTypes:!0})){if(!n.isFile()||!this.isWorkflowFile(n.name))continue;let o=this.idFromFilename(n.name),i=t.get(o)??[];i.push(n.name),t.set(o,i)}for(let[n,o]of t){if(o.length>1){let p=[...o].sort();for(let g of p)e.push({id:n,path:ue(this.baseDir,R(this.baseDir,g)),issues:[`duplicate workflow id "${n}" \u2014 found ${p.join(" and ")}; delete one to disambiguate`],isValid:!1});continue}let i=o[0],s=R(this.baseDir,i),a=ue(this.baseDir,s),d;try{d=this.readAndParse(i)}catch(p){let g=p instanceof v?p.message:`parse error: ${p?.message??p}`;e.push({id:n,path:a,issues:[g],isValid:!1});continue}let c=$.safeParse(d);if(!c.success){let p=c.error.issues.map(g=>`${g.path.join(".")||"<root>"}: ${g.message}`);e.push({id:String(d?.id??n),path:a,issues:p,isValid:!1});continue}let u=de(c.data);e.push({workflow:c.data,issues:u,isValid:u.length===0})}return e}get(e){let t=this.pathForJson(e),n=this.pathForYaml(e),o=R(this.baseDir,`${e}.yml`),i=I(t),s=I(n)||I(o);if(i&&s)return null;if(i)try{let d=JSON.parse(K(t,"utf-8")),c=$.safeParse(d);return c.success?c.data:null}catch{return null}let a=I(n)?n:I(o)?o:null;if(a)try{let d=K(a,"utf-8"),c=L(d,{filePath:ue(this.baseDir,a)}),u=$.safeParse(c);return u.success?u.data:null}catch{return null}if(!I(this.baseDir))return null;for(let d of U(this.baseDir,{withFileTypes:!0}))if(!(!d.isFile()||!this.isWorkflowFile(d.name)||this.idFromFilename(d.name)===e))try{let u=this.readAndParse(d.name),p=$.safeParse(u);if(p.success&&p.data.id===e)return p.data}catch{}return null}save(e,t={}){let n=new Date().toISOString().slice(0,10),o=$.parse({...e,created:e.created||n,updated:n}),i=this.pathForYaml(o.id),s=R(this.baseDir,`${o.id}.yml`),a=I(i)?i:I(s)?s:null;if(!a&&I(this.baseDir)){for(let d of U(this.baseDir,{withFileTypes:!0}))if(!(!d.isFile()||!this.isWorkflowFile(d.name))&&!d.name.endsWith(".json"))try{let c=this.readAndParse(d.name),u=$.safeParse(c);if(u.success&&u.data.id===o.id){a=R(this.baseDir,d.name);break}}catch{}}if(a&&t.convertFromYaml)return B(a),le(this.pathForJson(o.id),JSON.stringify(o,null,2)+`
|
|
12
|
+
`),o;if(a){let d=K(a,"utf-8");try{let c=ot(d,o);return le(a,c),o}catch(c){let u=new Error(`yaml round-trip failed for "${o.id}" at ${a}: ${c?.message??c}`);throw u.yamlPath=a,u}}return le(this.pathForJson(o.id),JSON.stringify(o,null,2)+`
|
|
13
|
+
`),o}delete(e){let t=this.pathForJson(e),n=this.pathForYaml(e),o=R(this.baseDir,`${e}.yml`),i=!1;return I(t)&&(B(t),i=!0),I(n)&&(B(n),i=!0),I(o)&&(B(o),i=!0),i}};import{createHash as fn,randomUUID as gn}from"crypto";import{appendFileSync as it,existsSync as j,mkdirSync as st,readdirSync as at,readFileSync as fe,statSync as dt,unlinkSync as ct,writeFileSync as mn}from"fs";import{resolve as W}from"path";function hn(r){return r.replace(/[^a-zA-Z0-9._:#@-]/g,"_").slice(0,200)}function T(r,e,t){return fn("sha1").update(`${r}|${e}|${t}`).digest("hex").slice(0,16)}var ge=class{baseDir;runsDir;indexDir;nodeId;constructor(e){this.baseDir=e.baseDir??W(process.cwd(),".agentx/workflows"),this.runsDir=W(this.baseDir,"_runs"),this.indexDir=W(this.baseDir,"_index"),this.nodeId=e.nodeId,st(this.runsDir,{recursive:!0}),st(this.indexDir,{recursive:!0})}runPath(e){return W(this.runsDir,`${e}.jsonl`)}indexPath(e){return W(this.indexDir,`${e.backend}__${hn(e.id)}.json`)}create(e){let t=new Date().toISOString(),n=gn(),o={id:n,workflowId:e.workflowId,workflowVersion:2,homeNode:this.nodeId,status:"running",pausedAt:void 0,context:e.initialContext??{},pending:e.initialPending,entityRef:e.entityRef,history:[],parentRunId:e.parentRunId??null,parentNodeId:e.parentNodeId??null,rootRunId:e.rootRunId??n,depth:e.depth??0,eventRootId:e.eventRootId??Ee()?.rootId,joinCounters:{},createdAt:t,updatedAt:t};return this.appendSnapshot(o),this.writeIndex(e.entityRef,o.id),o}get(e){let t=this.runPath(e);if(!j(t))return null;let n=fe(t,"utf-8").trim();if(!n)return null;let o=null;for(let i of n.split(`
|
|
14
|
+
`)){let s;try{s=JSON.parse(i)}catch{continue}if(s.v===2){if(s.kind==="snapshot")o=s.run;else if(s.kind==="exec"&&o&&o.id===s.runId){let a=o;o={...a,history:[...a.history,s.entry],pending:s.pending,status:s.status??a.status,pausedAt:s.pausedAt===null?void 0:s.pausedAt??a.pausedAt,context:s.context??a.context,joinCounters:s.joinCounters??a.joinCounters,updatedAt:s.entry.at}}}}return o}getActiveByEntity(e){let t=this.indexPath(e);if(!j(t))return null;try{return JSON.parse(fe(t,"utf-8")).runId}catch{return null}}getHomeNodeByEntity(e){let t=this.indexPath(e);if(!j(t))return null;try{return JSON.parse(fe(t,"utf-8")).homeNode}catch{return null}}recordExecution(e){let t=this.get(e.runId);if(!t)return null;if(t.history.some(i=>i.idempotencyKey===e.entry.idempotencyKey))return t;let n={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};it(this.runPath(e.runId),JSON.stringify(n)+`
|
|
15
|
+
`);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 n=this.get(e);if(!n)return null;let o={...n,status:t,updatedAt:new Date().toISOString()};return this.appendSnapshot(o),t!=="running"&&t!=="paused"&&this.clearIndex(o.entityRef),o}list(e={}){if(!j(this.runsDir))return[];let t=at(this.runsDir).filter(o=>o.endsWith(".jsonl")).map(o=>({name:o,mtime:dt(W(this.runsDir,o)).mtimeMs})).sort((o,i)=>i.mtime-o.mtime),n=[];for(let o of t){let i=this.get(o.name.replace(/\.jsonl$/,""));if(i&&!(e.workflowId&&i.workflowId!==e.workflowId)&&(n.push(i),e.limit&&n.length>=e.limit))break}return n}prune(e){if(!j(this.runsDir))return 0;let t=Date.now()-e.maxDays*24*60*60*1e3,n=[];for(let i of at(this.runsDir)){if(!i.endsWith(".jsonl"))continue;let s=W(this.runsDir,i),a=dt(s).mtimeMs,d=this.get(i.replace(/\.jsonl$/,""));d&&(d.status==="running"||d.status==="paused"||n.push({file:s,run:d,mtime:a}))}n.sort((i,s)=>s.mtime-i.mtime);let o=0;for(let i=0;i<n.length;i++){let s=n[i],a=s.mtime<t,d=i>=e.maxRuns;if(a||d)try{ct(s.file),o++}catch{}}return o}appendSnapshot(e){let t={v:2,kind:"snapshot",run:e};it(this.runPath(e.id),JSON.stringify(t)+`
|
|
16
|
+
`)}writeIndex(e,t){mn(this.indexPath(e),JSON.stringify({runId:t,homeNode:this.nodeId,updatedAt:new Date().toISOString()},null,2)+`
|
|
17
|
+
`)}clearIndex(e){let t=this.indexPath(e);if(j(t))try{ct(t)}catch{}}};import{existsSync as lt,mkdirSync as wn,readFileSync as yn,unlinkSync as kn,writeFileSync as bn}from"fs";import{resolve as me}from"path";import{z as D}from"zod";var ut=D.object({version:D.literal(1),nodes:D.record(D.object({x:D.number(),y:D.number()}))}),he=class{baseDir;layoutsDir;constructor(e={}){this.baseDir=e.baseDir??me(process.cwd(),".agentx/workflows"),this.layoutsDir=me(this.baseDir,"_layouts"),wn(this.layoutsDir,{recursive:!0})}pathFor(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return me(this.layoutsDir,`${t}.json`)}get(e){let t=this.pathFor(e);if(!lt(t))return null;try{let n=ut.safeParse(JSON.parse(yn(t,"utf-8")));return n.success?n.data:null}catch{return null}}save(e,t){let n=ut.parse(t);return bn(this.pathFor(e),JSON.stringify(n,null,2)+`
|
|
18
|
+
`),n}sync(e,t){let n=this.get(e);if(!n)return null;let o={};for(let s of t)n.nodes[s]&&(o[s]=n.nodes[s]);let i={version:1,nodes:o};return this.save(e,i)}delete(e){let t=this.pathFor(e);return lt(t)?(kn(t),!0):!1}};function pt(r){return new Set(r.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function vn(r,e){if(r.size===0||e.size===0)return 0;let t=0;for(let n of r)e.has(n)&&t++;return t/Math.max(r.size,e.size)}function In(r,e){let t=pt(r.message),n=e.filter(i=>i.state==="active"&&(i.status??"active")==="active"),o=null;for(let i of n){let s=0,a=[];if(i.ownerAgent&&i.ownerAgent===r.agentId&&(s+=.25,a.push("owner-agent")),r.channel&&i.tags.includes(r.channel)&&(s+=.15,a.push("channel-tag")),r.intentPath?.length&&i.intentPath.length){let p=r.intentPath.filter((g,f)=>i.intentPath[f]===g).length;p>0&&(s+=Math.min(.3,p*.1),a.push("intent-path"))}let d=[i.id,i.title,i.description??"",...i.tags].join(" "),c=vn(t,pt(d));c>0&&(s+=Math.min(.35,c),a.push("text-similarity")),(i.matchCount??0)>0&&(s+=Math.min(.1,i.matchCount*.01),a.push("prior-matches"));let u=Math.max(0,Math.min(1,s));(!o||u>o.confidence)&&(o={workflow:i,confidence:u,reasons:a})}return o&&o.confidence>0?o:null}function we(r){let{workflow:e,fromNodeId:t,selectedPort:n}=r,o=e.nodes.find(a=>a.id===t);if(!o)return{nextPending:[]};let i=e.edges.filter(a=>a.from===t);return{nextPending:(o.type==="branch"?i.filter(a=>(a.fromPort??"")===(n??"")):i).map(a=>a.to)}}function ye(r,e){let t=r.config.cases??[],n=r.config.default??"";for(let o of t)if(Sn(o.when,e))return o.to;return n}function Sn(r,e){let t=r.params??{},n=String(t.path??""),o=z(e,n);switch(r.kind){case"equals":return o===t.value;case"contains":return typeof o=="string"?o.includes(String(t.value??"")):Array.isArray(o)?o.some(i=>i===t.value):!1;case"matches":{if(typeof o!="string")return!1;try{return new RegExp(String(t.regex??"")).test(o)}catch{return!1}}case"exists":return o!=null&&o!=="";default:return!1}}function z(r,e){if(!e)return;let t=e.split("."),n=r;for(let o of t){if(n==null||typeof n!="object")return;n=n[o]}return n}function J(r){let e=r.nodes.find(n=>n.type.startsWith("trigger."));if(!e)return null;let t=r.edges.filter(n=>n.from===e.id).map(n=>n.to);return{triggerId:e.id,pending:t}}function N(r,e){return r.nodes.find(t=>t.id===e)}Et();Ft();function An(r,e,t){let n=r.split(".");if(n[0]==="env"){if(n.length!==2)return"";let i=n[1];if(!t.has(i))return"";let s=process.env[i];return typeof s=="string"?s:""}let o=e;for(let i of n){if(o==null||typeof o!="object")return"";o=o[i]}return o==null?"":typeof o=="object"?JSON.stringify(o):String(o)}function S(r,e,t={}){let n=new Set(t.envAllow||[]);return r.replace(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_.-]*)\s*\}\}/g,(o,i)=>An(i,e,n))}function b(r,e,t={}){let n={};for(let[o,i]of Object.entries(r))typeof i=="string"?n[o]=S(i,e,t):Array.isArray(i)?n[o]=i.map(s=>typeof s=="string"?S(s,e,t):s):i&&typeof i=="object"?n[o]=b(i,e,t):n[o]=i;return n}var ft="workflow-classify",q="unsure",gt=async r=>{let e=r.node.config,t=r.run.context,n={envAllow:r.workflow.envAllow},o=S(String(e.input??""),t,n).trim();if(!o)return{error:`classify node "${r.node.id}" missing config.input`};let i=e.labels,s=Array.isArray(i)?Object.fromEntries(i.map(m=>[String(m),null])):typeof i=="object"&&i?Object.fromEntries(Object.entries(i).map(([m,y])=>[m,y==null?null:String(y)])):{},a=Object.keys(s);if(a.length<2)return{error:`classify node "${r.node.id}" needs at least two labels`};if(a.includes(q))return{error:`classify node "${r.node.id}": "${q}" is reserved for the low-confidence port`};let d=typeof e.minConfidence=="number"?e.minConfidence:.7,c=e.instructions?S(String(e.instructions),t,n):void 0,u={input:o};if(e.state&&typeof e.state=="object")for(let[m,y]of Object.entries(e.state)){let w=typeof y=="string"?S(y,t,n):y;(w===null||["string","number","boolean"].includes(typeof w))&&(u[m]=w)}let p=await Oe(ft,u,{label:Ne(s,c)},{features:{workflow:r.workflow.id,node:r.node.id}});if(!p)return{error:`classify node "${r.node.id}": decision seat unavailable (set decisions.seats.${ft}.mode)`};let g=p.answers.label,f=g.confidence>=d,h=f?g.choice:q;return r.log(`[node:${r.node.id}] classify \u2192 ${g.choice} (${g.confidence.toFixed(2)})${f?"":` \u2014 below ${d}, routing to ${q}`}`),{output:{result:g.choice,label:g.choice,confidence:g.confidence,probabilities:g.probabilities,unsure:!f,port:h},port:h}};var ke=class{active=new Map;waiters=new Map;async acquire(e,t){let n=this.active.get(e)??0;if(n<t){this.active.set(e,n+1);return}return new Promise(o=>{let i=this.waiters.get(e)??[];i.push({resolve:()=>{this.active.set(e,(this.active.get(e)??0)+1),o()}}),this.waiters.set(e,i)})}release(e){let t=this.active.get(e)??0;this.active.set(e,Math.max(0,t-1));let n=this.waiters.get(e);n&&n.length>0&&n.shift().resolve()}stats(e){return{active:this.active.get(e)??0,waiting:this.waiters.get(e)?.length??0}}},Y=new ke;function mt(r,e){return`${r}:${e}`}var E=async r=>({output:r.run.context[r.node.id]??{}}),Rn=async r=>{let e=r.node.config,t=String(e.agentId??""),n=String(e.prompt??"");if(!t)return{error:`agent node "${r.node.id}" missing config.agentId`};let o=S(n,r.run.context,{envAllow:r.workflow.envAllow}),i=typeof e.timeoutMinutes=="number"?e.timeoutMinutes:void 0,s=e.autonomy===void 0||e.autonomy===null?void 0:String(e.autonomy);if(s!==void 0&&s!=="report"&&s!=="propose"&&s!=="act")return{error:`agent node "${r.node.id}" has invalid autonomy "${s}" (expected report, propose or act)`};let a=typeof e.maxConcurrent=="number"&&e.maxConcurrent>0?e.maxConcurrent:null,d=a?mt(r.workflow.id,r.node.id):null;if(d&&a){let u=Y.stats(d);u.active>=a&&r.log(`[node:${r.node.id}] gated: ${u.active} active (cap ${a}), ${u.waiting+1} waiting`),await Y.acquire(d,a)}let c=Date.now();try{let u=await r.agents.execute({agentId:t,message:o,workflowRunId:r.run.id,timeoutMinutes:i,...s?{autonomy:s}:{}}),p=Date.now()-c;if(u.error){let h=u.errorKind??"unknown";return r.log(`[node:${r.node.id}] agent "${t}" failed (${h}): ${u.error}`),{error:`[${h}] ${u.error}`}}let f=String(e.resultParser??"acme-result-token")==="json"?Gn(u.content):wt(u.content);return{output:{reply:u.content,result:f.result,json:f.json,taskId:u.taskId,durationMs:p,...u.autonomyBlocks?.length?{autonomyBlocks:u.autonomyBlocks}:{}}}}catch(u){return r.log(`[node:${r.node.id}] agent "${t}" threw: ${u.message}`),{error:u.message}}finally{d&&Y.release(d)}},$n=async r=>{let e=ye(r.node,r.run.context);return e?{output:{port:e},port:e}:(r.log(`[node:${r.node.id}] branch matched no case and no default port`),{output:{port:null}})},xn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??""),n=String(e.chatId??""),o=String(e.text??"");if(!t||!n){let a=String(r.node.config.chatId??""),d=String(r.node.config.channel??""),c=[];return t||c.push(`channel config="${d}" rendered=""`),n||c.push(`chatId config="${a}" rendered=""`),(/\{\{\s*env\./.test(a)||/\{\{\s*env\./.test(d))&&c.push("(env.* templates only resolve for names listed in workflow.envAllow and actually set in process.env)"),{error:`action.send "${r.node.id}" needs channel + chatId \u2014 ${c.join("; ")}`}}let i=ve(r,e.accountId),s=r.channels[t];if(s?.send)try{return{output:{messageId:await s.send({channel:t,chatId:n,text:o,...i?{accountId:i}:{}})??null}}}catch(a){return{error:`action.send failed: ${a.message}`}}if(r.forwardChannelSend)try{return{output:{messageId:(await r.forwardChannelSend({channel:t,chatId:n,text:o,accountId:i})).messageId,viaMesh:!0}}}catch(a){return r.log(`[node:${r.node.id}] mesh-forward of "${t}" send failed: ${a.message}`),{error:`action.send via mesh failed: ${a.message}`}}return r.log(`[node:${r.node.id}] adapter "${t}" not available locally and no mesh forwarder`),{error:`channel "${t}" not available (no local adapter, no mesh route)`}},Pn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??"gitlab"),n=String(e.project??""),o=String(e.title??""),i=String(e.description??""),s=Array.isArray(e.labels)?e.labels.map(String):[],a=Array.isArray(e.assignees)?e.assignees.map(String):[];if(!n||!o)return{error:`action.createIssue "${r.node.id}" needs project + title`};let d=Ie(r),c=r.channels[t];if(!c?.createIssue)return{error:`channel "${t}" does not support createIssue`};try{let u=await c.createIssue({project:n,title:o,description:i,labels:s,assignees:a,agentId:d});return u?{output:{issue:{iid:u.iid,url:u.url,webUrl:u.url}}}:{error:"createIssue returned null (see adapter log)"}}catch(u){return{error:`action.createIssue failed: ${u.message}`}}},Tn=async()=>({output:{}}),Nn=async r=>{let e=r.node.config,t=String(e.name??r.node.id),n=e.waitFor??{},o=e.resumeMatch??{};return{paused:!0,pausedAt:{kind:"checkpoint",nodeId:r.node.id,checkpointName:t,resumeMatch:{...n,...o}}}},On=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??"gitlab"),n=String(e.project??""),o=String(e.iid??""),i=Array.isArray(e.add)?e.add.map(String):[],s=Array.isArray(e.remove)?e.remove.map(String):[];if(!n||!o)return{error:`action.setLabel "${r.node.id}" needs project + iid (try {{trigger.project}} / {{trigger.issue.iid}})`};if(i.length===0&&s.length===0)return{output:{skipped:!0,reason:"no labels to add or remove"}};let a=r.channels[t];if(!a?.setLabels)return{error:`channel "${t}" does not support setLabels`};let d=Ie(r),c=e.kind==="merge_request"?"merge_request":"issue";return{output:{labels:await a.setLabels({project:n,kind:c,iid:o,add:i,remove:s,agentId:d})??[],add:i,remove:s}}},Wn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??"gitlab"),n=String(e.project??""),o=String(e.iid??"");if(!n||!o)return{error:`action.readLabel "${r.node.id}" needs project + iid`};let i=r.channels[t];if(!i?.getLabels)return{error:`channel "${t}" does not support getLabels`};let s=e.kind==="merge_request"?"merge_request":"issue";return{output:{labels:await i.getLabels({project:n,kind:s,iid:o})??[]}}},jn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??""),n=String(e.chatId??""),o=String(e.messageId??""),i=String(e.emoji??"\u{1F440}");if(!t||!n||!o)return{error:`action.react "${r.node.id}" needs channel + chatId + messageId`};let s=ve(r,e.accountId),a=r.channels[t];if(!a?.react)return{error:`channel "${t}" does not support react`};try{return await a.react(n,o,i,s),{output:{emoji:i}}}catch(d){return{error:`action.react failed: ${d.message}`}}},Dn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??""),n=String(e.chatId??""),o=String(e.messageId??""),i=String(e.text??""),s=e.parseMode?String(e.parseMode):void 0;if(!t||!n||!o||!i)return{error:`action.editMessage "${r.node.id}" needs channel + chatId + messageId + text`};let a=ve(r,e.accountId),d=r.channels[t];if(!d?.editMessage)return{error:`channel "${t}" does not support editMessage`};try{return{output:{edited:await d.editMessage(n,o,i,s,a)}}}catch(c){return{error:`action.editMessage failed: ${c.message}`}}},En=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??"gitlab"),n=String(e.chatId??""),o=Number(e.durationMs??0);if(!n||!o)return{error:`action.logTime "${r.node.id}" needs chatId + durationMs`};let i=r.channels[t];if(!i?.logTimeSpent)return{error:`channel "${t}" does not support logTimeSpent`};let s=Ie(r);try{return await i.logTimeSpent(n,o,s),{output:{durationMs:o}}}catch(a){return{error:`action.logTime failed: ${a.message}`}}},Fn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.url??"");if(!t)return{error:`action.callHTTP "${r.node.id}" needs url`};let n=String(e.method??"POST").toUpperCase(),o=e.headers&&typeof e.headers=="object"?e.headers:{"Content-Type":"application/json"},i;e.body!==void 0&&(i=typeof e.body=="string"?e.body:JSON.stringify(e.body));try{let s=await fetch(t,{method:n,headers:o,body:i}),a=await s.text(),d=a;try{d=JSON.parse(a)}catch{}return{output:{ok:s.ok,status:s.status,body:d}}}catch(s){return{error:`action.callHTTP failed: ${s.message}`}}},Cn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.actionId??e.id??"");if(!t)return{error:`action.run "${r.node.id}" needs actionId`};let n=e.inputs&&typeof e.inputs=="object"?e.inputs:{},{ActionStore:o}=await import("./store-TWQPEM5V.js"),{runAction:i}=await import("./runner-56G3N7M4.js"),s=new o().get(t);if(!s)return{error:`action.run "${r.node.id}": no action "${t}" in registry`};try{let a=await i(s,n),d={ok:a.ok,output:a.output,status:a.status,durationMs:a.durationMs};return a.errors!==void 0&&(d.errors=a.errors),a.ok?{output:d}:{output:d,error:`action "${t}" failed (status=${a.status})`}}catch(a){return{error:`action.run failed: ${a.message}`}}},Mn=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.name??"");if(!t)return{error:`action.builtin "${r.node.id}" needs a "name" (e.g. "http.fetch")`};let n=e.input&&typeof e.input=="object"?e.input:{},{runBuiltin:o,getBuiltin:i}=await import("./builtin-W6KNX7RS.js");if(!i(t))return{error:`action.builtin "${r.node.id}": unknown built-in "${t}"`};try{return{output:await o(t,n)}}catch(s){let a=s?.name==="ZodError"?`validation: ${s.message}`:s?.message||String(s);return{error:`action.builtin "${t}" failed: ${a}`}}},_n=async r=>{let e=r.node.config,t=r.run.context;return typeof e.path=="string"&&e.path?{output:{value:z(t,e.path)}}:e.template&&typeof e.template=="object"?{output:b(e.template,t,{envAllow:r.workflow.envAllow})}:{output:{}}};function Ln(r){if(r!=null){if(typeof r=="number")return new Date(Date.now()+r*6e4).toISOString();if(typeof r=="object"&&r&&"minutes"in r){let e=Number(r.minutes);if(Number.isFinite(e))return new Date(Date.now()+e*6e4).toISOString()}if(typeof r=="string"){let e=/^P(?:([0-9]+)D)?(?:T(?:([0-9]+)H)?(?:([0-9]+)M)?(?:([0-9]+)S)?)?$/.exec(r);if(e){let t=Number(e[1]??0),n=Number(e[2]??0),o=Number(e[3]??0),i=Number(e[4]??0),s=((t*24+n)*60+o)*6e4+i*1e3;if(s>0)return new Date(Date.now()+s).toISOString()}}}}var Hn=async r=>{let e=r.node.config,t=b(e,r.run.context,{envAllow:r.workflow.envAllow}),n=String(t.workflowId??"");if(!n)return{error:`subProcess "${r.node.id}" missing config.workflowId`};let o=r.run.depth??0,i=r.workflow.maxChildDepth??5;if(o+1>=i)return{error:`max child workflow depth ${i} exceeded at ${r.workflow.id} \u2192 ${n} (parent depth ${o})`};let s=e.inputMap,a={};if(s==="*")a={...r.run.context};else if(s&&typeof s=="object")for(let[d,c]of Object.entries(s))c&&typeof c=="object"&&!Array.isArray(c)?a[d]=b(c,r.run.context,{envAllow:r.workflow.envAllow}):typeof c=="string"&&(a[d]={value:S(c,r.run.context,{envAllow:r.workflow.envAllow})});return{paused:!0,pausedAt:{kind:"subProcess",nodeId:r.node.id,childRunId:"",childWorkflowId:n},spawnChild:{workflowId:n,input:a}}},Un=E,Kn=async r=>{let e=r.node.config,t=b(e,r.run.context,{envAllow:r.workflow.envAllow}),n=String(t.name??"");if(!n)return{error:`signal.emit "${r.node.id}" missing config.name`};let o=t.scope==="global"?"global":"workflow",i=t.payload&&typeof t.payload=="object"?t.payload:{};return{output:{emittedAt:new Date().toISOString(),name:n,scope:o,payload:i},emitSignal:{name:n,scope:o,payload:i}}},Bn=async r=>{let e=r.node.config,t=b(e,r.run.context,{envAllow:r.workflow.envAllow}),n=String(t.name??"");if(!n)return{error:`signal.wait "${r.node.id}" missing config.name`};let o=t.scope==="global"?"global":"workflow",i=e.match&&typeof e.match=="object"?e.match:{};return{paused:!0,pausedAt:{kind:"signalWait",nodeId:r.node.id,signalName:n,match:i,scope:o}}},zn=async r=>{let e=r.node.config,t=b(e,r.run.context,{envAllow:r.workflow.envAllow}),n=Ln(t.after??e.after);return n?{paused:!0,pausedAt:{kind:"timerWait",nodeId:r.node.id,fireAt:n}}:{error:`timer.boundary "${r.node.id}" needs config.after (duration or minutes)`}},Jn=async()=>({output:{}}),qn=async r=>{let e=r.node.config,n=(Array.isArray(e.inputs)?e.inputs:[]).map(s=>typeof s=="string"?S(s,r.run.context,{envAllow:r.workflow.envAllow}):s),o=Array.isArray(e.rules)?e.rules:[];for(let s of o){let a=Array.isArray(s.when)?s.when:[];if(a.length!==n.length)continue;let d=!0;for(let c=0;c<a.length;c++)if(!Yn(a[c],n[c])){d=!1;break}if(d)return{output:{...s.output??{},matchedPort:s.to??""},port:s.to}}let i=e.default;return{output:{...i?.output??{},matchedPort:i?.to??""},port:i?.to}};function Yn(r,e){if(r==null||r==="*")return!0;let t=String(r),n=typeof e=="number"?e:String(e??""),o=/^(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/.exec(t);if(o){let i=o[1],s=Number(o[2]),a=typeof n=="number"?n:Number(n);if(Number.isNaN(a))return!1;switch(i){case">":return a>s;case"<":return a<s;case">=":return a>=s;case"<=":return a<=s}}if(t.startsWith("!="))return String(n)!==t.slice(2);if(t.startsWith("/")&&t.endsWith("/")&&t.length>2)try{return new RegExp(t.slice(1,-1)).test(String(n))}catch{return!1}return String(n)===t}var ht={"trigger.channel":E,"trigger.manual":E,"trigger.cron":E,"trigger.hook":E,"trigger.form":Un,agent:Rn,classify:gt,branch:$n,transform:_n,"gateway.parallel":Jn,rule:qn,"action.send":xn,"action.createIssue":Pn,"action.setLabel":On,"action.readLabel":Wn,"action.react":jn,"action.editMessage":Dn,"action.logTime":En,"action.callHTTP":Fn,"action.run":Cn,"action.builtin":Mn,subProcess:Hn,"signal.emit":Kn,"signal.wait":Bn,"timer.boundary":zn,checkpoint:Nn,end:Tn};function be(r){return ht[r]}function ve(r,e){if(typeof e=="string"&&e)return e;let t=r.workflow.nodes.find(i=>i.type.startsWith("trigger."));if(!t)return;let o=r.run.context[t.id]?.accountId;return typeof o=="string"&&o?o:void 0}function Ie(r){for(let e=r.run.history.length-1;e>=0;e--){let t=r.run.history[e],n=r.workflow.nodes.find(o=>o.id===t.nodeId);if(n?.type==="agent")return n.config.agentId??void 0}}function wt(r){if(!r)return{};let e=r.match(/\bRESULT:\s*([a-z][a-z0-9_-]*)/i);if(e)return{result:e[1].toLowerCase()};let t=r.match(/\[(APPROVED|REJECTED|CHANGES[-_]REQUESTED|DONE|FAILED|SKIPPED)\]/i);return t?{result:t[1].toLowerCase().replace("_","-")}:{}}function Gn(r){let{result:e}=wt(r);if(!r)return{result:e};let t=r.match(/```(?:json)?\s*([\s\S]*?)```/);if(!t)return{result:e};try{return{result:e,json:JSON.parse(t[1])}}catch{return{result:e}}}var F=class{handlers=new Set;subscribe(e){return this.handlers.add(e),()=>this.handlers.delete(e)}emit(e){for(let t of this.handlers)try{Promise.resolve(t(e)).catch(()=>{})}catch{}}};function G(r,e){if(r.name!==e.name||r.scope==="workflow"&&r.workflowId!==e.workflowId)return!1;for(let[t,n]of Object.entries(r.match??{}))if(!(n===void 0||n===""||n==="*")&&e.payload[t]!==n)return!1;return!0}function Vn(r,e,t=Date.now){return{ts:t(),source:"workflow",sourceEventId:`${r.workflowId}:${r.eventId}`,project:r.project,subject:`workflow:${r.workflowId}:entity:${r.entityRef.backend}:${r.entityRef.id}`,intent:`workflow.${r.triggerSource}`,rawJson:e}}function Zn(r){return r.claimed&&r.runId?{agentId:`workflow-run:${r.runId}`,outcome:"dispatched",reason:r.reason??"claimed"}:r.claimed&&!r.runId?{agentId:null,outcome:"halted",reason:r.reason??"claimed-but-no-run"}:{agentId:null,outcome:"halted",reason:r.reason??"not-claimed"}}function Xn(r){return{decidedBy:"workflow-dispatcher",decide:()=>({agentId:r.agentId,outcome:r.outcome==="deduped"?"halted":r.outcome,reason:r.outcome==="deduped"?`legacy-dedup: ${r.reason??""}`.trim():r.reason??null})}}function yt(r,e,t,n,o=Date.now){let i=Vn(e,t,o),s=Zn(n),a=Xn(s),d=Me(r,i,a,o);return _e(r,"workflow",d,s,o),d}var Qn=4e3,er=8,Se=class{store;runs;nodeId;forwarder;channels;agents;log;timers;signals;events;ackTypingTimers=new Map;commitChains=new Map;constructor(e){this.store=e.store,this.runs=e.runs,this.nodeId=e.nodeId,this.forwarder=e.forwarder,this.channels=e.channels,this.agents=e.agents,this.log=e.log??(()=>{}),this.timers=e.timers??new ie({log:t=>this.log(t)}),this.signals=e.signals??new F,this.events=e.events,this.timers.onFire(t=>this.resumeFromTimer(t)),this.signals.subscribe(t=>this.resumeFromSignal(t))}emitRunEvent(e){if(this.events)try{this.events.publish({kind:"run",runId:e.runId,workflowId:e.workflowId,nodeId:e.nodeId,phase:e.phase,status:e.status,note:e.note,homeNode:e.homeNode,rootId:e.rootId})}catch{}}async commit(e,t){let o=(this.commitChains.get(e)??Promise.resolve()).then(()=>t(),()=>t());return this.commitChains.set(e,o.then(()=>{},()=>{})),o}emitSignal(e){let t={name:e.name,scope:e.scope??"global",workflowId:e.workflowId??"",payload:e.payload??{},emittedAt:new Date().toISOString()};if(this.signals.emit(t),this.events)try{this.events.publish({kind:"signal",name:t.name,scope:t.scope,workflowId:t.workflowId||void 0,payload:t.payload})}catch{}return t}async resumeFromSignal(e){let t=this.runs.list({limit:500});for(let n of t){if(n.status!=="paused"||!n.pausedAt||n.pausedAt.kind!=="signalWait")continue;let o={name:n.pausedAt.signalName,scope:n.pausedAt.scope,workflowId:n.workflowId,match:n.pausedAt.match??{}};if(!G(o,e))continue;let i=this.store.list().find(s=>s.id===n.workflowId);i&&(await this.commit(n.id,()=>{let s=this.runs.get(n.id);if(!s||s.status!=="paused"||!s.pausedAt||s.pausedAt.kind!=="signalWait"||!G({name:s.pausedAt.signalName,scope:s.pausedAt.scope,workflowId:s.workflowId,match:s.pausedAt.match??{}},e))return;let a=N(i,s.pausedAt.nodeId),d=a?i.edges.filter(u=>u.from===a.id).map(u=>u.to):[],c={receivedAt:new Date().toISOString(),name:e.name,payload:e.payload};this.runs.recordExecution({runId:s.id,entry:{at:c.receivedAt,nodeId:s.pausedAt.nodeId,inputKeys:[],status:"resumed",output:c,idempotencyKey:T(s.id,s.pausedAt.nodeId,`signal:${e.name}:${e.emittedAt}`)},nextPending:d,status:"running",pausedAt:null,context:{...s.context,[s.pausedAt.nodeId]:c}}),this.log(`[workflow:${i.id}] run ${s.id} resumed from signal "${e.name}"`),this.emitRunEvent({runId:s.id,workflowId:i.id,nodeId:s.pausedAt.nodeId,phase:"resumed",status:"running",note:`signal:${e.name}`,rootId:s.eventRootId})}),this.walk(i,n.id,`signal:${e.name}`).catch(s=>this.log(`[workflow:${i.id}] walk-after-signal failed: ${s.message}`)))}}async resumeFromTimer(e){let t=this.store.list().find(n=>n.id===(this.runs.get(e.runId)?.workflowId??""));t&&(await this.commit(e.runId,()=>{let n=this.runs.get(e.runId);if(!n||n.status!=="paused"||!n.pausedAt||n.pausedAt.kind!=="timerWait"||n.pausedAt.nodeId!==e.nodeId)return;let o=N(t,e.nodeId),i=o?t.edges.filter(d=>d.from===o.id).map(d=>d.to):[],s=new Date().toISOString(),a={firedAt:s,scheduledFor:e.fireAt};this.runs.recordExecution({runId:n.id,entry:{at:s,nodeId:e.nodeId,inputKeys:[],status:"resumed",output:a,idempotencyKey:T(n.id,e.nodeId,`timer:${e.id}`)},nextPending:i,status:"running",pausedAt:null,context:{...n.context,[e.nodeId]:a}}),this.log(`[workflow:${t.id}] run ${n.id} resumed from timer "${e.nodeId}" (fired ${s})`),this.emitRunEvent({runId:n.id,workflowId:t.id,nodeId:e.nodeId,phase:"resumed",status:"running",note:`timer:${e.id}`,rootId:n.eventRootId})}),this.walk(t,e.runId,`timer:${e.id}`).catch(n=>this.log(`[workflow:${t.id}] walk-after-timer failed: ${n.message}`)))}async dispatchWorkflow(e){let t=this.store.list().find(s=>s.id===e.workflowId);if(!t)return this.log(`[workflows] dispatchWorkflow: workflow "${e.workflowId}" not found`),{claimed:!1,run:null};let o=t.nodes.find(s=>s.type.startsWith("trigger."))?.config??{},i={source:e.trigger?.source??o.source??"hook",project:e.trigger?.project,repo:e.trigger?.repo,chat:e.trigger?.chat,labels:e.trigger?.labels};return this.dispatchOne(t,e.entityRef,e.event,i)}startChannelAck(e,t){let n=String(t.channel??""),o=String(t.chatId??"");if(!n||!o)return;let i=this.channels[n];if(!i)return;let s=typeof t.accountId=="string"?t.accountId:void 0,a=t.event,d=typeof a?.id=="string"?a.id:a?.id!=null?String(a.id):void 0;if(d&&i.react)try{Promise.resolve(i.react(o,d,"\u{1F440}",s)).catch(()=>{})}catch{}if(this.ackTypingTimers.has(e)||!i.sendTyping)return;let c=()=>{try{Promise.resolve(i.sendTyping(o,s)).catch(()=>{})}catch{}};c();let u=setInterval(c,Qn);this.ackTypingTimers.set(e,u)}stopChannelAck(e){let t=this.ackTypingTimers.get(e);t&&(clearInterval(t),this.ackTypingTimers.delete(e))}async dispatch(e){let t=this.matchByTrigger(e.trigger,e.fromRemote),o=t.some(a=>a.fanOut)?t:t.slice(0,1),i=[],s=[];for(let a of o){let d=await this.dispatchOne(a,e.entityRef,e.event,e.trigger);d.claimed&&i.push(a),d.run&&s.push(d.run)}return!e.fromRemote&&this.forwarder?.broadcastTrigger&&Promise.resolve(this.forwarder.broadcastTrigger({trigger:e.trigger,entityRef:e.entityRef,event:e.event})).catch(a=>this.log(`[mesh-broadcast] ${a?.message??a}`)),{claimed:i,runs:s}}matchByTrigger(e,t){let n=this.store.list(),o=[];for(let i of n){if(i.state&&i.state!=="active")continue;if(t){if(!i.mesh?.allowRemote)continue;let c=i.mesh.peers;if(c&&c.length>0&&!c.includes(t.peer))continue}let s=i.nodes.find(c=>c.type.startsWith("trigger."));if(!s)continue;let a=s.config;if(a.source!==e.source||i.project&&e.project&&i.project!==e.project)continue;let d=a.filter;if(d){if(d.project&&d.project!=="*"&&d.project!==e.project||d.repo&&d.repo!=="*"&&d.repo!==e.repo||d.chat&&d.chat!=="*"&&V(e.source,d.chat)!==V(e.source,e.chat))continue;if(d.labels?.length){let c=new Set(e.labels??[]);if(!d.labels.some(p=>c.has(p)))continue}}o.push(i)}return o.sort((i,s)=>s.priority-i.priority||i.id.localeCompare(s.id))}async dispatchOne(e,t,n,o){let i=await this.dispatchOneLegacy(e,t,n,o);if(Ce("workflow")!=="off")try{yt(De(),{workflowId:e.id,eventId:n.id,triggerSource:o.source,project:o.project??null,entityRef:t},JSON.stringify({event:n,trigger:o,entityRef:t}),{claimed:i.claimed,runId:i.run?.id??null})}catch(s){this.log(`[ledger] workflow ${e.id} run ${i.run?.id??"?"} record failed: ${s?.message??s}`)}return i}async dispatchOneLegacy(e,t,n,o){let i=this.runs.getActiveByEntity(t),s=i?this.runs.getHomeNodeByEntity(t):null;if(i&&s&&s!==this.nodeId){if(!this.forwarder)return this.log(`[workflow:${e.id}] run ${i} home'd on "${s}" but no forwarder \u2014 dropping`),{claimed:!1,run:null};try{await this.forwarder.forwardTransition(s,{workflowId:e.id,event:n,entityRef:t})}catch(d){this.log(`[workflow:${e.id}] forward to "${s}" failed: ${d.message}`)}return{claimed:!0,run:null}}let a=i?this.runs.get(i):null;if(a)if(a.status==="paused"&&a.pausedAt){if(a.pausedAt.kind!=="checkpoint")return this.log(`[workflow:${e.id}] run ${a.id} paused on ${a.pausedAt.kind} \u2014 channel event bypasses workflow`),{claimed:!1,run:null};if(!nr(a.pausedAt.resumeMatch,o,n))return this.log(`[workflow:${e.id}] run ${a.id} paused but event doesn't match resumeMatch \u2014 dropping`),{claimed:!1,run:null};let d=N(e,a.pausedAt.nodeId),c=d?e.edges.filter(h=>h.from===d.id).map(h=>h.to):[],u={at:new Date().toISOString(),nodeId:a.pausedAt.nodeId,inputKeys:[],status:"resumed",output:{event:n.payload},idempotencyKey:T(a.id,a.pausedAt.nodeId,`resume:${n.id}`)},p={...a.context,[a.pausedAt.nodeId]:{event:n.payload}},g=a.pausedAt.checkpointName,f=this.runs.recordExecution({runId:a.id,entry:u,nextPending:c,status:"running",pausedAt:null,context:p});f&&(a=f),this.log(`[workflow:${e.id}] run ${a.id} resumed from checkpoint "${g}"`),o.source.endsWith("-message")&&this.startChannelAck(a.id,n.payload)}else return a.status==="running"?(this.log(`[workflow:${e.id}] run ${a.id} already running; dropping concurrent event ${n.id}`),{claimed:!0,run:null}):(this.log(`[workflow:${e.id}] run ${a.id} is ${a.status}; dropping event ${n.id}`),{claimed:!1,run:null});else{let d=J(e);if(!d)return this.log(`[workflow:${e.id}] no trigger node found`),{claimed:!1,run:null};a=this.runs.create({workflowId:e.id,initialPending:d.pending,entityRef:t,initialContext:{[d.triggerId]:n.payload}}),this.log(`[workflow:${e.id}] run ${a.id} created from trigger "${d.triggerId}" for ${t.id}`),this.emitRunEvent({runId:a.id,workflowId:e.id,phase:"created",status:a.status,homeNode:a.homeNode,rootId:a.eventRootId}),o.source.endsWith("-message")&&this.startChannelAck(a.id,n.payload)}return this.walk(e,a.id,n.id),{claimed:!0,run:a}}async walk(e,t,n){let o=this.runs.get(t)?.eventRootId,i=()=>this.walkInner(e,t,n);try{await(o?Fe({rootId:o},i):i())}finally{this.stopChannelAck(t)}}async walkInner(e,t,n){let o=this.runs.get(t);if(o)for(;o.status==="running"&&o.pending.length>0;){let i=o.pending.slice(0,er);await Promise.allSettled(i.map(a=>this.executeNodeAndCommit(e,t,a,n)));let s=this.runs.get(t);if(!s||(o=s,o.status!=="running"))return}}async executeNodeAndCommit(e,t,n,o){let i=T(t,n,o),s=await this.commit(t,()=>{let m=this.runs.get(t);if(!m)return{kind:"done"};if(m.status!=="running")return{kind:"done"};let y=N(e,n);if(!y)return this.log(`[workflow:${e.id}] missing node "${n}" \u2014 marking run failed`),this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:n,inputKeys:[],status:"failed",idempotencyKey:i,note:"node definition missing from workflow"},nextPending:m.pending.filter(A=>A!==n),status:"failed"}),{kind:"done"};let w=be(y.type);return w?m.history.some(A=>A.idempotencyKey===i)?(this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:n,inputKeys:[],status:"skipped",idempotencyKey:i+"_dedup",note:"duplicate execution dropped"},nextPending:m.pending.filter(A=>A!==n)}),{kind:"done"}):{kind:"go",run:m,node:y,handler:w}:(this.log(`[workflow:${e.id}] no handler for node type "${y.type}"`),this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:n,inputKeys:[],status:"failed",idempotencyKey:i,note:`no handler for node type "${y.type}"`},nextPending:m.pending.filter(A=>A!==n),status:"failed"}),{kind:"done"})});if(s.kind==="done")return;let{run:a,node:d,handler:c}=s,u=e.edges.filter(m=>m.to===n).map(m=>m.from),p;if(d.type!=="agent"){let m=te();if(m)try{p=Le(m,{agentId:`workflow:${d.type}`,channel:"workflow",chatId:`${e.id}:${n}`,workflowRunId:t,workflowId:e.id,workflowNodeId:n,messagePreview:`${d.type} ${n}`})}catch{}}let g=d.retry??{maxAttempts:1,backoffMs:1e3},f={error:"retry-loop did not run"},h=0;for(;h<g.maxAttempts;){h++;try{f=await c({workflow:e,run:a,node:d,channels:this.channels,agents:this.agents,forwardChannelSend:this.forwarder?.forwardChannelSend?.bind(this.forwarder),log:this.log})}catch(m){this.log(`[workflow:${e.id}] handler "${d.type}" threw: ${m.message}`),f={error:m.message}}if(!f.error||f.paused)break;if(h<g.maxAttempts){let m=g.backoffMs*Math.pow(2,h-1);this.log(`[workflow:${e.id}] node "${n}" failed (attempt ${h}/${g.maxAttempts}): ${f.error.slice(0,120)} \u2014 retrying in ${m}ms`),await new Promise(y=>setTimeout(y,m))}}if(p){let m=te();if(m)try{He(m,p,{status:f.error?"error":"ok",error:f.error??null})}catch{}}await this.commit(t,async()=>{let m=this.runs.get(t);if(!m)return;let y=new Date().toISOString(),w=m.pending.filter(k=>k!==n);if(f.error){let k=m.status==="running"?"failed":void 0;this.runs.recordExecution({runId:t,entry:{at:y,nodeId:n,inputKeys:u,status:"failed",idempotencyKey:i,note:f.error.slice(0,200)},nextPending:w,status:k}),this.emitRunEvent({runId:t,workflowId:e.id,nodeId:n,phase:"failed",status:k??m.status,note:f.error.slice(0,200)});return}if(f.paused&&f.pausedAt){let k=f.pausedAt,P=null;if(f.spawnChild&&k.kind==="subProcess"){if(P=await this.spawnChild({parent:m,parentNodeId:n,childWorkflowId:f.spawnChild.workflowId,input:f.spawnChild.input}),!P){this.runs.recordExecution({runId:t,entry:{at:y,nodeId:n,inputKeys:u,status:"failed",idempotencyKey:i,note:`subProcess: child workflow "${f.spawnChild.workflowId}" not found`},nextPending:w,status:"failed"});return}k={...k,childRunId:P.id}}if(this.runs.recordExecution({runId:t,entry:{at:y,nodeId:n,inputKeys:u,status:"paused",idempotencyKey:i},nextPending:w,status:"paused",pausedAt:k}),this.emitRunEvent({runId:t,workflowId:e.id,nodeId:n,phase:"paused",status:"paused",note:k.kind}),P&&this.kickChildWalk(P),k.kind==="timerWait")try{this.timers.schedule({runId:t,workflowId:e.id,nodeId:k.nodeId,fireAt:k.fireAt,cancelKey:`${t}:${k.nodeId}`})}catch(xe){this.log(`[workflow:${e.id}] timer schedule failed: ${xe.message}`)}return}let A=f.output??{},Tt={...m.context,[n]:A},{nextPending:Nt}=we({workflow:e,fromNodeId:n,selectedPort:f.port}),ee=[],C={...m.joinCounters??{}};for(let k of Nt){let P=N(e,k);if(!(P?.type==="gateway.parallel"&&String(P.config?.mode??"fanOut")==="join")){ee.push(k);continue}let _=C[k]??[];_.includes(n)||_.push(n),C[k]=_;let jt=e.edges.filter(Dt=>Dt.to===k).length;_.length>=jt&&(ee.push(k),delete C[k])}let Ot=[...w,...ee],M=d.type==="end",Wt=m.status==="running"?M?String(d.config.status??"completed"):"running":void 0,O=this.runs.recordExecution({runId:t,entry:{at:y,nodeId:n,inputKeys:u,status:"ok",output:A,idempotencyKey:i},nextPending:M?[]:Ot,status:Wt,context:Tt,joinCounters:C});this.emitRunEvent({runId:t,workflowId:e.id,nodeId:n,phase:M?"completed":"ok",status:O?.status??m.status}),f.emitSignal&&this.emitSignal({name:f.emitSignal.name,scope:f.emitSignal.scope,workflowId:e.id,payload:f.emitSignal.payload}),M&&O&&O.parentRunId&&O.parentNodeId&&this.resumeParent({parentRunId:O.parentRunId,parentNodeId:O.parentNodeId,childRun:O}).catch(k=>this.log(`[workflow:${e.id}] resumeParent failed: ${k.message}`))})}async spawnChild(e){let t=this.store.list().find(a=>a.id===e.childWorkflowId);if(!t)return null;let n=J(t);if(!n)return this.log(`[workflow:${t.id}] no trigger node \u2014 cannot spawn as child`),null;let o={...e.input};o[n.triggerId]={...o[n.triggerId]??{},parentRunId:e.parent.id,parentNodeId:e.parentNodeId};let i={backend:"agentx-internal",id:`subprocess:${e.parent.id}:${e.parentNodeId}`},s=this.runs.create({workflowId:t.id,initialPending:n.pending,entityRef:i,initialContext:o,parentRunId:e.parent.id,parentNodeId:e.parentNodeId,rootRunId:e.parent.rootRunId??e.parent.id,depth:(e.parent.depth??0)+1});return this.log(`[workflow:${t.id}] child run ${s.id} spawned from ${e.parent.id}/${e.parentNodeId} (depth ${s.depth})`),s}kickChildWalk(e){let t=this.store.list().find(n=>n.id===e.workflowId);t&&this.walk(t,e.id,`spawn:${e.parentRunId}:${e.parentNodeId}`).catch(n=>this.log(`[workflow:${t.id}] child walk failed: ${n.message}`))}async resumeParent(e){let t=this.runs.get(e.parentRunId);if(!t)return;let n=this.store.list().find(o=>o.id===t.workflowId);n&&(await this.commit(e.parentRunId,()=>{let o=this.runs.get(e.parentRunId);if(!o||o.status!=="paused"||!o.pausedAt||o.pausedAt.kind!=="subProcess"||o.pausedAt.nodeId!==e.parentNodeId||o.pausedAt.childRunId!==e.childRun.id)return;let i=N(n,e.parentNodeId),s=i?n.edges.filter(d=>d.from===i.id).map(d=>d.to):[],a={childRunId:e.childRun.id,status:e.childRun.status,output:tr(e.childRun)};this.runs.recordExecution({runId:o.id,entry:{at:new Date().toISOString(),nodeId:e.parentNodeId,inputKeys:[],status:"resumed",output:a,idempotencyKey:T(o.id,e.parentNodeId,`child:${e.childRun.id}`)},nextPending:s,status:"running",pausedAt:null,context:{...o.context,[e.parentNodeId]:a}}),this.log(`[workflow:${n.id}] parent run ${o.id} resumed from subProcess child ${e.childRun.id}`),this.emitRunEvent({runId:o.id,workflowId:n.id,nodeId:e.parentNodeId,phase:"resumed",status:"running",note:`child:${e.childRun.id}`,rootId:o.eventRootId})}),this.walk(n,e.parentRunId,`child:${e.childRun.id}`))}};function tr(r){for(let e=r.history.length-1;e>=0;e--){let t=r.history[e];if(t.status==="ok"&&t.output&&Object.keys(t.output).length>0)return t.output}return{}}function nr(r,e,t){let n=i=>{let s=r[i];if(s===void 0||s===""||s==="*")return!0;if(Array.isArray(s)){let a=new Set(e.labels??[]);return s.some(d=>a.has(String(d)))}return i==="chat"?V(e.source,String(s))===V(e.source,e.chat):e[i]===s};if(!n("source")||!n("project")||!n("repo")||!n("chat"))return!1;let o=r.eventIdLike;return!(typeof o=="string"&&o&&!t.id.includes(o))}function V(r,e){return e==null?"":r==="whatsapp-message"?e.replace(/@s\.whatsapp\.net$|@g\.us$/i,"").replace(/[\s+()]/g,""):e}function rr(r){return{"pre:channel-message":async e=>{let t=e.msg;if(!t)return{};let n=or(t.channel);if(!n)return{};let o=t.group?.id??t.sender.id,i={backend:t.channel,id:`${t.channel}:${o}`},{claimed:s}=await r.dispatch({trigger:{source:n,chat:o},entityRef:i,event:{id:`${t.channel}:${t.accountId}:${t.id}`,payload:ir(t)}});return s.length===0?{}:s.every(d=>d.nodes.find(u=>u.type.startsWith("trigger."))?.config?.passthrough===!0)?{}:{blocked:!0,message:`handled by workflow${s.length>1?"s":""}: ${s.map(d=>d.id).join(", ")}`}},"on:gitlab-issue":async e=>{let t=e.project,n=e.iid,o=e.issueEvent;if(!t||n===void 0)return{};let i=Array.isArray(o?.object_attributes?.labels)?o.object_attributes.labels.map(d=>typeof d=="string"?d:d?.title).filter(Boolean):o?.labels?.map(d=>d?.title)??[],s=o?.assignees??o?.object_attributes?.assignee_ids??[],a={backend:"gitlab",id:`${t}#${n}`};return await r.dispatch({trigger:{source:"gitlab-issue",project:t,labels:i},entityRef:a,event:{id:`gitlab-issue:${t}:${n}:${o?.object_attributes?.updated_at||o?.object_attributes?.action||"evt"}`,payload:{issue:{iid:n,title:o?.object_attributes?.title,description:o?.object_attributes?.description,url:o?.object_attributes?.url,action:o?.object_attributes?.action,labels:i,assignees:s},project:t,channel:"gitlab",chatId:`${t}:issue:${n}`}}}),{}},"on:gitlab-mr":async e=>{let t=e.project,n=e.iid,o=e.mrEvent;if(!t||n===void 0)return{};let i=Array.isArray(e.labels)?e.labels:Array.isArray(o?.object_attributes?.labels)?o.object_attributes.labels.map(c=>typeof c=="string"?c:c?.title).filter(Boolean):[],s=o?.assignees??o?.object_attributes?.assignee_ids??[],a=o?.reviewers??[],d={backend:"gitlab",id:`${t}!${n}`};return await r.dispatch({trigger:{source:"gitlab-mr",project:t,labels:i},entityRef:d,event:{id:`gitlab-mr:${t}:${n}:${o?.object_attributes?.updated_at||o?.object_attributes?.action||"evt"}`,payload:{mr:{iid:n,title:e.title,description:e.description,url:e.url,action:e.action,state:e.state,source_branch:e.source_branch,target_branch:e.target_branch,labels:i,assignees:s,reviewers:a},project:t,channel:"gitlab",chatId:`${t}:merge_request:${n}`,iid:n,title:e.title,description:e.description,url:e.url,action:e.action,state:e.state,source_branch:e.source_branch,target_branch:e.target_branch,labels:i}}}),{}},"on:gitlab-note":async e=>{let t=e.project,n=e.noteId,o=e.noteableType,i=e.noteableIid,s=e.text,a=e.authorUsername,d=e.mentions??[];if(!t||!n||!o||!i)return{};let c=o==="merge_request"?{backend:"gitlab",id:`${t}!${i}`}:{backend:"gitlab",id:`${t}#${i}`};return await r.dispatch({trigger:{source:"gitlab-note",project:t},entityRef:c,event:{id:`gitlab-note:${t}:${o}:${i}:${n}`,payload:{note:{id:n,text:s,author:a,mentions:d,noteableType:o,noteableIid:i,noteableTitle:e.noteableTitle},project:t,channel:"gitlab",chatId:`${t}:${o}:${i}`,noteId:n,noteableType:o,noteableIid:i,text:s,author:a,mentions:d}}}),{}},"on:gitlab-pipeline":async e=>{let t=e.project,n=e.pipelineId,o=e.status,i=e.ref;if(!t||!o)return{};let a=e.raw?.merge_request?.iid;if(!a)return{};let d={backend:"gitlab",id:`${t}!${a}`};return await r.dispatch({trigger:{source:"gitlab-pipeline",project:t},entityRef:d,event:{id:`gitlab-pipeline:${t}:${n}:${o}`,payload:{pipeline:{id:n,status:o,ref:i},project:t,channel:"gitlab",chatId:`${t}:merge_request:${a}`}}}),{}}}}function or(r){switch(r){case"telegram":return"telegram-message";case"whatsapp":return"whatsapp-message";case"discord":return"discord-message";case"slack":return"slack-message";default:return null}}function ir(r){let e=r.group?.id??r.sender.id;return{channel:r.channel,chatId:e,accountId:r.accountId,text:r.text,fromJid:r.sender.id,sender:{id:r.sender.id,name:r.sender.name,username:r.sender.username},contact:r.channelMeta?.facts?{facts:r.channelMeta.facts}:void 0,group:r.group?{id:r.group.id,name:r.group.name}:void 0,channelMeta:r.channelMeta,replyTo:r.replyTo,replyToText:r.replyToText,media:r.media,event:{id:r.id,timestamp:r.timestamp?.toISOString?.()??new Date().toISOString()}}}var Z=r=>r.trim().toLowerCase().replace(/^@/,"");function sr(r){let e=typeof r.author=="string"?r.author:typeof r.authorUsername=="string"?r.authorUsername:void 0;if(e)return Z(e);let n=r.payload?.sender?.login;return typeof n=="string"&&n?Z(n):void 0}function ar(r,e){let t=typeof e.project=="string"?e.project:"";if(r==="on:gitlab-issue"||r==="on:gitlab-mr")return!t||e.iid==null?void 0:`gitlab:${t}${r==="on:gitlab-issue"?"#":"!"}${String(e.iid)}`;if(r==="on:gitlab-note"){let n=e.noteableIid!=null?String(e.noteableIid):"",o=typeof e.noteableType=="string"?e.noteableType:"";return!t||!n||!o?void 0:`gitlab:${t}${o==="issue"?"#":"!"}${n}`}if(r==="on:github-issue"||r==="on:github-pr"){let n=e.payload??{},o=typeof e.repo=="string"?e.repo:n.repository?.full_name,i=e.number??n.issue?.number??n.pull_request?.number;return typeof o!="string"||!o||i==null?void 0:`github:${o}#${String(i)}`}}function dr(r){let e=new Set;for(let t of r.nodes){let n=t.type==="agent"?t.config.agentId:void 0;typeof n=="string"&&n&&e.add(n)}return[...e]}var X=class{constructor(e=2e3){this.maxKeys=e}fires=new Map;tryFire(e,t,n,o=Date.now()){let i=(this.fires.get(e)??[]).filter(s=>o-s<n);if(i.length>=t)return this.fires.set(e,i),!1;for(i.push(o),this.fires.delete(e),this.fires.set(e,i);this.fires.size>this.maxKeys;){let s=this.fires.keys().next().value;if(s===void 0)break;this.fires.delete(s)}return!0}get size(){return this.fires.size}};function Ae(r,e,t){let n=r.logged??(r.logged=new Set);n.has(e)||(n.add(e),r.log(t))}function kt(r,e,t,n,o){let i=sr(t);if(i&&Array.isArray(n?.ignoreAuthors)&&n.ignoreAuthors.length>0&&n.ignoreAuthors.map(Z).includes(i))return{skip:!0,reason:"ignored-author",detail:`author @${i} is in filter.ignoreAuthors`};if(n?.skipSelfAuthored===!0){let a=dr(r),d=typeof t.authorAgent=="string"?t.authorAgent:void 0;if(d&&a.includes(d))return{skip:!0,reason:"self-authored",detail:`author @${i??"?"} is agent "${d}" which this workflow runs`};if(i){let c=new Set(a.flatMap(u=>(o.forgeUsernames?.(u)??[]).map(Z)));if(c.has(i))return{skip:!0,reason:"self-authored",detail:`author @${i} is this workflow's own bot identity`};a.length===0?Ae(o,`noagents:${r.id}`,`[workflows] ${r.id} has no agent node \u2014 self-authored skip can't resolve a bot identity; only filter.ignoreAuthors applies`):c.size===0&&!("authorAgent"in t)&&Ae(o,`noident:${r.id}:${e}`,`[workflows] ${r.id} no forge username known for agent(s) ${a.join(", ")} on ${e} \u2014 self-authored skip inactive; only filter.ignoreAuthors applies`)}}let s=n?.maxFiresPerTarget;if(s&&typeof s.count=="number"&&s.count>0){let a=ar(e,t);if(a){let d=typeof s.windowMinutes=="number"&&s.windowMinutes>0?s.windowMinutes:60,c=o.now?.()??Date.now();if(!o.fireWindow.tryFire(`${r.id}|${a}`,s.count,d*6e4,c))return{skip:!0,reason:"chain-limit",detail:`${a} already fired ${s.count}x within ${d}m (filter.maxFiresPerTarget)`}}else Ae(o,`notarget:${r.id}:${e}`,`[workflows] ${r.id} filter.maxFiresPerTarget has no target key for ${e} \u2014 limit not applied`)}return{skip:!1}}function cr(r){let e=r.store.list(),t={fireWindow:new X,log:r.log,forgeUsernames:r.forgeUsernames,logged:new Set},n=0,o=0;for(let i of e){if(i.state&&i.state!=="active"){r.log(`[workflows] ${i.id} state=${i.state} \u2014 skipping trigger registration`);continue}let s=i.nodes.find(a=>a.type.startsWith("trigger."));if(s){if(s.type==="trigger.cron"){let a=s.config;if(!a.spec){r.log(`[workflows] ${i.id} trigger.cron missing config.spec \u2014 skipping`);continue}ur({workflowId:i.id,triggerNodeId:s.id,spec:a.spec,timezone:a.timezone??"UTC"},r.dispatcher,r.log),n++}else if(s.type==="trigger.hook"){let a=s.config;if(!a.event||!a.event.startsWith("on:")){r.log(`[workflows] ${i.id} trigger.hook config.event must start with "on:" \u2014 skipping`);continue}r.hooks.registerHandler(a.event,`workflows:${i.id}`,async d=>{try{let c=typeof d.project=="string"?d.project:void 0;if(i.project&&c&&i.project!==c)return{};if(a.filter){if(Array.isArray(a.filter.topic)&&a.filter.topic.length>0){let h=typeof d.topic=="string"?d.topic.toLowerCase():void 0;if(!h||!a.filter.topic.map(m=>m.toLowerCase()).includes(h))return{}}if(Array.isArray(a.filter.action)&&a.filter.action.length>0){let h=typeof d.action=="string"?d.action:void 0;if(!h||!a.filter.action.includes(h))return{}}if(Array.isArray(a.filter.mentions)&&a.filter.mentions.length>0){let h=Array.isArray(d.mentions)?d.mentions.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.mentions.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>h.includes(w)))return{}}if(Array.isArray(a.filter.noteableType)&&a.filter.noteableType.length>0){let h=typeof d.noteableType=="string"?d.noteableType.toLowerCase():void 0,m=a.filter.noteableType.map(y=>y.toLowerCase());if(!h||!m.includes(h))return{}}if(Array.isArray(a.filter.assigneesAdded)&&a.filter.assigneesAdded.length>0){let h=Array.isArray(d.assigneesAdded)?d.assigneesAdded.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.assigneesAdded.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>h.includes(w)))return{}}if(Array.isArray(a.filter.reviewersAdded)&&a.filter.reviewersAdded.length>0){let h=Array.isArray(d.reviewersAdded)?d.reviewersAdded.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.reviewersAdded.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>h.includes(w)))return{}}if(Array.isArray(a.filter.labelsAdded)&&a.filter.labelsAdded.length>0){let h=Array.isArray(d.labelsAdded)?d.labelsAdded.map(w=>w.toLowerCase()):[];if(!a.filter.labelsAdded.map(w=>w.toLowerCase()).some(w=>h.includes(w)))return{}}}let u=kt(i,a.event,d,a.filter,t);if(u.skip){if(r.log(`[workflows] ${i.id} skipping ${a.event} (${u.reason}): ${u.detail}`),a.passthrough)return{};let h=d.__workflowClaimed;return{modified:{__workflowClaimed:[...Array.isArray(h)?h:[],i.id]}}}let p=lr(i.id,a.event,d);if(await r.dispatcher.dispatchWorkflow({workflowId:i.id,entityRef:{backend:"hook",id:p},event:{id:`hook:${a.event}:${Date.now().toString(36)}`,payload:{hookEvent:a.event,...d}}}),a.passthrough)return{};let g=d.__workflowClaimed;return{modified:{__workflowClaimed:[...Array.isArray(g)?g:[],i.id]}}}catch(c){return r.log(`[workflows] ${i.id} hook dispatch failed: ${c.message}`),{}}},60),o++}}}return{cronTimers:n,hookSubscribers:o}}function lr(r,e,t){let n=typeof t.project=="string"?t.project:"",o=t.iid!=null?String(t.iid):"";if(e==="on:gitlab-issue"&&n&&o)return`${r}:${e}:${n}#${o}`;if(e==="on:gitlab-mr"&&n&&o)return`${r}:${e}:${n}!${o}`;if(e==="on:gitlab-pipeline"&&n){let i=t.pipelineId!=null?String(t.pipelineId):"";if(i)return`${r}:${e}:${n}@pipeline:${i}`}return`${r}:${e}:${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function ur(r,e,t){let n=()=>{let o;try{o=Ue(r.spec,new Date,r.timezone)}catch(s){t(`[workflows] ${r.workflowId} cron spec invalid: ${s.message}`);return}let i=Math.max(1e3,o.getTime()-Date.now());setTimeout(()=>{(async()=>{let s=`cron:${r.workflowId}:${o.toISOString()}`;try{await e.dispatchWorkflow({workflowId:r.workflowId,trigger:{source:"cron"},entityRef:{backend:"cron",id:`${r.workflowId}@${o.toISOString()}`},event:{id:s,payload:{now:o.toISOString(),spec:r.spec,workflowId:r.workflowId}}})}catch(a){t(`[workflows] ${r.workflowId} cron dispatch failed: ${a.message}`)}finally{n()}})()},i)};n()}function bt(r){return r.nodes.find(n=>n.type.startsWith("trigger."))?.config?.inputSchema??null}function vt(r,e){if(!r||!e?.properties)return{};let t=r.match(/^([^:]+\/[^:]+):([^:]+):(.+)$/);if(!t)return{};let[,n,o,i]=t,s={};if(e.properties.project&&(s.project=n),o==="push"){let a=i.match(/^refs\/heads\/(.+)$/);a&&e.properties.ref&&(s.ref=a[1])}else{let a=Number(i);Number.isFinite(a)&&(e.properties.id&&(s.id=a),e.properties.iid&&(s.iid=a),e.properties.mrId&&(s.mrId=a),e.properties.issueId&&(s.issueId=a),e.properties.prId&&(s.prId=a))}return s}function It(r,e){if(!r?.properties)return e;let t={...e};for(let[n,o]of Object.entries(r.properties))t[n]===void 0&&o&&"default"in o&&(t[n]=o.default);return t}function St(r,e){return!r?.required||!Array.isArray(r.required)?[]:r.required.filter(t=>{let n=e[t];return n===void 0||n===""||n===null})}function fr(r,e){let t=bt(r);if(!t?.properties){let d={};for(let[c,u]of Object.entries(e))u!==void 0&&(d[c]=u);return{inputs:d,missing:[],filledFrom:{passthrough:Object.keys(d),chatId:[],defaults:[]}}}let n={};for(let d of["message","agentId","channel","chatId","senderId","senderUsername"])t.properties[d]&&e[d]!==void 0&&(n[d]=e[d]);let o=vt(e.chatId,t),i={...n,...o},s={...i};i=It(t,i);let a=Object.keys(i).filter(d=>s[d]===void 0&&i[d]!==void 0);return{inputs:i,missing:St(t,i),filledFrom:{passthrough:Object.keys(n),chatId:Object.keys(o),defaults:a}}}import{extname as gr}from"path";var At=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,Rt=/<agentx-artifact>[\s\S]*$/i;function ai(r,e=1/0,t=!1){let n=[],o=String(r??"");if(!/<agentx-artifact>/i.test(o))return{text:o,artifacts:n};let i=o.replace(At,(s,a)=>{try{let d=JSON.parse(a.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&n.length<e){let c=d.mime,u=c.startsWith("image/")?"image":c==="application/pdf"?"pdf":c.startsWith("text/")?"text":"file";n.push({type:u,filename:d.filename,mime:c})}}catch{}return""});return{text:(t?i.replace(Rt,""):i).trim(),artifacts:n}}function di(r,e=!1){let t=String(r??""),n=t;if(/<agentx-artifact>/i.test(t)){let o=t.replace(At,(i,s)=>{try{let a=JSON.parse(s.trim());return a&&typeof a.filename=="string"?a.filename:""}catch{return""}});n=(e?o.replace(Rt,""):o).trim()}return n.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(o,i,s)=>i===void 0||s===void 0?o:`[${i||s}](${s})`)}var mr={".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"}},ci={bytes:20*1024*1024,perMessage:20,pathChars:512};function li(r){return mr[gr(r).toLowerCase()]??null}var hr=["[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(`
|
|
19
|
+
`);function ui(r,e,t){return r==="app"&&e&&t!==!1?hr:void 0}import{lstatSync as $e,mkdirSync as wr,readdirSync as yr,realpathSync as Re,unlinkSync as kr}from"fs";import{join as Q,resolve as $t}from"path";var xt=".agentx/outbox",br=7*24*60*60*1e3;function vr(r,e){try{let t=Re($t(e,r)),n=Q(t,xt);return Re(n)===n&&$e(n).isDirectory()?n:null}catch{return null}}function mi(r,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let o=Re($t(t,r));$e(Q(o,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||wr(Q(o,xt),{recursive:!0})}catch{return 0}let n=vr(r,t);return n?Pt(n,(e.now??Date.now())-(e.maxAgeMs??br)):0}function Pt(r,e){let t=0;for(let n of yr(r)){let o=Q(r,n);try{let i=$e(o);i.isDirectory()?t+=Pt(o,e):Math.max(i.mtimeMs,i.ctimeMs)<e&&(kr(o),t++)}catch{}}return t}export{ze as a,Ye as b,$ as c,de as d,v as e,L as f,on as g,pe as h,ge as i,he as j,Se as k,rr as l,cr as m,In as n,fr as o,ai as p,di as q,ci as r,li as s,ui as t,xt as u,mi as v};
|
|
20
|
+
//# sourceMappingURL=chunk-ECBKTFTL.js.map
|