@decaf-ts/as-graph 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +59 -13
- package/dist/as-graph.cjs +1 -1
- package/dist/as-graph.cjs.map +1 -1
- package/dist/as-graph.js +1 -1
- package/dist/as-graph.js.map +1 -1
- package/lib/cjs/dagster/DagsterGraphExecutionBackend.cjs +102 -11
- package/lib/cjs/dagster/DagsterGraphExecutionBackend.cjs.map +1 -1
- package/lib/cjs/engine/execution/GraphExecutionEngine.cjs +7 -0
- package/lib/cjs/engine/execution/GraphExecutionEngine.cjs.map +1 -1
- package/lib/cjs/engine/execution/LocalGraphExecutionBackend.cjs +39 -0
- package/lib/cjs/engine/execution/LocalGraphExecutionBackend.cjs.map +1 -1
- package/lib/cjs/engine/index.cjs +1 -0
- package/lib/cjs/engine/index.cjs.map +1 -1
- package/lib/cjs/engine/services/GraphNodeModelService.cjs +129 -0
- package/lib/cjs/engine/services/GraphNodeModelService.cjs.map +1 -0
- package/lib/cjs/engine/services/GraphWorkflowService.cjs +33 -0
- package/lib/cjs/engine/services/GraphWorkflowService.cjs.map +1 -1
- package/lib/cjs/mastra/MastraDefaultStepHandlers.cjs +217 -0
- package/lib/cjs/mastra/MastraDefaultStepHandlers.cjs.map +1 -0
- package/lib/cjs/mastra/MastraEventBridge.cjs +10 -3
- package/lib/cjs/mastra/MastraEventBridge.cjs.map +1 -1
- package/lib/cjs/mastra/MastraGraphExecutionBackend.cjs +111 -13
- package/lib/cjs/mastra/MastraGraphExecutionBackend.cjs.map +1 -1
- package/lib/cjs/mastra/MastraWorkflowCompiler.cjs +3 -3
- package/lib/cjs/mastra/MastraWorkflowCompiler.cjs.map +1 -1
- package/lib/cjs/mastra/index.cjs +1 -0
- package/lib/cjs/mastra/index.cjs.map +1 -1
- package/lib/cjs/mastra/types.cjs +5 -1
- package/lib/cjs/mastra/types.cjs.map +1 -1
- package/lib/cjs/nest/graph/GraphBackendHost.cjs +105 -19
- package/lib/cjs/nest/graph/GraphBackendHost.cjs.map +1 -1
- package/lib/cjs/nest/graph/GraphExecutionModule.cjs +37 -1
- package/lib/cjs/nest/graph/GraphExecutionModule.cjs.map +1 -1
- package/lib/cjs/nest/graph/main.cjs +16 -1
- package/lib/cjs/nest/graph/main.cjs.map +1 -1
- package/lib/cjs/ram/GraphNodeRepository.cjs +40 -0
- package/lib/cjs/ram/GraphNodeRepository.cjs.map +1 -0
- package/lib/cjs/ram/index.cjs +1 -0
- package/lib/cjs/ram/index.cjs.map +1 -1
- package/lib/cjs/shared/graph/GraphNodeConverters.cjs +43 -0
- package/lib/cjs/shared/graph/GraphNodeConverters.cjs.map +1 -0
- package/lib/cjs/shared/graph/GraphNodeModel.cjs +74 -0
- package/lib/cjs/shared/graph/GraphNodeModel.cjs.map +1 -0
- package/lib/cjs/shared/graph/index.cjs +2 -0
- package/lib/cjs/shared/graph/index.cjs.map +1 -1
- package/lib/esm/dagster/DagsterGraphExecutionBackend.js +102 -11
- package/lib/esm/dagster/DagsterGraphExecutionBackend.js.map +1 -1
- package/lib/esm/engine/execution/GraphExecutionBackend.js.map +1 -1
- package/lib/esm/engine/execution/GraphExecutionEngine.js +7 -0
- package/lib/esm/engine/execution/GraphExecutionEngine.js.map +1 -1
- package/lib/esm/engine/execution/LocalGraphExecutionBackend.js +39 -0
- package/lib/esm/engine/execution/LocalGraphExecutionBackend.js.map +1 -1
- package/lib/esm/engine/index.js +1 -0
- package/lib/esm/engine/index.js.map +1 -1
- package/lib/esm/engine/services/GraphNodeModelService.js +120 -0
- package/lib/esm/engine/services/GraphNodeModelService.js.map +1 -0
- package/lib/esm/engine/services/GraphWorkflowService.js +34 -1
- package/lib/esm/engine/services/GraphWorkflowService.js.map +1 -1
- package/lib/esm/mastra/MastraDefaultStepHandlers.js +212 -0
- package/lib/esm/mastra/MastraDefaultStepHandlers.js.map +1 -0
- package/lib/esm/mastra/MastraEventBridge.js +10 -3
- package/lib/esm/mastra/MastraEventBridge.js.map +1 -1
- package/lib/esm/mastra/MastraGraphExecutionBackend.js +112 -14
- package/lib/esm/mastra/MastraGraphExecutionBackend.js.map +1 -1
- package/lib/esm/mastra/MastraWorkflowCompiler.js +3 -3
- package/lib/esm/mastra/MastraWorkflowCompiler.js.map +1 -1
- package/lib/esm/mastra/index.js +1 -0
- package/lib/esm/mastra/index.js.map +1 -1
- package/lib/esm/mastra/types.js +4 -0
- package/lib/esm/mastra/types.js.map +1 -1
- package/lib/esm/nest/graph/GraphBackendHost.js +69 -18
- package/lib/esm/nest/graph/GraphBackendHost.js.map +1 -1
- package/lib/esm/nest/graph/GraphExecutionModule.js +38 -2
- package/lib/esm/nest/graph/GraphExecutionModule.js.map +1 -1
- package/lib/esm/nest/graph/main.js +17 -2
- package/lib/esm/nest/graph/main.js.map +1 -1
- package/lib/esm/ram/GraphNodeRepository.js +31 -0
- package/lib/esm/ram/GraphNodeRepository.js.map +1 -0
- package/lib/esm/ram/index.js +1 -0
- package/lib/esm/ram/index.js.map +1 -1
- package/lib/esm/shared/graph/GraphNodeConverters.js +38 -0
- package/lib/esm/shared/graph/GraphNodeConverters.js.map +1 -0
- package/lib/esm/shared/graph/GraphNodeModel.js +65 -0
- package/lib/esm/shared/graph/GraphNodeModel.js.map +1 -0
- package/lib/esm/shared/graph/index.js +2 -0
- package/lib/esm/shared/graph/index.js.map +1 -1
- package/lib/types/dagster/DagsterGraphExecutionBackend.d.cts +40 -4
- package/lib/types/dagster/DagsterGraphExecutionBackend.d.mts +40 -4
- package/lib/types/engine/execution/GraphExecutionBackend.d.cts +27 -0
- package/lib/types/engine/execution/GraphExecutionBackend.d.mts +27 -0
- package/lib/types/engine/execution/GraphExecutionEngine.d.cts +9 -0
- package/lib/types/engine/execution/GraphExecutionEngine.d.mts +9 -0
- package/lib/types/engine/execution/LocalGraphExecutionBackend.d.cts +14 -0
- package/lib/types/engine/execution/LocalGraphExecutionBackend.d.mts +14 -0
- package/lib/types/engine/index.d.cts +1 -0
- package/lib/types/engine/index.d.mts +1 -0
- package/lib/types/engine/services/GraphNodeModelService.d.cts +54 -0
- package/lib/types/engine/services/GraphNodeModelService.d.mts +54 -0
- package/lib/types/engine/services/GraphWorkflowService.d.cts +21 -0
- package/lib/types/engine/services/GraphWorkflowService.d.mts +21 -0
- package/lib/types/mastra/MastraDefaultStepHandlers.d.cts +74 -0
- package/lib/types/mastra/MastraDefaultStepHandlers.d.mts +74 -0
- package/lib/types/mastra/MastraGraphExecutionBackend.d.cts +29 -0
- package/lib/types/mastra/MastraGraphExecutionBackend.d.mts +29 -0
- package/lib/types/mastra/MastraWorkflowCompiler.d.cts +3 -3
- package/lib/types/mastra/MastraWorkflowCompiler.d.mts +3 -3
- package/lib/types/mastra/index.d.cts +1 -0
- package/lib/types/mastra/index.d.mts +1 -0
- package/lib/types/mastra/types.d.cts +12 -0
- package/lib/types/mastra/types.d.mts +12 -0
- package/lib/types/nest/graph/GraphBackendHost.d.cts +52 -0
- package/lib/types/nest/graph/GraphBackendHost.d.mts +52 -0
- package/lib/types/nest/graph/GraphExecutionModule.d.cts +11 -0
- package/lib/types/nest/graph/GraphExecutionModule.d.mts +11 -0
- package/lib/types/ram/GraphNodeRepository.d.cts +13 -0
- package/lib/types/ram/GraphNodeRepository.d.mts +13 -0
- package/lib/types/ram/index.d.cts +1 -0
- package/lib/types/ram/index.d.mts +1 -0
- package/lib/types/shared/graph/GraphNodeConverters.d.cts +15 -0
- package/lib/types/shared/graph/GraphNodeConverters.d.mts +15 -0
- package/lib/types/shared/graph/GraphNodeModel.d.cts +24 -0
- package/lib/types/shared/graph/GraphNodeModel.d.mts +24 -0
- package/lib/types/shared/graph/index.d.cts +2 -0
- package/lib/types/shared/graph/index.d.mts +2 -0
- package/package.json +9 -3
package/dist/as-graph.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{logParameterRegistry as e,Logging as t,LoggedEnvironment as o}from"@decaf-ts/logging";import{RenderingEngine as n,uimodel as r,uielement as i,uilistprop as a,uilistmodel as s,hidden as d}from"@decaf-ts/ui-decorators";import{Metadata as l,Decoration as c,apply as u,metadata as p,propMetadata as h,description as f,prop as g,DefaultFlavour as m}from"@decaf-ts/decoration";import{ValidationKeys as y,Model as w,required as b,type as v,date as I,model as E,option as N,min as O,max as k}from"@decaf-ts/decorator-validation";import{ValidationError as A,InternalError as x,NotFoundError as _}from"@decaf-ts/db-decorators";import{__decorate as S,__metadata as D}from"tslib";import{pk as P,column as R,index as $,table as C,BaseModel as T,ForbiddenError as L,Context as M,repository as j,Repository as G,AuthorizationError as U,service as F,Service as B,ClientBasedService as W,Adapter as q,ModelService as H,OrderDirection as K}from"@decaf-ts/core";import V from"isolated-vm";import*as z from"acorn";import*as J from"acorn-walk";import*as X from"typescript";import{createHash as Y}from"node:crypto";var Q,Z;y.REQUIRED,y.MIN,y.MIN_LENGTH,y.MAX,y.MAX_LENGTH,y.PATTERN,y.URL,y.STEP,y.DATE,y.EMAIL,y.PASSWORD,y.EQUALS,y.DIFF,y.LESS_THAN,y.LESS_THAN_OR_EQUAL,y.GREATER_THAN,y.GREATER_THAN_OR_EQUAL,(e=>{e.GRAPH="graph",e.NODE="graph.node",e.EDGE="graph.edge",e.PORT="graph.port",e.STATE="graph.state"})(Q||(Q={})),(e=>{e.INPUT="input",e.OUTPUT="output",e.CONNECTION="connection"})(Z||(Z={}));const ee={};function te(e,t={}){let o=e.width??96,n=e.height??96;for(const r of e.sizeRules??[]){if("parameterCount"!==r.type)continue;const e=t[r.parameter]??0;e>0&&("width"===r.dimension?o+=e*r.perItem:n+=e*r.perItem)}return{width:o,height:n}}function oe(e,t){ee[e]=t}function ne(e,t,o){const n=t?ee[t]:void 0;return n?.color?n.color:e||"#64748b"}function re(e,t,o){const n=t?ee[t]:void 0;return n?.icon?n.icon:e||"ti-pointer"}const ie=["skip","passThroughFirstInput","emitDefaults"];function ae(e){return ie.includes(e)}var se,de,le,ce;(e=>{e.PENDING="pending",e.PLANNING="planning",e.RUNNING="running",e.SUCCEEDED="succeeded",e.FAILED="failed",e.SKIPPED="skipped",e.CANCELLED="cancelled",e.CACHED="cached"})(se||(se={})),(e=>{e.IDLE="idle",e.RUNNING="running",e.BLOCKED="blocked",e.SUCCEEDED="succeeded",e.FAILED="failed",e.SKIPPED="skipped"})(de||(de={})),(e=>{e.NODE_ID="nodeId",e.WORKFLOW_ID="workflowId",e.RUN_ID="runId",e.USER="user",e.ROLES="roles",e.NAMESPACES="namespaces",e.ORGANIZATION="organization",e.IP="ip"})(le||(le={})),(e=>{e.WORKFLOW_STARTED="workflow.started",e.WORKFLOW_PLANNED="workflow.planned",e.WORKFLOW_COMPLETED="workflow.completed",e.WORKFLOW_FAILED="workflow.failed",e.WORKFLOW_CANCELLED="workflow.cancelled",e.WORKFLOW_SUSPENDED="workflow.suspended",e.WORKFLOW_RESUMED="workflow.resumed",e.NODE_QUEUED="node.queued",e.NODE_STARTED="node.started",e.NODE_OUTPUT="node.output",e.NODE_COMPLETED="node.completed",e.NODE_FAILED="node.failed",e.NODE_SKIPPED="node.skipped",e.NODE_CACHE_HIT="node.cacheHit",e.NODE_PINNED="node.pinned",e.NODE_UNPINNED="node.unpinned",e.NODE_STATE_CHANGED="node.stateChanged",e.EDGE_VALUE_ROUTED="edge.valueRouted",e.EDGE_STATE_CHANGED="edge.stateChanged",e.GRAPH_RUN_LOG="graph.run.log",e.LOOP_STARTED="loop.started",e.LOOP_ITERATION_STARTED="loop.iteration.started",e.LOOP_ITERATION_COMPLETED="loop.iteration.completed",e.LOOP_CONDITION_EVALUATED="loop.condition.evaluated",e.LOOP_COMPLETED="loop.completed",e.LOOP_LIMIT_REACHED="loop.limitReached",e.VALIDATION_STARTED="validation.started",e.VALIDATION_FAILED="validation.failed",e.VALIDATION_COMPLETED="validation.completed",e.STORE_READ="store.read",e.STORE_WRITE="store.write",e.STORE_DELETE="store.delete"})(ce||(ce={}));const ue={maxRequestBytes:4e6,maxConcurrentRuns:32,maxEventsPerRun:1e4,maxEventPayloadBytes:256e3,executionTimeoutMs:6e5,eventReplayWindowMs:3e5},pe=[ce.WORKFLOW_COMPLETED,ce.WORKFLOW_FAILED,ce.WORKFLOW_CANCELLED];function he(e){return pe.includes(e)}function fe(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function ge(e){const t=l.constr(e);if("function"==typeof t)return t;const o=e.constructor;return"function"==typeof o?o:e}function me(e){if(null!=e)return"string"==typeof e?e:e+""}function ye(e,t,o){return me(e?.props?.label??e?.props?.name)??me(t?.name)??o??""}function we(e,t,o){const n=Ie(e,t);if(n?.model&&"function"==typeof n.model&&w.isModel(n.model))return n.model;const r=l.type(e,t);if("function"==typeof r&&w.isModel(r))return r;const i=l.getPropDesignTypes?.(e,t)?.designTypes||[];for(const e of i)if("function"==typeof e&&w.isModel(e))return e;const a=o?.[y.TYPE]?.customTypes||[];for(const e of a)if("function"==typeof e&&w.isModel(e))return e}function be(e,t){const o=[t,e.path??e.property].filter(Boolean).join(".");return{...e,path:o,children:e.children?.map(e=>be(e,o))}}function ve(e){const t=ge(e);return l.get(t,Q.NODE)}function Ie(e,t){const o=ge(e);return l.get(o,l.key(Q.PORT,t+""))}function Ee(e,t,o,n=new Set){const r=Ie(e,t);if(!r?.schema)return;const i=we(e,t,l.validationFor(e,t));if(!i)return;if(n.has(i))return[];const a=new Set(n);return a.add(e),a.add(i),ke(i,a).filter(e=>e.direction===o)}function Ne(e,t,o=new Set){const n=Ie(e,t);if(!n)return;const r=l.validationFor(e,t),i=we(e,t,r);if(n.schema&&i)return;const a=w.uiElementOf(e,t)||void 0,s=w.uiDecorationOf(e,t,"uiprop"),d=l.type(e,t),c=me(n.type??r?.[y.TYPE]?.customTypes?.[0]?.name??a?.props?.type??s?.type??d?.name),u=(n.expand||i&&!o.has(i))&&i?(()=>{const n=new Set(o);return n.add(e),n.add(i),ke(i,n).map(e=>be(e,t))})():void 0;return{property:t,path:t,direction:n.direction,name:t,label:ye(a,s,t),type:c?.toLowerCase(),required:!!r?.[y.REQUIRED],hidden:!!w.uiIsHidden(e,t),designType:d?.name,element:a,prop:s,validation:r,graph:n,connectionRules:n.connectionRules,composite:!!u?.length,children:u,model:i?.name}}function Oe(e){return ke(ge(e))}function ke(e,t=new Set){const o=l.properties(e)||[],n=[];for(const r of o){const o=r+"",i=Ie(e,o);if(i?.schema){const r=Ee(e,o,i.direction,t);if(r){n.push(...r);continue}}const a=Ne(e,o,t);a&&n.push(a)}return n}function Ae(e){return e.flatMap(e=>e.children&&e.children.length?Ae(e.children):[e])}function xe(e){const t=ge(e),o=w.uiModelOf(t),n=ve(t)||{},r=o?.tag||t.name,i=Oe(t),a=((e,t)=>{const o=t.portGroups||[],n=new Map(o.map(e=>[e.property,e])),r=[],i=l.properties(e)||[];for(const t of i){const o=t+"",i=Ie(e,o);if(!i?.schema)continue;if(!we(e,o,l.validationFor(e,o)))continue;const a=n.get(o);r.push(a?{...a,toggle:a.toggle??"all"}:{property:o,toggle:"all"})}for(const e of o)r.some(t=>t.property===e.property)||r.push(e);return r.length?r:void 0})(t,n),s=n.namespaces?.length?n.namespaces:(e=>{if(null==e)return[];let t,o=e;try{o=l.constr(e)}catch{o=e}try{t=l.get(o,"auth-namespace")}catch{t=void 0}return fe(t)??[]})(t),d=s.length?s:void 0;return{name:t.name,tag:r,kind:n.kind||r,category:n.category,color:n.color,effectiveColor:ne(n.color,n.category),group:n.group,height:n.height,icon:n.icon,effectiveIcon:re(n.icon,n.category),labels:n.labels||[],maxChildren:n.maxChildren,minWidth:n.minWidth,width:n.width,shape:n.shape,cornerRadius:n.cornerRadius,sizeRules:n.sizeRules,props:o?.props,ui:o,graph:n,ports:i,portGroups:a,namespaces:d}}const _e=new Set,Se=new Set;function De(e,t,o){return c.for(Q.NODE).define({decorator:(e,t,o)=>{const n={kind:t?.kind||e,...t};return t=>{const i=u(r(e,o),p(Q.NODE,n))(t);var a;return a=t,_e.add(a),i}},args:[e,t,o]}).apply()}function Pe(e,t){return c.for(Q.PORT).define({decorator:(e,t)=>(o,n)=>{const r={direction:e,...t};return u(h(l.key(Q.PORT,n),r))(o,n)},args:[e,t]}).apply()}function Re(e){return Pe(Z.INPUT,{...e,schema:!0})}function $e(e){return Pe(Z.OUTPUT,{...e,schema:!0})}function Ce(e){return Pe(Z.CONNECTION,e)}n.prototype.renderAsNode=(e,t,...o)=>xe(e),l.nodes=(()=>[..._e]).bind(l),l.workflows=(()=>[...Se]).bind(l);const Te=["__proto__","prototype","constructor"];function Le(e){return Te.includes(e)}function Me(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function je(e){return null===e||"string"==typeof e||"number"==typeof e&&Number.isFinite(e)||"boolean"==typeof e}function Ge(e){return!!je(e)||(Array.isArray(e)?e.every(e=>Ge(e)):!!Me(e)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&!Le(t)&&Ge(e[t])))}function Ue(e){if(void 0===e)return!1;if("number"==typeof e)return Number.isFinite(e);if("function"==typeof e)return!1;if(Ge(e))return!0;if(Array.isArray(e))return e.every(e=>Ue(e));if(Me(e)){const t=Reflect.ownKeys(e);for(const o of t){if("string"!=typeof o)return!1;if(Le(o))return!1;if(!Ue(e[o]))return!1}return!0}return!1}function Fe(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>Fe(e));const t={};for(const[o,n]of Object.entries(e))t[o]=Fe(n);return t}const Be={string:"string",char:"string",text:"string",textarea:"string",radio:"string",select:"string",number:"number",integer:"number",float:"number",double:"number",decimal:"number",boolean:"boolean",bool:"boolean",checkbox:"boolean",array:"array",list:"array",set:"array",object:"object",model:"model",any:"any",unknown:"any",enum:"enum"},We={date:"date",datetime:"date-time","date-time":"date-time",duration:"duration"};function qe(e){return e?Be[e.toLowerCase()]??"any":"any"}function He(e,t){const o=e[t];if(o&&"object"==typeof o)return o.value}function Ke(e,t){const o=He(e,t);return"number"==typeof o&&Number.isFinite(o)?o:void 0}function Ve(e,t,o){const n=e??{},r=(e=>{const t=He(e,y.ENUM);if(Array.isArray(t)&&t.every(je))return t})(n);if(r)return{type:"enum",values:r};const i=(e=>{const t=e[y.TYPE],o=t?.customTypes?.[0],n="function"==typeof o?o.name:o?.name;if(n)return n})(n)??o;return i?{type:"model",name:i}:((e,t)=>{switch(qe(e)){case"string":{const t=(e=>{if(e)return We[e.toLowerCase()]})(e);return void 0!==t?{type:"string",format:t}:{type:"string"}}case"number":{const o={type:"number"};e&&"integer"===e.toLowerCase()&&(o.integer=!0);const n=Ke(t,y.MIN),r=Ke(t,y.MAX);return void 0!==n&&(o.min=n),void 0!==r&&(o.max=r),o}case"boolean":return{type:"boolean"};case"array":return((e,t)=>{const o={type:"array",items:ze(e,t)},n=Ke(e,y.MIN),r=Ke(e,y.MAX);return void 0!==n&&(o.minItems=n),void 0!==r&&(o.maxItems=r),o})(t,e);case"object":return{type:"object",properties:{}};case"enum":return{type:"enum",values:[]};case"model":return{type:"model",name:e??"any"};default:return{type:"any"}}})(t,n)}function ze(e,t){if((e=>{const t=e[y.LIST];return!!t?.clazz?.length})(e))return{type:"model",name:Je(e)};const o=He(e,y.TYPE);if("string"==typeof o){const e=qe(o);return"model"===e?{type:"model",name:o}:{type:e}}if(t&&"array"!==t){const e=qe(t);return"model"===e?{type:"model",name:t}:{type:e}}return{type:"any"}}function Je(e){const t=e[y.LIST],o=t?.clazz?.[0];if("function"!=typeof o)return"any";if(o.name)return o.name;try{const e=o();if("function"==typeof e&&e.name)return e.name}catch{return"any"}return"any"}function Xe(e){return"workflow"===e.scope}function Ye(e){return"node"===e.scope}function Qe(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"workflow"===t.scope?"string"==typeof t.port&&2===Reflect.ownKeys(t).length:"node"===t.scope&&"string"==typeof t.nodeId&&"string"==typeof t.port&&3===Reflect.ownKeys(t).length}function Ze(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e.mode;if("edge"===t)return 1===Reflect.ownKeys(e).length;if("literal"===t){const t=e.value;return 2===Object.keys(e).length&&Ge(t)}return"expression"===t&&2===Object.keys(e).length&&"string"==typeof e.expression}const et=["any","string","number","boolean","array","object","enum","model"];function tt(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&(e=>et.includes(e))(e.type)}function ot(e,t={seen:[]}){if(t.seen.includes(e))throw new A(`Document '${(e=>{const t=e?.id;return"string"==typeof t?t:"<unnamed document>"})(e)}' contains a loop body that references itself (cyclic document)`);if("string"!=typeof e.id||!e.id)throw new A("Document 'id' is required and must be a non-empty string");if("string"!=typeof e.name||!e.name)throw new A("Document 'name' is required and must be a non-empty string");const o=new Set;for(const t of[...e.inputs,...e.outputs]){if("string"!=typeof t.id||!t.id)throw new A("Workflow port 'id' is required and must be a non-empty string");if(o.has(t.id))throw new A(`Workflow port '${t.id}' is declared more than once; workflow port ids must be unique`);if(void 0!==t.schema&&!tt(t.schema))throw new A(`Workflow port '${t.id}' schema must be a valid GraphValueSchema`);o.add(t.id)}const n={seen:[...t.seen,e]},r=new Set;for(const t of e.nodes)nt(t,r);for(const t of e.nodes)t.loop&&rt(t,t.loop,n),t.errorBoundary&&it(t,t.errorBoundary,n);const i=new Set;for(const t of e.edges)st(t,i);for(const t of e.edges)dt(t.source,0,o,r,`Edge '${t.id}' source`),dt(t.target,0,o,r,`Edge '${t.id}' target`);if(void 0!==e.settings&&!Ue(e.settings))throw new A("Document settings must be JSON-safe (a map of JSON-safe values)");if(void 0!==e.metadata&&!Ue(e.metadata))throw new A("Document metadata must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed");if(void 0!==e.ui&&!Ue(e.ui))throw new A("Document ui must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed")}function nt(e,t){if("string"!=typeof e.id||!e.id)throw new A("Node 'id' is required and must be a non-empty string");if(t.has(e.id))throw new A(`Node id '${e.id}' is declared more than once; node ids must be unique`);if("string"!=typeof e.kind||!e.kind)throw new A(`Node '${e.id}' must declare a non-empty string 'kind'`);if(void 0===e.parameters||null===e.parameters)throw new A(`Node '${e.id}' parameters must be present (an empty object when there are none)`);if(t.add(e.id),e.inputBindings)for(const[t,o]of Object.entries(e.inputBindings)){if(Le(t))throw new A(`Node '${e.id}' input binding key '${t}' is not allowed (unsafe prototype-pollutant key)`);if(!Ze(o))throw new A(`Node '${e.id}' input binding for '${t}' must be a valid GraphInputBinding (edge, literal, or expression)`);if("literal"===o.mode&&!Ue(o.value))throw new A(`Node '${e.id}' literal binding for '${t}' must contain JSON-safe values`);if("expression"===o.mode&&!o.expression)throw new A(`Node '${e.id}' expression binding for '${t}' must contain a non-empty expression`)}if(e.outputBindings)for(const[t,o]of Object.entries(e.outputBindings)){if(Le(t))throw new A(`Node '${e.id}' output binding key '${t}' is not allowed (unsafe prototype-pollutant key)`);if(!o||"object"!=typeof o||Array.isArray(o))throw new A(`Node '${e.id}' output binding for '${t}' must be an object with enabled and alias settings`)}if(!Ue(e.parameters))throw new A(`Node '${e.id}' parameters must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`);if(void 0!==e.state){if(!e.state||"object"!=typeof e.state||Array.isArray(e.state))throw new A(`Node '${e.id}' state must be an object when present`);if(!Ue(e.state))throw new A(`Node '${e.id}' state must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`)}}function rt(e,t,o){if(!t.body||"object"!=typeof t.body)throw new A(`Node '${e.id}' loop configuration requires a body document`);if(ot(t.body,o),!(void 0===t.maxIterations||Number.isFinite(t.maxIterations)&&t.maxIterations>0))throw new A(`Node '${e.id}' loop maxIterations must be a positive number`);if(void 0!==t.timeoutMs&&("number"!=typeof t.timeoutMs||0>=t.timeoutMs))throw new A(`Node '${e.id}' loop timeoutMs must be a positive number in milliseconds`);if(void 0!==t.concurrency&&("number"!=typeof t.concurrency||0>=t.concurrency))throw new A(`Node '${e.id}' loop concurrency must be a positive number`);for(const o of[t.inputMappings,t.outputMappings])if(o)for(const[t,n]of Object.entries(o)){if(Le(t))throw new A(`Node '${e.id}' loop mapping key '${t}' is not allowed (unsafe prototype-pollutant key)`);at(n,e.id,t)}}function it(e,t,o){if(!t.try||"object"!=typeof t.try)throw new A(`Node '${e.id}' error-boundary configuration requires a try body document`);ot(t.try,o);for(const[n,r]of[["catch",t.catch],["finally",t.finally]])if(void 0!==r){if(!r||"object"!=typeof r)throw new A(`Node '${e.id}' error-boundary ${n} body must be a document`);ot(r,o)}}function at(e,t,o){if(!e||"object"!=typeof e)throw new A(`Node '${t}' loop mapping '${o}' must reference a workflow port, node port, literal, or expression`);switch(e.source){case"workflow":if("string"!=typeof e.port||!e.port)throw new A(`Node '${t}' loop mapping '${o}' referencing a workflow must reference a port identifier`);break;case"node":if("string"!=typeof e.nodeId||!e.nodeId||"string"!=typeof e.port||!e.port)throw new A(`Node '${t}' loop mapping '${o}' referencing a node must reference a node id and a port`);break;case"literal":if(!Ue(e.value))throw new A(`Node '${t}' loop mapping '${o}' literal references must be JSON-safe values`);break;case"expression":if("string"!=typeof e.expression||!e.expression)throw new A(`Node '${t}' loop mapping '${o}' expression references must be non-empty expressions`);break;default:throw new A(`Node '${t}' loop mapping '${o}' must use a workflow, node, literal, or expression reference source`)}}function st(e,t){if("string"!=typeof e.id||!e.id)throw new A("Edge 'id' is required and must be a non-empty string");if(t.has(e.id))throw new A(`Edge id '${e.id}' is declared more than once; edge ids must be unique`);if(!Qe(e.source))throw new A(`Edge '${e.id}' source endpoint is not a valid GraphEndpoint`);if(!Qe(e.target))throw new A(`Edge '${e.id}' target endpoint is not a valid GraphEndpoint`);if("data"!==e.type&&"connection"!==e.type)throw new A(`Edge '${e.id}' type '${e.type+""}' is not a valid edge type (data or connection are allowed)`);if(t.add(e.id),!Ue(e))throw new A(`Edge '${e.id}' contains values that are not JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`)}function dt(e,t,o,n,r){if(Xe(e)){if(!o.has(e.port))throw new A(`${r} references workflow port '${e.port}' which is not declared on the document`)}else if(Ye(e)){if(!n.has(e.nodeId))throw new A(`${r} references node '${e.nodeId}' which is not part of the document`);if("string"!=typeof e.port||!e.port)throw new A(r+" node endpoints must reference a non-empty port identifier")}}const lt=["expression","template"],ct=["javascript","typescript","json","text"];function ut(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return!(!(e=>lt.includes(e))(t.mode)||"string"!=typeof t.expression||!t.expression||void 0!==t.language&&!(e=>ct.includes(e))(t.language)||void 0!==t.metadata&&!Ge(t.metadata))}function pt(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.name&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.nodes)&&Array.isArray(t.edges)}function ht(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.type&&(void 0===t.required||"boolean"==typeof t.required)&&(void 0===t.displayName||"string"==typeof t.displayName)&&(void 0===t.allowedOperations||Array.isArray(t.allowedOperations)&&t.allowedOperations.every(e=>"string"==typeof e))}const ft=["trigger","loop","branching","stateful","retryable","cancellable","parallel","resource"];function gt(e){return ft.includes(e)}function mt(e){if(!(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.kind&&"object"==typeof t.display&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.parameters)})(e))throw new A("Graph node manifest does not conform to the required shape");if(!Ue(e))throw new A("Graph node manifest contains values that are not JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys or unsafe prototype keys are not allowed on manifests")}const yt=["loadOptions","listSearch","resourceLocator","resourceMapping","validateParameter","action"];function wt(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.name&&(e=>yt.includes(e))(t.type)&&(void 0===t.parameter||"string"==typeof t.parameter)&&(void 0===t.dependencies||Array.isArray(t.dependencies)&&t.dependencies.every(e=>"string"==typeof e))}function bt(e){const t=e.element?.props?.value,o=t??e.prop?.value??e.validation?.defaultValue;if(void 0!==o&&"function"!=typeof o&&Ue(o))try{return JSON.parse(JSON.stringify(o))}catch{return}}function vt(e){if(e.type&&e.type in We)return{type:"string",format:We[e.type]};const t=(e=>{for(const t of[e.graph?.type,e.element?.props?.type,e.prop?.type])if("string"==typeof t&&"any"!==qe(t))return t})(e);return t?Ve((e=>{if(!e)return;const t=Object.entries(e).filter(([e])=>e!==y.TYPE);return Object.fromEntries(t)})(e.validation),t):Ve(e.validation,e.type,e.model)}function It(e){const t={};for(const[o,n]of Object.entries(e.graph?.metadata??{}))Ue(n)&&(t[o]=JSON.parse(JSON.stringify(n)));return Object.keys(t).length?t:void 0}function Et(e){switch(e){case"output":return"output";case"connection":return"connection";default:return"input"}}function Nt(e){const t=e.graph?.handle;return"connection"!==e.direction&&"string"==typeof t&&t?t:e.path??e.property}function Ot(e,t){const o={id:Nt(e),label:e.label,direction:Et(e.direction),schema:vt(e)};e.required&&(o.required=!0),e.hidden&&(o.hidden=!0);const n=e.graph?.category;"string"==typeof n&&(o.category=n),!0===e.graph?.userControlled&&(o.configurable=!0);const r=e.graph?.handle;"string"==typeof r&&(o.handle=r);const i=Ct(e.graph?.connectionRules)??t;i&&(o.connectionPolicy=i);const a=(e=>{const t=e.element;if(!t||!Ue(t))return;const o=t.tag;if("string"!=typeof o)return;const n=t.props;return{tag:o,serialize:!0===t.serialize,props:n&&"object"==typeof n&&!Array.isArray(n)?Fe(n):{}}})(e);a&&(o.element=a);const s=It(e);return s&&(o.metadata=s),o}function kt(e){const t={type:"string",id:Nt(e),label:e.label,required:e.required};if(e.hidden)return((e,t)=>{const o={...t,type:"hidden"},n=bt(e);return void 0!==n&&(o.defaultValue=n),At(o)})(e,t);const o=bt(e);void 0!==o&&(t.defaultValue=o);const n=(e=>{const t=e.element?.props?.placeholder??e.prop?.placeholder;return"string"==typeof t?t:void 0})(e);n&&(t.placeholder=n);const r=It(e);if(r&&(t.metadata=r),(e=>{const t=St(e);return"code"===t||"code-editor"===t})(e))return At({...t,type:"code",language:Rt(e)});const i=vt(e);switch(i.type){case"number":{const o={...t,type:"number",integer:i.integer,min:i.min,max:i.max},n=_t(e.validation?.step);return void 0!==n&&(o.step=n),At(o)}case"boolean":return At({...t,type:"boolean"});case"enum":return At({...t,type:"options",options:i.values.map(e=>({value:e,label:e+""}))});case"array":{const e={...t,type:"collection"};return void 0!==i.maxItems&&(e.maxItems=i.maxItems),At(e)}case"object":case"model":return At({...t,type:"object"});default:return At({...t,type:"string",multiline:!!Dt(e)||void 0,pattern:xt(e.validation?.pattern),minLength:_t(e.validation?.minlength),maxLength:_t(e.validation?.maxlength)})}}function At(e){const t=e;for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return e}function xt(e){const t=e?.value;return"string"==typeof t?t:void 0}function _t(e){const t=e?.value;return"number"==typeof t&&Number.isFinite(t)?t:void 0}function St(e){const t=e.element?.tag;return"string"==typeof t&&t?t:void 0}function Dt(e){return"textarea"===St(e)||"textarea"===(e=>{const t=e.element?.props?.type;return"string"==typeof t?t:void 0})(e)}const Pt=["javascript","typescript","json","text"];function Rt(e){const t=e.element?.props?.language;return"string"==typeof t&&Pt.includes(t)?t:"javascript"}function $t(e,t){const o={name:t.name??e.name},n=e.graph?.metadata?.description??void 0;"string"==typeof n&&n&&(o.description=n);const r=t.category??e.category;"string"==typeof r&&r&&(o.category=r),"string"==typeof e.group&&e.group&&(o.group=e.group),Array.isArray(e.labels)&&(o.labels=e.labels.slice());const i=((e,t)=>{if(t.icon)return t.icon;const o=e.effectiveIcon??e.icon;return"string"==typeof o?{type:"catalogue",name:o}:{type:"catalogue",name:"ph:circuitry"}})(e,t);return i&&(o.icon=i),"string"==typeof e.color&&e.color&&(o.color=e.color),"number"==typeof e.width&&Number.isFinite(e.width)&&(o.width=e.width),"number"==typeof e.minWidth&&Number.isFinite(e.minWidth)&&(o.minWidth=e.minWidth),"number"==typeof e.height&&Number.isFinite(e.height)&&(o.height=e.height),"string"==typeof e.shape&&(o.shape=e.shape),"number"==typeof e.cornerRadius&&Number.isFinite(e.cornerRadius)&&(o.cornerRadius=e.cornerRadius),Array.isArray(e.sizeRules)&&(o.sizeRules=e.sizeRules),o}function Ct(e){if(!e)return;const t=e,o={};"boolean"==typeof t.allowSelf&&(o.allowSelf=t.allowSelf),"boolean"==typeof t.allowMultiple&&(o.allowMultiple=t.allowMultiple);const n=t.allowedKinds;Array.isArray(n)&&n.every(e=>"string"==typeof e)&&(o.allowedNodeKinds=n);const r=t.blockedKinds;Array.isArray(r)&&r.every(e=>"string"==typeof e)&&(o.blockedNodeKinds=r);const i=t.maxConnections;return"number"==typeof i&&Number.isFinite(i)&&(o.maxConnections=i),Object.keys(o).length?o:void 0}function Tt(e,t={}){const o="function"==typeof e?e:e.constructor;if(!ve(o))throw new A(`Node '${o?.name??e+""}' is not decorated with @node and cannot produce a manifest`);const n=xe(o),r=Ae(Oe(o)),i=[],a=[],s=[],d=[],l=Ct(n.graph?.connectionRules);for(const e of r)("connection"===e.direction?s:"output"===e.direction?a:i).push(Ot(e,l)),"input"===e.direction&&d.push(kt(e));const c={kind:t.kind??n.kind??n.name,display:$t(n,t),inputs:i,outputs:a,parameters:d};return s.length&&(c.connections=s),n.namespaces?.length&&(c.namespaces=n.namespaces.slice()),mt(c),c}var Lt,Mt;(e=>{e.READABILITY="readability",e.COMPACTNESS="compactness",e.BALANCED="balanced"})(Lt||(Lt={})),(e=>{e.TIGHT="tight",e.NORMAL="normal",e.COMFORTABLE="comfortable"})(Mt||(Mt={})),Mt.TIGHT,Mt.NORMAL,Mt.COMFORTABLE,Lt.READABILITY,Mt.COMFORTABLE,Lt.COMPACTNESS,Mt.TIGHT,Lt.BALANCED,Mt.NORMAL;let jt=class extends T{constructor(e){super(e)}};S([P({type:String,generated:!1}),f("Unique graph run id"),i("ngx-decaf-crud-field",{label:"graph.run.id.label",readonly:!0}),D("design:type",String)],jt.prototype,"runId",void 0),S([R(),b(),$(),f("Workflow document id the run executes"),a("workflowId"),i("ngx-decaf-crud-field",{label:"graph.run.workflowId.label"}),D("design:type",String)],jt.prototype,"workflowId",void 0),S([R(),f("Owning user; absent for anonymous callers"),i("ngx-decaf-crud-field",{label:"graph.run.owner.label"}),D("design:type",String)],jt.prototype,"owner",void 0),S([R(),b(),v(String),$(),f("Current run lifecycle status"),a("status"),i("ngx-decaf-crud-field",{label:"graph.run.status.label",readonly:!0}),D("design:type",String)],jt.prototype,"status",void 0),S([R(),f("Fingerprint of the executed document"),i("ngx-decaf-crud-field",{label:"graph.run.fingerprint.label",readonly:!0}),D("design:type",String)],jt.prototype,"documentFingerprint",void 0),S([R(),g(),f("Workflow input values keyed by input port id"),D("design:type",Object)],jt.prototype,"inputs",void 0),S([R(),g(),f("Execution result, present on successful completion"),D("design:type",Object)],jt.prototype,"result",void 0),S([R(),g(),f("Structured error payload, present on failure"),D("design:type",Object)],jt.prototype,"error",void 0),S([I(),R(),f("Run creation timestamp"),D("design:type",Date)],jt.prototype,"createdAt",void 0),S([I(),R(),f("Execution start timestamp, once it has started"),D("design:type",Date)],jt.prototype,"startedAt",void 0),S([I(),R(),f("Terminal-state timestamp, once the run has finished"),D("design:type",Date)],jt.prototype,"finishedAt",void 0),jt=S([s("ngx-decaf-list-item",{icon:"ti-player-play"}),r("ngx-decaf-crud-form"),f("Persistable graph run lifecycle record"),C("graph_run"),E(),D("design:paramtypes",[Object])],jt);let Gt=class extends T{constructor(e){super(e)}};S([P({type:String,generated:!1}),D("design:type",String)],Gt.prototype,"workflowId",void 0),S([R(),D("design:type",String)],Gt.prototype,"name",void 0),S([R(),D("design:type",Object)],Gt.prototype,"document",void 0),S([R(),D("design:type",String)],Gt.prototype,"owner",void 0),S([R(),D("design:type",Object)],Gt.prototype,"snapshot",void 0),Gt=S([C("graph_workflow"),E(),D("design:paramtypes",[Object])],Gt),oe("Trigger",{color:"#3b82f6",icon:"ti-bolt"}),oe("Flow Control",{color:"#f59e0b",icon:"ti-arrows-split-2"}),oe("Utility",{color:"#0d9488",icon:"ti-tool"}),oe("Loop",{color:"#eab308",icon:"ti-repeat"}),oe("Workflow",{color:"#f97316",icon:"ti-sitemap"}),oe("Pipeline",{color:"#0ea5e9",icon:"ti-git-merge"}),oe("Node",{color:"#8b5cf6",icon:"ti-point-filled"}),oe("Agent",{color:"#7c3aed",icon:"ti-robot"}),oe("model",{color:"#3b82f6",icon:"ti-cpu"}),oe("memory",{color:"#10b981",icon:"ti-database"}),oe("workspace",{color:"#f59e0b",icon:"ti-folder"});const Ut=new Set;function Ft(e,t){return e.config[t]}function Bt(e){return Array.isArray(e)?e.map(e=>e+"").join(", "):e+""}(()=>{const t=[{key:le.NODE_ID,shouldInclude:e=>null!=Ft(e,le.NODE_ID),render:e=>Ft(e,le.NODE_ID)+""},{key:le.WORKFLOW_ID,shouldInclude:e=>null!=Ft(e,le.WORKFLOW_ID),render:e=>Ft(e,le.WORKFLOW_ID)+""},{key:le.RUN_ID,shouldInclude:e=>null!=Ft(e,le.RUN_ID),render:e=>Ft(e,le.RUN_ID)+""},{key:le.USER,shouldInclude:e=>null!=Ft(e,le.USER),render:e=>Ft(e,le.USER)+""},{key:le.ROLES,shouldInclude(e){const t=Ft(e,le.ROLES);return Array.isArray(t)&&t.length>0},render:e=>Bt(Ft(e,le.ROLES))},{key:le.NAMESPACES,shouldInclude(e){const t=Ft(e,le.NAMESPACES);return Array.isArray(t)&&t.length>0},render:e=>Bt(Ft(e,le.NAMESPACES))},{key:le.ORGANIZATION,shouldInclude:e=>null!=Ft(e,le.ORGANIZATION),render:e=>Ft(e,le.ORGANIZATION)+""},{key:le.IP,shouldInclude:e=>null!=Ft(e,le.IP),render:e=>Ft(e,le.IP)+""}];for(const o of t)Ut.has(o.key)||(e.register(o),Ut.add(o.key))})();const Wt="$workflow",qt="local",Ht=4,Kt=100,Vt=1e3,zt=1e3,Jt=1e4,Xt=3e4,Yt="graph.pinnable";var Qt,Zt;(e=>{e.MANUAL="manual",e.AUTOMATIC="automatic",e.DISABLED="disabled"})(Qt||(Qt={})),(e=>{e.TRUTHY="truthy",e.FALSY="falsy",e.EQUALS="equals",e.NOT_EQUALS="notEquals",e.GREATER_THAN="greaterThan",e.GREATER_THAN_OR_EQUAL="greaterThanOrEqual",e.LESS_THAN="lessThan",e.LESS_THAN_OR_EQUAL="lessThanOrEqual",e.EXISTS="exists",e.CUSTOM="custom"})(Zt||(Zt={}));const eo={FOREACH:"core.loop.foreach",WHILE:"core.loop.while",UNTIL:"core.loop.until"};class to extends x{constructor(e,t="GRAPH_EXECUTION_ERROR",o){super(e,to.name,500),this.graphCode=t,this.details=o,this.name=this.constructor.name}}class oo extends to{constructor(e){super("Graph workflow contains an unsupported cycle","GRAPH_CYCLE_ERROR",e)}}class no extends to{constructor(e,t){super(e,"GRAPH_INPUT_ERROR",t)}}class ro extends to{constructor(e,t){super(e,"GRAPH_LOOP_LIMIT_ERROR",t)}}class io extends to{constructor(e,t){super(e,"GRAPH_PINNING_ERROR",t)}}class ao extends to{constructor(e,t){super(e,"GRAPH_PORT_ERROR",t)}}class so extends to{constructor(e,t){super(e,"GRAPH_STORE_ERROR",t)}}class lo extends to{constructor(e,t){super(e,"GRAPH_TOPOLOGY_ERROR",t)}}class co extends to{constructor(e){super("Break signal","GRAPH_BREAK_SIGNAL",{value:e}),this.isBreakSignal=!0,this.name="GraphBreakSignal"}}class uo extends to{constructor(e){super(`Graph run '${e}' was cancelled`,"GRAPH_RUN_CANCELLED",{runId:e}),this.name=uo.name}}class po extends A{constructor(e){super(`Graph workflow document rejected with ${e.length} issue(s): ${e.map(e=>`${e.code} at ${e.path} (${e.message})`).join("; ")}`),this.name=po.name,this.issues=e}}class ho{constructor(){this.observers=new Set}observe(e){return this.observers.add(e),()=>this.unObserve(e)}unObserve(e){this.observers.delete(e)}async updateObservers(e){await Promise.all(Array.from(this.observers).map(async t=>{try{await Promise.resolve(t.refresh(e))}catch{}}))}}class fo{constructor(){this.sequence=0}create(e){return{...e,id:this.createEventId(),sequence:++this.sequence,timestamp:new Date}}createEventId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new to("Cannot generate a graph event id: crypto.randomUUID is unavailable in this runtime","GRAPH_EVENT_ID_ERROR",{runtime:typeof globalThis.crypto});return e.randomUUID()}}function go(e){if("string"!=typeof e)return;const t=e.trim();if(!t)return;const o=t.split(".");if(3!==o.length)return;const n=o[0].trim(),r=o[2].trim(),i=o[1].split(",").map(e=>e.trim()).filter(e=>e.length>0);return n&&r&&0!==i.length?{organization:n,departments:i,role:r}:void 0}function mo(e){return`${e.organization}.${e.departments.join(",")}.${e.role}`}function yo(e){if(!e||"string"!=typeof e.namespace||!e.parts)return!1;const t=go(e.namespace);return!!t&&mo(t)===mo(e.parts)}function wo(e,t){const o="string"==typeof e?e.trim():"";if(o){if(t)for(const e of t)if(e&&e.namespace===o&&yo(e))return e.parts;return go(o)}}function bo(e,t,o={},n){const r=wo(e,n),i=wo(t,n);return!(!r||!i)&&r.organization===i.organization&&r.role===i.role&&("exact"===(o.mode??"inherit")?r.departments.length===i.departments.length&&r.departments.every((e,t)=>e===i.departments[t]):r.departments.length<=i.departments.length&&r.departments.every((e,t)=>e===i.departments[t]))}function vo(e,t,o={},n){return e.filter(e=>!t.some(t=>bo(t,e,o,n)))}function Io(e){return e.filter(e=>void 0===go(e))}function Eo(e,t){const o=new Set;for(const n of e){const e=wo(n,t);e&&o.add(e.role)}return[...o]}function No(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function Oo(e,t){try{const o=e.cache;if(o&&void 0!==o[t]&&null!==o[t])return o[t]}catch{}try{return e.get(t)}catch{return}}function ko(e){if(!e)return{};const t={},o=e.user;"string"==typeof o&&o&&(t.user=o);const n=e.organization;"string"==typeof n&&n&&(t.organization=n);const r=e.ip;"string"==typeof r&&r&&(t.ip=r);const i=No(e.roles);i&&(t.roles=i);const a=No(e.namespaces);return a&&(t.namespaces=a,t.namespaceCache=xo(a)),t}function Ao(e){return e?ko({user:Oo(e,"user"),organization:Oo(e,"organization"),ip:Oo(e,"ip"),roles:Oo(e,"roles"),namespaces:Oo(e,"namespaces")}):{}}function xo(e){const t=[];for(const o of e){const e=go(o);e&&t.push({namespace:o,parts:e})}return t}function _o(...e){const t={};for(const o of e)o&&(void 0!==o.user&&(t.user=o.user),void 0!==o.organization&&(t.organization=o.organization),void 0!==o.ip&&(t.ip=o.ip),void 0!==o.roles&&(t.roles=o.roles),void 0!==o.namespaces&&(t.namespaces=o.namespaces),void 0!==o.namespaces?t.namespaceCache=o.namespaceCache??xo(o.namespaces):void 0!==o.namespaceCache&&(t.namespaceCache=o.namespaceCache));return t}class So{constructor(e={}){this.options=e}get enabled(){return!0===this.options.enabled}validate(e,o,n,r){if(!this.enabled)return;const i=r??this.options.logger??t.for("GraphAuth"),a=e.id||e.name||o.workflowId,s=(e=>{if(!e||"object"!=typeof e)return;const t=e.auth;return t&&"object"==typeof t&&!Array.isArray(t)?(e=>{if(!e)return;const t=fe(e.namespaces),o=fe(e.roles);if(!t&&!o)return;const n={};return t&&(n.namespaces=t),o&&(n.roles=o),n})(t):void 0})(e.metadata);this.assertGranted(`workflow '${a}'`,s?.namespaces??[],n,s?.roles??[],i);for(const e of o.nodes)this.assertGranted(`node '${e.id}'`,e.manifest.namespaces??[],n,[],i)}assertGranted(e,t,o,n,r){const i=o.namespaces??[],a=vo(t,i,this.options.match,o.namespaceCache),s=Eo(i,o.namespaceCache),d=n.filter(e=>!s.includes(e));if(0===a.length&&0===d.length)return;const l=[...new Set([...Io(t),...Io(i)])],c=[];throw a.length&&c.push("namespace(s) "+a.join(", ")),d.length&&c.push("role(s) "+d.join(", ")),r.warn(`Graph access denied for ${e} for user ${o.user??"anonymous"}: missing ${c.join(" and ")}${l.length?`; malformed namespace(s) ${l.join(", ")} failed closed`:""}`),new L(`Access to ${e} requires ${c.join(" and ")}`)}}class Do{constructor(e){this.baseOptions=e,this.inner=t.for("GraphRun").for(this.attributeConfig(e))}attributeConfig(e){return{[le.NODE_ID]:e.nodeId,[le.WORKFLOW_ID]:e.workflowId,[le.RUN_ID]:e.runId,[le.USER]:e.user??null,[le.ROLES]:e.roles,[le.NAMESPACES]:e.namespaces,[le.ORGANIZATION]:e.organization,[le.IP]:e.ip}}emit(e,t,o){const n="string"==typeof t?t:t instanceof Error?t.message:t+"",r={level:e,message:n,timestamp:(new Date).toISOString(),runId:this.baseOptions.runId,workflowId:this.baseOptions.workflowId,nodeId:this.baseOptions.nodeId,user:this.baseOptions.user??null};void 0!==this.baseOptions.roles&&(r.roles=this.baseOptions.roles),void 0!==this.baseOptions.namespaces&&(r.namespaces=this.baseOptions.namespaces),void 0!==this.baseOptions.organization&&(r.organization=this.baseOptions.organization),void 0!==this.baseOptions.ip&&(r.ip=this.baseOptions.ip),void 0!==o&&(r.payload=o),this.baseOptions.forward({type:ce.GRAPH_RUN_LOG,payload:r}).catch(()=>{}),{benchmark:(e,t)=>this.inner.benchmark(e,t),fatal:(e,t)=>this.inner.fatal(e,t),critical:(e,t)=>this.inner.critical(e,t),silly:(e,t)=>this.inner.silly(e,t),trace:(e,t)=>this.inner.trace(e,t),verbose:(e,t)=>this.inner.verbose(e,t),info:(e,t)=>this.inner.info(e,t),warn:(e,t)=>this.inner.warn(e,t),error:(e,t)=>this.inner.error(e,t),debug:(e,t)=>this.inner.debug(e,t)}[e](n,o)}benchmark(e,t){this.emit("benchmark",e,t)}fatal(e,t,o){this.emit("fatal",e,t??o)}critical(e,t,o){this.emit("critical",e,t??o)}silly(e,t,o){this.emit("silly",e,"object"==typeof t?t:o)}trace(e,t){this.emit("trace",e,t)}verbose(e,t,o){this.emit("verbose",e,"object"==typeof t?t:o)}info(e,t){this.emit("info",e,t)}error(e,t,o){this.emit("error",e,t??o)}warn(e,t){this.emit("warn",e,t)}debug(e,t){this.emit("debug",e,t)}action(e,t,o){this.inner.action(e,t,o)}setConfig(){}for(e,t,...o){return this}clear(){return this}get root(){return this.inner.root}}function Po(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}class Ro extends M{constructor(e,t,o,n,r,i,a,s,d={},l,c,u){super(),this.runId=e,this.parentRunId=t,this.workflowId=o,this.document=n,this.node=r,this.manifest=i,this.path=a,this.emitFn=s,this.metadata=d,this.engine=l,this.abortSignal=c,this.limits=u;const p=ko(d);this.accumulate({...p,operation:"execute"});const h="string"==typeof d?.user?d.user:null;this.runLogger=new Do({runId:e,workflowId:o,nodeId:r.id,user:h,roles:Po(d?.roles),namespaces:Po(d?.namespaces),organization:"string"==typeof d?.organization?d.organization:void 0,ip:"string"==typeof d?.ip?d.ip:void 0,forward:async e=>{await this.emit(e)}})}get logger(){return this.runLogger}get auth(){return Ao(this)}async emit(e){await this.emitFn({...e,runId:this.runId,parentRunId:this.parentRunId,workflowId:this.workflowId,nodeId:this.node.id,path:e.path??this.path})}async progress(e){await this.emit({type:ce.NODE_OUTPUT,payload:e})}async log(e,t){await this.emit({type:ce.NODE_OUTPUT,payload:{message:e,payload:t}})}}class $o{constructor(e,t,o,n){this.nodeResults=new Map,this.events=[],this.activeDataEdges=new Set,this.runId=e,this.plan=t,this.valueStore=o,this.eventFactory=n,this.startedAt=new Date}recordNodeResult(e){this.nodeResults.set(e.nodeId,e)}activateDataEdge(e){this.activeDataEdges.add(e)}isDataEdgeActive(e){return this.activeDataEdges.has(e)}appendEvent(e){this.events.push(e)}finish(){this.finishedAt=new Date}}function Co(e,t,o,n,r){const i=e.valueStore.getWorkflowValues(),a={};for(const[t,o]of e.nodeResults)a[t]=o;const s=[...e.events];return{runId:e.runId,workflowId:t.id||t.name,status:n,document:t,inputs:{...o},outputs:i,nodeResults:a,events:s,startedAt:e.startedAt,finishedAt:e.finishedAt,metadata:r}}class To{constructor(e,t,o){this.emitter=e,this.eventFactory=t,this.options=o}get engine(){return this.options.engine}get codeSandboxEvaluator(){return this.options.codeSandboxEvaluator}get frame(){return this._frame}bindFrame(e){this._frame=e}async emit(e){const t=this.eventFactory.create({id:"",sequence:0,timestamp:new Date,runId:this.options.runId,parentRunId:this.options.parentRunId,workflowId:this.options.workflowId,type:ce.NODE_OUTPUT,path:this.options.path??[],...e});this._frame?.appendEvent(t),await this.emitter.updateObservers(t)}async updateObservers(e){await this.emitter.updateObservers(e)}}function Lo(e){const t=e.capabilities;return{codeMode:t?.codeMode??e.codeMode,workflows:{list:t?.workflows?.list??("function"==typeof e.listWorkflows?"supported":"not_supported"),get:t?.workflows?.get??("function"==typeof e.getWorkflow?"supported":"not_supported")}}}class Mo{static{this._cache={}}static register(e,t){return Mo._cache[e]=t,t}static get(e){const t=e??Mo._currentFlavour;if(t)return Mo._cache[t]}static getOrFail(e){const t=Mo.get(e);if(!t)throw new to(`No graph execution backend registered under '${e}'`,"GRAPH_EXECUTION_BACKEND_NOT_REGISTERED");return t}static get current(){return Mo.get()}static get currentFlavour(){return Mo._currentFlavour??qt}static setCurrent(e){Mo._currentFlavour=e}static list(){return Object.entries(Mo._cache).map(([e,t])=>({flavour:e,backend:t}))}static unregister(e){e&&(delete Mo._cache[e],Mo._currentFlavour===e&&(Mo._currentFlavour=void 0))}static clear(){for(const e of Object.keys(Mo._cache))delete Mo._cache[e];Mo._currentFlavour=void 0}}class jo{evaluate(e,t){switch(e.op){case"eq":return this.resolveValue(e.left,t)===this.resolveValue(e.right,t);case"neq":return this.resolveValue(e.left,t)!==this.resolveValue(e.right,t);case"gt":return Number(this.resolveValue(e.left,t))>Number(this.resolveValue(e.right,t));case"gte":return Number(this.resolveValue(e.left,t))>=Number(this.resolveValue(e.right,t));case"lt":return Number(this.resolveValue(e.left,t))<Number(this.resolveValue(e.right,t));case"lte":return Number(this.resolveValue(e.left,t))<=Number(this.resolveValue(e.right,t));case"and":return e.conditions.every(e=>this.evaluate(e,t));case"or":return e.conditions.some(e=>this.evaluate(e,t));case"not":return!this.evaluate(e.condition,t);case"exists":return void 0!==this.resolveValue(e.value,t)&&null!==this.resolveValue(e.value,t);default:throw new to(`Unknown ConditionExpression op '${e.op}'`,"GRAPH_UNKNOWN_CONDITION_OP",{expr:e})}}resolveValue(e,t){if("const"in e)return e.const;if("path"in e&&!("step"in e))return this.resolvePath(e.path,t);if("step"in e&&"path"in e){const o=t?.nodes;if(o&&"object"==typeof o){const t=o[e.step];return this.resolvePath(e.path,t)}return this.resolvePath(e.path,t)}throw new to("Invalid ExprValue: must have `const`, `path`, or `step`+`path`","GRAPH_INVALID_EXPR_VALUE",{ref:e})}resolvePath(e,t){if(!e)return t;const o=e.split(".");let n=t;for(const e of o){if(null==n)return;n=n[e]}return n}}function Go(e){return"object"==typeof e&&null!==e&&"type"in e&&"code"===e.type}function Uo(e){return"object"==typeof e&&null!==e&&"op"in e&&"string"==typeof e.op}async function Fo(e,t,o){const n=o.engine?.codeSandboxEvaluator;if(!n)throw new to("Code conditions require a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{code:e.code});await o.log("Evaluating code condition",{language:e.language??"javascript"});const r=o.metadata;return!!await n.evaluate({code:e.code,language:e.language,input:t,vars:r?.vars??void 0,item:r?.item,index:r?.index,nodes:r?.nodes??void 0,logger:o.logger,abortSignal:o.abortSignal})}function Bo(e,t,o){if(Uo(e))return(new jo).evaluate(e,t);throw((e,t)=>new to(`Unknown ${t??"flow"} condition type \u2014 must be ConditionExpression (op) or CodeCondition (type: 'code')`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition:e}))(e,o)}async function Wo(e,t,o){return Go(e)?Fo(e,t.input,o):Bo(e,t.state,t.label)}function qo(e,t,o,n){if(e&&"object"==typeof e&&!n.has(e))if(n.add(e),Go(e))o.push({nodeId:t,kind:"code-condition"});else if(ut(e))o.push({nodeId:t,kind:"value-template"});else if((e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"expression"===t.source&&"string"==typeof t.expression})(e))o.push({nodeId:t,kind:"expression-binding"});else if((e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.name&&Array.isArray(t.nodes)&&Array.isArray(t.edges)})(e))Ko(e,o,n);else if(Array.isArray(e))for(const r of e)qo(r,t,o,n);else for(const r of Object.keys(e))qo(e[r],t,o,n)}function Ho(e,t,o){const n=e.id;"core.utility.code"===e.kind&&t.push({nodeId:n,kind:"code-node",detail:e.kind});const r=e.inputBindings??{};for(const[e,o]of Object.entries(r))o&&"expression"===o.mode&&t.push({nodeId:n,kind:"expression-binding",detail:e});qo(e.parameters,n,t,o),qo(e.metadata,n,t,o),qo(e.state,n,t,o),qo(e.loop,n,t,o)}function Ko(e,t,o){for(const n of e.nodes??[])Ho(n,t,o)}function Vo(e){const t=[];return Ko(e,t,new Set),t}function zo(e){return Vo(e).length>0}function Jo(e,t){if(!t)return{valid:!0};switch(t.type){case"any":default:return{valid:!0};case"string":return"string"!=typeof e?Xo("string"):{valid:!0};case"number":return"number"==typeof e&&Number.isFinite(e)?t.integer&&!Number.isInteger(e)?{valid:!1,message:"expected an integer number"}:void 0!==t.min&&e<t.min?{valid:!1,message:"expected a number >= "+t.min}:void 0!==t.max&&e>t.max?{valid:!1,message:"expected a number <= "+t.max}:{valid:!0}:Xo("number");case"boolean":return"boolean"!=typeof e?Xo("boolean"):{valid:!0};case"array":if(!Array.isArray(e))return Xo("array");if(void 0!==t.minItems&&e.length<t.minItems)return{valid:!1,message:`expected at least ${t.minItems} items`};if(void 0!==t.maxItems&&e.length>t.maxItems)return{valid:!1,message:`expected at most ${t.maxItems} items`};for(const o of e){const e=Jo(o,t.items);if(!e.valid)return e}return{valid:!0};case"object":case"model":{if(null===e||"object"!=typeof e||Array.isArray(e))return Xo(t.type);const o=t,n=o.properties;if(!n)return{valid:!0};for(const[t,o]of Object.entries(n))if(t in e){const n=Jo(e[t],o);if(!n.valid)return{valid:!1,message:`property '${t}': ${n.message}`}}if(o.required)for(const t of o.required)if(!(t in e))return{valid:!1,message:`missing required property '${t}'`};if(!1===o.additionalProperties)for(const t of Object.keys(e))if(!(t in n))return{valid:!1,message:`unexpected property '${t}'`};return{valid:!0}}case"enum":return t.values.some(t=>t===e)?{valid:!0}:{valid:!1,message:"value is not one of the enum values"}}}function Xo(e){return{valid:!1,message:`expected a ${e} value`}}function Yo(e){if("string"==typeof e)return e.length>0;if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.credentialId&&t.credentialId.length>0&&(void 0===t.credentialType||"string"==typeof t.credentialType)}const Qo=new Set(["loop"]),Zo=["secret","secrets","password","passwd","token","accessToken","refreshToken","apiKey","api_key","privateKey","credentials"];class en{validate(e,t,o,n,r){this.validateParameters(e,t,o,n,r),this.validateMetadataKeys(e,t,o,n),this.validateDisabledBehavior(e,o,n),this.validateBindingShapes(e,t,o,n)}validateParameters(e,t,o,n,r){const i=!0===t.policies?.allowUndeclaredParameters,a=new Map(t.parameters.map(e=>[e.id,e]));for(const[r,s]of Object.entries(e.parameters??{})){const d=a.get(r);if(!d){i||o.push({code:"parameter.undeclared",path:`${n}.parameters.${r}`,message:`Node '${e.id}' sets parameter '${r}' which is not declared by kind '${t.kind}'`,nodeId:e.id,details:{kind:t.kind}});continue}if(void 0===s){o.push({code:"parameter.invalid",path:`${n}.parameters.${r}`,message:`Node '${e.id}' parameter '${r}' must not be undefined`,nodeId:e.id});continue}const l=this.checkParameterValue(s,d);l.valid||o.push({code:"parameter.type-mismatch",path:`${n}.parameters.${r}`,message:`Node '${e.id}' parameter '${r}' is invalid: ${l.message}`,nodeId:e.id,details:{expectedType:d.type}})}for(const i of t.parameters)void 0===(e.parameters??{})[i.id]&&(this.isParameterSatisfiedByInput(e,i.id,r)||(!0===i.required||(i.validation??[]).some(e=>"required"===e.kind))&&void 0===i.defaultValue&&o.push({code:"parameter.required-missing",path:`${n}.parameters.${i.id}`,message:`Node '${e.id}' is missing required parameter '${i.id}' declared by kind '${t.kind}'`,nodeId:e.id}))}isParameterSatisfiedByInput(e,t,o){return void 0!==(e.inputBindings??{})[t]||!0===o?.has(t)}checkParameterValue(e,t){if(ut(e))return{valid:!0};switch(t.type){case"string":case"code":case"expression":return"string"!=typeof e?Xo("string"):{valid:!0};case"number":return"number"==typeof e&&Number.isFinite(e)?{valid:!0}:Xo("number");case"boolean":return"boolean"!=typeof e?Xo("boolean"):{valid:!0};case"options":{const o=t.options;return o&&o.length&&!o.some(t=>t.value===e)?{valid:!1,message:"value is not one of the declared options"}:{valid:!0}}case"collection":return Array.isArray(e)?{valid:!0}:Xo("array");case"object":case"resourceLocator":return null===e||"object"!=typeof e||Array.isArray(e)?Xo("object"):{valid:!0};case"credential":return Yo(e)?t.credentialType&&"object"==typeof e&&void 0!==e.credentialType&&e.credentialType!==t.credentialType?{valid:!1,message:`credential type '${e.credentialType}' does not match the declared type '${t.credentialType}'`}:{valid:!0}:{valid:!1,message:"credential parameters must hold a credential reference (credentialId), never a secret"};default:return{valid:!0}}}validateMetadataKeys(e,t,o,n){const r=t.metadata?.allowedInstanceMetadataKeys;for(const i of Object.keys(e.metadata??{}))Qo.has(i)?o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${i}`,message:`Node '${e.id}' metadata key '${i}' is reserved and must not be set directly`,nodeId:e.id}):Array.isArray(r)&&!r.includes(i)&&o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${i}`,message:`Node '${e.id}' metadata key '${i}' is not in the allowed metadata keys of kind '${t.kind}'`,nodeId:e.id})}validateDisabledBehavior(e,t,o){!0!==e.disabled&&!1!==e.disabled&&void 0!==e.disabled&&t.push({code:"disabled.invalid",path:o+".disabled",message:`Node '${e.id}' disabled flag must be a boolean`,nodeId:e.id});const n=(e.metadata??{}).disabledBehavior;void 0===n||ae(n)||t.push({code:"disabled.invalid-behavior",path:o+".metadata.disabledBehavior",message:`Node '${e.id}' disabled behavior '${n+""}' is not one of: ${ie.join(", ")}`,nodeId:e.id})}validateBindingShapes(e,t,o,n){for(const[r,i]of Object.entries(e.inputBindings??{})){if("literal"===i.mode){const a=t.inputs.find(e=>e.id===r);if(a?.schema){const t=Jo(i.value,a.schema);t.valid||o.push({code:"binding.literal-invalid",path:`${n}.inputBindings.${r}`,message:`Node '${e.id}' literal binding for '${r}' is schema-invalid: ${t.message}`,nodeId:e.id})}}"expression"!==i.mode||"string"==typeof i.expression&&i.expression.trim()||o.push({code:"binding.expression-invalid",path:`${n}.inputBindings.${r}`,message:`Node '${e.id}' expression binding for '${r}' must contain a non-empty expression`,nodeId:e.id})}}validateBindingSatisfaction(e,t,o,n,r,i={}){const a=new Set(o.filter(e=>"data"===e.type).map(e=>e.targetPort)),s=new Set(Object.entries(e.inputBindings??{}).map(([e])=>e));for(const t of a){const o=(e.inputBindings??{})[t];o&&"literal"===o.mode&&!0!==i.allowLiteralAndEdgeBindings&&n.push({code:"binding.conflict",path:`${r}.inputBindings.${t}`,message:`Node '${e.id}' input '${t}' has both an incoming edge and a literal binding`,nodeId:e.id})}for(const o of t.inputs)!0===o.required&&(a.has(o.id)||s.has(o.id)||void 0===(e.parameters??{})[o.id]&&n.push({code:"topology.required-input-unsatisfiable",path:r+".parameters",message:`Node '${e.id}' required input '${o.id}' has no incoming edge or binding`,nodeId:e.id,details:{port:o.id}}))}static disabledBehaviorOf(e,t){const o=(e.metadata??{}).disabledBehavior;if(ae(o))return o;const n=t?.disabledBehavior;return ae(n)?n:"skip"}}let tn=class extends T{constructor(e){super(e)}};function on(e){return[e.namespace??"default",e.workflowId,e.nodeId,e.version??"default",e.fingerprint].join(":")}function nn(e){return new tn({id:on(e.key),workflowId:e.key.workflowId,nodeId:e.key.nodeId,fingerprint:e.key.fingerprint,...void 0!==e.key.namespace?{namespace:e.key.namespace}:{},...void 0!==e.key.version?{version:e.key.version}:{},pinned:e.pinned,outputs:e.outputs,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt),...e.expiresAt?{expiresAt:new Date(e.expiresAt)}:{},...e.metadata?{metadata:e.metadata}:{}})}function rn(e){return{key:{workflowId:e.workflowId,nodeId:e.nodeId,fingerprint:e.fingerprint,...void 0!==e.namespace?{namespace:e.namespace}:{},...void 0!==e.version?{version:e.version}:{}},outputs:e.outputs,pinned:e.pinned,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString(),...e.expiresAt?{expiresAt:e.expiresAt.toISOString()}:{},...e.metadata?{metadata:e.metadata}:{}}}S([P({type:String,generated:!1}),D("design:type",String)],tn.prototype,"id",void 0),S([R(),$(),D("design:type",String)],tn.prototype,"workflowId",void 0),S([R(),$(),D("design:type",String)],tn.prototype,"nodeId",void 0),S([R(),D("design:type",String)],tn.prototype,"fingerprint",void 0),S([R(),D("design:type",String)],tn.prototype,"namespace",void 0),S([R(),D("design:type",String)],tn.prototype,"version",void 0),S([R(),D("design:type",Boolean)],tn.prototype,"pinned",void 0),S([R(),D("design:type",Object)],tn.prototype,"outputs",void 0),S([R(),D("design:type",Date)],tn.prototype,"createdAt",void 0),S([R(),D("design:type",Date)],tn.prototype,"updatedAt",void 0),S([R(),D("design:type",Date)],tn.prototype,"expiresAt",void 0),S([R(),D("design:type",Object)],tn.prototype,"metadata",void 0),tn=S([C("graph_value"),E(),D("design:paramtypes",[Object])],tn);let an=class extends G{constructor(e){super(e,tn,!0),this.runtimeValues=new Map}seedWorkflowInputs(e){this.runtimeValues.set(Wt,{...e})}setNodeOutputs(e,t){this.runtimeValues.set(e,{...t})}getPort(e,t){return this.runtimeValues.get(e)?.[t]}hasPort(e,t){return Object.prototype.hasOwnProperty.call(this.runtimeValues.get(e)??{},t)}setWorkflowOutput(e,t){const o=this.runtimeValues.get(Wt)??{};o[e]=t,this.runtimeValues.set(Wt,o)}getWorkflowValues(){return{...this.runtimeValues.get(Wt)??{}}}snapshot(){return Object.fromEntries(this.runtimeValues.entries())}async readCached(e,...t){try{return rn(await this.read(on(e),...t))}catch{return}}async writeCached(e,t,...o){const n=on(e);let r;try{r=await this.read(n,...o)}catch{r=void 0}r?await this.update(Object.assign(r,nn(t)),...o):await this.create(nn(t),...o)}async deleteCached(e,...t){try{await this.delete(on(e),...t)}catch{}}async hasCached(e,...t){return void 0!==await this.readCached(e,...t)}async listCached(e,...t){return(await this.select().execute(...t)).map(e=>rn(e)).filter(t=>((e,t)=>!(void 0!==t.workflowId&&e.workflowId!==t.workflowId||void 0!==t.nodeId&&e.nodeId!==t.nodeId||void 0!==t.namespace&&e.namespace!==t.namespace||void 0!==t.version&&e.version!==t.version||void 0!==t.fingerprint&&e.fingerprint!==t.fingerprint))(t.key,e))}async clearRun(e,...t){const o=await this.select().execute(...t);for(const e of o)await this.delete(e.id,...t)}readRuntimeValues(e){return this.runtimeValues.get(e)}writeRuntimeValues(e,t){this.runtimeValues.set(e,{...t})}getAdapter(){return this.adapter}};function sn(e){return new(0,G.forModel(tn,e.alias).constructor)(e)}an=S([j(tn,m),D("design:paramtypes",[Function])],an);class dn{static upstreamNodes(e,t,o=!1){const n=new Set,r=[e];for(;r.length;){const e=r.pop(),i=t.get(e)??[];for(const e of i)!o&&this.isBoundary(e.sourceNodeId)||n.has(e.sourceNodeId)||(n.add(e.sourceNodeId),r.push(e.sourceNodeId))}return n}static downstreamNodes(e,t,o=!1){const n=new Set,r=[e];for(;r.length;){const e=r.pop(),i=t.get(e)??[];for(const e of i)!o&&this.isBoundary(e.targetNodeId)||n.has(e.targetNodeId)||(n.add(e.targetNodeId),r.push(e.targetNodeId))}return n}static isBoundary(e){return"$workflow"===e}}class ln{constructor(e,t,o){this.store=e,this.policy=t,this.dependencyResolver=o}async pinNode(e){const t=e.plan,o=e.includeDependencies??!0?this.dependencyResolver.getPinSet(t,e.nodeId):new Set([e.nodeId]);for(const e of o){const o=t.nodes.find(t=>t.id===e);if(!o)throw new io(`Node '${e}' not found in plan`);if(!this.policy.canPin(o))throw new io(`Node '${e}' is not pinnable`,{nodeId:e})}const n=this.topologicalOrder(t,o);for(const o of n){const n=t.nodes.find(e=>e.id===o),r=e.result.nodeResults[o];if(!r||!r.outputs)throw new io(`Node '${o}' has no completed output to pin`);const i=r.inputs??{},a=this.dependencyFingerprints(t,o,e.result),s=this.createValueKey(e.document.id,n,i,a),d=(new Date).toISOString(),l={key:s,outputs:r.outputs,pinned:!0,createdAt:d,updatedAt:d,metadata:{...e.result.metadata,nodeId:o}};await this.store.writeCached(s,l)}}async unpinNode(e){const t={workflowId:e.document.id,nodeId:e.nodeId,fingerprint:e.fingerprint,namespace:e.namespace};await this.store.deleteCached(t)}async readPinnedValue(e,t,o,n,r){const i=this.createValueKey(e,t,o,n,r),a=await this.store.readCached(i);if(a&&a.pinned){if(a.expiresAt&&new Date(a.expiresAt)<new Date)return;return a}}createValueKey(e,t,o,n,r){return{workflowId:e,nodeId:t.id,fingerprint:this.computeFingerprint(e,t,o,n),namespace:r}}computeFingerprint(e,t,o,n){const r={workflowId:e,nodeId:t.id,nodeKind:t.kind,parameters:this.stableSerialize(t.instance.parameters??{}),inputBindings:this.stableSerialize(t.instance.inputBindings??{}),metadata:this.stableSerialize(this.relevantMetadata(t)),inputs:this.stableSerialize(o),dependencyFingerprints:this.stableSerialize(n)},i=this.stableSerialize(r);return this.simpleHash(i)}relevantMetadata(e){const t={...e.metadata??{}};return delete t.ui,delete t.position,delete t.visual,t}topologicalOrder(e,t){const o=[],n=new Set,r=i=>{if(n.has(i))return;n.add(i);const a=dn.upstreamNodes(i,e.incomingByNode,!1);for(const e of a)t.has(e)&&r(e);o.push(i)};for(const e of t)r(e);return o}dependencyFingerprints(e,t,o){const n=this.dependencyResolver.getDependencies(e,t),r={};for(const t of n){const n=e.nodes.find(e=>e.id===t);if(n){const i=o.nodeResults[t],a=i?.inputs??{},s=this.dependencyFingerprints(e,t,o);r[t]=this.computeFingerprint(e.workflowId,n,a,s)}}return r}stableSerialize(e){return null===e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?`[${e.map(e=>this.stableSerialize(e)).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${this.stableSerialize(e[t])}`).join(",")}}`}simpleHash(e){let t=0;for(let o=0;o<e.length;o++)t=(t<<5)-t+e.charCodeAt(o),t|=0;return`fp_${Math.abs(t).toString(16).padStart(8,"0")}_${e.length}`}}const cn={enabled:!0,strategy:"manual",includeDependencies:!0};function un(e){return!0===e?.enabled&&"disabled"!==e.strategy}class pn{canPin(e){return un(this.getPinningMetadata(e))}shouldUsePinnedValue(e){const t=this.getPinningMetadata(e);return!0===t.enabled&&"disabled"!==t.strategy}shouldAutoPin(e){const t=this.getPinningMetadata(e);return!0===t.enabled&&"automatic"===t.strategy}getPinningMetadata(e){const t=e.manifest.metadata?.pinnable??e.metadata?.pinnable;return t?{...cn,...t}:{...cn,enabled:!1}}}class hn{getDependencies(e,t){return dn.upstreamNodes(t,e.incomingByNode,!1)}getPinSet(e,t){const o=this.getDependencies(e,t);return o.add(t),o}}class fn{constructor(){this.local=!0,this.codeMode="hostSide",Mo.register(qt,this)}async initialize(e){this.valueAdapter=e.valueAdapter,this.codeSandboxEvaluator=e.codeSandboxEvaluator,this.workflowStore=e.workflowStore,this.engine=e.engine}get capabilities(){const e=this.workflowStore?"supported":"not_supported";return{codeMode:this.codeMode,workflows:{list:e,get:e}}}async listWorkflows(...e){const t=this.workflowStore;if(!t)throw new to("LocalGraphExecutionBackend has no workflowStore configured; workflow listing is not supported","GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED");return(await t.listWorkflows(...e)).map(e=>({id:e.workflowId,...void 0!==e.name?{name:e.name}:{},...void 0!==e.updatedAt&&null!==e.updatedAt?{updatedAt:e.updatedAt}:{}}))}async getWorkflow(e,...t){const o=this.workflowStore;if(!o)throw new to("LocalGraphExecutionBackend has no workflowStore configured; workflow lookup is not supported","GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED");return await o.getDocument(e,...t)}async execute(e){const{document:t,plan:o,inputs:n,options:r,events:i}=e,a=i,s=a.frame;if(!s)throw new to("LocalGraphExecutionBackend requires the frame-bound event sink created by GraphExecutionEngine","GRAPH_EXECUTION_FRAME_MISSING");const d=s.valueStore,l=s.runId,c=r.path??[],u=async e=>{await a.emit(e)};try{for(const e of o.layers)this.assertNotAborted(r),await this.executeLayer(s,o,e.nodes,r,u);this.assertNotAborted(r);const e=[...s.nodeResults.values()].find(e=>e.status===se.FAILED);if(e?.error)throw new to(e.error.message,e.error.code??"GRAPH_EXECUTION_ERROR",e.error.details);return s.finish(),await a.emit({type:ce.WORKFLOW_COMPLETED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:se.SUCCEEDED,payload:{outputs:d.getWorkflowValues()}}),Co(s,t,n,se.SUCCEEDED,r.metadata)}catch(e){if(e instanceof co)throw s.finish(),e;s.finish();const i=this.toErrorPayload(e);return e instanceof uo||!0===r.abortSignal?.aborted?(await a.emit({type:ce.WORKFLOW_CANCELLED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:se.CANCELLED,error:i}),Co(s,t,n,se.CANCELLED,r.metadata)):(await a.emit({type:ce.WORKFLOW_FAILED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:se.FAILED,error:i}),Co(s,t,n,se.FAILED,r.metadata))}}async executeLayer(e,t,o,n,r){const i=Math.max(1,n.concurrency??4),a=[...o];for(;a.length>0;){const o=a.splice(0,i);await Promise.all(o.map(o=>this.executeNode(e,t,o,n,r)))}}async executeNode(e,t,o,n,r){if(this.assertNotAborted(n),!this.isNodeActivated(e,t,o))return void await this.skipInactiveNode(e,t,o,n,r);if(!0===o.instance.disabled)return void await this.executeDisabledNode(e,t,o,n,r);const i=new Date,a=[...n.path??[],o.id];await r({type:ce.NODE_STARTED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.RUNNING}),this.emitNodeStateChanged(e,t,o,a,de.RUNNING,se.RUNNING,r);const s=await this.resolveNodeInputs(e,t,o,n);if(n.usePinnedValues){const n=await this.tryPinnedValue(e,t,o,s);if(n){e.valueStore.setNodeOutputs(o.id,n.outputs),this.routeOutgoingEdges(e,t,o,n.outputs,r);const d=new Date,l={nodeId:o.id,status:se.CACHED,inputs:s,outputs:n.outputs,startedAt:i,finishedAt:d,fromCache:!0,pinned:!0,events:[]};return e.recordNodeResult(l),await r({type:ce.NODE_CACHE_HIT,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.CACHED,payload:{outputs:n.outputs}}),await r({type:ce.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.SUCCEEDED,payload:{outputs:n.outputs,fromCache:!0}}),void this.emitNodeStateChanged(e,t,o,a,de.SUCCEEDED,se.SUCCEEDED,r)}}try{const d=new Ro(e.runId,n.parentRunId,t.workflowId,t.resolved.document,o.instance,o.manifest,a,r,n.metadata,this.engine,n.abortSignal,this.executionLimits(n)),l=await this.resolveNodeParameters(o,s,n),c={nodeId:o.id,kind:o.kind,inputs:s,parameters:l,credentials:this.collectCredentials(o),metadata:o.instance.metadata},u=await this.invokeExecutor(o,c,d),p=this.validateNodeOutputs(o,u??{});e.valueStore.setNodeOutputs(o.id,p),this.routeOutgoingEdges(e,t,o,p,r);const h=new Date,f={nodeId:o.id,status:se.SUCCEEDED,inputs:s,outputs:p,startedAt:i,finishedAt:h,events:[]};e.recordNodeResult(f),await r({type:ce.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.SUCCEEDED,payload:{outputs:p}}),this.emitNodeStateChanged(e,t,o,a,de.SUCCEEDED,se.SUCCEEDED,r)}catch(d){if(d instanceof co)throw d;const l=new Date,c=this.toErrorPayload(d),u={nodeId:o.id,status:se.FAILED,inputs:s,error:c,startedAt:i,finishedAt:l,events:[]};if(e.recordNodeResult(u),await r({type:ce.NODE_FAILED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.FAILED,error:c}),this.emitNodeStateChanged(e,t,o,a,de.FAILED,se.FAILED,r),n.failFast??!0)throw d}}isNodeActivated(e,t,o){const n=(t.incomingByNode.get(o.id)??[]).filter(e=>"data"===e.type);return 0===n.length||n.some(t=>t.sourceNodeId===Wt||e.isDataEdgeActive(t.id))}async skipInactiveNode(e,t,o,n,r){const i=new Date,a=[...n.path??[],o.id];await r({type:ce.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.SKIPPED,payload:{reason:"branchNotSelected"}});const s={nodeId:o.id,status:se.SKIPPED,inputs:{},startedAt:i,finishedAt:new Date,events:[]};e.recordNodeResult(s),this.emitNodeStateChanged(e,t,o,a,de.SKIPPED,se.SKIPPED,r)}async executeDisabledNode(e,t,o,n,r){const i=new Date,a=[...n.path??[],o.id],s=en.disabledBehaviorOf(o.instance,t.resolved.document.settings);if(await r({type:ce.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.SKIPPED,payload:{disabled:!0,behavior:s}}),"skip"===s){const n={nodeId:o.id,status:se.SKIPPED,inputs:{},startedAt:i,finishedAt:new Date,events:[]};return e.recordNodeResult(n),void this.emitNodeStateChanged(e,t,o,a,de.SKIPPED,se.SKIPPED,r)}const d=await this.resolveNodeInputs(e,t,o,n);let l;if("passThroughFirstInput"===s){const n=(t.incomingByNode.get(o.id)??[]).find(e=>"data"===e.type),r=o.manifest.outputs[0]?.id??"value",i=n?e.valueStore.getPort(n.sourceNodeId,n.sourcePort):Object.values(d)[0];l={[r]:i}}else{l={};for(const e of o.manifest.outputs)l[e.id]=e.metadata?.defaultValue}e.valueStore.setNodeOutputs(o.id,l),this.routeOutgoingEdges(e,t,o,l,r);const c={nodeId:o.id,status:se.SUCCEEDED,inputs:d,outputs:l,startedAt:i,finishedAt:new Date,events:[]};e.recordNodeResult(c),this.emitNodeStateChanged(e,t,o,a,de.SUCCEEDED,se.SUCCEEDED,r)}async invokeExecutor(e,t,o){return await e.executor.execute(t,o)}validateNodeOutputs(e,t){const o=e.manifest;if(!0===o.policies?.allowUnknownOutputs)return t;const n=new Set(o.outputs.map(e=>e.id)),r=Object.keys(t).filter(e=>!n.has(e));if(r.length>0)throw new to(`Node '${e.id}' of kind '${e.kind}' produced unknown output(s): ${r.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,unknownOutputs:r});const i=o.outputs.filter(e=>!0===e.required&&!(e.id in t)).map(e=>e.id);if(i.length>0)throw new to(`Node '${e.id}' of kind '${e.kind}' did not produce required output(s): ${i.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,missingRequired:i});return t}collectCredentials(e){const t={};for(const o of e.manifest.parameters){if("credential"!==o.type)continue;const n=(e.instance.parameters??{})[o.id];"string"==typeof n&&n.length>0?t[o.id]={credentialId:n,credentialType:o.credentialType??""}:Yo(n)&&(t[o.id]={credentialId:n.credentialId,credentialType:n.credentialType})}const o=(e.instance.metadata??{}).credentials;if(o&&"object"==typeof o&&!Array.isArray(o))for(const[e,n]of Object.entries(o)){const o=n;"string"==typeof o&&o.length>0?t[e]={credentialId:o,credentialType:""}:Yo(o)&&(t[e]={credentialId:o.credentialId,credentialType:o.credentialType})}return t}async resolveNodeInputs(e,t,o,n){const r={},i=(t.incomingByNode.get(o.id)??[]).filter(e=>"data"===e.type),a=new Map;for(const e of i){const t=a.get(e.targetPort)??[];t.push(e),a.set(e.targetPort,t)}for(const[t,o]of a)if(1===o.length)r[t]=e.valueStore.getPort(o[0].sourceNodeId,o[0].sourcePort);else{let n,i=!1;for(const t of o){const o=e.valueStore.getPort(t.sourceNodeId,t.sourcePort);r[t.sourcePort]=o,void 0!==o&&(n=o,i=!0)}i&&void 0===r[t]&&(r[t]=n)}const s=o.instance.inputBindings??{};for(const e of o.manifest.inputs){const t=s[e.id];if("literal"===t?.mode)r[e.id]=t.value;else if("expression"===t?.mode)r[e.id]=await this.evaluateExpressionBinding(o,t.expression,r,n);else if(void 0===r[e.id]){const t=e.metadata?.defaultValue;void 0!==t&&(r[e.id]=t)}}return r}async resolveNodeParameters(e,t,o){const n=e.instance.parameters??{},r={};for(const[i,a]of Object.entries(n))r[i]=ut(a)?await this.evaluateValueTemplate(a,e,t,o):a;return r}async evaluateValueTemplate(e,t,o,n){const r=this.codeSandboxEvaluator;if(!r)throw new to(`Value template on node '${t.id}' requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator`,"GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{nodeId:t.id});const i=e.language??("expression"===e.mode?"javascript":"text"),a="template"===e.mode?(e=>`\`${e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\{\{\s*([\s\S]*?)\s*\}\}/g,(e,t)=>`\${${t}}`)}\``)(e.expression):e.expression,s=n.metadata;return await r.evaluate({code:a,language:"typescript"===i?"typescript":"javascript",input:o,vars:s?.vars??void 0,item:s?.item,index:s?.index,abortSignal:n.abortSignal})}async evaluateExpressionBinding(e,t,o,n){const r=this.codeSandboxEvaluator;if(!r)throw new to(`Expression binding on node '${e.id}' requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator`,"GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{nodeId:e.id,expression:t});const i=n.metadata;return await r.evaluate({code:t,language:"javascript",input:o,vars:i?.vars??void 0,item:i?.item,index:i?.index,abortSignal:n.abortSignal})}async tryPinnedValue(e,t,o,n){if(!(new pn).shouldUsePinnedValue(o))return;const r=this.createPinningService(e),i=this.computeDependencyFingerprints(e,t,o.id);return r.readPinnedValue(t.workflowId,o,n,i)}computeDependencyFingerprints(e,t,o){const n=this.createPinningService(e),r=(new hn).getDependencies(t,o),i={};for(const o of r){const r=t.nodes.find(e=>e.id===o);if(r){const a=e.nodeResults.get(o),s=a?.inputs??{},d=this.computeDependencyFingerprints(e,t,o);i[o]=n.computeFingerprint(t.workflowId,r,s,d)}}return i}routeOutgoingEdges(e,t,o,n,r){const i=(t.outgoingByNode.get(o.id)??[]).filter(e=>"data"===e.type);for(const a of i){if(!Object.prototype.hasOwnProperty.call(n,a.sourcePort))continue;const i=n[a.sourcePort];e.activateDataEdge(a.id),a.targetNodeId===Wt&&e.valueStore.setWorkflowOutput(a.targetPort,i),this.emitEdgeStateChanged(e,t,o,a,de.SUCCEEDED,se.SUCCEEDED,r),r({type:ce.EDGE_VALUE_ROUTED,runId:e.runId,workflowId:t.workflowId,edgeId:a.id,nodeId:o.id,path:[],payload:{edge:a,value:i}}).catch(()=>{})}}emitNodeStateChanged(e,t,o,n,r,i,a){a({type:ce.NODE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:n,status:i,payload:{nodeId:o.id,state:r,runId:e.runId,workflowId:t.workflowId,status:i}}).catch(()=>{})}emitEdgeStateChanged(e,t,o,n,r,i,a){a({type:ce.EDGE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,edgeId:n.id,nodeId:o.id,path:[],status:i,payload:{edgeId:n.id,state:r,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,status:i}}).catch(()=>{})}createPinningService(e){const t=sn(e.valueStore.getAdapter()??this.valueAdapter);return new ln(t,new pn,new hn)}executionLimits(e){return{maxLoopIterations:e.maxLoopIterations??zt,maxForeachIterations:e.maxForeachIterations??Jt}}assertNotAborted(e){if(!0===e.abortSignal?.aborted)throw new uo(e.runId??"unknown")}toErrorPayload(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack,code:e.graphCode??("number"==typeof e.code?e.code+"":e.code)}:{name:"UnknownError",message:e+""}}}class gn{constructor(e){this.catalogue=e}async resolveNodes(e,t,o,...n){const r=new Map;for(const[i,a]of e.entries()){const e=`nodes[${i}]`;if(this.catalogue.has(a.kind,...n))try{const e=await this.catalogue.resolveManifest(a.kind,a,o,...n),t=this.catalogue.getExecutor(a.kind,...n);r.set(a.id,{instance:a,manifest:e,executor:t})}catch(o){t.push({code:"kind.resolution-failed",path:e+".kind",message:`Node '${a.id}' kind '${a.kind}' failed to resolve: ${o.message}`,nodeId:a.id,details:{kind:a.kind}})}else t.push({code:"kind.unknown",path:e+".kind",message:`Node '${a.id}' references kind '${a.kind}' which is not registered in the backend catalogue`,nodeId:a.id,details:{kind:a.kind}})}return r}validateEffectivePorts(e,t,o,n){const r=!0===t.policies?.allowUndeclaredParameters,i=new Set(t.inputs.map(e=>e.id)),a=new Set(t.outputs.map(e=>e.id));for(const a of Object.keys(e.inputBindings??{}))r||i.has(a)||o.push({code:"binding.unknown-port",path:`${n}.inputBindings.${a}`,message:`Node '${e.id}' input binding '${a}' does not refer to an effective input port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveInputs:[...i]}});for(const i of Object.keys(e.outputBindings??{}))r||a.has(i)||o.push({code:"binding.unknown-port",path:`${n}.outputBindings.${i}`,message:`Node '${e.id}' output binding '${i}' does not refer to an effective output port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveOutputs:[...a]}})}}function mn(e,t,o="$"){const n=new Set;for(const t of e.edges)"node"===t.source.scope&&n.add(t.source.nodeId),"node"===t.target.scope&&n.add(t.target.nodeId);for(const r of e.nodes){n.has(r.id)||t.push({code:"topology.loose-node",path:`${o}.nodes[${r.id}]`,message:`Node '${r.id}' is connected to nothing; every node must participate in at least one edge`,nodeId:r.id});const e=r.loop?.body;e&&mn(e,t,`${o}.nodes[${r.id}].loop.body`)}}class yn{resolveEdges(e,t,o){const n=new Set(e.inputs.map(e=>e.id)),r=new Set(e.outputs.map(e=>e.id)),i=[];for(const[a,s]of(e.edges??[]).entries()){const e=`edges[${a}]`,d=this.resolveEndpoint(s,"source",t,n,r,o,e),l=this.resolveEndpoint(s,"target",t,n,r,o,e);if(!d||!l)continue;if(!this.validateDirectionAndType(s,d,l,t,o,e))continue;const c={id:s.id,type:s.type,sourceNodeId:d.nodeId,sourcePort:d.port,targetNodeId:l.nodeId,targetPort:l.port,metadata:s.metadata,edge:s};void 0!==s.label&&(c.label=s.label),i.push(c)}return i}resolveEndpoint(e,t,o,n,r,i,a){const s=e[t];return Xe(s)?("source"===t?n.has(s.port):r.has(s.port))?{nodeId:Wt,port:s.port}:void i.push({code:"edge.unknown-port",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} references workflow port '${s.port}' which is not declared on the document boundary`,edgeId:e.id,details:{scope:"workflow",port:s.port}}):Ye(s)?o.get(s.nodeId)?{nodeId:s.nodeId,port:s.port}:void i.push({code:"edge.unknown-node",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} references node '${s.nodeId}' which is not part of the document or did not resolve`,edgeId:e.id,nodeId:s.nodeId}):void i.push({code:"edge.invalid-endpoint",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} endpoint is not a valid GraphEndpoint`,edgeId:e.id})}validateDirectionAndType(e,t,o,n,r,i){let a=!0;const s=t.nodeId===Wt?void 0:n.get(t.nodeId),d=o.nodeId===Wt?void 0:n.get(o.nodeId),l=e=>!0===e?.manifest.policies?.allowUndeclaredParameters;if("data"===e.type)!s||l(s)||this.hasPortDirection(s,t.port,"output")||(this.pushPortIssue(e,"source",t,s,r,i),a=!1),!d||l(d)||this.hasPortDirection(d,o.port,"input")||(this.pushPortIssue(e,"target",o,d,r,i),a=!1);else{if(!s||!d)return r.push({code:"edge.boundary-routing",path:i,message:`Connection edge '${e.id}' must connect two node connection ports; the workflow boundary only routes data`,edgeId:e.id}),!1;if(!(l(s)||l(d)||this.hasPortDirection(s,t.port,"connection")&&this.hasPortDirection(d,o.port,"connection")))return r.push({code:"edge.type-mismatch",path:i,message:`Connection edge '${e.id}' endpoints must both be connection ports`,edgeId:e.id,details:{sourcePort:t.port,targetPort:o.port}}),!1}return a}hasPortDirection(e,t,o){return("input"===o?e.manifest.inputs:"output"===o?e.manifest.outputs:e.manifest.connections??[]).some(e=>e.id===t)}pushPortIssue(e,t,o,n,r,i){const a="source"===t?"output":"input";r.push({code:"data"===e.type?"edge.invalid-direction":"edge.type-mismatch",path:`${i}.${t}`,message:`Edge '${e.id}' ${t} port '${o.port}' on node '${o.nodeId}' is not an ${a} port of kind '${n.manifest.kind}'`,edgeId:e.id,nodeId:o.nodeId,details:{port:o.port,expected:a}})}}class wn{validate(e,t){this.validateDuplicates(e.edges,t),this.validatePolicies(e,t)}validateDuplicates(e,t){const o=new Map;for(const n of e){const e=`${n.sourceNodeId}:${n.sourcePort}->${n.targetNodeId}:${n.targetPort}`,r=o.get(e);r?t.push({code:"connection.duplicate-edge",path:`edges[${n.id}]`,message:`Edge '${n.id}' duplicates the routing of edge '${r.id}' (${e})`,edgeId:n.id,details:{duplicateOf:r.id,routing:e}}):o.set(e,n)}}validatePolicies(e,t){const o=new Map;for(const t of e.edges){if("connection"!==t.type)continue;const e=`${t.targetNodeId}:${t.targetPort}`,n=o.get(e)??[];n.push(t),o.set(e,n)}for(const o of e.edges){if("connection"!==o.type)continue;const n=e.nodeById.get(o.targetNodeId),r=n?.manifest.connections?.find(e=>e.id===o.targetPort)?.connectionPolicy;this.validateEdgePolicy(o,e.nodeById,r,t)}for(const[n,r]of o){const o=n.lastIndexOf(":"),i=n.slice(0,o),a=n.slice(o+1),s=e.nodeById.get(i),d=s?.manifest.connections?.find(e=>e.id===a)?.connectionPolicy;if(!d)continue;const l=void 0!==d.maxConnections?d.maxConnections:!1===d.allowMultiple?1:1/0;r.length>l&&t.push({code:"connection.max-connections",path:`edges[${r[r.length-1].id}]`,message:`Connection port '${a}' on node '${i}' accepts at most ${l} connection(s) but has ${r.length}`,nodeId:i,edgeId:r[r.length-1].id,details:{port:a,max:l,actual:r.length}})}}validateEdgePolicy(e,t,o,n){if(e.sourceNodeId===e.targetNodeId&&!o?.allowSelf)return void n.push({code:"connection.self-connection",path:`edges[${e.id}]`,message:`Edge '${e.id}' connects node '${e.sourceNodeId}' to itself, which the target port policy does not allow`,edgeId:e.id,nodeId:e.sourceNodeId});if(!o)return;const r=t.get(e.sourceNodeId),i=r?.manifest.kind;if(!o.allowedNodeKinds?.length||i&&o.allowedNodeKinds.includes(i)||n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${i??"unknown"}' is not in the allowed node kinds of target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{allowedNodeKinds:o.allowedNodeKinds}}),i&&o.blockedNodeKinds?.includes(i)&&n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${i}' is blocked by target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{blockedNodeKinds:o.blockedNodeKinds}}),o.allowedPortCategories?.length){const t=r?.manifest.connections?.find(t=>t.id===e.sourcePort)?.category;t&&o.allowedPortCategories.includes(t)||n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source port '${e.sourcePort}' category '${t??"unknown"}' is not in the allowed port categories of target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{allowedPortCategories:o.allowedPortCategories}})}}}class bn{constructor(e){this.authorizer=e}async validate(e,t,o,n){const r=this.collectReferences(e,t);for(const i of t.credentials??[]){const a=r.find(e=>void 0===e.credentialType||e.credentialType===i.type);if(a){if(this.checkType(a,i))o.push({code:"credential.type-mismatch",path:n,message:`Node '${e.id}' credential '${a.credentialId}' has type '${a.credentialType}' but kind '${t.kind}' requires '${i.type}'`,nodeId:e.id,details:{credentialType:a.credentialType??"",requiredType:i.type}});else if(this.authorizer){if(!await this.authorizer.hasCredential(a)){o.push({code:"credential.not-found",path:n,message:`Node '${e.id}' references credential '${a.credentialId}' which does not exist`,nodeId:e.id,details:{credentialId:a.credentialId}});continue}await this.authorizer.authorize(a,i)||o.push({code:"credential.unauthorized",path:n,message:`Node '${e.id}' is not authorized to use credential '${a.credentialId}'`,nodeId:e.id,details:{credentialId:a.credentialId}})}}else!1!==i.required&&o.push({code:"credential.missing",path:n,message:`Node '${e.id}' does not provide the required credential of type '${i.type}'`,nodeId:e.id,details:{credentialType:i.type}})}this.scanPlainSecrets(e,o,n)}collectReferences(e,t){const o=[];for(const n of t.parameters){if("credential"!==n.type)continue;const t=(e.parameters??{})[n.id];Yo(t)&&o.push(this.normalize(t,n.credentialType))}const n=(e.metadata??{}).credentials;if(n&&"object"==typeof n&&!Array.isArray(n))for(const e of Object.values(n))Yo(e)&&o.push(this.normalize(e));return o}normalize(e,t){return"string"==typeof e?{credentialId:e,credentialType:t??""}:{credentialId:e.credentialId,credentialType:e.credentialType??t??""}}checkType(e,t){return void 0!==e.credentialType&&e.credentialType!==t.type}scanPlainSecrets(e,t,o){const n=new Set(Zo);for(const[r,i]of Object.entries(e.parameters??{}))this.scanPlainSecretValue(i,[r],e,o+".parameters",n,t);for(const[r,i]of Object.entries(e.metadata??{}))this.scanPlainSecretValue(i,[r],e,o+".metadata",n,t)}scanPlainSecretValue(e,t,o,n,r,i,a=0){const s=t[t.length-1];if(r.has(s))i.push({code:"credential.plain-secret",path:`${n}.${t.join(".")}`,message:`Node '${o.id}' carries plain secret material in '${t.join(".")}'; workflow documents may only hold credential references`,nodeId:o.id});else if(8>a&&null!==e)if(Array.isArray(e))for(const s of e)this.scanPlainSecretValue(s,[...t,"[]"],o,n,r,i,a+1);else if("object"==typeof e)for(const[s,d]of Object.entries(e))this.scanPlainSecretValue(d,[...t,s],o,n,r,i,a+1)}}class vn extends A{constructor(e,t=[]){super(e),this.issues=t,this.name=vn.name}}class In extends A{constructor(e,t){super(e),this.edgeId=t,this.name=In.name}}class En extends U{constructor(e){super(e),this.name=En.name}}const Nn={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},On=["node","definition","executor","execute","ports","component"];function kn(e){if(!e||"object"!=typeof e)return!1;const t=e;return pt(t.document)&&Array.isArray(t.nodes)&&Array.isArray(t.edges)&&t.nodeById instanceof Map&&t.incomingByNode instanceof Map&&t.outgoingByNode instanceof Map&&t.nodes.every(e=>null!==e&&"object"==typeof e&&"object"==typeof e.instance&&"object"==typeof e.manifest&&"object"==typeof e.executor)}function An(e,t){const o=[];for(const n of Object.keys(e))On.includes(n)&&o.push({code:"document.forbidden-field",path:`${t}.${n}`,message:`Field '${n}' is not accepted in a canonical workflow document: node, definition, executor, execute, ports and component fields are rejected`,details:{field:n}});return o}class xn{constructor(e){this.options=e,this.parameterValidator=new en,this.edgeValidator=new yn,this.connectionPolicyValidator=new wn,this.nodeValidator=new gn(e.catalogue),this.credentialValidator=new bn(e.credentialAuthorizer)}async validateOrThrow(e,...t){const o=await this.validate(e,0,...t);if(!o.valid||!o.resolved)throw new vn(`Graph workflow document '${e.id}' failed validation with ${o.issues.length} issue(s)`,o.issues);return o.resolved}async validate(e,t=0,...o){const n=[],r={...Nn,...this.options.limits};if(!await this.validateStructure(e,r,t,n,...o))return{valid:!1,issues:n};const i=await this.nodeValidator.resolveNodes(e.nodes,n,this.options.resolutionContext,...o),a=e.nodes.filter(e=>i.has(e.id)).map(e=>i.get(e.id)),s=(e=>{const t=new Map;for(const o of e.edges??[]){if("data"!==o.type)continue;const e=o.target;if("node"!==e.scope)continue;const n=t.get(e.nodeId)??new Set;n.add(e.port),t.set(e.nodeId,n)}return t})(e);for(const e of a)this.parameterValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`,s.get(e.instance.id));for(const e of a)this.nodeValidator.validateEffectivePorts(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);const d=this.edgeValidator.resolveEdges(e,i,n),l=new Map,c=new Map;for(const e of d){if(e.targetNodeId!==Wt){const t=l.get(e.targetNodeId)??[];t.push(e),l.set(e.targetNodeId,t)}if(e.sourceNodeId!==Wt){const t=c.get(e.sourceNodeId)??[];t.push(e),c.set(e.sourceNodeId,t)}}this.connectionPolicyValidator.validate({edges:d,nodeById:i},n),this.validateAcyclicity(a,d,e,n),mn(e,n);for(const e of a)this.parameterValidator.validateBindingSatisfaction(e.instance,e.manifest,l.get(e.instance.id)??[],n,`nodes[${e.instance.id}]`,{allowLiteralAndEdgeBindings:this.options.allowLiteralAndEdgeBindings});this.validateRequiredWorkflowOutputs(e,c,n);for(const e of a)await this.credentialValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);return this.validateCapabilities(a,n),n.length>0?{valid:!1,issues:n}:{valid:!0,issues:n,resolved:{document:e,nodes:a,edges:d,nodeById:i,incomingByNode:l,outgoingByNode:c}}}async validateStructure(e,t,o,n,...r){if(!pt(e))return n.push({code:"document.shape",path:"$",message:"Payload is not a canonical GraphWorkflowDocument: id and name must be strings and inputs, outputs, nodes and edges must be arrays"}),!1;if(e.id&&e.id.trim()||n.push({code:"document.empty-id",path:"$.id",message:"Workflow document id must be a non-empty string"}),!Ue(e))return n.push({code:"document.json-unsafe",path:"$",message:"Document contains JSON-unsafe values: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys are rejected"}),!1;n.push(...An(e,"$"));for(const t of[...e.inputs,...e.outputs])n.push(...An(t,"ports"));for(const t of e.nodes)n.push(...An(t,`nodes[${t.id}]`));for(const t of e.edges)n.push(...An(t,`edges[${t.id}]`));this.validateUniqueIds(e,n),this.validateLimits(e,t,o,n);try{ot(e)}catch(e){n.push({code:"document.structure",path:"$",message:e instanceof Error?e.message:e+""})}return await this.validateNestedBodies(e,o,n,...r),!0}validateUniqueIds(e,t){const o=new Set,n=new Set;for(const[r,i]of[["input",e.inputs],["output",e.outputs]]){const e="input"===r?o:n;for(const o of i)e.has(o.id)?t.push({code:"document.duplicate-port-id",path:`${"input"===r?"inputs":"outputs"}[${o.id}]`,message:`Workflow ${r} port '${o.id}' is declared more than once; workflow port ids must be unique`}):e.add(o.id)}const r=new Set;for(const o of e.nodes)r.has(o.id)?t.push({code:"document.duplicate-node-id",path:`nodes[${o.id}]`,message:`Node '${o.id}' is declared more than once; node ids must be unique`,nodeId:o.id}):r.add(o.id);const i=new Set;for(const o of e.edges)i.has(o.id)?t.push({code:"document.duplicate-edge-id",path:`edges[${o.id}]`,message:`Edge '${o.id}' is declared more than once; edge ids must be unique`,edgeId:o.id}):i.add(o.id)}validateLimits(e,t,o,n){e.nodes.length>t.maxNodes&&n.push({code:"document.limit.nodes",path:"$.nodes",message:`Document declares ${e.nodes.length} nodes; at most ${t.maxNodes} are allowed`,details:{count:e.nodes.length,limit:t.maxNodes}}),e.edges.length>t.maxEdges&&n.push({code:"document.limit.edges",path:"$.edges",message:`Document declares ${e.edges.length} edges; at most ${t.maxEdges} are allowed`,details:{count:e.edges.length,limit:t.maxEdges}}),o>t.maxNestingDepth&&n.push({code:"document.limit.depth",path:"$",message:`Document nests loop bodies ${o} levels deep; at most ${t.maxNestingDepth} levels are allowed`,details:{depth:o,limit:t.maxNestingDepth}});const r=Buffer.byteLength(JSON.stringify(e),"utf8");r>t.maxDocumentBytes&&n.push({code:"document.limit.size",path:"$",message:`Document serializes to ${r} bytes; at most ${t.maxDocumentBytes} bytes are allowed`,details:{bytes:r,limit:t.maxDocumentBytes}})}async validateNestedBodies(e,t,o,...n){for(const r of e.nodes){const e=[["loop.body",r.loop?.body],["errorBoundary.try",r.errorBoundary?.try],["errorBoundary.catch",r.errorBoundary?.catch],["errorBoundary.finally",r.errorBoundary?.finally]];for(const[i,a]of e){if(!a)continue;const e=await this.validate(a,t+1,...n);for(const t of e.issues)o.push({...t,path:`nodes[${r.id}].${i}.${t.path}`,nodeId:t.nodeId??r.id})}}}validateAcyclicity(e,t,o,n){const r=new Set(e.map(e=>e.instance.id)),i=new Map(e.map(e=>[e.instance.id,0]));for(const e of t)r.has(e.sourceNodeId)&&i.has(e.targetNodeId)&&i.set(e.targetNodeId,(i.get(e.targetNodeId)??0)+1);const a=[...i.entries()].filter(([,e])=>0===e).map(([e])=>e),s=[];for(;a.length>0;){const e=a.shift();s.push(e);for(const o of t){if(o.sourceNodeId!==e)continue;if(!i.has(o.targetNodeId))continue;const t=(i.get(o.targetNodeId)??1)-1;i.set(o.targetNodeId,t),0===t&&a.push(o.targetNodeId)}}if(s.length!==i.size){const e=[...i.keys()].filter(e=>!s.includes(e));n.push({code:"topology.cycle",path:"$.edges",message:`Workflow '${o.id}' contains an unsupported cycle involving node(s): ${e.join(", ")}`,details:{cyclicNodes:e}})}}validateRequiredWorkflowOutputs(e,t,o){const n=new Set;for(const e of t.values())for(const t of e)t.targetNodeId===Wt&&n.add(t.targetPort);for(const t of e.outputs)!0===t.required&&void 0===t.defaultValue&&(n.has(t.id)||o.push({code:"topology.required-output-unsatisfiable",path:`outputs[${t.id}]`,message:`Required workflow output '${t.id}' has no incoming edge from any node`}))}validateCapabilities(e,t){for(const o of e){const e=o.manifest;for(const n of e.capabilities??[])gt(n)||t.push({code:"capability.invalid",path:`nodes[${o.instance.id}]`,message:`Kind '${e.kind}' declares unknown capability '${n+""}'`,nodeId:o.instance.id,details:{capability:n+""}});!0!==e.policies?.allowUndeclaredParameters&&o.instance.loop&&((e.capabilities??[]).includes("loop")||t.push({code:"capability.loop-not-supported",path:`nodes[${o.instance.id}].loop`,message:`Node '${o.instance.id}' carries loop configuration but kind '${e.kind}' does not declare the 'loop' capability`,nodeId:o.instance.id}))}}}let _n=class extends B{constructor(){super()}async plan(e,...t){const{log:o}=(await this.logCtx(t,"plan",!0)).for(this.plan);if(o.debug(`Planning resolved workflow '${e?.document?.id??"unknown"}'`),!kn(e))throw new lo("GraphExecutionPlanner.plan accepts only a GraphResolvedWorkflow produced by the nine-stage validation gate; raw workflow definitions and inline node definitions are rejected",{received:(n=e,n&&"object"==typeof n?{reason:"input is not a GraphResolvedWorkflow",looksLikeWorkflowDefinition:"nodes"in n&&"relations"in n&&!("nodeById"in n),hasResolvedNodes:Array.isArray(n.nodes)}:{reason:"input is not an object"})});var n;const r=this.buildPlanNodes(e),i=this.buildPlanEdges(e),a=this.buildIncomingMap(i),s=this.buildOutgoingMap(i),d=this.topologicalLayers(r,i);return{resolved:e,workflowId:e.document.id||e.document.name,nodes:r,edges:i,layers:d,incomingByNode:a,outgoingByNode:s}}buildPlanNodes(e){return e.nodes.map(e=>({id:e.instance.id,kind:e.manifest.kind,instance:e.instance,manifest:e.manifest,executor:e.executor,inputPorts:e.manifest.inputs.map(e=>e.id),outputPorts:e.manifest.outputs.map(e=>e.id),connectionPorts:(e.manifest.connections??[]).map(e=>e.id),metadata:e.instance.metadata}))}buildPlanEdges(e){return e.edges.map(e=>({id:e.id,type:e.type,sourceNodeId:e.sourceNodeId,sourcePort:e.sourcePort,targetNodeId:e.targetNodeId,targetPort:e.targetPort,...void 0!==e.label?{label:e.label}:{},metadata:e.metadata}))}buildIncomingMap(e){const t=new Map;for(const o of e){if(o.targetNodeId===Wt)continue;const e=t.get(o.targetNodeId)??[];e.push(o),t.set(o.targetNodeId,e)}return t}buildOutgoingMap(e){const t=new Map;for(const o of e){if(o.sourceNodeId===Wt)continue;const e=t.get(o.sourceNodeId)??[];e.push(o),t.set(o.sourceNodeId,e)}return t}topologicalLayers(e,t){const o=e.filter(e=>e.id!==Wt),n=new Set(o.map(e=>e.id)),r=t.filter(e=>n.has(e.sourceNodeId)&&n.has(e.targetNodeId)),i=new Map;for(const e of o)i.set(e.id,0);for(const e of r)i.set(e.targetNodeId,(i.get(e.targetNodeId)??0)+1);const a=[],s=new Set;let d=o.filter(e=>0===(i.get(e.id)??0)),l=0;for(;d.length>0;){const e={index:l++,nodes:d};a.push(e);const t=[];for(const e of d){s.add(e.id);const n=r.filter(t=>t.sourceNodeId===e.id);for(const e of n){const n=(i.get(e.targetNodeId)??1)-1;if(i.set(e.targetNodeId,n),0===n&&!s.has(e.targetNodeId)){const n=o.find(t=>t.id===e.targetNodeId);n&&t.push(n)}}}d=t}if(s.size!==o.length){const e=o.filter(e=>!s.has(e.id)).map(e=>e.id);throw new oo({unplannedNodes:e,workflowId:o[0]?.manifest.kind})}return a}};_n=S([F(),D("design:paramtypes",[])],_n);const Sn=new Set(["engine","valueAdapter","codeSandboxEvaluator","workflowStore"]);function Dn(e,t){const o={};for(const[n,r]of Object.entries(e??{}))Sn.has(n)&&!t.has(n)||(o[n]=r);return o}class Pn extends W{constructor(){super()}async initialize(...e){const t=e[0];if(!t||"object"!=typeof t||!t.registry)return this._config=void 0,this._client=void 0,{config:void 0,client:void 0};const o=t.catalogue??t.registry.catalog,n=t.valueAdapter??q.current;if(!n)throw new to("GraphExecutionEngine requires a Decaf adapter for cached/pinned values: pass `valueAdapter` or configure one via `Adapter.setCurrent(...)`","GRAPH_VALUE_ADAPTER_MISSING");const r=t.backend??Mo.current??new fn,i={registry:t.registry,catalogue:o,planner:t.planner??new _n,backend:r,valueAdapter:n,eventEmitter:t.eventEmitter??new ho,documentValidator:t.documentValidator??new xn({catalogue:o,limits:t.documentLimits,credentialAuthorizer:t.credentialAuthorizer}),authValidator:new So({enabled:!0===t.authEnabled,...t.authMatch?{match:t.authMatch}:{}}),...t.codeSandboxEvaluator?{codeSandboxEvaluator:t.codeSandboxEvaluator}:{}};this._config=t,this._client=i;const a=new Set(["engine","valueAdapter"]);t.codeSandboxEvaluator&&a.add("codeSandboxEvaluator"),t.workflowStore&&a.add("workflowStore");const s=Dn(r.config,a);return await r.initialize({...s,valueAdapter:n,...t.codeSandboxEvaluator?{codeSandboxEvaluator:t.codeSandboxEvaluator}:{},...t.workflowStore?{workflowStore:t.workflowStore}:{},engine:this}),await(t.onEngineCreated?.(this)),{config:t,client:i}}get codeSandboxEvaluator(){return this.client.codeSandboxEvaluator}get emitter(){return this.client.eventEmitter}get planner(){return this.client.planner}get valueAdapter(){return this.client.valueAdapter}get defaultOptions(){return this.config.defaultOptions??{}}get documentValidator(){return this.client.documentValidator}observe(e){return this.emitter.observe(e)}unObserve(e){this.emitter.unObserve(e)}async dispatchEvent(e){await this.emitter.updateObservers(e)}async execute(e,t={},o={},...n){const{log:r,ctx:i}=(await this.logCtx(n,"execute",!0)).for(this.execute);r.debug(`Executing workflow '${e.id||e.name}'`);const a=this.mergeOptions(o);this.assertNotAborted(a);const s=_o(Ao(i),a.auth);a.auth=s,a.metadata={...a.metadata??{},...s};const d=a.runId??this.generateRunId();a.runId=d;const l=a.path??[],c=new fo,u=sn(this.valueAdapter);u.seedWorkflowInputs(this.withWorkflowInputDefaults(e,t));const p=new To(this.emitter,c,{runId:d,parentRunId:a.parentRunId,workflowId:e.id||e.name,path:l,engine:this,...this.codeSandboxEvaluator?{codeSandboxEvaluator:this.codeSandboxEvaluator}:{}});await p.emit({type:ce.VALIDATION_STARTED,status:se.PLANNING});const h=await this.documentValidator.validate(e,0,i);if(!h.valid||!h.resolved)throw await p.emit({type:ce.VALIDATION_FAILED,status:se.FAILED,payload:{issues:h.issues}}),new vn(`Graph workflow document '${e.id}' failed validation with ${h.issues.length} issue(s)`,h.issues);await p.emit({type:ce.VALIDATION_COMPLETED,status:se.PLANNING,payload:{issues:h.issues.length}}),this.assertNotAborted(a);const f=await this.planner.plan(h.resolved);this.client.authValidator.validate(e,f,s,r),r.debug(`Authorized workflow '${e.id||e.name}' for user ${s.user??"anonymous"}`),this.assertCodeModeSupported(e);const g=new $o(d,f,u,c);return p.bindFrame(g),await p.emit({type:ce.WORKFLOW_STARTED,runId:d,parentRunId:a.parentRunId,workflowId:f.workflowId,path:l,status:se.RUNNING,payload:{inputs:t}}),await p.emit({type:ce.WORKFLOW_PLANNED,runId:d,parentRunId:a.parentRunId,workflowId:f.workflowId,path:l,status:se.PLANNING,payload:{layers:f.layers.length,nodes:f.nodes.length}}),await this.client.backend.execute({document:e,plan:f,inputs:t,options:a,events:p},...n)}get backend(){return this.client.backend}get backendCapabilities(){return Lo(this.client.backend)}async listWorkflows(...e){const t=this.client.backend;if("supported"!==Lo(t).workflows.list||"function"!=typeof t.listWorkflows)throw new to(`Graph execution backend '${this.backendName}' does not support workflow listing`,"GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED",{backend:this.backendName});return await t.listWorkflows(...e)}async getWorkflow(e,...t){const o=this.client.backend;if("supported"!==Lo(o).workflows.get||"function"!=typeof o.getWorkflow)throw new to(`Graph execution backend '${this.backendName}' does not support workflow lookup`,"GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED",{backend:this.backendName,workflowId:e});return await o.getWorkflow(e,...t)}async listEngineWorkflows(e,...t){const o=Mo.getOrFail(e);if("supported"!==Lo(o).workflows.list||"function"!=typeof o.listWorkflows)throw new to(`Graph execution backend '${e}' does not support workflow listing`,"GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED",{backend:e});return await o.listWorkflows(...t)}async getEngineWorkflow(e,t,...o){const n=Mo.getOrFail(e);if("supported"!==Lo(n).workflows.get||"function"!=typeof n.getWorkflow)throw new to(`Graph execution backend '${e}' does not support workflow lookup`,"GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED",{backend:e,workflowId:t});return await n.getWorkflow(t,...o)}get backendName(){return this.client.backend.constructor?.name??"GraphExecutionBackend"}assertCodeModeSupported(e){const t=this.client.backend;if(t.local)return;const o=Vo(e);if(0!==o.length){if("unsupported"===t.codeMode)throw new to(`Graph execution backend '${this.backendName}' does not support code-mode workflows`,"GRAPH_CODE_MODE_UNSUPPORTED_BACKEND",{backend:this.backendName,surfaces:o});if(!this.codeSandboxEvaluator)throw new to("Code-mode workflows require a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{backend:this.backendName,surfaces:o})}}async pinNode(e){const t=this.createPinningService();await t.pinNode(e),await this.emitPinningEvent(e.nodeId,ce.NODE_PINNED)}async unpinNode(e){const t=this.createPinningService();await t.unpinNode(e),await this.emitPinningEvent(e.nodeId,ce.NODE_UNPINNED)}createPinningService(){const e=sn(this.valueAdapter);return new ln(e,new pn,new hn)}async emitPinningEvent(e,t){const o=(new fo).create({id:"",sequence:0,timestamp:new Date,runId:"pinning",workflowId:"",type:t,nodeId:e,path:[]});await this.emitter.updateObservers(o)}withWorkflowInputDefaults(e,t){const o={...t};for(const t of e.inputs)void 0===o[t.id]&&void 0!==t.defaultValue&&(o[t.id]=t.defaultValue);return o}mergeOptions(e){return{concurrency:4,failFast:!0,validateInputs:!0,validateOutputs:!0,maxLoopIterations:zt,maxForeachIterations:Jt,usePinnedValues:!0,writeThroughCache:!1,path:[],metadata:{},...this.defaultOptions,...e}}assertNotAborted(e){if(!0===e.abortSignal?.aborted)throw new uo(e.runId??"unknown")}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new to("Cannot generate a graph run id: crypto.randomUUID is unavailable in this runtime","GRAPH_RUN_ID_ERROR",{runtime:typeof globalThis.crypto});return e.randomUUID()}}const Rn=new Set(["process","require","module","exports","global","globalThis","Function","eval","fetch","XMLHttpRequest","WebSocket","Worker","Deno","Bun","__dispatch"]);class $n extends W{constructor(){super()}async initialize(...e){const t=e[0]??{},o=t&&"object"==typeof t?t:{};return this._config=o,this._client=V,{config:o,client:V}}get defaultTimeoutMs(){return this.config.timeoutMs??1e3}get defaultMemoryMb(){return this.config.memoryMb??32}async evaluate(e,...t){(await this.logCtx(t,"evaluate",!0)).for(this.evaluate);const o=e.code;if(!o||"string"!=typeof o||0===o.trim().length)throw new to("Code sandbox received empty code","GRAPH_CODE_SANDBOX_EMPTY_CODE");const n=((e,t)=>"javascript"===t?e:X.transpileModule(e,{compilerOptions:{target:X.ScriptTarget.ES2022,module:X.ModuleKind.None,strict:!0,noEmitHelpers:!0,importHelpers:!1}}).outputText.replace(/^"use strict";\s*/,""))(o,e.language??"javascript");(e=>{if(e.length>1e5)throw new to("Code exceeds the maximum length of 100000 characters","GRAPH_CODE_SANDBOX_CODE_TOO_LONG",{length:e.length});let t;try{t=z.parse(`async function __validate() {\n${e}\n}`,{ecmaVersion:"latest",sourceType:"script"})}catch{try{t=z.parse(e,{ecmaVersion:"latest",sourceType:"module"})}catch(t){throw new to("Code failed to parse: "+t.message,"GRAPH_CODE_SANDBOX_PARSE_ERROR",{code:e,error:t.message})}}J.full(t,e=>{const t=e;if("ImportDeclaration"===t.type)throw new to("Imports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"import"});if("ExportNamedDeclaration"===t.type||"ExportDefaultDeclaration"===t.type)throw new to("Exports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"export"});if("Identifier"===t.type&&"string"==typeof t.name&&Rn.has(t.name))throw new to(`Identifier "${t.name}" is not allowed in Code nodes.`,"GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:t.name});if("NewExpression"===t.type&&"Function"===t.callee?.name)throw new to("new Function() is not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"Function"});if("CallExpression"===t.type&&"eval"===t.callee?.name)throw new to("eval() is not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"eval"})})})(n);const r=!(e=>/\breturn\b[\s;]/.test(e))(n),i=r?n.replace(/[\s;]+$/,""):n,a={$input:e.input??{},$vars:e.vars??{},$item:e.item,$index:e.index,$node:e.nodes??{},$output:void 0},s=Object.keys(a),d=r?`return (${i});`:i,l=`"use strict";\nasync function __userFunction(${s.join(", ")}) {\n${d}\n}\n__userFunction(${s.join(", ")}).then(function(__r) { return JSON.stringify({ v: __r }); });`,c=new V.Isolate({memoryLimit:this.defaultMemoryMb}),u=await c.createContext();try{const t=u.global;e.logger&&await this.injectConsole(u,e.logger);for(const[e,o]of Object.entries(a))await t.set(e,new V.ExternalCopy(void 0===o?null:o).copyInto());let o;try{o=await c.compileScript(l,{filename:"graph-code-node.js"})}catch(e){if(!r)throw new to("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message});{const e=i,t=`"use strict";\nasync function __userFunction(${s.join(", ")}) {\n${e}\n}\n__userFunction(${s.join(", ")}).then(function(__r) { return JSON.stringify({ v: __r }); });`;try{o=await c.compileScript(t,{filename:"graph-code-node.js"})}catch(e){throw new to("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message})}}}const d=e.timeoutMs??this.defaultTimeoutMs;let p;try{p=await this.runBounded(o,u,d,e.abortSignal)}catch(e){if(e instanceof to)throw e;const t=e.message;if(t.includes("timed out")||t.includes("timeout"))throw new to(`Code execution timed out after ${d} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:d});if(t.includes("memory")||t.includes("heap"))throw new to(`Code exceeded the memory limit of ${this.defaultMemoryMb} MB`,"GRAPH_CODE_SANDBOX_MEMORY_LIMIT",{memoryMb:this.defaultMemoryMb});throw new to("Code execution failed: "+t,"GRAPH_CODE_SANDBOX_RUNTIME_ERROR",{code:n,error:t})}if("string"!=typeof p)throw new to("Code sandbox returned an unexpected non-string result","GRAPH_CODE_SANDBOX_UNEXPECTED_RESULT",{result:p});return JSON.parse(p).v}finally{u.release(),c.dispose()}}async runBounded(e,t,o,n){const r=e.run(t,{timeout:o,promise:!0});r.catch(()=>{});const i=[r];let a,s;try{return i.push(new Promise((e,t)=>{a=setTimeout(()=>{t(new to(`Code execution timed out after ${o} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:o}))},o+100)})),n&&i.push(new Promise((e,t)=>{const r=()=>{const e="timeout"===n.reason;t(new to(e?`Code execution timed out after ${o} ms`:"Code execution aborted",e?"GRAPH_CODE_SANDBOX_TIMEOUT":"GRAPH_CODE_SANDBOX_ABORTED",{timeoutMs:o,reason:n.reason}))};n.aborted?r():(n.addEventListener("abort",r,{once:!0}),s=()=>n.removeEventListener("abort",r))})),await Promise.race(i)}finally{a&&clearTimeout(a),s?.()}}async injectConsole(e,t){const o=new V.Reference((e,o)=>{let n;try{n=JSON.parse(o)}catch{n=[o]}const r=n.map(e=>"string"==typeof e?e:JSON.stringify(e)).join(" "),i=1===n.length?n[0]:n;switch(e){case"log":case"info":default:t.info(r,i);break;case"warn":t.warn(r,i);break;case"error":t.error(r,i);break;case"debug":case"dir":case"dirxml":case"table":t.debug(r,i);break;case"trace":t.trace(r,i);break;case"group":case"groupCollapsed":t.debug("[group] "+r,i);break;case"groupEnd":t.debug("[groupEnd]",void 0);break;case"time":case"timeEnd":case"timeLog":case"count":case"countReset":t.debug(`[${e}] ${r}`,i);break;case"assert":n[0]||t.error("Assertion failed: "+r,i);case"clear":}});await e.evalClosure("\n function __ser() {\n var out = [];\n for (var i = 0; i < arguments.length; i++) {\n var a = arguments[i];\n try { out.push(typeof a === 'object' ? JSON.parse(JSON.stringify(a)) : a); }\n catch (e) { out.push(String(a)); }\n }\n return JSON.stringify(out);\n }\n function __call(level) {\n return function() {\n $0.applySync(undefined, [level, __ser.apply(null, arguments)]);\n };\n }\n globalThis.console = {\n log: __call('log'),\n info: __call('info'),\n warn: __call('warn'),\n error: __call('error'),\n debug: __call('debug'),\n trace: __call('trace'),\n dir: __call('dir'),\n dirxml: __call('dirxml'),\n table: __call('table'),\n group: __call('group'),\n groupCollapsed: __call('groupCollapsed'),\n groupEnd: __call('groupEnd'),\n time: __call('time'),\n timeEnd: __call('timeEnd'),\n timeLog: __call('timeLog'),\n assert: __call('assert'),\n count: __call('count'),\n countReset: __call('countReset'),\n clear: __call('clear')\n };\n ",[o]),o.release()}}class Cn extends x{constructor(e){super(e,Cn.name,500)}}class Tn extends _{constructor(e){super(e),this.name=Tn.name}}class Ln extends _{constructor(e){super(e),this.name=Ln.name}}class Mn{constructor(e,t,o={}){this.kind=e,this.declarations=new Map,this.implementations=new Map;for(const e of t){if("string"!=typeof e?.name||!e.name)throw new Cn(`Method declaration for kind '${this.kind}' is missing a name`);if(this.declarations.has(e.name))throw new Cn(`Kind '${this.kind}' declares duplicate method '${e.name}'`);this.declarations.set(e.name,e)}for(const[e,t]of Object.entries(o)){if("function"!=typeof t)throw new Cn(`Method implementation '${e}' for kind '${this.kind}' is not a function`);if(!this.declarations.has(e))throw new Cn(`Kind '${this.kind}' implements method '${e}' which is not declared by its manifest`);this.implementations.set(e,t)}for(const e of this.declarations.keys())if(!this.implementations.has(e))throw new Cn(`Kind '${this.kind}' declares method '${e}' with no implementation`)}has(e){return this.declarations.has(e)}getDeclaration(e){const t=this.declarations.get(e);if(!t)throw new Ln(`Kind '${this.kind}' does not declare method '${e}'`);return t}get(e){return this.getDeclaration(e),this.implementations.get(e)}list(){return[...this.declarations.values()].sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}}function jn(e,t){if(!t)return;let o=e;for(const e of t.split(".")){if(!o||"object"!=typeof o)return;o=o[e]}return o}function Gn(e,t,o){const n=jn(t,e.itemIdPath),r=e.itemLabelPath?jn(t,e.itemLabelPath):void 0;return{id:"string"==typeof n&&n||"number"==typeof n&&Number.isFinite(n)&&n+""||o+"",label:"string"==typeof r?r:void 0}}function Un(e,t){switch(t){case"input":return e.inputs;case"output":return e.outputs;default:return e.connections}}function Fn(e,t){const o={inputs:[],outputs:[],connections:[]},n={input:new Set((e.inputs??[]).map(e=>e.id)),output:new Set((e.outputs??[]).map(e=>e.id)),connection:new Set((e.connections??[]).map(e=>e.id))},r=(e,t)=>{const o=n[e];return!o.has(t)&&(o.add(t),!0)};for(const n of e.dynamicPorts??[])if("repeatFromParameter"===n.type){const e=t[n.parameter];if(!Array.isArray(e))continue;const i=Un(o,n.direction);e.forEach((e,t)=>{const{id:o,label:a}=Gn(n,e,t),s=(d={id:o,index:t,label:a??o},n.portIdTemplate.replaceAll("${id}",d.id).replaceAll("${index}",d.index+"").replaceAll("${label}",d.label));var d;if(!r(n.direction,s))return;const l=n.defaultPort?Fe(n.defaultPort):{id:s,label:a??s,direction:n.direction};l.id=s,l.direction=n.direction,a&&(l.label=a),i.push(l)})}else if("togglePort"===n.type){if(t[n.parameter]!==n.equals)continue;const e=Fe(n.port);if(!r(e.direction,e.id))continue;Un(o,e.direction).push(e)}return o}function Bn(e,t){const o=Fn(e,t),n={kind:e.kind,display:e.display,inputs:[...e.inputs,...o.inputs],outputs:[...e.outputs,...o.outputs],parameters:e.parameters},r=[...e.connections??[],...o.connections];return r.length&&(n.connections=r),e.dynamicPorts?.length&&(n.dynamicPorts=e.dynamicPorts),e.credentials?.length&&(n.credentials=e.credentials),e.capabilities?.length&&(n.capabilities=e.capabilities),e.policies&&(n.policies=e.policies),e.metadata&&(n.metadata=e.metadata),e.namespaces?.length&&(n.namespaces=e.namespaces),Fe(n)}class Wn{async resolve(e,t,o,n,r){if(o){const i=await o(n,r);if(!(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.kind&&"object"==typeof t.display&&null!==t.display&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.parameters)})(i))throw new Cn(`resolveManifest provider for kind '${e}' returned a value that does not conform to GraphResolvedNodeManifest`);if(!Ue(i))throw new Cn(`resolveManifest provider for kind '${e}' returned a non-JSON-safe resolved manifest`);const a=Fe(i);return!a.namespaces?.length&&t.namespaces?.length&&(a.namespaces=t.namespaces.slice()),a}return Bn(t,n.parameters??{})}}const qn=["edge","literal","expression"];function Hn(e){return qn.includes(e)}function Kn(e,t,o){if("string"!=typeof o||!o)throw new Cn(`Manifest for kind '${e}' has a ${t} with an empty port id`);if(Le(o))throw new Cn(`Manifest for kind '${e}' has a ${t} with unsafe port id '${o}'`)}let Vn=class extends B{constructor(){super(),this.entries=new Map,this.resolver=new Wn,this.fallbackContext=new M}withContext(e){return e[e.length-1]instanceof M?e:[this.fallbackContext]}register(e,t={},...o){const{log:n}=this.logCtx(this.withContext(o),"register").for(this.register);n.debug(`Registering graph node kind '${e?.manifest?.kind??"unknown"}'`),(e=>{if(!e||"object"!=typeof e)throw new Cn("Graph node registration is required");if(!e.manifest||"object"!=typeof e.manifest)throw new Cn("Graph node registration is missing a manifest");if(!e.executor||"function"!=typeof e.executor.execute)throw new Cn(`Graph node registration for kind '${e.manifest?.kind+""}' is missing an executor`)})(e);const r=e.manifest;if("string"!=typeof r.kind||!r.kind.trim())throw new Cn("Graph node manifest kind is required and must be a non-empty string");const i=r.kind;if(this.entries.has(i)&&!t.replace)throw new Cn(`Graph node kind '${i}' is already registered; pass { replace: true } to replace it`);try{mt(r)}catch(e){throw new Cn(`Manifest for kind '${i}' is not JSON-serializable: ${e.message}`)}((e,t)=>{const o=[["input",t.inputs],["output",t.outputs],["connection",t.connections??[]]];for(const[t,n]of o){const o=new Set;for(const r of n){if(Kn(e,t+" port",r?.id),o.has(r.id))throw new Cn(`Manifest for kind '${e}' declares duplicate static ${t} port id '${r.id}'`);if(o.add(r.id),void 0!==r.defaultMode&&!Hn(r.defaultMode))throw new Cn(`Manifest for kind '${e}' declares invalid default binding mode '${r.defaultMode+""}' on ${t} port '${r.id}'`)}}})(i,r);const a=((e,t)=>{const o=new Set;for(const n of t.parameters){const t=n?.id;if("string"!=typeof t||!t)throw new Cn(`Manifest for kind '${e}' has a parameter with an empty id`);if(Le(t))throw new Cn(`Manifest for kind '${e}' has a parameter with unsafe id '${t}'`);if(o.has(t))throw new Cn(`Manifest for kind '${e}' declares duplicate parameter id '${t}'`);o.add(t)}return o})(i,r);((e,t,o)=>{for(const n of t.dynamicPorts??[]){if(!n||"string"!=typeof n.parameter||!n.parameter)throw new Cn(`Manifest for kind '${e}' has a dynamic-port rule without a parameter reference`);if(!o.has(n.parameter))throw new Cn(`Manifest for kind '${e}' has a dynamic-port rule referencing missing parameter '${n.parameter}'`);if("togglePort"===n.type){if(!n.port)throw new Cn(`Manifest for kind '${e}' has a togglePort rule without a port`);Kn(e,"togglePort rule port",n.port.id)}if("repeatFromParameter"===n.type&&"string"!=typeof n.portIdTemplate)throw new Cn(`Manifest for kind '${e}' has a repeatFromParameter rule without a portIdTemplate`)}})(i,r,a),((e,t)=>{for(const o of t.credentials??[]){if(!ht(o))throw new Cn(`Manifest for kind '${e}' has a malformed credential requirement`);if(!o.type)throw new Cn(`Manifest for kind '${e}' has a credential requirement with an empty type`)}})(i,r),((e,t)=>{for(const o of t.methods??[])if(!wt(o))throw new Cn(`Manifest for kind '${e}' has a malformed method declaration`)})(i,r);const s=new Mn(i,r.methods??[],e.methods??{});return this.entries.set(i,{registration:e,methods:s,placeholderManifest:!1}),this}registerExecutor(e,t,...o){const{log:n}=this.logCtx(this.withContext(o),"registerExecutor").for(this.registerExecutor);if(n.debug(`Registering graph executor for kind '${e}'`),"string"!=typeof e||!e.trim())throw new Cn("Graph executor kind is required");if(!t||"function"!=typeof t.execute)throw new Cn(`Executor registered for kind '${e}' is missing an execute method`);const r=this.entries.get(e);if(r)return r.registration={...r.registration,executor:t},this;const i={kind:e,display:{name:e},inputs:[],outputs:[],parameters:[],policies:{allowUndeclaredParameters:!0,allowUnknownOutputs:!0}};return this.entries.set(e,{registration:{manifest:i,executor:t},methods:new Mn(e,[],{}),placeholderManifest:!0}),this}unregister(e,...t){const{log:o}=this.logCtx(this.withContext(t),"unregister").for(this.unregister);return o.debug(`Unregistering graph node kind '${e}'`),this.entries.delete(e),this}has(e,...t){return this.logCtx(this.withContext(t),"has").for(this.has),this.entries.has(e)}entry(e){const t=this.entries.get(e);if(!t)throw new Tn(`No graph node kind '${e}' is registered in the catalogue`);return t}getManifest(e,...t){return this.logCtx(this.withContext(t),"getManifest").for(this.getManifest),Fe(this.entry(e).registration.manifest)}getExecutor(e,...t){return this.logCtx(this.withContext(t),"getExecutor").for(this.getExecutor),this.entry(e).registration.executor}getMethodDeclaration(e,t,...o){return this.logCtx(this.withContext(o),"getMethodDeclaration").for(this.getMethodDeclaration),this.entry(e).methods.getDeclaration(t)}getMethod(e,t,...o){return this.logCtx(this.withContext(o),"getMethod").for(this.getMethod),this.entry(e).methods.getDeclaration(t),this.entry(e).methods.get(t)}listMethodDeclarations(e,...t){return this.logCtx(this.withContext(t),"listMethodDeclarations").for(this.listMethodDeclarations),this.entry(e).methods.list()}listManifests(e,...t){this.logCtx(this.withContext(t),"listManifests").for(this.listManifests);const o=[...this.entries.keys()].sort(),n=e?.categories?.length?new Set(e.categories):void 0,r=e?.kinds?.length?new Set(e.kinds):void 0,i=[];for(const e of o){if(r&&!r.has(e))continue;const o=this.getManifest(e,...t);n&&!n.has(o.display.category??"")||i.push(o)}return i}listKinds(...e){return this.logCtx(this.withContext(e),"listKinds").for(this.listKinds),[...this.entries.keys()].sort()}get size(){return this.entries.size}async resolveManifest(e,t,o,...n){this.logCtx(this.withContext(n),"resolveManifest").for(this.resolveManifest);const r=this.entry(e);return this.resolver.resolve(e,r.registration.manifest,r.registration.resolveManifest,t,o)}};Vn=S([F(),D("design:paramtypes",[])],Vn);let zn=class extends B{constructor(e=new Vn){super(),this.catalogue=e}get catalog(){return this.catalogue}register(e,t,...o){const{log:n}=this.logCtx(o,"register").for(this.register);if(n.debug(`Registering graph executor for kind '${e}'`),!e)throw new to("Graph executor kind is required");return this.catalogue.registerExecutor(e,t,...o),this}unregister(e,...t){const{log:o}=this.logCtx(t,"unregister").for(this.unregister);return o.debug(`Unregistering graph executor for kind '${e}'`),this.catalogue.unregister(e,...t),this}has(e,...t){return this.logCtx(t,"has").for(this.has),this.catalogue.has(e,...t)}resolve(e,...t){this.logCtx(t,"resolve").for(this.resolve);try{return this.catalogue.getExecutor(e,...t)}catch(t){if(t instanceof Tn)throw new to(`No graph executor registered for kind '${e}'`,"GRAPH_EXECUTOR_NOT_FOUND",{kind:e});throw t}}};zn=S([F(),D("design:paramtypes",[Vn])],zn);let Jn=class extends B{constructor(e,t){super(),this.registry=e,this.defaultExecutor=t}resolve(e,...t){const{log:o}=this.logCtx(t,"resolve").for(this.resolve);return o.debug(`Resolving graph executor for kind '${e}'`),this.registry.has(e,...t)?this.registry.resolve(e,...t):this.defaultExecutor?this.defaultExecutor:this.registry.resolve(e,...t)}};function Xn(e){return e}function Yn(e){return e.methods??[]}function Qn(e){if(!e)return;const t={...e.metadata??{},...e.parameters??{},...e.state??{}};return e.loop&&(t.loop=e.loop),t}Jn=S([F(),D("design:paramtypes",[Function,Object])],Jn);class Zn extends w{constructor(e){super(),w.fromModel(this,e)}execute(e,t){throw new to(`Graph node kind '${this.constructor.name}' does not implement execute`,"GRAPH_NODE_EXECUTE_NOT_IMPLEMENTED",{kind:this.constructor.name})}static applyMetadata(e){return null}static instantiate(e){return new this(e)}}let er=class extends Zn{execute(e,t){throw new co(e.inputs.value)}};function tr(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack,code:e.graphCode??("number"==typeof e.code?e.code+"":e.code)}:{name:"UnknownError",message:e+""}}S([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.break.fields.value.label",placeholder:"graph.node.flow_control.break.fields.value.placeholder",type:"textarea"}),Re({handle:"value"}),D("design:type",Object)],er.prototype,"value",void 0),er=S([De("core.flow.break",{kind:"core.flow.break",category:"Flow Control",color:"#f59e0b",icon:"ti-square-arrow-right",width:96,height:96,labels:["flow","break","loop","control"],metadata:{title:"graph.node.flow_control.break.name",description:"graph.node.flow_control.break.description"}}),E()],er);let or=class extends Zn{async execute(e,t){const o=t.node.errorBoundary;if(!o?.try)return{result:e.inputs.value??e.inputs};const n=t.engine;if(!n)throw new to("errorBoundary node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");try{const r=await n.execute(o.try,e.inputs,{parentRunId:t.runId,path:[...t.path,"try"]}),i=Object.values(r.nodeResults).find(e=>e.status===se.FAILED);if(i)throw new to(i.error?.message??"error boundary try body failed",i.error?.code??"GRAPH_ERROR_BOUNDARY",i.error?.details);return{result:r.outputs.result??r.outputs}}catch(r){let i=r;if(o.catch){const a=await n.execute(o.catch,{...e.inputs,error:tr(r)},{parentRunId:t.runId,path:[...t.path,"catch"]});i=a.outputs.error??a.outputs}return{error:i}}finally{o.finally&&await n.execute(o.finally,e.inputs,{parentRunId:t.runId,path:[...t.path,"finally"]})}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.error_boundary.fields.value.label",placeholder:"graph.node.flow_control.error_boundary.fields.value.placeholder",type:"textarea"}),Re({handle:"value"}),D("design:type",Object)],or.prototype,"value",void 0),S([$e({handle:"result"}),D("design:type",Object)],or.prototype,"result",void 0),S([$e({handle:"error"}),D("design:type",Object)],or.prototype,"error",void 0),or=S([De("core.flow.errorBoundary",{kind:"core.flow.errorBoundary",category:"Flow Control",color:"#f59e0b",icon:"ti-shield-check",width:96,height:96,labels:["flow","error","try-catch"],metadata:{title:"graph.node.flow_control.error_boundary.name",description:"graph.node.flow_control.error_boundary.description",finally:!1}}),E()],or);let nr=class extends Zn{execute(e){const t=e.inputs.value??e.inputs;return!1===this.approved?{rejected:t}:{approved:t}}};S([b(),Re({handle:"value"}),D("design:type",Object)],nr.prototype,"value",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.human_approval.fields.message.label",placeholder:"graph.node.flow_control.human_approval.fields.message.placeholder",type:"textarea"}),Re({handle:"message",userControlled:!0}),D("design:type",String)],nr.prototype,"message",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.human_approval.fields.approved.label",type:"checkbox"}),Re({handle:"approved",userControlled:!0}),D("design:type",Boolean)],nr.prototype,"approved",void 0),S([$e({handle:"approved"}),D("design:type",Object)],nr.prototype,"approvedOut",void 0),S([$e({handle:"rejected"}),D("design:type",Object)],nr.prototype,"rejectedOut",void 0),nr=S([De("core.flow.humanApproval",{kind:"core.flow.humanApproval",category:"Flow Control",color:"#f59e0b",icon:"ti-user-check",width:96,height:96,labels:["flow","approval","suspend"],metadata:{title:"graph.node.flow_control.human_approval.name",description:"graph.node.flow_control.human_approval.description",approvers:[],timeoutMs:864e5}}),E()],nr);let rr=class extends Zn{execute(e,t){const o=e.inputs,n=o.value??o;if(!this.condition)throw new to("If node has no condition configured","GRAPH_IF_NO_CONDITION",{input:o});if(Go(this.condition))return Fo(this.condition,o,t).then(e=>this.route(e,n));const r=Bo(this.condition,((e,t)=>t===e||"object"!=typeof t||null===t||Array.isArray(t)?e:{...t,...e})(o,n),"if");return this.route(r,n)}route(e,t){if(e)return{then:t};if(!0===this.else)return{else:t};throw new to("If node condition evaluated to false and the else branch is disabled","GRAPH_IF_ELSE_DISABLED",{condition:this.condition})}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.value.label",placeholder:"graph.node.flow_control.if.fields.value.placeholder",type:"textarea"}),Re({handle:"value"}),D("design:type",Object)],rr.prototype,"value",void 0),S([b(),$e({handle:"then"}),D("design:type",Object)],rr.prototype,"then",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.condition.label",placeholder:"graph.node.flow_control.if.fields.condition.placeholder",type:"code"}),Re({handle:"condition",userControlled:!0,type:"object"}),D("design:type",Object)],rr.prototype,"condition",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.else.label",type:"checkbox"}),Re({handle:"else",userControlled:!0}),D("design:type",Boolean)],rr.prototype,"else",void 0),rr=S([De("core.flow.if",{kind:"core.flow.if",category:"Flow Control",color:"#f59e0b",icon:"ti-arrows-split-2",width:96,height:96,labels:["flow","conditional","branch"],metadata:{title:"graph.node.flow_control.if.name",description:"graph.node.flow_control.if.description"}}),E()],rr);let ir=class extends Zn{async execute(e,t){const o=((e,t)=>{const o={cases:t.cases??[],defaultPort:t.defaultPort??"default",hasDefault:!0===t.hasDefault},n=e.node.metadata?.switch;return n&&Array.isArray(n.cases)?{cases:n.cases,defaultPort:n.defaultPort??o.defaultPort,hasDefault:!0===n.hasDefault||o.hasDefault}:o})(t,this),n=o.cases,r=e.inputs,i=r.value??r,a=((e,t)=>t===e||"object"!=typeof t||null===t||Array.isArray(t)?e:{...t,...e})(r,i);for(const e of n)if(await Wo(e.condition,{input:r,state:a,label:"switch case"},t))return{[e.outputPort]:i};if(!0!==o.hasDefault)throw new to("No switch case matched and default port is not enabled","GRAPH_SWITCH_NO_MATCH",{cases:n.map(e=>e.id)});const s=o.defaultPort??"default";return{[s]:i}}static applyMetadata(e){const t=xe(this),o=e.defaultPort??"default",n=!0===e.hasDefault,r=t.ports.filter(t=>!e.cases.some(e=>e.outputPort===t.property)),i=r.filter(e=>e.property!==o),a=r.find(e=>e.property===o),s=[...i,...e.cases.map(e=>({property:e.outputPort,name:e.label,direction:Z.OUTPUT,label:e.label,required:!1,hidden:!1,path:e.outputPort}))];return n&&a&&s.push(a),{ports:s,size:te(t,{cases:e.cases.length}),dataPatch:{switchMetadata:e}}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.value.label",placeholder:"graph.node.flow_control.switch.fields.value.placeholder",type:"textarea"}),Re({handle:"value"}),D("design:type",Object)],ir.prototype,"value",void 0),S([b(),$e({handle:"default"}),D("design:type",Object)],ir.prototype,"default",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.cases.label",type:"collection"}),D("design:type",Object)],ir.prototype,"cases",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.hasDefault.label",type:"checkbox"}),D("design:type",Boolean)],ir.prototype,"hasDefault",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.defaultPort.label",type:"text"}),D("design:type",String)],ir.prototype,"defaultPort",void 0),ir=S([De("core.flow.switch",{kind:"core.flow.switch",category:"Flow Control",color:"#f59e0b",icon:"ti-arrows-shuffle",width:120,height:140,sizeRules:[{type:"parameterCount",parameter:"cases",dimension:"height",perItem:24}],labels:["flow","switch","multi-branch"],metadata:{title:"graph.node.flow_control.switch.name",description:"graph.node.flow_control.switch.description"}}),E()],ir);const ar={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},sr=o.accumulate({graph:{workflows:{limits:{...ar},allowAnonymousAccess:!1},execution:{maxCodeTimeoutMs:Xt}}}),dr=1e3;function lr(e,t){const o="number"==typeof t?t:Number(t),n=Number.isFinite(o)&&o>0?o:Xt,r="number"==typeof e?e:Number(e);return Number.isFinite(r)&&r>0?Math.min(Math.floor(r),n):1e3}const cr=["javascript","typescript"],ur="javascript";let pr=class extends w{constructor(){super(...arguments),this.language=ur}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.language.label",type:"select"}),N([...cr]),v(String),D("design:type",String)],pr.prototype,"language",void 0),S([b(),i("code-editor",{label:"graph.node.utility.code.fields.code.label",placeholder:"graph.node.utility.code.fields.code.placeholder"}),Re({handle:"code"}),D("design:type",String)],pr.prototype,"code",void 0),S([d(),Re({handle:"data"}),D("design:type",Object)],pr.prototype,"data",void 0),pr=S([E()],pr);let hr=class extends Zn{async execute(e,t){const o=e.inputs,n=this.input,r=o.code??e.parameters?.code??n?.code??this.defaultCode,i=n?.language??ur;if(!r||"string"!=typeof r||0===r.trim().length)throw new no("Code node has no code to execute (input.code is empty)",{input:o});const a=t.engine?.codeSandboxEvaluator;if(!a)throw new to("Code node execution requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{code:r});const s=sr.graph.execution?.maxCodeTimeoutMs,d="number"==typeof s&&Number.isFinite(s)&&s>0?s:Xt,l=lr(this.timeoutMs,d),c=t.metadata,u={code:r,language:i,input:o,vars:c?.vars??void 0,item:c?.item,index:c?.index,nodes:c?.nodes??void 0,logger:t.logger,timeoutMs:l,abortSignal:t.abortSignal};await t.log("Executing code node",{language:i,length:r.length,timeoutMs:l});const p=await a.evaluate(u);return await t.log("Code node executed",{hasResult:void 0!==p}),{result:p}}};S([b(),Re({handle:"input",model:pr}),D("design:type",pr)],hr.prototype,"input",void 0),S([O(1),k(Xt),i("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.timeoutMs.label",type:"number"}),Re({handle:"timeoutMs"}),D("design:type",Number)],hr.prototype,"timeoutMs",void 0),S([i("code-editor",{label:"graph.node.utility.code.fields.defaultCode.label",placeholder:"graph.node.utility.code.fields.defaultCode.placeholder"}),Re({handle:"defaultCode",userControlled:!0}),D("design:type",String)],hr.prototype,"defaultCode",void 0),S([b(),$e({handle:"result"}),D("design:type",Object)],hr.prototype,"result",void 0),hr=S([De("core.utility.code",{kind:"core.utility.code",category:"Utility",color:"#0d9488",icon:"ti-code",width:96,height:96,labels:["utility","code","sandbox","transform"],metadata:{title:"graph.node.utility.code.name",description:"graph.node.utility.code.description"}}),E()],hr);let fr=class extends Zn{execute(e){return{value:e.inputs.value??e.inputs}}};S([b(),Re({handle:"value"}),D("design:type",Object)],fr.prototype,"value",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.utility.delay.fields.timeoutMs.label",type:"number"}),Re({handle:"timeoutMs"}),D("design:type",Number)],fr.prototype,"timeoutMs",void 0),S([b(),$e({handle:"value"}),D("design:type",Object)],fr.prototype,"valueOut",void 0),fr=S([De("core.flow.delay",{kind:"core.flow.delay",category:"Utility",color:"#0d9488",icon:"ti-clock-hour-4",width:96,height:96,labels:["flow","delay","wait"],metadata:{title:"graph.node.utility.delay.name",description:"graph.node.utility.delay.description"}}),E()],fr);let gr=class extends Zn{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}};S([b(),Re({handle:"value"}),D("design:type",Object)],gr.prototype,"value",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.message.label",placeholder:"graph.node.utility.log.fields.message.placeholder",type:"textarea"}),Re({handle:"message"}),D("design:type",String)],gr.prototype,"message",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.level.label",placeholder:"graph.node.utility.log.fields.level.placeholder",type:"text"}),Re({handle:"level",userControlled:!0}),D("design:type",String)],gr.prototype,"level",void 0),S([b(),$e({handle:"value"}),D("design:type",Object)],gr.prototype,"valueOut",void 0),gr=S([De("core.flow.log",{kind:"core.flow.log",category:"Utility",color:"#0d9488",icon:"ti-terminal",width:96,height:96,labels:["flow","log","debug","utility"],metadata:{title:"graph.node.utility.log.name",description:"graph.node.utility.log.description"}}),E()],gr);let mr=class extends Zn{execute(e){return{result:{mapped:e.inputs.value??e.inputs}}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.utility.map.fields.value.label",placeholder:"graph.node.utility.map.fields.value.placeholder",type:"textarea"}),Re({handle:"value"}),D("design:type",Object)],mr.prototype,"value",void 0),S([b(),$e({handle:"result"}),D("design:type",Object)],mr.prototype,"result",void 0),mr=S([De("core.utility.map",{kind:"core.utility.map",category:"Utility",color:"#0d9488",icon:"ti-arrows-right-left",width:96,height:96,labels:["utility","map","transform"],metadata:{title:"graph.node.utility.map.name",description:"graph.node.utility.map.description",mapper:{}}}),E()],mr);let yr=class extends Zn{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}};S([b(),Re({handle:"value"}),D("design:type",Object)],yr.prototype,"value",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.message.label",placeholder:"graph.node.utility.utility_log.fields.message.placeholder",type:"textarea"}),Re({handle:"message"}),D("design:type",String)],yr.prototype,"message",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.level.label",placeholder:"graph.node.utility.utility_log.fields.level.placeholder"}),Re({handle:"level",userControlled:!0,type:"string"}),D("design:type",String)],yr.prototype,"level",void 0),S([b(),$e({handle:"value"}),D("design:type",Object)],yr.prototype,"valueOut",void 0),yr=S([De("core.utility.log",{kind:"core.utility.log",category:"Utility",color:"#0d9488",icon:"ti-terminal",width:96,height:96,labels:["utility","log","debug","observability"],metadata:{title:"graph.node.utility.utility_log.name",description:"graph.node.utility.utility_log.description"}}),E()],yr);let wr=class extends Zn{execute(e){return{message:e.inputs.message??null,sessionId:e.inputs.sessionId??null,userId:e.inputs.userId??null}}};S([b(),$e({handle:"message"}),D("design:type",String)],wr.prototype,"message",void 0),S([b(),$e({handle:"sessionId"}),D("design:type",String)],wr.prototype,"sessionId",void 0),S([b(),$e({handle:"userId"}),D("design:type",String)],wr.prototype,"userId",void 0),wr=S([De("core.trigger.chat",{kind:"core.trigger.chat",category:"Trigger",color:"#3b82f6",icon:"ti-message-circle",width:96,height:96,labels:["trigger","chat","entrypoint"],metadata:{title:"graph.node.trigger.chat.name",description:"graph.node.trigger.chat.description",trigger:{type:"chat"}}}),E()],wr);let br=class extends Zn{execute(e){return{payload:e.inputs.payload??null}}};S([b(),$e({handle:"payload"}),D("design:type",Object)],br.prototype,"payload",void 0),br=S([De("core.trigger.event",{kind:"core.trigger.event",category:"Trigger",color:"#3b82f6",icon:"ti-broadcast",width:96,height:96,labels:["trigger","event","bus"],metadata:{title:"graph.node.trigger.event.name",description:"graph.node.trigger.event.description",trigger:{type:"event",topic:"default"}}}),E()],br);let vr=class extends Zn{execute(e){return{payload:e.inputs.payload??null}}};S([b(),Re({handle:"schema"}),i("ngx-decaf-model-builder",{label:"graph.node.trigger.form.fields.schema.label",placeholder:"graph.node.trigger.form.fields.schema.placeholder"}),D("design:type",Object)],vr.prototype,"schema",void 0),S([b(),$e({handle:"payload"}),D("design:type",Object)],vr.prototype,"payload",void 0),vr=S([De("core.trigger.form",{kind:"core.trigger.form",category:"Trigger",color:"#3b82f6",icon:"ti-forms",width:96,height:96,labels:["trigger","form","public"],metadata:{title:"graph.node.trigger.form.name",description:"graph.node.trigger.form.description",trigger:{type:"form",fields:[]}}}),E()],vr);let Ir=class extends Zn{execute(e){return{payload:e.inputs.payload??null}}};S([b(),$e({handle:"payload"}),D("design:type",Object)],Ir.prototype,"payload",void 0),Ir=S([De("core.trigger.manual",{kind:"core.trigger.manual",category:"Trigger",color:"#3b82f6",icon:"ti-hand-click",width:96,height:96,labels:["trigger","manual","entrypoint"],metadata:{title:"graph.node.trigger.manual.name",description:"graph.node.trigger.manual.description",trigger:{type:"manual",inputSchema:{}}}}),E()],Ir);let Er=class extends Zn{execute(e){return{payload:e.inputs.payload??null}}};S([b(),Re({handle:"cron"}),i("app-cron-selector-field",{label:"graph.node.trigger.schedule.fields.cron.label",placeholder:"graph.node.trigger.schedule.fields.cron.placeholder"}),D("design:type",String)],Er.prototype,"cron",void 0),S([b(),$e({handle:"payload"}),D("design:type",Object)],Er.prototype,"payload",void 0),Er=S([De("core.trigger.schedule",{kind:"core.trigger.schedule",category:"Trigger",color:"#3b82f6",icon:"ti-calendar-time",width:96,height:96,labels:["trigger","schedule","cron"],metadata:{title:"graph.node.trigger.schedule.name",description:"graph.node.trigger.schedule.description",trigger:{type:"schedule",schedule:"0 * * * *",timezone:"UTC"}}}),E()],Er);let Nr=class extends Zn{execute(e){return{payload:e.inputs.payload??null}}};S([b(),Re({handle:"schema"}),i("ngx-decaf-model-builder",{label:"graph.node.trigger.webhook.fields.schema.label",placeholder:"graph.node.trigger.webhook.fields.schema.placeholder"}),D("design:type",Object)],Nr.prototype,"schema",void 0),S([b(),$e({handle:"payload"}),D("design:type",Object)],Nr.prototype,"payload",void 0),Nr=S([De("core.trigger.webhook",{kind:"core.trigger.webhook",category:"Trigger",color:"#3b82f6",icon:"ti-webhook",width:96,height:96,labels:["trigger","webhook","http"],metadata:{title:"graph.node.trigger.webhook.name",description:"graph.node.trigger.webhook.description",trigger:{type:"webhook",path:"/webhook",method:"POST",auth:"none",responseMode:"onReceived"}}}),E()],Nr);let Or=class extends Zn{execute(e){return{response:"[Agent response] "+(e.inputs.prompt??""),actions:[]}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.agent.agent.fields.prompt.label",placeholder:"graph.node.agent.agent.fields.prompt.placeholder",type:"textarea"}),Re({handle:"prompt"}),D("design:type",String)],Or.prototype,"prompt",void 0),S([b(),$e({handle:"response"}),D("design:type",String)],Or.prototype,"response",void 0),S([b(),$e({handle:"actions"}),D("design:type",Array)],Or.prototype,"actions",void 0),S([Ce({category:"model",handle:"model"}),D("design:type",Object)],Or.prototype,"model",void 0),S([Ce({category:"memory",handle:"memory"}),D("design:type",Object)],Or.prototype,"memory",void 0),S([Ce({category:"workspace",handle:"workspace"}),D("design:type",Object)],Or.prototype,"workspace",void 0),Or=S([De("core.agent",{kind:"core.agent",category:"Agent",width:140,height:120,labels:["agent","ai","orchestrator"],metadata:{title:"graph.node.agent.agent.name",description:"graph.node.agent.agent.description",shape:"rectangle"}}),E()],Or);const kr=[Or];function Ar(e,t,o,n){const r=t??o;if(null==e)return Math.min(o,r);const i=Number(e);if(!Number.isFinite(i)||0>=i)throw new no(n+" loop maxIterations must be a positive finite number");return Math.min(Math.floor(i),r)}function xr(e,t,o){const n=t.node.loop,r=t.metadata?.loop;if(!n?.body&&!r?.body)throw new no(o+" node is missing loop configuration (instance.loop.body)");const i=t=>{const o=e[t]??n?.[t]??r?.[t],i=Number(o);return void 0!==o&&Number.isFinite(i)?i:void 0},a=t=>{const o=e[t]??r?.[t];return"string"==typeof o?o:void 0};return{body:n?.body??r?.body,maxIterations:i("maxIterations"),timeoutMs:i("timeoutMs"),concurrency:i("concurrency"),condition:e.condition??r?.condition,inputPort:a("inputPort"),outputPort:a("outputPort"),itemPort:a("itemPort"),resultPort:a("resultPort"),statePort:a("statePort"),slice:i("slice")}}let _r=class extends Zn{async execute(e,t){const o=xr(this,t,"foreach"),n=e.inputs,r=n.items,i=Ar(o.maxIterations,t.limits?.maxForeachIterations,1e3,"foreach");if(!Array.isArray(r))throw new no("foreach input 'items' must be an array");const a=t.engine;if(!a)throw new to("foreach node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");const s=Number(n.slice??o.slice??1),d=Number.isFinite(s)&&s>0?Math.floor(s):1,l=d>1?Math.ceil(r.length/d):r.length;if(l>i)throw new ro(`foreach exceeded max iterations (${l} > ${i})`);const c=o.itemPort??"item",u=o.resultPort??"result",p=o.statePort??"state",h=o.body,f=[];let g=n.state,m=!1;await t.emit({type:ce.LOOP_STARTED});for(let e=0;l>e;e++){await t.emit({type:ce.LOOP_ITERATION_STARTED,iteration:e});const o=d>1?r.slice(e*d,e*d+d):r[e],n={[c]:o,index:e};d>1&&(n.slice=o),void 0!==g&&(n[p]=g);try{const r=await a.execute(h,n,{parentRunId:t.runId,path:[...t.path,"iteration:"+e],metadata:{item:o,index:e,slice:d},auth:t.auth},t);f.push(r.outputs[u]),void 0!==r.outputs[p]&&(g=r.outputs[p])}catch(o){if(o instanceof co){const n=o.details?.value;void 0!==n&&f.push(n),m=!0,await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:e,metadata:{broken:!0}});break}throw o}await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:e})}await t.emit({type:ce.LOOP_COMPLETED,metadata:{broken:m}});const y={results:f,completed:f,iterations:f.length,broken:m};return void 0!==g&&(y[p]=g),y}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.items.label",placeholder:"graph.node.loop.foreach.fields.items.placeholder",type:"textarea"}),Re({handle:"items"}),D("design:type",Array)],_r.prototype,"items",void 0),S([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.slice.label",placeholder:"graph.node.loop.foreach.fields.slice.placeholder",type:"number"}),Re({handle:"slice"}),D("design:type",Number)],_r.prototype,"slice",void 0),S([b(),$e({handle:"item"}),D("design:type",Object)],_r.prototype,"item",void 0),S([b(),Ce({handle:"loop",connectionRules:{allowSelf:!0,maxConnections:1}}),D("design:type",Object)],_r.prototype,"loop",void 0),S([b(),$e({handle:"completed"}),D("design:type",Array)],_r.prototype,"completed",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.maxIterations.label",type:"number"}),Re({handle:"maxIterations",userControlled:!0}),D("design:type",Number)],_r.prototype,"maxIterations",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.condition.label",type:"code"}),Re({handle:"condition",userControlled:!0}),D("design:type",Object)],_r.prototype,"condition",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.itemPort.label",type:"text"}),Re({handle:"itemPort",userControlled:!0}),D("design:type",String)],_r.prototype,"itemPort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.resultPort.label",type:"text"}),Re({handle:"resultPort",userControlled:!0}),D("design:type",String)],_r.prototype,"resultPort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.statePort.label",type:"text"}),Re({handle:"statePort",userControlled:!0}),D("design:type",String)],_r.prototype,"statePort",void 0),_r=S([De("graph-foreach-loop-node",{kind:"core.loop.foreach",category:"Loop",color:"#eab308",icon:"ti-repeat",width:120,height:140,labels:["loop","iteration","foreach"],metadata:{title:"graph.node.loop.foreach.name",description:"graph.node.loop.foreach.description",loop:{maxIterations:100,itemPort:"item",resultPort:"result",slice:1}}}),E()],_r);class Sr{constructor(){this.expressionEvaluator=new jo}evaluate(e,t){if(this.isConditionExpression(e))return this.expressionEvaluator.evaluate(e,t);const o=this.resolveValue(e.left,t),n=e.right;switch(e.type){case Zt.TRUTHY:return!!o;case Zt.FALSY:return!o;case Zt.EQUALS:return o===n;case Zt.NOT_EQUALS:return o!==n;case Zt.GREATER_THAN:return Number(o)>Number(n);case Zt.GREATER_THAN_OR_EQUAL:return Number(o)>=Number(n);case Zt.LESS_THAN:return Number(n)>Number(o);case Zt.LESS_THAN_OR_EQUAL:return Number(n)>=Number(o);case Zt.EXISTS:return null!=o;case Zt.CUSTOM:throw new to("Custom condition evaluators are not supported in v1","GRAPH_CUSTOM_CONDITION_UNSUPPORTED");default:throw new to(`Unknown condition type '${e.type}'`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition:e})}}async evaluateAsync(e,t,o,n){return Go(e)?Fo(e,n,o):this.evaluate(e,t)}resolveValue(e,t){if(!e)return t;const o=e.split(".");let n=t;for(const e of o){if(null==n)return;n=n[e]}return n}isConditionExpression(e){return"string"==typeof e.op}}let Dr=class extends Zn{async execute(e,t){const o=xr(this,t,"until"),n=e.inputs,r=Ar(o.maxIterations,t.limits?.maxLoopIterations,100,"until"),i=o.condition;if(!i)throw new no("until node is missing a condition");const a=o.statePort??"state",s=o.inputPort??a,d=o.outputPort??a,l=o.body,c=t.engine;if(!c)throw new to("until node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;await t.emit({type:ce.LOOP_STARTED});let h=!1;do{if(p>=r)throw await t.emit({type:ce.LOOP_LIMIT_REACHED,iteration:p}),new ro(`until loop exceeded max iterations (${r})`);await t.emit({type:ce.LOOP_ITERATION_STARTED,iteration:p}),u=(await c.execute(l,{[s]:u,iteration:p},{parentRunId:t.runId,path:[...t.path,"iteration:"+p],auth:t.auth},t)).outputs[d],await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:p});const e=await(new Sr).evaluateAsync(i,u,t,{...n,state:u});await t.emit({type:ce.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:e}}),p++,h=e}while(!h);return await t.emit({type:ce.LOOP_COMPLETED}),{state:u,iterations:p}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.state.label",placeholder:"graph.node.loop.until.fields.state.placeholder",type:"textarea"}),Re({handle:"state"}),D("design:type",Object)],Dr.prototype,"state",void 0),S([b(),$e({handle:"state"}),D("design:type",Object)],Dr.prototype,"stateOut",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.maxIterations.label",type:"number"}),Re({handle:"maxIterations",userControlled:!0}),D("design:type",Number)],Dr.prototype,"maxIterations",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.condition.label",type:"code"}),Re({handle:"condition",userControlled:!0}),D("design:type",Object)],Dr.prototype,"condition",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.statePort.label",type:"text"}),Re({handle:"statePort",userControlled:!0}),D("design:type",String)],Dr.prototype,"statePort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.inputPort.label",type:"text"}),Re({handle:"inputPort",userControlled:!0}),D("design:type",String)],Dr.prototype,"inputPort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.outputPort.label",type:"text"}),Re({handle:"outputPort",userControlled:!0}),D("design:type",String)],Dr.prototype,"outputPort",void 0),Dr=S([De("graph-until-loop-node",{kind:"core.loop.until",category:"Loop",color:"#eab308",icon:"ti-player-stop",width:96,height:96,labels:["loop","conditional","until"],metadata:{title:"graph.node.loop.until.name",description:"graph.node.loop.until.description",loop:{maxIterations:50,statePort:"state",condition:{type:"greaterThanOrEqual",left:"iteration",right:2}}}}),E()],Dr);let Pr=class extends Zn{async execute(e,t){const o=xr(this,t,"while"),n=e.inputs,r=Ar(o.maxIterations,t.limits?.maxLoopIterations,100,"while"),i=o.condition;if(!i)throw new no("while node is missing a condition");const a=o.statePort??"state",s=o.inputPort??a,d=o.outputPort??a,l=o.body,c=t.engine;if(!c)throw new to("while node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;for(await t.emit({type:ce.LOOP_STARTED});await(new Sr).evaluateAsync(i,u,t,{...n,state:u});){if(p>=r)throw await t.emit({type:ce.LOOP_LIMIT_REACHED,iteration:p}),new ro(`while loop exceeded max iterations (${r})`);await t.emit({type:ce.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:!0}}),await t.emit({type:ce.LOOP_ITERATION_STARTED,iteration:p}),u=(await c.execute(l,{[s]:u,iteration:p},{parentRunId:t.runId,path:[...t.path,"iteration:"+p],auth:t.auth},t)).outputs[d],await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:p}),p++}return await t.emit({type:ce.LOOP_COMPLETED}),{state:u,iterations:p}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.state.label",placeholder:"graph.node.loop.while.fields.state.placeholder",type:"textarea"}),Re({handle:"state"}),D("design:type",Object)],Pr.prototype,"state",void 0),S([b(),$e({handle:"state"}),D("design:type",Object)],Pr.prototype,"stateOut",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.maxIterations.label",type:"number"}),Re({handle:"maxIterations",userControlled:!0}),D("design:type",Number)],Pr.prototype,"maxIterations",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.condition.label",type:"code"}),Re({handle:"condition",userControlled:!0}),D("design:type",Object)],Pr.prototype,"condition",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.statePort.label",type:"text"}),Re({handle:"statePort",userControlled:!0}),D("design:type",String)],Pr.prototype,"statePort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.inputPort.label",type:"text"}),Re({handle:"inputPort",userControlled:!0}),D("design:type",String)],Pr.prototype,"inputPort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.outputPort.label",type:"text"}),Re({handle:"outputPort",userControlled:!0}),D("design:type",String)],Pr.prototype,"outputPort",void 0),Pr=S([De("graph-while-loop-node",{kind:"core.loop.while",category:"Loop",color:"#eab308",icon:"ti-arrows-loop",width:96,height:96,labels:["loop","conditional","while"],metadata:{title:"graph.node.loop.while.name",description:"graph.node.loop.while.description",loop:{maxIterations:50,statePort:"state",condition:{type:"lessThan",left:"iteration",right:3}}}}),E()],Pr);let Rr=class extends Zn{execute(e){const t=e.inputs;return{value:t?.value??null}}};S([$e({handle:"value",connectionRules:{allowMultiple:!0}}),D("design:type",Object)],Rr.prototype,"value",void 0),Rr=S([De("graph-input-value-node",{kind:"value",category:"Boundary",color:"#0f766e",icon:"ti-circle-plus",labels:["workflow","input","value"],metadata:{title:"graph.node.boundary.input.name",description:"graph.node.boundary.input.description"}}),E()],Rr);let $r=class extends Zn{execute(e){return{}}};function Cr(e,t,o,n={}){return{id:e,label:t,direction:o,...n}}function Tr(e){const t=e,o=ve(t),n=o?.metadata?.title;return Tt(t,n?{name:n}:{})}S([b(),Re({handle:"value"}),D("design:type",Object)],$r.prototype,"value",void 0),$r=S([De("graph-output-value-node",{kind:"result",category:"Boundary",color:"#0f766e",icon:"ti-circle-minus",width:96,height:96,labels:["workflow","output","value"],metadata:{title:"graph.node.boundary.output.name",description:"graph.node.boundary.output.description"}}),E()],$r);const Lr={kind:"core.loop.foreach",capabilities:["loop"],display:{name:"graph.node.loop.foreach.name",description:"graph.node.loop.foreach.description",category:"Loop",color:"#eab308",icon:{type:"catalogue",name:"ti-repeat"},width:120,height:140,labels:["loop","iteration","foreach"]},inputs:[Cr("items","graph.node.loop.foreach.ports.input.items.label","input",{required:!0,schema:{type:"array",items:{type:"any"}}}),Cr("slice","graph.node.loop.foreach.ports.input.slice.label","input",{schema:{type:"number",integer:!0,min:1}}),Cr("state","graph.node.loop.foreach.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[Cr("results","graph.node.loop.foreach.ports.output.results.label","output",{schema:{type:"array",items:{type:"any"}}}),Cr("completed","graph.node.loop.foreach.ports.output.completed.label","output",{schema:{type:"array",items:{type:"any"}}}),Cr("iterations","graph.node.loop.foreach.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}}),Cr("broken","graph.node.loop.foreach.ports.output.broken.label","output",{schema:{type:"boolean"}}),Cr("state","graph.node.loop.foreach.ports.output.state.label","output",{schema:{type:"any"}})],parameters:[{type:"number",id:"maxIterations",label:"graph.node.loop.foreach.fields.maxIterations.label",integer:!0,min:1},{type:"object",id:"condition",label:"graph.node.loop.foreach.fields.condition.label"},{type:"string",id:"itemPort",label:"graph.node.loop.foreach.fields.itemPort.label"},{type:"string",id:"resultPort",label:"graph.node.loop.foreach.fields.resultPort.label"},{type:"string",id:"statePort",label:"graph.node.loop.foreach.fields.statePort.label"},{type:"number",id:"slice",label:"graph.node.loop.foreach.fields.slice.label",integer:!0,min:1}]},Mr={kind:"core.loop.while",capabilities:["loop"],display:{name:"graph.node.loop.while.name",description:"graph.node.loop.while.description",category:"Loop",color:"#eab308",icon:{type:"catalogue",name:"ti-arrows-loop"},width:120,height:140,labels:["loop","conditional","while"]},inputs:[Cr("state","graph.node.loop.while.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[Cr("state","graph.node.loop.while.ports.output.state.label","output",{schema:{type:"any"}}),Cr("iterations","graph.node.loop.while.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}})],parameters:[{type:"number",id:"maxIterations",label:"graph.node.loop.while.fields.maxIterations.label",integer:!0,min:1},{type:"object",id:"condition",label:"graph.node.loop.while.fields.condition.label",required:!0},{type:"string",id:"statePort",label:"graph.node.loop.while.fields.statePort.label"},{type:"string",id:"inputPort",label:"graph.node.loop.while.fields.inputPort.label"},{type:"string",id:"outputPort",label:"graph.node.loop.while.fields.outputPort.label"}]},jr={kind:"core.loop.until",capabilities:["loop"],display:{name:"graph.node.loop.until.name",description:"graph.node.loop.until.description",category:"Loop",color:"#eab308",icon:{type:"catalogue",name:"ti-player-stop"},width:120,height:140,labels:["loop","conditional","until"]},inputs:[Cr("state","graph.node.loop.until.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[Cr("state","graph.node.loop.until.ports.output.state.label","output",{schema:{type:"any"}}),Cr("iterations","graph.node.loop.until.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}})],parameters:[{type:"number",id:"maxIterations",label:"graph.node.loop.until.fields.maxIterations.label",integer:!0,min:1},{type:"object",id:"condition",label:"graph.node.loop.until.fields.condition.label",required:!0},{type:"string",id:"statePort",label:"graph.node.loop.until.fields.statePort.label"},{type:"string",id:"inputPort",label:"graph.node.loop.until.fields.inputPort.label"},{type:"string",id:"outputPort",label:"graph.node.loop.until.fields.outputPort.label"}]},Gr=[Tr(Rr),Tr($r),Tr(Ir),Tr(Nr),Tr(Er),Tr(br),Tr(vr),Tr(wr),(Ur=Tr(rr),{...Ur,dynamicPorts:[{type:"togglePort",parameter:"else",equals:!0,port:{id:"else",label:"graph.node.flow_control.if.ports.output.else.label",direction:"output",schema:{type:"any"}}}]}),(e=>({...e,outputs:[],parameters:[...e.parameters,{type:"collection",id:"cases",label:"graph.node.flow_control.switch.fields.cases.label",required:!0,itemIdPath:"outputPort",itemLabelPath:"label"},{type:"boolean",id:"hasDefault",label:"graph.node.flow_control.switch.fields.hasDefault.label",defaultValue:!1},{type:"object",id:"switch",label:"graph.node.flow_control.switch.fields.switch.label",required:!1}],dynamicPorts:[{type:"repeatFromParameter",parameter:"cases",itemIdPath:"outputPort",itemLabelPath:"label",direction:"output",portIdTemplate:"${id}",defaultPort:{id:"case",label:"graph.node.flow_control.switch.ports.output.case.label",direction:"output",schema:{type:"any"}}},{type:"togglePort",parameter:"hasDefault",equals:!0,port:{id:"default",label:"graph.node.flow_control.switch.ports.output.default.label",direction:"output",schema:{type:"any"}}}]}))(Tr(ir)),Tr(mr),Tr(fr),Tr(or),Tr(nr),Tr(hr),Tr(gr),Tr(yr),Tr(er),Tr(Or),Lr,Mr,jr];var Ur;const Fr=Object.fromEntries(Gr.map(e=>[e.kind,e])),Br=[Ir,Nr,Er,br,vr,wr],Wr=[rr,ir,fr,or,nr,gr,er],qr=[hr,mr,yr],Hr=[_r,Pr,Dr],Kr=[Rr,$r],Vr={value:Rr,result:$r,"core.trigger.manual":Ir,"core.trigger.webhook":Nr,"core.trigger.schedule":Er,"core.trigger.event":br,"core.trigger.form":vr,"core.trigger.chat":wr,"core.flow.if":rr,"core.flow.switch":ir,"core.utility.map":mr,"core.flow.delay":fr,"core.flow.errorBoundary":or,"core.flow.humanApproval":nr,"core.utility.code":hr,"core.flow.log":gr,"core.utility.log":yr,"core.flow.break":er,"core.agent":Or,"core.loop.foreach":_r,"core.loop.while":Pr,"core.loop.until":Dr};function zr(e){return{execute:(t,o)=>e.instantiate({...Qn(o.node),...t.parameters,...o.node.state??{}}).execute(t,o)}}function Jr(){const e=[];for(const[t,o]of Object.entries(Fr)){const n=Vr[t];n&&e.push(Xn({manifest:o,executor:zr(n)}))}return e}function Xr(e,...t){for(const o of Jr())e.register(o,{},...t);return e}class Yr{resolve(e){const t=this.createValidator(e);return{name:e.name,required:e.required,validate:t}}resolveAll(e){const t={};for(const o of e)t[o.name]=this.resolve(o);return t}createValidator(e){switch((e.type??e.designType??"").toLowerCase()){case"string":return e=>"string"==typeof e;case"number":return e=>"number"==typeof e;case"boolean":return e=>"boolean"==typeof e;case"date":return e=>e instanceof Date||"string"==typeof e&&!isNaN(Date.parse(e));case"array":return e=>Array.isArray(e);case"bigint":return e=>"bigint"==typeof e;default:return()=>!0}}}class Qr{constructor(e){this.resolver=e}validateWorkflowInputs(e,t){this.validatePorts(e.inputs,t,"workflow input")}validateWorkflowOutputs(e,t){this.validatePorts(e.outputs,t,"workflow output")}validateNodeInputs(e,t){const o=(e.ports??[]).filter(e=>"input"===e.direction);this.validatePorts(o,t,`node '${e.name}' input`)}validateNodeOutputs(e,t){const o=(e.ports??[]).filter(e=>"output"===e.direction);this.validatePorts(o,t,`node '${e.name}' output`)}validatePorts(e,t,o){if(e)for(const n of e){const e=Object.prototype.hasOwnProperty.call(t,n.name);if(n.required&&!e)throw new no(`Missing required ${o} port '${n.name}'`);if(e&&!this.resolver.resolve(n).validate(t[n.name]))throw new no(`Invalid value for ${o} port '${n.name}'`)}}}const Zr=["node","definition","executor","execute","ports","component"];function ei(e,t,o,n){return{code:e,path:t,message:o,...void 0!==n?.nodeId?{nodeId:n.nodeId}:{},...void 0!==n?.edgeId?{edgeId:n.edgeId}:{},...n?.details?{details:n.details}:{}}}function ti(e,t){const o=[];for(const n of Object.keys(e))Zr.includes(n)&&o.push(ei("document.forbidden-field",`${t}.${n}`,`Field '${n}' is not accepted in a canonical workflow document: node, definition, executor, execute, ports and component fields are rejected at the boundary`,{details:{field:n}}));return o}function oi(e,t){t.push(...ti(e,"$")),e.inputs.forEach((e,o)=>t.push(...ti(e,`inputs[${o}]`))),e.outputs.forEach((e,o)=>t.push(...ti(e,`outputs[${o}]`)));for(const o of e.nodes)t.push(...ti(o,`nodes[${o.id}]`)),o.loop&&(t.push(...ti(o.loop,`nodes[${o.id}].loop`)),oi(o.loop.body,t));for(const o of e.edges)t.push(...ti(o,`edges[${o.id}]`))}function ni(e,t){const o=[];e.nodes.length>t.maxNodes&&o.push(ei("document.limit.nodes","$.nodes",`Document declares ${e.nodes.length} nodes; at most ${t.maxNodes} are allowed`,{details:{count:e.nodes.length,limit:t.maxNodes}})),e.edges.length>t.maxEdges&&o.push(ei("document.limit.edges","$.edges",`Document declares ${e.edges.length} edges; at most ${t.maxEdges} are allowed`,{details:{count:e.edges.length,limit:t.maxEdges}}));const n=ri(e);n>t.maxNestingDepth&&o.push(ei("document.limit.depth","$.nodes",`Document nests loop bodies ${n} levels deep; at most ${t.maxNestingDepth} levels are allowed`,{details:{depth:n,limit:t.maxNestingDepth}}));const r=Buffer.byteLength(JSON.stringify(e),"utf8");return r>t.maxDocumentBytes&&o.push(ei("document.limit.size","$",`Document serializes to ${r} bytes; at most ${t.maxDocumentBytes} bytes are allowed`,{details:{bytes:r,limit:t.maxDocumentBytes}})),o}function ri(e,t=0){let o=t;for(const n of e.nodes)n.loop?.body&&(o=Math.max(o,ri(n.loop.body,t+1)));return o}async function ii(e,t,...o){const n=[];for(const r of e.nodes)t.has(r.kind,...o)||n.push(ei("node.unknown-kind",`nodes[${r.id}].kind`,`Node '${r.id}' references kind '${r.kind}' which is not registered in the backend catalogue`,{nodeId:r.id,details:{kind:r.kind}})),r.loop?.body&&n.push(...await ii(r.loop.body,t,...o));return n}async function ai(e,t={},...o){const n={...ar,...t.limits},r=[];if(!pt(e))return r.push(ei("document.shape","$","Payload is not a canonical GraphWorkflowDocument: id and name must be strings and inputs, outputs, nodes and edges must be arrays")),{valid:!1,issues:r};if(!Ue(e))return r.push(ei("document.json-unsafe","$","Document contains JSON-unsafe values: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys (__proto__/prototype/constructor) are rejected")),{valid:!1,issues:r};oi(e,r),r.push(...(e=>{const t=[],o=new Set;for(const n of[...e.inputs,...e.outputs])o.has(n.id)?t.push(ei("document.duplicate-port-id",`ports[${n.id}]`,`Workflow port '${n.id}' is declared more than once; workflow port ids must be unique`)):o.add(n.id);const n=new Set;for(const o of e.nodes)n.has(o.id)?t.push(ei("document.duplicate-node-id",`nodes[${o.id}]`,`Node '${o.id}' is declared more than once; node ids must be unique`,{nodeId:o.id})):n.add(o.id);const r=new Set;for(const o of e.edges)r.has(o.id)?t.push(ei("document.duplicate-edge-id",`edges[${o.id}]`,`Edge '${o.id}' is declared more than once; edge ids must be unique`,{edgeId:o.id})):r.add(o.id);return t})(e)),r.push(...ni(e,n)),mn(e,r);try{ot(e)}catch(e){const t=e instanceof A?e.message:e+"";r.push(ei("document.structure","$",t))}return t.catalogue&&r.push(...await ii(e,t.catalogue,...o)),{valid:0===r.length,issues:r}}class si{constructor(e,t){this.iteration=e,this.metadata=t}}function di(e,t,o={}){const n=e?.owner??null;return!n||n===t||(null==t||""===t)&&!0===o.allowAnonymousAccess}function li(e,t){return(e?.owner??null)===(t??null)}function ci(e,t,o){if(!li(e,t))throw new L(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function ui(e,t,o){if(!di(e,t,o))throw new L(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function pi(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>pi(e)).join(",")}]`;const t=e;return`{${Object.keys(t).filter(e=>void 0!==t[e]).sort().map(e=>`${JSON.stringify(e)}:${pi(t[e])}`).join(",")}}`}function hi(e){return Y("sha256").update(pi(e)).digest("hex")}class fi{constructor(e={}){this.events=new Map,this.listeners=new Map,this.limits={...ue,...e}}async append(e){let t=this.events.get(e.runId);t||(t=[],this.events.set(e.runId,t)),t.push(e),this.enforceRetention(t);for(const t of this.listeners.get(e.runId)??[])try{t(e)}catch{}}async listAfter(e,t){const o=this.events.get(e);return o?o.filter(e=>e.sequence>t):[]}subscribe(e,t){let o=this.listeners.get(e);return o||(o=new Set,this.listeners.set(e,o)),o.add(t),()=>{o.delete(t),0===o.size&&this.listeners.delete(e)}}release(e){this.events.delete(e),this.listeners.delete(e)}enforceRetention(e){const t=this.limits.maxEventsPerRun;for(;e.length>t;){const t=e.findIndex(e=>!he(e.type));if(-1===t)break;e.splice(t,1)}}}function gi(e){return new jt({runId:e.runId,workflowId:e.workflowId,...e.ownerUser?{owner:e.ownerUser}:{},status:e.status,...e.documentFingerprint?{documentFingerprint:e.documentFingerprint}:{},...void 0!==e.result?{result:mi(e.result)}:{},...e.error?{error:mi(e.error)}:{},createdAt:new Date(e.createdAt),...e.startedAt?{startedAt:new Date(e.startedAt)}:{},...e.finishedAt?{finishedAt:new Date(e.finishedAt)}:{}})}function mi(e){if(null!=e)return JSON.parse(JSON.stringify(e))}class yi{constructor(){this.runs=new Map}async saveRun(e){this.runs.set(e.runId,{...e})}async readRun(e){const t=this.runs.get(e);return t?{...t}:null}async listRuns(e){return[...this.runs.values()].filter(t=>t.workflowId===e).map(e=>gi(e))}release(e){this.runs.delete(e)}}class wi{constructor(e,t={}){this.sequences=new Map,this.chains=new Map,this.store=e,this.limits={...ue,...t}}async publish(e){const t=e.runId,o=(this.sequences.get(t)??0)+1;this.sequences.set(t,o);const n={...e,payload:this.limitPayload(e.payload),sequence:o,timestamp:(new Date).toISOString()},r=(this.chains.get(t)??Promise.resolve()).then(()=>this.store.append(n));return this.chains.set(t,r.catch(()=>{})),await r,n}lastSequence(e){return this.sequences.get(e)??0}release(e){this.sequences.delete(e),this.chains.delete(e)}limitPayload(e){if(void 0===e)return;let t;try{t=JSON.stringify(e)}catch{return{nonSerializable:!0}}return t.length>this.limits.maxEventPayloadBytes?{truncated:!0,reason:"event payload exceeds the configured byte limit",bytes:t.length}:e}}class bi{constructor(e,t,o,n={},r={}){this.controllers=new Map,this.completions=new Map,this.timeouts=new Map,this.engine=e,this.runStore=t,this.publisher=o,this.hooks=n,this.limits={...ue,...r}}begin(e){const t=this.controllers.get(e);if(t)return t;const o=new AbortController;return this.controllers.set(e,o),o}abort(e,t){const o=this.controllers.get(e);return!!o&&(o.signal.aborted||o.abort(t),!0)}isAborted(e){return!0===this.controllers.get(e)?.signal.aborted}abortReason(e){const t=this.controllers.get(e)?.signal;if(t?.aborted)return"timeout"===t.reason?"timeout":"user"}waitFor(e){return this.completions.get(e)}schedule(e,t,o,...n){const r=this.completions.get(e.runId);if(r)return r;const i=this.runExecution({...e},t,o,...n).catch(async t=>{const o=vi(t);try{await this.emitTerminal({...e},ce.WORKFLOW_FAILED,o)}catch{}return await this.finalize({...e},"failed",void 0,o,...n)});return this.completions.set(e.runId,i),i}release(e){this.controllers.delete(e),this.completions.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.publisher.release(e)}armTimeout(e){const t=setTimeout(()=>{this.timeouts.delete(e),this.abort(e,"timeout")},this.limits.executionTimeoutMs);this.timeouts.set(e,t)}async runExecution(e,t,o,...n){const r=e.runId;let i,a,s=!1;const d=this.engine.observe({refresh:async t=>{t.runId===r&&(t.error&&(i=t.error),he((await this.publisher.publish(this.envelopeOf(e,t))).type)?s=!0:t.type===ce.WORKFLOW_STARTED&&"validating"===e.status&&(e.status="running",await this.persist(e,...n)))}});this.armTimeout(r);try{if(this.isAborted(r)){const t={name:"GraphRunCancelledError",message:`Graph run '${r}' was cancelled before execution started`,code:"GRAPH_RUN_CANCELLED"};return i=t,await this.emitTerminal(e,ce.WORKFLOW_CANCELLED,t),s=!0,await this.finalize(e,"cancelled",void 0,t,...n)}let d,l;e.status="validating",e.startedAt=(new Date).toISOString(),await this.persist(e,...n);try{({document:d,fingerprint:l}=await t(...n)),e.documentFingerprint=l,await this.persist(e,...n)}catch(t){const o=vi(t);return i=o,s||(await this.emitTerminal(e,ce.WORKFLOW_FAILED,o),s=!0),await this.finalize(e,"failed",void 0,o,...n)}if(this.isAborted(r)){const t={name:"GraphRunCancelledError",message:`Graph run '${r}' was cancelled before execution started`,code:"GRAPH_RUN_CANCELLED"};return i=t,s||(await this.emitTerminal(e,ce.WORKFLOW_CANCELLED,t),s=!0),await this.finalize(e,"cancelled",void 0,t,...n)}try{a=await this.engine.execute(d,o,{runId:r,abortSignal:this.controllers.get(r)?.signal,metadata:{documentFingerprint:l}},...n)}catch(e){i=vi(e)}const c=this.abortReason(r);let u,p;return"timeout"===c?(u="failed",p=i??{name:"GraphRunTimeoutError",message:`Graph run '${r}' exceeded the configured execution timeout of ${this.limits.executionTimeoutMs}ms`,code:"GRAPH_RUN_TIMEOUT"}):"user"===c?(u="cancelled",p=i):a?.status===se.SUCCEEDED?u="succeeded":a?.status===se.CANCELLED?(u="cancelled",p=i):(u="failed",p=i??vi(new to(a?`Graph run '${r}' failed`:`Graph run '${r}' failed without a result`,"GRAPH_RUN_FAILED",{runId:r}))),s||await this.emitTerminal(e,"succeeded"===u?ce.WORKFLOW_COMPLETED:"cancelled"===u?ce.WORKFLOW_CANCELLED:ce.WORKFLOW_FAILED,p),await this.finalize(e,u,a,p,...n)}finally{d();const e=this.timeouts.get(r);e&&(clearTimeout(e),this.timeouts.delete(r))}}async emitTerminal(e,t,o){await this.publisher.publish({runId:e.runId,workflowId:e.workflowId,type:t,error:o})}async finalize(e,t,o,n,...r){e.status=t,o&&(e.result=o),n&&(e.error=n),e.startedAt||(e.startedAt=(new Date).toISOString()),e.finishedAt=(new Date).toISOString(),await this.persist(e,...r);try{await(this.hooks.onRunCompleted?.(e,o))}catch{}return e}async persist(e,...t){await this.runStore.saveRun({...e},...t)}envelopeOf(e,t){return{runId:e.runId,workflowId:t.workflowId??e.workflowId,type:t.type,nodeId:t.nodeId,edgeId:t.edgeId,payload:void 0===t.payload?void 0:Ge(t.payload)?t.payload:{nonSerializable:!0},error:t.error,parentRunId:t.parentRunId,path:t.path}}}function vi(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack,code:e.graphCode??("number"==typeof e.code?e.code+"":e.code)}:{name:"UnknownError",message:e+""}}class Ii{constructor(e,t,o,n={}){this.activeByCaller=new Map,this.callerKeysByRun=new Map,this.releaseTimers=new Map,this.engine=e,this.runStore=t,this.eventStore=o,this.publisher=new wi(o,n.limits),this.executor=new bi(e,t,this.publisher,{onRunCompleted:n.onRunCompleted},n.limits),this.options={...n,limits:{...ue,...n.limits}}}get limits(){return this.options.limits}async createRun(e,t,o,...n){this.validateCreateRequest(e);const r=e.workflowId??e.workflow?.id??"";if(!r)throw new A("Graph run request must carry a workflow document with an id or a saved workflowId");if(e.workflowId&&!this.options.documentResolver)throw new A("Graph run requests by workflowId require a document resolver");const i=o??t??"anonymous",a=this.activeByCaller.get(i)??new Set;if(a.size>=this.options.limits.maxConcurrentRuns)throw new A(`Graph run rejected: the configured limit of ${this.options.limits.maxConcurrentRuns} concurrent runs per caller is exhausted`);const s=this.generateRunId(),d={runId:s,workflowId:r,ownerUser:t,status:"queued",createdAt:(new Date).toISOString()};this.executor.begin(s),await this.runStore.saveRun({...d},...n);const l=this.documentProviderFor(e,t);return a.add(s),this.activeByCaller.set(i,a),this.callerKeysByRun.set(s,i),this.executor.schedule(d,l,e.inputs??{},...n).catch(()=>{}).finally(()=>this.finishActiveRun(s)),d}async getRun(e,t,...o){const n=await this.runStore.readRun(e,...o);if(!n)throw new _(`No graph run found for runId '${e}'`);return this.assertOwnership(n,t),n}async listRunsByWorkflow(e,t,...o){return(await this.runStore.listRuns(e,...o)).filter(e=>di({owner:e.owner},t,{allowAnonymousAccess:!0===this.options.allowAnonymousAccess})).sort((e,t)=>{const o=e.updatedAt instanceof Date?e.updatedAt.getTime():NaN,n=t.updatedAt instanceof Date?t.updatedAt.getTime():NaN;return(Number.isFinite(n)?n:0)-(Number.isFinite(o)?o:0)})}async cancelRun(e,t,...o){const n=await this.runStore.readRun(e,...o);if(!n)throw new _(`No graph run found for runId '${e}'`);return this.assertWriteOwnership(n,t),"succeeded"===(r=n.status)||"failed"===r||"cancelled"===r||(this.executor.abort(e,"user"),n.status="cancelled",n.finishedAt=(new Date).toISOString(),await this.runStore.saveRun({...n},...o)),n;var r}async resumeRun(e,t,o,...n){const r=await this.runStore.readRun(e,...n);if(!r)throw new _(`No graph run found for runId '${e}'`);this.assertWriteOwnership(r,o);const i=this.engine.backend,a=i.resume;if("function"!=typeof a)throw new to(`Graph execution backend '${i.constructor?.name??"GraphExecutionBackend"}' does not support resume`,"GRAPH_RESUME_UNSUPPORTED_BACKEND",{runId:e});let s;try{s=await a.call(i,e,t,...n)}catch(e){throw(d=e)instanceof to?new to(d.message,d.graphCode):d}var d;const l={...s,runId:e,caller:o};return await this.publisher.publish({runId:e,workflowId:r.workflowId,type:ce.WORKFLOW_RESUMED,payload:l}),l}async listEvents(e,t,o,...n){return await this.getRun(e,o,...n),this.eventStore.listAfter(e,t)}async subscribeEvents(e,t,o,...n){return await this.getRun(e,t,...n),this.eventStore.subscribe(e,o)}subscribeRunEvents(e,t){return this.eventStore.subscribe(e.runId,t)}async waitForRun(e,t,...o){const n=this.executor.waitFor(e);return n&&await n,this.getRun(e,t,...o)}async executeAndWait(e,t,o,...n){const r=await this.createRun(e,t,o,...n);return this.waitForRun(r.runId,t,...n)}release(e){this.finishActiveRun(e);const t=this.releaseTimers.get(e);t&&(clearTimeout(t),this.releaseTimers.delete(e)),this.executor.release(e),this.eventStore.release?.(e)}finishActiveRun(e){const t=this.callerKeysByRun.get(e);if(void 0!==t){this.callerKeysByRun.delete(e);const o=this.activeByCaller.get(t);o&&(o.delete(e),0===o.size&&this.activeByCaller.delete(t))}if(this.releaseTimers.has(e))return;const o=setTimeout(()=>{this.releaseTimers.delete(e),this.release(e)},this.options.limits.eventReplayWindowMs);o.unref?.(),this.releaseTimers.set(e,o)}validateCreateRequest(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new A("Graph run request must be an object carrying either a workflow document or a workflowId plus inputs");const t=void 0!==e.workflow,o=void 0!==e.workflowId;if(t&&o)throw new A("Graph run request is ambiguous: supply either an unsaved workflow document or a saved workflowId, not both");if(!t&&!o)throw new A("Graph run request must supply either an unsaved workflow document or a saved workflowId");if(t&&!pt(e.workflow))throw new A("Graph run request carries a payload that is not a canonical GraphWorkflowDocument");if(void 0!==e.inputs&&!Ue(e.inputs))throw new A("Graph run inputs must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys (__proto__/prototype/constructor) are rejected");const n=(e=>{try{return JSON.stringify(e)?.length??0}catch{return Number.MAX_SAFE_INTEGER}})(e);if(n>this.options.limits.maxRequestBytes)throw new A(`Graph run request of ${n} bytes exceeds the configured limit of ${this.options.limits.maxRequestBytes} bytes`)}documentProviderFor(e,t){if(e.workflow){const t=e.workflow;return async()=>({document:t,fingerprint:hi(t)})}const o=e.workflowId;return async(...e)=>{const n=this.options.documentResolver;if(!n)throw new A("Graph run requests by workflowId require a document resolver");const r=await n.resolve(o,t,...e);return{document:r,fingerprint:hi(r)}}}assertOwnership(e,t){ui({owner:e.ownerUser},t,{allowAnonymousAccess:!0===this.options.allowAnonymousAccess,resourceKind:"Graph run",resourceId:e.runId})}assertWriteOwnership(e,t){ci({owner:e.ownerUser},t,{resourceKind:"Graph run",resourceId:e.runId})}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new so("Cannot generate a graph run id: crypto.randomUUID is unavailable in this runtime",{runtime:typeof globalThis.crypto});return e.randomUUID()}}function Ei(e){if(!e)return;let t;try{t=e.cache?.user}catch{t=void 0}if(null==t)try{t=e.get("user")}catch{t=void 0}return"string"==typeof t&&t.length>0?t:void 0}function Ni(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&pt(e.document)&&!pt(e)}function Oi(e){return JSON.parse(JSON.stringify(e))}function ki(e){if(null==e)return 0;let t;try{t=e.getTime()}catch{return 0}return Number.isFinite(t)?t:0}let Ai=class extends H{constructor(e){super(Gt),this.catalogue=e}get limits(){return{...ar,...sr.graph.workflows.limits??{}}}get allowAnonymousAccess(){return!0===sr.graph.workflows.allowAnonymousAccess}async saveDocument(e,t,...o){const{ctx:n,ctxArgs:r}=(await this.logCtx(o,"saveDocument",!0)).for(this.saveDocument);if(!pt(t))throw new A("Payload is not a canonical GraphWorkflowDocument: id and name must be strings and inputs, outputs, nodes and edges must be arrays");if(t.id!==e)throw new A(`Document id '${t.id}' does not match the workflow id '${e}' from the request path`);const i=await this.validateDocument(t,n);if(!i.valid)throw new po(i.issues);const a=Ei(n),s=await this.readExistingForWrite(e,r);s&&this.assertWriteOwnership(e,s,a);const d=new Date;if(s)return s.name=t.name,s.document=Oi(t),s.updatedAt=d,this.update(s,...r);const l=new Gt({workflowId:e,name:t.name,document:Oi(t),...a?{owner:a}:{},updatedAt:d});return this.create(l,...r)}async getDocument(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"getDocument",!0)).for(this.getDocument);let r;try{r=await this.read(e,...n)}catch{r=null}if(!r)throw new _(`No graph workflow found for workflowId '${e}'`);if(this.assertOwnership(e,r,Ei(o)),r.document)return Oi(r.document);throw new _(`Graph workflow '${e}' has no canonical document; legacy definition/state snapshots are no longer supported (DECAF-50 \xa74.26 R2-2)`)}async listWorkflows(...e){const{ctx:t,ctxArgs:o}=(await this.logCtx(e,"listWorkflows",!0)).for(this.listWorkflows),n=await this.listBy("workflowId",K.ASC,...o),r=Ei(t);return n.filter(e=>di(e,r,{allowAnonymousAccess:this.allowAnonymousAccess})).sort((e,t)=>ki(t.updatedAt)-ki(e.updatedAt))}async assertAccess(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"assertAccess",!0)).for(this.assertAccess);let r;try{r=await this.read(e,...n)}catch{r=null}if(!r)throw new _(`No graph workflow found for workflowId '${e}'`);return this.assertOwnership(e,r,Ei(o)),r}async validateDocument(e,...t){const{ctx:o}=(await this.logCtx(t,"validateDocument",!0)).for(this.validateDocument);return await ai(e,{limits:this.limits,...this.catalogue?{catalogue:this.catalogue}:{}},o)}async saveSnapshot(e,t,...o){const{ctx:n,ctxArgs:r}=(await this.logCtx(o,"saveSnapshot",!0)).for(this.saveSnapshot);if(!Ue(t))throw new A("Workflow snapshot payload must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys (__proto__/prototype/constructor) are rejected");if(!Ni(t))throw new A("Workflow snapshots must wrap a canonical GraphWorkflowDocument ({ document, editor?, metadata? }): legacy definition/state snapshots are no longer accepted; save canonical documents via PUT /graph/workflows/{workflowId}");const i=Ei(n),a=await this.readExistingForWrite(e,r);a&&this.assertWriteOwnership(e,a,i);const s=new Date;if(a)return a.snapshot=t,await this.applyCanonicalWrapper(a,t,n),a.updatedAt=s,this.update(a,...r);const d=new Gt({workflowId:e,snapshot:t,...i?{owner:i}:{},updatedAt:s});return await this.applyCanonicalWrapper(d,t,n),this.create(d,...r)}async loadSnapshot(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"loadSnapshot",!0)).for(this.loadSnapshot);try{const t=await this.read(e,...n);return this.assertOwnership(e,t,Ei(o)),t}catch{return null}}async readExistingForWrite(e,t){try{return await this.read(e,...t)}catch(e){if(e instanceof _)return null;throw e}}assertOwnership(e,t,o){ui(t??null,o??null,{allowAnonymousAccess:this.allowAnonymousAccess,resourceKind:"Graph workflow",resourceId:e})}assertWriteOwnership(e,t,o){ci(t??null,o??null,{resourceKind:"Graph workflow",resourceId:e})}async applyCanonicalWrapper(e,t,o){if(!Ni(t))return;if(t.document.id!==e.workflowId)throw new A(`Document id '${t.document.id}' does not match the workflow id '${e.workflowId}' from the request path`);const n=await ai(t.document,{limits:this.limits,...this.catalogue?{catalogue:this.catalogue}:{}},o);if(!n.valid)throw new po(n.issues);e.document=Oi(t.document),e.name=t.document.name}};Ai=S([F(Gt),D("design:paramtypes",[Function])],Ai);let xi=class extends H{constructor(){super(jt)}async saveRun(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"saveRun",!0)).for(this.saveRun),n=gi(e);let r;try{r=await super.read(e.runId,...o)}catch{r=null}if(r)return r.workflowId=n.workflowId,r.owner=n.owner,r.status=n.status,r.documentFingerprint=n.documentFingerprint,r.result=n.result,r.error=n.error,r.startedAt=n.startedAt,r.finishedAt=n.finishedAt,void await this.update(r,...o);await this.create(n,...o)}async readRun(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"readRun",!0)).for(this.readRun);try{return(e=>{const t=e.result;return{runId:e.runId,workflowId:e.workflowId,ownerUser:e.owner??null,status:(o=e.status,"string"==typeof o&&["queued","validating","running","succeeded","failed","cancelled"].includes(o)?e.status:"failed"),createdAt:e.createdAt.toISOString(),...e.startedAt?{startedAt:e.startedAt.toISOString()}:{},...e.finishedAt?{finishedAt:e.finishedAt.toISOString()}:{},...t?{result:t}:{},...e.error?{error:e.error}:{},...e.documentFingerprint?{documentFingerprint:e.documentFingerprint}:{}};var o})(await super.read(e,...o))}catch{return null}}async listRuns(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"listRuns",!0)).for(this.listRuns);return await this.findBy("workflowId",e,...o)}};xi=S([F(jt),D("design:paramtypes",[])],xi);class _i{map(e){const t={};for(const[o,n]of Object.entries(e.nodeResults))t[o]={status:n.status,startedAt:n.startedAt?.toISOString(),finishedAt:n.finishedAt?.toISOString(),error:n.error,outputs:n.outputs,fromCache:n.fromCache,pinned:n.pinned};const o={};for(const t of e.events)t.edgeId&&"edge.valueRouted"===t.type&&(o[t.edgeId]={status:se.SUCCEEDED,lastValue:t.payload?.value,updatedAt:t.timestamp.toISOString()});const n=[...e.events];return{runId:e.runId,status:e.status,nodes:t,edges:o,outputs:e.outputs,events:n}}}export{Or as AgentNode,er as BreakFlowNode,wr as ChatTriggerNode,pr as CodeInputSchema,hr as CodeNode,jo as ConditionExpressionEvaluator,ar as DEFAULT_GRAPH_WORKFLOW_DOCUMENT_LIMITS,Nn as DEFAULT_GRAPH_WORKFLOW_VALIDATION_LIMITS,cn as DEFAULT_PINNING_METADATA,fr as DelayFlowNode,or as ErrorBoundaryFlowNode,br as EventTriggerNode,vr as FormTriggerNode,kr as GRAPH_AGENT_NODES,Kr as GRAPH_BOUNDARY_NODES,Vr as GRAPH_BUILT_IN_NODE_CLASSES_BY_KIND,Gr as GRAPH_BUILT_IN_NODE_MANIFESTS,Fr as GRAPH_BUILT_IN_NODE_MANIFESTS_BY_KIND,ur as GRAPH_CODE_DEFAULT_LANGUAGE,dr as GRAPH_CODE_DEFAULT_TIMEOUT_MS,cr as GRAPH_CODE_LANGUAGES,Xt as GRAPH_CODE_MAX_TIMEOUT_MS,Ht as GRAPH_DEFAULT_CONCURRENCY,Vt as GRAPH_DEFAULT_MAX_FOREACH_ITERATIONS,Kt as GRAPH_DEFAULT_MAX_LOOP_ITERATIONS,On as GRAPH_DOCUMENT_FORBIDDEN_FIELD_KEYS,Wr as GRAPH_FLOW_CONTROL_NODES,qt as GRAPH_LOCAL_EXECUTION_BACKEND,eo as GRAPH_LOOP_KIND,Hr as GRAPH_LOOP_NODES,Jt as GRAPH_MAX_FOREACH_ITERATIONS,zt as GRAPH_MAX_LOOP_ITERATIONS,Yt as GRAPH_PINNING_METADATA_KEY,Zo as GRAPH_PLAIN_SECRET_KEYS,Br as GRAPH_TRIGGER_NODES,qr as GRAPH_UTILITY_NODES,Wt as GRAPH_WORKFLOW_BOUNDARY,Zr as GRAPH_WORKFLOW_FORBIDDEN_FIELD_KEYS,So as GraphAuthValidator,co as GraphBreakSignal,Sr as GraphConditionEvaluator,Zt as GraphConditionType,wn as GraphConnectionPolicyValidator,In as GraphConnectionValidationError,En as GraphCredentialAuthorizationError,bn as GraphCredentialReferenceValidator,oo as GraphCycleError,vn as GraphDocumentValidationError,yn as GraphEdgeInstanceValidator,To as GraphEngineEventSink,sr as GraphEnvironment,Mo as GraphExecutionBackendRegistry,Ro as GraphExecutionContext,Pn as GraphExecutionEngine,to as GraphExecutionError,ho as GraphExecutionEventEmitter,fo as GraphExecutionEventFactory,$o as GraphExecutionFrame,_n as GraphExecutionPlanner,_i as GraphExecutionSnapshotMapper,_r as GraphForeachLoopNode,no as GraphInputError,Rr as GraphInputValueNode,si as GraphLoopExecutionContext,ro as GraphLoopLimitError,Zn as GraphNode,Vn as GraphNodeCatalogue,zn as GraphNodeExecutorRegistry,Jn as GraphNodeExecutorResolver,gn as GraphNodeInstanceValidator,Wn as GraphNodeManifestResolver,Ln as GraphNodeMethodNotFoundError,Mn as GraphNodeMethodRegistry,Tn as GraphNodeNotFoundError,Cn as GraphNodeRegistrationError,$r as GraphOutputValueNode,en as GraphParameterValidator,hn as GraphPinningDependencyResolver,io as GraphPinningError,pn as GraphPinningPolicy,ln as GraphPinningService,Qt as GraphPinningStrategy,ao as GraphPortError,Yr as GraphPortSchemaResolver,uo as GraphRunCancelledError,wi as GraphRunEventPublisher,bi as GraphRunExecutor,xi as GraphRunModelService,Ii as GraphRunService,so as GraphStoreError,dn as GraphTopology,lo as GraphTopologyError,Dr as GraphUntilLoopNode,tn as GraphValueModel,an as GraphValueRepository,Qr as GraphValueValidator,Pr as GraphWhileLoopNode,po as GraphWorkflowDocumentRejectedError,xn as GraphWorkflowDocumentValidator,Ai as GraphWorkflowService,nr as HumanApprovalFlowNode,rr as IfFlowNode,fi as InMemoryGraphRunEventStore,yi as InMemoryGraphRunStore,$n as IsolatedVmCodeSandboxEvaluator,fn as LocalGraphExecutionBackend,gr as LogFlowNode,Ir as ManualTriggerNode,mr as MapNode,Er as ScheduleTriggerNode,ir as SwitchFlowNode,yr as UtilityLogNode,Nr as WebhookTriggerNode,ui as assertGraphResourceOwnership,ci as assertGraphResourceWriteOwnership,Co as buildGraphExecutionResult,Jr as builtInGraphNodeRegistrations,di as canAccessGraphResource,li as canAccessGraphResourcePayload,Jo as checkGraphValueAgainstSchema,lr as clampGraphCodeTimeoutMs,mn as collectLooseNodeIssues,mo as composeGraphNamespace,sn as createGraphValueRepository,Yn as declaredGraphNodeMethods,go as decomposeGraphNamespace,xo as decomposeGraphNamespaces,Xn as defineGraphNode,Vo as detectGraphCodeModeSurfaces,Fo as evaluateCodeCondition,Wo as evaluateCondition,Bo as evaluateConditionSync,Io as findMalformedGraphNamespaces,vo as findUngrantedGraphNamespaces,ko as graphAuthDataFromRecord,Ao as graphAuthDataOf,zo as graphDocumentHasCodeMode,bo as graphNamespaceCovers,wo as graphNamespacePartsOf,Qn as graphNodeConfig,Eo as graphRolesFromNamespaces,hi as graphRunDocumentFingerprint,Ei as graphWorkflowOwnerOf,Go as isCodeCondition,Uo as isConditionExpression,Yo as isGraphCredentialReferenceLike,yo as isGraphNamespaceCacheEntryValid,kn as isGraphResolvedWorkflow,un as isPinnable,_o as mergeGraphAuthData,Xr as registerBuiltInGraphNodes,Lo as resolveGraphBackendCapabilities,Fn as resolveGraphDynamicPorts,Bn as resolveGraphNodeManifest,on as serializeGraphValueKey,Dn as stripFacadeOwnedBackendConfig,ai as validateGraphWorkflowDocumentAtBoundary};
|
|
1
|
+
import{logParameterRegistry as e,Logging as t,LoggedEnvironment as o}from"@decaf-ts/logging";import{RenderingEngine as n,uimodel as r,uielement as i,uilistprop as a,uilistmodel as s,hidden as d}from"@decaf-ts/ui-decorators";import{Metadata as l,Decoration as c,apply as u,metadata as p,propMetadata as h,description as f,prop as g,DefaultFlavour as m}from"@decaf-ts/decoration";import{ValidationKeys as y,Model as w,required as b,type as v,date as I,model as E,option as N,min as k,max as O}from"@decaf-ts/decorator-validation";import{ValidationError as A,InternalError as x,NotFoundError as _}from"@decaf-ts/db-decorators";import{__decorate as S,__metadata as D}from"tslib";import{pk as P,column as R,index as $,table as C,BaseModel as T,ForbiddenError as L,Context as M,repository as j,Repository as G,AuthorizationError as U,service as F,Service as B,ClientBasedService as W,Adapter as q,ModelService as H,OrderDirection as K}from"@decaf-ts/core";import V from"isolated-vm";import*as z from"acorn";import*as J from"acorn-walk";import*as X from"typescript";import{createHash as Y}from"node:crypto";var Q,Z;y.REQUIRED,y.MIN,y.MIN_LENGTH,y.MAX,y.MAX_LENGTH,y.PATTERN,y.URL,y.STEP,y.DATE,y.EMAIL,y.PASSWORD,y.EQUALS,y.DIFF,y.LESS_THAN,y.LESS_THAN_OR_EQUAL,y.GREATER_THAN,y.GREATER_THAN_OR_EQUAL,(e=>{e.GRAPH="graph",e.NODE="graph.node",e.EDGE="graph.edge",e.PORT="graph.port",e.STATE="graph.state"})(Q||(Q={})),(e=>{e.INPUT="input",e.OUTPUT="output",e.CONNECTION="connection"})(Z||(Z={}));const ee={};function te(e,t={}){let o=e.width??96,n=e.height??96;for(const r of e.sizeRules??[]){if("parameterCount"!==r.type)continue;const e=t[r.parameter]??0;e>0&&("width"===r.dimension?o+=e*r.perItem:n+=e*r.perItem)}return{width:o,height:n}}function oe(e,t){ee[e]=t}function ne(e,t,o){const n=t?ee[t]:void 0;return n?.color?n.color:e||"#64748b"}function re(e,t,o){const n=t?ee[t]:void 0;return n?.icon?n.icon:e||"ti-pointer"}const ie=["skip","passThroughFirstInput","emitDefaults"];function ae(e){return ie.includes(e)}var se,de,le,ce;(e=>{e.PENDING="pending",e.PLANNING="planning",e.RUNNING="running",e.SUCCEEDED="succeeded",e.FAILED="failed",e.SKIPPED="skipped",e.CANCELLED="cancelled",e.CACHED="cached"})(se||(se={})),(e=>{e.IDLE="idle",e.RUNNING="running",e.BLOCKED="blocked",e.SUCCEEDED="succeeded",e.FAILED="failed",e.SKIPPED="skipped"})(de||(de={})),(e=>{e.NODE_ID="nodeId",e.WORKFLOW_ID="workflowId",e.RUN_ID="runId",e.USER="user",e.ROLES="roles",e.NAMESPACES="namespaces",e.ORGANIZATION="organization",e.IP="ip"})(le||(le={})),(e=>{e.WORKFLOW_STARTED="workflow.started",e.WORKFLOW_PLANNED="workflow.planned",e.WORKFLOW_COMPLETED="workflow.completed",e.WORKFLOW_FAILED="workflow.failed",e.WORKFLOW_CANCELLED="workflow.cancelled",e.WORKFLOW_SUSPENDED="workflow.suspended",e.WORKFLOW_RESUMED="workflow.resumed",e.NODE_QUEUED="node.queued",e.NODE_STARTED="node.started",e.NODE_OUTPUT="node.output",e.NODE_COMPLETED="node.completed",e.NODE_FAILED="node.failed",e.NODE_SKIPPED="node.skipped",e.NODE_CACHE_HIT="node.cacheHit",e.NODE_PINNED="node.pinned",e.NODE_UNPINNED="node.unpinned",e.NODE_STATE_CHANGED="node.stateChanged",e.EDGE_VALUE_ROUTED="edge.valueRouted",e.EDGE_STATE_CHANGED="edge.stateChanged",e.GRAPH_RUN_LOG="graph.run.log",e.LOOP_STARTED="loop.started",e.LOOP_ITERATION_STARTED="loop.iteration.started",e.LOOP_ITERATION_COMPLETED="loop.iteration.completed",e.LOOP_CONDITION_EVALUATED="loop.condition.evaluated",e.LOOP_COMPLETED="loop.completed",e.LOOP_LIMIT_REACHED="loop.limitReached",e.VALIDATION_STARTED="validation.started",e.VALIDATION_FAILED="validation.failed",e.VALIDATION_COMPLETED="validation.completed",e.STORE_READ="store.read",e.STORE_WRITE="store.write",e.STORE_DELETE="store.delete"})(ce||(ce={}));const ue={maxRequestBytes:4e6,maxConcurrentRuns:32,maxEventsPerRun:1e4,maxEventPayloadBytes:256e3,executionTimeoutMs:6e5,eventReplayWindowMs:3e5},pe=[ce.WORKFLOW_COMPLETED,ce.WORKFLOW_FAILED,ce.WORKFLOW_CANCELLED];function he(e){return pe.includes(e)}function fe(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function ge(e){const t=l.constr(e);if("function"==typeof t)return t;const o=e.constructor;return"function"==typeof o?o:e}function me(e){if(null!=e)return"string"==typeof e?e:e+""}function ye(e,t,o){return me(e?.props?.label??e?.props?.name)??me(t?.name)??o??""}function we(e,t,o){const n=Ie(e,t);if(n?.model&&"function"==typeof n.model&&w.isModel(n.model))return n.model;const r=l.type(e,t);if("function"==typeof r&&w.isModel(r))return r;const i=l.getPropDesignTypes?.(e,t)?.designTypes||[];for(const e of i)if("function"==typeof e&&w.isModel(e))return e;const a=o?.[y.TYPE]?.customTypes||[];for(const e of a)if("function"==typeof e&&w.isModel(e))return e}function be(e,t){const o=[t,e.path??e.property].filter(Boolean).join(".");return{...e,path:o,children:e.children?.map(e=>be(e,o))}}function ve(e){const t=ge(e);return l.get(t,Q.NODE)}function Ie(e,t){const o=ge(e);return l.get(o,l.key(Q.PORT,t+""))}function Ee(e,t,o,n=new Set){const r=Ie(e,t);if(!r?.schema)return;const i=we(e,t,l.validationFor(e,t));if(!i)return;if(n.has(i))return[];const a=new Set(n);return a.add(e),a.add(i),Oe(i,a).filter(e=>e.direction===o)}function Ne(e,t,o=new Set){const n=Ie(e,t);if(!n)return;const r=l.validationFor(e,t),i=we(e,t,r);if(n.schema&&i)return;const a=w.uiElementOf(e,t)||void 0,s=w.uiDecorationOf(e,t,"uiprop"),d=l.type(e,t),c=me(n.type??r?.[y.TYPE]?.customTypes?.[0]?.name??a?.props?.type??s?.type??d?.name),u=(n.expand||i&&!o.has(i))&&i?(()=>{const n=new Set(o);return n.add(e),n.add(i),Oe(i,n).map(e=>be(e,t))})():void 0;return{property:t,path:t,direction:n.direction,name:t,label:ye(a,s,t),type:c?.toLowerCase(),required:!!r?.[y.REQUIRED],hidden:!!w.uiIsHidden(e,t),designType:d?.name,element:a,prop:s,validation:r,graph:n,connectionRules:n.connectionRules,composite:!!u?.length,children:u,model:i?.name}}function ke(e){return Oe(ge(e))}function Oe(e,t=new Set){const o=l.properties(e)||[],n=[];for(const r of o){const o=r+"",i=Ie(e,o);if(i?.schema){const r=Ee(e,o,i.direction,t);if(r){n.push(...r);continue}}const a=Ne(e,o,t);a&&n.push(a)}return n}function Ae(e){return e.flatMap(e=>e.children&&e.children.length?Ae(e.children):[e])}function xe(e){const t=ge(e),o=w.uiModelOf(t),n=ve(t)||{},r=o?.tag||t.name,i=ke(t),a=((e,t)=>{const o=t.portGroups||[],n=new Map(o.map(e=>[e.property,e])),r=[],i=l.properties(e)||[];for(const t of i){const o=t+"",i=Ie(e,o);if(!i?.schema)continue;if(!we(e,o,l.validationFor(e,o)))continue;const a=n.get(o);r.push(a?{...a,toggle:a.toggle??"all"}:{property:o,toggle:"all"})}for(const e of o)r.some(t=>t.property===e.property)||r.push(e);return r.length?r:void 0})(t,n),s=n.namespaces?.length?n.namespaces:(e=>{if(null==e)return[];let t,o=e;try{o=l.constr(e)}catch{o=e}try{t=l.get(o,"auth-namespace")}catch{t=void 0}return fe(t)??[]})(t),d=s.length?s:void 0;return{name:t.name,tag:r,kind:n.kind||r,category:n.category,color:n.color,effectiveColor:ne(n.color,n.category),group:n.group,height:n.height,icon:n.icon,effectiveIcon:re(n.icon,n.category),labels:n.labels||[],maxChildren:n.maxChildren,minWidth:n.minWidth,width:n.width,shape:n.shape,cornerRadius:n.cornerRadius,sizeRules:n.sizeRules,props:o?.props,ui:o,graph:n,ports:i,portGroups:a,namespaces:d}}const _e=new Set,Se=new Set;function De(e,t,o){return c.for(Q.NODE).define({decorator:(e,t,o)=>{const n={kind:t?.kind||e,...t};return t=>{const i=u(r(e,o),p(Q.NODE,n))(t);var a;return a=t,_e.add(a),i}},args:[e,t,o]}).apply()}function Pe(e,t){return c.for(Q.PORT).define({decorator:(e,t)=>(o,n)=>{const r={direction:e,...t};return u(h(l.key(Q.PORT,n),r))(o,n)},args:[e,t]}).apply()}function Re(e){return Pe(Z.INPUT,{...e,schema:!0})}function $e(e){return Pe(Z.OUTPUT,{...e,schema:!0})}function Ce(e){return Pe(Z.CONNECTION,e)}n.prototype.renderAsNode=(e,t,...o)=>xe(e),l.nodes=(()=>[..._e]).bind(l),l.workflows=(()=>[...Se]).bind(l);const Te=["__proto__","prototype","constructor"];function Le(e){return Te.includes(e)}function Me(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function je(e){return null===e||"string"==typeof e||"number"==typeof e&&Number.isFinite(e)||"boolean"==typeof e}function Ge(e){return!!je(e)||(Array.isArray(e)?e.every(e=>Ge(e)):!!Me(e)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&!Le(t)&&Ge(e[t])))}function Ue(e){if(void 0===e)return!1;if("number"==typeof e)return Number.isFinite(e);if("function"==typeof e)return!1;if(Ge(e))return!0;if(Array.isArray(e))return e.every(e=>Ue(e));if(Me(e)){const t=Reflect.ownKeys(e);for(const o of t){if("string"!=typeof o)return!1;if(Le(o))return!1;if(!Ue(e[o]))return!1}return!0}return!1}function Fe(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>Fe(e));const t={};for(const[o,n]of Object.entries(e))t[o]=Fe(n);return t}const Be={string:"string",char:"string",text:"string",textarea:"string",radio:"string",select:"string",number:"number",integer:"number",float:"number",double:"number",decimal:"number",boolean:"boolean",bool:"boolean",checkbox:"boolean",array:"array",list:"array",set:"array",object:"object",model:"model",any:"any",unknown:"any",enum:"enum"},We={date:"date",datetime:"date-time","date-time":"date-time",duration:"duration"};function qe(e){return e?Be[e.toLowerCase()]??"any":"any"}function He(e,t){const o=e[t];if(o&&"object"==typeof o)return o.value}function Ke(e,t){const o=He(e,t);return"number"==typeof o&&Number.isFinite(o)?o:void 0}function Ve(e,t,o){const n=e??{},r=(e=>{const t=He(e,y.ENUM);if(Array.isArray(t)&&t.every(je))return t})(n);if(r)return{type:"enum",values:r};const i=(e=>{const t=e[y.TYPE],o=t?.customTypes?.[0],n="function"==typeof o?o.name:o?.name;if(n)return n})(n)??o;return i?{type:"model",name:i}:((e,t)=>{switch(qe(e)){case"string":{const t=(e=>{if(e)return We[e.toLowerCase()]})(e);return void 0!==t?{type:"string",format:t}:{type:"string"}}case"number":{const o={type:"number"};e&&"integer"===e.toLowerCase()&&(o.integer=!0);const n=Ke(t,y.MIN),r=Ke(t,y.MAX);return void 0!==n&&(o.min=n),void 0!==r&&(o.max=r),o}case"boolean":return{type:"boolean"};case"array":return((e,t)=>{const o={type:"array",items:ze(e,t)},n=Ke(e,y.MIN),r=Ke(e,y.MAX);return void 0!==n&&(o.minItems=n),void 0!==r&&(o.maxItems=r),o})(t,e);case"object":return{type:"object",properties:{}};case"enum":return{type:"enum",values:[]};case"model":return{type:"model",name:e??"any"};default:return{type:"any"}}})(t,n)}function ze(e,t){if((e=>{const t=e[y.LIST];return!!t?.clazz?.length})(e))return{type:"model",name:Je(e)};const o=He(e,y.TYPE);if("string"==typeof o){const e=qe(o);return"model"===e?{type:"model",name:o}:{type:e}}if(t&&"array"!==t){const e=qe(t);return"model"===e?{type:"model",name:t}:{type:e}}return{type:"any"}}function Je(e){const t=e[y.LIST],o=t?.clazz?.[0];if("function"!=typeof o)return"any";if(o.name)return o.name;try{const e=o();if("function"==typeof e&&e.name)return e.name}catch{return"any"}return"any"}function Xe(e){return"workflow"===e.scope}function Ye(e){return"node"===e.scope}function Qe(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"workflow"===t.scope?"string"==typeof t.port&&2===Reflect.ownKeys(t).length:"node"===t.scope&&"string"==typeof t.nodeId&&"string"==typeof t.port&&3===Reflect.ownKeys(t).length}function Ze(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e.mode;if("edge"===t)return 1===Reflect.ownKeys(e).length;if("literal"===t){const t=e.value;return 2===Object.keys(e).length&&Ge(t)}return"expression"===t&&2===Object.keys(e).length&&"string"==typeof e.expression}const et=["any","string","number","boolean","array","object","enum","model"];function tt(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&(e=>et.includes(e))(e.type)}function ot(e,t={seen:[]}){if(t.seen.includes(e))throw new A(`Document '${(e=>{const t=e?.id;return"string"==typeof t?t:"<unnamed document>"})(e)}' contains a loop body that references itself (cyclic document)`);if("string"!=typeof e.id||!e.id)throw new A("Document 'id' is required and must be a non-empty string");if("string"!=typeof e.name||!e.name)throw new A("Document 'name' is required and must be a non-empty string");const o=new Set;for(const t of[...e.inputs,...e.outputs]){if("string"!=typeof t.id||!t.id)throw new A("Workflow port 'id' is required and must be a non-empty string");if(o.has(t.id))throw new A(`Workflow port '${t.id}' is declared more than once; workflow port ids must be unique`);if(void 0!==t.schema&&!tt(t.schema))throw new A(`Workflow port '${t.id}' schema must be a valid GraphValueSchema`);o.add(t.id)}const n={seen:[...t.seen,e]},r=new Set;for(const t of e.nodes)nt(t,r);for(const t of e.nodes)t.loop&&rt(t,t.loop,n),t.errorBoundary&&it(t,t.errorBoundary,n);const i=new Set;for(const t of e.edges)st(t,i);for(const t of e.edges)dt(t.source,0,o,r,`Edge '${t.id}' source`),dt(t.target,0,o,r,`Edge '${t.id}' target`);if(void 0!==e.settings&&!Ue(e.settings))throw new A("Document settings must be JSON-safe (a map of JSON-safe values)");if(void 0!==e.metadata&&!Ue(e.metadata))throw new A("Document metadata must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed");if(void 0!==e.ui&&!Ue(e.ui))throw new A("Document ui must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed")}function nt(e,t){if("string"!=typeof e.id||!e.id)throw new A("Node 'id' is required and must be a non-empty string");if(t.has(e.id))throw new A(`Node id '${e.id}' is declared more than once; node ids must be unique`);if("string"!=typeof e.kind||!e.kind)throw new A(`Node '${e.id}' must declare a non-empty string 'kind'`);if(void 0===e.parameters||null===e.parameters)throw new A(`Node '${e.id}' parameters must be present (an empty object when there are none)`);if(t.add(e.id),e.inputBindings)for(const[t,o]of Object.entries(e.inputBindings)){if(Le(t))throw new A(`Node '${e.id}' input binding key '${t}' is not allowed (unsafe prototype-pollutant key)`);if(!Ze(o))throw new A(`Node '${e.id}' input binding for '${t}' must be a valid GraphInputBinding (edge, literal, or expression)`);if("literal"===o.mode&&!Ue(o.value))throw new A(`Node '${e.id}' literal binding for '${t}' must contain JSON-safe values`);if("expression"===o.mode&&!o.expression)throw new A(`Node '${e.id}' expression binding for '${t}' must contain a non-empty expression`)}if(e.outputBindings)for(const[t,o]of Object.entries(e.outputBindings)){if(Le(t))throw new A(`Node '${e.id}' output binding key '${t}' is not allowed (unsafe prototype-pollutant key)`);if(!o||"object"!=typeof o||Array.isArray(o))throw new A(`Node '${e.id}' output binding for '${t}' must be an object with enabled and alias settings`)}if(!Ue(e.parameters))throw new A(`Node '${e.id}' parameters must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`);if(void 0!==e.state){if(!e.state||"object"!=typeof e.state||Array.isArray(e.state))throw new A(`Node '${e.id}' state must be an object when present`);if(!Ue(e.state))throw new A(`Node '${e.id}' state must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`)}}function rt(e,t,o){if(!t.body||"object"!=typeof t.body)throw new A(`Node '${e.id}' loop configuration requires a body document`);if(ot(t.body,o),!(void 0===t.maxIterations||Number.isFinite(t.maxIterations)&&t.maxIterations>0))throw new A(`Node '${e.id}' loop maxIterations must be a positive number`);if(void 0!==t.timeoutMs&&("number"!=typeof t.timeoutMs||0>=t.timeoutMs))throw new A(`Node '${e.id}' loop timeoutMs must be a positive number in milliseconds`);if(void 0!==t.concurrency&&("number"!=typeof t.concurrency||0>=t.concurrency))throw new A(`Node '${e.id}' loop concurrency must be a positive number`);for(const o of[t.inputMappings,t.outputMappings])if(o)for(const[t,n]of Object.entries(o)){if(Le(t))throw new A(`Node '${e.id}' loop mapping key '${t}' is not allowed (unsafe prototype-pollutant key)`);at(n,e.id,t)}}function it(e,t,o){if(!t.try||"object"!=typeof t.try)throw new A(`Node '${e.id}' error-boundary configuration requires a try body document`);ot(t.try,o);for(const[n,r]of[["catch",t.catch],["finally",t.finally]])if(void 0!==r){if(!r||"object"!=typeof r)throw new A(`Node '${e.id}' error-boundary ${n} body must be a document`);ot(r,o)}}function at(e,t,o){if(!e||"object"!=typeof e)throw new A(`Node '${t}' loop mapping '${o}' must reference a workflow port, node port, literal, or expression`);switch(e.source){case"workflow":if("string"!=typeof e.port||!e.port)throw new A(`Node '${t}' loop mapping '${o}' referencing a workflow must reference a port identifier`);break;case"node":if("string"!=typeof e.nodeId||!e.nodeId||"string"!=typeof e.port||!e.port)throw new A(`Node '${t}' loop mapping '${o}' referencing a node must reference a node id and a port`);break;case"literal":if(!Ue(e.value))throw new A(`Node '${t}' loop mapping '${o}' literal references must be JSON-safe values`);break;case"expression":if("string"!=typeof e.expression||!e.expression)throw new A(`Node '${t}' loop mapping '${o}' expression references must be non-empty expressions`);break;default:throw new A(`Node '${t}' loop mapping '${o}' must use a workflow, node, literal, or expression reference source`)}}function st(e,t){if("string"!=typeof e.id||!e.id)throw new A("Edge 'id' is required and must be a non-empty string");if(t.has(e.id))throw new A(`Edge id '${e.id}' is declared more than once; edge ids must be unique`);if(!Qe(e.source))throw new A(`Edge '${e.id}' source endpoint is not a valid GraphEndpoint`);if(!Qe(e.target))throw new A(`Edge '${e.id}' target endpoint is not a valid GraphEndpoint`);if("data"!==e.type&&"connection"!==e.type)throw new A(`Edge '${e.id}' type '${e.type+""}' is not a valid edge type (data or connection are allowed)`);if(t.add(e.id),!Ue(e))throw new A(`Edge '${e.id}' contains values that are not JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`)}function dt(e,t,o,n,r){if(Xe(e)){if(!o.has(e.port))throw new A(`${r} references workflow port '${e.port}' which is not declared on the document`)}else if(Ye(e)){if(!n.has(e.nodeId))throw new A(`${r} references node '${e.nodeId}' which is not part of the document`);if("string"!=typeof e.port||!e.port)throw new A(r+" node endpoints must reference a non-empty port identifier")}}const lt=["expression","template"],ct=["javascript","typescript","json","text"];function ut(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return!(!(e=>lt.includes(e))(t.mode)||"string"!=typeof t.expression||!t.expression||void 0!==t.language&&!(e=>ct.includes(e))(t.language)||void 0!==t.metadata&&!Ge(t.metadata))}function pt(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.name&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.nodes)&&Array.isArray(t.edges)}function ht(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.type&&(void 0===t.required||"boolean"==typeof t.required)&&(void 0===t.displayName||"string"==typeof t.displayName)&&(void 0===t.allowedOperations||Array.isArray(t.allowedOperations)&&t.allowedOperations.every(e=>"string"==typeof e))}const ft=["trigger","loop","branching","stateful","retryable","cancellable","parallel","resource"];function gt(e){return ft.includes(e)}function mt(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.kind&&"object"==typeof t.display&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.parameters)}function yt(e){if(!mt(e))throw new A("Graph node manifest does not conform to the required shape");if(!Ue(e))throw new A("Graph node manifest contains values that are not JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys or unsafe prototype keys are not allowed on manifests")}function wt(e){return yt(e),Fe(e)}function bt(e){if(!mt(e))throw new A("Serialized graph node manifest does not conform to the required shape");return Fe(e)}const vt=["loadOptions","listSearch","resourceLocator","resourceMapping","validateParameter","action"];function It(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.name&&(e=>vt.includes(e))(t.type)&&(void 0===t.parameter||"string"==typeof t.parameter)&&(void 0===t.dependencies||Array.isArray(t.dependencies)&&t.dependencies.every(e=>"string"==typeof e))}function Et(e){const t=e.element?.props?.value,o=t??e.prop?.value??e.validation?.defaultValue;if(void 0!==o&&"function"!=typeof o&&Ue(o))try{return JSON.parse(JSON.stringify(o))}catch{return}}function Nt(e){if(e.type&&e.type in We)return{type:"string",format:We[e.type]};const t=(e=>{for(const t of[e.graph?.type,e.element?.props?.type,e.prop?.type])if("string"==typeof t&&"any"!==qe(t))return t})(e);return t?Ve((e=>{if(!e)return;const t=Object.entries(e).filter(([e])=>e!==y.TYPE);return Object.fromEntries(t)})(e.validation),t):Ve(e.validation,e.type,e.model)}function kt(e){const t={};for(const[o,n]of Object.entries(e.graph?.metadata??{}))Ue(n)&&(t[o]=JSON.parse(JSON.stringify(n)));return Object.keys(t).length?t:void 0}function Ot(e){switch(e){case"output":return"output";case"connection":return"connection";default:return"input"}}function At(e){const t=e.graph?.handle;return"connection"!==e.direction&&"string"==typeof t&&t?t:e.path??e.property}function xt(e,t){const o={id:At(e),label:e.label,direction:Ot(e.direction),schema:Nt(e)};e.required&&(o.required=!0),e.hidden&&(o.hidden=!0);const n=e.graph?.category;"string"==typeof n&&(o.category=n),!0===e.graph?.userControlled&&(o.configurable=!0);const r=e.graph?.handle;"string"==typeof r&&(o.handle=r);const i=Mt(e.graph?.connectionRules)??t;i&&(o.connectionPolicy=i);const a=(e=>{const t=e.element;if(!t||!Ue(t))return;const o=t.tag;if("string"!=typeof o)return;const n=t.props;return{tag:o,serialize:!0===t.serialize,props:n&&"object"==typeof n&&!Array.isArray(n)?Fe(n):{}}})(e);a&&(o.element=a);const s=kt(e);return s&&(o.metadata=s),o}function _t(e){const t={type:"string",id:At(e),label:e.label,required:e.required};if(e.hidden)return((e,t)=>{const o={...t,type:"hidden"},n=Et(e);return void 0!==n&&(o.defaultValue=n),St(o)})(e,t);const o=Et(e);void 0!==o&&(t.defaultValue=o);const n=(e=>{const t=e.element?.props?.placeholder??e.prop?.placeholder;return"string"==typeof t?t:void 0})(e);n&&(t.placeholder=n);const r=kt(e);if(r&&(t.metadata=r),(e=>{const t=Rt(e);return"code"===t||"code-editor"===t})(e))return St({...t,type:"code",language:Tt(e)});const i=Nt(e);switch(i.type){case"number":{const o={...t,type:"number",integer:i.integer,min:i.min,max:i.max},n=Pt(e.validation?.step);return void 0!==n&&(o.step=n),St(o)}case"boolean":return St({...t,type:"boolean"});case"enum":return St({...t,type:"options",options:i.values.map(e=>({value:e,label:e+""}))});case"array":{const e={...t,type:"collection"};return void 0!==i.maxItems&&(e.maxItems=i.maxItems),St(e)}case"object":case"model":return St({...t,type:"object"});default:return St({...t,type:"string",multiline:!!$t(e)||void 0,pattern:Dt(e.validation?.pattern),minLength:Pt(e.validation?.minlength),maxLength:Pt(e.validation?.maxlength)})}}function St(e){const t=e;for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return e}function Dt(e){const t=e?.value;return"string"==typeof t?t:void 0}function Pt(e){const t=e?.value;return"number"==typeof t&&Number.isFinite(t)?t:void 0}function Rt(e){const t=e.element?.tag;return"string"==typeof t&&t?t:void 0}function $t(e){return"textarea"===Rt(e)||"textarea"===(e=>{const t=e.element?.props?.type;return"string"==typeof t?t:void 0})(e)}const Ct=["javascript","typescript","json","text"];function Tt(e){const t=e.element?.props?.language;return"string"==typeof t&&Ct.includes(t)?t:"javascript"}function Lt(e,t){const o={name:t.name??e.name},n=e.graph?.metadata?.description??void 0;"string"==typeof n&&n&&(o.description=n);const r=t.category??e.category;"string"==typeof r&&r&&(o.category=r),"string"==typeof e.group&&e.group&&(o.group=e.group),Array.isArray(e.labels)&&(o.labels=e.labels.slice());const i=((e,t)=>{if(t.icon)return t.icon;const o=e.effectiveIcon??e.icon;return"string"==typeof o?{type:"catalogue",name:o}:{type:"catalogue",name:"ph:circuitry"}})(e,t);return i&&(o.icon=i),"string"==typeof e.color&&e.color&&(o.color=e.color),"number"==typeof e.width&&Number.isFinite(e.width)&&(o.width=e.width),"number"==typeof e.minWidth&&Number.isFinite(e.minWidth)&&(o.minWidth=e.minWidth),"number"==typeof e.height&&Number.isFinite(e.height)&&(o.height=e.height),"string"==typeof e.shape&&(o.shape=e.shape),"number"==typeof e.cornerRadius&&Number.isFinite(e.cornerRadius)&&(o.cornerRadius=e.cornerRadius),Array.isArray(e.sizeRules)&&(o.sizeRules=e.sizeRules),o}function Mt(e){if(!e)return;const t=e,o={};"boolean"==typeof t.allowSelf&&(o.allowSelf=t.allowSelf),"boolean"==typeof t.allowMultiple&&(o.allowMultiple=t.allowMultiple);const n=t.allowedKinds;Array.isArray(n)&&n.every(e=>"string"==typeof e)&&(o.allowedNodeKinds=n);const r=t.blockedKinds;Array.isArray(r)&&r.every(e=>"string"==typeof e)&&(o.blockedNodeKinds=r);const i=t.maxConnections;return"number"==typeof i&&Number.isFinite(i)&&(o.maxConnections=i),Object.keys(o).length?o:void 0}function jt(e,t={}){const o="function"==typeof e?e:e.constructor;if(!ve(o))throw new A(`Node '${o?.name??e+""}' is not decorated with @node and cannot produce a manifest`);const n=xe(o),r=Ae(ke(o)),i=[],a=[],s=[],d=[],l=Mt(n.graph?.connectionRules);for(const e of r)("connection"===e.direction?s:"output"===e.direction?a:i).push(xt(e,l)),"input"===e.direction&&d.push(_t(e));const c={kind:t.kind??n.kind??n.name,display:Lt(n,t),inputs:i,outputs:a,parameters:d};return s.length&&(c.connections=s),n.namespaces?.length&&(c.namespaces=n.namespaces.slice()),yt(c),c}var Gt,Ut;(e=>{e.READABILITY="readability",e.COMPACTNESS="compactness",e.BALANCED="balanced"})(Gt||(Gt={})),(e=>{e.TIGHT="tight",e.NORMAL="normal",e.COMFORTABLE="comfortable"})(Ut||(Ut={})),Ut.TIGHT,Ut.NORMAL,Ut.COMFORTABLE,Gt.READABILITY,Ut.COMFORTABLE,Gt.COMPACTNESS,Ut.TIGHT,Gt.BALANCED,Ut.NORMAL;let Ft=class extends T{constructor(e){super(e)}};S([P({type:String,generated:!1}),f("Unique graph run id"),i("ngx-decaf-crud-field",{label:"graph.run.id.label",readonly:!0}),D("design:type",String)],Ft.prototype,"runId",void 0),S([R(),b(),$(),f("Workflow document id the run executes"),a("workflowId"),i("ngx-decaf-crud-field",{label:"graph.run.workflowId.label"}),D("design:type",String)],Ft.prototype,"workflowId",void 0),S([R(),f("Owning user; absent for anonymous callers"),i("ngx-decaf-crud-field",{label:"graph.run.owner.label"}),D("design:type",String)],Ft.prototype,"owner",void 0),S([R(),b(),v(String),$(),f("Current run lifecycle status"),a("status"),i("ngx-decaf-crud-field",{label:"graph.run.status.label",readonly:!0}),D("design:type",String)],Ft.prototype,"status",void 0),S([R(),f("Fingerprint of the executed document"),i("ngx-decaf-crud-field",{label:"graph.run.fingerprint.label",readonly:!0}),D("design:type",String)],Ft.prototype,"documentFingerprint",void 0),S([R(),g(),f("Workflow input values keyed by input port id"),D("design:type",Object)],Ft.prototype,"inputs",void 0),S([R(),g(),f("Execution result, present on successful completion"),D("design:type",Object)],Ft.prototype,"result",void 0),S([R(),g(),f("Structured error payload, present on failure"),D("design:type",Object)],Ft.prototype,"error",void 0),S([I(),R(),f("Run creation timestamp"),D("design:type",Date)],Ft.prototype,"createdAt",void 0),S([I(),R(),f("Execution start timestamp, once it has started"),D("design:type",Date)],Ft.prototype,"startedAt",void 0),S([I(),R(),f("Terminal-state timestamp, once the run has finished"),D("design:type",Date)],Ft.prototype,"finishedAt",void 0),Ft=S([s("ngx-decaf-list-item",{icon:"ti-player-play"}),r("ngx-decaf-crud-form"),f("Persistable graph run lifecycle record"),C("graph_run"),E(),D("design:paramtypes",[Object])],Ft);let Bt=class extends T{constructor(e){super(e)}};S([P({type:String,generated:!1}),D("design:type",String)],Bt.prototype,"workflowId",void 0),S([R(),D("design:type",String)],Bt.prototype,"name",void 0),S([R(),D("design:type",Object)],Bt.prototype,"document",void 0),S([R(),D("design:type",String)],Bt.prototype,"owner",void 0),S([R(),D("design:type",Object)],Bt.prototype,"snapshot",void 0),Bt=S([C("graph_workflow"),E(),D("design:paramtypes",[Object])],Bt);let Wt=class extends T{constructor(e){super(e)}};S([P({type:String,generated:!1}),D("design:type",String)],Wt.prototype,"kind",void 0),S([R(),$(),D("design:type",String)],Wt.prototype,"name",void 0),S([R(),$(),D("design:type",String)],Wt.prototype,"category",void 0),S([R(),D("design:type",String)],Wt.prototype,"group",void 0),S([R(),D("design:type",String)],Wt.prototype,"description",void 0),S([R(),D("design:type",Object)],Wt.prototype,"manifest",void 0),Wt=S([C("graph_node"),E(),D("design:paramtypes",[Object])],Wt),oe("Trigger",{color:"#3b82f6",icon:"ti-bolt"}),oe("Flow Control",{color:"#f59e0b",icon:"ti-arrows-split-2"}),oe("Utility",{color:"#0d9488",icon:"ti-tool"}),oe("Loop",{color:"#eab308",icon:"ti-repeat"}),oe("Workflow",{color:"#f97316",icon:"ti-sitemap"}),oe("Pipeline",{color:"#0ea5e9",icon:"ti-git-merge"}),oe("Node",{color:"#8b5cf6",icon:"ti-point-filled"}),oe("Agent",{color:"#7c3aed",icon:"ti-robot"}),oe("model",{color:"#3b82f6",icon:"ti-cpu"}),oe("memory",{color:"#10b981",icon:"ti-database"}),oe("workspace",{color:"#f59e0b",icon:"ti-folder"});const qt=new Set;function Ht(e,t){return e.config[t]}function Kt(e){return Array.isArray(e)?e.map(e=>e+"").join(", "):e+""}(()=>{const t=[{key:le.NODE_ID,shouldInclude:e=>null!=Ht(e,le.NODE_ID),render:e=>Ht(e,le.NODE_ID)+""},{key:le.WORKFLOW_ID,shouldInclude:e=>null!=Ht(e,le.WORKFLOW_ID),render:e=>Ht(e,le.WORKFLOW_ID)+""},{key:le.RUN_ID,shouldInclude:e=>null!=Ht(e,le.RUN_ID),render:e=>Ht(e,le.RUN_ID)+""},{key:le.USER,shouldInclude:e=>null!=Ht(e,le.USER),render:e=>Ht(e,le.USER)+""},{key:le.ROLES,shouldInclude(e){const t=Ht(e,le.ROLES);return Array.isArray(t)&&t.length>0},render:e=>Kt(Ht(e,le.ROLES))},{key:le.NAMESPACES,shouldInclude(e){const t=Ht(e,le.NAMESPACES);return Array.isArray(t)&&t.length>0},render:e=>Kt(Ht(e,le.NAMESPACES))},{key:le.ORGANIZATION,shouldInclude:e=>null!=Ht(e,le.ORGANIZATION),render:e=>Ht(e,le.ORGANIZATION)+""},{key:le.IP,shouldInclude:e=>null!=Ht(e,le.IP),render:e=>Ht(e,le.IP)+""}];for(const o of t)qt.has(o.key)||(e.register(o),qt.add(o.key))})();const Vt="$workflow",zt="local",Jt=4,Xt=100,Yt=1e3,Qt=1e3,Zt=1e4,eo=3e4,to="graph.pinnable";var oo,no;(e=>{e.MANUAL="manual",e.AUTOMATIC="automatic",e.DISABLED="disabled"})(oo||(oo={})),(e=>{e.TRUTHY="truthy",e.FALSY="falsy",e.EQUALS="equals",e.NOT_EQUALS="notEquals",e.GREATER_THAN="greaterThan",e.GREATER_THAN_OR_EQUAL="greaterThanOrEqual",e.LESS_THAN="lessThan",e.LESS_THAN_OR_EQUAL="lessThanOrEqual",e.EXISTS="exists",e.CUSTOM="custom"})(no||(no={}));const ro={FOREACH:"core.loop.foreach",WHILE:"core.loop.while",UNTIL:"core.loop.until"};class io extends x{constructor(e,t="GRAPH_EXECUTION_ERROR",o){super(e,io.name,500),this.graphCode=t,this.details=o,this.name=this.constructor.name}}class ao extends io{constructor(e){super("Graph workflow contains an unsupported cycle","GRAPH_CYCLE_ERROR",e)}}class so extends io{constructor(e,t){super(e,"GRAPH_INPUT_ERROR",t)}}class lo extends io{constructor(e,t){super(e,"GRAPH_LOOP_LIMIT_ERROR",t)}}class co extends io{constructor(e,t){super(e,"GRAPH_PINNING_ERROR",t)}}class uo extends io{constructor(e,t){super(e,"GRAPH_PORT_ERROR",t)}}class po extends io{constructor(e,t){super(e,"GRAPH_STORE_ERROR",t)}}class ho extends io{constructor(e,t){super(e,"GRAPH_TOPOLOGY_ERROR",t)}}class fo extends io{constructor(e){super("Break signal","GRAPH_BREAK_SIGNAL",{value:e}),this.isBreakSignal=!0,this.name="GraphBreakSignal"}}class go extends io{constructor(e){super(`Graph run '${e}' was cancelled`,"GRAPH_RUN_CANCELLED",{runId:e}),this.name=go.name}}class mo extends A{constructor(e){super(`Graph workflow document rejected with ${e.length} issue(s): ${e.map(e=>`${e.code} at ${e.path} (${e.message})`).join("; ")}`),this.name=mo.name,this.issues=e}}class yo{constructor(){this.observers=new Set}observe(e){return this.observers.add(e),()=>this.unObserve(e)}unObserve(e){this.observers.delete(e)}async updateObservers(e){await Promise.all(Array.from(this.observers).map(async t=>{try{await Promise.resolve(t.refresh(e))}catch{}}))}}class wo{constructor(){this.sequence=0}create(e){return{...e,id:this.createEventId(),sequence:++this.sequence,timestamp:new Date}}createEventId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new io("Cannot generate a graph event id: crypto.randomUUID is unavailable in this runtime","GRAPH_EVENT_ID_ERROR",{runtime:typeof globalThis.crypto});return e.randomUUID()}}function bo(e){if("string"!=typeof e)return;const t=e.trim();if(!t)return;const o=t.split(".");if(3!==o.length)return;const n=o[0].trim(),r=o[2].trim(),i=o[1].split(",").map(e=>e.trim()).filter(e=>e.length>0);return n&&r&&0!==i.length?{organization:n,departments:i,role:r}:void 0}function vo(e){return`${e.organization}.${e.departments.join(",")}.${e.role}`}function Io(e){if(!e||"string"!=typeof e.namespace||!e.parts)return!1;const t=bo(e.namespace);return!!t&&vo(t)===vo(e.parts)}function Eo(e,t){const o="string"==typeof e?e.trim():"";if(o){if(t)for(const e of t)if(e&&e.namespace===o&&Io(e))return e.parts;return bo(o)}}function No(e,t,o={},n){const r=Eo(e,n),i=Eo(t,n);return!(!r||!i)&&r.organization===i.organization&&r.role===i.role&&("exact"===(o.mode??"inherit")?r.departments.length===i.departments.length&&r.departments.every((e,t)=>e===i.departments[t]):r.departments.length<=i.departments.length&&r.departments.every((e,t)=>e===i.departments[t]))}function ko(e,t,o={},n){return e.filter(e=>!t.some(t=>No(t,e,o,n)))}function Oo(e){return e.filter(e=>void 0===bo(e))}function Ao(e,t){const o=new Set;for(const n of e){const e=Eo(n,t);e&&o.add(e.role)}return[...o]}function xo(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function _o(e,t){try{const o=e.cache;if(o&&void 0!==o[t]&&null!==o[t])return o[t]}catch{}try{return e.get(t)}catch{return}}function So(e){if(!e)return{};const t={},o=e.user;"string"==typeof o&&o&&(t.user=o);const n=e.organization;"string"==typeof n&&n&&(t.organization=n);const r=e.ip;"string"==typeof r&&r&&(t.ip=r);const i=xo(e.roles);i&&(t.roles=i);const a=xo(e.namespaces);return a&&(t.namespaces=a,t.namespaceCache=Po(a)),t}function Do(e){return e?So({user:_o(e,"user"),organization:_o(e,"organization"),ip:_o(e,"ip"),roles:_o(e,"roles"),namespaces:_o(e,"namespaces")}):{}}function Po(e){const t=[];for(const o of e){const e=bo(o);e&&t.push({namespace:o,parts:e})}return t}function Ro(...e){const t={};for(const o of e)o&&(void 0!==o.user&&(t.user=o.user),void 0!==o.organization&&(t.organization=o.organization),void 0!==o.ip&&(t.ip=o.ip),void 0!==o.roles&&(t.roles=o.roles),void 0!==o.namespaces&&(t.namespaces=o.namespaces),void 0!==o.namespaces?t.namespaceCache=o.namespaceCache??Po(o.namespaces):void 0!==o.namespaceCache&&(t.namespaceCache=o.namespaceCache));return t}class $o{constructor(e={}){this.options=e}get enabled(){return!0===this.options.enabled}validate(e,o,n,r){if(!this.enabled)return;const i=r??this.options.logger??t.for("GraphAuth"),a=e.id||e.name||o.workflowId,s=(e=>{if(!e||"object"!=typeof e)return;const t=e.auth;return t&&"object"==typeof t&&!Array.isArray(t)?(e=>{if(!e)return;const t=fe(e.namespaces),o=fe(e.roles);if(!t&&!o)return;const n={};return t&&(n.namespaces=t),o&&(n.roles=o),n})(t):void 0})(e.metadata);this.assertGranted(`workflow '${a}'`,s?.namespaces??[],n,s?.roles??[],i);for(const e of o.nodes)this.assertGranted(`node '${e.id}'`,e.manifest.namespaces??[],n,[],i)}assertGranted(e,t,o,n,r){const i=o.namespaces??[],a=ko(t,i,this.options.match,o.namespaceCache),s=Ao(i,o.namespaceCache),d=n.filter(e=>!s.includes(e));if(0===a.length&&0===d.length)return;const l=[...new Set([...Oo(t),...Oo(i)])],c=[];throw a.length&&c.push("namespace(s) "+a.join(", ")),d.length&&c.push("role(s) "+d.join(", ")),r.warn(`Graph access denied for ${e} for user ${o.user??"anonymous"}: missing ${c.join(" and ")}${l.length?`; malformed namespace(s) ${l.join(", ")} failed closed`:""}`),new L(`Access to ${e} requires ${c.join(" and ")}`)}}class Co{constructor(e){this.baseOptions=e,this.inner=t.for("GraphRun").for(this.attributeConfig(e))}attributeConfig(e){return{[le.NODE_ID]:e.nodeId,[le.WORKFLOW_ID]:e.workflowId,[le.RUN_ID]:e.runId,[le.USER]:e.user??null,[le.ROLES]:e.roles,[le.NAMESPACES]:e.namespaces,[le.ORGANIZATION]:e.organization,[le.IP]:e.ip}}emit(e,t,o){const n="string"==typeof t?t:t instanceof Error?t.message:t+"",r={level:e,message:n,timestamp:(new Date).toISOString(),runId:this.baseOptions.runId,workflowId:this.baseOptions.workflowId,nodeId:this.baseOptions.nodeId,user:this.baseOptions.user??null};void 0!==this.baseOptions.roles&&(r.roles=this.baseOptions.roles),void 0!==this.baseOptions.namespaces&&(r.namespaces=this.baseOptions.namespaces),void 0!==this.baseOptions.organization&&(r.organization=this.baseOptions.organization),void 0!==this.baseOptions.ip&&(r.ip=this.baseOptions.ip),void 0!==o&&(r.payload=o),this.baseOptions.forward({type:ce.GRAPH_RUN_LOG,payload:r}).catch(()=>{}),{benchmark:(e,t)=>this.inner.benchmark(e,t),fatal:(e,t)=>this.inner.fatal(e,t),critical:(e,t)=>this.inner.critical(e,t),silly:(e,t)=>this.inner.silly(e,t),trace:(e,t)=>this.inner.trace(e,t),verbose:(e,t)=>this.inner.verbose(e,t),info:(e,t)=>this.inner.info(e,t),warn:(e,t)=>this.inner.warn(e,t),error:(e,t)=>this.inner.error(e,t),debug:(e,t)=>this.inner.debug(e,t)}[e](n,o)}benchmark(e,t){this.emit("benchmark",e,t)}fatal(e,t,o){this.emit("fatal",e,t??o)}critical(e,t,o){this.emit("critical",e,t??o)}silly(e,t,o){this.emit("silly",e,"object"==typeof t?t:o)}trace(e,t){this.emit("trace",e,t)}verbose(e,t,o){this.emit("verbose",e,"object"==typeof t?t:o)}info(e,t){this.emit("info",e,t)}error(e,t,o){this.emit("error",e,t??o)}warn(e,t){this.emit("warn",e,t)}debug(e,t){this.emit("debug",e,t)}action(e,t,o){this.inner.action(e,t,o)}setConfig(){}for(e,t,...o){return this}clear(){return this}get root(){return this.inner.root}}function To(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}class Lo extends M{constructor(e,t,o,n,r,i,a,s,d={},l,c,u){super(),this.runId=e,this.parentRunId=t,this.workflowId=o,this.document=n,this.node=r,this.manifest=i,this.path=a,this.emitFn=s,this.metadata=d,this.engine=l,this.abortSignal=c,this.limits=u;const p=So(d);this.accumulate({...p,operation:"execute"});const h="string"==typeof d?.user?d.user:null;this.runLogger=new Co({runId:e,workflowId:o,nodeId:r.id,user:h,roles:To(d?.roles),namespaces:To(d?.namespaces),organization:"string"==typeof d?.organization?d.organization:void 0,ip:"string"==typeof d?.ip?d.ip:void 0,forward:async e=>{await this.emit(e)}})}get logger(){return this.runLogger}get auth(){return Do(this)}async emit(e){await this.emitFn({...e,runId:this.runId,parentRunId:this.parentRunId,workflowId:this.workflowId,nodeId:this.node.id,path:e.path??this.path})}async progress(e){await this.emit({type:ce.NODE_OUTPUT,payload:e})}async log(e,t){await this.emit({type:ce.NODE_OUTPUT,payload:{message:e,payload:t}})}}class Mo{constructor(e,t,o,n){this.nodeResults=new Map,this.events=[],this.activeDataEdges=new Set,this.runId=e,this.plan=t,this.valueStore=o,this.eventFactory=n,this.startedAt=new Date}recordNodeResult(e){this.nodeResults.set(e.nodeId,e)}activateDataEdge(e){this.activeDataEdges.add(e)}isDataEdgeActive(e){return this.activeDataEdges.has(e)}appendEvent(e){this.events.push(e)}finish(){this.finishedAt=new Date}}function jo(e,t,o,n,r){const i=e.valueStore.getWorkflowValues(),a={};for(const[t,o]of e.nodeResults)a[t]=o;const s=[...e.events];return{runId:e.runId,workflowId:t.id||t.name,status:n,document:t,inputs:{...o},outputs:i,nodeResults:a,events:s,startedAt:e.startedAt,finishedAt:e.finishedAt,metadata:r}}class Go{constructor(e,t,o){this.emitter=e,this.eventFactory=t,this.options=o}get engine(){return this.options.engine}get codeSandboxEvaluator(){return this.options.codeSandboxEvaluator}get frame(){return this._frame}bindFrame(e){this._frame=e}async emit(e){const t=this.eventFactory.create({id:"",sequence:0,timestamp:new Date,runId:this.options.runId,parentRunId:this.options.parentRunId,workflowId:this.options.workflowId,type:ce.NODE_OUTPUT,path:this.options.path??[],...e});this._frame?.appendEvent(t),await this.emitter.updateObservers(t)}async updateObservers(e){await this.emitter.updateObservers(e)}}function Uo(e){const t=e.capabilities;return{codeMode:t?.codeMode??e.codeMode,workflows:{list:t?.workflows?.list??("function"==typeof e.listWorkflows?"supported":"not_supported"),get:t?.workflows?.get??("function"==typeof e.getWorkflow?"supported":"not_supported")}}}class Fo{static{this._cache={}}static register(e,t){return Fo._cache[e]=t,t}static get(e){const t=e??Fo._currentFlavour;if(t)return Fo._cache[t]}static getOrFail(e){const t=Fo.get(e);if(!t)throw new io(`No graph execution backend registered under '${e}'`,"GRAPH_EXECUTION_BACKEND_NOT_REGISTERED");return t}static get current(){return Fo.get()}static get currentFlavour(){return Fo._currentFlavour??zt}static setCurrent(e){Fo._currentFlavour=e}static list(){return Object.entries(Fo._cache).map(([e,t])=>({flavour:e,backend:t}))}static unregister(e){e&&(delete Fo._cache[e],Fo._currentFlavour===e&&(Fo._currentFlavour=void 0))}static clear(){for(const e of Object.keys(Fo._cache))delete Fo._cache[e];Fo._currentFlavour=void 0}}class Bo{evaluate(e,t){switch(e.op){case"eq":return this.resolveValue(e.left,t)===this.resolveValue(e.right,t);case"neq":return this.resolveValue(e.left,t)!==this.resolveValue(e.right,t);case"gt":return Number(this.resolveValue(e.left,t))>Number(this.resolveValue(e.right,t));case"gte":return Number(this.resolveValue(e.left,t))>=Number(this.resolveValue(e.right,t));case"lt":return Number(this.resolveValue(e.left,t))<Number(this.resolveValue(e.right,t));case"lte":return Number(this.resolveValue(e.left,t))<=Number(this.resolveValue(e.right,t));case"and":return e.conditions.every(e=>this.evaluate(e,t));case"or":return e.conditions.some(e=>this.evaluate(e,t));case"not":return!this.evaluate(e.condition,t);case"exists":return void 0!==this.resolveValue(e.value,t)&&null!==this.resolveValue(e.value,t);default:throw new io(`Unknown ConditionExpression op '${e.op}'`,"GRAPH_UNKNOWN_CONDITION_OP",{expr:e})}}resolveValue(e,t){if("const"in e)return e.const;if("path"in e&&!("step"in e))return this.resolvePath(e.path,t);if("step"in e&&"path"in e){const o=t?.nodes;if(o&&"object"==typeof o){const t=o[e.step];return this.resolvePath(e.path,t)}return this.resolvePath(e.path,t)}throw new io("Invalid ExprValue: must have `const`, `path`, or `step`+`path`","GRAPH_INVALID_EXPR_VALUE",{ref:e})}resolvePath(e,t){if(!e)return t;const o=e.split(".");let n=t;for(const e of o){if(null==n)return;n=n[e]}return n}}function Wo(e){return"object"==typeof e&&null!==e&&"type"in e&&"code"===e.type}function qo(e){return"object"==typeof e&&null!==e&&"op"in e&&"string"==typeof e.op}async function Ho(e,t,o){const n=o.engine?.codeSandboxEvaluator;if(!n)throw new io("Code conditions require a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{code:e.code});await o.log("Evaluating code condition",{language:e.language??"javascript"});const r=o.metadata;return!!await n.evaluate({code:e.code,language:e.language,input:t,vars:r?.vars??void 0,item:r?.item,index:r?.index,nodes:r?.nodes??void 0,logger:o.logger,abortSignal:o.abortSignal})}function Ko(e,t,o){if(qo(e))return(new Bo).evaluate(e,t);throw((e,t)=>new io(`Unknown ${t??"flow"} condition type \u2014 must be ConditionExpression (op) or CodeCondition (type: 'code')`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition:e}))(e,o)}async function Vo(e,t,o){return Wo(e)?Ho(e,t.input,o):Ko(e,t.state,t.label)}function zo(e,t,o,n){if(e&&"object"==typeof e&&!n.has(e))if(n.add(e),Wo(e))o.push({nodeId:t,kind:"code-condition"});else if(ut(e))o.push({nodeId:t,kind:"value-template"});else if((e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"expression"===t.source&&"string"==typeof t.expression})(e))o.push({nodeId:t,kind:"expression-binding"});else if((e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.name&&Array.isArray(t.nodes)&&Array.isArray(t.edges)})(e))Xo(e,o,n);else if(Array.isArray(e))for(const r of e)zo(r,t,o,n);else for(const r of Object.keys(e))zo(e[r],t,o,n)}function Jo(e,t,o){const n=e.id;"core.utility.code"===e.kind&&t.push({nodeId:n,kind:"code-node",detail:e.kind});const r=e.inputBindings??{};for(const[e,o]of Object.entries(r))o&&"expression"===o.mode&&t.push({nodeId:n,kind:"expression-binding",detail:e});zo(e.parameters,n,t,o),zo(e.metadata,n,t,o),zo(e.state,n,t,o),zo(e.loop,n,t,o)}function Xo(e,t,o){for(const n of e.nodes??[])Jo(n,t,o)}function Yo(e){const t=[];return Xo(e,t,new Set),t}function Qo(e){return Yo(e).length>0}function Zo(e,t){if(!t)return{valid:!0};switch(t.type){case"any":default:return{valid:!0};case"string":return"string"!=typeof e?en("string"):{valid:!0};case"number":return"number"==typeof e&&Number.isFinite(e)?t.integer&&!Number.isInteger(e)?{valid:!1,message:"expected an integer number"}:void 0!==t.min&&e<t.min?{valid:!1,message:"expected a number >= "+t.min}:void 0!==t.max&&e>t.max?{valid:!1,message:"expected a number <= "+t.max}:{valid:!0}:en("number");case"boolean":return"boolean"!=typeof e?en("boolean"):{valid:!0};case"array":if(!Array.isArray(e))return en("array");if(void 0!==t.minItems&&e.length<t.minItems)return{valid:!1,message:`expected at least ${t.minItems} items`};if(void 0!==t.maxItems&&e.length>t.maxItems)return{valid:!1,message:`expected at most ${t.maxItems} items`};for(const o of e){const e=Zo(o,t.items);if(!e.valid)return e}return{valid:!0};case"object":case"model":{if(null===e||"object"!=typeof e||Array.isArray(e))return en(t.type);const o=t,n=o.properties;if(!n)return{valid:!0};for(const[t,o]of Object.entries(n))if(t in e){const n=Zo(e[t],o);if(!n.valid)return{valid:!1,message:`property '${t}': ${n.message}`}}if(o.required)for(const t of o.required)if(!(t in e))return{valid:!1,message:`missing required property '${t}'`};if(!1===o.additionalProperties)for(const t of Object.keys(e))if(!(t in n))return{valid:!1,message:`unexpected property '${t}'`};return{valid:!0}}case"enum":return t.values.some(t=>t===e)?{valid:!0}:{valid:!1,message:"value is not one of the enum values"}}}function en(e){return{valid:!1,message:`expected a ${e} value`}}function tn(e){if("string"==typeof e)return e.length>0;if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.credentialId&&t.credentialId.length>0&&(void 0===t.credentialType||"string"==typeof t.credentialType)}const on=new Set(["loop"]),nn=["secret","secrets","password","passwd","token","accessToken","refreshToken","apiKey","api_key","privateKey","credentials"];class rn{validate(e,t,o,n,r){this.validateParameters(e,t,o,n,r),this.validateMetadataKeys(e,t,o,n),this.validateDisabledBehavior(e,o,n),this.validateBindingShapes(e,t,o,n)}validateParameters(e,t,o,n,r){const i=!0===t.policies?.allowUndeclaredParameters,a=new Map(t.parameters.map(e=>[e.id,e]));for(const[r,s]of Object.entries(e.parameters??{})){const d=a.get(r);if(!d){i||o.push({code:"parameter.undeclared",path:`${n}.parameters.${r}`,message:`Node '${e.id}' sets parameter '${r}' which is not declared by kind '${t.kind}'`,nodeId:e.id,details:{kind:t.kind}});continue}if(void 0===s){o.push({code:"parameter.invalid",path:`${n}.parameters.${r}`,message:`Node '${e.id}' parameter '${r}' must not be undefined`,nodeId:e.id});continue}const l=this.checkParameterValue(s,d);l.valid||o.push({code:"parameter.type-mismatch",path:`${n}.parameters.${r}`,message:`Node '${e.id}' parameter '${r}' is invalid: ${l.message}`,nodeId:e.id,details:{expectedType:d.type}})}for(const i of t.parameters)void 0===(e.parameters??{})[i.id]&&(this.isParameterSatisfiedByInput(e,i.id,r)||(!0===i.required||(i.validation??[]).some(e=>"required"===e.kind))&&void 0===i.defaultValue&&o.push({code:"parameter.required-missing",path:`${n}.parameters.${i.id}`,message:`Node '${e.id}' is missing required parameter '${i.id}' declared by kind '${t.kind}'`,nodeId:e.id}))}isParameterSatisfiedByInput(e,t,o){return void 0!==(e.inputBindings??{})[t]||!0===o?.has(t)}checkParameterValue(e,t){if(ut(e))return{valid:!0};switch(t.type){case"string":case"code":case"expression":return"string"!=typeof e?en("string"):{valid:!0};case"number":return"number"==typeof e&&Number.isFinite(e)?{valid:!0}:en("number");case"boolean":return"boolean"!=typeof e?en("boolean"):{valid:!0};case"options":{const o=t.options;return o&&o.length&&!o.some(t=>t.value===e)?{valid:!1,message:"value is not one of the declared options"}:{valid:!0}}case"collection":return Array.isArray(e)?{valid:!0}:en("array");case"object":case"resourceLocator":return null===e||"object"!=typeof e||Array.isArray(e)?en("object"):{valid:!0};case"credential":return tn(e)?t.credentialType&&"object"==typeof e&&void 0!==e.credentialType&&e.credentialType!==t.credentialType?{valid:!1,message:`credential type '${e.credentialType}' does not match the declared type '${t.credentialType}'`}:{valid:!0}:{valid:!1,message:"credential parameters must hold a credential reference (credentialId), never a secret"};default:return{valid:!0}}}validateMetadataKeys(e,t,o,n){const r=t.metadata?.allowedInstanceMetadataKeys;for(const i of Object.keys(e.metadata??{}))on.has(i)?o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${i}`,message:`Node '${e.id}' metadata key '${i}' is reserved and must not be set directly`,nodeId:e.id}):Array.isArray(r)&&!r.includes(i)&&o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${i}`,message:`Node '${e.id}' metadata key '${i}' is not in the allowed metadata keys of kind '${t.kind}'`,nodeId:e.id})}validateDisabledBehavior(e,t,o){!0!==e.disabled&&!1!==e.disabled&&void 0!==e.disabled&&t.push({code:"disabled.invalid",path:o+".disabled",message:`Node '${e.id}' disabled flag must be a boolean`,nodeId:e.id});const n=(e.metadata??{}).disabledBehavior;void 0===n||ae(n)||t.push({code:"disabled.invalid-behavior",path:o+".metadata.disabledBehavior",message:`Node '${e.id}' disabled behavior '${n+""}' is not one of: ${ie.join(", ")}`,nodeId:e.id})}validateBindingShapes(e,t,o,n){for(const[r,i]of Object.entries(e.inputBindings??{})){if("literal"===i.mode){const a=t.inputs.find(e=>e.id===r);if(a?.schema){const t=Zo(i.value,a.schema);t.valid||o.push({code:"binding.literal-invalid",path:`${n}.inputBindings.${r}`,message:`Node '${e.id}' literal binding for '${r}' is schema-invalid: ${t.message}`,nodeId:e.id})}}"expression"!==i.mode||"string"==typeof i.expression&&i.expression.trim()||o.push({code:"binding.expression-invalid",path:`${n}.inputBindings.${r}`,message:`Node '${e.id}' expression binding for '${r}' must contain a non-empty expression`,nodeId:e.id})}}validateBindingSatisfaction(e,t,o,n,r,i={}){const a=new Set(o.filter(e=>"data"===e.type).map(e=>e.targetPort)),s=new Set(Object.entries(e.inputBindings??{}).map(([e])=>e));for(const t of a){const o=(e.inputBindings??{})[t];o&&"literal"===o.mode&&!0!==i.allowLiteralAndEdgeBindings&&n.push({code:"binding.conflict",path:`${r}.inputBindings.${t}`,message:`Node '${e.id}' input '${t}' has both an incoming edge and a literal binding`,nodeId:e.id})}for(const o of t.inputs)!0===o.required&&(a.has(o.id)||s.has(o.id)||void 0===(e.parameters??{})[o.id]&&n.push({code:"topology.required-input-unsatisfiable",path:r+".parameters",message:`Node '${e.id}' required input '${o.id}' has no incoming edge or binding`,nodeId:e.id,details:{port:o.id}}))}static disabledBehaviorOf(e,t){const o=(e.metadata??{}).disabledBehavior;if(ae(o))return o;const n=t?.disabledBehavior;return ae(n)?n:"skip"}}let an=class extends T{constructor(e){super(e)}};function sn(e){return[e.namespace??"default",e.workflowId,e.nodeId,e.version??"default",e.fingerprint].join(":")}function dn(e){return new an({id:sn(e.key),workflowId:e.key.workflowId,nodeId:e.key.nodeId,fingerprint:e.key.fingerprint,...void 0!==e.key.namespace?{namespace:e.key.namespace}:{},...void 0!==e.key.version?{version:e.key.version}:{},pinned:e.pinned,outputs:e.outputs,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt),...e.expiresAt?{expiresAt:new Date(e.expiresAt)}:{},...e.metadata?{metadata:e.metadata}:{}})}function ln(e){return{key:{workflowId:e.workflowId,nodeId:e.nodeId,fingerprint:e.fingerprint,...void 0!==e.namespace?{namespace:e.namespace}:{},...void 0!==e.version?{version:e.version}:{}},outputs:e.outputs,pinned:e.pinned,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString(),...e.expiresAt?{expiresAt:e.expiresAt.toISOString()}:{},...e.metadata?{metadata:e.metadata}:{}}}S([P({type:String,generated:!1}),D("design:type",String)],an.prototype,"id",void 0),S([R(),$(),D("design:type",String)],an.prototype,"workflowId",void 0),S([R(),$(),D("design:type",String)],an.prototype,"nodeId",void 0),S([R(),D("design:type",String)],an.prototype,"fingerprint",void 0),S([R(),D("design:type",String)],an.prototype,"namespace",void 0),S([R(),D("design:type",String)],an.prototype,"version",void 0),S([R(),D("design:type",Boolean)],an.prototype,"pinned",void 0),S([R(),D("design:type",Object)],an.prototype,"outputs",void 0),S([R(),D("design:type",Date)],an.prototype,"createdAt",void 0),S([R(),D("design:type",Date)],an.prototype,"updatedAt",void 0),S([R(),D("design:type",Date)],an.prototype,"expiresAt",void 0),S([R(),D("design:type",Object)],an.prototype,"metadata",void 0),an=S([C("graph_value"),E(),D("design:paramtypes",[Object])],an);let cn=class extends G{constructor(e){super(e,an,!0),this.runtimeValues=new Map}seedWorkflowInputs(e){this.runtimeValues.set(Vt,{...e})}setNodeOutputs(e,t){this.runtimeValues.set(e,{...t})}getPort(e,t){return this.runtimeValues.get(e)?.[t]}hasPort(e,t){return Object.prototype.hasOwnProperty.call(this.runtimeValues.get(e)??{},t)}setWorkflowOutput(e,t){const o=this.runtimeValues.get(Vt)??{};o[e]=t,this.runtimeValues.set(Vt,o)}getWorkflowValues(){return{...this.runtimeValues.get(Vt)??{}}}snapshot(){return Object.fromEntries(this.runtimeValues.entries())}async readCached(e,...t){try{return ln(await this.read(sn(e),...t))}catch{return}}async writeCached(e,t,...o){const n=sn(e);let r;try{r=await this.read(n,...o)}catch{r=void 0}r?await this.update(Object.assign(r,dn(t)),...o):await this.create(dn(t),...o)}async deleteCached(e,...t){try{await this.delete(sn(e),...t)}catch{}}async hasCached(e,...t){return void 0!==await this.readCached(e,...t)}async listCached(e,...t){return(await this.select().execute(...t)).map(e=>ln(e)).filter(t=>((e,t)=>!(void 0!==t.workflowId&&e.workflowId!==t.workflowId||void 0!==t.nodeId&&e.nodeId!==t.nodeId||void 0!==t.namespace&&e.namespace!==t.namespace||void 0!==t.version&&e.version!==t.version||void 0!==t.fingerprint&&e.fingerprint!==t.fingerprint))(t.key,e))}async clearRun(e,...t){const o=await this.select().execute(...t);for(const e of o)await this.delete(e.id,...t)}readRuntimeValues(e){return this.runtimeValues.get(e)}writeRuntimeValues(e,t){this.runtimeValues.set(e,{...t})}getAdapter(){return this.adapter}};function un(e){return new(0,G.forModel(an,e.alias).constructor)(e)}cn=S([j(an,m),D("design:paramtypes",[Function])],cn);class pn{static upstreamNodes(e,t,o=!1){const n=new Set,r=[e];for(;r.length;){const e=r.pop(),i=t.get(e)??[];for(const e of i)!o&&this.isBoundary(e.sourceNodeId)||n.has(e.sourceNodeId)||(n.add(e.sourceNodeId),r.push(e.sourceNodeId))}return n}static downstreamNodes(e,t,o=!1){const n=new Set,r=[e];for(;r.length;){const e=r.pop(),i=t.get(e)??[];for(const e of i)!o&&this.isBoundary(e.targetNodeId)||n.has(e.targetNodeId)||(n.add(e.targetNodeId),r.push(e.targetNodeId))}return n}static isBoundary(e){return"$workflow"===e}}class hn{constructor(e,t,o){this.store=e,this.policy=t,this.dependencyResolver=o}async pinNode(e){const t=e.plan,o=e.includeDependencies??!0?this.dependencyResolver.getPinSet(t,e.nodeId):new Set([e.nodeId]);for(const e of o){const o=t.nodes.find(t=>t.id===e);if(!o)throw new co(`Node '${e}' not found in plan`);if(!this.policy.canPin(o))throw new co(`Node '${e}' is not pinnable`,{nodeId:e})}const n=this.topologicalOrder(t,o);for(const o of n){const n=t.nodes.find(e=>e.id===o),r=e.result.nodeResults[o];if(!r||!r.outputs)throw new co(`Node '${o}' has no completed output to pin`);const i=r.inputs??{},a=this.dependencyFingerprints(t,o,e.result),s=this.createValueKey(e.document.id,n,i,a),d=(new Date).toISOString(),l={key:s,outputs:r.outputs,pinned:!0,createdAt:d,updatedAt:d,metadata:{...e.result.metadata,nodeId:o}};await this.store.writeCached(s,l)}}async unpinNode(e){const t={workflowId:e.document.id,nodeId:e.nodeId,fingerprint:e.fingerprint,namespace:e.namespace};await this.store.deleteCached(t)}async readPinnedValue(e,t,o,n,r){const i=this.createValueKey(e,t,o,n,r),a=await this.store.readCached(i);if(a&&a.pinned){if(a.expiresAt&&new Date(a.expiresAt)<new Date)return;return a}}createValueKey(e,t,o,n,r){return{workflowId:e,nodeId:t.id,fingerprint:this.computeFingerprint(e,t,o,n),namespace:r}}computeFingerprint(e,t,o,n){const r={workflowId:e,nodeId:t.id,nodeKind:t.kind,parameters:this.stableSerialize(t.instance.parameters??{}),inputBindings:this.stableSerialize(t.instance.inputBindings??{}),metadata:this.stableSerialize(this.relevantMetadata(t)),inputs:this.stableSerialize(o),dependencyFingerprints:this.stableSerialize(n)},i=this.stableSerialize(r);return this.simpleHash(i)}relevantMetadata(e){const t={...e.metadata??{}};return delete t.ui,delete t.position,delete t.visual,t}topologicalOrder(e,t){const o=[],n=new Set,r=i=>{if(n.has(i))return;n.add(i);const a=pn.upstreamNodes(i,e.incomingByNode,!1);for(const e of a)t.has(e)&&r(e);o.push(i)};for(const e of t)r(e);return o}dependencyFingerprints(e,t,o){const n=this.dependencyResolver.getDependencies(e,t),r={};for(const t of n){const n=e.nodes.find(e=>e.id===t);if(n){const i=o.nodeResults[t],a=i?.inputs??{},s=this.dependencyFingerprints(e,t,o);r[t]=this.computeFingerprint(e.workflowId,n,a,s)}}return r}stableSerialize(e){return null===e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?`[${e.map(e=>this.stableSerialize(e)).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${this.stableSerialize(e[t])}`).join(",")}}`}simpleHash(e){let t=0;for(let o=0;o<e.length;o++)t=(t<<5)-t+e.charCodeAt(o),t|=0;return`fp_${Math.abs(t).toString(16).padStart(8,"0")}_${e.length}`}}const fn={enabled:!0,strategy:"manual",includeDependencies:!0};function gn(e){return!0===e?.enabled&&"disabled"!==e.strategy}class mn{canPin(e){return gn(this.getPinningMetadata(e))}shouldUsePinnedValue(e){const t=this.getPinningMetadata(e);return!0===t.enabled&&"disabled"!==t.strategy}shouldAutoPin(e){const t=this.getPinningMetadata(e);return!0===t.enabled&&"automatic"===t.strategy}getPinningMetadata(e){const t=e.manifest.metadata?.pinnable??e.metadata?.pinnable;return t?{...fn,...t}:{...fn,enabled:!1}}}class yn{getDependencies(e,t){return pn.upstreamNodes(t,e.incomingByNode,!1)}getPinSet(e,t){const o=this.getDependencies(e,t);return o.add(t),o}}class wn{constructor(){this.local=!0,this.codeMode="hostSide",Fo.register(zt,this)}async initialize(e){this.valueAdapter=e.valueAdapter,this.codeSandboxEvaluator=e.codeSandboxEvaluator,this.workflowStore=e.workflowStore,this.engine=e.engine}get capabilities(){const e=this.workflowStore?"supported":"not_supported";return{codeMode:this.codeMode,workflows:{list:e,get:e}}}async listWorkflows(...e){const t=this.workflowStore;if(!t)throw new io("LocalGraphExecutionBackend has no workflowStore configured; workflow listing is not supported","GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED");return(await t.listWorkflows(...e)).map(e=>({id:e.workflowId,...void 0!==e.name?{name:e.name}:{},...void 0!==e.updatedAt&&null!==e.updatedAt?{updatedAt:e.updatedAt}:{}}))}async getWorkflow(e,...t){const o=this.workflowStore;if(!o)throw new io("LocalGraphExecutionBackend has no workflowStore configured; workflow lookup is not supported","GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED");return await o.getDocument(e,...t)}async seedWorkflows(e,...t){const o=this.workflowStore,n=o?.seedDocument??o?.saveDocument;if(!o||"function"!=typeof n)throw new io("LocalGraphExecutionBackend has no writable workflowStore configured; workflow seeding is not supported","GRAPH_BACKEND_SEED_NOT_SUPPORTED");const r=[];for(const i of e)null!==await n.call(o,i.id,i,...t)&&r.push({id:i.id,...void 0!==i.name?{name:i.name}:{}});return r}async execute(e){const{document:t,plan:o,inputs:n,options:r,events:i}=e,a=i,s=a.frame;if(!s)throw new io("LocalGraphExecutionBackend requires the frame-bound event sink created by GraphExecutionEngine","GRAPH_EXECUTION_FRAME_MISSING");const d=s.valueStore,l=s.runId,c=r.path??[],u=async e=>{await a.emit(e)};try{for(const e of o.layers)this.assertNotAborted(r),await this.executeLayer(s,o,e.nodes,r,u);this.assertNotAborted(r);const e=[...s.nodeResults.values()].find(e=>e.status===se.FAILED);if(e?.error)throw new io(e.error.message,e.error.code??"GRAPH_EXECUTION_ERROR",e.error.details);return s.finish(),await a.emit({type:ce.WORKFLOW_COMPLETED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:se.SUCCEEDED,payload:{outputs:d.getWorkflowValues()}}),jo(s,t,n,se.SUCCEEDED,r.metadata)}catch(e){if(e instanceof fo)throw s.finish(),e;s.finish();const i=this.toErrorPayload(e);return e instanceof go||!0===r.abortSignal?.aborted?(await a.emit({type:ce.WORKFLOW_CANCELLED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:se.CANCELLED,error:i}),jo(s,t,n,se.CANCELLED,r.metadata)):(await a.emit({type:ce.WORKFLOW_FAILED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:se.FAILED,error:i}),jo(s,t,n,se.FAILED,r.metadata))}}async executeLayer(e,t,o,n,r){const i=Math.max(1,n.concurrency??4),a=[...o];for(;a.length>0;){const o=a.splice(0,i);await Promise.all(o.map(o=>this.executeNode(e,t,o,n,r)))}}async executeNode(e,t,o,n,r){if(this.assertNotAborted(n),!this.isNodeActivated(e,t,o))return void await this.skipInactiveNode(e,t,o,n,r);if(!0===o.instance.disabled)return void await this.executeDisabledNode(e,t,o,n,r);const i=new Date,a=[...n.path??[],o.id];await r({type:ce.NODE_STARTED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.RUNNING}),this.emitNodeStateChanged(e,t,o,a,de.RUNNING,se.RUNNING,r);const s=await this.resolveNodeInputs(e,t,o,n);if(n.usePinnedValues){const n=await this.tryPinnedValue(e,t,o,s);if(n){e.valueStore.setNodeOutputs(o.id,n.outputs),this.routeOutgoingEdges(e,t,o,n.outputs,r);const d=new Date,l={nodeId:o.id,status:se.CACHED,inputs:s,outputs:n.outputs,startedAt:i,finishedAt:d,fromCache:!0,pinned:!0,events:[]};return e.recordNodeResult(l),await r({type:ce.NODE_CACHE_HIT,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.CACHED,payload:{outputs:n.outputs}}),await r({type:ce.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.SUCCEEDED,payload:{outputs:n.outputs,fromCache:!0}}),void this.emitNodeStateChanged(e,t,o,a,de.SUCCEEDED,se.SUCCEEDED,r)}}try{const d=new Lo(e.runId,n.parentRunId,t.workflowId,t.resolved.document,o.instance,o.manifest,a,r,n.metadata,this.engine,n.abortSignal,this.executionLimits(n)),l=await this.resolveNodeParameters(o,s,n),c={nodeId:o.id,kind:o.kind,inputs:s,parameters:l,credentials:this.collectCredentials(o),metadata:o.instance.metadata},u=await this.invokeExecutor(o,c,d),p=this.validateNodeOutputs(o,u??{});e.valueStore.setNodeOutputs(o.id,p),this.routeOutgoingEdges(e,t,o,p,r);const h=new Date,f={nodeId:o.id,status:se.SUCCEEDED,inputs:s,outputs:p,startedAt:i,finishedAt:h,events:[]};e.recordNodeResult(f),await r({type:ce.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.SUCCEEDED,payload:{outputs:p}}),this.emitNodeStateChanged(e,t,o,a,de.SUCCEEDED,se.SUCCEEDED,r)}catch(d){if(d instanceof fo)throw d;const l=new Date,c=this.toErrorPayload(d),u={nodeId:o.id,status:se.FAILED,inputs:s,error:c,startedAt:i,finishedAt:l,events:[]};if(e.recordNodeResult(u),await r({type:ce.NODE_FAILED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.FAILED,error:c}),this.emitNodeStateChanged(e,t,o,a,de.FAILED,se.FAILED,r),n.failFast??!0)throw d}}isNodeActivated(e,t,o){const n=(t.incomingByNode.get(o.id)??[]).filter(e=>"data"===e.type);return 0===n.length||n.some(t=>t.sourceNodeId===Vt||e.isDataEdgeActive(t.id))}async skipInactiveNode(e,t,o,n,r){const i=new Date,a=[...n.path??[],o.id];await r({type:ce.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.SKIPPED,payload:{reason:"branchNotSelected"}});const s={nodeId:o.id,status:se.SKIPPED,inputs:{},startedAt:i,finishedAt:new Date,events:[]};e.recordNodeResult(s),this.emitNodeStateChanged(e,t,o,a,de.SKIPPED,se.SKIPPED,r)}async executeDisabledNode(e,t,o,n,r){const i=new Date,a=[...n.path??[],o.id],s=rn.disabledBehaviorOf(o.instance,t.resolved.document.settings);if(await r({type:ce.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.SKIPPED,payload:{disabled:!0,behavior:s}}),"skip"===s){const n={nodeId:o.id,status:se.SKIPPED,inputs:{},startedAt:i,finishedAt:new Date,events:[]};return e.recordNodeResult(n),void this.emitNodeStateChanged(e,t,o,a,de.SKIPPED,se.SKIPPED,r)}const d=await this.resolveNodeInputs(e,t,o,n);let l;if("passThroughFirstInput"===s){const n=(t.incomingByNode.get(o.id)??[]).find(e=>"data"===e.type),r=o.manifest.outputs[0]?.id??"value",i=n?e.valueStore.getPort(n.sourceNodeId,n.sourcePort):Object.values(d)[0];l={[r]:i}}else{l={};for(const e of o.manifest.outputs)l[e.id]=e.metadata?.defaultValue}e.valueStore.setNodeOutputs(o.id,l),this.routeOutgoingEdges(e,t,o,l,r);const c={nodeId:o.id,status:se.SUCCEEDED,inputs:d,outputs:l,startedAt:i,finishedAt:new Date,events:[]};e.recordNodeResult(c),this.emitNodeStateChanged(e,t,o,a,de.SUCCEEDED,se.SUCCEEDED,r)}async invokeExecutor(e,t,o){return await e.executor.execute(t,o)}validateNodeOutputs(e,t){const o=e.manifest;if(!0===o.policies?.allowUnknownOutputs)return t;const n=new Set(o.outputs.map(e=>e.id)),r=Object.keys(t).filter(e=>!n.has(e));if(r.length>0)throw new io(`Node '${e.id}' of kind '${e.kind}' produced unknown output(s): ${r.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,unknownOutputs:r});const i=o.outputs.filter(e=>!0===e.required&&!(e.id in t)).map(e=>e.id);if(i.length>0)throw new io(`Node '${e.id}' of kind '${e.kind}' did not produce required output(s): ${i.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,missingRequired:i});return t}collectCredentials(e){const t={};for(const o of e.manifest.parameters){if("credential"!==o.type)continue;const n=(e.instance.parameters??{})[o.id];"string"==typeof n&&n.length>0?t[o.id]={credentialId:n,credentialType:o.credentialType??""}:tn(n)&&(t[o.id]={credentialId:n.credentialId,credentialType:n.credentialType})}const o=(e.instance.metadata??{}).credentials;if(o&&"object"==typeof o&&!Array.isArray(o))for(const[e,n]of Object.entries(o)){const o=n;"string"==typeof o&&o.length>0?t[e]={credentialId:o,credentialType:""}:tn(o)&&(t[e]={credentialId:o.credentialId,credentialType:o.credentialType})}return t}async resolveNodeInputs(e,t,o,n){const r={},i=(t.incomingByNode.get(o.id)??[]).filter(e=>"data"===e.type),a=new Map;for(const e of i){const t=a.get(e.targetPort)??[];t.push(e),a.set(e.targetPort,t)}for(const[t,o]of a)if(1===o.length)r[t]=e.valueStore.getPort(o[0].sourceNodeId,o[0].sourcePort);else{let n,i=!1;for(const t of o){const o=e.valueStore.getPort(t.sourceNodeId,t.sourcePort);r[t.sourcePort]=o,void 0!==o&&(n=o,i=!0)}i&&void 0===r[t]&&(r[t]=n)}const s=o.instance.inputBindings??{};for(const e of o.manifest.inputs){const t=s[e.id];if("literal"===t?.mode)r[e.id]=t.value;else if("expression"===t?.mode)r[e.id]=await this.evaluateExpressionBinding(o,t.expression,r,n);else if(void 0===r[e.id]){const t=e.metadata?.defaultValue;void 0!==t&&(r[e.id]=t)}}return r}async resolveNodeParameters(e,t,o){const n=e.instance.parameters??{},r={};for(const[i,a]of Object.entries(n))r[i]=ut(a)?await this.evaluateValueTemplate(a,e,t,o):a;return r}async evaluateValueTemplate(e,t,o,n){const r=this.codeSandboxEvaluator;if(!r)throw new io(`Value template on node '${t.id}' requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator`,"GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{nodeId:t.id});const i=e.language??("expression"===e.mode?"javascript":"text"),a="template"===e.mode?(e=>`\`${e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\{\{\s*([\s\S]*?)\s*\}\}/g,(e,t)=>`\${${t}}`)}\``)(e.expression):e.expression,s=n.metadata;return await r.evaluate({code:a,language:"typescript"===i?"typescript":"javascript",input:o,vars:s?.vars??void 0,item:s?.item,index:s?.index,abortSignal:n.abortSignal})}async evaluateExpressionBinding(e,t,o,n){const r=this.codeSandboxEvaluator;if(!r)throw new io(`Expression binding on node '${e.id}' requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator`,"GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{nodeId:e.id,expression:t});const i=n.metadata;return await r.evaluate({code:t,language:"javascript",input:o,vars:i?.vars??void 0,item:i?.item,index:i?.index,abortSignal:n.abortSignal})}async tryPinnedValue(e,t,o,n){if(!(new mn).shouldUsePinnedValue(o))return;const r=this.createPinningService(e),i=this.computeDependencyFingerprints(e,t,o.id);return r.readPinnedValue(t.workflowId,o,n,i)}computeDependencyFingerprints(e,t,o){const n=this.createPinningService(e),r=(new yn).getDependencies(t,o),i={};for(const o of r){const r=t.nodes.find(e=>e.id===o);if(r){const a=e.nodeResults.get(o),s=a?.inputs??{},d=this.computeDependencyFingerprints(e,t,o);i[o]=n.computeFingerprint(t.workflowId,r,s,d)}}return i}routeOutgoingEdges(e,t,o,n,r){const i=(t.outgoingByNode.get(o.id)??[]).filter(e=>"data"===e.type);for(const a of i){if(!Object.prototype.hasOwnProperty.call(n,a.sourcePort))continue;const i=n[a.sourcePort];e.activateDataEdge(a.id),a.targetNodeId===Vt&&e.valueStore.setWorkflowOutput(a.targetPort,i),this.emitEdgeStateChanged(e,t,o,a,de.SUCCEEDED,se.SUCCEEDED,r),r({type:ce.EDGE_VALUE_ROUTED,runId:e.runId,workflowId:t.workflowId,edgeId:a.id,nodeId:o.id,path:[],payload:{edge:a,value:i}}).catch(()=>{})}}emitNodeStateChanged(e,t,o,n,r,i,a){a({type:ce.NODE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:n,status:i,payload:{nodeId:o.id,state:r,runId:e.runId,workflowId:t.workflowId,status:i}}).catch(()=>{})}emitEdgeStateChanged(e,t,o,n,r,i,a){a({type:ce.EDGE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,edgeId:n.id,nodeId:o.id,path:[],status:i,payload:{edgeId:n.id,state:r,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,status:i}}).catch(()=>{})}createPinningService(e){const t=un(e.valueStore.getAdapter()??this.valueAdapter);return new hn(t,new mn,new yn)}executionLimits(e){return{maxLoopIterations:e.maxLoopIterations??Qt,maxForeachIterations:e.maxForeachIterations??Zt}}assertNotAborted(e){if(!0===e.abortSignal?.aborted)throw new go(e.runId??"unknown")}toErrorPayload(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack,code:e.graphCode??("number"==typeof e.code?e.code+"":e.code)}:{name:"UnknownError",message:e+""}}}class bn{constructor(e){this.catalogue=e}async resolveNodes(e,t,o,...n){const r=new Map;for(const[i,a]of e.entries()){const e=`nodes[${i}]`;if(this.catalogue.has(a.kind,...n))try{const e=await this.catalogue.resolveManifest(a.kind,a,o,...n),t=this.catalogue.getExecutor(a.kind,...n);r.set(a.id,{instance:a,manifest:e,executor:t})}catch(o){t.push({code:"kind.resolution-failed",path:e+".kind",message:`Node '${a.id}' kind '${a.kind}' failed to resolve: ${o.message}`,nodeId:a.id,details:{kind:a.kind}})}else t.push({code:"kind.unknown",path:e+".kind",message:`Node '${a.id}' references kind '${a.kind}' which is not registered in the backend catalogue`,nodeId:a.id,details:{kind:a.kind}})}return r}validateEffectivePorts(e,t,o,n){const r=!0===t.policies?.allowUndeclaredParameters,i=new Set(t.inputs.map(e=>e.id)),a=new Set(t.outputs.map(e=>e.id));for(const a of Object.keys(e.inputBindings??{}))r||i.has(a)||o.push({code:"binding.unknown-port",path:`${n}.inputBindings.${a}`,message:`Node '${e.id}' input binding '${a}' does not refer to an effective input port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveInputs:[...i]}});for(const i of Object.keys(e.outputBindings??{}))r||a.has(i)||o.push({code:"binding.unknown-port",path:`${n}.outputBindings.${i}`,message:`Node '${e.id}' output binding '${i}' does not refer to an effective output port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveOutputs:[...a]}})}}function vn(e,t,o="$"){const n=new Set;for(const t of e.edges)"node"===t.source.scope&&n.add(t.source.nodeId),"node"===t.target.scope&&n.add(t.target.nodeId);for(const r of e.nodes){n.has(r.id)||t.push({code:"topology.loose-node",path:`${o}.nodes[${r.id}]`,message:`Node '${r.id}' is connected to nothing; every node must participate in at least one edge`,nodeId:r.id});const e=r.loop?.body;e&&vn(e,t,`${o}.nodes[${r.id}].loop.body`)}}class In{resolveEdges(e,t,o){const n=new Set(e.inputs.map(e=>e.id)),r=new Set(e.outputs.map(e=>e.id)),i=[];for(const[a,s]of(e.edges??[]).entries()){const e=`edges[${a}]`,d=this.resolveEndpoint(s,"source",t,n,r,o,e),l=this.resolveEndpoint(s,"target",t,n,r,o,e);if(!d||!l)continue;if(!this.validateDirectionAndType(s,d,l,t,o,e))continue;const c={id:s.id,type:s.type,sourceNodeId:d.nodeId,sourcePort:d.port,targetNodeId:l.nodeId,targetPort:l.port,metadata:s.metadata,edge:s};void 0!==s.label&&(c.label=s.label),i.push(c)}return i}resolveEndpoint(e,t,o,n,r,i,a){const s=e[t];return Xe(s)?("source"===t?n.has(s.port):r.has(s.port))?{nodeId:Vt,port:s.port}:void i.push({code:"edge.unknown-port",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} references workflow port '${s.port}' which is not declared on the document boundary`,edgeId:e.id,details:{scope:"workflow",port:s.port}}):Ye(s)?o.get(s.nodeId)?{nodeId:s.nodeId,port:s.port}:void i.push({code:"edge.unknown-node",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} references node '${s.nodeId}' which is not part of the document or did not resolve`,edgeId:e.id,nodeId:s.nodeId}):void i.push({code:"edge.invalid-endpoint",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} endpoint is not a valid GraphEndpoint`,edgeId:e.id})}validateDirectionAndType(e,t,o,n,r,i){let a=!0;const s=t.nodeId===Vt?void 0:n.get(t.nodeId),d=o.nodeId===Vt?void 0:n.get(o.nodeId),l=e=>!0===e?.manifest.policies?.allowUndeclaredParameters;if("data"===e.type)!s||l(s)||this.hasPortDirection(s,t.port,"output")||(this.pushPortIssue(e,"source",t,s,r,i),a=!1),!d||l(d)||this.hasPortDirection(d,o.port,"input")||(this.pushPortIssue(e,"target",o,d,r,i),a=!1);else{if(!s||!d)return r.push({code:"edge.boundary-routing",path:i,message:`Connection edge '${e.id}' must connect two node connection ports; the workflow boundary only routes data`,edgeId:e.id}),!1;if(!(l(s)||l(d)||this.hasPortDirection(s,t.port,"connection")&&this.hasPortDirection(d,o.port,"connection")))return r.push({code:"edge.type-mismatch",path:i,message:`Connection edge '${e.id}' endpoints must both be connection ports`,edgeId:e.id,details:{sourcePort:t.port,targetPort:o.port}}),!1}return a}hasPortDirection(e,t,o){return("input"===o?e.manifest.inputs:"output"===o?e.manifest.outputs:e.manifest.connections??[]).some(e=>e.id===t)}pushPortIssue(e,t,o,n,r,i){const a="source"===t?"output":"input";r.push({code:"data"===e.type?"edge.invalid-direction":"edge.type-mismatch",path:`${i}.${t}`,message:`Edge '${e.id}' ${t} port '${o.port}' on node '${o.nodeId}' is not an ${a} port of kind '${n.manifest.kind}'`,edgeId:e.id,nodeId:o.nodeId,details:{port:o.port,expected:a}})}}class En{validate(e,t){this.validateDuplicates(e.edges,t),this.validatePolicies(e,t)}validateDuplicates(e,t){const o=new Map;for(const n of e){const e=`${n.sourceNodeId}:${n.sourcePort}->${n.targetNodeId}:${n.targetPort}`,r=o.get(e);r?t.push({code:"connection.duplicate-edge",path:`edges[${n.id}]`,message:`Edge '${n.id}' duplicates the routing of edge '${r.id}' (${e})`,edgeId:n.id,details:{duplicateOf:r.id,routing:e}}):o.set(e,n)}}validatePolicies(e,t){const o=new Map;for(const t of e.edges){if("connection"!==t.type)continue;const e=`${t.targetNodeId}:${t.targetPort}`,n=o.get(e)??[];n.push(t),o.set(e,n)}for(const o of e.edges){if("connection"!==o.type)continue;const n=e.nodeById.get(o.targetNodeId),r=n?.manifest.connections?.find(e=>e.id===o.targetPort)?.connectionPolicy;this.validateEdgePolicy(o,e.nodeById,r,t)}for(const[n,r]of o){const o=n.lastIndexOf(":"),i=n.slice(0,o),a=n.slice(o+1),s=e.nodeById.get(i),d=s?.manifest.connections?.find(e=>e.id===a)?.connectionPolicy;if(!d)continue;const l=void 0!==d.maxConnections?d.maxConnections:!1===d.allowMultiple?1:1/0;r.length>l&&t.push({code:"connection.max-connections",path:`edges[${r[r.length-1].id}]`,message:`Connection port '${a}' on node '${i}' accepts at most ${l} connection(s) but has ${r.length}`,nodeId:i,edgeId:r[r.length-1].id,details:{port:a,max:l,actual:r.length}})}}validateEdgePolicy(e,t,o,n){if(e.sourceNodeId===e.targetNodeId&&!o?.allowSelf)return void n.push({code:"connection.self-connection",path:`edges[${e.id}]`,message:`Edge '${e.id}' connects node '${e.sourceNodeId}' to itself, which the target port policy does not allow`,edgeId:e.id,nodeId:e.sourceNodeId});if(!o)return;const r=t.get(e.sourceNodeId),i=r?.manifest.kind;if(!o.allowedNodeKinds?.length||i&&o.allowedNodeKinds.includes(i)||n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${i??"unknown"}' is not in the allowed node kinds of target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{allowedNodeKinds:o.allowedNodeKinds}}),i&&o.blockedNodeKinds?.includes(i)&&n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${i}' is blocked by target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{blockedNodeKinds:o.blockedNodeKinds}}),o.allowedPortCategories?.length){const t=r?.manifest.connections?.find(t=>t.id===e.sourcePort)?.category;t&&o.allowedPortCategories.includes(t)||n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source port '${e.sourcePort}' category '${t??"unknown"}' is not in the allowed port categories of target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{allowedPortCategories:o.allowedPortCategories}})}}}class Nn{constructor(e){this.authorizer=e}async validate(e,t,o,n){const r=this.collectReferences(e,t);for(const i of t.credentials??[]){const a=r.find(e=>void 0===e.credentialType||e.credentialType===i.type);if(a){if(this.checkType(a,i))o.push({code:"credential.type-mismatch",path:n,message:`Node '${e.id}' credential '${a.credentialId}' has type '${a.credentialType}' but kind '${t.kind}' requires '${i.type}'`,nodeId:e.id,details:{credentialType:a.credentialType??"",requiredType:i.type}});else if(this.authorizer){if(!await this.authorizer.hasCredential(a)){o.push({code:"credential.not-found",path:n,message:`Node '${e.id}' references credential '${a.credentialId}' which does not exist`,nodeId:e.id,details:{credentialId:a.credentialId}});continue}await this.authorizer.authorize(a,i)||o.push({code:"credential.unauthorized",path:n,message:`Node '${e.id}' is not authorized to use credential '${a.credentialId}'`,nodeId:e.id,details:{credentialId:a.credentialId}})}}else!1!==i.required&&o.push({code:"credential.missing",path:n,message:`Node '${e.id}' does not provide the required credential of type '${i.type}'`,nodeId:e.id,details:{credentialType:i.type}})}this.scanPlainSecrets(e,o,n)}collectReferences(e,t){const o=[];for(const n of t.parameters){if("credential"!==n.type)continue;const t=(e.parameters??{})[n.id];tn(t)&&o.push(this.normalize(t,n.credentialType))}const n=(e.metadata??{}).credentials;if(n&&"object"==typeof n&&!Array.isArray(n))for(const e of Object.values(n))tn(e)&&o.push(this.normalize(e));return o}normalize(e,t){return"string"==typeof e?{credentialId:e,credentialType:t??""}:{credentialId:e.credentialId,credentialType:e.credentialType??t??""}}checkType(e,t){return void 0!==e.credentialType&&e.credentialType!==t.type}scanPlainSecrets(e,t,o){const n=new Set(nn);for(const[r,i]of Object.entries(e.parameters??{}))this.scanPlainSecretValue(i,[r],e,o+".parameters",n,t);for(const[r,i]of Object.entries(e.metadata??{}))this.scanPlainSecretValue(i,[r],e,o+".metadata",n,t)}scanPlainSecretValue(e,t,o,n,r,i,a=0){const s=t[t.length-1];if(r.has(s))i.push({code:"credential.plain-secret",path:`${n}.${t.join(".")}`,message:`Node '${o.id}' carries plain secret material in '${t.join(".")}'; workflow documents may only hold credential references`,nodeId:o.id});else if(8>a&&null!==e)if(Array.isArray(e))for(const s of e)this.scanPlainSecretValue(s,[...t,"[]"],o,n,r,i,a+1);else if("object"==typeof e)for(const[s,d]of Object.entries(e))this.scanPlainSecretValue(d,[...t,s],o,n,r,i,a+1)}}class kn extends A{constructor(e,t=[]){super(e),this.issues=t,this.name=kn.name}}class On extends A{constructor(e,t){super(e),this.edgeId=t,this.name=On.name}}class An extends U{constructor(e){super(e),this.name=An.name}}const xn={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},_n=["node","definition","executor","execute","ports","component"];function Sn(e){if(!e||"object"!=typeof e)return!1;const t=e;return pt(t.document)&&Array.isArray(t.nodes)&&Array.isArray(t.edges)&&t.nodeById instanceof Map&&t.incomingByNode instanceof Map&&t.outgoingByNode instanceof Map&&t.nodes.every(e=>null!==e&&"object"==typeof e&&"object"==typeof e.instance&&"object"==typeof e.manifest&&"object"==typeof e.executor)}function Dn(e,t){const o=[];for(const n of Object.keys(e))_n.includes(n)&&o.push({code:"document.forbidden-field",path:`${t}.${n}`,message:`Field '${n}' is not accepted in a canonical workflow document: node, definition, executor, execute, ports and component fields are rejected`,details:{field:n}});return o}class Pn{constructor(e){this.options=e,this.parameterValidator=new rn,this.edgeValidator=new In,this.connectionPolicyValidator=new En,this.nodeValidator=new bn(e.catalogue),this.credentialValidator=new Nn(e.credentialAuthorizer)}async validateOrThrow(e,...t){const o=await this.validate(e,0,...t);if(!o.valid||!o.resolved)throw new kn(`Graph workflow document '${e.id}' failed validation with ${o.issues.length} issue(s)`,o.issues);return o.resolved}async validate(e,t=0,...o){const n=[],r={...xn,...this.options.limits};if(!await this.validateStructure(e,r,t,n,...o))return{valid:!1,issues:n};const i=await this.nodeValidator.resolveNodes(e.nodes,n,this.options.resolutionContext,...o),a=e.nodes.filter(e=>i.has(e.id)).map(e=>i.get(e.id)),s=(e=>{const t=new Map;for(const o of e.edges??[]){if("data"!==o.type)continue;const e=o.target;if("node"!==e.scope)continue;const n=t.get(e.nodeId)??new Set;n.add(e.port),t.set(e.nodeId,n)}return t})(e);for(const e of a)this.parameterValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`,s.get(e.instance.id));for(const e of a)this.nodeValidator.validateEffectivePorts(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);const d=this.edgeValidator.resolveEdges(e,i,n),l=new Map,c=new Map;for(const e of d){if(e.targetNodeId!==Vt){const t=l.get(e.targetNodeId)??[];t.push(e),l.set(e.targetNodeId,t)}if(e.sourceNodeId!==Vt){const t=c.get(e.sourceNodeId)??[];t.push(e),c.set(e.sourceNodeId,t)}}this.connectionPolicyValidator.validate({edges:d,nodeById:i},n),this.validateAcyclicity(a,d,e,n),vn(e,n);for(const e of a)this.parameterValidator.validateBindingSatisfaction(e.instance,e.manifest,l.get(e.instance.id)??[],n,`nodes[${e.instance.id}]`,{allowLiteralAndEdgeBindings:this.options.allowLiteralAndEdgeBindings});this.validateRequiredWorkflowOutputs(e,c,n);for(const e of a)await this.credentialValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);return this.validateCapabilities(a,n),n.length>0?{valid:!1,issues:n}:{valid:!0,issues:n,resolved:{document:e,nodes:a,edges:d,nodeById:i,incomingByNode:l,outgoingByNode:c}}}async validateStructure(e,t,o,n,...r){if(!pt(e))return n.push({code:"document.shape",path:"$",message:"Payload is not a canonical GraphWorkflowDocument: id and name must be strings and inputs, outputs, nodes and edges must be arrays"}),!1;if(e.id&&e.id.trim()||n.push({code:"document.empty-id",path:"$.id",message:"Workflow document id must be a non-empty string"}),!Ue(e))return n.push({code:"document.json-unsafe",path:"$",message:"Document contains JSON-unsafe values: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys are rejected"}),!1;n.push(...Dn(e,"$"));for(const t of[...e.inputs,...e.outputs])n.push(...Dn(t,"ports"));for(const t of e.nodes)n.push(...Dn(t,`nodes[${t.id}]`));for(const t of e.edges)n.push(...Dn(t,`edges[${t.id}]`));this.validateUniqueIds(e,n),this.validateLimits(e,t,o,n);try{ot(e)}catch(e){n.push({code:"document.structure",path:"$",message:e instanceof Error?e.message:e+""})}return await this.validateNestedBodies(e,o,n,...r),!0}validateUniqueIds(e,t){const o=new Set,n=new Set;for(const[r,i]of[["input",e.inputs],["output",e.outputs]]){const e="input"===r?o:n;for(const o of i)e.has(o.id)?t.push({code:"document.duplicate-port-id",path:`${"input"===r?"inputs":"outputs"}[${o.id}]`,message:`Workflow ${r} port '${o.id}' is declared more than once; workflow port ids must be unique`}):e.add(o.id)}const r=new Set;for(const o of e.nodes)r.has(o.id)?t.push({code:"document.duplicate-node-id",path:`nodes[${o.id}]`,message:`Node '${o.id}' is declared more than once; node ids must be unique`,nodeId:o.id}):r.add(o.id);const i=new Set;for(const o of e.edges)i.has(o.id)?t.push({code:"document.duplicate-edge-id",path:`edges[${o.id}]`,message:`Edge '${o.id}' is declared more than once; edge ids must be unique`,edgeId:o.id}):i.add(o.id)}validateLimits(e,t,o,n){e.nodes.length>t.maxNodes&&n.push({code:"document.limit.nodes",path:"$.nodes",message:`Document declares ${e.nodes.length} nodes; at most ${t.maxNodes} are allowed`,details:{count:e.nodes.length,limit:t.maxNodes}}),e.edges.length>t.maxEdges&&n.push({code:"document.limit.edges",path:"$.edges",message:`Document declares ${e.edges.length} edges; at most ${t.maxEdges} are allowed`,details:{count:e.edges.length,limit:t.maxEdges}}),o>t.maxNestingDepth&&n.push({code:"document.limit.depth",path:"$",message:`Document nests loop bodies ${o} levels deep; at most ${t.maxNestingDepth} levels are allowed`,details:{depth:o,limit:t.maxNestingDepth}});const r=Buffer.byteLength(JSON.stringify(e),"utf8");r>t.maxDocumentBytes&&n.push({code:"document.limit.size",path:"$",message:`Document serializes to ${r} bytes; at most ${t.maxDocumentBytes} bytes are allowed`,details:{bytes:r,limit:t.maxDocumentBytes}})}async validateNestedBodies(e,t,o,...n){for(const r of e.nodes){const e=[["loop.body",r.loop?.body],["errorBoundary.try",r.errorBoundary?.try],["errorBoundary.catch",r.errorBoundary?.catch],["errorBoundary.finally",r.errorBoundary?.finally]];for(const[i,a]of e){if(!a)continue;const e=await this.validate(a,t+1,...n);for(const t of e.issues)o.push({...t,path:`nodes[${r.id}].${i}.${t.path}`,nodeId:t.nodeId??r.id})}}}validateAcyclicity(e,t,o,n){const r=new Set(e.map(e=>e.instance.id)),i=new Map(e.map(e=>[e.instance.id,0]));for(const e of t)r.has(e.sourceNodeId)&&i.has(e.targetNodeId)&&i.set(e.targetNodeId,(i.get(e.targetNodeId)??0)+1);const a=[...i.entries()].filter(([,e])=>0===e).map(([e])=>e),s=[];for(;a.length>0;){const e=a.shift();s.push(e);for(const o of t){if(o.sourceNodeId!==e)continue;if(!i.has(o.targetNodeId))continue;const t=(i.get(o.targetNodeId)??1)-1;i.set(o.targetNodeId,t),0===t&&a.push(o.targetNodeId)}}if(s.length!==i.size){const e=[...i.keys()].filter(e=>!s.includes(e));n.push({code:"topology.cycle",path:"$.edges",message:`Workflow '${o.id}' contains an unsupported cycle involving node(s): ${e.join(", ")}`,details:{cyclicNodes:e}})}}validateRequiredWorkflowOutputs(e,t,o){const n=new Set;for(const e of t.values())for(const t of e)t.targetNodeId===Vt&&n.add(t.targetPort);for(const t of e.outputs)!0===t.required&&void 0===t.defaultValue&&(n.has(t.id)||o.push({code:"topology.required-output-unsatisfiable",path:`outputs[${t.id}]`,message:`Required workflow output '${t.id}' has no incoming edge from any node`}))}validateCapabilities(e,t){for(const o of e){const e=o.manifest;for(const n of e.capabilities??[])gt(n)||t.push({code:"capability.invalid",path:`nodes[${o.instance.id}]`,message:`Kind '${e.kind}' declares unknown capability '${n+""}'`,nodeId:o.instance.id,details:{capability:n+""}});!0!==e.policies?.allowUndeclaredParameters&&o.instance.loop&&((e.capabilities??[]).includes("loop")||t.push({code:"capability.loop-not-supported",path:`nodes[${o.instance.id}].loop`,message:`Node '${o.instance.id}' carries loop configuration but kind '${e.kind}' does not declare the 'loop' capability`,nodeId:o.instance.id}))}}}let Rn=class extends B{constructor(){super()}async plan(e,...t){const{log:o}=(await this.logCtx(t,"plan",!0)).for(this.plan);if(o.debug(`Planning resolved workflow '${e?.document?.id??"unknown"}'`),!Sn(e))throw new ho("GraphExecutionPlanner.plan accepts only a GraphResolvedWorkflow produced by the nine-stage validation gate; raw workflow definitions and inline node definitions are rejected",{received:(n=e,n&&"object"==typeof n?{reason:"input is not a GraphResolvedWorkflow",looksLikeWorkflowDefinition:"nodes"in n&&"relations"in n&&!("nodeById"in n),hasResolvedNodes:Array.isArray(n.nodes)}:{reason:"input is not an object"})});var n;const r=this.buildPlanNodes(e),i=this.buildPlanEdges(e),a=this.buildIncomingMap(i),s=this.buildOutgoingMap(i),d=this.topologicalLayers(r,i);return{resolved:e,workflowId:e.document.id||e.document.name,nodes:r,edges:i,layers:d,incomingByNode:a,outgoingByNode:s}}buildPlanNodes(e){return e.nodes.map(e=>({id:e.instance.id,kind:e.manifest.kind,instance:e.instance,manifest:e.manifest,executor:e.executor,inputPorts:e.manifest.inputs.map(e=>e.id),outputPorts:e.manifest.outputs.map(e=>e.id),connectionPorts:(e.manifest.connections??[]).map(e=>e.id),metadata:e.instance.metadata}))}buildPlanEdges(e){return e.edges.map(e=>({id:e.id,type:e.type,sourceNodeId:e.sourceNodeId,sourcePort:e.sourcePort,targetNodeId:e.targetNodeId,targetPort:e.targetPort,...void 0!==e.label?{label:e.label}:{},metadata:e.metadata}))}buildIncomingMap(e){const t=new Map;for(const o of e){if(o.targetNodeId===Vt)continue;const e=t.get(o.targetNodeId)??[];e.push(o),t.set(o.targetNodeId,e)}return t}buildOutgoingMap(e){const t=new Map;for(const o of e){if(o.sourceNodeId===Vt)continue;const e=t.get(o.sourceNodeId)??[];e.push(o),t.set(o.sourceNodeId,e)}return t}topologicalLayers(e,t){const o=e.filter(e=>e.id!==Vt),n=new Set(o.map(e=>e.id)),r=t.filter(e=>n.has(e.sourceNodeId)&&n.has(e.targetNodeId)),i=new Map;for(const e of o)i.set(e.id,0);for(const e of r)i.set(e.targetNodeId,(i.get(e.targetNodeId)??0)+1);const a=[],s=new Set;let d=o.filter(e=>0===(i.get(e.id)??0)),l=0;for(;d.length>0;){const e={index:l++,nodes:d};a.push(e);const t=[];for(const e of d){s.add(e.id);const n=r.filter(t=>t.sourceNodeId===e.id);for(const e of n){const n=(i.get(e.targetNodeId)??1)-1;if(i.set(e.targetNodeId,n),0===n&&!s.has(e.targetNodeId)){const n=o.find(t=>t.id===e.targetNodeId);n&&t.push(n)}}}d=t}if(s.size!==o.length){const e=o.filter(e=>!s.has(e.id)).map(e=>e.id);throw new ao({unplannedNodes:e,workflowId:o[0]?.manifest.kind})}return a}};Rn=S([F(),D("design:paramtypes",[])],Rn);const $n=new Set(["engine","valueAdapter","codeSandboxEvaluator","workflowStore"]);function Cn(e,t){const o={};for(const[n,r]of Object.entries(e??{}))$n.has(n)&&!t.has(n)||(o[n]=r);return o}class Tn extends W{constructor(){super()}async initialize(...e){const t=e[0];if(!t||"object"!=typeof t||!t.registry)return this._config=void 0,this._client=void 0,{config:void 0,client:void 0};const o=t.catalogue??t.registry.catalog,n=t.valueAdapter??q.current;if(!n)throw new io("GraphExecutionEngine requires a Decaf adapter for cached/pinned values: pass `valueAdapter` or configure one via `Adapter.setCurrent(...)`","GRAPH_VALUE_ADAPTER_MISSING");const r=t.backend??Fo.current??new wn,i={registry:t.registry,catalogue:o,planner:t.planner??new Rn,backend:r,valueAdapter:n,eventEmitter:t.eventEmitter??new yo,documentValidator:t.documentValidator??new Pn({catalogue:o,limits:t.documentLimits,credentialAuthorizer:t.credentialAuthorizer}),authValidator:new $o({enabled:!0===t.authEnabled,...t.authMatch?{match:t.authMatch}:{}}),...t.codeSandboxEvaluator?{codeSandboxEvaluator:t.codeSandboxEvaluator}:{}};this._config=t,this._client=i;const a=new Set(["engine","valueAdapter"]);t.codeSandboxEvaluator&&a.add("codeSandboxEvaluator"),t.workflowStore&&a.add("workflowStore");const s=Cn(r.config,a);if(await r.initialize({...s,valueAdapter:n,...t.codeSandboxEvaluator?{codeSandboxEvaluator:t.codeSandboxEvaluator}:{},...t.workflowStore?{workflowStore:t.workflowStore}:{},engine:this}),t.seedWorkflows&&t.seedWorkflows.length>0){const o=r.seedWorkflows;if("function"!=typeof o)throw new io(`Graph execution backend '${r.constructor?.name??"GraphExecutionBackend"}' does not support workflow seeding`,"GRAPH_BACKEND_SEED_NOT_SUPPORTED",{backend:r.constructor?.name??"GraphExecutionBackend"});await o.call(r,t.seedWorkflows,...e.slice(1))}return await(t.onEngineCreated?.(this)),{config:t,client:i}}get codeSandboxEvaluator(){return this.client.codeSandboxEvaluator}get emitter(){return this.client.eventEmitter}get planner(){return this.client.planner}get valueAdapter(){return this.client.valueAdapter}get defaultOptions(){return this.config.defaultOptions??{}}get documentValidator(){return this.client.documentValidator}observe(e){return this.emitter.observe(e)}unObserve(e){this.emitter.unObserve(e)}async dispatchEvent(e){await this.emitter.updateObservers(e)}async execute(e,t={},o={},...n){const{log:r,ctx:i}=(await this.logCtx(n,"execute",!0)).for(this.execute);r.debug(`Executing workflow '${e.id||e.name}'`);const a=this.mergeOptions(o);this.assertNotAborted(a);const s=Ro(Do(i),a.auth);a.auth=s,a.metadata={...a.metadata??{},...s};const d=a.runId??this.generateRunId();a.runId=d;const l=a.path??[],c=new wo,u=un(this.valueAdapter);u.seedWorkflowInputs(this.withWorkflowInputDefaults(e,t));const p=new Go(this.emitter,c,{runId:d,parentRunId:a.parentRunId,workflowId:e.id||e.name,path:l,engine:this,...this.codeSandboxEvaluator?{codeSandboxEvaluator:this.codeSandboxEvaluator}:{}});await p.emit({type:ce.VALIDATION_STARTED,status:se.PLANNING});const h=await this.documentValidator.validate(e,0,i);if(!h.valid||!h.resolved)throw await p.emit({type:ce.VALIDATION_FAILED,status:se.FAILED,payload:{issues:h.issues}}),new kn(`Graph workflow document '${e.id}' failed validation with ${h.issues.length} issue(s)`,h.issues);await p.emit({type:ce.VALIDATION_COMPLETED,status:se.PLANNING,payload:{issues:h.issues.length}}),this.assertNotAborted(a);const f=await this.planner.plan(h.resolved);this.client.authValidator.validate(e,f,s,r),r.debug(`Authorized workflow '${e.id||e.name}' for user ${s.user??"anonymous"}`),this.assertCodeModeSupported(e);const g=new Mo(d,f,u,c);return p.bindFrame(g),await p.emit({type:ce.WORKFLOW_STARTED,runId:d,parentRunId:a.parentRunId,workflowId:f.workflowId,path:l,status:se.RUNNING,payload:{inputs:t}}),await p.emit({type:ce.WORKFLOW_PLANNED,runId:d,parentRunId:a.parentRunId,workflowId:f.workflowId,path:l,status:se.PLANNING,payload:{layers:f.layers.length,nodes:f.nodes.length}}),await this.client.backend.execute({document:e,plan:f,inputs:t,options:a,events:p},...n)}get backend(){return this.client.backend}get backendCapabilities(){return Uo(this.client.backend)}async listWorkflows(...e){const t=this.client.backend;if("supported"!==Uo(t).workflows.list||"function"!=typeof t.listWorkflows)throw new io(`Graph execution backend '${this.backendName}' does not support workflow listing`,"GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED",{backend:this.backendName});return await t.listWorkflows(...e)}async getWorkflow(e,...t){const o=this.client.backend;if("supported"!==Uo(o).workflows.get||"function"!=typeof o.getWorkflow)throw new io(`Graph execution backend '${this.backendName}' does not support workflow lookup`,"GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED",{backend:this.backendName,workflowId:e});return await o.getWorkflow(e,...t)}async listEngineWorkflows(e,...t){const o=Fo.getOrFail(e);if("supported"!==Uo(o).workflows.list||"function"!=typeof o.listWorkflows)throw new io(`Graph execution backend '${e}' does not support workflow listing`,"GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED",{backend:e});return await o.listWorkflows(...t)}async getEngineWorkflow(e,t,...o){const n=Fo.getOrFail(e);if("supported"!==Uo(n).workflows.get||"function"!=typeof n.getWorkflow)throw new io(`Graph execution backend '${e}' does not support workflow lookup`,"GRAPH_BACKEND_WORKFLOWS_NOT_SUPPORTED",{backend:e,workflowId:t});return await n.getWorkflow(t,...o)}get backendName(){return this.client.backend.constructor?.name??"GraphExecutionBackend"}assertCodeModeSupported(e){const t=this.client.backend;if(t.local)return;const o=Yo(e);if(0!==o.length){if("unsupported"===t.codeMode)throw new io(`Graph execution backend '${this.backendName}' does not support code-mode workflows`,"GRAPH_CODE_MODE_UNSUPPORTED_BACKEND",{backend:this.backendName,surfaces:o});if(!this.codeSandboxEvaluator)throw new io("Code-mode workflows require a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{backend:this.backendName,surfaces:o})}}async pinNode(e){const t=this.createPinningService();await t.pinNode(e),await this.emitPinningEvent(e.nodeId,ce.NODE_PINNED)}async unpinNode(e){const t=this.createPinningService();await t.unpinNode(e),await this.emitPinningEvent(e.nodeId,ce.NODE_UNPINNED)}createPinningService(){const e=un(this.valueAdapter);return new hn(e,new mn,new yn)}async emitPinningEvent(e,t){const o=(new wo).create({id:"",sequence:0,timestamp:new Date,runId:"pinning",workflowId:"",type:t,nodeId:e,path:[]});await this.emitter.updateObservers(o)}withWorkflowInputDefaults(e,t){const o={...t};for(const t of e.inputs)void 0===o[t.id]&&void 0!==t.defaultValue&&(o[t.id]=t.defaultValue);return o}mergeOptions(e){return{concurrency:4,failFast:!0,validateInputs:!0,validateOutputs:!0,maxLoopIterations:Qt,maxForeachIterations:Zt,usePinnedValues:!0,writeThroughCache:!1,path:[],metadata:{},...this.defaultOptions,...e}}assertNotAborted(e){if(!0===e.abortSignal?.aborted)throw new go(e.runId??"unknown")}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new io("Cannot generate a graph run id: crypto.randomUUID is unavailable in this runtime","GRAPH_RUN_ID_ERROR",{runtime:typeof globalThis.crypto});return e.randomUUID()}}const Ln=new Set(["process","require","module","exports","global","globalThis","Function","eval","fetch","XMLHttpRequest","WebSocket","Worker","Deno","Bun","__dispatch"]);class Mn extends W{constructor(){super()}async initialize(...e){const t=e[0]??{},o=t&&"object"==typeof t?t:{};return this._config=o,this._client=V,{config:o,client:V}}get defaultTimeoutMs(){return this.config.timeoutMs??1e3}get defaultMemoryMb(){return this.config.memoryMb??32}async evaluate(e,...t){(await this.logCtx(t,"evaluate",!0)).for(this.evaluate);const o=e.code;if(!o||"string"!=typeof o||0===o.trim().length)throw new io("Code sandbox received empty code","GRAPH_CODE_SANDBOX_EMPTY_CODE");const n=((e,t)=>"javascript"===t?e:X.transpileModule(e,{compilerOptions:{target:X.ScriptTarget.ES2022,module:X.ModuleKind.None,strict:!0,noEmitHelpers:!0,importHelpers:!1}}).outputText.replace(/^"use strict";\s*/,""))(o,e.language??"javascript");(e=>{if(e.length>1e5)throw new io("Code exceeds the maximum length of 100000 characters","GRAPH_CODE_SANDBOX_CODE_TOO_LONG",{length:e.length});let t;try{t=z.parse(`async function __validate() {\n${e}\n}`,{ecmaVersion:"latest",sourceType:"script"})}catch{try{t=z.parse(e,{ecmaVersion:"latest",sourceType:"module"})}catch(t){throw new io("Code failed to parse: "+t.message,"GRAPH_CODE_SANDBOX_PARSE_ERROR",{code:e,error:t.message})}}J.full(t,e=>{const t=e;if("ImportDeclaration"===t.type)throw new io("Imports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"import"});if("ExportNamedDeclaration"===t.type||"ExportDefaultDeclaration"===t.type)throw new io("Exports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"export"});if("Identifier"===t.type&&"string"==typeof t.name&&Ln.has(t.name))throw new io(`Identifier "${t.name}" is not allowed in Code nodes.`,"GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:t.name});if("NewExpression"===t.type&&"Function"===t.callee?.name)throw new io("new Function() is not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"Function"});if("CallExpression"===t.type&&"eval"===t.callee?.name)throw new io("eval() is not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"eval"})})})(n);const r=!(e=>/\breturn\b[\s;]/.test(e))(n),i=r?n.replace(/[\s;]+$/,""):n,a={$input:e.input??{},$vars:e.vars??{},$item:e.item,$index:e.index,$node:e.nodes??{},$output:void 0},s=Object.keys(a),d=r?`return (${i});`:i,l=`"use strict";\nasync function __userFunction(${s.join(", ")}) {\n${d}\n}\n__userFunction(${s.join(", ")}).then(function(__r) { return JSON.stringify({ v: __r }); });`,c=new V.Isolate({memoryLimit:this.defaultMemoryMb}),u=await c.createContext();try{const t=u.global;e.logger&&await this.injectConsole(u,e.logger);for(const[e,o]of Object.entries(a))await t.set(e,new V.ExternalCopy(void 0===o?null:o).copyInto());let o;try{o=await c.compileScript(l,{filename:"graph-code-node.js"})}catch(e){if(!r)throw new io("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message});{const e=i,t=`"use strict";\nasync function __userFunction(${s.join(", ")}) {\n${e}\n}\n__userFunction(${s.join(", ")}).then(function(__r) { return JSON.stringify({ v: __r }); });`;try{o=await c.compileScript(t,{filename:"graph-code-node.js"})}catch(e){throw new io("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message})}}}const d=e.timeoutMs??this.defaultTimeoutMs;let p;try{p=await this.runBounded(o,u,d,e.abortSignal)}catch(e){if(e instanceof io)throw e;const t=e.message;if(t.includes("timed out")||t.includes("timeout"))throw new io(`Code execution timed out after ${d} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:d});if(t.includes("memory")||t.includes("heap"))throw new io(`Code exceeded the memory limit of ${this.defaultMemoryMb} MB`,"GRAPH_CODE_SANDBOX_MEMORY_LIMIT",{memoryMb:this.defaultMemoryMb});throw new io("Code execution failed: "+t,"GRAPH_CODE_SANDBOX_RUNTIME_ERROR",{code:n,error:t})}if("string"!=typeof p)throw new io("Code sandbox returned an unexpected non-string result","GRAPH_CODE_SANDBOX_UNEXPECTED_RESULT",{result:p});return JSON.parse(p).v}finally{u.release(),c.dispose()}}async runBounded(e,t,o,n){const r=e.run(t,{timeout:o,promise:!0});r.catch(()=>{});const i=[r];let a,s;try{return i.push(new Promise((e,t)=>{a=setTimeout(()=>{t(new io(`Code execution timed out after ${o} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:o}))},o+100)})),n&&i.push(new Promise((e,t)=>{const r=()=>{const e="timeout"===n.reason;t(new io(e?`Code execution timed out after ${o} ms`:"Code execution aborted",e?"GRAPH_CODE_SANDBOX_TIMEOUT":"GRAPH_CODE_SANDBOX_ABORTED",{timeoutMs:o,reason:n.reason}))};n.aborted?r():(n.addEventListener("abort",r,{once:!0}),s=()=>n.removeEventListener("abort",r))})),await Promise.race(i)}finally{a&&clearTimeout(a),s?.()}}async injectConsole(e,t){const o=new V.Reference((e,o)=>{let n;try{n=JSON.parse(o)}catch{n=[o]}const r=n.map(e=>"string"==typeof e?e:JSON.stringify(e)).join(" "),i=1===n.length?n[0]:n;switch(e){case"log":case"info":default:t.info(r,i);break;case"warn":t.warn(r,i);break;case"error":t.error(r,i);break;case"debug":case"dir":case"dirxml":case"table":t.debug(r,i);break;case"trace":t.trace(r,i);break;case"group":case"groupCollapsed":t.debug("[group] "+r,i);break;case"groupEnd":t.debug("[groupEnd]",void 0);break;case"time":case"timeEnd":case"timeLog":case"count":case"countReset":t.debug(`[${e}] ${r}`,i);break;case"assert":n[0]||t.error("Assertion failed: "+r,i);case"clear":}});await e.evalClosure("\n function __ser() {\n var out = [];\n for (var i = 0; i < arguments.length; i++) {\n var a = arguments[i];\n try { out.push(typeof a === 'object' ? JSON.parse(JSON.stringify(a)) : a); }\n catch (e) { out.push(String(a)); }\n }\n return JSON.stringify(out);\n }\n function __call(level) {\n return function() {\n $0.applySync(undefined, [level, __ser.apply(null, arguments)]);\n };\n }\n globalThis.console = {\n log: __call('log'),\n info: __call('info'),\n warn: __call('warn'),\n error: __call('error'),\n debug: __call('debug'),\n trace: __call('trace'),\n dir: __call('dir'),\n dirxml: __call('dirxml'),\n table: __call('table'),\n group: __call('group'),\n groupCollapsed: __call('groupCollapsed'),\n groupEnd: __call('groupEnd'),\n time: __call('time'),\n timeEnd: __call('timeEnd'),\n timeLog: __call('timeLog'),\n assert: __call('assert'),\n count: __call('count'),\n countReset: __call('countReset'),\n clear: __call('clear')\n };\n ",[o]),o.release()}}class jn extends x{constructor(e){super(e,jn.name,500)}}class Gn extends _{constructor(e){super(e),this.name=Gn.name}}class Un extends _{constructor(e){super(e),this.name=Un.name}}class Fn{constructor(e,t,o={}){this.kind=e,this.declarations=new Map,this.implementations=new Map;for(const e of t){if("string"!=typeof e?.name||!e.name)throw new jn(`Method declaration for kind '${this.kind}' is missing a name`);if(this.declarations.has(e.name))throw new jn(`Kind '${this.kind}' declares duplicate method '${e.name}'`);this.declarations.set(e.name,e)}for(const[e,t]of Object.entries(o)){if("function"!=typeof t)throw new jn(`Method implementation '${e}' for kind '${this.kind}' is not a function`);if(!this.declarations.has(e))throw new jn(`Kind '${this.kind}' implements method '${e}' which is not declared by its manifest`);this.implementations.set(e,t)}for(const e of this.declarations.keys())if(!this.implementations.has(e))throw new jn(`Kind '${this.kind}' declares method '${e}' with no implementation`)}has(e){return this.declarations.has(e)}getDeclaration(e){const t=this.declarations.get(e);if(!t)throw new Un(`Kind '${this.kind}' does not declare method '${e}'`);return t}get(e){return this.getDeclaration(e),this.implementations.get(e)}list(){return[...this.declarations.values()].sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}}function Bn(e,t){if(!t)return;let o=e;for(const e of t.split(".")){if(!o||"object"!=typeof o)return;o=o[e]}return o}function Wn(e,t,o){const n=Bn(t,e.itemIdPath),r=e.itemLabelPath?Bn(t,e.itemLabelPath):void 0;return{id:"string"==typeof n&&n||"number"==typeof n&&Number.isFinite(n)&&n+""||o+"",label:"string"==typeof r?r:void 0}}function qn(e,t){switch(t){case"input":return e.inputs;case"output":return e.outputs;default:return e.connections}}function Hn(e,t){const o={inputs:[],outputs:[],connections:[]},n={input:new Set((e.inputs??[]).map(e=>e.id)),output:new Set((e.outputs??[]).map(e=>e.id)),connection:new Set((e.connections??[]).map(e=>e.id))},r=(e,t)=>{const o=n[e];return!o.has(t)&&(o.add(t),!0)};for(const n of e.dynamicPorts??[])if("repeatFromParameter"===n.type){const e=t[n.parameter];if(!Array.isArray(e))continue;const i=qn(o,n.direction);e.forEach((e,t)=>{const{id:o,label:a}=Wn(n,e,t),s=(d={id:o,index:t,label:a??o},n.portIdTemplate.replaceAll("${id}",d.id).replaceAll("${index}",d.index+"").replaceAll("${label}",d.label));var d;if(!r(n.direction,s))return;const l=n.defaultPort?Fe(n.defaultPort):{id:s,label:a??s,direction:n.direction};l.id=s,l.direction=n.direction,a&&(l.label=a),i.push(l)})}else if("togglePort"===n.type){if(t[n.parameter]!==n.equals)continue;const e=Fe(n.port);if(!r(e.direction,e.id))continue;qn(o,e.direction).push(e)}return o}function Kn(e,t){const o=Hn(e,t),n={kind:e.kind,display:e.display,inputs:[...e.inputs,...o.inputs],outputs:[...e.outputs,...o.outputs],parameters:e.parameters},r=[...e.connections??[],...o.connections];return r.length&&(n.connections=r),e.dynamicPorts?.length&&(n.dynamicPorts=e.dynamicPorts),e.credentials?.length&&(n.credentials=e.credentials),e.capabilities?.length&&(n.capabilities=e.capabilities),e.policies&&(n.policies=e.policies),e.metadata&&(n.metadata=e.metadata),e.namespaces?.length&&(n.namespaces=e.namespaces),Fe(n)}class Vn{async resolve(e,t,o,n,r){if(o){const i=await o(n,r);if(!(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.kind&&"object"==typeof t.display&&null!==t.display&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.parameters)})(i))throw new jn(`resolveManifest provider for kind '${e}' returned a value that does not conform to GraphResolvedNodeManifest`);if(!Ue(i))throw new jn(`resolveManifest provider for kind '${e}' returned a non-JSON-safe resolved manifest`);const a=Fe(i);return!a.namespaces?.length&&t.namespaces?.length&&(a.namespaces=t.namespaces.slice()),a}return Kn(t,n.parameters??{})}}const zn=["edge","literal","expression"];function Jn(e){return zn.includes(e)}function Xn(e,t,o){if("string"!=typeof o||!o)throw new jn(`Manifest for kind '${e}' has a ${t} with an empty port id`);if(Le(o))throw new jn(`Manifest for kind '${e}' has a ${t} with unsafe port id '${o}'`)}let Yn=class extends B{constructor(){super(),this.entries=new Map,this.resolver=new Vn,this.fallbackContext=new M}withContext(e){return e[e.length-1]instanceof M?e:[this.fallbackContext]}register(e,t={},...o){const{log:n}=this.logCtx(this.withContext(o),"register").for(this.register);n.debug(`Registering graph node kind '${e?.manifest?.kind??"unknown"}'`),(e=>{if(!e||"object"!=typeof e)throw new jn("Graph node registration is required");if(!e.manifest||"object"!=typeof e.manifest)throw new jn("Graph node registration is missing a manifest");if(!e.executor||"function"!=typeof e.executor.execute)throw new jn(`Graph node registration for kind '${e.manifest?.kind+""}' is missing an executor`)})(e);const r=e.manifest;if("string"!=typeof r.kind||!r.kind.trim())throw new jn("Graph node manifest kind is required and must be a non-empty string");const i=r.kind;if(this.entries.has(i)&&!t.replace)throw new jn(`Graph node kind '${i}' is already registered; pass { replace: true } to replace it`);try{yt(r)}catch(e){throw new jn(`Manifest for kind '${i}' is not JSON-serializable: ${e.message}`)}((e,t)=>{const o=[["input",t.inputs],["output",t.outputs],["connection",t.connections??[]]];for(const[t,n]of o){const o=new Set;for(const r of n){if(Xn(e,t+" port",r?.id),o.has(r.id))throw new jn(`Manifest for kind '${e}' declares duplicate static ${t} port id '${r.id}'`);if(o.add(r.id),void 0!==r.defaultMode&&!Jn(r.defaultMode))throw new jn(`Manifest for kind '${e}' declares invalid default binding mode '${r.defaultMode+""}' on ${t} port '${r.id}'`)}}})(i,r);const a=((e,t)=>{const o=new Set;for(const n of t.parameters){const t=n?.id;if("string"!=typeof t||!t)throw new jn(`Manifest for kind '${e}' has a parameter with an empty id`);if(Le(t))throw new jn(`Manifest for kind '${e}' has a parameter with unsafe id '${t}'`);if(o.has(t))throw new jn(`Manifest for kind '${e}' declares duplicate parameter id '${t}'`);o.add(t)}return o})(i,r);((e,t,o)=>{for(const n of t.dynamicPorts??[]){if(!n||"string"!=typeof n.parameter||!n.parameter)throw new jn(`Manifest for kind '${e}' has a dynamic-port rule without a parameter reference`);if(!o.has(n.parameter))throw new jn(`Manifest for kind '${e}' has a dynamic-port rule referencing missing parameter '${n.parameter}'`);if("togglePort"===n.type){if(!n.port)throw new jn(`Manifest for kind '${e}' has a togglePort rule without a port`);Xn(e,"togglePort rule port",n.port.id)}if("repeatFromParameter"===n.type&&"string"!=typeof n.portIdTemplate)throw new jn(`Manifest for kind '${e}' has a repeatFromParameter rule without a portIdTemplate`)}})(i,r,a),((e,t)=>{for(const o of t.credentials??[]){if(!ht(o))throw new jn(`Manifest for kind '${e}' has a malformed credential requirement`);if(!o.type)throw new jn(`Manifest for kind '${e}' has a credential requirement with an empty type`)}})(i,r),((e,t)=>{for(const o of t.methods??[])if(!It(o))throw new jn(`Manifest for kind '${e}' has a malformed method declaration`)})(i,r);const s=new Fn(i,r.methods??[],e.methods??{});return this.entries.set(i,{registration:e,methods:s,placeholderManifest:!1}),this}registerExecutor(e,t,...o){const{log:n}=this.logCtx(this.withContext(o),"registerExecutor").for(this.registerExecutor);if(n.debug(`Registering graph executor for kind '${e}'`),"string"!=typeof e||!e.trim())throw new jn("Graph executor kind is required");if(!t||"function"!=typeof t.execute)throw new jn(`Executor registered for kind '${e}' is missing an execute method`);const r=this.entries.get(e);if(r)return r.registration={...r.registration,executor:t},this;const i={kind:e,display:{name:e},inputs:[],outputs:[],parameters:[],policies:{allowUndeclaredParameters:!0,allowUnknownOutputs:!0}};return this.entries.set(e,{registration:{manifest:i,executor:t},methods:new Fn(e,[],{}),placeholderManifest:!0}),this}unregister(e,...t){const{log:o}=this.logCtx(this.withContext(t),"unregister").for(this.unregister);return o.debug(`Unregistering graph node kind '${e}'`),this.entries.delete(e),this}has(e,...t){return this.logCtx(this.withContext(t),"has").for(this.has),this.entries.has(e)}entry(e){const t=this.entries.get(e);if(!t)throw new Gn(`No graph node kind '${e}' is registered in the catalogue`);return t}getManifest(e,...t){return this.logCtx(this.withContext(t),"getManifest").for(this.getManifest),Fe(this.entry(e).registration.manifest)}getExecutor(e,...t){return this.logCtx(this.withContext(t),"getExecutor").for(this.getExecutor),this.entry(e).registration.executor}getMethodDeclaration(e,t,...o){return this.logCtx(this.withContext(o),"getMethodDeclaration").for(this.getMethodDeclaration),this.entry(e).methods.getDeclaration(t)}getMethod(e,t,...o){return this.logCtx(this.withContext(o),"getMethod").for(this.getMethod),this.entry(e).methods.getDeclaration(t),this.entry(e).methods.get(t)}listMethodDeclarations(e,...t){return this.logCtx(this.withContext(t),"listMethodDeclarations").for(this.listMethodDeclarations),this.entry(e).methods.list()}listManifests(e,...t){this.logCtx(this.withContext(t),"listManifests").for(this.listManifests);const o=[...this.entries.keys()].sort(),n=e?.categories?.length?new Set(e.categories):void 0,r=e?.kinds?.length?new Set(e.kinds):void 0,i=[];for(const e of o){if(r&&!r.has(e))continue;const o=this.getManifest(e,...t);n&&!n.has(o.display.category??"")||i.push(o)}return i}listKinds(...e){return this.logCtx(this.withContext(e),"listKinds").for(this.listKinds),[...this.entries.keys()].sort()}get size(){return this.entries.size}async resolveManifest(e,t,o,...n){this.logCtx(this.withContext(n),"resolveManifest").for(this.resolveManifest);const r=this.entry(e);return this.resolver.resolve(e,r.registration.manifest,r.registration.resolveManifest,t,o)}};Yn=S([F(),D("design:paramtypes",[])],Yn);let Qn=class extends B{constructor(e=new Yn){super(),this.catalogue=e}get catalog(){return this.catalogue}register(e,t,...o){const{log:n}=this.logCtx(o,"register").for(this.register);if(n.debug(`Registering graph executor for kind '${e}'`),!e)throw new io("Graph executor kind is required");return this.catalogue.registerExecutor(e,t,...o),this}unregister(e,...t){const{log:o}=this.logCtx(t,"unregister").for(this.unregister);return o.debug(`Unregistering graph executor for kind '${e}'`),this.catalogue.unregister(e,...t),this}has(e,...t){return this.logCtx(t,"has").for(this.has),this.catalogue.has(e,...t)}resolve(e,...t){this.logCtx(t,"resolve").for(this.resolve);try{return this.catalogue.getExecutor(e,...t)}catch(t){if(t instanceof Gn)throw new io(`No graph executor registered for kind '${e}'`,"GRAPH_EXECUTOR_NOT_FOUND",{kind:e});throw t}}};Qn=S([F(),D("design:paramtypes",[Yn])],Qn);let Zn=class extends B{constructor(e,t){super(),this.registry=e,this.defaultExecutor=t}resolve(e,...t){const{log:o}=this.logCtx(t,"resolve").for(this.resolve);return o.debug(`Resolving graph executor for kind '${e}'`),this.registry.has(e,...t)?this.registry.resolve(e,...t):this.defaultExecutor?this.defaultExecutor:this.registry.resolve(e,...t)}};function er(e){return e}function tr(e){return e.methods??[]}function or(e){if(!e)return;const t={...e.metadata??{},...e.parameters??{},...e.state??{}};return e.loop&&(t.loop=e.loop),t}Zn=S([F(),D("design:paramtypes",[Function,Object])],Zn);class nr extends w{constructor(e){super(),w.fromModel(this,e)}execute(e,t){throw new io(`Graph node kind '${this.constructor.name}' does not implement execute`,"GRAPH_NODE_EXECUTE_NOT_IMPLEMENTED",{kind:this.constructor.name})}static applyMetadata(e){return null}static instantiate(e){return new this(e)}}let rr=class extends nr{execute(e,t){throw new fo(e.inputs.value)}};function ir(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack,code:e.graphCode??("number"==typeof e.code?e.code+"":e.code)}:{name:"UnknownError",message:e+""}}S([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.break.fields.value.label",placeholder:"graph.node.flow_control.break.fields.value.placeholder",type:"textarea"}),Re({handle:"value"}),D("design:type",Object)],rr.prototype,"value",void 0),rr=S([De("core.flow.break",{kind:"core.flow.break",category:"Flow Control",color:"#f59e0b",icon:"ti-square-arrow-right",width:96,height:96,labels:["flow","break","loop","control"],metadata:{title:"graph.node.flow_control.break.name",description:"graph.node.flow_control.break.description"}}),E()],rr);let ar=class extends nr{async execute(e,t){const o=t.node.errorBoundary;if(!o?.try)return{result:e.inputs.value??e.inputs};const n=t.engine;if(!n)throw new io("errorBoundary node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");try{const r=await n.execute(o.try,e.inputs,{parentRunId:t.runId,path:[...t.path,"try"]}),i=Object.values(r.nodeResults).find(e=>e.status===se.FAILED);if(i)throw new io(i.error?.message??"error boundary try body failed",i.error?.code??"GRAPH_ERROR_BOUNDARY",i.error?.details);return{result:r.outputs.result??r.outputs}}catch(r){let i=r;if(o.catch){const a=await n.execute(o.catch,{...e.inputs,error:ir(r)},{parentRunId:t.runId,path:[...t.path,"catch"]});i=a.outputs.error??a.outputs}return{error:i}}finally{o.finally&&await n.execute(o.finally,e.inputs,{parentRunId:t.runId,path:[...t.path,"finally"]})}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.error_boundary.fields.value.label",placeholder:"graph.node.flow_control.error_boundary.fields.value.placeholder",type:"textarea"}),Re({handle:"value"}),D("design:type",Object)],ar.prototype,"value",void 0),S([$e({handle:"result"}),D("design:type",Object)],ar.prototype,"result",void 0),S([$e({handle:"error"}),D("design:type",Object)],ar.prototype,"error",void 0),ar=S([De("core.flow.errorBoundary",{kind:"core.flow.errorBoundary",category:"Flow Control",color:"#f59e0b",icon:"ti-shield-check",width:96,height:96,labels:["flow","error","try-catch"],metadata:{title:"graph.node.flow_control.error_boundary.name",description:"graph.node.flow_control.error_boundary.description",finally:!1}}),E()],ar);let sr=class extends nr{execute(e){const t=e.inputs.value??e.inputs;return!1===this.approved?{rejected:t}:{approved:t}}};S([b(),Re({handle:"value"}),D("design:type",Object)],sr.prototype,"value",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.human_approval.fields.message.label",placeholder:"graph.node.flow_control.human_approval.fields.message.placeholder",type:"textarea"}),Re({handle:"message",userControlled:!0}),D("design:type",String)],sr.prototype,"message",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.human_approval.fields.approved.label",type:"checkbox"}),Re({handle:"approved",userControlled:!0}),D("design:type",Boolean)],sr.prototype,"approved",void 0),S([$e({handle:"approved"}),D("design:type",Object)],sr.prototype,"approvedOut",void 0),S([$e({handle:"rejected"}),D("design:type",Object)],sr.prototype,"rejectedOut",void 0),sr=S([De("core.flow.humanApproval",{kind:"core.flow.humanApproval",category:"Flow Control",color:"#f59e0b",icon:"ti-user-check",width:96,height:96,labels:["flow","approval","suspend"],metadata:{title:"graph.node.flow_control.human_approval.name",description:"graph.node.flow_control.human_approval.description",approvers:[],timeoutMs:864e5}}),E()],sr);let dr=class extends nr{execute(e,t){const o=e.inputs,n=o.value??o;if(!this.condition)throw new io("If node has no condition configured","GRAPH_IF_NO_CONDITION",{input:o});if(Wo(this.condition))return Ho(this.condition,o,t).then(e=>this.route(e,n));const r=Ko(this.condition,((e,t)=>t===e||"object"!=typeof t||null===t||Array.isArray(t)?e:{...t,...e})(o,n),"if");return this.route(r,n)}route(e,t){if(e)return{then:t};if(!0===this.else)return{else:t};throw new io("If node condition evaluated to false and the else branch is disabled","GRAPH_IF_ELSE_DISABLED",{condition:this.condition})}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.value.label",placeholder:"graph.node.flow_control.if.fields.value.placeholder",type:"textarea"}),Re({handle:"value"}),D("design:type",Object)],dr.prototype,"value",void 0),S([b(),$e({handle:"then"}),D("design:type",Object)],dr.prototype,"then",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.condition.label",placeholder:"graph.node.flow_control.if.fields.condition.placeholder",type:"code"}),Re({handle:"condition",userControlled:!0,type:"object"}),D("design:type",Object)],dr.prototype,"condition",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.else.label",type:"checkbox"}),Re({handle:"else",userControlled:!0}),D("design:type",Boolean)],dr.prototype,"else",void 0),dr=S([De("core.flow.if",{kind:"core.flow.if",category:"Flow Control",color:"#f59e0b",icon:"ti-arrows-split-2",width:96,height:96,labels:["flow","conditional","branch"],metadata:{title:"graph.node.flow_control.if.name",description:"graph.node.flow_control.if.description"}}),E()],dr);let lr=class extends nr{async execute(e,t){const o=((e,t)=>{const o={cases:t.cases??[],defaultPort:t.defaultPort??"default",hasDefault:!0===t.hasDefault},n=e.node.metadata?.switch;return n&&Array.isArray(n.cases)?{cases:n.cases,defaultPort:n.defaultPort??o.defaultPort,hasDefault:!0===n.hasDefault||o.hasDefault}:o})(t,this),n=o.cases,r=e.inputs,i=r.value??r,a=((e,t)=>t===e||"object"!=typeof t||null===t||Array.isArray(t)?e:{...t,...e})(r,i);for(const e of n)if(await Vo(e.condition,{input:r,state:a,label:"switch case"},t))return{[e.outputPort]:i};if(!0!==o.hasDefault)throw new io("No switch case matched and default port is not enabled","GRAPH_SWITCH_NO_MATCH",{cases:n.map(e=>e.id)});const s=o.defaultPort??"default";return{[s]:i}}static applyMetadata(e){const t=xe(this),o=e.defaultPort??"default",n=!0===e.hasDefault,r=t.ports.filter(t=>!e.cases.some(e=>e.outputPort===t.property)),i=r.filter(e=>e.property!==o),a=r.find(e=>e.property===o),s=[...i,...e.cases.map(e=>({property:e.outputPort,name:e.label,direction:Z.OUTPUT,label:e.label,required:!1,hidden:!1,path:e.outputPort}))];return n&&a&&s.push(a),{ports:s,size:te(t,{cases:e.cases.length}),dataPatch:{switchMetadata:e}}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.value.label",placeholder:"graph.node.flow_control.switch.fields.value.placeholder",type:"textarea"}),Re({handle:"value"}),D("design:type",Object)],lr.prototype,"value",void 0),S([b(),$e({handle:"default"}),D("design:type",Object)],lr.prototype,"default",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.cases.label",type:"collection"}),D("design:type",Object)],lr.prototype,"cases",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.hasDefault.label",type:"checkbox"}),D("design:type",Boolean)],lr.prototype,"hasDefault",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.defaultPort.label",type:"text"}),D("design:type",String)],lr.prototype,"defaultPort",void 0),lr=S([De("core.flow.switch",{kind:"core.flow.switch",category:"Flow Control",color:"#f59e0b",icon:"ti-arrows-shuffle",width:120,height:140,sizeRules:[{type:"parameterCount",parameter:"cases",dimension:"height",perItem:24}],labels:["flow","switch","multi-branch"],metadata:{title:"graph.node.flow_control.switch.name",description:"graph.node.flow_control.switch.description"}}),E()],lr);const cr={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},ur=o.accumulate({graph:{workflows:{limits:{...cr},allowAnonymousAccess:!1},execution:{maxCodeTimeoutMs:eo}}}),pr=1e3;function hr(e,t){const o="number"==typeof t?t:Number(t),n=Number.isFinite(o)&&o>0?o:eo,r="number"==typeof e?e:Number(e);return Number.isFinite(r)&&r>0?Math.min(Math.floor(r),n):1e3}const fr=["javascript","typescript"],gr="javascript";let mr=class extends w{constructor(){super(...arguments),this.language=gr}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.language.label",type:"select"}),N([...fr]),v(String),D("design:type",String)],mr.prototype,"language",void 0),S([b(),i("code-editor",{label:"graph.node.utility.code.fields.code.label",placeholder:"graph.node.utility.code.fields.code.placeholder"}),Re({handle:"code"}),D("design:type",String)],mr.prototype,"code",void 0),S([d(),Re({handle:"data"}),D("design:type",Object)],mr.prototype,"data",void 0),mr=S([E()],mr);let yr=class extends nr{async execute(e,t){const o=e.inputs,n=this.input,r=o.code??e.parameters?.code??n?.code??this.defaultCode,i=n?.language??gr;if(!r||"string"!=typeof r||0===r.trim().length)throw new so("Code node has no code to execute (input.code is empty)",{input:o});const a=t.engine?.codeSandboxEvaluator;if(!a)throw new io("Code node execution requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{code:r});const s=ur.graph.execution?.maxCodeTimeoutMs,d="number"==typeof s&&Number.isFinite(s)&&s>0?s:eo,l=hr(this.timeoutMs,d),c=t.metadata,u={code:r,language:i,input:o,vars:c?.vars??void 0,item:c?.item,index:c?.index,nodes:c?.nodes??void 0,logger:t.logger,timeoutMs:l,abortSignal:t.abortSignal};await t.log("Executing code node",{language:i,length:r.length,timeoutMs:l});const p=await a.evaluate(u);return await t.log("Code node executed",{hasResult:void 0!==p}),{result:p}}};S([b(),Re({handle:"input",model:mr}),D("design:type",mr)],yr.prototype,"input",void 0),S([k(1),O(eo),i("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.timeoutMs.label",type:"number"}),Re({handle:"timeoutMs"}),D("design:type",Number)],yr.prototype,"timeoutMs",void 0),S([i("code-editor",{label:"graph.node.utility.code.fields.defaultCode.label",placeholder:"graph.node.utility.code.fields.defaultCode.placeholder"}),Re({handle:"defaultCode",userControlled:!0}),D("design:type",String)],yr.prototype,"defaultCode",void 0),S([b(),$e({handle:"result"}),D("design:type",Object)],yr.prototype,"result",void 0),yr=S([De("core.utility.code",{kind:"core.utility.code",category:"Utility",color:"#0d9488",icon:"ti-code",width:96,height:96,labels:["utility","code","sandbox","transform"],metadata:{title:"graph.node.utility.code.name",description:"graph.node.utility.code.description"}}),E()],yr);let wr=class extends nr{execute(e){return{value:e.inputs.value??e.inputs}}};S([b(),Re({handle:"value"}),D("design:type",Object)],wr.prototype,"value",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.utility.delay.fields.timeoutMs.label",type:"number"}),Re({handle:"timeoutMs"}),D("design:type",Number)],wr.prototype,"timeoutMs",void 0),S([b(),$e({handle:"value"}),D("design:type",Object)],wr.prototype,"valueOut",void 0),wr=S([De("core.flow.delay",{kind:"core.flow.delay",category:"Utility",color:"#0d9488",icon:"ti-clock-hour-4",width:96,height:96,labels:["flow","delay","wait"],metadata:{title:"graph.node.utility.delay.name",description:"graph.node.utility.delay.description"}}),E()],wr);let br=class extends nr{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}};S([b(),Re({handle:"value"}),D("design:type",Object)],br.prototype,"value",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.message.label",placeholder:"graph.node.utility.log.fields.message.placeholder",type:"textarea"}),Re({handle:"message"}),D("design:type",String)],br.prototype,"message",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.level.label",placeholder:"graph.node.utility.log.fields.level.placeholder",type:"text"}),Re({handle:"level",userControlled:!0}),D("design:type",String)],br.prototype,"level",void 0),S([b(),$e({handle:"value"}),D("design:type",Object)],br.prototype,"valueOut",void 0),br=S([De("core.flow.log",{kind:"core.flow.log",category:"Utility",color:"#0d9488",icon:"ti-terminal",width:96,height:96,labels:["flow","log","debug","utility"],metadata:{title:"graph.node.utility.log.name",description:"graph.node.utility.log.description"}}),E()],br);let vr=class extends nr{execute(e){return{result:{mapped:e.inputs.value??e.inputs}}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.utility.map.fields.value.label",placeholder:"graph.node.utility.map.fields.value.placeholder",type:"textarea"}),Re({handle:"value"}),D("design:type",Object)],vr.prototype,"value",void 0),S([b(),$e({handle:"result"}),D("design:type",Object)],vr.prototype,"result",void 0),vr=S([De("core.utility.map",{kind:"core.utility.map",category:"Utility",color:"#0d9488",icon:"ti-arrows-right-left",width:96,height:96,labels:["utility","map","transform"],metadata:{title:"graph.node.utility.map.name",description:"graph.node.utility.map.description",mapper:{}}}),E()],vr);let Ir=class extends nr{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}};S([b(),Re({handle:"value"}),D("design:type",Object)],Ir.prototype,"value",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.message.label",placeholder:"graph.node.utility.utility_log.fields.message.placeholder",type:"textarea"}),Re({handle:"message"}),D("design:type",String)],Ir.prototype,"message",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.level.label",placeholder:"graph.node.utility.utility_log.fields.level.placeholder"}),Re({handle:"level",userControlled:!0,type:"string"}),D("design:type",String)],Ir.prototype,"level",void 0),S([b(),$e({handle:"value"}),D("design:type",Object)],Ir.prototype,"valueOut",void 0),Ir=S([De("core.utility.log",{kind:"core.utility.log",category:"Utility",color:"#0d9488",icon:"ti-terminal",width:96,height:96,labels:["utility","log","debug","observability"],metadata:{title:"graph.node.utility.utility_log.name",description:"graph.node.utility.utility_log.description"}}),E()],Ir);let Er=class extends nr{execute(e){return{message:e.inputs.message??null,sessionId:e.inputs.sessionId??null,userId:e.inputs.userId??null}}};S([b(),$e({handle:"message"}),D("design:type",String)],Er.prototype,"message",void 0),S([b(),$e({handle:"sessionId"}),D("design:type",String)],Er.prototype,"sessionId",void 0),S([b(),$e({handle:"userId"}),D("design:type",String)],Er.prototype,"userId",void 0),Er=S([De("core.trigger.chat",{kind:"core.trigger.chat",category:"Trigger",color:"#3b82f6",icon:"ti-message-circle",width:96,height:96,labels:["trigger","chat","entrypoint"],metadata:{title:"graph.node.trigger.chat.name",description:"graph.node.trigger.chat.description",trigger:{type:"chat"}}}),E()],Er);let Nr=class extends nr{execute(e){return{payload:e.inputs.payload??null}}};S([b(),$e({handle:"payload"}),D("design:type",Object)],Nr.prototype,"payload",void 0),Nr=S([De("core.trigger.event",{kind:"core.trigger.event",category:"Trigger",color:"#3b82f6",icon:"ti-broadcast",width:96,height:96,labels:["trigger","event","bus"],metadata:{title:"graph.node.trigger.event.name",description:"graph.node.trigger.event.description",trigger:{type:"event",topic:"default"}}}),E()],Nr);let kr=class extends nr{execute(e){return{payload:e.inputs.payload??null}}};S([b(),Re({handle:"schema"}),i("ngx-decaf-model-builder",{label:"graph.node.trigger.form.fields.schema.label",placeholder:"graph.node.trigger.form.fields.schema.placeholder"}),D("design:type",Object)],kr.prototype,"schema",void 0),S([b(),$e({handle:"payload"}),D("design:type",Object)],kr.prototype,"payload",void 0),kr=S([De("core.trigger.form",{kind:"core.trigger.form",category:"Trigger",color:"#3b82f6",icon:"ti-forms",width:96,height:96,labels:["trigger","form","public"],metadata:{title:"graph.node.trigger.form.name",description:"graph.node.trigger.form.description",trigger:{type:"form",fields:[]}}}),E()],kr);let Or=class extends nr{execute(e){return{payload:e.inputs.payload??null}}};S([b(),$e({handle:"payload"}),D("design:type",Object)],Or.prototype,"payload",void 0),Or=S([De("core.trigger.manual",{kind:"core.trigger.manual",category:"Trigger",color:"#3b82f6",icon:"ti-hand-click",width:96,height:96,labels:["trigger","manual","entrypoint"],metadata:{title:"graph.node.trigger.manual.name",description:"graph.node.trigger.manual.description",trigger:{type:"manual",inputSchema:{}}}}),E()],Or);let Ar=class extends nr{execute(e){return{payload:e.inputs.payload??null}}};S([b(),Re({handle:"cron"}),i("app-cron-selector-field",{label:"graph.node.trigger.schedule.fields.cron.label",placeholder:"graph.node.trigger.schedule.fields.cron.placeholder"}),D("design:type",String)],Ar.prototype,"cron",void 0),S([b(),$e({handle:"payload"}),D("design:type",Object)],Ar.prototype,"payload",void 0),Ar=S([De("core.trigger.schedule",{kind:"core.trigger.schedule",category:"Trigger",color:"#3b82f6",icon:"ti-calendar-time",width:96,height:96,labels:["trigger","schedule","cron"],metadata:{title:"graph.node.trigger.schedule.name",description:"graph.node.trigger.schedule.description",trigger:{type:"schedule",schedule:"0 * * * *",timezone:"UTC"}}}),E()],Ar);let xr=class extends nr{execute(e){return{payload:e.inputs.payload??null}}};S([b(),Re({handle:"schema"}),i("ngx-decaf-model-builder",{label:"graph.node.trigger.webhook.fields.schema.label",placeholder:"graph.node.trigger.webhook.fields.schema.placeholder"}),D("design:type",Object)],xr.prototype,"schema",void 0),S([b(),$e({handle:"payload"}),D("design:type",Object)],xr.prototype,"payload",void 0),xr=S([De("core.trigger.webhook",{kind:"core.trigger.webhook",category:"Trigger",color:"#3b82f6",icon:"ti-webhook",width:96,height:96,labels:["trigger","webhook","http"],metadata:{title:"graph.node.trigger.webhook.name",description:"graph.node.trigger.webhook.description",trigger:{type:"webhook",path:"/webhook",method:"POST",auth:"none",responseMode:"onReceived"}}}),E()],xr);let _r=class extends nr{execute(e){return{response:"[Agent response] "+(e.inputs.prompt??""),actions:[]}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.agent.agent.fields.prompt.label",placeholder:"graph.node.agent.agent.fields.prompt.placeholder",type:"textarea"}),Re({handle:"prompt"}),D("design:type",String)],_r.prototype,"prompt",void 0),S([b(),$e({handle:"response"}),D("design:type",String)],_r.prototype,"response",void 0),S([b(),$e({handle:"actions"}),D("design:type",Array)],_r.prototype,"actions",void 0),S([Ce({category:"model",handle:"model"}),D("design:type",Object)],_r.prototype,"model",void 0),S([Ce({category:"memory",handle:"memory"}),D("design:type",Object)],_r.prototype,"memory",void 0),S([Ce({category:"workspace",handle:"workspace"}),D("design:type",Object)],_r.prototype,"workspace",void 0),_r=S([De("core.agent",{kind:"core.agent",category:"Agent",width:140,height:120,labels:["agent","ai","orchestrator"],metadata:{title:"graph.node.agent.agent.name",description:"graph.node.agent.agent.description",shape:"rectangle"}}),E()],_r);const Sr=[_r];function Dr(e,t,o,n){const r=t??o;if(null==e)return Math.min(o,r);const i=Number(e);if(!Number.isFinite(i)||0>=i)throw new so(n+" loop maxIterations must be a positive finite number");return Math.min(Math.floor(i),r)}function Pr(e,t,o){const n=t.node.loop,r=t.metadata?.loop;if(!n?.body&&!r?.body)throw new so(o+" node is missing loop configuration (instance.loop.body)");const i=t=>{const o=e[t]??n?.[t]??r?.[t],i=Number(o);return void 0!==o&&Number.isFinite(i)?i:void 0},a=t=>{const o=e[t]??r?.[t];return"string"==typeof o?o:void 0};return{body:n?.body??r?.body,maxIterations:i("maxIterations"),timeoutMs:i("timeoutMs"),concurrency:i("concurrency"),condition:e.condition??r?.condition,inputPort:a("inputPort"),outputPort:a("outputPort"),itemPort:a("itemPort"),resultPort:a("resultPort"),statePort:a("statePort"),slice:i("slice")}}let Rr=class extends nr{async execute(e,t){const o=Pr(this,t,"foreach"),n=e.inputs,r=n.items,i=Dr(o.maxIterations,t.limits?.maxForeachIterations,1e3,"foreach");if(!Array.isArray(r))throw new so("foreach input 'items' must be an array");const a=t.engine;if(!a)throw new io("foreach node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");const s=Number(n.slice??o.slice??1),d=Number.isFinite(s)&&s>0?Math.floor(s):1,l=d>1?Math.ceil(r.length/d):r.length;if(l>i)throw new lo(`foreach exceeded max iterations (${l} > ${i})`);const c=o.itemPort??"item",u=o.resultPort??"result",p=o.statePort??"state",h=o.body,f=[];let g=n.state,m=!1;await t.emit({type:ce.LOOP_STARTED});for(let e=0;l>e;e++){await t.emit({type:ce.LOOP_ITERATION_STARTED,iteration:e});const o=d>1?r.slice(e*d,e*d+d):r[e],n={[c]:o,index:e};d>1&&(n.slice=o),void 0!==g&&(n[p]=g);try{const r=await a.execute(h,n,{parentRunId:t.runId,path:[...t.path,"iteration:"+e],metadata:{item:o,index:e,slice:d},auth:t.auth},t);f.push(r.outputs[u]),void 0!==r.outputs[p]&&(g=r.outputs[p])}catch(o){if(o instanceof fo){const n=o.details?.value;void 0!==n&&f.push(n),m=!0,await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:e,metadata:{broken:!0}});break}throw o}await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:e})}await t.emit({type:ce.LOOP_COMPLETED,metadata:{broken:m}});const y={results:f,completed:f,iterations:f.length,broken:m};return void 0!==g&&(y[p]=g),y}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.items.label",placeholder:"graph.node.loop.foreach.fields.items.placeholder",type:"textarea"}),Re({handle:"items"}),D("design:type",Array)],Rr.prototype,"items",void 0),S([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.slice.label",placeholder:"graph.node.loop.foreach.fields.slice.placeholder",type:"number"}),Re({handle:"slice"}),D("design:type",Number)],Rr.prototype,"slice",void 0),S([b(),$e({handle:"item"}),D("design:type",Object)],Rr.prototype,"item",void 0),S([b(),Ce({handle:"loop",connectionRules:{allowSelf:!0,maxConnections:1}}),D("design:type",Object)],Rr.prototype,"loop",void 0),S([b(),$e({handle:"completed"}),D("design:type",Array)],Rr.prototype,"completed",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.maxIterations.label",type:"number"}),Re({handle:"maxIterations",userControlled:!0}),D("design:type",Number)],Rr.prototype,"maxIterations",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.condition.label",type:"code"}),Re({handle:"condition",userControlled:!0}),D("design:type",Object)],Rr.prototype,"condition",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.itemPort.label",type:"text"}),Re({handle:"itemPort",userControlled:!0}),D("design:type",String)],Rr.prototype,"itemPort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.resultPort.label",type:"text"}),Re({handle:"resultPort",userControlled:!0}),D("design:type",String)],Rr.prototype,"resultPort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.statePort.label",type:"text"}),Re({handle:"statePort",userControlled:!0}),D("design:type",String)],Rr.prototype,"statePort",void 0),Rr=S([De("graph-foreach-loop-node",{kind:"core.loop.foreach",category:"Loop",color:"#eab308",icon:"ti-repeat",width:120,height:140,labels:["loop","iteration","foreach"],metadata:{title:"graph.node.loop.foreach.name",description:"graph.node.loop.foreach.description",loop:{maxIterations:100,itemPort:"item",resultPort:"result",slice:1}}}),E()],Rr);class $r{constructor(){this.expressionEvaluator=new Bo}evaluate(e,t){if(this.isConditionExpression(e))return this.expressionEvaluator.evaluate(e,t);const o=this.resolveValue(e.left,t),n=e.right;switch(e.type){case no.TRUTHY:return!!o;case no.FALSY:return!o;case no.EQUALS:return o===n;case no.NOT_EQUALS:return o!==n;case no.GREATER_THAN:return Number(o)>Number(n);case no.GREATER_THAN_OR_EQUAL:return Number(o)>=Number(n);case no.LESS_THAN:return Number(n)>Number(o);case no.LESS_THAN_OR_EQUAL:return Number(n)>=Number(o);case no.EXISTS:return null!=o;case no.CUSTOM:throw new io("Custom condition evaluators are not supported in v1","GRAPH_CUSTOM_CONDITION_UNSUPPORTED");default:throw new io(`Unknown condition type '${e.type}'`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition:e})}}async evaluateAsync(e,t,o,n){return Wo(e)?Ho(e,n,o):this.evaluate(e,t)}resolveValue(e,t){if(!e)return t;const o=e.split(".");let n=t;for(const e of o){if(null==n)return;n=n[e]}return n}isConditionExpression(e){return"string"==typeof e.op}}let Cr=class extends nr{async execute(e,t){const o=Pr(this,t,"until"),n=e.inputs,r=Dr(o.maxIterations,t.limits?.maxLoopIterations,100,"until"),i=o.condition;if(!i)throw new so("until node is missing a condition");const a=o.statePort??"state",s=o.inputPort??a,d=o.outputPort??a,l=o.body,c=t.engine;if(!c)throw new io("until node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;await t.emit({type:ce.LOOP_STARTED});let h=!1;do{if(p>=r)throw await t.emit({type:ce.LOOP_LIMIT_REACHED,iteration:p}),new lo(`until loop exceeded max iterations (${r})`);await t.emit({type:ce.LOOP_ITERATION_STARTED,iteration:p}),u=(await c.execute(l,{[s]:u,iteration:p},{parentRunId:t.runId,path:[...t.path,"iteration:"+p],auth:t.auth},t)).outputs[d],await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:p});const e=await(new $r).evaluateAsync(i,u,t,{...n,state:u});await t.emit({type:ce.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:e}}),p++,h=e}while(!h);return await t.emit({type:ce.LOOP_COMPLETED}),{state:u,iterations:p}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.state.label",placeholder:"graph.node.loop.until.fields.state.placeholder",type:"textarea"}),Re({handle:"state"}),D("design:type",Object)],Cr.prototype,"state",void 0),S([b(),$e({handle:"state"}),D("design:type",Object)],Cr.prototype,"stateOut",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.maxIterations.label",type:"number"}),Re({handle:"maxIterations",userControlled:!0}),D("design:type",Number)],Cr.prototype,"maxIterations",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.condition.label",type:"code"}),Re({handle:"condition",userControlled:!0}),D("design:type",Object)],Cr.prototype,"condition",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.statePort.label",type:"text"}),Re({handle:"statePort",userControlled:!0}),D("design:type",String)],Cr.prototype,"statePort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.inputPort.label",type:"text"}),Re({handle:"inputPort",userControlled:!0}),D("design:type",String)],Cr.prototype,"inputPort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.outputPort.label",type:"text"}),Re({handle:"outputPort",userControlled:!0}),D("design:type",String)],Cr.prototype,"outputPort",void 0),Cr=S([De("graph-until-loop-node",{kind:"core.loop.until",category:"Loop",color:"#eab308",icon:"ti-player-stop",width:96,height:96,labels:["loop","conditional","until"],metadata:{title:"graph.node.loop.until.name",description:"graph.node.loop.until.description",loop:{maxIterations:50,statePort:"state",condition:{type:"greaterThanOrEqual",left:"iteration",right:2}}}}),E()],Cr);let Tr=class extends nr{async execute(e,t){const o=Pr(this,t,"while"),n=e.inputs,r=Dr(o.maxIterations,t.limits?.maxLoopIterations,100,"while"),i=o.condition;if(!i)throw new so("while node is missing a condition");const a=o.statePort??"state",s=o.inputPort??a,d=o.outputPort??a,l=o.body,c=t.engine;if(!c)throw new io("while node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;for(await t.emit({type:ce.LOOP_STARTED});await(new $r).evaluateAsync(i,u,t,{...n,state:u});){if(p>=r)throw await t.emit({type:ce.LOOP_LIMIT_REACHED,iteration:p}),new lo(`while loop exceeded max iterations (${r})`);await t.emit({type:ce.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:!0}}),await t.emit({type:ce.LOOP_ITERATION_STARTED,iteration:p}),u=(await c.execute(l,{[s]:u,iteration:p},{parentRunId:t.runId,path:[...t.path,"iteration:"+p],auth:t.auth},t)).outputs[d],await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:p}),p++}return await t.emit({type:ce.LOOP_COMPLETED}),{state:u,iterations:p}}};S([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.state.label",placeholder:"graph.node.loop.while.fields.state.placeholder",type:"textarea"}),Re({handle:"state"}),D("design:type",Object)],Tr.prototype,"state",void 0),S([b(),$e({handle:"state"}),D("design:type",Object)],Tr.prototype,"stateOut",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.maxIterations.label",type:"number"}),Re({handle:"maxIterations",userControlled:!0}),D("design:type",Number)],Tr.prototype,"maxIterations",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.condition.label",type:"code"}),Re({handle:"condition",userControlled:!0}),D("design:type",Object)],Tr.prototype,"condition",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.statePort.label",type:"text"}),Re({handle:"statePort",userControlled:!0}),D("design:type",String)],Tr.prototype,"statePort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.inputPort.label",type:"text"}),Re({handle:"inputPort",userControlled:!0}),D("design:type",String)],Tr.prototype,"inputPort",void 0),S([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.outputPort.label",type:"text"}),Re({handle:"outputPort",userControlled:!0}),D("design:type",String)],Tr.prototype,"outputPort",void 0),Tr=S([De("graph-while-loop-node",{kind:"core.loop.while",category:"Loop",color:"#eab308",icon:"ti-arrows-loop",width:96,height:96,labels:["loop","conditional","while"],metadata:{title:"graph.node.loop.while.name",description:"graph.node.loop.while.description",loop:{maxIterations:50,statePort:"state",condition:{type:"lessThan",left:"iteration",right:3}}}}),E()],Tr);let Lr=class extends nr{execute(e){const t=e.inputs;return{value:t?.value??null}}};S([$e({handle:"value",connectionRules:{allowMultiple:!0}}),D("design:type",Object)],Lr.prototype,"value",void 0),Lr=S([De("graph-input-value-node",{kind:"value",category:"Boundary",color:"#0f766e",icon:"ti-circle-plus",labels:["workflow","input","value"],metadata:{title:"graph.node.boundary.input.name",description:"graph.node.boundary.input.description"}}),E()],Lr);let Mr=class extends nr{execute(e){return{}}};function jr(e,t,o,n={}){return{id:e,label:t,direction:o,...n}}function Gr(e){const t=e,o=ve(t),n=o?.metadata?.title;return jt(t,n?{name:n}:{})}S([b(),Re({handle:"value"}),D("design:type",Object)],Mr.prototype,"value",void 0),Mr=S([De("graph-output-value-node",{kind:"result",category:"Boundary",color:"#0f766e",icon:"ti-circle-minus",width:96,height:96,labels:["workflow","output","value"],metadata:{title:"graph.node.boundary.output.name",description:"graph.node.boundary.output.description"}}),E()],Mr);const Ur={kind:"core.loop.foreach",capabilities:["loop"],display:{name:"graph.node.loop.foreach.name",description:"graph.node.loop.foreach.description",category:"Loop",color:"#eab308",icon:{type:"catalogue",name:"ti-repeat"},width:120,height:140,labels:["loop","iteration","foreach"]},inputs:[jr("items","graph.node.loop.foreach.ports.input.items.label","input",{required:!0,schema:{type:"array",items:{type:"any"}}}),jr("slice","graph.node.loop.foreach.ports.input.slice.label","input",{schema:{type:"number",integer:!0,min:1}}),jr("state","graph.node.loop.foreach.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[jr("results","graph.node.loop.foreach.ports.output.results.label","output",{schema:{type:"array",items:{type:"any"}}}),jr("completed","graph.node.loop.foreach.ports.output.completed.label","output",{schema:{type:"array",items:{type:"any"}}}),jr("iterations","graph.node.loop.foreach.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}}),jr("broken","graph.node.loop.foreach.ports.output.broken.label","output",{schema:{type:"boolean"}}),jr("state","graph.node.loop.foreach.ports.output.state.label","output",{schema:{type:"any"}})],parameters:[{type:"number",id:"maxIterations",label:"graph.node.loop.foreach.fields.maxIterations.label",integer:!0,min:1},{type:"object",id:"condition",label:"graph.node.loop.foreach.fields.condition.label"},{type:"string",id:"itemPort",label:"graph.node.loop.foreach.fields.itemPort.label"},{type:"string",id:"resultPort",label:"graph.node.loop.foreach.fields.resultPort.label"},{type:"string",id:"statePort",label:"graph.node.loop.foreach.fields.statePort.label"},{type:"number",id:"slice",label:"graph.node.loop.foreach.fields.slice.label",integer:!0,min:1}]},Fr={kind:"core.loop.while",capabilities:["loop"],display:{name:"graph.node.loop.while.name",description:"graph.node.loop.while.description",category:"Loop",color:"#eab308",icon:{type:"catalogue",name:"ti-arrows-loop"},width:120,height:140,labels:["loop","conditional","while"]},inputs:[jr("state","graph.node.loop.while.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[jr("state","graph.node.loop.while.ports.output.state.label","output",{schema:{type:"any"}}),jr("iterations","graph.node.loop.while.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}})],parameters:[{type:"number",id:"maxIterations",label:"graph.node.loop.while.fields.maxIterations.label",integer:!0,min:1},{type:"object",id:"condition",label:"graph.node.loop.while.fields.condition.label",required:!0},{type:"string",id:"statePort",label:"graph.node.loop.while.fields.statePort.label"},{type:"string",id:"inputPort",label:"graph.node.loop.while.fields.inputPort.label"},{type:"string",id:"outputPort",label:"graph.node.loop.while.fields.outputPort.label"}]},Br={kind:"core.loop.until",capabilities:["loop"],display:{name:"graph.node.loop.until.name",description:"graph.node.loop.until.description",category:"Loop",color:"#eab308",icon:{type:"catalogue",name:"ti-player-stop"},width:120,height:140,labels:["loop","conditional","until"]},inputs:[jr("state","graph.node.loop.until.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[jr("state","graph.node.loop.until.ports.output.state.label","output",{schema:{type:"any"}}),jr("iterations","graph.node.loop.until.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}})],parameters:[{type:"number",id:"maxIterations",label:"graph.node.loop.until.fields.maxIterations.label",integer:!0,min:1},{type:"object",id:"condition",label:"graph.node.loop.until.fields.condition.label",required:!0},{type:"string",id:"statePort",label:"graph.node.loop.until.fields.statePort.label"},{type:"string",id:"inputPort",label:"graph.node.loop.until.fields.inputPort.label"},{type:"string",id:"outputPort",label:"graph.node.loop.until.fields.outputPort.label"}]},Wr=[Gr(Lr),Gr(Mr),Gr(Or),Gr(xr),Gr(Ar),Gr(Nr),Gr(kr),Gr(Er),(qr=Gr(dr),{...qr,dynamicPorts:[{type:"togglePort",parameter:"else",equals:!0,port:{id:"else",label:"graph.node.flow_control.if.ports.output.else.label",direction:"output",schema:{type:"any"}}}]}),(e=>({...e,outputs:[],parameters:[...e.parameters,{type:"collection",id:"cases",label:"graph.node.flow_control.switch.fields.cases.label",required:!0,itemIdPath:"outputPort",itemLabelPath:"label"},{type:"boolean",id:"hasDefault",label:"graph.node.flow_control.switch.fields.hasDefault.label",defaultValue:!1},{type:"object",id:"switch",label:"graph.node.flow_control.switch.fields.switch.label",required:!1}],dynamicPorts:[{type:"repeatFromParameter",parameter:"cases",itemIdPath:"outputPort",itemLabelPath:"label",direction:"output",portIdTemplate:"${id}",defaultPort:{id:"case",label:"graph.node.flow_control.switch.ports.output.case.label",direction:"output",schema:{type:"any"}}},{type:"togglePort",parameter:"hasDefault",equals:!0,port:{id:"default",label:"graph.node.flow_control.switch.ports.output.default.label",direction:"output",schema:{type:"any"}}}]}))(Gr(lr)),Gr(vr),Gr(wr),Gr(ar),Gr(sr),Gr(yr),Gr(br),Gr(Ir),Gr(rr),Gr(_r),Ur,Fr,Br];var qr;const Hr=Object.fromEntries(Wr.map(e=>[e.kind,e])),Kr=[Or,xr,Ar,Nr,kr,Er],Vr=[dr,lr,wr,ar,sr,br,rr],zr=[yr,vr,Ir],Jr=[Rr,Tr,Cr],Xr=[Lr,Mr],Yr={value:Lr,result:Mr,"core.trigger.manual":Or,"core.trigger.webhook":xr,"core.trigger.schedule":Ar,"core.trigger.event":Nr,"core.trigger.form":kr,"core.trigger.chat":Er,"core.flow.if":dr,"core.flow.switch":lr,"core.utility.map":vr,"core.flow.delay":wr,"core.flow.errorBoundary":ar,"core.flow.humanApproval":sr,"core.utility.code":yr,"core.flow.log":br,"core.utility.log":Ir,"core.flow.break":rr,"core.agent":_r,"core.loop.foreach":Rr,"core.loop.while":Tr,"core.loop.until":Cr};function Qr(e){return{execute:(t,o)=>e.instantiate({...or(o.node),...t.parameters,...o.node.state??{}}).execute(t,o)}}function Zr(){const e=[];for(const[t,o]of Object.entries(Hr)){const n=Yr[t];n&&e.push(er({manifest:o,executor:Qr(n)}))}return e}function ei(e,...t){for(const o of Zr())e.register(o,{},...t);return e}class ti{resolve(e){const t=this.createValidator(e);return{name:e.name,required:e.required,validate:t}}resolveAll(e){const t={};for(const o of e)t[o.name]=this.resolve(o);return t}createValidator(e){switch((e.type??e.designType??"").toLowerCase()){case"string":return e=>"string"==typeof e;case"number":return e=>"number"==typeof e;case"boolean":return e=>"boolean"==typeof e;case"date":return e=>e instanceof Date||"string"==typeof e&&!isNaN(Date.parse(e));case"array":return e=>Array.isArray(e);case"bigint":return e=>"bigint"==typeof e;default:return()=>!0}}}class oi{constructor(e){this.resolver=e}validateWorkflowInputs(e,t){this.validatePorts(e.inputs,t,"workflow input")}validateWorkflowOutputs(e,t){this.validatePorts(e.outputs,t,"workflow output")}validateNodeInputs(e,t){const o=(e.ports??[]).filter(e=>"input"===e.direction);this.validatePorts(o,t,`node '${e.name}' input`)}validateNodeOutputs(e,t){const o=(e.ports??[]).filter(e=>"output"===e.direction);this.validatePorts(o,t,`node '${e.name}' output`)}validatePorts(e,t,o){if(e)for(const n of e){const e=Object.prototype.hasOwnProperty.call(t,n.name);if(n.required&&!e)throw new so(`Missing required ${o} port '${n.name}'`);if(e&&!this.resolver.resolve(n).validate(t[n.name]))throw new so(`Invalid value for ${o} port '${n.name}'`)}}}const ni=["node","definition","executor","execute","ports","component"];function ri(e,t,o,n){return{code:e,path:t,message:o,...void 0!==n?.nodeId?{nodeId:n.nodeId}:{},...void 0!==n?.edgeId?{edgeId:n.edgeId}:{},...n?.details?{details:n.details}:{}}}function ii(e,t){const o=[];for(const n of Object.keys(e))ni.includes(n)&&o.push(ri("document.forbidden-field",`${t}.${n}`,`Field '${n}' is not accepted in a canonical workflow document: node, definition, executor, execute, ports and component fields are rejected at the boundary`,{details:{field:n}}));return o}function ai(e,t){t.push(...ii(e,"$")),e.inputs.forEach((e,o)=>t.push(...ii(e,`inputs[${o}]`))),e.outputs.forEach((e,o)=>t.push(...ii(e,`outputs[${o}]`)));for(const o of e.nodes)t.push(...ii(o,`nodes[${o.id}]`)),o.loop&&(t.push(...ii(o.loop,`nodes[${o.id}].loop`)),ai(o.loop.body,t));for(const o of e.edges)t.push(...ii(o,`edges[${o.id}]`))}function si(e,t){const o=[];e.nodes.length>t.maxNodes&&o.push(ri("document.limit.nodes","$.nodes",`Document declares ${e.nodes.length} nodes; at most ${t.maxNodes} are allowed`,{details:{count:e.nodes.length,limit:t.maxNodes}})),e.edges.length>t.maxEdges&&o.push(ri("document.limit.edges","$.edges",`Document declares ${e.edges.length} edges; at most ${t.maxEdges} are allowed`,{details:{count:e.edges.length,limit:t.maxEdges}}));const n=di(e);n>t.maxNestingDepth&&o.push(ri("document.limit.depth","$.nodes",`Document nests loop bodies ${n} levels deep; at most ${t.maxNestingDepth} levels are allowed`,{details:{depth:n,limit:t.maxNestingDepth}}));const r=Buffer.byteLength(JSON.stringify(e),"utf8");return r>t.maxDocumentBytes&&o.push(ri("document.limit.size","$",`Document serializes to ${r} bytes; at most ${t.maxDocumentBytes} bytes are allowed`,{details:{bytes:r,limit:t.maxDocumentBytes}})),o}function di(e,t=0){let o=t;for(const n of e.nodes)n.loop?.body&&(o=Math.max(o,di(n.loop.body,t+1)));return o}async function li(e,t,...o){const n=[];for(const r of e.nodes)t.has(r.kind,...o)||n.push(ri("node.unknown-kind",`nodes[${r.id}].kind`,`Node '${r.id}' references kind '${r.kind}' which is not registered in the backend catalogue`,{nodeId:r.id,details:{kind:r.kind}})),r.loop?.body&&n.push(...await li(r.loop.body,t,...o));return n}async function ci(e,t={},...o){const n={...cr,...t.limits},r=[];if(!pt(e))return r.push(ri("document.shape","$","Payload is not a canonical GraphWorkflowDocument: id and name must be strings and inputs, outputs, nodes and edges must be arrays")),{valid:!1,issues:r};if(!Ue(e))return r.push(ri("document.json-unsafe","$","Document contains JSON-unsafe values: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys (__proto__/prototype/constructor) are rejected")),{valid:!1,issues:r};ai(e,r),r.push(...(e=>{const t=[],o=new Set;for(const n of[...e.inputs,...e.outputs])o.has(n.id)?t.push(ri("document.duplicate-port-id",`ports[${n.id}]`,`Workflow port '${n.id}' is declared more than once; workflow port ids must be unique`)):o.add(n.id);const n=new Set;for(const o of e.nodes)n.has(o.id)?t.push(ri("document.duplicate-node-id",`nodes[${o.id}]`,`Node '${o.id}' is declared more than once; node ids must be unique`,{nodeId:o.id})):n.add(o.id);const r=new Set;for(const o of e.edges)r.has(o.id)?t.push(ri("document.duplicate-edge-id",`edges[${o.id}]`,`Edge '${o.id}' is declared more than once; edge ids must be unique`,{edgeId:o.id})):r.add(o.id);return t})(e)),r.push(...si(e,n)),vn(e,r);try{ot(e)}catch(e){const t=e instanceof A?e.message:e+"";r.push(ri("document.structure","$",t))}return t.catalogue&&r.push(...await li(e,t.catalogue,...o)),{valid:0===r.length,issues:r}}class ui{constructor(e,t){this.iteration=e,this.metadata=t}}function pi(e,t,o={}){const n=e?.owner??null;return!n||n===t||(null==t||""===t)&&!0===o.allowAnonymousAccess}function hi(e,t){return(e?.owner??null)===(t??null)}function fi(e,t,o){if(!hi(e,t))throw new L(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function gi(e,t,o){if(!pi(e,t,o))throw new L(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function mi(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>mi(e)).join(",")}]`;const t=e;return`{${Object.keys(t).filter(e=>void 0!==t[e]).sort().map(e=>`${JSON.stringify(e)}:${mi(t[e])}`).join(",")}}`}function yi(e){return Y("sha256").update(mi(e)).digest("hex")}class wi{constructor(e={}){this.events=new Map,this.listeners=new Map,this.limits={...ue,...e}}async append(e){let t=this.events.get(e.runId);t||(t=[],this.events.set(e.runId,t)),t.push(e),this.enforceRetention(t);for(const t of this.listeners.get(e.runId)??[])try{t(e)}catch{}}async listAfter(e,t){const o=this.events.get(e);return o?o.filter(e=>e.sequence>t):[]}subscribe(e,t){let o=this.listeners.get(e);return o||(o=new Set,this.listeners.set(e,o)),o.add(t),()=>{o.delete(t),0===o.size&&this.listeners.delete(e)}}release(e){this.events.delete(e),this.listeners.delete(e)}enforceRetention(e){const t=this.limits.maxEventsPerRun;for(;e.length>t;){const t=e.findIndex(e=>!he(e.type));if(-1===t)break;e.splice(t,1)}}}function bi(e){return new Ft({runId:e.runId,workflowId:e.workflowId,...e.ownerUser?{owner:e.ownerUser}:{},status:e.status,...e.documentFingerprint?{documentFingerprint:e.documentFingerprint}:{},...void 0!==e.result?{result:vi(e.result)}:{},...e.error?{error:vi(e.error)}:{},createdAt:new Date(e.createdAt),...e.startedAt?{startedAt:new Date(e.startedAt)}:{},...e.finishedAt?{finishedAt:new Date(e.finishedAt)}:{}})}function vi(e){if(null!=e)return JSON.parse(JSON.stringify(e))}class Ii{constructor(){this.runs=new Map}async saveRun(e){this.runs.set(e.runId,{...e})}async readRun(e){const t=this.runs.get(e);return t?{...t}:null}async listRuns(e){return[...this.runs.values()].filter(t=>t.workflowId===e).map(e=>bi(e))}release(e){this.runs.delete(e)}}class Ei{constructor(e,t={}){this.sequences=new Map,this.chains=new Map,this.store=e,this.limits={...ue,...t}}async publish(e){const t=e.runId,o=(this.sequences.get(t)??0)+1;this.sequences.set(t,o);const n={...e,payload:this.limitPayload(e.payload),sequence:o,timestamp:(new Date).toISOString()},r=(this.chains.get(t)??Promise.resolve()).then(()=>this.store.append(n));return this.chains.set(t,r.catch(()=>{})),await r,n}lastSequence(e){return this.sequences.get(e)??0}release(e){this.sequences.delete(e),this.chains.delete(e)}limitPayload(e){if(void 0===e)return;let t;try{t=JSON.stringify(e)}catch{return{nonSerializable:!0}}return t.length>this.limits.maxEventPayloadBytes?{truncated:!0,reason:"event payload exceeds the configured byte limit",bytes:t.length}:e}}class Ni{constructor(e,t,o,n={},r={}){this.controllers=new Map,this.completions=new Map,this.timeouts=new Map,this.engine=e,this.runStore=t,this.publisher=o,this.hooks=n,this.limits={...ue,...r}}begin(e){const t=this.controllers.get(e);if(t)return t;const o=new AbortController;return this.controllers.set(e,o),o}abort(e,t){const o=this.controllers.get(e);return!!o&&(o.signal.aborted||o.abort(t),!0)}isAborted(e){return!0===this.controllers.get(e)?.signal.aborted}abortReason(e){const t=this.controllers.get(e)?.signal;if(t?.aborted)return"timeout"===t.reason?"timeout":"user"}waitFor(e){return this.completions.get(e)}schedule(e,t,o,...n){const r=this.completions.get(e.runId);if(r)return r;const i=this.runExecution({...e},t,o,...n).catch(async t=>{const o=ki(t);try{await this.emitTerminal({...e},ce.WORKFLOW_FAILED,o)}catch{}return await this.finalize({...e},"failed",void 0,o,...n)});return this.completions.set(e.runId,i),i}release(e){this.controllers.delete(e),this.completions.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.publisher.release(e)}armTimeout(e){const t=setTimeout(()=>{this.timeouts.delete(e),this.abort(e,"timeout")},this.limits.executionTimeoutMs);this.timeouts.set(e,t)}async runExecution(e,t,o,...n){const r=e.runId;let i,a,s=!1;const d=this.engine.observe({refresh:async t=>{t.runId===r&&(t.error&&(i=t.error),he((await this.publisher.publish(this.envelopeOf(e,t))).type)?s=!0:t.type===ce.WORKFLOW_STARTED&&"validating"===e.status&&(e.status="running",await this.persist(e,...n)))}});this.armTimeout(r);try{if(this.isAborted(r)){const t={name:"GraphRunCancelledError",message:`Graph run '${r}' was cancelled before execution started`,code:"GRAPH_RUN_CANCELLED"};return i=t,await this.emitTerminal(e,ce.WORKFLOW_CANCELLED,t),s=!0,await this.finalize(e,"cancelled",void 0,t,...n)}let d,l;e.status="validating",e.startedAt=(new Date).toISOString(),await this.persist(e,...n);try{({document:d,fingerprint:l}=await t(...n)),e.documentFingerprint=l,await this.persist(e,...n)}catch(t){const o=ki(t);return i=o,s||(await this.emitTerminal(e,ce.WORKFLOW_FAILED,o),s=!0),await this.finalize(e,"failed",void 0,o,...n)}if(this.isAborted(r)){const t={name:"GraphRunCancelledError",message:`Graph run '${r}' was cancelled before execution started`,code:"GRAPH_RUN_CANCELLED"};return i=t,s||(await this.emitTerminal(e,ce.WORKFLOW_CANCELLED,t),s=!0),await this.finalize(e,"cancelled",void 0,t,...n)}try{a=await this.engine.execute(d,o,{runId:r,abortSignal:this.controllers.get(r)?.signal,metadata:{documentFingerprint:l}},...n)}catch(e){i=ki(e)}const c=this.abortReason(r);let u,p;return"timeout"===c?(u="failed",p=i??{name:"GraphRunTimeoutError",message:`Graph run '${r}' exceeded the configured execution timeout of ${this.limits.executionTimeoutMs}ms`,code:"GRAPH_RUN_TIMEOUT"}):"user"===c?(u="cancelled",p=i):a?.status===se.SUCCEEDED?u="succeeded":a?.status===se.CANCELLED?(u="cancelled",p=i):(u="failed",p=i??ki(new io(a?`Graph run '${r}' failed`:`Graph run '${r}' failed without a result`,"GRAPH_RUN_FAILED",{runId:r}))),s||await this.emitTerminal(e,"succeeded"===u?ce.WORKFLOW_COMPLETED:"cancelled"===u?ce.WORKFLOW_CANCELLED:ce.WORKFLOW_FAILED,p),await this.finalize(e,u,a,p,...n)}finally{d();const e=this.timeouts.get(r);e&&(clearTimeout(e),this.timeouts.delete(r))}}async emitTerminal(e,t,o){await this.publisher.publish({runId:e.runId,workflowId:e.workflowId,type:t,error:o})}async finalize(e,t,o,n,...r){e.status=t,o&&(e.result=o),n&&(e.error=n),e.startedAt||(e.startedAt=(new Date).toISOString()),e.finishedAt=(new Date).toISOString(),await this.persist(e,...r);try{await(this.hooks.onRunCompleted?.(e,o))}catch{}return e}async persist(e,...t){await this.runStore.saveRun({...e},...t)}envelopeOf(e,t){return{runId:e.runId,workflowId:t.workflowId??e.workflowId,type:t.type,nodeId:t.nodeId,edgeId:t.edgeId,payload:void 0===t.payload?void 0:Ge(t.payload)?t.payload:{nonSerializable:!0},error:t.error,parentRunId:t.parentRunId,path:t.path}}}function ki(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack,code:e.graphCode??("number"==typeof e.code?e.code+"":e.code)}:{name:"UnknownError",message:e+""}}class Oi{constructor(e,t,o,n={}){this.activeByCaller=new Map,this.callerKeysByRun=new Map,this.releaseTimers=new Map,this.engine=e,this.runStore=t,this.eventStore=o,this.publisher=new Ei(o,n.limits),this.executor=new Ni(e,t,this.publisher,{onRunCompleted:n.onRunCompleted},n.limits),this.options={...n,limits:{...ue,...n.limits}}}get limits(){return this.options.limits}async createRun(e,t,o,...n){this.validateCreateRequest(e);const r=e.workflowId??e.workflow?.id??"";if(!r)throw new A("Graph run request must carry a workflow document with an id or a saved workflowId");if(e.workflowId&&!this.options.documentResolver)throw new A("Graph run requests by workflowId require a document resolver");const i=o??t??"anonymous",a=this.activeByCaller.get(i)??new Set;if(a.size>=this.options.limits.maxConcurrentRuns)throw new A(`Graph run rejected: the configured limit of ${this.options.limits.maxConcurrentRuns} concurrent runs per caller is exhausted`);const s=this.generateRunId(),d={runId:s,workflowId:r,ownerUser:t,status:"queued",createdAt:(new Date).toISOString()};this.executor.begin(s),await this.runStore.saveRun({...d},...n);const l=this.documentProviderFor(e,t);return a.add(s),this.activeByCaller.set(i,a),this.callerKeysByRun.set(s,i),this.executor.schedule(d,l,e.inputs??{},...n).catch(()=>{}).finally(()=>this.finishActiveRun(s)),d}async getRun(e,t,...o){const n=await this.runStore.readRun(e,...o);if(!n)throw new _(`No graph run found for runId '${e}'`);return this.assertOwnership(n,t),n}async listRunsByWorkflow(e,t,...o){return(await this.runStore.listRuns(e,...o)).filter(e=>pi({owner:e.owner},t,{allowAnonymousAccess:!0===this.options.allowAnonymousAccess})).sort((e,t)=>{const o=e.updatedAt instanceof Date?e.updatedAt.getTime():NaN,n=t.updatedAt instanceof Date?t.updatedAt.getTime():NaN;return(Number.isFinite(n)?n:0)-(Number.isFinite(o)?o:0)})}async cancelRun(e,t,...o){const n=await this.runStore.readRun(e,...o);if(!n)throw new _(`No graph run found for runId '${e}'`);return this.assertWriteOwnership(n,t),"succeeded"===(r=n.status)||"failed"===r||"cancelled"===r||(this.executor.abort(e,"user"),n.status="cancelled",n.finishedAt=(new Date).toISOString(),await this.runStore.saveRun({...n},...o)),n;var r}async resumeRun(e,t,o,...n){const r=await this.runStore.readRun(e,...n);if(!r)throw new _(`No graph run found for runId '${e}'`);this.assertWriteOwnership(r,o);const i=this.engine.backend,a=i.resume;if("function"!=typeof a)throw new io(`Graph execution backend '${i.constructor?.name??"GraphExecutionBackend"}' does not support resume`,"GRAPH_RESUME_UNSUPPORTED_BACKEND",{runId:e});let s;try{s=await a.call(i,e,t,...n)}catch(e){throw(d=e)instanceof io?new io(d.message,d.graphCode):d}var d;const l={...s,runId:e,caller:o};return await this.publisher.publish({runId:e,workflowId:r.workflowId,type:ce.WORKFLOW_RESUMED,payload:l}),l}async listEvents(e,t,o,...n){return await this.getRun(e,o,...n),this.eventStore.listAfter(e,t)}async subscribeEvents(e,t,o,...n){return await this.getRun(e,t,...n),this.eventStore.subscribe(e,o)}subscribeRunEvents(e,t){return this.eventStore.subscribe(e.runId,t)}async waitForRun(e,t,...o){const n=this.executor.waitFor(e);return n&&await n,this.getRun(e,t,...o)}async executeAndWait(e,t,o,...n){const r=await this.createRun(e,t,o,...n);return this.waitForRun(r.runId,t,...n)}release(e){this.finishActiveRun(e);const t=this.releaseTimers.get(e);t&&(clearTimeout(t),this.releaseTimers.delete(e)),this.executor.release(e),this.eventStore.release?.(e)}finishActiveRun(e){const t=this.callerKeysByRun.get(e);if(void 0!==t){this.callerKeysByRun.delete(e);const o=this.activeByCaller.get(t);o&&(o.delete(e),0===o.size&&this.activeByCaller.delete(t))}if(this.releaseTimers.has(e))return;const o=setTimeout(()=>{this.releaseTimers.delete(e),this.release(e)},this.options.limits.eventReplayWindowMs);o.unref?.(),this.releaseTimers.set(e,o)}validateCreateRequest(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new A("Graph run request must be an object carrying either a workflow document or a workflowId plus inputs");const t=void 0!==e.workflow,o=void 0!==e.workflowId;if(t&&o)throw new A("Graph run request is ambiguous: supply either an unsaved workflow document or a saved workflowId, not both");if(!t&&!o)throw new A("Graph run request must supply either an unsaved workflow document or a saved workflowId");if(t&&!pt(e.workflow))throw new A("Graph run request carries a payload that is not a canonical GraphWorkflowDocument");if(void 0!==e.inputs&&!Ue(e.inputs))throw new A("Graph run inputs must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys (__proto__/prototype/constructor) are rejected");const n=(e=>{try{return JSON.stringify(e)?.length??0}catch{return Number.MAX_SAFE_INTEGER}})(e);if(n>this.options.limits.maxRequestBytes)throw new A(`Graph run request of ${n} bytes exceeds the configured limit of ${this.options.limits.maxRequestBytes} bytes`)}documentProviderFor(e,t){if(e.workflow){const t=e.workflow;return async()=>({document:t,fingerprint:yi(t)})}const o=e.workflowId;return async(...e)=>{const n=this.options.documentResolver;if(!n)throw new A("Graph run requests by workflowId require a document resolver");const r=await n.resolve(o,t,...e);return{document:r,fingerprint:yi(r)}}}assertOwnership(e,t){gi({owner:e.ownerUser},t,{allowAnonymousAccess:!0===this.options.allowAnonymousAccess,resourceKind:"Graph run",resourceId:e.runId})}assertWriteOwnership(e,t){fi({owner:e.ownerUser},t,{resourceKind:"Graph run",resourceId:e.runId})}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new po("Cannot generate a graph run id: crypto.randomUUID is unavailable in this runtime",{runtime:typeof globalThis.crypto});return e.randomUUID()}}function Ai(e){if(!e)return;let t;try{t=e.cache?.user}catch{t=void 0}if(null==t)try{t=e.get("user")}catch{t=void 0}return"string"==typeof t&&t.length>0?t:void 0}function xi(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&pt(e.document)&&!pt(e)}function _i(e){return JSON.parse(JSON.stringify(e))}function Si(e){if(null==e)return 0;let t;try{t=e.getTime()}catch{return 0}return Number.isFinite(t)?t:0}let Di=class extends H{constructor(e){super(Bt),this.catalogue=e}get limits(){return{...cr,...ur.graph.workflows.limits??{}}}get allowAnonymousAccess(){return!0===ur.graph.workflows.allowAnonymousAccess}async saveDocument(e,t,...o){const{ctx:n,ctxArgs:r}=(await this.logCtx(o,"saveDocument",!0)).for(this.saveDocument);if(!pt(t))throw new A("Payload is not a canonical GraphWorkflowDocument: id and name must be strings and inputs, outputs, nodes and edges must be arrays");if(t.id!==e)throw new A(`Document id '${t.id}' does not match the workflow id '${e}' from the request path`);const i=await this.validateDocument(t,n);if(!i.valid)throw new mo(i.issues);const a=Ai(n),s=await this.readExistingForWrite(e,r);s&&this.assertWriteOwnership(e,s,a);const d=new Date;if(s)return s.name=t.name,s.document=_i(t),s.updatedAt=d,this.update(s,...r);const l=new Bt({workflowId:e,name:t.name,document:_i(t),...a?{owner:a}:{},updatedAt:d});return this.create(l,...r)}async seedDocument(e,t,...o){const{log:n,ctxArgs:r}=(await this.logCtx(o,"seedDocument",!0)).for(this.seedDocument);try{return await this.saveDocument(e,t,...r)}catch(t){if(t instanceof L)return n.warn(`Skipping boot seed of graph workflow '${e}': an existing row is owned by another user`),null;throw t}}async getDocument(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"getDocument",!0)).for(this.getDocument);let r;try{r=await this.read(e,...n)}catch{r=null}if(!r)throw new _(`No graph workflow found for workflowId '${e}'`);if(this.assertOwnership(e,r,Ai(o)),r.document)return _i(r.document);throw new _(`Graph workflow '${e}' has no canonical document; legacy definition/state snapshots are no longer supported (DECAF-50 \xa74.26 R2-2)`)}async listWorkflows(...e){const{ctx:t,ctxArgs:o}=(await this.logCtx(e,"listWorkflows",!0)).for(this.listWorkflows),n=await this.listBy("workflowId",K.ASC,...o),r=Ai(t);return n.filter(e=>pi(e,r,{allowAnonymousAccess:this.allowAnonymousAccess})).sort((e,t)=>Si(t.updatedAt)-Si(e.updatedAt))}async assertAccess(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"assertAccess",!0)).for(this.assertAccess);let r;try{r=await this.read(e,...n)}catch{r=null}if(!r)throw new _(`No graph workflow found for workflowId '${e}'`);return this.assertOwnership(e,r,Ai(o)),r}async validateDocument(e,...t){const{ctx:o}=(await this.logCtx(t,"validateDocument",!0)).for(this.validateDocument);return await ci(e,{limits:this.limits,...this.catalogue?{catalogue:this.catalogue}:{}},o)}async saveSnapshot(e,t,...o){const{ctx:n,ctxArgs:r}=(await this.logCtx(o,"saveSnapshot",!0)).for(this.saveSnapshot);if(!Ue(t))throw new A("Workflow snapshot payload must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys (__proto__/prototype/constructor) are rejected");if(!xi(t))throw new A("Workflow snapshots must wrap a canonical GraphWorkflowDocument ({ document, editor?, metadata? }): legacy definition/state snapshots are no longer accepted; save canonical documents via PUT /graph/workflows/{workflowId}");const i=Ai(n),a=await this.readExistingForWrite(e,r);a&&this.assertWriteOwnership(e,a,i);const s=new Date;if(a)return a.snapshot=t,await this.applyCanonicalWrapper(a,t,n),a.updatedAt=s,this.update(a,...r);const d=new Bt({workflowId:e,snapshot:t,...i?{owner:i}:{},updatedAt:s});return await this.applyCanonicalWrapper(d,t,n),this.create(d,...r)}async loadSnapshot(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"loadSnapshot",!0)).for(this.loadSnapshot);try{const t=await this.read(e,...n);return this.assertOwnership(e,t,Ai(o)),t}catch{return null}}async readExistingForWrite(e,t){try{return await this.read(e,...t)}catch(e){if(e instanceof _)return null;throw e}}assertOwnership(e,t,o){gi(t??null,o??null,{allowAnonymousAccess:this.allowAnonymousAccess,resourceKind:"Graph workflow",resourceId:e})}assertWriteOwnership(e,t,o){fi(t??null,o??null,{resourceKind:"Graph workflow",resourceId:e})}async applyCanonicalWrapper(e,t,o){if(!xi(t))return;if(t.document.id!==e.workflowId)throw new A(`Document id '${t.document.id}' does not match the workflow id '${e.workflowId}' from the request path`);const n=await ci(t.document,{limits:this.limits,...this.catalogue?{catalogue:this.catalogue}:{}},o);if(!n.valid)throw new mo(n.issues);e.document=_i(t.document),e.name=t.document.name}};Di=S([F(Bt),D("design:paramtypes",[Function])],Di);let Pi=class extends H{constructor(){super(Ft)}async saveRun(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"saveRun",!0)).for(this.saveRun),n=bi(e);let r;try{r=await super.read(e.runId,...o)}catch{r=null}if(r)return r.workflowId=n.workflowId,r.owner=n.owner,r.status=n.status,r.documentFingerprint=n.documentFingerprint,r.result=n.result,r.error=n.error,r.startedAt=n.startedAt,r.finishedAt=n.finishedAt,void await this.update(r,...o);await this.create(n,...o)}async readRun(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"readRun",!0)).for(this.readRun);try{return(e=>{const t=e.result;return{runId:e.runId,workflowId:e.workflowId,ownerUser:e.owner??null,status:(o=e.status,"string"==typeof o&&["queued","validating","running","succeeded","failed","cancelled"].includes(o)?e.status:"failed"),createdAt:e.createdAt.toISOString(),...e.startedAt?{startedAt:e.startedAt.toISOString()}:{},...e.finishedAt?{finishedAt:e.finishedAt.toISOString()}:{},...t?{result:t}:{},...e.error?{error:e.error}:{},...e.documentFingerprint?{documentFingerprint:e.documentFingerprint}:{}};var o})(await super.read(e,...o))}catch{return null}}async listRuns(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"listRuns",!0)).for(this.listRuns);return await this.findBy("workflowId",e,...o)}};Pi=S([F(Ft),D("design:paramtypes",[])],Pi);let Ri=class extends H{constructor(){super(Wt)}async upsertManifest(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"upsertManifest",!0)).for(this.upsertManifest),n=(e=>new Wt({kind:e.kind,name:e.display?.name,category:e.display?.category,group:e.display?.group,description:e.display?.description,manifest:bt(wt(e))}))(e);let r;try{r=await this.read(n.kind,...o)}catch{r=void 0}return r?(r.name=n.name,r.category=n.category,r.group=n.group,r.description=n.description,r.manifest=n.manifest,await this.update(r,...o)):await this.create(n,...o)}async syncFromCatalogue(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"syncFromCatalogue",!0)).for(this.syncFromCatalogue),n=e.listManifests(void 0,...o),r=[];for(const e of n)r.push(await this.upsertManifest(e,...o));return r}async listNodes(...e){const{ctxArgs:t}=(await this.logCtx(e,"listNodes",!0)).for(this.listNodes);return await this.listBy("kind",K.ASC,...t)}async listManifests(...e){return(await this.listNodes(...e)).map(e=>(e=>{if(!e.manifest)throw new A(`Graph node row '${e.kind}' has no manifest to convert`);return bt(wt(e.manifest))})(e))}async getNode(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"getNode",!0)).for(this.getNode);try{return await this.read(e,...o)}catch{throw new _(`Graph node kind '${e}' is not registered`)}}};Ri=S([F(Wt),D("design:paramtypes",[])],Ri);class $i{map(e){const t={};for(const[o,n]of Object.entries(e.nodeResults))t[o]={status:n.status,startedAt:n.startedAt?.toISOString(),finishedAt:n.finishedAt?.toISOString(),error:n.error,outputs:n.outputs,fromCache:n.fromCache,pinned:n.pinned};const o={};for(const t of e.events)t.edgeId&&"edge.valueRouted"===t.type&&(o[t.edgeId]={status:se.SUCCEEDED,lastValue:t.payload?.value,updatedAt:t.timestamp.toISOString()});const n=[...e.events];return{runId:e.runId,status:e.status,nodes:t,edges:o,outputs:e.outputs,events:n}}}export{_r as AgentNode,rr as BreakFlowNode,Er as ChatTriggerNode,mr as CodeInputSchema,yr as CodeNode,Bo as ConditionExpressionEvaluator,cr as DEFAULT_GRAPH_WORKFLOW_DOCUMENT_LIMITS,xn as DEFAULT_GRAPH_WORKFLOW_VALIDATION_LIMITS,fn as DEFAULT_PINNING_METADATA,wr as DelayFlowNode,ar as ErrorBoundaryFlowNode,Nr as EventTriggerNode,kr as FormTriggerNode,Sr as GRAPH_AGENT_NODES,Xr as GRAPH_BOUNDARY_NODES,Yr as GRAPH_BUILT_IN_NODE_CLASSES_BY_KIND,Wr as GRAPH_BUILT_IN_NODE_MANIFESTS,Hr as GRAPH_BUILT_IN_NODE_MANIFESTS_BY_KIND,gr as GRAPH_CODE_DEFAULT_LANGUAGE,pr as GRAPH_CODE_DEFAULT_TIMEOUT_MS,fr as GRAPH_CODE_LANGUAGES,eo as GRAPH_CODE_MAX_TIMEOUT_MS,Jt as GRAPH_DEFAULT_CONCURRENCY,Yt as GRAPH_DEFAULT_MAX_FOREACH_ITERATIONS,Xt as GRAPH_DEFAULT_MAX_LOOP_ITERATIONS,_n as GRAPH_DOCUMENT_FORBIDDEN_FIELD_KEYS,Vr as GRAPH_FLOW_CONTROL_NODES,zt as GRAPH_LOCAL_EXECUTION_BACKEND,ro as GRAPH_LOOP_KIND,Jr as GRAPH_LOOP_NODES,Zt as GRAPH_MAX_FOREACH_ITERATIONS,Qt as GRAPH_MAX_LOOP_ITERATIONS,to as GRAPH_PINNING_METADATA_KEY,nn as GRAPH_PLAIN_SECRET_KEYS,Kr as GRAPH_TRIGGER_NODES,zr as GRAPH_UTILITY_NODES,Vt as GRAPH_WORKFLOW_BOUNDARY,ni as GRAPH_WORKFLOW_FORBIDDEN_FIELD_KEYS,$o as GraphAuthValidator,fo as GraphBreakSignal,$r as GraphConditionEvaluator,no as GraphConditionType,En as GraphConnectionPolicyValidator,On as GraphConnectionValidationError,An as GraphCredentialAuthorizationError,Nn as GraphCredentialReferenceValidator,ao as GraphCycleError,kn as GraphDocumentValidationError,In as GraphEdgeInstanceValidator,Go as GraphEngineEventSink,ur as GraphEnvironment,Fo as GraphExecutionBackendRegistry,Lo as GraphExecutionContext,Tn as GraphExecutionEngine,io as GraphExecutionError,yo as GraphExecutionEventEmitter,wo as GraphExecutionEventFactory,Mo as GraphExecutionFrame,Rn as GraphExecutionPlanner,$i as GraphExecutionSnapshotMapper,Rr as GraphForeachLoopNode,so as GraphInputError,Lr as GraphInputValueNode,ui as GraphLoopExecutionContext,lo as GraphLoopLimitError,nr as GraphNode,Yn as GraphNodeCatalogue,Qn as GraphNodeExecutorRegistry,Zn as GraphNodeExecutorResolver,bn as GraphNodeInstanceValidator,Vn as GraphNodeManifestResolver,Un as GraphNodeMethodNotFoundError,Fn as GraphNodeMethodRegistry,Ri as GraphNodeModelService,Gn as GraphNodeNotFoundError,jn as GraphNodeRegistrationError,Mr as GraphOutputValueNode,rn as GraphParameterValidator,yn as GraphPinningDependencyResolver,co as GraphPinningError,mn as GraphPinningPolicy,hn as GraphPinningService,oo as GraphPinningStrategy,uo as GraphPortError,ti as GraphPortSchemaResolver,go as GraphRunCancelledError,Ei as GraphRunEventPublisher,Ni as GraphRunExecutor,Pi as GraphRunModelService,Oi as GraphRunService,po as GraphStoreError,pn as GraphTopology,ho as GraphTopologyError,Cr as GraphUntilLoopNode,an as GraphValueModel,cn as GraphValueRepository,oi as GraphValueValidator,Tr as GraphWhileLoopNode,mo as GraphWorkflowDocumentRejectedError,Pn as GraphWorkflowDocumentValidator,Di as GraphWorkflowService,sr as HumanApprovalFlowNode,dr as IfFlowNode,wi as InMemoryGraphRunEventStore,Ii as InMemoryGraphRunStore,Mn as IsolatedVmCodeSandboxEvaluator,wn as LocalGraphExecutionBackend,br as LogFlowNode,Or as ManualTriggerNode,vr as MapNode,Ar as ScheduleTriggerNode,lr as SwitchFlowNode,Ir as UtilityLogNode,xr as WebhookTriggerNode,gi as assertGraphResourceOwnership,fi as assertGraphResourceWriteOwnership,jo as buildGraphExecutionResult,Zr as builtInGraphNodeRegistrations,pi as canAccessGraphResource,hi as canAccessGraphResourcePayload,Zo as checkGraphValueAgainstSchema,hr as clampGraphCodeTimeoutMs,vn as collectLooseNodeIssues,vo as composeGraphNamespace,un as createGraphValueRepository,tr as declaredGraphNodeMethods,bo as decomposeGraphNamespace,Po as decomposeGraphNamespaces,er as defineGraphNode,Yo as detectGraphCodeModeSurfaces,Ho as evaluateCodeCondition,Vo as evaluateCondition,Ko as evaluateConditionSync,Oo as findMalformedGraphNamespaces,ko as findUngrantedGraphNamespaces,So as graphAuthDataFromRecord,Do as graphAuthDataOf,Qo as graphDocumentHasCodeMode,No as graphNamespaceCovers,Eo as graphNamespacePartsOf,or as graphNodeConfig,Ao as graphRolesFromNamespaces,yi as graphRunDocumentFingerprint,Ai as graphWorkflowOwnerOf,Wo as isCodeCondition,qo as isConditionExpression,tn as isGraphCredentialReferenceLike,Io as isGraphNamespaceCacheEntryValid,Sn as isGraphResolvedWorkflow,gn as isPinnable,Ro as mergeGraphAuthData,ei as registerBuiltInGraphNodes,Uo as resolveGraphBackendCapabilities,Hn as resolveGraphDynamicPorts,Kn as resolveGraphNodeManifest,sn as serializeGraphValueKey,Cn as stripFacadeOwnedBackendConfig,ci as validateGraphWorkflowDocumentAtBoundary};
|
|
2
2
|
//# sourceMappingURL=as-graph.js.map
|