agentix-cli 0.68.0 → 0.68.1

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.
Files changed (38) hide show
  1. package/dist/{agent-HM7GNNUR.js → agent-32KAOR6W.js} +2 -2
  2. package/dist/{board-dashboard-LEUIFDNJ.js → board-dashboard-DJXGWM4G.js} +151 -151
  3. package/dist/board-dashboard-DJXGWM4G.js.map +1 -0
  4. package/dist/chunk-5V6HNNFY.js +2 -0
  5. package/dist/chunk-5V6HNNFY.js.map +1 -0
  6. package/dist/{chunk-YQT4ZKY5.js → chunk-HMW5CVOT.js} +2 -2
  7. package/dist/{chunk-WDRLN7F2.js → chunk-HNR6GLNV.js} +6 -6
  8. package/dist/chunk-LP4DLIZ5.js +20 -0
  9. package/dist/chunk-LP4DLIZ5.js.map +1 -0
  10. package/dist/{chunk-AQYST6P6.js → chunk-NRSXMPFM.js} +204 -202
  11. package/dist/chunk-NRSXMPFM.js.map +1 -0
  12. package/dist/{chunk-QHD473UI.js → chunk-REFLUAXH.js} +2 -2
  13. package/dist/{chunk-CW63GAH5.js → chunk-XFI63BEM.js} +64 -63
  14. package/dist/chunk-XFI63BEM.js.map +1 -0
  15. package/dist/cli.js +1 -1
  16. package/dist/cli.js.map +1 -1
  17. package/dist/facts-72AFTTDG.js +22 -0
  18. package/dist/facts-72AFTTDG.js.map +1 -0
  19. package/dist/index.d.ts +17 -0
  20. package/dist/index.js +1 -1
  21. package/dist/index.js.map +1 -1
  22. package/dist/program-7QBU5CYO.js +2 -0
  23. package/dist/{registry-6XJMNXY6.js → registry-BVOLZUYL.js} +2 -2
  24. package/package.json +1 -1
  25. package/dist/board-dashboard-LEUIFDNJ.js.map +0 -1
  26. package/dist/chunk-ANGX6XPA.js +0 -20
  27. package/dist/chunk-ANGX6XPA.js.map +0 -1
  28. package/dist/chunk-AQYST6P6.js.map +0 -1
  29. package/dist/chunk-CW63GAH5.js.map +0 -1
  30. package/dist/facts-4YPSHIXJ.js +0 -22
  31. package/dist/facts-4YPSHIXJ.js.map +0 -1
  32. package/dist/program-KWSQLVSV.js +0 -2
  33. /package/dist/{agent-HM7GNNUR.js.map → agent-32KAOR6W.js.map} +0 -0
  34. /package/dist/{chunk-YQT4ZKY5.js.map → chunk-HMW5CVOT.js.map} +0 -0
  35. /package/dist/{chunk-WDRLN7F2.js.map → chunk-HNR6GLNV.js.map} +0 -0
  36. /package/dist/{chunk-QHD473UI.js.map → chunk-REFLUAXH.js.map} +0 -0
  37. /package/dist/{program-KWSQLVSV.js.map → program-7QBU5CYO.js.map} +0 -0
  38. /package/dist/{registry-6XJMNXY6.js.map → registry-BVOLZUYL.js.map} +0 -0
@@ -1,20 +0,0 @@
1
- import{a as te}from"./chunk-N6EWZGIX.js";import{b as Ue,c as Ke}from"./chunk-WP6KLXTP.js";import{b as je,e as Ce,f as Me,i as _e,k as Le,l as He,q as Be}from"./chunk-JHWBCDD2.js";import{b as ie}from"./chunk-AFRHKA7B.js";import{a as De,b as ne,c as re,d as Fe,e as oe}from"./chunk-QD6IICK7.js";import{v as Ee,w as _t}from"./chunk-TX7MWUC4.js";import{b as We,f as Mt}from"./chunk-72SZI2UW.js";import{c as Ne,d as Oe}from"./chunk-QOYAX2FT.js";import{existsSync as Lt,mkdirSync as ze,readFileSync as Ht,writeFileSync as Ut,renameSync as Kt}from"fs";import{resolve as Ye,dirname as Bt}from"path";var qe=class{filePath;log;constructor(e={}){let t=e.baseDir??Ye(process.cwd(),".agentx");this.filePath=Ye(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),ze(t,{recursive:!0})}key(e,t,n){return`${e}::${t}::${n||"-"}`}load(){if(!Lt(this.filePath))return{version:1,overrides:{}};try{let e=Ht(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){ze(Bt(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Ut(t,JSON.stringify(e,null,2)),Kt(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 qt,writeFileSync as de,appendFileSync as Jt,mkdirSync as Gt,existsSync as Ge}from"fs";import{resolve as ce}from"path";var zt=new RegExp(["billing","invoice","payment","past[- ]due","overdue","unpaid","refund","subscription","trial","credits?","balance","quota","rate[- ]limit","expired?","expir(es|y|ing)","suspended","renew(al|ed|s)?","outage","down","offline","unreachable","blocked","broken","failing","deploy(ed|ment)?","live on","in prod(uction)?"].map(r=>`\\b${r}\\b`).join("|"),"i");function Yt(r){return r.source.sender==="system:rotation"||zt.test(r.content)}function se(r,e=Date.now()){let t=Date.parse(r.createdAt);return Number.isFinite(t)?Math.max(0,Math.floor((e-t)/864e5)):null}function Je(r,e=Date.now()){if(!Yt(r))return!1;let t=se(r,e);return t===null||t>=2}var ae="[These are notes, not checked facts. Before you state one marked UNVERIFIED to a person or act on it, re-check it against its source (API, CLI, dashboard). If you can't, say it is unverified and ask the owner.]";var Ve=200,Vt=7,Ze=class{memoryDir;constructor(e=process.cwd()){this.memoryDir=ce(e,".agentx/memory"),Ge(this.memoryDir)||Gt(this.memoryDir,{recursive:!0})}filePath(e){return ce(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||ne(t.content))return!1;let n=t.source.trust??De(t.source.channel),o=t.review??Fe(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 Jt(this.filePath(e),JSON.stringify(i)+`
2
- `),!0}getAll(e){let t=this.filePath(e);if(!Ge(t))return[];try{return qt(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=ce(this.memoryDir,`${t}_bm25_cache.json`),a=Oe(i,s),d=Ne(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);return t.length===0?"":["[Agent Memory \u2014 persistent facts from past conversations]",...t.some(o=>o.unverified)?[ae]:[],...t.map(o=>o.line),"[End Memory]"].join(`
4
- `)}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[],n=57,o=!1,i=Date.now();for(let s of e){let d=!s.source.chatId.startsWith("-")&&/^\d+$/.test(s.source.chatId)?"DM":s.source.chatId,c=Je(s,i),u=se(s,i),p=c?`UNVERIFIED (${u===null?"age unknown":`${u}d old`}) `:"",g=`- [${s.category}] ${p}${s.content} (${d}, ${s.source.date})`,f=c&&!o?ae.length:0;if(n+f+g.length>2400)break;t.push({fact:s,line:g,unverified:c}),n+=f+g.length,f&&(o=!0)}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&&de(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){de(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=Vt*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>Ve&&(t=t.slice(-Ve));let i=this.filePath(e);de(i,t.map(s=>JSON.stringify(s)).join(`
10
- `)+`
11
- `)}};import{existsSync as I,mkdirSync as wn,readdirSync as U,readFileSync as K,unlinkSync as B,writeFileSync as pe}from"fs";import{resolve as R,relative as fe}from"path";import{z as l}from"zod";var Zt=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"]),Xt=l.enum(["equals","contains","matches","exists"]),Qt=l.object({kind:Xt,params:l.record(l.unknown()).default({})}),Qe=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}),et=l.object({id:l.string().min(1).regex(/^[a-zA-Z_][a-zA-Z0-9_-]*$/,"node id must be identifier-safe"),type:Zt,config:l.record(l.unknown()).default({}),retry:Qe,position:l.object({x:l.number(),y:l.number()}).optional()}),tt=l.object({from:l.string(),fromPort:l.string().optional(),to:l.string(),toPort:l.string().optional(),label:l.string().optional()}),Xe=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(et).refine(r=>r.length>0,{message:"workflow must have at least one node"}),edges:l.array(tt).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:Xe.optional(),updated:Xe.optional()});function le(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)&&en(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=nn(r);for(let s of i)e.push(`cycle without agent/checkpoint: ${s.join(" -> ")}`);return e}function en(r){return r==="end"||r==="checkpoint"||r==="subProcess"||r==="signal.wait"||r==="timer.boundary"}function tn(r){return r==="agent"||r==="checkpoint"||r==="subProcess"||r==="signal.wait"||r==="timer.boundary"}function nn(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?tn(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 nt=l.enum(["running","paused","completed","failed","canceled"]),rn=l.enum(["ok","failed","timeout","skipped","paused","resumed"]),on=l.object({at:l.string(),nodeId:l.string(),inputKeys:l.array(l.string()).default([]),status:rn,output:l.record(l.unknown()).optional(),idempotencyKey:l.string(),note:l.string().optional()}),sn=l.object({backend:l.string(),id:l.string()}),an=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()})]),dn=l.object({id:l.string(),workflowId:l.string(),workflowVersion:l.literal(2),homeNode:l.string(),status:nt,pausedAt:an.optional(),context:l.record(l.record(l.unknown())).default({}),pending:l.array(l.string()).default([]),joinCounters:l.record(l.array(l.string())).default({}),entityRef:sn,history:l.array(on).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 ot from"js-yaml";var cn=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=ot.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 it(n,e)}function it(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(cn.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=rt(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=rt(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 rt(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 ln(r){return ot.dump(r,{noRefs:!0,lineWidth:100,sortKeys:!1})}import{Document as un,isMap as H,isSeq as pn,isScalar as st,parseDocument as fn}from"yaml";function at(r,e){let t=fn(r);if(!t.contents||!H(t.contents)){let n=new un(e);return t.commentBefore&&(n.commentBefore=t.commentBefore),String(n)}return ue(t,t.contents,e),String(t)}function ue(r,e,t){let n=Object.keys(t),o=new Set(n),i=new Map;for(let a of e.items){let d=hn(a);d!==null&&i.set(d,a)}let s=[];for(let a of n){let d=t[a],c=i.get(a);c?(gn(r,c,d),s.push(c)):s.push(r.createPair(a,d))}e.items=s}function gn(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)){pn(n)?mn(r,n,t):e.value=r.createNode(t);return}H(n)?ue(r,n,t):e.value=r.createNode(t)}function mn(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);st(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)?(ue(r,d,s),i.push(d)):i.push(r.createNode(s))}e.items=i}function hn(r){let e=r.key;return st(e)&&typeof e.value=="string"?e.value:typeof e=="string"?e:null}var ge=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??R(process.cwd(),".agentx/workflows"),wn(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:fe(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=fe(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=le(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:fe(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),pe(this.pathForJson(o.id),JSON.stringify(o,null,2)+`
12
- `),o;if(a){let d=K(a,"utf-8");try{let c=at(d,o);return pe(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 pe(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 yn,randomUUID as kn}from"crypto";import{appendFileSync as dt,existsSync as E,mkdirSync as ct,readdirSync as lt,readFileSync as me,statSync as ut,unlinkSync as pt,writeFileSync as bn}from"fs";import{resolve as W}from"path";function vn(r){return r.replace(/[^a-zA-Z0-9._:#@-]/g,"_").slice(0,200)}function P(r,e,t){return yn("sha1").update(`${r}|${e}|${t}`).digest("hex").slice(0,16)}var he=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,ct(this.runsDir,{recursive:!0}),ct(this.indexDir,{recursive:!0})}runPath(e){return W(this.runsDir,`${e}.jsonl`)}indexPath(e){return W(this.indexDir,`${e.backend}__${vn(e.id)}.json`)}create(e){let t=new Date().toISOString(),n=kn(),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??Ce()?.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(!E(t))return null;let n=me(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(!E(t))return null;try{return JSON.parse(me(t,"utf-8")).runId}catch{return null}}getHomeNodeByEntity(e){let t=this.indexPath(e);if(!E(t))return null;try{return JSON.parse(me(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};dt(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(!E(this.runsDir))return[];let t=lt(this.runsDir).filter(o=>o.endsWith(".jsonl")).map(o=>({name:o,mtime:ut(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(!E(this.runsDir))return 0;let t=Date.now()-e.maxDays*24*60*60*1e3,n=[];for(let i of lt(this.runsDir)){if(!i.endsWith(".jsonl"))continue;let s=W(this.runsDir,i),a=ut(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{pt(s.file),o++}catch{}}return o}appendSnapshot(e){let t={v:2,kind:"snapshot",run:e};dt(this.runPath(e.id),JSON.stringify(t)+`
16
- `)}writeIndex(e,t){bn(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(E(t))try{pt(t)}catch{}}};import{existsSync as ft,mkdirSync as In,readFileSync as An,unlinkSync as Sn,writeFileSync as Rn}from"fs";import{resolve as we}from"path";import{z as D}from"zod";var gt=D.object({version:D.literal(1),nodes:D.record(D.object({x:D.number(),y:D.number()}))}),ye=class{baseDir;layoutsDir;constructor(e={}){this.baseDir=e.baseDir??we(process.cwd(),".agentx/workflows"),this.layoutsDir=we(this.baseDir,"_layouts"),In(this.layoutsDir,{recursive:!0})}pathFor(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return we(this.layoutsDir,`${t}.json`)}get(e){let t=this.pathFor(e);if(!ft(t))return null;try{let n=gt.safeParse(JSON.parse(An(t,"utf-8")));return n.success?n.data:null}catch{return null}}save(e,t){let n=gt.parse(t);return Rn(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 ft(t)?(Sn(t),!0):!1}};function mt(r){return new Set(r.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function $n(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 xn(r,e){let t=mt(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=$n(t,mt(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 ke(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 be(r,e){let t=r.config.cases??[],n=r.config.default??"";for(let o of t)if(Tn(o.when,e))return o.to;return n}function Tn(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 Y(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)}Mt();_t();function Pn(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 A(r,e,t={}){let n=new Set(t.envAllow||[]);return r.replace(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_.-]*)\s*\}\}/g,(o,i)=>Pn(i,e,n))}function b(r,e,t={}){let n={};for(let[o,i]of Object.entries(r))typeof i=="string"?n[o]=A(i,e,t):Array.isArray(i)?n[o]=i.map(s=>typeof s=="string"?A(s,e,t):s):i&&typeof i=="object"?n[o]=b(i,e,t):n[o]=i;return n}var ht="workflow-classify",q="unsure",wt=async r=>{let e=r.node.config,t=r.run.context,n={envAllow:r.workflow.envAllow},o=A(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?A(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"?A(y,t,n):y;(w===null||["string","number","boolean"].includes(typeof w))&&(u[m]=w)}let p=await Ee(ht,u,{label:We(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.${ht}.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 ve=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}}},J=new ve;function yt(r,e){return`${r}:${e}`}var F=async r=>({output:r.run.context[r.node.id]??{}}),Nn=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=A(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?yt(r.workflow.id,r.node.id):null;if(d&&a){let u=J.stats(d);u.active>=a&&r.log(`[node:${r.node.id}] gated: ${u.active} active (cap ${a}), ${u.waiting+1} waiting`),await J.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"?er(u.content):bt(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&&J.release(d)}},On=async r=>{let e=be(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}})},Wn=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=Ae(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)`}},En=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=Se(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}`}}},Dn=async()=>({output:{}}),Fn=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}}}},jn=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=Se(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}}},Cn=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})??[]}}},Mn=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=Ae(r,e.accountId),a=r.channels[t];if(!a?.react)return{error:`channel "${t}" does not support react`};try{return await a.react(n,o,i,s),{output:{emoji:i}}}catch(d){return{error:`action.react failed: ${d.message}`}}},_n=async r=>{let e=b(r.node.config,r.run.context,{envAllow:r.workflow.envAllow}),t=String(e.channel??""),n=String(e.chatId??""),o=String(e.messageId??""),i=String(e.text??""),s=e.parseMode?String(e.parseMode):void 0;if(!t||!n||!o||!i)return{error:`action.editMessage "${r.node.id}" needs channel + chatId + messageId + text`};let a=Ae(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}`}}},Ln=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=Se(r);try{return await i.logTimeSpent(n,o,s),{output:{durationMs:o}}}catch(a){return{error:`action.logTime failed: ${a.message}`}}},Hn=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}`}}},Un=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}`}}},Kn=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}`}}},Bn=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 zn(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 Yn=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:A(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}}},qn=F,Jn=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}}},Gn=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}}},Vn=async r=>{let e=r.node.config,t=b(e,r.run.context,{envAllow:r.workflow.envAllow}),n=zn(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)`}},Zn=async()=>({output:{}}),Xn=async r=>{let e=r.node.config,n=(Array.isArray(e.inputs)?e.inputs:[]).map(s=>typeof s=="string"?A(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(!Qn(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 Qn(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 kt={"trigger.channel":F,"trigger.manual":F,"trigger.cron":F,"trigger.hook":F,"trigger.form":qn,agent:Nn,classify:wt,branch:On,transform:Bn,"gateway.parallel":Zn,rule:Xn,"action.send":Wn,"action.createIssue":En,"action.setLabel":jn,"action.readLabel":Cn,"action.react":Mn,"action.editMessage":_n,"action.logTime":Ln,"action.callHTTP":Hn,"action.run":Un,"action.builtin":Kn,subProcess:Yn,"signal.emit":Jn,"signal.wait":Gn,"timer.boundary":Vn,checkpoint:Fn,end:Dn};function Ie(r){return kt[r]}function Ae(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 Se(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 bt(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 er(r){let{result:e}=bt(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 j=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 tr(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 nr(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 rr(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 vt(r,e,t,n,o=Date.now){let i=tr(e,t,o),s=nr(n),a=rr(s),d=Le(r,i,a,o);return He(r,"workflow",d,s,o),d}var or=4e3,ir=8,Re=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 j,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:P(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:P(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,or);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(_e("workflow")!=="off")try{vt(je(),{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(!ar(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:P(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=Y(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?Me({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,ir);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=P(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(S=>S!==n),status:"failed"}),{kind:"done"};let w=Ie(y.type);return w?m.history.some(S=>S.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(S=>S!==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(S=>S!==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=Ue(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{Ke(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,T=null;if(f.spawnChild&&k.kind==="subProcess"){if(T=await this.spawnChild({parent:m,parentNodeId:n,childWorkflowId:f.spawnChild.workflowId,input:f.spawnChild.input}),!T){this.runs.recordExecution({runId:t,entry:{at:y,nodeId:n,inputKeys:u,status:"failed",idempotencyKey:i,note:`subProcess: child workflow "${f.spawnChild.workflowId}" not found`},nextPending:w,status:"failed"});return}k={...k,childRunId:T.id}}if(this.runs.recordExecution({runId:t,entry:{at:y,nodeId:n,inputKeys: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}),T&&this.kickChildWalk(T),k.kind==="timerWait")try{this.timers.schedule({runId:t,workflowId:e.id,nodeId:k.nodeId,fireAt:k.fireAt,cancelKey:`${t}:${k.nodeId}`})}catch(Pe){this.log(`[workflow:${e.id}] timer schedule failed: ${Pe.message}`)}return}let S=f.output??{},Wt={...m.context,[n]:S},{nextPending:Et}=ke({workflow:e,fromNodeId:n,selectedPort:f.port}),ee=[],C={...m.joinCounters??{}};for(let k of Et){let T=N(e,k);if(!(T?.type==="gateway.parallel"&&String(T.config?.mode??"fanOut")==="join")){ee.push(k);continue}let _=C[k]??[];_.includes(n)||_.push(n),C[k]=_;let jt=e.edges.filter(Ct=>Ct.to===k).length;_.length>=jt&&(ee.push(k),delete C[k])}let Dt=[...w,...ee],M=d.type==="end",Ft=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:S,idempotencyKey:i},nextPending:M?[]:Dt,status:Ft,context:Wt,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=Y(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:sr(e.childRun)};this.runs.recordExecution({runId:o.id,entry:{at:new Date().toISOString(),nodeId:e.parentNodeId,inputKeys:[],status:"resumed",output:a,idempotencyKey:P(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 sr(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 ar(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 dr(r){return{"pre:channel-message":async e=>{let t=e.msg;if(!t)return{};let n=cr(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:lr(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 cr(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 lr(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 ur(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 pr(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 fr(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 $e(r,e,t){let n=r.logged??(r.logged=new Set);n.has(e)||(n.add(e),r.log(t))}function It(r,e,t,n,o){let i=ur(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=fr(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?$e(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)&&$e(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=pr(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 $e(o,`notarget:${r.id}:${e}`,`[workflows] ${r.id} filter.maxFiresPerTarget has no target key for ${e} \u2014 limit not applied`)}return{skip:!1}}function gr(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}hr({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=It(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=mr(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 mr(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 hr(r,e,t){let n=()=>{let o;try{o=Be(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 At(r){return r.nodes.find(n=>n.type.startsWith("trigger."))?.config?.inputSchema??null}function St(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 Rt(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 $t(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 yr(r,e){let t=At(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=St(e.chatId,t),i={...n,...o},s={...i};i=Rt(t,i);let a=Object.keys(i).filter(d=>s[d]===void 0&&i[d]!==void 0);return{inputs:i,missing:$t(t,i),filledFrom:{passthrough:Object.keys(n),chatId:Object.keys(o),defaults:a}}}import{extname as kr}from"path";var xt=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,Tt=/<agentx-artifact>[\s\S]*$/i;function gi(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(xt,(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(Tt,""):i).trim(),artifacts:n}}function mi(r,e=!1){let t=String(r??""),n=t;if(/<agentx-artifact>/i.test(t)){let o=t.replace(xt,(i,s)=>{try{let a=JSON.parse(s.trim());return a&&typeof a.filename=="string"?a.filename:""}catch{return""}});n=(e?o.replace(Tt,""):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 br={".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"}},hi={bytes:20*1024*1024,perMessage:20,pathChars:512};function wi(r){return br[kr(r).toLowerCase()]??null}var vr=["[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 ![what it shows](https://...)."].join(`
19
- `);function yi(r,e,t){return r==="app"&&e&&t!==!1?vr:void 0}import{lstatSync as Te,mkdirSync as Ir,readdirSync as Ar,realpathSync as xe,unlinkSync as Sr}from"fs";import{join as Q,resolve as Pt}from"path";var Nt=".agentx/outbox",Rr=7*24*60*60*1e3;function $r(r,e){try{let t=xe(Pt(e,r)),n=Q(t,Nt);return xe(n)===n&&Te(n).isDirectory()?n:null}catch{return null}}function Ii(r,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let o=xe(Pt(t,r));Te(Q(o,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||Ir(Q(o,Nt),{recursive:!0})}catch{return 0}let n=$r(r,t);return n?Ot(n,(e.now??Date.now())-(e.maxAgeMs??Rr)):0}function Ot(r,e){let t=0;for(let n of Ar(r)){let o=Q(r,n);try{let i=Te(o);i.isDirectory()?t+=Ot(o,e):Math.max(i.mtimeMs,i.ctimeMs)<e&&(Sr(o),t++)}catch{}}return t}export{qe as a,Ze as b,$ as c,le as d,v as e,L as f,ln as g,ge as h,he as i,ye as j,Re as k,dr as l,gr as m,xn as n,yr as o,gi as p,mi as q,hi as r,wi as s,yi as t,Nt as u,Ii as v};
20
- //# sourceMappingURL=chunk-ANGX6XPA.js.map