@robota-sdk/agent-cli 3.0.0 → 3.0.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.
@@ -2774,7 +2774,7 @@ Options:
2774
2774
  `);return}let u=l.at(-1);u||(process.stderr.write(`No sessions found.
2775
2775
  `),process.exit(1)),process.stdout.write(_J(fJ(u))+`
2776
2776
  `)}function uGe(e){let t,n,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a===`--threshold`){let t=e[i+1],a=t===void 0?NaN:Number.parseFloat(t);Number.isFinite(a)?n=a:r=!0,i++}else a&&!a.startsWith(`-`)&&t===void 0&&(t=a)}return{definitionPath:t,threshold:n,thresholdInvalid:r}}async function dGe(e){let t=await import(Jr(e).href),n=t.default??t.evalDefinition;if(!n)throw Error(`eval definition module '${e}' has no default (or 'evalDefinition') export`);return n}async function fGe(e,t){let n=t.settingsSources??(()=>{throw Error(`Eval startup requires explicit host settings sources.`)})(),r=t.providerDefinitions??AH(),i=sb(n,{providerDefinitions:r,...t.environment===void 0?{}:{env:t.environment}});return Cme(Wme({cwd:e,provider:at(t.resolveProviderCredential===void 0?i:await t.resolveProviderCredential(i),r),userSettingsSources:n.filter(e=>e.kind===`host`),...t.projectAccess===void 0?{}:{projectAccess:t.projectAccess}}))}async function A1(e,t=process.cwd(),n={}){let r=uGe(e);if(!r.definitionPath||r.thresholdInvalid)return process.stderr.write(`Usage: eval <definition-file> [--threshold <0..1>]
2777
- `),1;let i=Mn.resolve(t,r.definitionPath),a;try{let e=await(n.loadDefinition??dGe)(i);a=r.threshold===void 0?e:{...e,threshold:r.threshold},gC(a)}catch(e){return process.stderr.write(`Failed to load eval definition: ${e instanceof Error?e.message:String(e)}\n`),1}let o;try{let e=n.runFn??await fGe(t,n);o=await bme(a,e)}catch(e){return process.stderr.write(`Eval run failed: ${e instanceof Error?e.message:String(e)}\n`),1}return process.stdout.write(Eme(o)),+!o.passed}const j1=()=>`3.0.0`,pGe=()=>`3.0.0`,mGe=()=>null,M1=e=>e.artifact?.version??j1(),hGe=e=>e.artifact===void 0?pGe():e.artifact.sourceVersion??e.artifact.version,gGe=e=>e.artifact===void 0?mGe():e.artifact.buildMetadata??null;async function _Ge(e){let t=ki({input:process.stdin,output:process.stdout});try{let n=(await t.question(e)).trim().toLowerCase();return n===`y`||n===`yes`}finally{t.close()}}async function vGe(e,t){let n=mE(t.productRuntime);if(!cr(n))return e.writeLine(`No user settings found.`),0;if(!t.yes){if(!t.isTTY)return e.writeError(`--reset deletes ${n}. Refusing without confirmation in non-interactive mode — pass --yes to proceed.`),1;if(!await(t.confirm??_Ge)(`Delete ${n}? [y/N] `))return e.writeLine(`Reset cancelled.`),1}let r=Fme(n);return r.deleted?e.writeLine(`Deleted ${r.path}`):e.writeLine(`No user settings found.`),0}function yGe(e){return!cr(e)}function bGe(e){mr(Pn(e),{recursive:!0}),Tr(e,new Date().toISOString())}function xGe(e){return[`Welcome to ${e.vocabulary.cliName}! — AI coding assistant`,``,`Try asking:`,` "Explain this project structure"`,` "Find files with TODO comments"`,` "Run tests and analyze failures"`,` "What changed recently in git?"`,``,`Useful commands:`,` /help show all slash commands`,` /cost show token usage and estimated cost`,` /clear clear conversation history`,``,`${e.vocabulary.cliName} diagnose — check your setup`]}function SGe(e){let t=Math.max(...e.map(e=>wn(e)))+4,n=e.map(e=>{let n=t-2-wn(e);return`│${` `.repeat(2)}${e}${` `.repeat(n)}│`});return[`╭${`─`.repeat(t)}╮`,...n,`╰${`─`.repeat(t)}╯`].join(`
2777
+ `),1;let i=Mn.resolve(t,r.definitionPath),a;try{let e=await(n.loadDefinition??dGe)(i);a=r.threshold===void 0?e:{...e,threshold:r.threshold},gC(a)}catch(e){return process.stderr.write(`Failed to load eval definition: ${e instanceof Error?e.message:String(e)}\n`),1}let o;try{let e=n.runFn??await fGe(t,n);o=await bme(a,e)}catch(e){return process.stderr.write(`Eval run failed: ${e instanceof Error?e.message:String(e)}\n`),1}return process.stdout.write(Eme(o)),+!o.passed}const j1=()=>`3.0.1`,pGe=()=>`3.0.1`,mGe=()=>null,M1=e=>e.artifact?.version??j1(),hGe=e=>e.artifact===void 0?pGe():e.artifact.sourceVersion??e.artifact.version,gGe=e=>e.artifact===void 0?mGe():e.artifact.buildMetadata??null;async function _Ge(e){let t=ki({input:process.stdin,output:process.stdout});try{let n=(await t.question(e)).trim().toLowerCase();return n===`y`||n===`yes`}finally{t.close()}}async function vGe(e,t){let n=mE(t.productRuntime);if(!cr(n))return e.writeLine(`No user settings found.`),0;if(!t.yes){if(!t.isTTY)return e.writeError(`--reset deletes ${n}. Refusing without confirmation in non-interactive mode — pass --yes to proceed.`),1;if(!await(t.confirm??_Ge)(`Delete ${n}? [y/N] `))return e.writeLine(`Reset cancelled.`),1}let r=Fme(n);return r.deleted?e.writeLine(`Deleted ${r.path}`):e.writeLine(`No user settings found.`),0}function yGe(e){return!cr(e)}function bGe(e){mr(Pn(e),{recursive:!0}),Tr(e,new Date().toISOString())}function xGe(e){return[`Welcome to ${e.vocabulary.cliName}! — AI coding assistant`,``,`Try asking:`,` "Explain this project structure"`,` "Find files with TODO comments"`,` "Run tests and analyze failures"`,` "What changed recently in git?"`,``,`Useful commands:`,` /help show all slash commands`,` /cost show token usage and estimated cost`,` /clear clear conversation history`,``,`${e.vocabulary.cliName} diagnose — check your setup`]}function SGe(e){let t=Math.max(...e.map(e=>wn(e)))+4,n=e.map(e=>{let n=t-2-wn(e);return`│${` `.repeat(2)}${e}${` `.repeat(n)}│`});return[`╭${`─`.repeat(t)}╮`,...n,`╰${`─`.repeat(t)}╯`].join(`
2778
2778
  `)}function CGe(e,t,n={}){let r=xGe(t);e.writeLine(`\n${n.screenReader===!0?r.join(`
2779
2779
  `):SGe(r)}\n`)}function wGe(e,t){process.platform===`darwin`&&t.TERM_PROGRAM===`Apple_Terminal`&&e.writeError(`
2780
2780
  ⚠ macOS Terminal.app detected: CJK/IME input may be unstable.
@@ -2786,7 +2786,7 @@ Options:
2786
2786
  `,0,1)||!r(e,o,s)?!1:(i=!0,!0)};if(t===``){for(let t=0;t<e.length;t++)if(!a(t,t+1))return!1;return!0}let o=0;for(;;){let n=e.indexOf(t,o);if(n<0)return a(o,e.length);if(!a(o,n))return!1;o=n+t.length}},r,`text-split`)}function W0(e,t,n){let r=0,i=!1;for(let a of e){let e=n===`text-lower`?a.toLowerCase():a.toUpperCase();for(let a=0;a<e.length;a++){let o=e.charCodeAt(a);if(r+=o<128?1:o<2048?2:o>=56320&&o<=57343&&i?1:3,i=o>=55296&&o<=56319,r>t)return{ok:!1,error:F1(`DAG_TASK_EXECUTION_BYTE_LIMIT_EXCEEDED`,`${n} output exceeds its UTF-8 byte limit`,!1,{maxBytes:t,nodeType:n})}}}return{ok:!0,value:n===`text-lower`?e.toLowerCase():e.toUpperCase()}}const G0={ok:!0,value:{estimatedCredits:0}},K0=I.object({});var GKe=class extends m0{nodeType=`string-to-number`;displayName=`String → Number`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`number`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`number`,label:`Number`,order:0,type:`string`,required:!0}];configSchemaDefinition=K0;async estimateCostWithConfig(){return G0}async executeWithConfig(e,t,n){let r=new v0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=Number(i.value);return isNaN(a)?{ok:!1,error:Q(`DAG_VALIDATION_STRING_TO_NUMBER_INVALID`,`Cannot convert "${i.value}" to a number`,{nodeId:t.nodeDefinition.nodeId})}:(r.setOutput(`number`,String(a)),{ok:!0,value:r.toOutput()})}},KKe=class extends m0{nodeType=`number-to-string`;displayName=`Number → String`;category=`Utility`;defaultInputPort=`number`;defaultOutputPort=`text`;inputs=[{key:`number`,label:`Number`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=K0;async estimateCostWithConfig(){return G0}async executeWithConfig(e,t,n){let r=new v0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`number`);return i.ok?(r.setOutput(`text`,i.value),{ok:!0,value:r.toOutput()}):i}};const qKe=I.object({separator:I.string().default(`, `)});var JKe=class extends m0{nodeType=`text-join`;displayName=`Text Join`;category=`Utility`;defaultInputPort=`items`;defaultOutputPort=`text`;inputs=[{key:`items`,label:`Items (newline-separated)`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=qKe;async estimateCostWithConfig(){return G0}async executeWithConfig(e,t,n){let r=new v0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`items`);if(!i.ok)return i;let a=UKe(i.value,n.separator,H1(t.byteLimits).maxTextJoinOutputBytes);return a.ok?(r.setOutput(`text`,a.value),{ok:!0,value:r.toOutput()}):a}};const YKe=I.object({separator:I.string().default(`
2787
2787
  `),trim:I.boolean().default(!0)});var XKe=class extends m0{nodeType=`text-split`;displayName=`Text Split`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`items`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`items`,label:`Items (newline-separated)`,order:0,type:`string`,required:!0}];configSchemaDefinition=YKe;async estimateCostWithConfig(){return G0}async executeWithConfig(e,t,n){let r=new v0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=WKe(i.value,n.separator,n.trim,H1(t.byteLimits).maxTextSplitOutputBytes);return a.ok?(r.setOutput(`items`,a.value),{ok:!0,value:r.toOutput()}):a}};const ZKe=I.object({search:I.string().default(``),replacement:I.string().default(``),useRegex:I.boolean().default(!1),flags:I.string().default(`g`)});var QKe=class extends m0{nodeType=`text-replace`;displayName=`Text Replace`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=ZKe;async estimateCostWithConfig(){return G0}async executeWithConfig(e,t,n){let r=new v0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a;if(n.useRegex){if(!t.regexReplaceOperation)return{ok:!1,error:F1(`DAG_TASK_ISOLATION_UNAVAILABLE`,`Regex-based text-replace requires an isolated regex executor; none was supplied for this run`,!1,{nodeId:t.nodeDefinition.nodeId})};let e=await t.regexReplaceOperation.execute({text:i.value,search:n.search,replacement:n.replacement,flags:n.flags},t.signal);if(!e.ok)return e;a=e.value}else{let e=BKe(i.value,n.search,n.replacement,H1(t.byteLimits).maxTextReplaceOutputBytes);if(!e.ok)return e;a=e.value}return r.setOutput(`text`,a),{ok:!0,value:r.toOutput()}}},$Ke=class extends m0{nodeType=`text-length`;displayName=`Text Length`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Length`,order:0,type:`string`,required:!0}];configSchemaDefinition=K0;async estimateCostWithConfig(){return G0}async executeWithConfig(e,t){let n=new v0(e,t.nodeDefinition.nodeId),r=n.requireInputString(`text`);return r.ok?(n.setOutput(`text`,String(r.value.length)),{ok:!0,value:n.toOutput()}):r}},eqe=class extends m0{nodeType=`text-upper`;displayName=`Text Uppercase`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=K0;async estimateCostWithConfig(){return G0}async executeWithConfig(e,t){let n=new v0(e,t.nodeDefinition.nodeId),r=n.requireInputString(`text`);if(!r.ok)return r;let i=W0(r.value,H1(t.byteLimits).maxTextUpperOutputBytes,`text-upper`);return i.ok?(n.setOutput(`text`,i.value),{ok:!0,value:n.toOutput()}):i}},tqe=class extends m0{nodeType=`text-lower`;displayName=`Text Lowercase`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=K0;async estimateCostWithConfig(){return G0}async executeWithConfig(e,t){let n=new v0(e,t.nodeDefinition.nodeId),r=n.requireInputString(`text`);if(!r.ok)return r;let i=W0(r.value,H1(t.byteLimits).maxTextLowerOutputBytes,`text-lower`);return i.ok?(n.setOutput(`text`,i.value),{ok:!0,value:n.toOutput()}):i}};const nqe=I.object({mode:I.enum([`both`,`start`,`end`]).default(`both`)});var rqe=class extends m0{nodeType=`text-trim`;displayName=`Text Trim`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=nqe;async estimateCostWithConfig(){return G0}async executeWithConfig(e,t,n){let r=new v0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=n.mode===`start`?i.value.trimStart():n.mode===`end`?i.value.trimEnd():i.value.trim();return r.setOutput(`text`,a),{ok:!0,value:r.toOutput()}}};const iqe=I.object({path:I.string().default(``),fallback:I.string().default(``)});var aqe=class extends m0{nodeType=`json-extract`;displayName=`JSON Extract`;category=`Utility`;defaultInputPort=`json`;defaultOutputPort=`text`;inputs=[{key:`json`,label:`JSON`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Value`,order:0,type:`string`,required:!0}];configSchemaDefinition=iqe;async estimateCostWithConfig(){return G0}async executeWithConfig(e,t,n){let r=new v0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`json`);if(!i.ok)return i;let a;try{a=JSON.parse(i.value)}catch{return{ok:!1,error:Q(`DAG_VALIDATION_JSON_EXTRACT_INVALID_JSON`,`Input is not valid JSON`,{nodeId:t.nodeDefinition.nodeId})}}let o=n.path?n.path.split(`.`):[],s=a;for(let e of o){if(typeof s!=`object`||!s){s=void 0;break}s=s[e]}let c=s===void 0?n.fallback:String(s);return r.setOutput(`text`,c),{ok:!0,value:r.toOutput()}}};const oqe=I.object({operator:I.enum([`non-empty`,`equals`,`contains`,`starts-with`,`ends-with`]).default(`non-empty`),operand:I.string().default(``)});var sqe=class extends m0{nodeType=`conditional-text`;displayName=`Conditional Text`;category=`Utility`;defaultInputPort=`condition`;defaultOutputPort=`text`;inputs=[{key:`condition`,label:`Condition`,order:0,type:`string`,required:!0},{key:`text_true`,label:`If True`,order:1,type:`string`,required:!0},{key:`text_false`,label:`If False`,order:2,type:`string`,required:!1}];outputs=[{key:`text`,label:`Result`,order:0,type:`string`,required:!0}];configSchemaDefinition=oqe;async estimateCostWithConfig(){return G0}async executeWithConfig(e,t,n){let r=new v0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`condition`);if(!i.ok)return i;let a=r.requireInputString(`text_true`);if(!a.ok)return a;let o=r.getInput(`text_false`),s=i.value,c=n.operand,l;switch(n.operator){case`non-empty`:l=s.trim().length>0;break;case`equals`:l=s===c;break;case`contains`:l=s.includes(c);break;case`starts-with`:l=s.startsWith(c);break;case`ends-with`:l=s.endsWith(c)}let u=l?a.value:typeof o==`string`?o:``;return r.setOutput(`text`,u),{ok:!0,value:r.toOutput()}}};const cqe=I.object({skipEmpty:I.boolean().default(!1)}),lqe=/\S/;function uqe(e,t){if(!t){let t=1;for(let n=0;n<e.length;n++)e[n]===`
2788
2788
  `&&t++;return t}let n=0,r=!1;for(let t=0;t<e.length;t++){let i=e[t];i===`
2789
- `?(r&&n++,r=!1):!r&&lqe.test(i)&&(r=!0)}return r&&n++,n}var dqe=class extends m0{nodeType=`text-count-lines`;displayName=`Text Count Lines`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Line Count`,order:0,type:`string`,required:!0}];configSchemaDefinition=cqe;async estimateCostWithConfig(){return G0}async executeWithConfig(e,t,n){let r=new v0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);return i.ok?(r.setOutput(`text`,String(uqe(i.value,n.skipEmpty))),{ok:!0,value:r.toOutput()}):i}};const fqe=I.object({times:I.number().int().min(0).max(2**53-1).default(2),separator:I.string().default(``)});var pqe=class extends m0{nodeType=`text-repeat`;displayName=`Text Repeat`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Repeated Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=fqe;async estimateCostWithConfig(){return G0}async executeWithConfig(e,t,n){let r=new v0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=H1(t.byteLimits),o=HKe(i.value,n.separator,n.times,a.maxTextRepeatOutputBytes);return o.ok?(r.setOutput(`text`,o.value),{ok:!0,value:r.toOutput()}):o}};const mqe=I.object({start:I.number().int().default(0),end:I.number().int().optional()});var hqe=class extends m0{nodeType=`text-slice`;displayName=`Text Slice`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Sliced Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=mqe;async estimateCostWithConfig(){return G0}async executeWithConfig(e,t,n){let r=new v0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);return i.ok?(r.setOutput(`text`,i.value.slice(n.start,n.end)),{ok:!0,value:r.toOutput()}):i}},gqe=aKe({createDefaultNodeRegistry:()=>J0,createDefaultNodeRegistrySync:()=>q0});function q0(){return[new mKe,new gKe,new yKe,new SKe,new wKe,new EKe,new OKe,new AKe,new zKe,new GKe,new KKe,new JKe,new XKe,new QKe,new $Ke,new eqe,new tqe,new rqe,new aqe,new sqe,new dqe,new pqe,new hqe]}const _qe=async()=>{try{return(await Promise.resolve().then(()=>wH)).createDefaultMediaProviderDefinitions()}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to load the default media provider definitions. Install @robota-sdk/agent-builtin-providers (and its provider SDKs), or inject mediaProviders explicitly. Cause: ${t}`)}},vqe=async()=>{try{return(await Promise.resolve().then(()=>wH)).createDefaultProviderDefinitions()}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to load the default LLM provider set for the llm-text node. A provider SDK package is likely not installed. Install @robota-sdk/agent-builtin-providers (and its provider SDKs), or pass createDagFramework({ providers: [...] }) explicitly. Cause: ${t}`)}};async function J0(e,t=vqe,n={},r=[],i=[]){let a=e??await t(),o=[...q0(),new fKe(a)],s=n.mediaProviders??await(n.loadMediaDefaults??_qe)(),l=c(s,`gemini-image`),u=c(s,`seedance-video`),d=await Promise.all([...[{modulePath:`@robota-sdk/dag-node-gemini-image-edit`,factories:[e=>new e.GeminiImageEditNodeDefinition({imageProviderDefinition:l}),e=>new e.GeminiImageComposeNodeDefinition({imageProviderDefinition:l})]},{modulePath:`@robota-sdk/dag-node-text-to-image`,factories:[e=>new e.TextToImageNodeDefinition({imageProviderDefinition:l})]},{modulePath:`@robota-sdk/dag-node-seedance-video`,factories:[e=>new e.SeedanceVideoNodeDefinition({videoProviderDefinition:u})]}].map(bqe),yqe(i,r)]);for(let e of d)o.push(...e);return o}async function yqe(e,t){try{return[new(await(import(`./src-DwAfU-9z-DOErKivb.js`))).SkillNodeDefinition({skillPort:nde(e,t)})]}catch{return[]}}async function bqe(e){let t=await xqe(e.modulePath);if(!t)return[];let n=[];for(let r of e.factories){let e=Sqe(r,t);e&&n.push(e)}return n}async function xqe(e){try{switch(e){case`@robota-sdk/dag-node-gemini-image-edit`:return await import(`./src-B9UMvThT-Cvs0M0_E.js`);case`@robota-sdk/dag-node-text-to-image`:return await import(`./src-BzaNFPZx-DAgH-EaI.js`);case`@robota-sdk/dag-node-seedance-video`:return await import(`./src-UPsd6jNY-CgN4wopU.js`);default:return}}catch{return}}function Sqe(e,t){try{return e(t)}catch{return}}var Cqe=class{limit;committed=0;reserved=0;closed=!1;constructor(e){if(this.limit=e,e!==void 0&&(!Number.isFinite(e)||e<=0))throw RangeError(`Root credit limit must be positive and finite`)}close(){this.closed=!0}reserve(e){if(!Number.isFinite(e)||e<0)return{ok:!1,error:Q(`DAG_VALIDATION_NEGATIVE_ESTIMATED_CREDITS`,`estimatedCredits must be finite and zero or positive`,{estimatedCredits:e})};if(this.closed||this.limit!==void 0&&e>this.limit-this.committed-this.reserved)return{ok:!1,error:Q(`DAG_VALIDATION_CREDIT_LIMIT_EXCEEDED`,`Estimated run credits exceeds root runCreditLimit`,{estimatedCredits:e,...this.limit===void 0?{}:{runCreditLimit:this.limit}})};this.reserved+=e;let t=!1;return{ok:!0,value:{commit:()=>(t||(t=!0,this.reserved-=e,this.committed+=e),this.committed),release:()=>{t||(t=!0,this.reserved-=e)}}}}};function Y0(e){if(e==null)return;if(typeof e!=`object`||Array.isArray(e))throw Error(`Invalid persisted DAG execution lineage`);let t=e,n=t.parentRunId!==void 0,r=!n||typeof t.parentRunId==`string`&&t.parentRunId.length>0;if(typeof t.rootRunId!=`string`||t.rootRunId.length===0||!r||!Number.isSafeInteger(t.depth)||t.depth<0||t.maxDepth!==void 0&&(!Number.isSafeInteger(t.maxDepth)||t.maxDepth<1)||!Array.isArray(t.ancestorCompositeNodeTypes)||!t.ancestorCompositeNodeTypes.every(e=>typeof e==`string`&&e.length>0))throw Error(`Invalid persisted DAG execution lineage`);let i=t.depth,a=t.ancestorCompositeNodeTypes.length;if(!(i===0?!n&&a===0:n&&a===i))throw Error(`Invalid persisted DAG execution lineage`);return{rootRunId:t.rootRunId,...n?{parentRunId:t.parentRunId}:{},depth:i,...t.maxDepth===void 0?{}:{maxDepth:t.maxDepth},ancestorCompositeNodeTypes:[...t.ancestorCompositeNodeTypes]}}const X0={STARTED:`execution.started`,COMPLETED:`execution.completed`,FAILED:`execution.failed`},Z0={STARTED:`task.started`,COMPLETED:`task.completed`,FAILED:`task.failed`};function Q0(e){let t=Date.parse(e);return Number.isNaN(t)?{ok:!1,error:Q(`DAG_VALIDATION_INVALID_LOGICAL_DATE`,`logicalDate must be a valid ISO-8601 datetime string`,{logicalDate:e})}:{ok:!0,value:new Date(t).toISOString()}}var wqe=class{clock;constructor(e){this.clock=e}resolve(e,t){let n=this.clock.nowIso();if(e===`scheduled`){if(!t)return{ok:!1,error:Q(`DAG_VALIDATION_MISSING_LOGICAL_DATE`,`scheduled trigger requires logicalDate`,{trigger:e})};let r=Q0(t);return r.ok?{ok:!0,value:{trigger:e,logicalDate:r.value,requestedAt:n}}:r}if(!t)return{ok:!0,value:{trigger:e,logicalDate:n,requestedAt:n}};let r=Q0(t);return r.ok?{ok:!0,value:{trigger:e,logicalDate:r.value,requestedAt:n}}:r}},Tqe=class{assertWithinBudget(e,t,n){if(t<0)return{ok:!1,error:Q(`DAG_VALIDATION_NEGATIVE_ESTIMATED_CREDITS`,`estimatedCredits must be zero or positive`,{nextEstimatedCredits:t})};let r=e+t;return typeof n==`number`&&r>n?{ok:!1,error:Q(`DAG_VALIDATION_CREDIT_LIMIT_EXCEEDED`,`Estimated run credits exceeds runCreditLimit`,{nextTotalCredits:r,runCreditLimit:n})}:{ok:!0,value:r}}},Eqe=class{lifecycleFactory;costPolicyEvaluator;constructor(e,t){this.lifecycleFactory=e,this.costPolicyEvaluator=t}async runNode(e){let t=()=>({ok:!1,error:I1(e.context.taskRunId)});if(e.context.signal?.aborted)return t();let n=this.lifecycleFactory.create(e.context.nodeDefinition.nodeType);if(!n.ok)return n;let r=await n.value.initialize(e.context);if(e.context.signal?.aborted)return await n.value.dispose(e.context),t();if(!r.ok)return r;let i=await n.value.validateInput(e.input,e.context);if(e.context.signal?.aborted)return await n.value.dispose(e.context),t();if(!i.ok)return await n.value.dispose(e.context),i;let a=await n.value.estimateCost(e.input,e.context);if(e.context.signal?.aborted)return await n.value.dispose(e.context),t();if(!a.ok)return await n.value.dispose(e.context),a;let o=this.costPolicyEvaluator.assertWithinBudget(e.context.currentTotalCredits,a.value.estimatedCredits,e.context.runCreditLimit);if(!o.ok)return await n.value.dispose(e.context),o;if(e.context.reserveCredits){let r=await e.context.reserveCredits(a.value.estimatedCredits);if(!r.ok)return await n.value.dispose(e.context),r;if(e.context.signal?.aborted)return await n.value.dispose(e.context),t()}let s=e.context.rootCreditBudget?.reserve(a.value.estimatedCredits);if(s&&!s.ok)return await n.value.dispose(e.context),s;try{let r=await n.value.execute(e.input,e.context);if(e.context.signal?.aborted)return await n.value.dispose(e.context),t();if(!r.ok)return await n.value.dispose(e.context),r;let i=await n.value.validateOutput(r.value,e.context);if(e.context.signal?.aborted)return await n.value.dispose(e.context),t();if(!i.ok)return await n.value.dispose(e.context),i;let c=await n.value.dispose(e.context);return e.context.signal?.aborted?t():c.ok?(s?.value.commit(),{ok:!0,value:{output:r.value,estimatedCredits:a.value.estimatedCredits,totalCredits:o.value}}):{ok:!1,error:F1(`DAG_TASK_EXECUTION_DISPOSE_FAILED`,`Node dispose step failed after execution`,!1,{nodeType:e.context.nodeDefinition.nodeType,taskRunId:e.context.taskRunId})}}finally{s?.ok&&s.value.release()}}},Dqe=class{create(e){return{ok:!1,error:Q(`DAG_VALIDATION_NODE_LIFECYCLE_NOT_REGISTERED`,`Node lifecycle is not registered for nodeType`,{nodeType:e})}}},$0=class{nodeManifestRegistry;lineage;lifecycleFactory;runner;constructor(e,t,n){this.nodeManifestRegistry=e,this.lineage=n,this.lifecycleFactory=t??new Dqe,this.runner=new Eqe(this.lifecycleFactory,new Tqe)}async execute(e){if(!e.nodeDefinition)return{ok:!1,error:Q(`DAG_VALIDATION_NODE_DEFINITION_MISSING`,`Task execution requires nodeDefinition in execution input`,{nodeId:e.nodeId})};let t=this.nodeManifestRegistry.getManifest(e.nodeDefinition.nodeType);if(!t)return{ok:!1,error:Q(`DAG_VALIDATION_NODE_MANIFEST_NOT_FOUND`,`Node manifest is not registered for nodeType`,{nodeType:e.nodeDefinition.nodeType})};let n=await this.runner.runNode({input:e.input,context:{executionRoot:e.executionRoot,regexReplaceOperation:e.regexReplaceOperation,snapshotBudget:e.snapshotBudget,rootCreditBudget:e.rootCreditBudget,reserveCredits:e.reserveCredits,...e.byteLimits===void 0?{}:{byteLimits:e.byteLimits},...e.signal===void 0?{}:{signal:e.signal},dagId:e.dagId,dagRunId:e.dagRunId,taskRunId:e.taskRunId,nodeDefinition:e.nodeDefinition,nodeManifest:t,attempt:e.attempt,executionPath:e.executionPath,lineage:e.lineage??this.lineage??{rootRunId:e.dagRunId,depth:0,ancestorCompositeNodeTypes:[]},runCreditLimit:e.costPolicy?.runCreditLimit,currentTotalCredits:e.currentTotalCredits??0,...e.runtimeBaseUrl===void 0?{}:{runtimeBaseUrl:e.runtimeBaseUrl}}});return n.ok?{ok:!0,output:n.value.output,estimatedCredits:n.value.estimatedCredits,totalCredits:n.value.totalCredits}:n}};const e2={root:`.workflows`,workflowExt:`.json`};var Oqe=class{manifestByType=new Map;constructor(e){for(let t of e)this.manifestByType.set(t.nodeType,t)}getManifest(e){return this.manifestByType.get(e)}listManifests(){return[...this.manifestByType.values()]}};function kqe(e){let t=[],n=Pqe(e,``,t);return n!==void 0&&t.length===0?{ok:!0,value:n}:{ok:!1,error:t}}function t2(e,t,n){if(!Array.isArray(e)||e.length!==2)return q1(n,t,`expected a [number, number] pair`);let r=Z1(e[0],J1(t,0),n),i=Z1(e[1],J1(t,1),n);return r===void 0||i===void 0?void 0:[r,i]}function Aqe(e,t,n){if(!Array.isArray(e)||e.length!==6)return q1(n,t,`expected a 6-tuple [linkId, srcId, srcSlot, tgtId, tgtSlot, type]`);let r=[0,1,2,3,4].map(r=>Z1(e[r],J1(t,r),n)),i=X1(e[5],J1(t,5),n);if(r.some(e=>e===void 0)||i===void 0)return;let[a,o,s,c,l]=r;return[a,o,s,c,l,i]}function jqe(e,t,n){let r=Y1(e,t,n);if(r===void 0)return;let i=X1(r.name,J1(t,`name`),n),a=X1(r.type,J1(t,`type`),n),o=r.link,s=o===null?null:Z1(o,J1(t,`link`),n);return i===void 0||a===void 0||s===void 0?void 0:{name:i,type:a,link:s}}function Mqe(e,t,n){let r=Y1(e,t,n);if(r===void 0)return;let i=X1(r.name,J1(t,`name`),n),a=X1(r.type,J1(t,`type`),n),o=t0(r.links,J1(t,`links`),n,Z1),s=e0(r.slot_index,J1(t,`slot_index`),n,Z1);if(i===void 0||a===void 0||o===void 0)return;let c={name:i,type:a,links:o};return s!==void 0&&(c.slot_index=s),c}function Nqe(e,t,n){let r=Y1(e,t,n);if(r===void 0)return;let i=e=>J1(t,e),a=Z1(r.id,i(`id`),n),o=X1(r.type,i(`type`),n),s=t2(r.pos,i(`pos`),n),c=e0(r.size,i(`size`),n,t2),l=e0(r.flags,i(`flags`),n,Y1),u=e0(r.order,i(`order`),n,Z1),d=e0(r.mode,i(`mode`),n,Z1),f=e0(r.inputs,i(`inputs`),n,(e,t,n)=>t0(e,t,n,jqe)),p=e0(r.outputs,i(`outputs`),n,(e,t,n)=>t0(e,t,n,Mqe)),m=e0(r.properties,i(`properties`),n,Y1),h=e0(r.widgets_values,i(`widgets_values`),n,(e,t,n)=>Array.isArray(e)?e:q1(n,t,`expected an array`));if(a===void 0||o===void 0||s===void 0)return;let g={id:a,type:o,pos:s};return c!==void 0&&(g.size=c),l!==void 0&&(g.flags=l),u!==void 0&&(g.order=u),d!==void 0&&(g.mode=d),f!==void 0&&(g.inputs=f),p!==void 0&&(g.outputs=p),m!==void 0&&(g.properties=m),h!==void 0&&(g.widgets_values=h),g}function Pqe(e,t,n){let r=Y1(e,t,n);if(r===void 0)return;let i=e=>J1(t,e);if(`dagId`in r)return q1(n,i(`dagId`),`a workflow file carries no dagId — that is a definition file`);let a=Z1(r.last_node_id,i(`last_node_id`),n),o=Z1(r.last_link_id,i(`last_link_id`),n),s=t0(r.nodes,i(`nodes`),n,Nqe),c=t0(r.links,i(`links`),n,Aqe),l=Z1(r.version,i(`version`),n),u=e0(r.groups,i(`groups`),n,(e,t,n)=>Array.isArray(e)?e:q1(n,t,`expected an array`)),d=e0(r.config,i(`config`),n,Y1),f=e0(r.extra,i(`extra`),n,Y1);if(a===void 0||o===void 0||s===void 0||c===void 0||l===void 0)return;let p={last_node_id:a,last_link_id:o,nodes:s,links:c,version:l};return u!==void 0&&(p.groups=u),d!==void 0&&(p.config=d),f!==void 0&&(p.extra=f),p}function Fqe(e){return`parallel`in e}function n2(e,t){return e.id??`${e.nodeType}-${t}`}function r2(e,t){return e.find(e=>e.nodeType===t)}function i2(e,t){let n=t.map(e=>e.nodeType),r={action:`replace_node_type`,suggestion:n[0],options:n};return Q(`UNKNOWN_NODE_TYPE`,`Node type "${e}" is not registered`,{requestedType:e},r)}function Iqe(e,t){let n=[],r=[],i=[],a=[],o=0;for(let s of e.pipeline)if(Fqe(s)){let e=[];for(let c of s.parallel){let l=n2(c,o);o+=1;let u=r2(t,c.nodeType);if(!u)return{ok:!1,error:i2(c.nodeType,t),warnings:n};let d=a.map(e=>e.nodeId);r.push({nodeId:l,nodeType:c.nodeType,dependsOn:d,config:c.config??{}});for(let e of a){let t=c.toPort??u.defaultInputPort;if(!t){n.push({message:`Node "${l}" (${c.nodeType}) has no defaultInputPort; edge from "${e.nodeId}" requires explicit toPort`});continue}i.push({from:e.nodeId,to:l,bindings:[{outputKey:e.portKey,inputKey:t}]})}let f=s.fromPort??c.fromPort??u.defaultOutputPort;f?e.push({nodeId:l,portKey:f}):n.push({message:`Node "${l}" (${c.nodeType}) has no defaultOutputPort; downstream connections require explicit fromPort`})}a=e}else{let e=n2(s,o);o+=1;let c=r2(t,s.nodeType);if(!c)return{ok:!1,error:i2(s.nodeType,t),warnings:n};let l=a.map(e=>e.nodeId);r.push({nodeId:e,nodeType:s.nodeType,dependsOn:l,config:s.config??{}});for(let t of a){let r=s.toPort??c.defaultInputPort;if(!r){n.push({message:`Node "${e}" (${s.nodeType}) has no defaultInputPort; edge from "${t.nodeId}" requires explicit toPort`});continue}i.push({from:t.nodeId,to:e,bindings:[{outputKey:t.portKey,inputKey:r}]})}let u=s.fromPort??c.defaultOutputPort;a=u?[{nodeId:e,portKey:u}]:[]}return r.length===0?{ok:!1,error:Q(`EMPTY_PIPELINE`,`pipeline must contain at least one node`,void 0,{action:`add_node`,suggestion:`Add at least one node spec to the pipeline array`}),warnings:n}:{ok:!0,definition:{dagId:e.dagId??`dag-build-result`,version:1,status:`draft`,nodes:r,edges:i},warnings:n,nodeCount:r.length,edgeCount:i.length}}function Lqe(e){return(e.startsWith(`ConversationAgent`)?e.slice(17):e).replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`).replace(/^-/,``)}function Rqe(e,t){let n=new Map;for(let t of e.links)n.set(t[0],t);let r=t?.nodes??{},i=e.nodes.map(e=>{let t=r[String(e.id)],n={nodeId:t?.nodeId??`node-${e.id}`,nodeType:Lqe(e.type),dependsOn:[],config:e.properties?.agent_config??{},position:e.pos[0]!==0||e.pos[1]!==0?{x:e.pos[0],y:e.pos[1]}:void 0};return t?.retryPolicy&&(n.retryPolicy=t.retryPolicy),t?.timeoutMs!==void 0&&(n.timeoutMs=t.timeoutMs),t?.costPolicy&&(n.costPolicy=t.costPolicy),n}),a=new Map;e.nodes.forEach((e,t)=>{a.set(e.id,i[t])});let o=new Map,s=[],c=new Map;for(let t of e.links){let[,n,,r]=t,i=a.get(n),l=a.get(r);if(!i||!l)continue;let u=e.nodes.find(e=>e.id===n),d=e.nodes.find(e=>e.id===r),f=t[2],p=t[4],m=u?.outputs?.[f]?.name??`out${f}`,h=d?.inputs?.[p]?.name??`in${p}`,g=JSON.stringify([i.nodeId,l.nodeId]),_=o.get(g);_||(_=[],o.set(g,_),s.push({from:i.nodeId,to:l.nodeId,bindings:_})),_.push({outputKey:m,inputKey:h}),c.has(l.nodeId)||c.set(l.nodeId,new Set),c.get(l.nodeId).add(i.nodeId)}for(let e of i){let t=c.get(e.nodeId);t&&(e.dependsOn=[...t])}return{dagId:t?.dagId??`unknown`,version:t?.version??1,status:t?.status??`draft`,nodes:i,edges:s,...t?.costPolicy?{costPolicy:t.costPolicy}:{},...t?.inputSchema?{inputSchema:t.inputSchema}:{},...t?.outputSchema?{outputSchema:t.outputSchema}:{}}}const zqe={absentStatus:`draft`,absentEdgesAsEmpty:!0};function Bqe(e){if(typeof e!=`object`||!e||Array.isArray(e))return`unrecognised`;let t=e;return`dagId`in t?`definition`:`links`in t||`last_node_id`in t?`workflow-file`:`unrecognised`}function Vqe(e,t){let n=Bqe(e);if(n===`unrecognised`)return{ok:!1,error:{format:n,issues:[{path:``,message:`expected either a workflow file (nodes + links + version) or a definition (dagId + nodes)`}]}};if(n===`workflow-file`){let r=kqe(e);return r.ok?Hqe(Rqe(r.value,t),n):{ok:!1,error:{format:n,issues:r.error}}}let r=a0(e,zqe);return r.ok?r:{ok:!1,error:{format:n,issues:r.error}}}function Hqe(e,t){let n=a0(e);return n.ok?n:{ok:!1,error:{format:t,issues:n.error}}}function Uqe(e){return e.format===`unrecognised`?`Not a DAG file: ${i0(e.issues)}.`:`Malformed ${e.format===`workflow-file`?`workflow file`:`DAG definition`}: ${i0(e.issues)}`}var Wqe=class extends Error{failure;constructor(e){super(Uqe(e)),this.name=`DagFileDecodeError`,this.failure=e}};function a2(e,t){let n=Vqe(e,t);if(n.ok)return n.value;throw new Wqe(n.error)}function Gqe(e,t,n,r){for(let[i,a]of e.entries())if(a.taskRunId===t){e.set(i,{...a,leaseOwner:n,leaseUntil:r});return}}function Kqe(e,t){return[...e.values()].filter(e=>e.status===`running`&&(e.leaseUntil===void 0||e.leaseUntil<=t))}function o2(e,t){return`${e}:${t}`}var qqe=class{definitions=new Map;latestPublishedVersionByDagId=new Map;dagRuns=new Map;taskRuns=new Map;async commitExecution(e,t){let n=[...this.taskRuns.values()].filter(t=>t.dagRunId===e),r=WGe(this.dagRuns.get(e),n,t);return r.dagRun&&this.dagRuns.set(e,r.dagRun),r.taskRun&&this.taskRuns.set(o2(e,r.taskRun.taskRunId),r.taskRun),r.result}async saveDefinition(e){let t=`${e.dagId}:${e.version}`;if(this.definitions.set(t,e),e.status===`published`){let t=this.latestPublishedVersionByDagId.get(e.dagId)??0;e.version>t&&this.latestPublishedVersionByDagId.set(e.dagId,e.version)}}async getDefinition(e,t){let n=`${e}:${t}`;return this.definitions.get(n)}async listDefinitions(){return[...this.definitions.values()].sort((e,t)=>e.dagId.localeCompare(t.dagId)||e.version-t.version)}async listDefinitionsByDagId(e){return[...this.definitions.values()].filter(t=>t.dagId===e).sort((e,t)=>e.version-t.version)}async getLatestPublishedDefinition(e){let t=this.latestPublishedVersionByDagId.get(e);if(t)return this.definitions.get(`${e}:${t}`)}async deleteDefinition(e,t){this.definitions.delete(`${e}:${t}`);let n=[...this.definitions.values()].filter(t=>t.dagId===e&&t.status===`published`).sort((e,t)=>e.version-t.version);if(n.length===0){this.latestPublishedVersionByDagId.delete(e);return}this.latestPublishedVersionByDagId.set(e,n[n.length-1].version)}async createDagRun(e){this.dagRuns.set(e.dagRunId,e)}async getDagRun(e){return this.dagRuns.get(e)}async listDagRuns(){return[...this.dagRuns.values()].sort((e,t)=>e.dagRunId.localeCompare(t.dagRunId))}async getDagRunByRunKey(e){for(let t of this.dagRuns.values())if(t.runKey===e)return t}async updateDagRunStatus(e,t,n){let r=this.dagRuns.get(e);if(!r)return;let i={...r,status:t,endedAt:n};this.dagRuns.set(e,i)}async deleteDagRun(e){this.dagRuns.delete(e)}async createTaskRun(e){let t=o2(e.dagRunId,e.taskRunId);this.taskRuns.set(t,e)}async getTaskRun(e){for(let t of this.taskRuns.values())if(t.taskRunId===e)return t}async listTaskRunsByDagRunId(e){let t=[];for(let n of this.taskRuns.values())n.dagRunId===e&&t.push(n);return t}async deleteTaskRunsByDagRunId(e){for(let[t,n]of this.taskRuns.entries())n.dagRunId===e&&this.taskRuns.delete(t)}async updateTaskRunStatus(e,t,n){for(let[r,i]of this.taskRuns.entries()){if(i.taskRunId!==e)continue;let a={...i,status:t,...[`failed`,`cancelled`,`queued`].includes(t)?{reservedCredits:void 0,reservationAttempt:void 0,reservationOwner:void 0}:{},errorCode:n?.code,errorMessage:n?.message};this.taskRuns.set(r,a);return}}async setTaskRunLease(e,t,n){Gqe(this.taskRuns,e,t,n)}async listStaleRunningTaskRuns(e){return Kqe(this.taskRuns,e)}async saveTaskRunSnapshots(e,t,n,r,i){for(let[a,o]of this.taskRuns.entries()){if(o.taskRunId!==e)continue;let s={...o,inputSnapshot:typeof t==`string`?t:o.inputSnapshot,outputSnapshot:typeof n==`string`?n:o.outputSnapshot,estimatedCredits:typeof r==`number`?r:o.estimatedCredits,totalCredits:typeof i==`number`?i:o.totalCredits};this.taskRuns.set(a,s);return}}async incrementTaskAttempt(e){for(let[t,n]of this.taskRuns.entries()){if(n.taskRunId!==e)continue;let r={...n,attempt:n.attempt+1,reservedCredits:void 0,reservationAttempt:void 0,reservationOwner:void 0};this.taskRuns.set(t,r);return}}},s2=class{pendingQueue=[];inFlight=new Map;waiters=[];async enqueue(e){this.pendingQueue.push(e),this.notifyNextWaiter()}async dequeue(e,t,n=0){let r=this.tryDequeue(e,t);return r||n<=0?r:(await this.waitForMessage(n),this.tryDequeue(e,t))}async ack(e){this.inFlight.delete(e)}async nack(e){let t=this.inFlight.get(e);t&&(this.inFlight.delete(e),this.pendingQueue.unshift(t.message),this.notifyNextWaiter())}tryDequeue(e,t){this.requeueExpiredMessages();let n=this.pendingQueue.shift();if(!n)return;let r=Date.now();return this.inFlight.set(n.messageId,{message:n,ownerId:e,visibleAtEpochMs:r+t}),n}requeueExpiredMessages(){let e=Date.now();for(let[t,n]of this.inFlight.entries())n.visibleAtEpochMs>e||(this.inFlight.delete(t),this.pendingQueue.push(n.message))}async waitForMessage(e){return new Promise(t=>{let n={resolve:()=>{clearTimeout(n.timeout),this.removeWaiter(n),t()},timeout:setTimeout(()=>{n.resolve()},e)};this.waiters.push(n)})}notifyNextWaiter(){this.waiters.shift()?.resolve()}removeWaiter(e){let t=this.waiters.indexOf(e);t>=0&&this.waiters.splice(t,1)}},Jqe=class{records=new Map;async acquire(e,t,n){let r=new Date().toISOString(),i=Date.now(),a=this.records.get(e);if(a&&Date.parse(a.leaseUntil)>i)return;let o={leaseKey:e,ownerId:t,acquiredAt:r,leaseUntil:new Date(i+n).toISOString()};return this.records.set(e,o),o}async release(e,t){let n=this.records.get(e);!n||n.ownerId!==t||this.records.delete(e)}async get(e){return this.records.get(e)}},Yqe=class{nowIso(){return new Date().toISOString()}nowEpochMs(){return Date.now()}},Xqe=class{listeners=new Set;logger;constructor(e){this.logger=e}publish(e){let t=[];for(let n of[...this.listeners])try{n(e)}catch(n){t.push(n),this.logger&&this.logger.error(`RunProgressEventBus listener threw an error`,{eventType:e.eventType,error:n instanceof Error?n.message:String(n)})}if(t.length>0&&!this.logger)throw t[0]instanceof Error?t[0]:Error(String(t[0]))}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}};function Zqe(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t||Array.isArray(t)?{ok:!1,error:Q(`DAG_VALIDATION_PAYLOAD_INVALID`,`Payload must be a JSON object`)}:{ok:!0,value:t}}catch{return{ok:!1,error:Q(`DAG_VALIDATION_PAYLOAD_PARSE_FAILED`,`Failed to parse payload JSON`)}}}function Qqe(e){let t;try{t=JSON.parse(e)}catch{return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_SNAPSHOT_PARSE_FAILED`,`Failed to parse definition snapshot JSON`)}}return o0(t,`DAG_VALIDATION_DEFINITION_SNAPSHOT_INVALID`,`Definition snapshot must be a valid DAG definition object`)}async function $qe(e,t,n,r,i){let{dagRunId:a,definition:o,input:s}=e,c=o.nodes.filter(e=>e.dependsOn.length===0);if(c.length===0)return{ok:!1,error:Q(`DAG_VALIDATION_NO_ENTRY_NODE`,`DAG must include at least one entry node (dependsOn = [])`,{dagId:o.dagId,version:o.version})};let l=G1.transition(`created`,`QUEUE`);if(!l.ok)return l;if(!(await t.commitExecution(a,{kind:`transition-run`,expectedStatus:`created`,event:`QUEUE`})).applied)return{ok:!0,value:{taskRunIds:[]}};let u=G1.transition(`queued`,`START`);if(!u.ok)return u;if(!(await t.commitExecution(a,{kind:`transition-run`,expectedStatus:`queued`,event:`START`})).applied)return{ok:!0,value:{taskRunIds:[]}};i?.publish({dagRunId:a,eventType:X0.STARTED,occurredAt:r.nowIso(),dagId:o.dagId,version:o.version});let d=[],f=[];for(let e of c){let n=`${a}:${e.nodeId}:attempt:1`;(await t.commitExecution(a,{kind:`admit`,dependsOn:[],taskRun:{taskRunId:n,dagRunId:a,nodeId:e.nodeId,status:`queued`,attempt:1}})).applied&&(d.push(n),f.push({messageId:`${n}:message`,dagRunId:a,taskRunId:n,nodeId:e.nodeId,attempt:1,executionPath:[`dagId:${o.dagId}`,`dagRunId:${a}`,`nodeId:${e.nodeId}`,`taskRunId:${n}`,`attempt:1`],payload:s,createdAt:r.nowIso()}))}for(let e of f)try{await n.enqueue(e)}catch(n){return eJe(a,e.taskRunId,e.nodeId,d,n,t,r,i)}return{ok:!0,value:{taskRunIds:d}}}async function eJe(e,t,n,r,i,a,o,s){let c=P1(`DAG_DISPATCH_ENQUEUE_FAILED`,`Failed to enqueue entry task`,{dagRunId:e,taskRunId:t,nodeId:n,errorMessage:i instanceof Error&&i.message.trim().length>0?i.message:`Unknown error`});G1.transition(`running`,`COMPLETE_FAILURE`).ok&&(await a.commitExecution(e,{kind:`transition-run`,expectedStatus:`running`,event:`COMPLETE_FAILURE`,endedAt:o.nowIso()})).applied&&s?.publish({dagRunId:e,eventType:X0.FAILED,occurredAt:o.nowIso(),error:c});for(let t of r)await a.commitExecution(e,{kind:`cancel-task`,taskRunId:t,error:c});return{ok:!1,error:c}}function tJe(e,t){return e===void 0||t===void 0?e===t:e.rootRunId===t.rootRunId&&e.parentRunId===t.parentRunId&&e.depth===t.depth&&e.maxDepth===t.maxDepth&&e.ancestorCompositeNodeTypes.length===t.ancestorCompositeNodeTypes.length&&e.ancestorCompositeNodeTypes.every((e,n)=>e===t.ancestorCompositeNodeTypes[n])}var nJe=class{storage;queue;clock;runProgressEventReporter;snapshotBudget;timeSemanticsService;constructor(e,t,n,r,i){this.storage=e,this.queue=t,this.clock=n,this.runProgressEventReporter=r,this.snapshotBudget=i,this.timeSemanticsService=new wqe(n)}async createRun(e){let t=e.version?await this.storage.getDefinition(e.dagId,e.version):await this.storage.getLatestPublishedDefinition(e.dagId);if(!t)return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_NOT_FOUND`,`Published DAG definition was not found`,{dagId:e.dagId,hasVersion:!!e.version})};if(t.status!==`published`)return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_NOT_PUBLISHED`,`Only published definitions can be executed`,{dagId:t.dagId,version:t.version,status:t.status})};let n=this.timeSemanticsService.resolve(e.trigger,e.logicalDate);if(!n.ok)return n;let r;try{r=Y0(e.lineage)}catch{return{ok:!1,error:Q(`DAG_VALIDATION_RUN_LINEAGE_INVALID`,`Composite child run lineage is invalid`,{dagId:t.dagId})}}let i=e.rerunKey?`${t.dagId}:${n.value.logicalDate}:rerun:${e.rerunKey}`:`${t.dagId}:${n.value.logicalDate}`,a=await this.storage.getDagRunByRunKey(i);if(a){let e;try{e=Y0(a.lineage)}catch{return{ok:!1,error:Q(`DAG_VALIDATION_RUN_LINEAGE_INVALID`,`Existing run for this run key has invalid persisted lineage`,{dagId:t.dagId,runKey:i})}}return tJe(e,r)?{ok:!0,value:{dagRunId:a.dagRunId,dagId:a.dagId,version:a.version,logicalDate:a.logicalDate,status:a.status}}:{ok:!1,error:Q(`DAG_VALIDATION_RUN_KEY_LINEAGE_MISMATCH`,`An existing run for this run key has different composite lineage`,{dagId:t.dagId,runKey:i,existingDagRunId:a.dagRunId})}}let o=this.generateDagRunId(t.dagId,n.value.logicalDate,e.rerunKey);try{let a=(a,s)=>this.storage.createDagRun({dagRunId:o,dagId:t.dagId,version:t.version,status:`created`,definitionSnapshot:a,inputSnapshot:s,runKey:i,logicalDate:n.value.logicalDate,trigger:e.trigger,...r===void 0?{}:{lineage:r},startedAt:this.clock.nowIso()});if(this.snapshotBudget){let n=await this.snapshotBudget.admitRun(t,e.input,a);if(!n.ok)return n}else await a(JSON.stringify(t),JSON.stringify(e.input))}catch(e){return this.snapshotBudget?{ok:!1,error:F1(`DAG_RUN_SNAPSHOT_PERSISTENCE_UNCERTAIN`,`Run snapshot persistence outcome is uncertain; root snapshot admission is closed`,!1)}:{ok:!1,error:P1(`DAG_DISPATCH_DAG_RUN_CREATE_FAILED`,`Failed to create DagRun`,{dagId:t.dagId,version:t.version,runKey:i,errorMessage:this.resolveErrorMessage(e instanceof Error?e:void 0)})}}return{ok:!0,value:{dagRunId:o,dagId:t.dagId,version:t.version,logicalDate:n.value.logicalDate,status:`created`}}}async startCreatedRun(e){let t=await this.storage.getDagRun(e);if(!t)return{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})};if(t.status!==`created`){let n=await this.storage.listTaskRunsByDagRunId(e);return{ok:!0,value:{dagRunId:e,dagId:t.dagId,version:t.version,logicalDate:t.logicalDate,taskRunIds:n.map(e=>e.taskRunId)}}}if(typeof t.definitionSnapshot!=`string`||t.definitionSnapshot.trim().length===0)return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_SNAPSHOT_MISSING`,`DagRun definition snapshot is missing`,{dagRunId:e})};let n=Qqe(t.definitionSnapshot);if(!n.ok)return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_SNAPSHOT_INVALID`,`DagRun definition snapshot is invalid`,{dagRunId:e})};let r=Zqe(t.inputSnapshot??`{}`);if(!r.ok)return{ok:!1,error:Q(`DAG_VALIDATION_RUN_INPUT_SNAPSHOT_INVALID`,`DagRun input snapshot is invalid`,{dagRunId:e})};let i=await $qe({dagRunId:e,definition:n.value,input:r.value},this.storage,this.queue,this.clock,this.runProgressEventReporter);return i.ok?{ok:!0,value:{dagRunId:e,dagId:t.dagId,version:t.version,logicalDate:t.logicalDate,taskRunIds:i.value.taskRunIds}}:i}async startRun(e){let t=await this.createRun(e);if(!t.ok)return t;if(t.value.status===`created`)return this.startCreatedRun(t.value.dagRunId);let n=await this.storage.listTaskRunsByDagRunId(t.value.dagRunId);return{ok:!0,value:{dagRunId:t.value.dagRunId,dagId:t.value.dagId,version:t.value.version,logicalDate:t.value.logicalDate,taskRunIds:n.map(e=>e.taskRunId)}}}generateDagRunId(e,t,n){let r=Date.parse(t);return n?`${e}:run:${r}:rerun:${n}`:`${e}:run:${r}`}resolveErrorMessage(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}},rJe=class{storage;constructor(e){this.storage=e}async getRun(e){let t=await this.storage.getDagRun(e);return t?{ok:!0,value:{dagRun:t,taskRuns:await this.storage.listTaskRunsByDagRunId(e)}}:{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})}}},iJe=class{storage;clock;notifier;constructor(e,t,n){this.storage=e,this.clock=t,this.notifier=n}async cancelRun(e){let t=await this.storage.getDagRun(e);if(!t)return{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})};let n=G1.transition(t.status,`CANCEL`);if(!n.ok)return n;let r=await this.storage.commitExecution(e,{kind:`transition-run`,expectedStatus:t.status,event:`CANCEL`,endedAt:this.clock.nowIso()});if(!r.applied){if(r.runStatus===`cancelled`)return this.notify(e),{ok:!0,value:{dagRunId:e,status:`cancelled`}};if(r.runStatus!==void 0){let t=G1.transition(r.runStatus,`CANCEL`);return t.ok?this.cancelRun(e):t}return{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})}}return this.notify(e),{ok:!0,value:{dagRunId:e,status:`cancelled`}}}notify(e){try{this.notifier?.notifyRunCancelled(e)}catch{}}};async function c2(e,t,n,r){let i=await t.commitExecution(e,{kind:`finalize`,endedAt:n.nowIso()});if(i.error)return{ok:!1,error:i.error};if(i.runStatus===void 0)return{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun not found while finalizing run status`,{dagRunId:e})};if(!i.applied)return{ok:!0,value:void 0};let a=i.runStatus===`failed`,o=await t.listTaskRunsByDagRunId(e);return a?aJe(e,o,n,r):r?.publish({dagRunId:e,eventType:X0.COMPLETED,occurredAt:n.nowIso()}),{ok:!0,value:void 0}}function aJe(e,t,n,r){let i=t.find(e=>e.status===`failed`),a=typeof i?.errorCode==`string`&&typeof i.errorMessage==`string`?F1(i.errorCode,i.errorMessage,!1,{dagRunId:e,taskRunId:i.taskRunId,nodeId:i.nodeId}):F1(`DAG_TASK_EXECUTION_FAILED`,`Run completed with failure.`,!1,{dagRunId:e});r?.publish({dagRunId:e,eventType:X0.FAILED,occurredAt:n.nowIso(),error:a})}async function l2(e,t,n,r,i){await e.updateTaskRunStatus(n.taskRunId,r,i),await e.setTaskRunLease(n.taskRunId,void 0,void 0),await c2(n.dagRunId,e,t)}async function oJe(e,t){let n=K1.transition(t.status,`CANCEL`);return n.ok?(await e.updateTaskRunStatus(t.taskRunId,n.value.nextStatus,{code:`DAG_TASK_EXECUTION_ORPHANED`,category:`task_execution`,message:`Task's DAG run ${t.dagRunId} no longer exists; the task cannot be run or finalized`,retryable:!1,context:{taskRunId:t.taskRunId,dagRunId:t.dagRunId}}),await e.setTaskRunLease(t.taskRunId,void 0,void 0),{ok:!0,value:void 0}):n}async function sJe(e,t,n,r,i){let a=await e.listStaleRunningTaskRuns(n.nowIso()),o={requeued:[],abandoned:[],skipped:[],failed:[],orphaned:[]};for(let s of a){let a=`taskRun:${s.taskRunId}`;if(!await r.acquire(a,i.workerId,i.leaseDurationMs)){o.skipped.push(s.taskRunId);continue}try{let r=await e.getTaskRun(s.taskRunId);if(r===void 0||r.status!==`running`||fJe(r,n.nowIso())){o.skipped.push(s.taskRunId);continue}await cJe(e,t,n,r,i.maxAttempts,o)}catch(e){o.failed.push({taskRunId:s.taskRunId,error:e})}finally{await r.release(a,i.workerId)}}return o}async function cJe(e,t,n,r,i,a){{let o=K1.transition(r.status,`RECLAIM`);if(!o.ok){a.skipped.push(r.taskRunId);return}let s=await e.getDagRun(r.dagRunId);if(s===void 0){if(!(await oJe(e,r)).ok){a.skipped.push(r.taskRunId);return}a.orphaned.push(r.taskRunId);return}if(lJe.has(s.status)){let t=K1.transition(r.status,`CANCEL`);if(!t.ok){a.skipped.push(r.taskRunId);return}await l2(e,n,r,t.value.nextStatus),a.abandoned.push(r.taskRunId);return}if(r.attempt>=i){let t=K1.transition(r.status,`COMPLETE_FAILURE`);if(!t.ok){a.skipped.push(r.taskRunId);return}await l2(e,n,r,t.value.nextStatus,{code:`DAG_TASK_EXECUTION_ABANDONED`,category:`task_execution`,message:`Task was abandoned by its worker ${r.attempt} time(s) and has no attempts left`,retryable:!1,context:{taskRunId:r.taskRunId,attempt:r.attempt,maxAttempts:i}}),a.abandoned.push(r.taskRunId);return}let c=r.attempt+1;await e.incrementTaskAttempt(r.taskRunId),await t.enqueue(uJe(r,c,n.nowIso())),await e.updateTaskRunStatus(r.taskRunId,o.value.nextStatus),await e.setTaskRunLease(r.taskRunId,void 0,void 0),a.requeued.push(r.taskRunId)}}const lJe=new Set([`success`,`failed`,`cancelled`]);function uJe(e,t,n){return{payload:dJe(e.inputSnapshot),messageId:`${e.taskRunId}:reclaim:${t}`,dagRunId:e.dagRunId,taskRunId:e.taskRunId,nodeId:e.nodeId,attempt:t,executionPath:[`dagRunId:${e.dagRunId}`,`nodeId:${e.nodeId}`,`taskRunId:${e.taskRunId}`,`attempt:${t}`,`reclaimed:true`],createdAt:n}}function dJe(e){if(e===void 0)return{};try{let t=JSON.parse(e);return typeof t==`object`&&t?t:{}}catch{return{}}}function fJe(e,t){return e.leaseUntil!==void 0&&e.leaseUntil>t}var pJe=class{clock;lease;options;lastSweepAtMs=0;sweeping=!1;constructor(e,t,n){this.clock=e,this.lease=t,this.options=n}async sweepIfDue(e,t){let n=this.clock.nowEpochMs();if(!(this.sweeping||n-this.lastSweepAtMs<this.options.leaseDurationMs)){this.sweeping=!0;try{let n=(await sJe(e,t,this.clock,this.lease,this.options)).failed[0];if(n===void 0)return;throw n.error}catch(e){return{code:`DAG_TASK_SWEEP_FAILED`,category:`task_execution`,message:`Stale-task sweep failed: ${e instanceof Error?e.message:String(e)}`,retryable:!0,context:{workerId:this.options.workerId}}}finally{this.lastSweepAtMs=this.clock.nowEpochMs(),this.sweeping=!1}}}};function mJe(e,t){let n=e.map(e=>e.startsWith(`attempt:`)?`attempt:${t}`:e);return n.some(e=>e.startsWith(`attempt:`))||n.push(`attempt:${t}`),n}function u2(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}async function d2(e,t,n,r,i,a,o,s){if(r.deadLetterEnabled){let t=await gJe(e,n,r,o);if(!t.ok)return f2(a,e.messageId,t.error)}let c=await c2(e.dagRunId,i,o,s);return c.ok?p2(a,e.messageId,t,!1):f2(a,e.messageId,c.error)}async function hJe(e,t,n,r){let i=e.attempt+1,a={...e,messageId:`${e.taskRunId}:message:${i}`,attempt:i,executionPath:mJe(e.executionPath,i),createdAt:r.nowIso()};try{await n.enqueue(a)}catch(r){return f2(n,e.messageId,P1(`DAG_DISPATCH_ENQUEUE_RETRY_FAILED`,`Failed to enqueue retry message`,{taskRunId:t,attempt:i,errorMessage:u2(r)}))}return p2(n,e.messageId,t,!0)}async function gJe(e,t,n,r){if(!n.deadLetterQueue)return{ok:!1,error:Q(`DAG_VALIDATION_DEAD_LETTER_QUEUE_NOT_CONFIGURED`,`deadLetterEnabled requires deadLetterQueue to be configured`,{taskRunId:e.taskRunId})};let i={...e,messageId:`${e.taskRunId}:dlq:${r.nowEpochMs()}`,payload:{...e.payload,dlqReasonCode:t.code,dlqReasonMessage:t.message,dlqSourceMessageId:e.messageId},createdAt:r.nowIso()};try{return await n.deadLetterQueue.enqueue(i),{ok:!0,value:void 0}}catch(t){return{ok:!1,error:P1(`DAG_DISPATCH_DEAD_LETTER_ENQUEUE_FAILED`,`Failed to enqueue dead letter message`,{taskRunId:e.taskRunId,originalMessageId:e.messageId,errorMessage:u2(t)})}}}async function f2(e,t,n){return await e.ack(t),{ok:!1,error:n}}async function p2(e,t,n,r){return await e.ack(t),{ok:!0,value:{processed:!0,taskRunId:n,retried:r}}}function _Je(e){if(e.status!==`running`)return{ok:!0,value:e.status};let t=K1.transition(e.status,`RECLAIM`);return t.ok?{ok:!0,value:t.value.nextStatus}:t}function m2(e,t){return Math.max(e,t)+3e4}function vJe(e,t,n){return new Date(e.nowEpochMs()+m2(t,n)).toISOString()}async function yJe(e){let{storage:t,clock:n,message:r,taskRun:i}=e,a=i.status===`running`,o=_Je(i);if(!o.ok)return o;if(a){if(i.attempt>=e.options.maxAttempts)return{ok:!1,error:{code:`DAG_TASK_EXECUTION_ABANDONED`,category:`task_execution`,message:`Task was abandoned by its worker ${i.attempt} time(s) and has no attempts left`,retryable:!1,context:{taskRunId:i.taskRunId,attempt:i.attempt,maxAttempts:e.options.maxAttempts}}};await t.incrementTaskAttempt(i.taskRunId)}let s=a?i.attempt+1:i.attempt,c=K1.transition(o.value,`START`);return c.ok?(await t.setTaskRunLease(i.taskRunId,e.options.workerId,vJe(n,e.timeoutMs,e.options.leaseDurationMs)),await t.updateTaskRunStatus(i.taskRunId,c.value.nextStatus),e.reporter?.publish({dagRunId:r.dagRunId,eventType:Z0.STARTED,occurredAt:n.nowIso(),taskRunId:i.taskRunId,nodeId:r.nodeId,input:r.payload}),{ok:!0,value:s}):c}async function bJe(e,t,n,r,i,a){let o=`taskRun:${t}`;if(!await e.acquire(o,n,r))return a();try{return await i()}finally{await e.release(o,n)}}async function xJe(e,t){let{message:n,taskRun:r,storage:i,queue:a,clock:o}=t;if(e.code!==`DAG_TASK_EXECUTION_ABANDONED`)return f2(a,n.messageId,e);let s=K1.transition(r.status,`COMPLETE_FAILURE`);return s.ok?(await i.updateTaskRunStatus(r.taskRunId,s.value.nextStatus,e),await i.setTaskRunLease(r.taskRunId,void 0,void 0),d2(n,r.taskRunId,e,t.options,i,a,o,t.reporter)):f2(a,n.messageId,s.error)}function SJe(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}function CJe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function wJe(e,t,n){let r=e.nodes.find(e=>e.nodeId===n);if(!r)return{ok:!1,error:Q(`DAG_VALIDATION_DOWNSTREAM_NODE_NOT_FOUND`,`Downstream node was not found while building payload`,{downstreamNodeId:n})};let i=e.edges.filter(e=>e.to===n);if(i.length===0)return{ok:!0,value:{}};let a={};for(let e of i){let n=TJe(a,e,r,t);if(!n.ok)return n}return AJe(a,r.inputs??[]),{ok:!0,value:a}}function TJe(e,t,n,r){if(!t.bindings||t.bindings.length===0)return{ok:!1,error:Q(`DAG_VALIDATION_BINDING_REQUIRED`,`Incoming edge must define at least one binding`,{from:t.from,to:t.to})};let i=EJe(t.from,t.to,r);if(!i.ok)return i;let a=i.value;for(let r of t.bindings){let i=DJe(e,r,a,t,n);if(!i.ok)return i}return{ok:!0,value:void 0}}function EJe(e,t,n){let r=n.find(t=>t.nodeId===e&&t.status===`success`);if(!r||!r.outputSnapshot)return{ok:!1,error:Q(`DAG_VALIDATION_UPSTREAM_OUTPUT_MISSING`,`Upstream output snapshot is missing for binding dispatch`,{from:e,to:t})};try{let n=JSON.parse(r.outputSnapshot);return CJe(n)?{ok:!0,value:n}:{ok:!1,error:Q(`DAG_VALIDATION_UPSTREAM_OUTPUT_INVALID`,`Upstream output snapshot has invalid payload shape`,{from:e,to:t})}}catch(n){return{ok:!1,error:Q(`DAG_VALIDATION_UPSTREAM_OUTPUT_PARSE_FAILED`,`Failed to parse upstream output snapshot`,{from:e,to:t,errorMessage:SJe(n)})}}}function DJe(e,t,n,r,i){let a=n[t.outputKey];if(a===void 0)return{ok:!1,error:Q(`DAG_VALIDATION_BINDING_OUTPUT_KEY_MISSING`,`Binding outputKey was not found in upstream output`,{from:r.from,outputKey:t.outputKey})};if((i.inputs??[]).find(e=>e.key===t.inputKey)?.isList)return OJe(e,t.inputKey,a,r.to);let o=p0(t.inputKey);return o?kJe(e,o,a,t.inputKey,r.to,i):e[t.inputKey]===void 0?(e[t.inputKey]=a,{ok:!0,value:void 0}):{ok:!1,error:Q(`DAG_VALIDATION_BINDING_INPUT_KEY_CONFLICT`,`Multiple bindings target the same input key`,{to:r.to,inputKey:t.inputKey})}}function OJe(e,t,n,r){Array.isArray(e[t])||(e[t]=[]);let i=e[t];return Array.isArray(i)?(i.push(n),{ok:!0,value:void 0}):{ok:!1,error:Q(`DAG_VALIDATION_BINDING_LIST_PAYLOAD_INVALID`,`List payload container is invalid`,{to:r,inputKey:t})}}function kJe(e,t,n,r,i,a){if(!(a.inputs??[]).find(e=>e.key===t.portKey)?.isList)return{ok:!1,error:Q(`DAG_VALIDATION_BINDING_INPUT_KEY_MISSING`,`Binding inputKey does not resolve to a valid list input port`,{to:i,inputKey:r})};let o=e[t.portKey],s=Array.isArray(o)?o:[];return s[t.index]=n,e[t.portKey]=s,{ok:!0,value:void 0}}function AJe(e,t){for(let n of t){if(!n.isList)continue;let t=e[n.key];Array.isArray(t)&&(e[n.key]=t.filter(e=>e!==void 0))}}function jJe(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}async function MJe(e,t,n,r,i,a,o){let s=t.nodes.filter(e=>e.dependsOn.includes(n));if(s.length===0)return{ok:!0,value:void 0};let c=await i.listTaskRunsByDagRunId(e.dagRunId);for(let n of s){let r=await NJe(e,t,n,c,i,a,o);if(!r.ok)return r}return{ok:!0,value:void 0}}async function NJe(e,t,n,r,i,a,o){if(r.some(e=>e.nodeId===n.nodeId)||!n.dependsOn.every(e=>r.some(t=>t.nodeId===e&&t.status===`success`)))return{ok:!0,value:void 0};let s=`${e.dagRunId}:${n.nodeId}:attempt:1`;if(!(await i.commitExecution(e.dagRunId,{kind:`admit`,dependsOn:n.dependsOn,taskRun:{taskRunId:s,dagRunId:e.dagRunId,nodeId:n.nodeId,status:`queued`,attempt:1}})).applied)return{ok:!0,value:void 0};let c=wJe(t,r,n.nodeId);if(!c.ok)return c;let l={messageId:`${s}:message:1`,dagRunId:e.dagRunId,taskRunId:s,nodeId:n.nodeId,attempt:1,executionPath:[`dagId:${e.dagId}`,`dagRunId:${e.dagRunId}`,`nodeId:${n.nodeId}`,`taskRunId:${s}`,`attempt:1`],payload:c.value,createdAt:o.nowIso()};try{await a.enqueue(l)}catch(t){let r=K1.transition(`queued`,`CANCEL`);return r.ok&&await i.updateTaskRunStatus(s,r.value.nextStatus),{ok:!1,error:P1(`DAG_DISPATCH_ENQUEUE_DOWNSTREAM_FAILED`,`Failed to enqueue downstream task`,{dagRunId:e.dagRunId,nodeId:n.nodeId,errorMessage:jJe(t)})}}return r.push({taskRunId:s,dagRunId:e.dagRunId,nodeId:n.nodeId,status:`queued`,attempt:1}),{ok:!0,value:void 0}}var PJe=class{storage;queue;clock;options;runProgressEventReporter;snapshotBudget;constructor(e,t,n,r,i,a){this.storage=e,this.queue=t,this.clock=n,this.options=r,this.runProgressEventReporter=i,this.snapshotBudget=a}async handleSuccessPath(e,t,n,r,i,a,o){let s=n=>this.storage.commitExecution(e.dagRunId,{kind:`settle`,taskRunId:t,attempt:e.attempt,leaseOwner:this.options.workerId,status:`success`,outputSnapshot:n,estimatedCredits:a,totalCredits:o}),c=this.snapshotBudget?await this.snapshotBudget.admitValue(`output`,i,s):{ok:!0,value:await s(JSON.stringify(i))};if(!c.ok)return this.handleFailurePath(e,t,c.error);if(!c.value.applied){let[n,r]=await Promise.all([this.storage.getDagRun(e.dagRunId),this.storage.getTaskRun(t)]);return n?.status===`running`&&r?.status===`running`&&r.attempt===e.attempt&&r.leaseOwner===this.options.workerId?this.handleFailurePath(e,t,Q(`DAG_VALIDATION_EXECUTION_SETTLEMENT_REJECTED`,`Current task attempt could not settle its successful output`,{taskRunId:t})):p2(this.queue,e.messageId,t,!1)}this.runProgressEventReporter?.publish({dagRunId:e.dagRunId,eventType:Z0.COMPLETED,occurredAt:this.clock.nowIso(),taskRunId:t,nodeId:e.nodeId,input:e.payload,output:i});let l=await MJe(n,r,e.nodeId,i,this.storage,this.queue,this.clock);if(!l.ok)return f2(this.queue,e.messageId,l.error);let u=await c2(e.dagRunId,this.storage,this.clock,this.runProgressEventReporter);return u.ok?p2(this.queue,e.messageId,t,!1):f2(this.queue,e.messageId,u.error)}async handleFailurePath(e,t,n){let r=this.options.retryEnabled&&n.retryable&&e.attempt<this.options.maxAttempts;return(await this.storage.commitExecution(e.dagRunId,{kind:`settle`,taskRunId:t,attempt:e.attempt,leaseOwner:this.options.workerId,status:`failed`,reserveRetry:r,error:n})).applied?(this.runProgressEventReporter?.publish({dagRunId:e.dagRunId,eventType:Z0.FAILED,occurredAt:this.clock.nowIso(),taskRunId:t,nodeId:e.nodeId,input:e.payload,error:n}),r?hJe(e,t,this.queue,this.clock):d2(e,t,n,this.options,this.storage,this.queue,this.clock,this.runProgressEventReporter)):p2(this.queue,e.messageId,t,!1)}};function FJe(e,t){return F1(`DAG_TASK_EXECUTION_TIMEOUT`,`Task execution timed out after ${t}ms`,!0,{taskRunId:e,timeoutMs:t})}function h2(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}function g2(e,t,n,r){return new Promise(i=>{let a=new AbortController,o=!1,s,c=e=>{o||(o=!0,clearTimeout(s),t.signal?.removeEventListener(`abort`,u),i(e))},l=n=>{if(!o){if(o=!0,clearTimeout(s),t.signal?.removeEventListener(`abort`,u),a.abort(n),!e.stopAndWait){i({ok:!1,error:n});return}Promise.resolve().then(()=>e.stopAndWait?.(t)).then(()=>i({ok:!1,error:n}),e=>i({ok:!1,error:{...n,retryable:!1,context:{...n.context,isolationStopError:h2(e)}}}))}},u=()=>l(I1(r));if(t.signal?.aborted){u();return}t.signal?.addEventListener(`abort`,u,{once:!0}),s=setTimeout(()=>l(FJe(r,n)),n);let d=e=>c({ok:!1,error:F1(`DAG_TASK_EXECUTION_EXCEPTION`,`Task executor threw an exception`,!0,{taskRunId:r,errorMessage:h2(e)})});try{e.execute({...t,signal:a.signal}).then(c,d)}catch(e){d(e)}})}function IJe(e){let t=0;for(let n of e)typeof n.totalCredits==`number`&&n.totalCredits>t&&(t=n.totalCredits);return t}function LJe(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}function RJe(e,t){if(typeof e.definitionSnapshot!=`string`||e.definitionSnapshot.trim().length===0)return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_SNAPSHOT_MISSING`,`DagRun definition snapshot is missing`,{dagRunId:t})};let n;try{n=JSON.parse(e.definitionSnapshot)}catch(e){return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_SNAPSHOT_PARSE_FAILED`,`Failed to parse DagRun definition snapshot`,{dagRunId:t,errorMessage:LJe(e)})}}return o0(n,`DAG_VALIDATION_DEFINITION_SNAPSHOT_INVALID`,`DagRun definition snapshot has invalid shape`,{dagRunId:t})}async function _2(e,t){let n=await e.getDagRun(t.dagRunId);if(!n)return{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun not found for dequeued message`,{dagRunId:t.dagRunId})};let r=RJe(n,t.dagRunId);if(!r.ok)return r;let i=r.value,a=i.nodes.find(e=>e.nodeId===t.nodeId);return a?{ok:!0,value:{dagRun:n,definition:i,nodeDefinition:a}}:{ok:!1,error:Q(`DAG_VALIDATION_NODE_NOT_FOUND`,`Node definition not found for task execution`,{nodeId:t.nodeId,dagId:n.dagId,version:n.version})}}var zJe=class{storage;queue;lease;executor;clock;options;runProgressEventReporter;snapshotBudget;rootCreditBudget;lifecycleCreditAdmission;executionRoot;byteLimits;cancellationPollMs;activeAttempts=new Set;notifyRunCancelled(e){for(let t of this.activeAttempts)t.dagRunId===e&&t.controller.abort()}constructor(e,t,n,r,i,a,o,s,c,l,u,d=!1){if(this.storage=e,this.queue=t,this.lease=n,this.executor=r,this.clock=i,this.options=o,this.runProgressEventReporter=s,this.snapshotBudget=l,this.rootCreditBudget=u,this.lifecycleCreditAdmission=d,this.executionRoot=rn(a),this.byteLimits=H1(c),this.cancellationPollMs=o.cancellationPollMs??250,!Number.isSafeInteger(this.cancellationPollMs)||this.cancellationPollMs<1||this.cancellationPollMs>6e4)throw RangeError(`cancellationPollMs must be an integer between 1 and 60000`)}sweeper;outcomesInstance;get outcomes(){return this.outcomesInstance??=new PJe(this.storage,this.queue,this.clock,this.options,this.runProgressEventReporter,this.snapshotBudget),this.outcomesInstance}async processOnce(){let e=await this.queue.dequeue(this.options.workerId,this.options.visibilityTimeoutMs,this.options.idleWaitMs);if(!e){this.sweeper??=new pJe(this.clock,this.lease,this.options);let e=await this.sweeper.sweepIfDue(this.storage,this.queue);return e?{ok:!1,error:e}:{ok:!0,value:{processed:!1}}}let t=await this.resolveTimeoutMs(e);return bJe(this.lease,e.taskRunId,this.options.workerId,m2(t,this.options.leaseDurationMs),async()=>this.processAcquiredMessage(e,t),async()=>(await this.queue.nack(e.messageId),{ok:!0,value:{processed:!1}}))}async processAcquiredMessage(e,t){let n=await this.storage.getTaskRun(e.taskRunId);if(!n){let t=Q(`DAG_VALIDATION_TASK_RUN_NOT_FOUND`,`TaskRun not found for dequeued message`,{taskRunId:e.taskRunId});return f2(this.queue,e.messageId,t)}let r=await this.cancelIfRunCancelled(e);if(r)return r;let i=this.claimDepsFor(e,n,t),a=await yJe(i);if(!a.ok)return xJe(a.error,i);let o={...e,attempt:a.value},s=await _2(this.storage,o);if(!s.ok)return f2(this.queue,e.messageId,s.error);let{dagRun:c,definition:l,nodeDefinition:u}=s.value;if(c.status===`cancelled`)return this.settleCancelledRunMessage(e);let d;try{d=Y0(c.lineage)}catch{return this.outcomes.handleFailurePath(o,o.taskRunId,Q(`DAG_VALIDATION_RUN_LINEAGE_INVALID`,`Persisted composite child run lineage is invalid`,{dagRunId:o.dagRunId}))}if(d){let t=await this.cancelIfAncestorCancelled(e,c,d);if(t)return t}let f=e=>this.storage.commitExecution(o.dagRunId,{kind:`snapshot-input`,taskRunId:o.taskRunId,attempt:o.attempt,leaseOwner:this.options.workerId,inputSnapshot:e}),p=this.snapshotBudget?await this.snapshotBudget.admitValue(`input`,o.payload,f):{ok:!0,value:await f(JSON.stringify(o.payload))};if(!p.ok)return this.outcomes.handleFailurePath(o,o.taskRunId,p.error);if(!p.value.applied)return p2(this.queue,e.messageId,o.taskRunId,!1);let m=await this.buildExecutionInput(o,c,l,u,d),h=new AbortController,g={dagRunId:o.dagRunId,taskRunId:o.taskRunId,attempt:o.attempt,controller:h};this.activeAttempts.add(g);let _,v,y=Date.now()+i.timeoutMs,b;try{let t=await this.cancelIfRunCancelled(e);if(t)return t;if(b=this.watchCommittedCancellation(g),l.costPolicy&&!this.lifecycleCreditAdmission&&!(this.executor instanceof $0)){let t=this.executor.estimateCost;if(!t)return this.outcomes.handleFailurePath(o,n.taskRunId,Q(`DAG_VALIDATION_CREDIT_ESTIMATE_REQUIRED`,`Cost-limited runs require a custom executor to estimate credits before execution`,{taskRunId:o.taskRunId}));let r=await g2({execute:async e=>{let n=await t.call(this.executor,e);return n.ok?{ok:!0,output:{},estimatedCredits:n.value}:n},...this.executor.stopAndWait?{stopAndWait:this.executor.stopAndWait.bind(this.executor)}:{}},{...m,signal:h.signal},Math.max(1,y-Date.now()),e.taskRunId);if(!r.ok)return this.outcomes.handleFailurePath(o,n.taskRunId,r.error);if(r.estimatedCredits===void 0||!Number.isFinite(r.estimatedCredits)||r.estimatedCredits<0)return this.outcomes.handleFailurePath(o,n.taskRunId,Q(`DAG_VALIDATION_CREDIT_ESTIMATE_INVALID`,`Custom executor credit estimate must be a finite nonnegative number`,{taskRunId:o.taskRunId}));let i=await m.reserveCredits(r.estimatedCredits);if(!i.ok)return this.outcomes.handleFailurePath(o,n.taskRunId,i.error);v=r.estimatedCredits}let r=y-Date.now();if(r<=0)return this.outcomes.handleFailurePath(o,n.taskRunId,F1(`DAG_TASK_EXECUTION_TIMEOUT`,`Task execution timed out after ${i.timeoutMs}ms`,!0,{taskRunId:e.taskRunId,timeoutMs:i.timeoutMs}));_=await g2(this.executor,{...m,signal:h.signal},r,e.taskRunId)}finally{b?.(),this.activeAttempts.delete(g)}return _.ok?v!==void 0&&_.estimatedCredits!==void 0&&_.estimatedCredits!==v?this.outcomes.handleFailurePath(o,n.taskRunId,Q(`DAG_VALIDATION_CREDIT_ESTIMATE_MISMATCH`,`Custom executor reported credits different from its preflight estimate`,{taskRunId:o.taskRunId})):this.outcomes.handleSuccessPath(o,n.taskRunId,c,l,_.output,v??_.estimatedCredits,_.totalCredits):this.outcomes.handleFailurePath(o,n.taskRunId,_.error)}watchCommittedCancellation(e){let t=!1,n,r=async()=>{if(!t){try{let n=await this.storage.getDagRun(e.dagRunId);!t&&n?.status!==`running`&&e.controller.abort()}catch{t||e.controller.abort()}!t&&!e.controller.signal.aborted&&(n=setTimeout(()=>{r()},this.cancellationPollMs))}};return n=setTimeout(()=>{r()},this.cancellationPollMs),()=>{t=!0,clearTimeout(n)}}async cancelIfRunCancelled(e){return(await this.storage.getDagRun(e.dagRunId))?.status===`cancelled`?this.settleCancelledRunMessage(e):void 0}async cancelIfAncestorCancelled(e,t,n){if(n.parentRunId===void 0)return;let r=new Set([n.rootRunId,n.parentRunId]);for(let n of r)if((await this.storage.getDagRun(n))?.status===`cancelled`)return await this.cancelOwnRunForAncestor(t),this.settleCancelledRunMessage(e)}async cancelOwnRunForAncestor(e){if(!G1.transition(e.status,`CANCEL`).ok)return;let t=await this.storage.commitExecution(e.dagRunId,{kind:`transition-run`,expectedStatus:e.status,event:`CANCEL`,endedAt:this.clock.nowIso()});if(t.applied||t.runStatus===`cancelled`){this.notifyRunCancelled(e.dagRunId);return}if(t.runStatus!==void 0){let t=await this.storage.getDagRun(e.dagRunId);t&&await this.cancelOwnRunForAncestor(t)}}async settleCancelledRunMessage(e){let t=await this.storage.getTaskRun(e.taskRunId);if(t){let e=K1.transition(t.status,`CANCEL`);e.ok&&await this.storage.updateTaskRunStatus(t.taskRunId,e.value.nextStatus),await this.storage.setTaskRunLease(t.taskRunId,void 0,void 0)}return p2(this.queue,e.messageId,e.taskRunId,!1)}async buildExecutionInput(e,t,n,r,i){let a=IJe(await this.storage.listTaskRunsByDagRunId(e.dagRunId));return{executionRoot:this.executionRoot,...i===void 0?{}:{lineage:i},byteLimits:this.byteLimits,snapshotBudget:this.snapshotBudget,rootCreditBudget:this.rootCreditBudget,reserveCredits:n.costPolicy?async t=>{let n=await this.storage.commitExecution(e.dagRunId,{kind:`reserve-credits`,taskRunId:e.taskRunId,attempt:e.attempt,leaseOwner:this.options.workerId,estimatedCredits:t});return n.applied?{ok:!0,value:void 0}:{ok:!1,error:n.error??Q(`DAG_VALIDATION_CREDIT_RESERVATION_REJECTED`,`Task attempt lost credit reservation authority`,{taskRunId:e.taskRunId})}}:void 0,dagId:t.dagId,dagRunId:e.dagRunId,taskRunId:e.taskRunId,nodeId:e.nodeId,attempt:e.attempt,executionPath:e.executionPath,input:e.payload,nodeDefinition:r,costPolicy:n.costPolicy,currentTotalCredits:a}}claimDepsFor(e,t,n){return{storage:this.storage,queue:this.queue,clock:this.clock,reporter:this.runProgressEventReporter,options:this.options,timeoutMs:n,message:e,taskRun:t}}async resolveTimeoutMs(e){let t=await _2(this.storage,e);if(!t.ok)return this.options.defaultTimeoutMs;let n=t.value.nodeDefinition.timeoutMs;return typeof n==`number`&&n>0?n:this.options.defaultTimeoutMs}},BJe=class extends Error{constructor(){super(`Run advancement has stopped and cannot be restarted.`),this.name=`RunAdvancementStoppedError`}};function VJe(e){return e===`success`||e===`failed`||e===`cancelled`}function v2(e,t,n){return P1(e,t,{dagRunId:n})}var HJe=class{workerStep;runReader;logger;lifecycle=`created`;continuousDemand=!1;waiters=new Map;actorPromise=null;stopPromise=null;wakeSleep=null;constructor(e,t,n={error:()=>void 0}){this.workerStep=e,this.runReader=t,this.logger=n}async start(){if(this.lifecycle===`stopping`||this.lifecycle===`stopped`)throw new BJe;this.lifecycle=`running`,this.continuousDemand=!0,this.wake(),this.ensureActor()}waitForTerminal(e,t={}){if(this.lifecycle===`stopping`||this.lifecycle===`stopped`)return Promise.resolve({ok:!1,error:v2(`DAG_RUNTIME_ADVANCEMENT_STOPPED`,`Run advancement stopped before the observed run became terminal.`,e)});if(t.signal?.aborted)return Promise.resolve({ok:!1,error:v2(`DAG_RUNTIME_ADVANCEMENT_WAIT_ABORTED`,`Run terminal-state observation was aborted.`,e)});if(t.deadlineEpochMs!==void 0&&t.deadlineEpochMs<=Date.now())return Promise.resolve({ok:!1,error:v2(`DAG_RUNTIME_ADVANCEMENT_WAIT_DEADLINE`,`Run terminal-state observation exceeded its deadline.`,e)});let n=new Promise(n=>{let r={id:Symbol(e),dagRunId:e,resolve:n,signal:t.signal,settled:!1};t.signal!==void 0&&(r.abortListener=()=>{this.settle(r,{ok:!1,error:v2(`DAG_RUNTIME_ADVANCEMENT_WAIT_ABORTED`,`Run terminal-state observation was aborted.`,e)})},t.signal.addEventListener(`abort`,r.abortListener,{once:!0})),t.deadlineEpochMs!==void 0&&(r.deadlineTimer=setTimeout(()=>{this.settle(r,{ok:!1,error:v2(`DAG_RUNTIME_ADVANCEMENT_WAIT_DEADLINE`,`Run terminal-state observation exceeded its deadline.`,e)})},Math.max(0,t.deadlineEpochMs-Date.now())),r.deadlineTimer.unref?.()),this.waiters.set(r.id,r)});return this.wake(),this.ensureActor(),n}stop(){if(this.stopPromise!==null)return this.stopPromise;this.lifecycle=`stopping`,this.continuousDemand=!1;for(let e of[...this.waiters.values()])this.settle(e,{ok:!1,error:v2(`DAG_RUNTIME_ADVANCEMENT_STOPPED`,`Run advancement stopped before the observed run became terminal.`,e.dagRunId)});return this.wake(),this.stopPromise=(async()=>{await this.actorPromise,this.lifecycle=`stopped`})(),this.stopPromise}hasDemand(){return(this.lifecycle===`created`||this.lifecycle===`running`)&&(this.continuousDemand||this.waiters.size>0)}ensureActor(){if(!this.hasDemand()||this.actorPromise!==null)return;let e=this.runActor().catch(e=>{this.logger.error(`Run advancement actor failed unexpectedly.`,e)}).finally(()=>{this.actorPromise===e&&(this.actorPromise=null),this.hasDemand()&&this.ensureActor()});this.actorPromise=e}async runActor(){let e=25;for(;this.hasDemand();){if(await this.queryAndSettleWaiters(),!this.hasDemand())return;let t;try{t=await this.workerStep.processOnce()}catch(e){this.logger.error(`Worker step threw during run advancement.`,e),await this.sleepUntilWake(500);continue}if(!this.hasDemand())return;if(!t.ok){this.logger.error(`Worker step failed during run advancement.`,t.error),await this.sleepUntilWake(500);continue}if(t.value.processed){e=25;continue}await this.sleepUntilWake(e),e=Math.min(e*2,500)}}async queryAndSettleWaiters(){let e=new Set([...this.waiters.values()].map(e=>e.dagRunId));for(let t of e){let e;try{e=await this.runReader.getRun(t)}catch(n){e={ok:!1,error:v2(`DAG_RUNTIME_ADVANCEMENT_QUERY_THROW`,n instanceof Error?n.message:String(n),t)}}let n=[...this.waiters.values()].filter(e=>e.dagRunId===t);if(!e.ok||VJe(e.value.dagRun.status))for(let t of n)this.settle(t,e)}}settle(e,t){e.settled||(e.settled=!0,this.waiters.delete(e.id),e.deadlineTimer!==void 0&&clearTimeout(e.deadlineTimer),e.signal!==void 0&&e.abortListener!==void 0&&e.signal.removeEventListener(`abort`,e.abortListener),e.resolve(t),this.wake())}wake(){this.wakeSleep?.()}async sleepUntilWake(e){this.hasDemand()&&await new Promise(t=>{let n=!1,r=()=>{n||(n=!0,clearTimeout(i),this.wakeSleep===r&&(this.wakeSleep=null),t())},i=setTimeout(r,e);i.unref?.(),this.wakeSleep=r,this.hasDemand()||r()})}};function UJe(e,t){let n={...t,retryEnabled:t.retryEnabled??!1,deadLetterEnabled:t.deadLetterEnabled??!1,deadLetterQueue:e.deadLetterQueue};return new zJe(e.storage,e.queue,e.lease,e.executor,e.clock,e.executionRoot,n,e.runProgressEventReporter,e.byteLimits,e.snapshotBudget,e.rootCreditBudget,e.lifecycleCreditAdmission)}function WJe(e,t){let n=new Xqe,r=new nJe(e.storage,e.queue,e.clock,n,e.snapshotBudget),i=new rJe(e.storage),a=UJe({executionRoot:e.executionRoot,byteLimits:e.byteLimits,snapshotBudget:e.snapshotBudget,rootCreditBudget:e.rootCreditBudget,lifecycleCreditAdmission:e.lifecycleCreditAdmission,storage:e.storage,queue:e.queue,deadLetterQueue:e.deadLetterQueue,lease:e.lease,executor:e.executor,clock:e.clock,runProgressEventReporter:n},{...t.worker,retryEnabled:t.worker.retryEnabled??!1});return{runOrchestrator:r,runQuery:i,runCancel:new iJe(e.storage,e.clock,{notifyRunCancelled(t){e.snapshotBudget?.close(),e.rootCreditBudget?.close(),a.notifyRunCancelled(t)}}),runAdvancement:new HJe(a,i,t.logger),runProgressEventBus:n}}function y2(e,t){let{text:n,search:r,replacement:i,flags:a}=e,o;try{o=new RegExp(r,a)}catch{return{type:`invalid-regex`}}let s=Symbol(`regex output exceeds byte limit`),c=new Uint16Array(t),l=0,u=0,d=!1,f=0,p=(e,n,r)=>{for(let i=n;i<r;i++){let n=e.charCodeAt(i);if(u+=n<128?1:n<2048?2:n>=56320&&n<=57343&&d?1:3,d=n>=55296&&n<=56319,u>t)throw s;c[l++]=n}},m=(e,t,r,a)=>{for(let o=0;o<i.length;){let s=i.indexOf(`$`,o);if(s<0){p(i,o,i.length);return}p(i,o,s);let c=i[s+1];if(c===`$`)p(i,s,s+1),o=s+2;else if(c===`&`)p(e,0,e.length),o=s+2;else if(c==="`")p(n,0,r),o=s+2;else if(c===`'`)p(n,r+e.length,n.length),o=s+2;else if(c!==void 0&&c>=`0`&&c<=`9`){let e=i[s+2],n=e!==void 0&&e>=`0`&&e<=`9`?2:1,r=Number(i.slice(s+1,s+1+n));if(n===2&&r>t.length&&(n=1,r=Number(c)),r>=1&&r<=t.length){let e=t[r-1];e!==void 0&&p(e,0,e.length)}else p(i,s,s+1+n);o=s+1+n}else if(c===`<`){let e=i.indexOf(`>`,s+2);if(e>=0&&a!==void 0){let t=a[i.slice(s+2,e)];t!==void 0&&p(t,0,t.length),o=e+1}else p(i,s,s+2),o=s+2}else p(i,s,s+1),o=s+1}};try{let e=a.includes(`u`)||a.includes(`v`);for(let t=o.exec(n);t!==null;t=o.exec(n)){let r=t[0],i=t.index;if(p(n,f,i),m(r,t.slice(1),i,t.groups),f=i+r.length,!o.global)break;if(r.length===0){let t=o.lastIndex,r=n.charCodeAt(t),i=n.charCodeAt(t+1);o.lastIndex+=e&&r>=55296&&r<=56319&&i>=56320&&i<=57343?2:1}}p(n,f,n.length)}catch(e){return e===s?{type:`oversized`}:{type:`invalid-regex`}}let h=[];for(let e=0;e<l;e+=8192)h.push(String.fromCharCode(...c.subarray(e,Math.min(e+8192,l))));return{type:`result`,value:h.join(``)}}const b2=25166848,GJe=`
2789
+ `?(r&&n++,r=!1):!r&&lqe.test(i)&&(r=!0)}return r&&n++,n}var dqe=class extends m0{nodeType=`text-count-lines`;displayName=`Text Count Lines`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Line Count`,order:0,type:`string`,required:!0}];configSchemaDefinition=cqe;async estimateCostWithConfig(){return G0}async executeWithConfig(e,t,n){let r=new v0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);return i.ok?(r.setOutput(`text`,String(uqe(i.value,n.skipEmpty))),{ok:!0,value:r.toOutput()}):i}};const fqe=I.object({times:I.number().int().min(0).max(2**53-1).default(2),separator:I.string().default(``)});var pqe=class extends m0{nodeType=`text-repeat`;displayName=`Text Repeat`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Repeated Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=fqe;async estimateCostWithConfig(){return G0}async executeWithConfig(e,t,n){let r=new v0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=H1(t.byteLimits),o=HKe(i.value,n.separator,n.times,a.maxTextRepeatOutputBytes);return o.ok?(r.setOutput(`text`,o.value),{ok:!0,value:r.toOutput()}):o}};const mqe=I.object({start:I.number().int().default(0),end:I.number().int().optional()});var hqe=class extends m0{nodeType=`text-slice`;displayName=`Text Slice`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Sliced Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=mqe;async estimateCostWithConfig(){return G0}async executeWithConfig(e,t,n){let r=new v0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);return i.ok?(r.setOutput(`text`,i.value.slice(n.start,n.end)),{ok:!0,value:r.toOutput()}):i}},gqe=aKe({createDefaultNodeRegistry:()=>J0,createDefaultNodeRegistrySync:()=>q0});function q0(){return[new mKe,new gKe,new yKe,new SKe,new wKe,new EKe,new OKe,new AKe,new zKe,new GKe,new KKe,new JKe,new XKe,new QKe,new $Ke,new eqe,new tqe,new rqe,new aqe,new sqe,new dqe,new pqe,new hqe]}const _qe=async()=>{try{return(await Promise.resolve().then(()=>wH)).createDefaultMediaProviderDefinitions()}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to load the default media provider definitions. Install @robota-sdk/agent-builtin-providers (and its provider SDKs), or inject mediaProviders explicitly. Cause: ${t}`)}},vqe=async()=>{try{return(await Promise.resolve().then(()=>wH)).createDefaultProviderDefinitions()}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to load the default LLM provider set for the llm-text node. A provider SDK package is likely not installed. Install @robota-sdk/agent-builtin-providers (and its provider SDKs), or pass createDagFramework({ providers: [...] }) explicitly. Cause: ${t}`)}};async function J0(e,t=vqe,n={},r=[],i=[]){let a=e??await t(),o=[...q0(),new fKe(a)],s=n.mediaProviders??await(n.loadMediaDefaults??_qe)(),l=c(s,`gemini-image`),u=c(s,`seedance-video`),d=await Promise.all([...[{modulePath:`@robota-sdk/dag-node-gemini-image-edit`,factories:[e=>new e.GeminiImageEditNodeDefinition({imageProviderDefinition:l}),e=>new e.GeminiImageComposeNodeDefinition({imageProviderDefinition:l})]},{modulePath:`@robota-sdk/dag-node-text-to-image`,factories:[e=>new e.TextToImageNodeDefinition({imageProviderDefinition:l})]},{modulePath:`@robota-sdk/dag-node-seedance-video`,factories:[e=>new e.SeedanceVideoNodeDefinition({videoProviderDefinition:u})]}].map(bqe),yqe(i,r)]);for(let e of d)o.push(...e);return o}async function yqe(e,t){try{return[new(await(import(`./src-DwAfU-9z-DU29KIpt.js`))).SkillNodeDefinition({skillPort:nde(e,t)})]}catch{return[]}}async function bqe(e){let t=await xqe(e.modulePath);if(!t)return[];let n=[];for(let r of e.factories){let e=Sqe(r,t);e&&n.push(e)}return n}async function xqe(e){try{switch(e){case`@robota-sdk/dag-node-gemini-image-edit`:return await import(`./src-B9UMvThT-C1A4E6i9.js`);case`@robota-sdk/dag-node-text-to-image`:return await import(`./src-BzaNFPZx-Cn-T7595.js`);case`@robota-sdk/dag-node-seedance-video`:return await import(`./src-UPsd6jNY-DPPw_--T.js`);default:return}}catch{return}}function Sqe(e,t){try{return e(t)}catch{return}}var Cqe=class{limit;committed=0;reserved=0;closed=!1;constructor(e){if(this.limit=e,e!==void 0&&(!Number.isFinite(e)||e<=0))throw RangeError(`Root credit limit must be positive and finite`)}close(){this.closed=!0}reserve(e){if(!Number.isFinite(e)||e<0)return{ok:!1,error:Q(`DAG_VALIDATION_NEGATIVE_ESTIMATED_CREDITS`,`estimatedCredits must be finite and zero or positive`,{estimatedCredits:e})};if(this.closed||this.limit!==void 0&&e>this.limit-this.committed-this.reserved)return{ok:!1,error:Q(`DAG_VALIDATION_CREDIT_LIMIT_EXCEEDED`,`Estimated run credits exceeds root runCreditLimit`,{estimatedCredits:e,...this.limit===void 0?{}:{runCreditLimit:this.limit}})};this.reserved+=e;let t=!1;return{ok:!0,value:{commit:()=>(t||(t=!0,this.reserved-=e,this.committed+=e),this.committed),release:()=>{t||(t=!0,this.reserved-=e)}}}}};function Y0(e){if(e==null)return;if(typeof e!=`object`||Array.isArray(e))throw Error(`Invalid persisted DAG execution lineage`);let t=e,n=t.parentRunId!==void 0,r=!n||typeof t.parentRunId==`string`&&t.parentRunId.length>0;if(typeof t.rootRunId!=`string`||t.rootRunId.length===0||!r||!Number.isSafeInteger(t.depth)||t.depth<0||t.maxDepth!==void 0&&(!Number.isSafeInteger(t.maxDepth)||t.maxDepth<1)||!Array.isArray(t.ancestorCompositeNodeTypes)||!t.ancestorCompositeNodeTypes.every(e=>typeof e==`string`&&e.length>0))throw Error(`Invalid persisted DAG execution lineage`);let i=t.depth,a=t.ancestorCompositeNodeTypes.length;if(!(i===0?!n&&a===0:n&&a===i))throw Error(`Invalid persisted DAG execution lineage`);return{rootRunId:t.rootRunId,...n?{parentRunId:t.parentRunId}:{},depth:i,...t.maxDepth===void 0?{}:{maxDepth:t.maxDepth},ancestorCompositeNodeTypes:[...t.ancestorCompositeNodeTypes]}}const X0={STARTED:`execution.started`,COMPLETED:`execution.completed`,FAILED:`execution.failed`},Z0={STARTED:`task.started`,COMPLETED:`task.completed`,FAILED:`task.failed`};function Q0(e){let t=Date.parse(e);return Number.isNaN(t)?{ok:!1,error:Q(`DAG_VALIDATION_INVALID_LOGICAL_DATE`,`logicalDate must be a valid ISO-8601 datetime string`,{logicalDate:e})}:{ok:!0,value:new Date(t).toISOString()}}var wqe=class{clock;constructor(e){this.clock=e}resolve(e,t){let n=this.clock.nowIso();if(e===`scheduled`){if(!t)return{ok:!1,error:Q(`DAG_VALIDATION_MISSING_LOGICAL_DATE`,`scheduled trigger requires logicalDate`,{trigger:e})};let r=Q0(t);return r.ok?{ok:!0,value:{trigger:e,logicalDate:r.value,requestedAt:n}}:r}if(!t)return{ok:!0,value:{trigger:e,logicalDate:n,requestedAt:n}};let r=Q0(t);return r.ok?{ok:!0,value:{trigger:e,logicalDate:r.value,requestedAt:n}}:r}},Tqe=class{assertWithinBudget(e,t,n){if(t<0)return{ok:!1,error:Q(`DAG_VALIDATION_NEGATIVE_ESTIMATED_CREDITS`,`estimatedCredits must be zero or positive`,{nextEstimatedCredits:t})};let r=e+t;return typeof n==`number`&&r>n?{ok:!1,error:Q(`DAG_VALIDATION_CREDIT_LIMIT_EXCEEDED`,`Estimated run credits exceeds runCreditLimit`,{nextTotalCredits:r,runCreditLimit:n})}:{ok:!0,value:r}}},Eqe=class{lifecycleFactory;costPolicyEvaluator;constructor(e,t){this.lifecycleFactory=e,this.costPolicyEvaluator=t}async runNode(e){let t=()=>({ok:!1,error:I1(e.context.taskRunId)});if(e.context.signal?.aborted)return t();let n=this.lifecycleFactory.create(e.context.nodeDefinition.nodeType);if(!n.ok)return n;let r=await n.value.initialize(e.context);if(e.context.signal?.aborted)return await n.value.dispose(e.context),t();if(!r.ok)return r;let i=await n.value.validateInput(e.input,e.context);if(e.context.signal?.aborted)return await n.value.dispose(e.context),t();if(!i.ok)return await n.value.dispose(e.context),i;let a=await n.value.estimateCost(e.input,e.context);if(e.context.signal?.aborted)return await n.value.dispose(e.context),t();if(!a.ok)return await n.value.dispose(e.context),a;let o=this.costPolicyEvaluator.assertWithinBudget(e.context.currentTotalCredits,a.value.estimatedCredits,e.context.runCreditLimit);if(!o.ok)return await n.value.dispose(e.context),o;if(e.context.reserveCredits){let r=await e.context.reserveCredits(a.value.estimatedCredits);if(!r.ok)return await n.value.dispose(e.context),r;if(e.context.signal?.aborted)return await n.value.dispose(e.context),t()}let s=e.context.rootCreditBudget?.reserve(a.value.estimatedCredits);if(s&&!s.ok)return await n.value.dispose(e.context),s;try{let r=await n.value.execute(e.input,e.context);if(e.context.signal?.aborted)return await n.value.dispose(e.context),t();if(!r.ok)return await n.value.dispose(e.context),r;let i=await n.value.validateOutput(r.value,e.context);if(e.context.signal?.aborted)return await n.value.dispose(e.context),t();if(!i.ok)return await n.value.dispose(e.context),i;let c=await n.value.dispose(e.context);return e.context.signal?.aborted?t():c.ok?(s?.value.commit(),{ok:!0,value:{output:r.value,estimatedCredits:a.value.estimatedCredits,totalCredits:o.value}}):{ok:!1,error:F1(`DAG_TASK_EXECUTION_DISPOSE_FAILED`,`Node dispose step failed after execution`,!1,{nodeType:e.context.nodeDefinition.nodeType,taskRunId:e.context.taskRunId})}}finally{s?.ok&&s.value.release()}}},Dqe=class{create(e){return{ok:!1,error:Q(`DAG_VALIDATION_NODE_LIFECYCLE_NOT_REGISTERED`,`Node lifecycle is not registered for nodeType`,{nodeType:e})}}},$0=class{nodeManifestRegistry;lineage;lifecycleFactory;runner;constructor(e,t,n){this.nodeManifestRegistry=e,this.lineage=n,this.lifecycleFactory=t??new Dqe,this.runner=new Eqe(this.lifecycleFactory,new Tqe)}async execute(e){if(!e.nodeDefinition)return{ok:!1,error:Q(`DAG_VALIDATION_NODE_DEFINITION_MISSING`,`Task execution requires nodeDefinition in execution input`,{nodeId:e.nodeId})};let t=this.nodeManifestRegistry.getManifest(e.nodeDefinition.nodeType);if(!t)return{ok:!1,error:Q(`DAG_VALIDATION_NODE_MANIFEST_NOT_FOUND`,`Node manifest is not registered for nodeType`,{nodeType:e.nodeDefinition.nodeType})};let n=await this.runner.runNode({input:e.input,context:{executionRoot:e.executionRoot,regexReplaceOperation:e.regexReplaceOperation,snapshotBudget:e.snapshotBudget,rootCreditBudget:e.rootCreditBudget,reserveCredits:e.reserveCredits,...e.byteLimits===void 0?{}:{byteLimits:e.byteLimits},...e.signal===void 0?{}:{signal:e.signal},dagId:e.dagId,dagRunId:e.dagRunId,taskRunId:e.taskRunId,nodeDefinition:e.nodeDefinition,nodeManifest:t,attempt:e.attempt,executionPath:e.executionPath,lineage:e.lineage??this.lineage??{rootRunId:e.dagRunId,depth:0,ancestorCompositeNodeTypes:[]},runCreditLimit:e.costPolicy?.runCreditLimit,currentTotalCredits:e.currentTotalCredits??0,...e.runtimeBaseUrl===void 0?{}:{runtimeBaseUrl:e.runtimeBaseUrl}}});return n.ok?{ok:!0,output:n.value.output,estimatedCredits:n.value.estimatedCredits,totalCredits:n.value.totalCredits}:n}};const e2={root:`.workflows`,workflowExt:`.json`};var Oqe=class{manifestByType=new Map;constructor(e){for(let t of e)this.manifestByType.set(t.nodeType,t)}getManifest(e){return this.manifestByType.get(e)}listManifests(){return[...this.manifestByType.values()]}};function kqe(e){let t=[],n=Pqe(e,``,t);return n!==void 0&&t.length===0?{ok:!0,value:n}:{ok:!1,error:t}}function t2(e,t,n){if(!Array.isArray(e)||e.length!==2)return q1(n,t,`expected a [number, number] pair`);let r=Z1(e[0],J1(t,0),n),i=Z1(e[1],J1(t,1),n);return r===void 0||i===void 0?void 0:[r,i]}function Aqe(e,t,n){if(!Array.isArray(e)||e.length!==6)return q1(n,t,`expected a 6-tuple [linkId, srcId, srcSlot, tgtId, tgtSlot, type]`);let r=[0,1,2,3,4].map(r=>Z1(e[r],J1(t,r),n)),i=X1(e[5],J1(t,5),n);if(r.some(e=>e===void 0)||i===void 0)return;let[a,o,s,c,l]=r;return[a,o,s,c,l,i]}function jqe(e,t,n){let r=Y1(e,t,n);if(r===void 0)return;let i=X1(r.name,J1(t,`name`),n),a=X1(r.type,J1(t,`type`),n),o=r.link,s=o===null?null:Z1(o,J1(t,`link`),n);return i===void 0||a===void 0||s===void 0?void 0:{name:i,type:a,link:s}}function Mqe(e,t,n){let r=Y1(e,t,n);if(r===void 0)return;let i=X1(r.name,J1(t,`name`),n),a=X1(r.type,J1(t,`type`),n),o=t0(r.links,J1(t,`links`),n,Z1),s=e0(r.slot_index,J1(t,`slot_index`),n,Z1);if(i===void 0||a===void 0||o===void 0)return;let c={name:i,type:a,links:o};return s!==void 0&&(c.slot_index=s),c}function Nqe(e,t,n){let r=Y1(e,t,n);if(r===void 0)return;let i=e=>J1(t,e),a=Z1(r.id,i(`id`),n),o=X1(r.type,i(`type`),n),s=t2(r.pos,i(`pos`),n),c=e0(r.size,i(`size`),n,t2),l=e0(r.flags,i(`flags`),n,Y1),u=e0(r.order,i(`order`),n,Z1),d=e0(r.mode,i(`mode`),n,Z1),f=e0(r.inputs,i(`inputs`),n,(e,t,n)=>t0(e,t,n,jqe)),p=e0(r.outputs,i(`outputs`),n,(e,t,n)=>t0(e,t,n,Mqe)),m=e0(r.properties,i(`properties`),n,Y1),h=e0(r.widgets_values,i(`widgets_values`),n,(e,t,n)=>Array.isArray(e)?e:q1(n,t,`expected an array`));if(a===void 0||o===void 0||s===void 0)return;let g={id:a,type:o,pos:s};return c!==void 0&&(g.size=c),l!==void 0&&(g.flags=l),u!==void 0&&(g.order=u),d!==void 0&&(g.mode=d),f!==void 0&&(g.inputs=f),p!==void 0&&(g.outputs=p),m!==void 0&&(g.properties=m),h!==void 0&&(g.widgets_values=h),g}function Pqe(e,t,n){let r=Y1(e,t,n);if(r===void 0)return;let i=e=>J1(t,e);if(`dagId`in r)return q1(n,i(`dagId`),`a workflow file carries no dagId — that is a definition file`);let a=Z1(r.last_node_id,i(`last_node_id`),n),o=Z1(r.last_link_id,i(`last_link_id`),n),s=t0(r.nodes,i(`nodes`),n,Nqe),c=t0(r.links,i(`links`),n,Aqe),l=Z1(r.version,i(`version`),n),u=e0(r.groups,i(`groups`),n,(e,t,n)=>Array.isArray(e)?e:q1(n,t,`expected an array`)),d=e0(r.config,i(`config`),n,Y1),f=e0(r.extra,i(`extra`),n,Y1);if(a===void 0||o===void 0||s===void 0||c===void 0||l===void 0)return;let p={last_node_id:a,last_link_id:o,nodes:s,links:c,version:l};return u!==void 0&&(p.groups=u),d!==void 0&&(p.config=d),f!==void 0&&(p.extra=f),p}function Fqe(e){return`parallel`in e}function n2(e,t){return e.id??`${e.nodeType}-${t}`}function r2(e,t){return e.find(e=>e.nodeType===t)}function i2(e,t){let n=t.map(e=>e.nodeType),r={action:`replace_node_type`,suggestion:n[0],options:n};return Q(`UNKNOWN_NODE_TYPE`,`Node type "${e}" is not registered`,{requestedType:e},r)}function Iqe(e,t){let n=[],r=[],i=[],a=[],o=0;for(let s of e.pipeline)if(Fqe(s)){let e=[];for(let c of s.parallel){let l=n2(c,o);o+=1;let u=r2(t,c.nodeType);if(!u)return{ok:!1,error:i2(c.nodeType,t),warnings:n};let d=a.map(e=>e.nodeId);r.push({nodeId:l,nodeType:c.nodeType,dependsOn:d,config:c.config??{}});for(let e of a){let t=c.toPort??u.defaultInputPort;if(!t){n.push({message:`Node "${l}" (${c.nodeType}) has no defaultInputPort; edge from "${e.nodeId}" requires explicit toPort`});continue}i.push({from:e.nodeId,to:l,bindings:[{outputKey:e.portKey,inputKey:t}]})}let f=s.fromPort??c.fromPort??u.defaultOutputPort;f?e.push({nodeId:l,portKey:f}):n.push({message:`Node "${l}" (${c.nodeType}) has no defaultOutputPort; downstream connections require explicit fromPort`})}a=e}else{let e=n2(s,o);o+=1;let c=r2(t,s.nodeType);if(!c)return{ok:!1,error:i2(s.nodeType,t),warnings:n};let l=a.map(e=>e.nodeId);r.push({nodeId:e,nodeType:s.nodeType,dependsOn:l,config:s.config??{}});for(let t of a){let r=s.toPort??c.defaultInputPort;if(!r){n.push({message:`Node "${e}" (${s.nodeType}) has no defaultInputPort; edge from "${t.nodeId}" requires explicit toPort`});continue}i.push({from:t.nodeId,to:e,bindings:[{outputKey:t.portKey,inputKey:r}]})}let u=s.fromPort??c.defaultOutputPort;a=u?[{nodeId:e,portKey:u}]:[]}return r.length===0?{ok:!1,error:Q(`EMPTY_PIPELINE`,`pipeline must contain at least one node`,void 0,{action:`add_node`,suggestion:`Add at least one node spec to the pipeline array`}),warnings:n}:{ok:!0,definition:{dagId:e.dagId??`dag-build-result`,version:1,status:`draft`,nodes:r,edges:i},warnings:n,nodeCount:r.length,edgeCount:i.length}}function Lqe(e){return(e.startsWith(`ConversationAgent`)?e.slice(17):e).replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`).replace(/^-/,``)}function Rqe(e,t){let n=new Map;for(let t of e.links)n.set(t[0],t);let r=t?.nodes??{},i=e.nodes.map(e=>{let t=r[String(e.id)],n={nodeId:t?.nodeId??`node-${e.id}`,nodeType:Lqe(e.type),dependsOn:[],config:e.properties?.agent_config??{},position:e.pos[0]!==0||e.pos[1]!==0?{x:e.pos[0],y:e.pos[1]}:void 0};return t?.retryPolicy&&(n.retryPolicy=t.retryPolicy),t?.timeoutMs!==void 0&&(n.timeoutMs=t.timeoutMs),t?.costPolicy&&(n.costPolicy=t.costPolicy),n}),a=new Map;e.nodes.forEach((e,t)=>{a.set(e.id,i[t])});let o=new Map,s=[],c=new Map;for(let t of e.links){let[,n,,r]=t,i=a.get(n),l=a.get(r);if(!i||!l)continue;let u=e.nodes.find(e=>e.id===n),d=e.nodes.find(e=>e.id===r),f=t[2],p=t[4],m=u?.outputs?.[f]?.name??`out${f}`,h=d?.inputs?.[p]?.name??`in${p}`,g=JSON.stringify([i.nodeId,l.nodeId]),_=o.get(g);_||(_=[],o.set(g,_),s.push({from:i.nodeId,to:l.nodeId,bindings:_})),_.push({outputKey:m,inputKey:h}),c.has(l.nodeId)||c.set(l.nodeId,new Set),c.get(l.nodeId).add(i.nodeId)}for(let e of i){let t=c.get(e.nodeId);t&&(e.dependsOn=[...t])}return{dagId:t?.dagId??`unknown`,version:t?.version??1,status:t?.status??`draft`,nodes:i,edges:s,...t?.costPolicy?{costPolicy:t.costPolicy}:{},...t?.inputSchema?{inputSchema:t.inputSchema}:{},...t?.outputSchema?{outputSchema:t.outputSchema}:{}}}const zqe={absentStatus:`draft`,absentEdgesAsEmpty:!0};function Bqe(e){if(typeof e!=`object`||!e||Array.isArray(e))return`unrecognised`;let t=e;return`dagId`in t?`definition`:`links`in t||`last_node_id`in t?`workflow-file`:`unrecognised`}function Vqe(e,t){let n=Bqe(e);if(n===`unrecognised`)return{ok:!1,error:{format:n,issues:[{path:``,message:`expected either a workflow file (nodes + links + version) or a definition (dagId + nodes)`}]}};if(n===`workflow-file`){let r=kqe(e);return r.ok?Hqe(Rqe(r.value,t),n):{ok:!1,error:{format:n,issues:r.error}}}let r=a0(e,zqe);return r.ok?r:{ok:!1,error:{format:n,issues:r.error}}}function Hqe(e,t){let n=a0(e);return n.ok?n:{ok:!1,error:{format:t,issues:n.error}}}function Uqe(e){return e.format===`unrecognised`?`Not a DAG file: ${i0(e.issues)}.`:`Malformed ${e.format===`workflow-file`?`workflow file`:`DAG definition`}: ${i0(e.issues)}`}var Wqe=class extends Error{failure;constructor(e){super(Uqe(e)),this.name=`DagFileDecodeError`,this.failure=e}};function a2(e,t){let n=Vqe(e,t);if(n.ok)return n.value;throw new Wqe(n.error)}function Gqe(e,t,n,r){for(let[i,a]of e.entries())if(a.taskRunId===t){e.set(i,{...a,leaseOwner:n,leaseUntil:r});return}}function Kqe(e,t){return[...e.values()].filter(e=>e.status===`running`&&(e.leaseUntil===void 0||e.leaseUntil<=t))}function o2(e,t){return`${e}:${t}`}var qqe=class{definitions=new Map;latestPublishedVersionByDagId=new Map;dagRuns=new Map;taskRuns=new Map;async commitExecution(e,t){let n=[...this.taskRuns.values()].filter(t=>t.dagRunId===e),r=WGe(this.dagRuns.get(e),n,t);return r.dagRun&&this.dagRuns.set(e,r.dagRun),r.taskRun&&this.taskRuns.set(o2(e,r.taskRun.taskRunId),r.taskRun),r.result}async saveDefinition(e){let t=`${e.dagId}:${e.version}`;if(this.definitions.set(t,e),e.status===`published`){let t=this.latestPublishedVersionByDagId.get(e.dagId)??0;e.version>t&&this.latestPublishedVersionByDagId.set(e.dagId,e.version)}}async getDefinition(e,t){let n=`${e}:${t}`;return this.definitions.get(n)}async listDefinitions(){return[...this.definitions.values()].sort((e,t)=>e.dagId.localeCompare(t.dagId)||e.version-t.version)}async listDefinitionsByDagId(e){return[...this.definitions.values()].filter(t=>t.dagId===e).sort((e,t)=>e.version-t.version)}async getLatestPublishedDefinition(e){let t=this.latestPublishedVersionByDagId.get(e);if(t)return this.definitions.get(`${e}:${t}`)}async deleteDefinition(e,t){this.definitions.delete(`${e}:${t}`);let n=[...this.definitions.values()].filter(t=>t.dagId===e&&t.status===`published`).sort((e,t)=>e.version-t.version);if(n.length===0){this.latestPublishedVersionByDagId.delete(e);return}this.latestPublishedVersionByDagId.set(e,n[n.length-1].version)}async createDagRun(e){this.dagRuns.set(e.dagRunId,e)}async getDagRun(e){return this.dagRuns.get(e)}async listDagRuns(){return[...this.dagRuns.values()].sort((e,t)=>e.dagRunId.localeCompare(t.dagRunId))}async getDagRunByRunKey(e){for(let t of this.dagRuns.values())if(t.runKey===e)return t}async updateDagRunStatus(e,t,n){let r=this.dagRuns.get(e);if(!r)return;let i={...r,status:t,endedAt:n};this.dagRuns.set(e,i)}async deleteDagRun(e){this.dagRuns.delete(e)}async createTaskRun(e){let t=o2(e.dagRunId,e.taskRunId);this.taskRuns.set(t,e)}async getTaskRun(e){for(let t of this.taskRuns.values())if(t.taskRunId===e)return t}async listTaskRunsByDagRunId(e){let t=[];for(let n of this.taskRuns.values())n.dagRunId===e&&t.push(n);return t}async deleteTaskRunsByDagRunId(e){for(let[t,n]of this.taskRuns.entries())n.dagRunId===e&&this.taskRuns.delete(t)}async updateTaskRunStatus(e,t,n){for(let[r,i]of this.taskRuns.entries()){if(i.taskRunId!==e)continue;let a={...i,status:t,...[`failed`,`cancelled`,`queued`].includes(t)?{reservedCredits:void 0,reservationAttempt:void 0,reservationOwner:void 0}:{},errorCode:n?.code,errorMessage:n?.message};this.taskRuns.set(r,a);return}}async setTaskRunLease(e,t,n){Gqe(this.taskRuns,e,t,n)}async listStaleRunningTaskRuns(e){return Kqe(this.taskRuns,e)}async saveTaskRunSnapshots(e,t,n,r,i){for(let[a,o]of this.taskRuns.entries()){if(o.taskRunId!==e)continue;let s={...o,inputSnapshot:typeof t==`string`?t:o.inputSnapshot,outputSnapshot:typeof n==`string`?n:o.outputSnapshot,estimatedCredits:typeof r==`number`?r:o.estimatedCredits,totalCredits:typeof i==`number`?i:o.totalCredits};this.taskRuns.set(a,s);return}}async incrementTaskAttempt(e){for(let[t,n]of this.taskRuns.entries()){if(n.taskRunId!==e)continue;let r={...n,attempt:n.attempt+1,reservedCredits:void 0,reservationAttempt:void 0,reservationOwner:void 0};this.taskRuns.set(t,r);return}}},s2=class{pendingQueue=[];inFlight=new Map;waiters=[];async enqueue(e){this.pendingQueue.push(e),this.notifyNextWaiter()}async dequeue(e,t,n=0){let r=this.tryDequeue(e,t);return r||n<=0?r:(await this.waitForMessage(n),this.tryDequeue(e,t))}async ack(e){this.inFlight.delete(e)}async nack(e){let t=this.inFlight.get(e);t&&(this.inFlight.delete(e),this.pendingQueue.unshift(t.message),this.notifyNextWaiter())}tryDequeue(e,t){this.requeueExpiredMessages();let n=this.pendingQueue.shift();if(!n)return;let r=Date.now();return this.inFlight.set(n.messageId,{message:n,ownerId:e,visibleAtEpochMs:r+t}),n}requeueExpiredMessages(){let e=Date.now();for(let[t,n]of this.inFlight.entries())n.visibleAtEpochMs>e||(this.inFlight.delete(t),this.pendingQueue.push(n.message))}async waitForMessage(e){return new Promise(t=>{let n={resolve:()=>{clearTimeout(n.timeout),this.removeWaiter(n),t()},timeout:setTimeout(()=>{n.resolve()},e)};this.waiters.push(n)})}notifyNextWaiter(){this.waiters.shift()?.resolve()}removeWaiter(e){let t=this.waiters.indexOf(e);t>=0&&this.waiters.splice(t,1)}},Jqe=class{records=new Map;async acquire(e,t,n){let r=new Date().toISOString(),i=Date.now(),a=this.records.get(e);if(a&&Date.parse(a.leaseUntil)>i)return;let o={leaseKey:e,ownerId:t,acquiredAt:r,leaseUntil:new Date(i+n).toISOString()};return this.records.set(e,o),o}async release(e,t){let n=this.records.get(e);!n||n.ownerId!==t||this.records.delete(e)}async get(e){return this.records.get(e)}},Yqe=class{nowIso(){return new Date().toISOString()}nowEpochMs(){return Date.now()}},Xqe=class{listeners=new Set;logger;constructor(e){this.logger=e}publish(e){let t=[];for(let n of[...this.listeners])try{n(e)}catch(n){t.push(n),this.logger&&this.logger.error(`RunProgressEventBus listener threw an error`,{eventType:e.eventType,error:n instanceof Error?n.message:String(n)})}if(t.length>0&&!this.logger)throw t[0]instanceof Error?t[0]:Error(String(t[0]))}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}};function Zqe(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t||Array.isArray(t)?{ok:!1,error:Q(`DAG_VALIDATION_PAYLOAD_INVALID`,`Payload must be a JSON object`)}:{ok:!0,value:t}}catch{return{ok:!1,error:Q(`DAG_VALIDATION_PAYLOAD_PARSE_FAILED`,`Failed to parse payload JSON`)}}}function Qqe(e){let t;try{t=JSON.parse(e)}catch{return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_SNAPSHOT_PARSE_FAILED`,`Failed to parse definition snapshot JSON`)}}return o0(t,`DAG_VALIDATION_DEFINITION_SNAPSHOT_INVALID`,`Definition snapshot must be a valid DAG definition object`)}async function $qe(e,t,n,r,i){let{dagRunId:a,definition:o,input:s}=e,c=o.nodes.filter(e=>e.dependsOn.length===0);if(c.length===0)return{ok:!1,error:Q(`DAG_VALIDATION_NO_ENTRY_NODE`,`DAG must include at least one entry node (dependsOn = [])`,{dagId:o.dagId,version:o.version})};let l=G1.transition(`created`,`QUEUE`);if(!l.ok)return l;if(!(await t.commitExecution(a,{kind:`transition-run`,expectedStatus:`created`,event:`QUEUE`})).applied)return{ok:!0,value:{taskRunIds:[]}};let u=G1.transition(`queued`,`START`);if(!u.ok)return u;if(!(await t.commitExecution(a,{kind:`transition-run`,expectedStatus:`queued`,event:`START`})).applied)return{ok:!0,value:{taskRunIds:[]}};i?.publish({dagRunId:a,eventType:X0.STARTED,occurredAt:r.nowIso(),dagId:o.dagId,version:o.version});let d=[],f=[];for(let e of c){let n=`${a}:${e.nodeId}:attempt:1`;(await t.commitExecution(a,{kind:`admit`,dependsOn:[],taskRun:{taskRunId:n,dagRunId:a,nodeId:e.nodeId,status:`queued`,attempt:1}})).applied&&(d.push(n),f.push({messageId:`${n}:message`,dagRunId:a,taskRunId:n,nodeId:e.nodeId,attempt:1,executionPath:[`dagId:${o.dagId}`,`dagRunId:${a}`,`nodeId:${e.nodeId}`,`taskRunId:${n}`,`attempt:1`],payload:s,createdAt:r.nowIso()}))}for(let e of f)try{await n.enqueue(e)}catch(n){return eJe(a,e.taskRunId,e.nodeId,d,n,t,r,i)}return{ok:!0,value:{taskRunIds:d}}}async function eJe(e,t,n,r,i,a,o,s){let c=P1(`DAG_DISPATCH_ENQUEUE_FAILED`,`Failed to enqueue entry task`,{dagRunId:e,taskRunId:t,nodeId:n,errorMessage:i instanceof Error&&i.message.trim().length>0?i.message:`Unknown error`});G1.transition(`running`,`COMPLETE_FAILURE`).ok&&(await a.commitExecution(e,{kind:`transition-run`,expectedStatus:`running`,event:`COMPLETE_FAILURE`,endedAt:o.nowIso()})).applied&&s?.publish({dagRunId:e,eventType:X0.FAILED,occurredAt:o.nowIso(),error:c});for(let t of r)await a.commitExecution(e,{kind:`cancel-task`,taskRunId:t,error:c});return{ok:!1,error:c}}function tJe(e,t){return e===void 0||t===void 0?e===t:e.rootRunId===t.rootRunId&&e.parentRunId===t.parentRunId&&e.depth===t.depth&&e.maxDepth===t.maxDepth&&e.ancestorCompositeNodeTypes.length===t.ancestorCompositeNodeTypes.length&&e.ancestorCompositeNodeTypes.every((e,n)=>e===t.ancestorCompositeNodeTypes[n])}var nJe=class{storage;queue;clock;runProgressEventReporter;snapshotBudget;timeSemanticsService;constructor(e,t,n,r,i){this.storage=e,this.queue=t,this.clock=n,this.runProgressEventReporter=r,this.snapshotBudget=i,this.timeSemanticsService=new wqe(n)}async createRun(e){let t=e.version?await this.storage.getDefinition(e.dagId,e.version):await this.storage.getLatestPublishedDefinition(e.dagId);if(!t)return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_NOT_FOUND`,`Published DAG definition was not found`,{dagId:e.dagId,hasVersion:!!e.version})};if(t.status!==`published`)return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_NOT_PUBLISHED`,`Only published definitions can be executed`,{dagId:t.dagId,version:t.version,status:t.status})};let n=this.timeSemanticsService.resolve(e.trigger,e.logicalDate);if(!n.ok)return n;let r;try{r=Y0(e.lineage)}catch{return{ok:!1,error:Q(`DAG_VALIDATION_RUN_LINEAGE_INVALID`,`Composite child run lineage is invalid`,{dagId:t.dagId})}}let i=e.rerunKey?`${t.dagId}:${n.value.logicalDate}:rerun:${e.rerunKey}`:`${t.dagId}:${n.value.logicalDate}`,a=await this.storage.getDagRunByRunKey(i);if(a){let e;try{e=Y0(a.lineage)}catch{return{ok:!1,error:Q(`DAG_VALIDATION_RUN_LINEAGE_INVALID`,`Existing run for this run key has invalid persisted lineage`,{dagId:t.dagId,runKey:i})}}return tJe(e,r)?{ok:!0,value:{dagRunId:a.dagRunId,dagId:a.dagId,version:a.version,logicalDate:a.logicalDate,status:a.status}}:{ok:!1,error:Q(`DAG_VALIDATION_RUN_KEY_LINEAGE_MISMATCH`,`An existing run for this run key has different composite lineage`,{dagId:t.dagId,runKey:i,existingDagRunId:a.dagRunId})}}let o=this.generateDagRunId(t.dagId,n.value.logicalDate,e.rerunKey);try{let a=(a,s)=>this.storage.createDagRun({dagRunId:o,dagId:t.dagId,version:t.version,status:`created`,definitionSnapshot:a,inputSnapshot:s,runKey:i,logicalDate:n.value.logicalDate,trigger:e.trigger,...r===void 0?{}:{lineage:r},startedAt:this.clock.nowIso()});if(this.snapshotBudget){let n=await this.snapshotBudget.admitRun(t,e.input,a);if(!n.ok)return n}else await a(JSON.stringify(t),JSON.stringify(e.input))}catch(e){return this.snapshotBudget?{ok:!1,error:F1(`DAG_RUN_SNAPSHOT_PERSISTENCE_UNCERTAIN`,`Run snapshot persistence outcome is uncertain; root snapshot admission is closed`,!1)}:{ok:!1,error:P1(`DAG_DISPATCH_DAG_RUN_CREATE_FAILED`,`Failed to create DagRun`,{dagId:t.dagId,version:t.version,runKey:i,errorMessage:this.resolveErrorMessage(e instanceof Error?e:void 0)})}}return{ok:!0,value:{dagRunId:o,dagId:t.dagId,version:t.version,logicalDate:n.value.logicalDate,status:`created`}}}async startCreatedRun(e){let t=await this.storage.getDagRun(e);if(!t)return{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})};if(t.status!==`created`){let n=await this.storage.listTaskRunsByDagRunId(e);return{ok:!0,value:{dagRunId:e,dagId:t.dagId,version:t.version,logicalDate:t.logicalDate,taskRunIds:n.map(e=>e.taskRunId)}}}if(typeof t.definitionSnapshot!=`string`||t.definitionSnapshot.trim().length===0)return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_SNAPSHOT_MISSING`,`DagRun definition snapshot is missing`,{dagRunId:e})};let n=Qqe(t.definitionSnapshot);if(!n.ok)return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_SNAPSHOT_INVALID`,`DagRun definition snapshot is invalid`,{dagRunId:e})};let r=Zqe(t.inputSnapshot??`{}`);if(!r.ok)return{ok:!1,error:Q(`DAG_VALIDATION_RUN_INPUT_SNAPSHOT_INVALID`,`DagRun input snapshot is invalid`,{dagRunId:e})};let i=await $qe({dagRunId:e,definition:n.value,input:r.value},this.storage,this.queue,this.clock,this.runProgressEventReporter);return i.ok?{ok:!0,value:{dagRunId:e,dagId:t.dagId,version:t.version,logicalDate:t.logicalDate,taskRunIds:i.value.taskRunIds}}:i}async startRun(e){let t=await this.createRun(e);if(!t.ok)return t;if(t.value.status===`created`)return this.startCreatedRun(t.value.dagRunId);let n=await this.storage.listTaskRunsByDagRunId(t.value.dagRunId);return{ok:!0,value:{dagRunId:t.value.dagRunId,dagId:t.value.dagId,version:t.value.version,logicalDate:t.value.logicalDate,taskRunIds:n.map(e=>e.taskRunId)}}}generateDagRunId(e,t,n){let r=Date.parse(t);return n?`${e}:run:${r}:rerun:${n}`:`${e}:run:${r}`}resolveErrorMessage(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}},rJe=class{storage;constructor(e){this.storage=e}async getRun(e){let t=await this.storage.getDagRun(e);return t?{ok:!0,value:{dagRun:t,taskRuns:await this.storage.listTaskRunsByDagRunId(e)}}:{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})}}},iJe=class{storage;clock;notifier;constructor(e,t,n){this.storage=e,this.clock=t,this.notifier=n}async cancelRun(e){let t=await this.storage.getDagRun(e);if(!t)return{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})};let n=G1.transition(t.status,`CANCEL`);if(!n.ok)return n;let r=await this.storage.commitExecution(e,{kind:`transition-run`,expectedStatus:t.status,event:`CANCEL`,endedAt:this.clock.nowIso()});if(!r.applied){if(r.runStatus===`cancelled`)return this.notify(e),{ok:!0,value:{dagRunId:e,status:`cancelled`}};if(r.runStatus!==void 0){let t=G1.transition(r.runStatus,`CANCEL`);return t.ok?this.cancelRun(e):t}return{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})}}return this.notify(e),{ok:!0,value:{dagRunId:e,status:`cancelled`}}}notify(e){try{this.notifier?.notifyRunCancelled(e)}catch{}}};async function c2(e,t,n,r){let i=await t.commitExecution(e,{kind:`finalize`,endedAt:n.nowIso()});if(i.error)return{ok:!1,error:i.error};if(i.runStatus===void 0)return{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun not found while finalizing run status`,{dagRunId:e})};if(!i.applied)return{ok:!0,value:void 0};let a=i.runStatus===`failed`,o=await t.listTaskRunsByDagRunId(e);return a?aJe(e,o,n,r):r?.publish({dagRunId:e,eventType:X0.COMPLETED,occurredAt:n.nowIso()}),{ok:!0,value:void 0}}function aJe(e,t,n,r){let i=t.find(e=>e.status===`failed`),a=typeof i?.errorCode==`string`&&typeof i.errorMessage==`string`?F1(i.errorCode,i.errorMessage,!1,{dagRunId:e,taskRunId:i.taskRunId,nodeId:i.nodeId}):F1(`DAG_TASK_EXECUTION_FAILED`,`Run completed with failure.`,!1,{dagRunId:e});r?.publish({dagRunId:e,eventType:X0.FAILED,occurredAt:n.nowIso(),error:a})}async function l2(e,t,n,r,i){await e.updateTaskRunStatus(n.taskRunId,r,i),await e.setTaskRunLease(n.taskRunId,void 0,void 0),await c2(n.dagRunId,e,t)}async function oJe(e,t){let n=K1.transition(t.status,`CANCEL`);return n.ok?(await e.updateTaskRunStatus(t.taskRunId,n.value.nextStatus,{code:`DAG_TASK_EXECUTION_ORPHANED`,category:`task_execution`,message:`Task's DAG run ${t.dagRunId} no longer exists; the task cannot be run or finalized`,retryable:!1,context:{taskRunId:t.taskRunId,dagRunId:t.dagRunId}}),await e.setTaskRunLease(t.taskRunId,void 0,void 0),{ok:!0,value:void 0}):n}async function sJe(e,t,n,r,i){let a=await e.listStaleRunningTaskRuns(n.nowIso()),o={requeued:[],abandoned:[],skipped:[],failed:[],orphaned:[]};for(let s of a){let a=`taskRun:${s.taskRunId}`;if(!await r.acquire(a,i.workerId,i.leaseDurationMs)){o.skipped.push(s.taskRunId);continue}try{let r=await e.getTaskRun(s.taskRunId);if(r===void 0||r.status!==`running`||fJe(r,n.nowIso())){o.skipped.push(s.taskRunId);continue}await cJe(e,t,n,r,i.maxAttempts,o)}catch(e){o.failed.push({taskRunId:s.taskRunId,error:e})}finally{await r.release(a,i.workerId)}}return o}async function cJe(e,t,n,r,i,a){{let o=K1.transition(r.status,`RECLAIM`);if(!o.ok){a.skipped.push(r.taskRunId);return}let s=await e.getDagRun(r.dagRunId);if(s===void 0){if(!(await oJe(e,r)).ok){a.skipped.push(r.taskRunId);return}a.orphaned.push(r.taskRunId);return}if(lJe.has(s.status)){let t=K1.transition(r.status,`CANCEL`);if(!t.ok){a.skipped.push(r.taskRunId);return}await l2(e,n,r,t.value.nextStatus),a.abandoned.push(r.taskRunId);return}if(r.attempt>=i){let t=K1.transition(r.status,`COMPLETE_FAILURE`);if(!t.ok){a.skipped.push(r.taskRunId);return}await l2(e,n,r,t.value.nextStatus,{code:`DAG_TASK_EXECUTION_ABANDONED`,category:`task_execution`,message:`Task was abandoned by its worker ${r.attempt} time(s) and has no attempts left`,retryable:!1,context:{taskRunId:r.taskRunId,attempt:r.attempt,maxAttempts:i}}),a.abandoned.push(r.taskRunId);return}let c=r.attempt+1;await e.incrementTaskAttempt(r.taskRunId),await t.enqueue(uJe(r,c,n.nowIso())),await e.updateTaskRunStatus(r.taskRunId,o.value.nextStatus),await e.setTaskRunLease(r.taskRunId,void 0,void 0),a.requeued.push(r.taskRunId)}}const lJe=new Set([`success`,`failed`,`cancelled`]);function uJe(e,t,n){return{payload:dJe(e.inputSnapshot),messageId:`${e.taskRunId}:reclaim:${t}`,dagRunId:e.dagRunId,taskRunId:e.taskRunId,nodeId:e.nodeId,attempt:t,executionPath:[`dagRunId:${e.dagRunId}`,`nodeId:${e.nodeId}`,`taskRunId:${e.taskRunId}`,`attempt:${t}`,`reclaimed:true`],createdAt:n}}function dJe(e){if(e===void 0)return{};try{let t=JSON.parse(e);return typeof t==`object`&&t?t:{}}catch{return{}}}function fJe(e,t){return e.leaseUntil!==void 0&&e.leaseUntil>t}var pJe=class{clock;lease;options;lastSweepAtMs=0;sweeping=!1;constructor(e,t,n){this.clock=e,this.lease=t,this.options=n}async sweepIfDue(e,t){let n=this.clock.nowEpochMs();if(!(this.sweeping||n-this.lastSweepAtMs<this.options.leaseDurationMs)){this.sweeping=!0;try{let n=(await sJe(e,t,this.clock,this.lease,this.options)).failed[0];if(n===void 0)return;throw n.error}catch(e){return{code:`DAG_TASK_SWEEP_FAILED`,category:`task_execution`,message:`Stale-task sweep failed: ${e instanceof Error?e.message:String(e)}`,retryable:!0,context:{workerId:this.options.workerId}}}finally{this.lastSweepAtMs=this.clock.nowEpochMs(),this.sweeping=!1}}}};function mJe(e,t){let n=e.map(e=>e.startsWith(`attempt:`)?`attempt:${t}`:e);return n.some(e=>e.startsWith(`attempt:`))||n.push(`attempt:${t}`),n}function u2(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}async function d2(e,t,n,r,i,a,o,s){if(r.deadLetterEnabled){let t=await gJe(e,n,r,o);if(!t.ok)return f2(a,e.messageId,t.error)}let c=await c2(e.dagRunId,i,o,s);return c.ok?p2(a,e.messageId,t,!1):f2(a,e.messageId,c.error)}async function hJe(e,t,n,r){let i=e.attempt+1,a={...e,messageId:`${e.taskRunId}:message:${i}`,attempt:i,executionPath:mJe(e.executionPath,i),createdAt:r.nowIso()};try{await n.enqueue(a)}catch(r){return f2(n,e.messageId,P1(`DAG_DISPATCH_ENQUEUE_RETRY_FAILED`,`Failed to enqueue retry message`,{taskRunId:t,attempt:i,errorMessage:u2(r)}))}return p2(n,e.messageId,t,!0)}async function gJe(e,t,n,r){if(!n.deadLetterQueue)return{ok:!1,error:Q(`DAG_VALIDATION_DEAD_LETTER_QUEUE_NOT_CONFIGURED`,`deadLetterEnabled requires deadLetterQueue to be configured`,{taskRunId:e.taskRunId})};let i={...e,messageId:`${e.taskRunId}:dlq:${r.nowEpochMs()}`,payload:{...e.payload,dlqReasonCode:t.code,dlqReasonMessage:t.message,dlqSourceMessageId:e.messageId},createdAt:r.nowIso()};try{return await n.deadLetterQueue.enqueue(i),{ok:!0,value:void 0}}catch(t){return{ok:!1,error:P1(`DAG_DISPATCH_DEAD_LETTER_ENQUEUE_FAILED`,`Failed to enqueue dead letter message`,{taskRunId:e.taskRunId,originalMessageId:e.messageId,errorMessage:u2(t)})}}}async function f2(e,t,n){return await e.ack(t),{ok:!1,error:n}}async function p2(e,t,n,r){return await e.ack(t),{ok:!0,value:{processed:!0,taskRunId:n,retried:r}}}function _Je(e){if(e.status!==`running`)return{ok:!0,value:e.status};let t=K1.transition(e.status,`RECLAIM`);return t.ok?{ok:!0,value:t.value.nextStatus}:t}function m2(e,t){return Math.max(e,t)+3e4}function vJe(e,t,n){return new Date(e.nowEpochMs()+m2(t,n)).toISOString()}async function yJe(e){let{storage:t,clock:n,message:r,taskRun:i}=e,a=i.status===`running`,o=_Je(i);if(!o.ok)return o;if(a){if(i.attempt>=e.options.maxAttempts)return{ok:!1,error:{code:`DAG_TASK_EXECUTION_ABANDONED`,category:`task_execution`,message:`Task was abandoned by its worker ${i.attempt} time(s) and has no attempts left`,retryable:!1,context:{taskRunId:i.taskRunId,attempt:i.attempt,maxAttempts:e.options.maxAttempts}}};await t.incrementTaskAttempt(i.taskRunId)}let s=a?i.attempt+1:i.attempt,c=K1.transition(o.value,`START`);return c.ok?(await t.setTaskRunLease(i.taskRunId,e.options.workerId,vJe(n,e.timeoutMs,e.options.leaseDurationMs)),await t.updateTaskRunStatus(i.taskRunId,c.value.nextStatus),e.reporter?.publish({dagRunId:r.dagRunId,eventType:Z0.STARTED,occurredAt:n.nowIso(),taskRunId:i.taskRunId,nodeId:r.nodeId,input:r.payload}),{ok:!0,value:s}):c}async function bJe(e,t,n,r,i,a){let o=`taskRun:${t}`;if(!await e.acquire(o,n,r))return a();try{return await i()}finally{await e.release(o,n)}}async function xJe(e,t){let{message:n,taskRun:r,storage:i,queue:a,clock:o}=t;if(e.code!==`DAG_TASK_EXECUTION_ABANDONED`)return f2(a,n.messageId,e);let s=K1.transition(r.status,`COMPLETE_FAILURE`);return s.ok?(await i.updateTaskRunStatus(r.taskRunId,s.value.nextStatus,e),await i.setTaskRunLease(r.taskRunId,void 0,void 0),d2(n,r.taskRunId,e,t.options,i,a,o,t.reporter)):f2(a,n.messageId,s.error)}function SJe(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}function CJe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function wJe(e,t,n){let r=e.nodes.find(e=>e.nodeId===n);if(!r)return{ok:!1,error:Q(`DAG_VALIDATION_DOWNSTREAM_NODE_NOT_FOUND`,`Downstream node was not found while building payload`,{downstreamNodeId:n})};let i=e.edges.filter(e=>e.to===n);if(i.length===0)return{ok:!0,value:{}};let a={};for(let e of i){let n=TJe(a,e,r,t);if(!n.ok)return n}return AJe(a,r.inputs??[]),{ok:!0,value:a}}function TJe(e,t,n,r){if(!t.bindings||t.bindings.length===0)return{ok:!1,error:Q(`DAG_VALIDATION_BINDING_REQUIRED`,`Incoming edge must define at least one binding`,{from:t.from,to:t.to})};let i=EJe(t.from,t.to,r);if(!i.ok)return i;let a=i.value;for(let r of t.bindings){let i=DJe(e,r,a,t,n);if(!i.ok)return i}return{ok:!0,value:void 0}}function EJe(e,t,n){let r=n.find(t=>t.nodeId===e&&t.status===`success`);if(!r||!r.outputSnapshot)return{ok:!1,error:Q(`DAG_VALIDATION_UPSTREAM_OUTPUT_MISSING`,`Upstream output snapshot is missing for binding dispatch`,{from:e,to:t})};try{let n=JSON.parse(r.outputSnapshot);return CJe(n)?{ok:!0,value:n}:{ok:!1,error:Q(`DAG_VALIDATION_UPSTREAM_OUTPUT_INVALID`,`Upstream output snapshot has invalid payload shape`,{from:e,to:t})}}catch(n){return{ok:!1,error:Q(`DAG_VALIDATION_UPSTREAM_OUTPUT_PARSE_FAILED`,`Failed to parse upstream output snapshot`,{from:e,to:t,errorMessage:SJe(n)})}}}function DJe(e,t,n,r,i){let a=n[t.outputKey];if(a===void 0)return{ok:!1,error:Q(`DAG_VALIDATION_BINDING_OUTPUT_KEY_MISSING`,`Binding outputKey was not found in upstream output`,{from:r.from,outputKey:t.outputKey})};if((i.inputs??[]).find(e=>e.key===t.inputKey)?.isList)return OJe(e,t.inputKey,a,r.to);let o=p0(t.inputKey);return o?kJe(e,o,a,t.inputKey,r.to,i):e[t.inputKey]===void 0?(e[t.inputKey]=a,{ok:!0,value:void 0}):{ok:!1,error:Q(`DAG_VALIDATION_BINDING_INPUT_KEY_CONFLICT`,`Multiple bindings target the same input key`,{to:r.to,inputKey:t.inputKey})}}function OJe(e,t,n,r){Array.isArray(e[t])||(e[t]=[]);let i=e[t];return Array.isArray(i)?(i.push(n),{ok:!0,value:void 0}):{ok:!1,error:Q(`DAG_VALIDATION_BINDING_LIST_PAYLOAD_INVALID`,`List payload container is invalid`,{to:r,inputKey:t})}}function kJe(e,t,n,r,i,a){if(!(a.inputs??[]).find(e=>e.key===t.portKey)?.isList)return{ok:!1,error:Q(`DAG_VALIDATION_BINDING_INPUT_KEY_MISSING`,`Binding inputKey does not resolve to a valid list input port`,{to:i,inputKey:r})};let o=e[t.portKey],s=Array.isArray(o)?o:[];return s[t.index]=n,e[t.portKey]=s,{ok:!0,value:void 0}}function AJe(e,t){for(let n of t){if(!n.isList)continue;let t=e[n.key];Array.isArray(t)&&(e[n.key]=t.filter(e=>e!==void 0))}}function jJe(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}async function MJe(e,t,n,r,i,a,o){let s=t.nodes.filter(e=>e.dependsOn.includes(n));if(s.length===0)return{ok:!0,value:void 0};let c=await i.listTaskRunsByDagRunId(e.dagRunId);for(let n of s){let r=await NJe(e,t,n,c,i,a,o);if(!r.ok)return r}return{ok:!0,value:void 0}}async function NJe(e,t,n,r,i,a,o){if(r.some(e=>e.nodeId===n.nodeId)||!n.dependsOn.every(e=>r.some(t=>t.nodeId===e&&t.status===`success`)))return{ok:!0,value:void 0};let s=`${e.dagRunId}:${n.nodeId}:attempt:1`;if(!(await i.commitExecution(e.dagRunId,{kind:`admit`,dependsOn:n.dependsOn,taskRun:{taskRunId:s,dagRunId:e.dagRunId,nodeId:n.nodeId,status:`queued`,attempt:1}})).applied)return{ok:!0,value:void 0};let c=wJe(t,r,n.nodeId);if(!c.ok)return c;let l={messageId:`${s}:message:1`,dagRunId:e.dagRunId,taskRunId:s,nodeId:n.nodeId,attempt:1,executionPath:[`dagId:${e.dagId}`,`dagRunId:${e.dagRunId}`,`nodeId:${n.nodeId}`,`taskRunId:${s}`,`attempt:1`],payload:c.value,createdAt:o.nowIso()};try{await a.enqueue(l)}catch(t){let r=K1.transition(`queued`,`CANCEL`);return r.ok&&await i.updateTaskRunStatus(s,r.value.nextStatus),{ok:!1,error:P1(`DAG_DISPATCH_ENQUEUE_DOWNSTREAM_FAILED`,`Failed to enqueue downstream task`,{dagRunId:e.dagRunId,nodeId:n.nodeId,errorMessage:jJe(t)})}}return r.push({taskRunId:s,dagRunId:e.dagRunId,nodeId:n.nodeId,status:`queued`,attempt:1}),{ok:!0,value:void 0}}var PJe=class{storage;queue;clock;options;runProgressEventReporter;snapshotBudget;constructor(e,t,n,r,i,a){this.storage=e,this.queue=t,this.clock=n,this.options=r,this.runProgressEventReporter=i,this.snapshotBudget=a}async handleSuccessPath(e,t,n,r,i,a,o){let s=n=>this.storage.commitExecution(e.dagRunId,{kind:`settle`,taskRunId:t,attempt:e.attempt,leaseOwner:this.options.workerId,status:`success`,outputSnapshot:n,estimatedCredits:a,totalCredits:o}),c=this.snapshotBudget?await this.snapshotBudget.admitValue(`output`,i,s):{ok:!0,value:await s(JSON.stringify(i))};if(!c.ok)return this.handleFailurePath(e,t,c.error);if(!c.value.applied){let[n,r]=await Promise.all([this.storage.getDagRun(e.dagRunId),this.storage.getTaskRun(t)]);return n?.status===`running`&&r?.status===`running`&&r.attempt===e.attempt&&r.leaseOwner===this.options.workerId?this.handleFailurePath(e,t,Q(`DAG_VALIDATION_EXECUTION_SETTLEMENT_REJECTED`,`Current task attempt could not settle its successful output`,{taskRunId:t})):p2(this.queue,e.messageId,t,!1)}this.runProgressEventReporter?.publish({dagRunId:e.dagRunId,eventType:Z0.COMPLETED,occurredAt:this.clock.nowIso(),taskRunId:t,nodeId:e.nodeId,input:e.payload,output:i});let l=await MJe(n,r,e.nodeId,i,this.storage,this.queue,this.clock);if(!l.ok)return f2(this.queue,e.messageId,l.error);let u=await c2(e.dagRunId,this.storage,this.clock,this.runProgressEventReporter);return u.ok?p2(this.queue,e.messageId,t,!1):f2(this.queue,e.messageId,u.error)}async handleFailurePath(e,t,n){let r=this.options.retryEnabled&&n.retryable&&e.attempt<this.options.maxAttempts;return(await this.storage.commitExecution(e.dagRunId,{kind:`settle`,taskRunId:t,attempt:e.attempt,leaseOwner:this.options.workerId,status:`failed`,reserveRetry:r,error:n})).applied?(this.runProgressEventReporter?.publish({dagRunId:e.dagRunId,eventType:Z0.FAILED,occurredAt:this.clock.nowIso(),taskRunId:t,nodeId:e.nodeId,input:e.payload,error:n}),r?hJe(e,t,this.queue,this.clock):d2(e,t,n,this.options,this.storage,this.queue,this.clock,this.runProgressEventReporter)):p2(this.queue,e.messageId,t,!1)}};function FJe(e,t){return F1(`DAG_TASK_EXECUTION_TIMEOUT`,`Task execution timed out after ${t}ms`,!0,{taskRunId:e,timeoutMs:t})}function h2(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}function g2(e,t,n,r){return new Promise(i=>{let a=new AbortController,o=!1,s,c=e=>{o||(o=!0,clearTimeout(s),t.signal?.removeEventListener(`abort`,u),i(e))},l=n=>{if(!o){if(o=!0,clearTimeout(s),t.signal?.removeEventListener(`abort`,u),a.abort(n),!e.stopAndWait){i({ok:!1,error:n});return}Promise.resolve().then(()=>e.stopAndWait?.(t)).then(()=>i({ok:!1,error:n}),e=>i({ok:!1,error:{...n,retryable:!1,context:{...n.context,isolationStopError:h2(e)}}}))}},u=()=>l(I1(r));if(t.signal?.aborted){u();return}t.signal?.addEventListener(`abort`,u,{once:!0}),s=setTimeout(()=>l(FJe(r,n)),n);let d=e=>c({ok:!1,error:F1(`DAG_TASK_EXECUTION_EXCEPTION`,`Task executor threw an exception`,!0,{taskRunId:r,errorMessage:h2(e)})});try{e.execute({...t,signal:a.signal}).then(c,d)}catch(e){d(e)}})}function IJe(e){let t=0;for(let n of e)typeof n.totalCredits==`number`&&n.totalCredits>t&&(t=n.totalCredits);return t}function LJe(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}function RJe(e,t){if(typeof e.definitionSnapshot!=`string`||e.definitionSnapshot.trim().length===0)return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_SNAPSHOT_MISSING`,`DagRun definition snapshot is missing`,{dagRunId:t})};let n;try{n=JSON.parse(e.definitionSnapshot)}catch(e){return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_SNAPSHOT_PARSE_FAILED`,`Failed to parse DagRun definition snapshot`,{dagRunId:t,errorMessage:LJe(e)})}}return o0(n,`DAG_VALIDATION_DEFINITION_SNAPSHOT_INVALID`,`DagRun definition snapshot has invalid shape`,{dagRunId:t})}async function _2(e,t){let n=await e.getDagRun(t.dagRunId);if(!n)return{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun not found for dequeued message`,{dagRunId:t.dagRunId})};let r=RJe(n,t.dagRunId);if(!r.ok)return r;let i=r.value,a=i.nodes.find(e=>e.nodeId===t.nodeId);return a?{ok:!0,value:{dagRun:n,definition:i,nodeDefinition:a}}:{ok:!1,error:Q(`DAG_VALIDATION_NODE_NOT_FOUND`,`Node definition not found for task execution`,{nodeId:t.nodeId,dagId:n.dagId,version:n.version})}}var zJe=class{storage;queue;lease;executor;clock;options;runProgressEventReporter;snapshotBudget;rootCreditBudget;lifecycleCreditAdmission;executionRoot;byteLimits;cancellationPollMs;activeAttempts=new Set;notifyRunCancelled(e){for(let t of this.activeAttempts)t.dagRunId===e&&t.controller.abort()}constructor(e,t,n,r,i,a,o,s,c,l,u,d=!1){if(this.storage=e,this.queue=t,this.lease=n,this.executor=r,this.clock=i,this.options=o,this.runProgressEventReporter=s,this.snapshotBudget=l,this.rootCreditBudget=u,this.lifecycleCreditAdmission=d,this.executionRoot=rn(a),this.byteLimits=H1(c),this.cancellationPollMs=o.cancellationPollMs??250,!Number.isSafeInteger(this.cancellationPollMs)||this.cancellationPollMs<1||this.cancellationPollMs>6e4)throw RangeError(`cancellationPollMs must be an integer between 1 and 60000`)}sweeper;outcomesInstance;get outcomes(){return this.outcomesInstance??=new PJe(this.storage,this.queue,this.clock,this.options,this.runProgressEventReporter,this.snapshotBudget),this.outcomesInstance}async processOnce(){let e=await this.queue.dequeue(this.options.workerId,this.options.visibilityTimeoutMs,this.options.idleWaitMs);if(!e){this.sweeper??=new pJe(this.clock,this.lease,this.options);let e=await this.sweeper.sweepIfDue(this.storage,this.queue);return e?{ok:!1,error:e}:{ok:!0,value:{processed:!1}}}let t=await this.resolveTimeoutMs(e);return bJe(this.lease,e.taskRunId,this.options.workerId,m2(t,this.options.leaseDurationMs),async()=>this.processAcquiredMessage(e,t),async()=>(await this.queue.nack(e.messageId),{ok:!0,value:{processed:!1}}))}async processAcquiredMessage(e,t){let n=await this.storage.getTaskRun(e.taskRunId);if(!n){let t=Q(`DAG_VALIDATION_TASK_RUN_NOT_FOUND`,`TaskRun not found for dequeued message`,{taskRunId:e.taskRunId});return f2(this.queue,e.messageId,t)}let r=await this.cancelIfRunCancelled(e);if(r)return r;let i=this.claimDepsFor(e,n,t),a=await yJe(i);if(!a.ok)return xJe(a.error,i);let o={...e,attempt:a.value},s=await _2(this.storage,o);if(!s.ok)return f2(this.queue,e.messageId,s.error);let{dagRun:c,definition:l,nodeDefinition:u}=s.value;if(c.status===`cancelled`)return this.settleCancelledRunMessage(e);let d;try{d=Y0(c.lineage)}catch{return this.outcomes.handleFailurePath(o,o.taskRunId,Q(`DAG_VALIDATION_RUN_LINEAGE_INVALID`,`Persisted composite child run lineage is invalid`,{dagRunId:o.dagRunId}))}if(d){let t=await this.cancelIfAncestorCancelled(e,c,d);if(t)return t}let f=e=>this.storage.commitExecution(o.dagRunId,{kind:`snapshot-input`,taskRunId:o.taskRunId,attempt:o.attempt,leaseOwner:this.options.workerId,inputSnapshot:e}),p=this.snapshotBudget?await this.snapshotBudget.admitValue(`input`,o.payload,f):{ok:!0,value:await f(JSON.stringify(o.payload))};if(!p.ok)return this.outcomes.handleFailurePath(o,o.taskRunId,p.error);if(!p.value.applied)return p2(this.queue,e.messageId,o.taskRunId,!1);let m=await this.buildExecutionInput(o,c,l,u,d),h=new AbortController,g={dagRunId:o.dagRunId,taskRunId:o.taskRunId,attempt:o.attempt,controller:h};this.activeAttempts.add(g);let _,v,y=Date.now()+i.timeoutMs,b;try{let t=await this.cancelIfRunCancelled(e);if(t)return t;if(b=this.watchCommittedCancellation(g),l.costPolicy&&!this.lifecycleCreditAdmission&&!(this.executor instanceof $0)){let t=this.executor.estimateCost;if(!t)return this.outcomes.handleFailurePath(o,n.taskRunId,Q(`DAG_VALIDATION_CREDIT_ESTIMATE_REQUIRED`,`Cost-limited runs require a custom executor to estimate credits before execution`,{taskRunId:o.taskRunId}));let r=await g2({execute:async e=>{let n=await t.call(this.executor,e);return n.ok?{ok:!0,output:{},estimatedCredits:n.value}:n},...this.executor.stopAndWait?{stopAndWait:this.executor.stopAndWait.bind(this.executor)}:{}},{...m,signal:h.signal},Math.max(1,y-Date.now()),e.taskRunId);if(!r.ok)return this.outcomes.handleFailurePath(o,n.taskRunId,r.error);if(r.estimatedCredits===void 0||!Number.isFinite(r.estimatedCredits)||r.estimatedCredits<0)return this.outcomes.handleFailurePath(o,n.taskRunId,Q(`DAG_VALIDATION_CREDIT_ESTIMATE_INVALID`,`Custom executor credit estimate must be a finite nonnegative number`,{taskRunId:o.taskRunId}));let i=await m.reserveCredits(r.estimatedCredits);if(!i.ok)return this.outcomes.handleFailurePath(o,n.taskRunId,i.error);v=r.estimatedCredits}let r=y-Date.now();if(r<=0)return this.outcomes.handleFailurePath(o,n.taskRunId,F1(`DAG_TASK_EXECUTION_TIMEOUT`,`Task execution timed out after ${i.timeoutMs}ms`,!0,{taskRunId:e.taskRunId,timeoutMs:i.timeoutMs}));_=await g2(this.executor,{...m,signal:h.signal},r,e.taskRunId)}finally{b?.(),this.activeAttempts.delete(g)}return _.ok?v!==void 0&&_.estimatedCredits!==void 0&&_.estimatedCredits!==v?this.outcomes.handleFailurePath(o,n.taskRunId,Q(`DAG_VALIDATION_CREDIT_ESTIMATE_MISMATCH`,`Custom executor reported credits different from its preflight estimate`,{taskRunId:o.taskRunId})):this.outcomes.handleSuccessPath(o,n.taskRunId,c,l,_.output,v??_.estimatedCredits,_.totalCredits):this.outcomes.handleFailurePath(o,n.taskRunId,_.error)}watchCommittedCancellation(e){let t=!1,n,r=async()=>{if(!t){try{let n=await this.storage.getDagRun(e.dagRunId);!t&&n?.status!==`running`&&e.controller.abort()}catch{t||e.controller.abort()}!t&&!e.controller.signal.aborted&&(n=setTimeout(()=>{r()},this.cancellationPollMs))}};return n=setTimeout(()=>{r()},this.cancellationPollMs),()=>{t=!0,clearTimeout(n)}}async cancelIfRunCancelled(e){return(await this.storage.getDagRun(e.dagRunId))?.status===`cancelled`?this.settleCancelledRunMessage(e):void 0}async cancelIfAncestorCancelled(e,t,n){if(n.parentRunId===void 0)return;let r=new Set([n.rootRunId,n.parentRunId]);for(let n of r)if((await this.storage.getDagRun(n))?.status===`cancelled`)return await this.cancelOwnRunForAncestor(t),this.settleCancelledRunMessage(e)}async cancelOwnRunForAncestor(e){if(!G1.transition(e.status,`CANCEL`).ok)return;let t=await this.storage.commitExecution(e.dagRunId,{kind:`transition-run`,expectedStatus:e.status,event:`CANCEL`,endedAt:this.clock.nowIso()});if(t.applied||t.runStatus===`cancelled`){this.notifyRunCancelled(e.dagRunId);return}if(t.runStatus!==void 0){let t=await this.storage.getDagRun(e.dagRunId);t&&await this.cancelOwnRunForAncestor(t)}}async settleCancelledRunMessage(e){let t=await this.storage.getTaskRun(e.taskRunId);if(t){let e=K1.transition(t.status,`CANCEL`);e.ok&&await this.storage.updateTaskRunStatus(t.taskRunId,e.value.nextStatus),await this.storage.setTaskRunLease(t.taskRunId,void 0,void 0)}return p2(this.queue,e.messageId,e.taskRunId,!1)}async buildExecutionInput(e,t,n,r,i){let a=IJe(await this.storage.listTaskRunsByDagRunId(e.dagRunId));return{executionRoot:this.executionRoot,...i===void 0?{}:{lineage:i},byteLimits:this.byteLimits,snapshotBudget:this.snapshotBudget,rootCreditBudget:this.rootCreditBudget,reserveCredits:n.costPolicy?async t=>{let n=await this.storage.commitExecution(e.dagRunId,{kind:`reserve-credits`,taskRunId:e.taskRunId,attempt:e.attempt,leaseOwner:this.options.workerId,estimatedCredits:t});return n.applied?{ok:!0,value:void 0}:{ok:!1,error:n.error??Q(`DAG_VALIDATION_CREDIT_RESERVATION_REJECTED`,`Task attempt lost credit reservation authority`,{taskRunId:e.taskRunId})}}:void 0,dagId:t.dagId,dagRunId:e.dagRunId,taskRunId:e.taskRunId,nodeId:e.nodeId,attempt:e.attempt,executionPath:e.executionPath,input:e.payload,nodeDefinition:r,costPolicy:n.costPolicy,currentTotalCredits:a}}claimDepsFor(e,t,n){return{storage:this.storage,queue:this.queue,clock:this.clock,reporter:this.runProgressEventReporter,options:this.options,timeoutMs:n,message:e,taskRun:t}}async resolveTimeoutMs(e){let t=await _2(this.storage,e);if(!t.ok)return this.options.defaultTimeoutMs;let n=t.value.nodeDefinition.timeoutMs;return typeof n==`number`&&n>0?n:this.options.defaultTimeoutMs}},BJe=class extends Error{constructor(){super(`Run advancement has stopped and cannot be restarted.`),this.name=`RunAdvancementStoppedError`}};function VJe(e){return e===`success`||e===`failed`||e===`cancelled`}function v2(e,t,n){return P1(e,t,{dagRunId:n})}var HJe=class{workerStep;runReader;logger;lifecycle=`created`;continuousDemand=!1;waiters=new Map;actorPromise=null;stopPromise=null;wakeSleep=null;constructor(e,t,n={error:()=>void 0}){this.workerStep=e,this.runReader=t,this.logger=n}async start(){if(this.lifecycle===`stopping`||this.lifecycle===`stopped`)throw new BJe;this.lifecycle=`running`,this.continuousDemand=!0,this.wake(),this.ensureActor()}waitForTerminal(e,t={}){if(this.lifecycle===`stopping`||this.lifecycle===`stopped`)return Promise.resolve({ok:!1,error:v2(`DAG_RUNTIME_ADVANCEMENT_STOPPED`,`Run advancement stopped before the observed run became terminal.`,e)});if(t.signal?.aborted)return Promise.resolve({ok:!1,error:v2(`DAG_RUNTIME_ADVANCEMENT_WAIT_ABORTED`,`Run terminal-state observation was aborted.`,e)});if(t.deadlineEpochMs!==void 0&&t.deadlineEpochMs<=Date.now())return Promise.resolve({ok:!1,error:v2(`DAG_RUNTIME_ADVANCEMENT_WAIT_DEADLINE`,`Run terminal-state observation exceeded its deadline.`,e)});let n=new Promise(n=>{let r={id:Symbol(e),dagRunId:e,resolve:n,signal:t.signal,settled:!1};t.signal!==void 0&&(r.abortListener=()=>{this.settle(r,{ok:!1,error:v2(`DAG_RUNTIME_ADVANCEMENT_WAIT_ABORTED`,`Run terminal-state observation was aborted.`,e)})},t.signal.addEventListener(`abort`,r.abortListener,{once:!0})),t.deadlineEpochMs!==void 0&&(r.deadlineTimer=setTimeout(()=>{this.settle(r,{ok:!1,error:v2(`DAG_RUNTIME_ADVANCEMENT_WAIT_DEADLINE`,`Run terminal-state observation exceeded its deadline.`,e)})},Math.max(0,t.deadlineEpochMs-Date.now())),r.deadlineTimer.unref?.()),this.waiters.set(r.id,r)});return this.wake(),this.ensureActor(),n}stop(){if(this.stopPromise!==null)return this.stopPromise;this.lifecycle=`stopping`,this.continuousDemand=!1;for(let e of[...this.waiters.values()])this.settle(e,{ok:!1,error:v2(`DAG_RUNTIME_ADVANCEMENT_STOPPED`,`Run advancement stopped before the observed run became terminal.`,e.dagRunId)});return this.wake(),this.stopPromise=(async()=>{await this.actorPromise,this.lifecycle=`stopped`})(),this.stopPromise}hasDemand(){return(this.lifecycle===`created`||this.lifecycle===`running`)&&(this.continuousDemand||this.waiters.size>0)}ensureActor(){if(!this.hasDemand()||this.actorPromise!==null)return;let e=this.runActor().catch(e=>{this.logger.error(`Run advancement actor failed unexpectedly.`,e)}).finally(()=>{this.actorPromise===e&&(this.actorPromise=null),this.hasDemand()&&this.ensureActor()});this.actorPromise=e}async runActor(){let e=25;for(;this.hasDemand();){if(await this.queryAndSettleWaiters(),!this.hasDemand())return;let t;try{t=await this.workerStep.processOnce()}catch(e){this.logger.error(`Worker step threw during run advancement.`,e),await this.sleepUntilWake(500);continue}if(!this.hasDemand())return;if(!t.ok){this.logger.error(`Worker step failed during run advancement.`,t.error),await this.sleepUntilWake(500);continue}if(t.value.processed){e=25;continue}await this.sleepUntilWake(e),e=Math.min(e*2,500)}}async queryAndSettleWaiters(){let e=new Set([...this.waiters.values()].map(e=>e.dagRunId));for(let t of e){let e;try{e=await this.runReader.getRun(t)}catch(n){e={ok:!1,error:v2(`DAG_RUNTIME_ADVANCEMENT_QUERY_THROW`,n instanceof Error?n.message:String(n),t)}}let n=[...this.waiters.values()].filter(e=>e.dagRunId===t);if(!e.ok||VJe(e.value.dagRun.status))for(let t of n)this.settle(t,e)}}settle(e,t){e.settled||(e.settled=!0,this.waiters.delete(e.id),e.deadlineTimer!==void 0&&clearTimeout(e.deadlineTimer),e.signal!==void 0&&e.abortListener!==void 0&&e.signal.removeEventListener(`abort`,e.abortListener),e.resolve(t),this.wake())}wake(){this.wakeSleep?.()}async sleepUntilWake(e){this.hasDemand()&&await new Promise(t=>{let n=!1,r=()=>{n||(n=!0,clearTimeout(i),this.wakeSleep===r&&(this.wakeSleep=null),t())},i=setTimeout(r,e);i.unref?.(),this.wakeSleep=r,this.hasDemand()||r()})}};function UJe(e,t){let n={...t,retryEnabled:t.retryEnabled??!1,deadLetterEnabled:t.deadLetterEnabled??!1,deadLetterQueue:e.deadLetterQueue};return new zJe(e.storage,e.queue,e.lease,e.executor,e.clock,e.executionRoot,n,e.runProgressEventReporter,e.byteLimits,e.snapshotBudget,e.rootCreditBudget,e.lifecycleCreditAdmission)}function WJe(e,t){let n=new Xqe,r=new nJe(e.storage,e.queue,e.clock,n,e.snapshotBudget),i=new rJe(e.storage),a=UJe({executionRoot:e.executionRoot,byteLimits:e.byteLimits,snapshotBudget:e.snapshotBudget,rootCreditBudget:e.rootCreditBudget,lifecycleCreditAdmission:e.lifecycleCreditAdmission,storage:e.storage,queue:e.queue,deadLetterQueue:e.deadLetterQueue,lease:e.lease,executor:e.executor,clock:e.clock,runProgressEventReporter:n},{...t.worker,retryEnabled:t.worker.retryEnabled??!1});return{runOrchestrator:r,runQuery:i,runCancel:new iJe(e.storage,e.clock,{notifyRunCancelled(t){e.snapshotBudget?.close(),e.rootCreditBudget?.close(),a.notifyRunCancelled(t)}}),runAdvancement:new HJe(a,i,t.logger),runProgressEventBus:n}}function y2(e,t){let{text:n,search:r,replacement:i,flags:a}=e,o;try{o=new RegExp(r,a)}catch{return{type:`invalid-regex`}}let s=Symbol(`regex output exceeds byte limit`),c=new Uint16Array(t),l=0,u=0,d=!1,f=0,p=(e,n,r)=>{for(let i=n;i<r;i++){let n=e.charCodeAt(i);if(u+=n<128?1:n<2048?2:n>=56320&&n<=57343&&d?1:3,d=n>=55296&&n<=56319,u>t)throw s;c[l++]=n}},m=(e,t,r,a)=>{for(let o=0;o<i.length;){let s=i.indexOf(`$`,o);if(s<0){p(i,o,i.length);return}p(i,o,s);let c=i[s+1];if(c===`$`)p(i,s,s+1),o=s+2;else if(c===`&`)p(e,0,e.length),o=s+2;else if(c==="`")p(n,0,r),o=s+2;else if(c===`'`)p(n,r+e.length,n.length),o=s+2;else if(c!==void 0&&c>=`0`&&c<=`9`){let e=i[s+2],n=e!==void 0&&e>=`0`&&e<=`9`?2:1,r=Number(i.slice(s+1,s+1+n));if(n===2&&r>t.length&&(n=1,r=Number(c)),r>=1&&r<=t.length){let e=t[r-1];e!==void 0&&p(e,0,e.length)}else p(i,s,s+1+n);o=s+1+n}else if(c===`<`){let e=i.indexOf(`>`,s+2);if(e>=0&&a!==void 0){let t=a[i.slice(s+2,e)];t!==void 0&&p(t,0,t.length),o=e+1}else p(i,s,s+2),o=s+2}else p(i,s,s+1),o=s+1}};try{let e=a.includes(`u`)||a.includes(`v`);for(let t=o.exec(n);t!==null;t=o.exec(n)){let r=t[0],i=t.index;if(p(n,f,i),m(r,t.slice(1),i,t.groups),f=i+r.length,!o.global)break;if(r.length===0){let t=o.lastIndex,r=n.charCodeAt(t),i=n.charCodeAt(t+1);o.lastIndex+=e&&r>=55296&&r<=56319&&i>=56320&&i<=57343?2:1}}p(n,f,n.length)}catch(e){return e===s?{type:`oversized`}:{type:`invalid-regex`}}let h=[];for(let e=0;e<l;e+=8192)h.push(String.fromCharCode(...c.subarray(e,Math.min(e+8192,l))));return{type:`result`,value:h.join(``)}}const b2=25166848,GJe=`
2790
2790
  const boundedRegexReplace = ${y2.toString()};
2791
2791
  const send = (message) => process.stdout.write(JSON.stringify(message) + '\\n');
2792
2792
  let input = '';
@@ -2951,4 +2951,4 @@ npm run build
2951
2951
  Alternatively, use headless mode: -p "your prompt here"
2952
2952
 
2953
2953
  `}function F8e(e){Z9=e,!X9&&(X9=!0,process.on(`uncaughtException`,e=>{let t=bSe(e,vSe());if(t===`ime-hint`){process.stderr.write(P8e(Z9));return}if(t!==`guard-owned`)throw e}))}async function Q9(e={}){try{let t=qj(e);A8e(t.config.identity.cliName),F8e(t.config.identity.cliName),await J9({...e,productRuntime:t})}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),d1(KK(process.argv))?process.exitCode=1:process.exit(1)}}function $9(e){if(typeof e==`object`&&e){for(let t of Object.values(e))$9(t);Object.freeze(e)}return e}function I8e(e){if(!e.identity||!e.version?.trim())throw Error(`Consumer CLI artifact requires identity and version.`);if(e.webRoot!==void 0&&!In(e.webRoot))throw Error(`Consumer web asset root must be absolute.`);let t=LSe(structuredClone(e.identity)),n=t.identity.id,r=eD({PRODUCT_USER_STATE_DIR:`${n}/state`,PRODUCT_CACHE_DIR:`${n}/cache`,PRODUCT_LOG_DIR:`${n}/logs`,PRODUCT_PROJECT_STATE_DIR:`.${n}`,PRODUCT_SHARED_USER_SETTINGS:`[]`,PRODUCT_SHARED_PROJECT_SETTINGS:`[]`,...structuredClone(e.runtimeDefaults??{})}),i=$9({...structuredClone(e),identity:t,runtimeDefaults:r,sourceVersion:e.sourceVersion??e.version,buildMetadata:e.buildMetadata??null,update:e.update??!1}),a=(e={})=>Kj(e,i);return Object.freeze({resolveRuntime:(e={})=>qj(a(e)),run:(e={})=>Q9(a(e))})}export{Zj as A,XM as C,Y as D,Qj as E,KE as M,qE as N,$j as O,YM as S,rM as T,aN as _,D0 as a,tN as b,v0 as c,Q as d,hF as f,oN as g,eF as h,E0 as i,$E as j,eM as k,XGe as l,KP as m,Q9 as n,m0 as o,_F as p,J9 as r,g0 as s,I8e as t,F1 as u,iN as v,nM as w,$M as x,rN as y};
2954
- //# sourceMappingURL=product-host-BPPyJk9w.js.map
2954
+ //# sourceMappingURL=product-host-C-IQQ6ph.js.map