@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.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e,t;e=this,t=function(e,t,o,n,r,a,i,s,d,l,c,u,p){"use strict";function h(e){var t=Object.create(null);return e&&Object.keys(e).forEach(o=>{if("default"!==o){var n=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(t,o,n.get?n:{enumerable:!0,get:()=>e[o]})}}),t.default=e,Object.freeze(t)}var f,g,m=h(l),y=h(c),w=h(u);r.ValidationKeys.REQUIRED,r.ValidationKeys.MIN,r.ValidationKeys.MIN_LENGTH,r.ValidationKeys.MAX,r.ValidationKeys.MAX_LENGTH,r.ValidationKeys.PATTERN,r.ValidationKeys.URL,r.ValidationKeys.STEP,r.ValidationKeys.DATE,r.ValidationKeys.EMAIL,r.ValidationKeys.PASSWORD,r.ValidationKeys.EQUALS,r.ValidationKeys.DIFF,r.ValidationKeys.LESS_THAN,r.ValidationKeys.LESS_THAN_OR_EQUAL,r.ValidationKeys.GREATER_THAN,r.ValidationKeys.GREATER_THAN_OR_EQUAL,(e=>{e.GRAPH="graph",e.NODE="graph.node",e.EDGE="graph.edge",e.PORT="graph.port",e.STATE="graph.state"})(f||(f={})),(e=>{e.INPUT="input",e.OUTPUT="output",e.CONNECTION="connection"})(g||(g={}));const b={};function _(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 v(e,t){b[e]=t}function N(e,t,o){const n=t?b[t]:void 0;return n?.color?n.color:e||"#64748b"}function I(e,t,o){const n=t?b[t]:void 0;return n?.icon?n.icon:e||"ti-pointer"}const E=["skip","passThroughFirstInput","emitDefaults"];function A(e){return E.includes(e)}var O,k,x,S;(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"})(O||(O={})),(e=>{e.IDLE="idle",e.RUNNING="running",e.BLOCKED="blocked",e.SUCCEEDED="succeeded",e.FAILED="failed",e.SKIPPED="skipped"})(k||(k={})),(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"})(x||(x={})),(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"})(S||(S={}));const D={maxRequestBytes:4e6,maxConcurrentRuns:32,maxEventsPerRun:1e4,maxEventPayloadBytes:256e3,executionTimeoutMs:6e5,eventReplayWindowMs:3e5},R=[S.WORKFLOW_COMPLETED,S.WORKFLOW_FAILED,S.WORKFLOW_CANCELLED];function P(e){return R.includes(e)}function C(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function T(e){const t=n.Metadata.constr(e);if("function"==typeof t)return t;const o=e.constructor;return"function"==typeof o?o:e}function $(e){if(null!=e)return"string"==typeof e?e:e+""}function G(e,t,o){return $(e?.props?.label??e?.props?.name)??$(t?.name)??o??""}function L(e,t,o){const a=V(e,t);if(a?.model&&"function"==typeof a.model&&r.Model.isModel(a.model))return a.model;const i=n.Metadata.type(e,t);if("function"==typeof i&&r.Model.isModel(i))return i;const s=n.Metadata.getPropDesignTypes?.(e,t)?.designTypes||[];for(const e of s)if("function"==typeof e&&r.Model.isModel(e))return e;const d=o?.[r.ValidationKeys.TYPE]?.customTypes||[];for(const e of d)if("function"==typeof e&&r.Model.isModel(e))return e}function M(e,t){const o=[t,e.path??e.property].filter(Boolean).join(".");return{...e,path:o,children:e.children?.map(e=>M(e,o))}}function F(e){const t=T(e);return n.Metadata.get(t,f.NODE)}function V(e,t){const o=T(e);return n.Metadata.get(o,n.Metadata.key(f.PORT,t+""))}function j(e,t,o,r=new Set){const a=V(e,t);if(!a?.schema)return;const i=L(e,t,n.Metadata.validationFor(e,t));if(!i)return;if(r.has(i))return[];const s=new Set(r);return s.add(e),s.add(i),W(i,s).filter(e=>e.direction===o)}function U(e,t,o=new Set){const a=V(e,t);if(!a)return;const i=n.Metadata.validationFor(e,t),s=L(e,t,i);if(a.schema&&s)return;const d=r.Model.uiElementOf(e,t)||void 0,l=r.Model.uiDecorationOf(e,t,"uiprop"),c=n.Metadata.type(e,t),u=$(a.type??i?.[r.ValidationKeys.TYPE]?.customTypes?.[0]?.name??d?.props?.type??l?.type??c?.name),p=(a.expand||s&&!o.has(s))&&s?(()=>{const n=new Set(o);return n.add(e),n.add(s),W(s,n).map(e=>M(e,t))})():void 0;return{property:t,path:t,direction:a.direction,name:t,label:G(d,l,t),type:u?.toLowerCase(),required:!!i?.[r.ValidationKeys.REQUIRED],hidden:!!r.Model.uiIsHidden(e,t),designType:c?.name,element:d,prop:l,validation:i,graph:a,connectionRules:a.connectionRules,composite:!!p?.length,children:p,model:s?.name}}function B(e){return W(T(e))}function W(e,t=new Set){const o=n.Metadata.properties(e)||[],r=[];for(const n of o){const o=n+"",a=V(e,o);if(a?.schema){const n=j(e,o,a.direction,t);if(n){r.push(...n);continue}}const i=U(e,o,t);i&&r.push(i)}return r}function q(e){return e.flatMap(e=>e.children&&e.children.length?q(e.children):[e])}function H(e){const t=T(e),o=r.Model.uiModelOf(t),a=F(t)||{},i=o?.tag||t.name,s=B(t),d=((e,t)=>{const o=t.portGroups||[],r=new Map(o.map(e=>[e.property,e])),a=[],i=n.Metadata.properties(e)||[];for(const t of i){const o=t+"",i=V(e,o);if(!i?.schema)continue;if(!L(e,o,n.Metadata.validationFor(e,o)))continue;const s=r.get(o);a.push(s?{...s,toggle:s.toggle??"all"}:{property:o,toggle:"all"})}for(const e of o)a.some(t=>t.property===e.property)||a.push(e);return a.length?a:void 0})(t,a),l=a.namespaces?.length?a.namespaces:(e=>{if(null==e)return[];let t,o=e;try{o=n.Metadata.constr(e)}catch{o=e}try{t=n.Metadata.get(o,"auth-namespace")}catch{t=void 0}return C(t)??[]})(t),c=l.length?l:void 0;return{name:t.name,tag:i,kind:a.kind||i,category:a.category,color:a.color,effectiveColor:N(a.color,a.category),group:a.group,height:a.height,icon:a.icon,effectiveIcon:I(a.icon,a.category),labels:a.labels||[],maxChildren:a.maxChildren,minWidth:a.minWidth,width:a.width,shape:a.shape,cornerRadius:a.cornerRadius,sizeRules:a.sizeRules,props:o?.props,ui:o,graph:a,ports:s,portGroups:d,namespaces:c}}const K=new Set,z=new Set;function X(e,t,r){return n.Decoration.for(f.NODE).define({decorator:(e,t,r)=>{const a={kind:t?.kind||e,...t};return t=>{const i=n.apply(o.uimodel(e,r),n.metadata(f.NODE,a))(t);var s;return s=t,K.add(s),i}},args:[e,t,r]}).apply()}function J(e,t){return n.Decoration.for(f.PORT).define({decorator:(e,t)=>(o,r)=>{const a={direction:e,...t};return n.apply(n.propMetadata(n.Metadata.key(f.PORT,r),a))(o,r)},args:[e,t]}).apply()}function Y(e){return J(g.INPUT,{...e,schema:!0})}function Q(e){return J(g.OUTPUT,{...e,schema:!0})}function Z(e){return J(g.CONNECTION,e)}o.RenderingEngine.prototype.renderAsNode=(e,t,...o)=>H(e),n.Metadata.nodes=(()=>[...K]).bind(n.Metadata),n.Metadata.workflows=(()=>[...z]).bind(n.Metadata);const ee=["__proto__","prototype","constructor"];function te(e){return ee.includes(e)}function oe(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function ne(e){return null===e||"string"==typeof e||"number"==typeof e&&Number.isFinite(e)||"boolean"==typeof e}function re(e){return!!ne(e)||(Array.isArray(e)?e.every(e=>re(e)):!!oe(e)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&!te(t)&&re(e[t])))}function ae(e){if(void 0===e)return!1;if("number"==typeof e)return Number.isFinite(e);if("function"==typeof e)return!1;if(re(e))return!0;if(Array.isArray(e))return e.every(e=>ae(e));if(oe(e)){const t=Reflect.ownKeys(e);for(const o of t){if("string"!=typeof o)return!1;if(te(o))return!1;if(!ae(e[o]))return!1}return!0}return!1}function ie(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>ie(e));const t={};for(const[o,n]of Object.entries(e))t[o]=ie(n);return t}const se={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"},de={date:"date",datetime:"date-time","date-time":"date-time",duration:"duration"};function le(e){return e?se[e.toLowerCase()]??"any":"any"}function ce(e,t){const o=e[t];if(o&&"object"==typeof o)return o.value}function ue(e,t){const o=ce(e,t);return"number"==typeof o&&Number.isFinite(o)?o:void 0}function pe(e,t,o){const n=e??{},a=(e=>{const t=ce(e,r.ValidationKeys.ENUM);if(Array.isArray(t)&&t.every(ne))return t})(n);if(a)return{type:"enum",values:a};const i=(e=>{const t=e[r.ValidationKeys.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(le(e)){case"string":{const t=(e=>{if(e)return de[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=ue(t,r.ValidationKeys.MIN),a=ue(t,r.ValidationKeys.MAX);return void 0!==n&&(o.min=n),void 0!==a&&(o.max=a),o}case"boolean":return{type:"boolean"};case"array":return((e,t)=>{const o={type:"array",items:he(e,t)},n=ue(e,r.ValidationKeys.MIN),a=ue(e,r.ValidationKeys.MAX);return void 0!==n&&(o.minItems=n),void 0!==a&&(o.maxItems=a),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 he(e,t){if((e=>{const t=e[r.ValidationKeys.LIST];return!!t?.clazz?.length})(e))return{type:"model",name:fe(e)};const o=ce(e,r.ValidationKeys.TYPE);if("string"==typeof o){const e=le(o);return"model"===e?{type:"model",name:o}:{type:e}}if(t&&"array"!==t){const e=le(t);return"model"===e?{type:"model",name:t}:{type:e}}return{type:"any"}}function fe(e){const t=e[r.ValidationKeys.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 ge(e){return"workflow"===e.scope}function me(e){return"node"===e.scope}function ye(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 we(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&&re(t)}return"expression"===t&&2===Object.keys(e).length&&"string"==typeof e.expression}const be=["any","string","number","boolean","array","object","enum","model"];function _e(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&(e=>be.includes(e))(e.type)}function ve(e,t={seen:[]}){if(t.seen.includes(e))throw new a.ValidationError(`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.ValidationError("Document 'id' is required and must be a non-empty string");if("string"!=typeof e.name||!e.name)throw new a.ValidationError("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.ValidationError("Workflow port 'id' is required and must be a non-empty string");if(o.has(t.id))throw new a.ValidationError(`Workflow port '${t.id}' is declared more than once; workflow port ids must be unique`);if(void 0!==t.schema&&!_e(t.schema))throw new a.ValidationError(`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)Ne(t,r);for(const t of e.nodes)t.loop&&Ie(t,t.loop,n),t.errorBoundary&&Ee(t,t.errorBoundary,n);const i=new Set;for(const t of e.edges)Oe(t,i);for(const t of e.edges)ke(t.source,0,o,r,`Edge '${t.id}' source`),ke(t.target,0,o,r,`Edge '${t.id}' target`);if(void 0!==e.settings&&!ae(e.settings))throw new a.ValidationError("Document settings must be JSON-safe (a map of JSON-safe values)");if(void 0!==e.metadata&&!ae(e.metadata))throw new a.ValidationError("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&&!ae(e.ui))throw new a.ValidationError("Document ui must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed")}function Ne(e,t){if("string"!=typeof e.id||!e.id)throw new a.ValidationError("Node 'id' is required and must be a non-empty string");if(t.has(e.id))throw new a.ValidationError(`Node id '${e.id}' is declared more than once; node ids must be unique`);if("string"!=typeof e.kind||!e.kind)throw new a.ValidationError(`Node '${e.id}' must declare a non-empty string 'kind'`);if(void 0===e.parameters||null===e.parameters)throw new a.ValidationError(`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(te(t))throw new a.ValidationError(`Node '${e.id}' input binding key '${t}' is not allowed (unsafe prototype-pollutant key)`);if(!we(o))throw new a.ValidationError(`Node '${e.id}' input binding for '${t}' must be a valid GraphInputBinding (edge, literal, or expression)`);if("literal"===o.mode&&!ae(o.value))throw new a.ValidationError(`Node '${e.id}' literal binding for '${t}' must contain JSON-safe values`);if("expression"===o.mode&&!o.expression)throw new a.ValidationError(`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(te(t))throw new a.ValidationError(`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.ValidationError(`Node '${e.id}' output binding for '${t}' must be an object with enabled and alias settings`)}if(!ae(e.parameters))throw new a.ValidationError(`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.ValidationError(`Node '${e.id}' state must be an object when present`);if(!ae(e.state))throw new a.ValidationError(`Node '${e.id}' state must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`)}}function Ie(e,t,o){if(!t.body||"object"!=typeof t.body)throw new a.ValidationError(`Node '${e.id}' loop configuration requires a body document`);if(ve(t.body,o),!(void 0===t.maxIterations||Number.isFinite(t.maxIterations)&&t.maxIterations>0))throw new a.ValidationError(`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.ValidationError(`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.ValidationError(`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(te(t))throw new a.ValidationError(`Node '${e.id}' loop mapping key '${t}' is not allowed (unsafe prototype-pollutant key)`);Ae(n,e.id,t)}}function Ee(e,t,o){if(!t.try||"object"!=typeof t.try)throw new a.ValidationError(`Node '${e.id}' error-boundary configuration requires a try body document`);ve(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.ValidationError(`Node '${e.id}' error-boundary ${n} body must be a document`);ve(r,o)}}function Ae(e,t,o){if(!e||"object"!=typeof e)throw new a.ValidationError(`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.ValidationError(`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.ValidationError(`Node '${t}' loop mapping '${o}' referencing a node must reference a node id and a port`);break;case"literal":if(!ae(e.value))throw new a.ValidationError(`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.ValidationError(`Node '${t}' loop mapping '${o}' expression references must be non-empty expressions`);break;default:throw new a.ValidationError(`Node '${t}' loop mapping '${o}' must use a workflow, node, literal, or expression reference source`)}}function Oe(e,t){if("string"!=typeof e.id||!e.id)throw new a.ValidationError("Edge 'id' is required and must be a non-empty string");if(t.has(e.id))throw new a.ValidationError(`Edge id '${e.id}' is declared more than once; edge ids must be unique`);if(!ye(e.source))throw new a.ValidationError(`Edge '${e.id}' source endpoint is not a valid GraphEndpoint`);if(!ye(e.target))throw new a.ValidationError(`Edge '${e.id}' target endpoint is not a valid GraphEndpoint`);if("data"!==e.type&&"connection"!==e.type)throw new a.ValidationError(`Edge '${e.id}' type '${e.type+""}' is not a valid edge type (data or connection are allowed)`);if(t.add(e.id),!ae(e))throw new a.ValidationError(`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 ke(e,t,o,n,r){if(ge(e)){if(!o.has(e.port))throw new a.ValidationError(`${r} references workflow port '${e.port}' which is not declared on the document`)}else if(me(e)){if(!n.has(e.nodeId))throw new a.ValidationError(`${r} references node '${e.nodeId}' which is not part of the document`);if("string"!=typeof e.port||!e.port)throw new a.ValidationError(r+" node endpoints must reference a non-empty port identifier")}}const xe=["expression","template"],Se=["javascript","typescript","json","text"];function De(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return!(!(e=>xe.includes(e))(t.mode)||"string"!=typeof t.expression||!t.expression||void 0!==t.language&&!(e=>Se.includes(e))(t.language)||void 0!==t.metadata&&!re(t.metadata))}function Re(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 Pe(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 Ce=["trigger","loop","branching","stateful","retryable","cancellable","parallel","resource"];function Te(e){return Ce.includes(e)}function $e(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.ValidationError("Graph node manifest does not conform to the required shape");if(!ae(e))throw new a.ValidationError("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 Ge=["loadOptions","listSearch","resourceLocator","resourceMapping","validateParameter","action"];function Le(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.name&&(e=>Ge.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 Me(e){const t=e.element?.props?.value,o=t??e.prop?.value??e.validation?.defaultValue;if(void 0!==o&&"function"!=typeof o&&ae(o))try{return JSON.parse(JSON.stringify(o))}catch{return}}function Fe(e){if(e.type&&e.type in de)return{type:"string",format:de[e.type]};const t=(e=>{for(const t of[e.graph?.type,e.element?.props?.type,e.prop?.type])if("string"==typeof t&&"any"!==le(t))return t})(e);return t?pe((e=>{if(!e)return;const t=Object.entries(e).filter(([e])=>e!==r.ValidationKeys.TYPE);return Object.fromEntries(t)})(e.validation),t):pe(e.validation,e.type,e.model)}function Ve(e){const t={};for(const[o,n]of Object.entries(e.graph?.metadata??{}))ae(n)&&(t[o]=JSON.parse(JSON.stringify(n)));return Object.keys(t).length?t:void 0}function je(e){switch(e){case"output":return"output";case"connection":return"connection";default:return"input"}}function Ue(e){const t=e.graph?.handle;return"connection"!==e.direction&&"string"==typeof t&&t?t:e.path??e.property}function Be(e,t){const o={id:Ue(e),label:e.label,direction:je(e.direction),schema:Fe(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 a=Ze(e.graph?.connectionRules)??t;a&&(o.connectionPolicy=a);const i=(e=>{const t=e.element;if(!t||!ae(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)?ie(n):{}}})(e);i&&(o.element=i);const s=Ve(e);return s&&(o.metadata=s),o}function We(e){const t={type:"string",id:Ue(e),label:e.label,required:e.required};if(e.hidden)return((e,t)=>{const o={...t,type:"hidden"},n=Me(e);return void 0!==n&&(o.defaultValue=n),qe(o)})(e,t);const o=Me(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=Ve(e);if(r&&(t.metadata=r),(e=>{const t=ze(e);return"code"===t||"code-editor"===t})(e))return qe({...t,type:"code",language:Ye(e)});const a=Fe(e);switch(a.type){case"number":{const o={...t,type:"number",integer:a.integer,min:a.min,max:a.max},n=Ke(e.validation?.step);return void 0!==n&&(o.step=n),qe(o)}case"boolean":return qe({...t,type:"boolean"});case"enum":return qe({...t,type:"options",options:a.values.map(e=>({value:e,label:e+""}))});case"array":{const e={...t,type:"collection"};return void 0!==a.maxItems&&(e.maxItems=a.maxItems),qe(e)}case"object":case"model":return qe({...t,type:"object"});default:return qe({...t,type:"string",multiline:!!Xe(e)||void 0,pattern:He(e.validation?.pattern),minLength:Ke(e.validation?.minlength),maxLength:Ke(e.validation?.maxlength)})}}function qe(e){const t=e;for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return e}function He(e){const t=e?.value;return"string"==typeof t?t:void 0}function Ke(e){const t=e?.value;return"number"==typeof t&&Number.isFinite(t)?t:void 0}function ze(e){const t=e.element?.tag;return"string"==typeof t&&t?t:void 0}function Xe(e){return"textarea"===ze(e)||"textarea"===(e=>{const t=e.element?.props?.type;return"string"==typeof t?t:void 0})(e)}const Je=["javascript","typescript","json","text"];function Ye(e){const t=e.element?.props?.language;return"string"==typeof t&&Je.includes(t)?t:"javascript"}function Qe(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 a=((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 a&&(o.icon=a),"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 Ze(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 a=t.maxConnections;return"number"==typeof a&&Number.isFinite(a)&&(o.maxConnections=a),Object.keys(o).length?o:void 0}function et(e,t={}){const o="function"==typeof e?e:e.constructor;if(!F(o))throw new a.ValidationError(`Node '${o?.name??e+""}' is not decorated with @node and cannot produce a manifest`);const n=H(o),r=q(B(o)),i=[],s=[],d=[],l=[],c=Ze(n.graph?.connectionRules);for(const e of r)("connection"===e.direction?d:"output"===e.direction?s:i).push(Be(e,c)),"input"===e.direction&&l.push(We(e));const u={kind:t.kind??n.kind??n.name,display:Qe(n,t),inputs:i,outputs:s,parameters:l};return d.length&&(u.connections=d),n.namespaces?.length&&(u.namespaces=n.namespaces.slice()),$e(u),u}var tt,ot;(e=>{e.READABILITY="readability",e.COMPACTNESS="compactness",e.BALANCED="balanced"})(tt||(tt={})),(e=>{e.TIGHT="tight",e.NORMAL="normal",e.COMFORTABLE="comfortable"})(ot||(ot={})),ot.TIGHT,ot.NORMAL,ot.COMFORTABLE,tt.READABILITY,ot.COMFORTABLE,tt.COMPACTNESS,ot.TIGHT,tt.BALANCED,ot.NORMAL;let nt=class extends s.BaseModel{constructor(e){super(e)}};i.__decorate([s.pk({type:String,generated:!1}),n.description("Unique graph run id"),o.uielement("ngx-decaf-crud-field",{label:"graph.run.id.label",readonly:!0}),i.__metadata("design:type",String)],nt.prototype,"runId",void 0),i.__decorate([s.column(),r.required(),s.index(),n.description("Workflow document id the run executes"),o.uilistprop("workflowId"),o.uielement("ngx-decaf-crud-field",{label:"graph.run.workflowId.label"}),i.__metadata("design:type",String)],nt.prototype,"workflowId",void 0),i.__decorate([s.column(),n.description("Owning user; absent for anonymous callers"),o.uielement("ngx-decaf-crud-field",{label:"graph.run.owner.label"}),i.__metadata("design:type",String)],nt.prototype,"owner",void 0),i.__decorate([s.column(),r.required(),r.type(String),s.index(),n.description("Current run lifecycle status"),o.uilistprop("status"),o.uielement("ngx-decaf-crud-field",{label:"graph.run.status.label",readonly:!0}),i.__metadata("design:type",String)],nt.prototype,"status",void 0),i.__decorate([s.column(),n.description("Fingerprint of the executed document"),o.uielement("ngx-decaf-crud-field",{label:"graph.run.fingerprint.label",readonly:!0}),i.__metadata("design:type",String)],nt.prototype,"documentFingerprint",void 0),i.__decorate([s.column(),n.prop(),n.description("Workflow input values keyed by input port id"),i.__metadata("design:type",Object)],nt.prototype,"inputs",void 0),i.__decorate([s.column(),n.prop(),n.description("Execution result, present on successful completion"),i.__metadata("design:type",Object)],nt.prototype,"result",void 0),i.__decorate([s.column(),n.prop(),n.description("Structured error payload, present on failure"),i.__metadata("design:type",Object)],nt.prototype,"error",void 0),i.__decorate([r.date(),s.column(),n.description("Run creation timestamp"),i.__metadata("design:type",Date)],nt.prototype,"createdAt",void 0),i.__decorate([r.date(),s.column(),n.description("Execution start timestamp, once it has started"),i.__metadata("design:type",Date)],nt.prototype,"startedAt",void 0),i.__decorate([r.date(),s.column(),n.description("Terminal-state timestamp, once the run has finished"),i.__metadata("design:type",Date)],nt.prototype,"finishedAt",void 0),nt=i.__decorate([o.uilistmodel("ngx-decaf-list-item",{icon:"ti-player-play"}),o.uimodel("ngx-decaf-crud-form"),n.description("Persistable graph run lifecycle record"),s.table("graph_run"),r.model(),i.__metadata("design:paramtypes",[Object])],nt);let rt=class extends s.BaseModel{constructor(e){super(e)}};i.__decorate([s.pk({type:String,generated:!1}),i.__metadata("design:type",String)],rt.prototype,"workflowId",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],rt.prototype,"name",void 0),i.__decorate([s.column(),i.__metadata("design:type",Object)],rt.prototype,"document",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],rt.prototype,"owner",void 0),i.__decorate([s.column(),i.__metadata("design:type",Object)],rt.prototype,"snapshot",void 0),rt=i.__decorate([s.table("graph_workflow"),r.model(),i.__metadata("design:paramtypes",[Object])],rt),v("Trigger",{color:"#3b82f6",icon:"ti-bolt"}),v("Flow Control",{color:"#f59e0b",icon:"ti-arrows-split-2"}),v("Utility",{color:"#0d9488",icon:"ti-tool"}),v("Loop",{color:"#eab308",icon:"ti-repeat"}),v("Workflow",{color:"#f97316",icon:"ti-sitemap"}),v("Pipeline",{color:"#0ea5e9",icon:"ti-git-merge"}),v("Node",{color:"#8b5cf6",icon:"ti-point-filled"}),v("Agent",{color:"#7c3aed",icon:"ti-robot"}),v("model",{color:"#3b82f6",icon:"ti-cpu"}),v("memory",{color:"#10b981",icon:"ti-database"}),v("workspace",{color:"#f59e0b",icon:"ti-folder"});const at=new Set;function it(e,t){return e.config[t]}function st(e){return Array.isArray(e)?e.map(e=>e+"").join(", "):e+""}(()=>{const e=[{key:x.NODE_ID,shouldInclude:e=>null!=it(e,x.NODE_ID),render:e=>it(e,x.NODE_ID)+""},{key:x.WORKFLOW_ID,shouldInclude:e=>null!=it(e,x.WORKFLOW_ID),render:e=>it(e,x.WORKFLOW_ID)+""},{key:x.RUN_ID,shouldInclude:e=>null!=it(e,x.RUN_ID),render:e=>it(e,x.RUN_ID)+""},{key:x.USER,shouldInclude:e=>null!=it(e,x.USER),render:e=>it(e,x.USER)+""},{key:x.ROLES,shouldInclude(e){const t=it(e,x.ROLES);return Array.isArray(t)&&t.length>0},render:e=>st(it(e,x.ROLES))},{key:x.NAMESPACES,shouldInclude(e){const t=it(e,x.NAMESPACES);return Array.isArray(t)&&t.length>0},render:e=>st(it(e,x.NAMESPACES))},{key:x.ORGANIZATION,shouldInclude:e=>null!=it(e,x.ORGANIZATION),render:e=>it(e,x.ORGANIZATION)+""},{key:x.IP,shouldInclude:e=>null!=it(e,x.IP),render:e=>it(e,x.IP)+""}];for(const o of e)at.has(o.key)||(t.logParameterRegistry.register(o),at.add(o.key))})();const dt="$workflow",lt="local",ct=1e3,ut=1e4,pt=3e4;var ht,ft;e.GraphPinningStrategy=void 0,(ht=e.GraphPinningStrategy||(e.GraphPinningStrategy={})).MANUAL="manual",ht.AUTOMATIC="automatic",ht.DISABLED="disabled",e.GraphConditionType=void 0,(ft=e.GraphConditionType||(e.GraphConditionType={})).TRUTHY="truthy",ft.FALSY="falsy",ft.EQUALS="equals",ft.NOT_EQUALS="notEquals",ft.GREATER_THAN="greaterThan",ft.GREATER_THAN_OR_EQUAL="greaterThanOrEqual",ft.LESS_THAN="lessThan",ft.LESS_THAN_OR_EQUAL="lessThanOrEqual",ft.EXISTS="exists",ft.CUSTOM="custom";class gt extends a.InternalError{constructor(e,t="GRAPH_EXECUTION_ERROR",o){super(e,gt.name,500),this.graphCode=t,this.details=o,this.name=this.constructor.name}}class mt extends gt{constructor(e){super("Graph workflow contains an unsupported cycle","GRAPH_CYCLE_ERROR",e)}}class yt extends gt{constructor(e,t){super(e,"GRAPH_INPUT_ERROR",t)}}class wt extends gt{constructor(e,t){super(e,"GRAPH_LOOP_LIMIT_ERROR",t)}}class bt extends gt{constructor(e,t){super(e,"GRAPH_PINNING_ERROR",t)}}class _t extends gt{constructor(e,t){super(e,"GRAPH_STORE_ERROR",t)}}class vt extends gt{constructor(e,t){super(e,"GRAPH_TOPOLOGY_ERROR",t)}}class Nt extends gt{constructor(e){super("Break signal","GRAPH_BREAK_SIGNAL",{value:e}),this.isBreakSignal=!0,this.name="GraphBreakSignal"}}class It extends gt{constructor(e){super(`Graph run '${e}' was cancelled`,"GRAPH_RUN_CANCELLED",{runId:e}),this.name=It.name}}class Et extends a.ValidationError{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=Et.name,this.issues=e}}class At{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 Ot{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 gt("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 kt(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(),a=o[1].split(",").map(e=>e.trim()).filter(e=>e.length>0);return n&&r&&0!==a.length?{organization:n,departments:a,role:r}:void 0}function xt(e){return`${e.organization}.${e.departments.join(",")}.${e.role}`}function St(e){if(!e||"string"!=typeof e.namespace||!e.parts)return!1;const t=kt(e.namespace);return!!t&&xt(t)===xt(e.parts)}function Dt(e,t){const o="string"==typeof e?e.trim():"";if(o){if(t)for(const e of t)if(e&&e.namespace===o&&St(e))return e.parts;return kt(o)}}function Rt(e,t,o={},n){const r=Dt(e,n),a=Dt(t,n);return!(!r||!a)&&r.organization===a.organization&&r.role===a.role&&("exact"===(o.mode??"inherit")?r.departments.length===a.departments.length&&r.departments.every((e,t)=>e===a.departments[t]):r.departments.length<=a.departments.length&&r.departments.every((e,t)=>e===a.departments[t]))}function Pt(e,t,o={},n){return e.filter(e=>!t.some(t=>Rt(t,e,o,n)))}function Ct(e){return e.filter(e=>void 0===kt(e))}function Tt(e,t){const o=new Set;for(const n of e){const e=Dt(n,t);e&&o.add(e.role)}return[...o]}function $t(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function Gt(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 Lt(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 a=$t(e.roles);a&&(t.roles=a);const i=$t(e.namespaces);return i&&(t.namespaces=i,t.namespaceCache=Ft(i)),t}function Mt(e){return e?Lt({user:Gt(e,"user"),organization:Gt(e,"organization"),ip:Gt(e,"ip"),roles:Gt(e,"roles"),namespaces:Gt(e,"namespaces")}):{}}function Ft(e){const t=[];for(const o of e){const e=kt(o);e&&t.push({namespace:o,parts:e})}return t}function Vt(...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??Ft(o.namespaces):void 0!==o.namespaceCache&&(t.namespaceCache=o.namespaceCache));return t}class jt{constructor(e={}){this.options=e}get enabled(){return!0===this.options.enabled}validate(e,o,n,r){if(!this.enabled)return;const a=r??this.options.logger??t.Logging.for("GraphAuth"),i=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=C(e.namespaces),o=C(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 '${i}'`,s?.namespaces??[],n,s?.roles??[],a);for(const e of o.nodes)this.assertGranted(`node '${e.id}'`,e.manifest.namespaces??[],n,[],a)}assertGranted(e,t,o,n,r){const a=o.namespaces??[],i=Pt(t,a,this.options.match,o.namespaceCache),d=Tt(a,o.namespaceCache),l=n.filter(e=>!d.includes(e));if(0===i.length&&0===l.length)return;const c=[...new Set([...Ct(t),...Ct(a)])],u=[];throw i.length&&u.push("namespace(s) "+i.join(", ")),l.length&&u.push("role(s) "+l.join(", ")),r.warn(`Graph access denied for ${e} for user ${o.user??"anonymous"}: missing ${u.join(" and ")}${c.length?`; malformed namespace(s) ${c.join(", ")} failed closed`:""}`),new s.ForbiddenError(`Access to ${e} requires ${u.join(" and ")}`)}}class Ut{constructor(e){this.baseOptions=e,this.inner=t.Logging.for("GraphRun").for(this.attributeConfig(e))}attributeConfig(e){return{[x.NODE_ID]:e.nodeId,[x.WORKFLOW_ID]:e.workflowId,[x.RUN_ID]:e.runId,[x.USER]:e.user??null,[x.ROLES]:e.roles,[x.NAMESPACES]:e.namespaces,[x.ORGANIZATION]:e.organization,[x.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:S.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 Bt(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}class Wt extends s.Context{constructor(e,t,o,n,r,a,i,s,d={},l,c,u){super(),this.runId=e,this.parentRunId=t,this.workflowId=o,this.document=n,this.node=r,this.manifest=a,this.path=i,this.emitFn=s,this.metadata=d,this.engine=l,this.abortSignal=c,this.limits=u;const p=Lt(d);this.accumulate({...p,operation:"execute"});const h="string"==typeof d?.user?d.user:null;this.runLogger=new Ut({runId:e,workflowId:o,nodeId:r.id,user:h,roles:Bt(d?.roles),namespaces:Bt(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 Mt(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:S.NODE_OUTPUT,payload:e})}async log(e,t){await this.emit({type:S.NODE_OUTPUT,payload:{message:e,payload:t}})}}class qt{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 Ht(e,t,o,n,r){const a=e.valueStore.getWorkflowValues(),i={};for(const[t,o]of e.nodeResults)i[t]=o;const s=[...e.events];return{runId:e.runId,workflowId:t.id||t.name,status:n,document:t,inputs:{...o},outputs:a,nodeResults:i,events:s,startedAt:e.startedAt,finishedAt:e.finishedAt,metadata:r}}class Kt{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:S.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 zt(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 Xt{static{this._cache={}}static register(e,t){return Xt._cache[e]=t,t}static get(e){const t=e??Xt._currentFlavour;if(t)return Xt._cache[t]}static getOrFail(e){const t=Xt.get(e);if(!t)throw new gt(`No graph execution backend registered under '${e}'`,"GRAPH_EXECUTION_BACKEND_NOT_REGISTERED");return t}static get current(){return Xt.get()}static get currentFlavour(){return Xt._currentFlavour??lt}static setCurrent(e){Xt._currentFlavour=e}static list(){return Object.entries(Xt._cache).map(([e,t])=>({flavour:e,backend:t}))}static unregister(e){e&&(delete Xt._cache[e],Xt._currentFlavour===e&&(Xt._currentFlavour=void 0))}static clear(){for(const e of Object.keys(Xt._cache))delete Xt._cache[e];Xt._currentFlavour=void 0}}class Jt{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 gt(`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 gt("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 Yt(e){return"object"==typeof e&&null!==e&&"type"in e&&"code"===e.type}function Qt(e){return"object"==typeof e&&null!==e&&"op"in e&&"string"==typeof e.op}async function Zt(e,t,o){const n=o.engine?.codeSandboxEvaluator;if(!n)throw new gt("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 eo(e,t,o){if(Qt(e))return(new Jt).evaluate(e,t);throw((e,t)=>new gt(`Unknown ${t??"flow"} condition type \u2014 must be ConditionExpression (op) or CodeCondition (type: 'code')`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition:e}))(e,o)}async function to(e,t,o){return Yt(e)?Zt(e,t.input,o):eo(e,t.state,t.label)}function oo(e,t,o,n){if(e&&"object"==typeof e&&!n.has(e))if(n.add(e),Yt(e))o.push({nodeId:t,kind:"code-condition"});else if(De(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))ro(e,o,n);else if(Array.isArray(e))for(const r of e)oo(r,t,o,n);else for(const r of Object.keys(e))oo(e[r],t,o,n)}function no(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});oo(e.parameters,n,t,o),oo(e.metadata,n,t,o),oo(e.state,n,t,o),oo(e.loop,n,t,o)}function ro(e,t,o){for(const n of e.nodes??[])no(n,t,o)}function ao(e){const t=[];return ro(e,t,new Set),t}function io(e,t){if(!t)return{valid:!0};switch(t.type){case"any":default:return{valid:!0};case"string":return"string"!=typeof e?so("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}:so("number");case"boolean":return"boolean"!=typeof e?so("boolean"):{valid:!0};case"array":if(!Array.isArray(e))return so("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=io(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 so(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=io(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 so(e){return{valid:!1,message:`expected a ${e} value`}}function lo(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 co=new Set(["loop"]),uo=["secret","secrets","password","passwd","token","accessToken","refreshToken","apiKey","api_key","privateKey","credentials"];class po{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 a=!0===t.policies?.allowUndeclaredParameters,i=new Map(t.parameters.map(e=>[e.id,e]));for(const[r,s]of Object.entries(e.parameters??{})){const d=i.get(r);if(!d){a||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 a of t.parameters)void 0===(e.parameters??{})[a.id]&&(this.isParameterSatisfiedByInput(e,a.id,r)||(!0===a.required||(a.validation??[]).some(e=>"required"===e.kind))&&void 0===a.defaultValue&&o.push({code:"parameter.required-missing",path:`${n}.parameters.${a.id}`,message:`Node '${e.id}' is missing required parameter '${a.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(De(e))return{valid:!0};switch(t.type){case"string":case"code":case"expression":return"string"!=typeof e?so("string"):{valid:!0};case"number":return"number"==typeof e&&Number.isFinite(e)?{valid:!0}:so("number");case"boolean":return"boolean"!=typeof e?so("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}:so("array");case"object":case"resourceLocator":return null===e||"object"!=typeof e||Array.isArray(e)?so("object"):{valid:!0};case"credential":return lo(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 a of Object.keys(e.metadata??{}))co.has(a)?o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${a}`,message:`Node '${e.id}' metadata key '${a}' is reserved and must not be set directly`,nodeId:e.id}):Array.isArray(r)&&!r.includes(a)&&o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${a}`,message:`Node '${e.id}' metadata key '${a}' 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||A(n)||t.push({code:"disabled.invalid-behavior",path:o+".metadata.disabledBehavior",message:`Node '${e.id}' disabled behavior '${n+""}' is not one of: ${E.join(", ")}`,nodeId:e.id})}validateBindingShapes(e,t,o,n){for(const[r,a]of Object.entries(e.inputBindings??{})){if("literal"===a.mode){const i=t.inputs.find(e=>e.id===r);if(i?.schema){const t=io(a.value,i.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"!==a.mode||"string"==typeof a.expression&&a.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,a={}){const i=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 i){const o=(e.inputBindings??{})[t];o&&"literal"===o.mode&&!0!==a.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&&(i.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(A(o))return o;const n=t?.disabledBehavior;return A(n)?n:"skip"}}function ho(e){return[e.namespace??"default",e.workflowId,e.nodeId,e.version??"default",e.fingerprint].join(":")}function fo(t){return new e.GraphValueModel({id:ho(t.key),workflowId:t.key.workflowId,nodeId:t.key.nodeId,fingerprint:t.key.fingerprint,...void 0!==t.key.namespace?{namespace:t.key.namespace}:{},...void 0!==t.key.version?{version:t.key.version}:{},pinned:t.pinned,outputs:t.outputs,createdAt:new Date(t.createdAt),updatedAt:new Date(t.updatedAt),...t.expiresAt?{expiresAt:new Date(t.expiresAt)}:{},...t.metadata?{metadata:t.metadata}:{}})}function go(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}:{}}}function mo(t){return new(0,s.Repository.forModel(e.GraphValueModel,t.alias).constructor)(t)}e.GraphValueModel=class extends s.BaseModel{constructor(e){super(e)}},i.__decorate([s.pk({type:String,generated:!1}),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"id",void 0),i.__decorate([s.column(),s.index(),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"workflowId",void 0),i.__decorate([s.column(),s.index(),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"nodeId",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"fingerprint",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"namespace",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"version",void 0),i.__decorate([s.column(),i.__metadata("design:type",Boolean)],e.GraphValueModel.prototype,"pinned",void 0),i.__decorate([s.column(),i.__metadata("design:type",Object)],e.GraphValueModel.prototype,"outputs",void 0),i.__decorate([s.column(),i.__metadata("design:type",Date)],e.GraphValueModel.prototype,"createdAt",void 0),i.__decorate([s.column(),i.__metadata("design:type",Date)],e.GraphValueModel.prototype,"updatedAt",void 0),i.__decorate([s.column(),i.__metadata("design:type",Date)],e.GraphValueModel.prototype,"expiresAt",void 0),i.__decorate([s.column(),i.__metadata("design:type",Object)],e.GraphValueModel.prototype,"metadata",void 0),e.GraphValueModel=i.__decorate([s.table("graph_value"),r.model(),i.__metadata("design:paramtypes",[Object])],e.GraphValueModel),e.GraphValueRepository=class extends s.Repository{constructor(t){super(t,e.GraphValueModel,!0),this.runtimeValues=new Map}seedWorkflowInputs(e){this.runtimeValues.set(dt,{...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(dt)??{};o[e]=t,this.runtimeValues.set(dt,o)}getWorkflowValues(){return{...this.runtimeValues.get(dt)??{}}}snapshot(){return Object.fromEntries(this.runtimeValues.entries())}async readCached(e,...t){try{return go(await this.read(ho(e),...t))}catch{return}}async writeCached(e,t,...o){const n=ho(e);let r;try{r=await this.read(n,...o)}catch{r=void 0}r?await this.update(Object.assign(r,fo(t)),...o):await this.create(fo(t),...o)}async deleteCached(e,...t){try{await this.delete(ho(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=>go(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}},e.GraphValueRepository=i.__decorate([s.repository(e.GraphValueModel,n.DefaultFlavour),i.__metadata("design:paramtypes",[Function])],e.GraphValueRepository);class yo{static upstreamNodes(e,t,o=!1){const n=new Set,r=[e];for(;r.length;){const e=r.pop(),a=t.get(e)??[];for(const e of a)!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(),a=t.get(e)??[];for(const e of a)!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 wo{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 bt(`Node '${e}' not found in plan`);if(!this.policy.canPin(o))throw new bt(`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 bt(`Node '${o}' has no completed output to pin`);const a=r.inputs??{},i=this.dependencyFingerprints(t,o,e.result),s=this.createValueKey(e.document.id,n,a,i),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 a=this.createValueKey(e,t,o,n,r),i=await this.store.readCached(a);if(i&&i.pinned){if(i.expiresAt&&new Date(i.expiresAt)<new Date)return;return i}}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)},a=this.stableSerialize(r);return this.simpleHash(a)}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=a=>{if(n.has(a))return;n.add(a);const i=yo.upstreamNodes(a,e.incomingByNode,!1);for(const e of i)t.has(e)&&r(e);o.push(a)};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 a=o.nodeResults[t],i=a?.inputs??{},s=this.dependencyFingerprints(e,t,o);r[t]=this.computeFingerprint(e.workflowId,n,i,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 bo={enabled:!0,strategy:"manual",includeDependencies:!0};function _o(e){return!0===e?.enabled&&"disabled"!==e.strategy}class vo{canPin(e){return _o(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?{...bo,...t}:{...bo,enabled:!1}}}class No{getDependencies(e,t){return yo.upstreamNodes(t,e.incomingByNode,!1)}getPinSet(e,t){const o=this.getDependencies(e,t);return o.add(t),o}}class Io{constructor(){this.local=!0,this.codeMode="hostSide",Xt.register(lt,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 gt("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 gt("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:a}=e,i=a,s=i.frame;if(!s)throw new gt("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 i.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===O.FAILED);if(e?.error)throw new gt(e.error.message,e.error.code??"GRAPH_EXECUTION_ERROR",e.error.details);return s.finish(),await i.emit({type:S.WORKFLOW_COMPLETED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:O.SUCCEEDED,payload:{outputs:d.getWorkflowValues()}}),Ht(s,t,n,O.SUCCEEDED,r.metadata)}catch(e){if(e instanceof Nt)throw s.finish(),e;s.finish();const a=this.toErrorPayload(e);return e instanceof It||!0===r.abortSignal?.aborted?(await i.emit({type:S.WORKFLOW_CANCELLED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:O.CANCELLED,error:a}),Ht(s,t,n,O.CANCELLED,r.metadata)):(await i.emit({type:S.WORKFLOW_FAILED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:O.FAILED,error:a}),Ht(s,t,n,O.FAILED,r.metadata))}}async executeLayer(e,t,o,n,r){const a=Math.max(1,n.concurrency??4),i=[...o];for(;i.length>0;){const o=i.splice(0,a);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 a=new Date,i=[...n.path??[],o.id];await r({type:S.NODE_STARTED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.RUNNING}),this.emitNodeStateChanged(e,t,o,i,k.RUNNING,O.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:O.CACHED,inputs:s,outputs:n.outputs,startedAt:a,finishedAt:d,fromCache:!0,pinned:!0,events:[]};return e.recordNodeResult(l),await r({type:S.NODE_CACHE_HIT,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.CACHED,payload:{outputs:n.outputs}}),await r({type:S.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.SUCCEEDED,payload:{outputs:n.outputs,fromCache:!0}}),void this.emitNodeStateChanged(e,t,o,i,k.SUCCEEDED,O.SUCCEEDED,r)}}try{const d=new Wt(e.runId,n.parentRunId,t.workflowId,t.resolved.document,o.instance,o.manifest,i,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:O.SUCCEEDED,inputs:s,outputs:p,startedAt:a,finishedAt:h,events:[]};e.recordNodeResult(f),await r({type:S.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.SUCCEEDED,payload:{outputs:p}}),this.emitNodeStateChanged(e,t,o,i,k.SUCCEEDED,O.SUCCEEDED,r)}catch(d){if(d instanceof Nt)throw d;const l=new Date,c=this.toErrorPayload(d),u={nodeId:o.id,status:O.FAILED,inputs:s,error:c,startedAt:a,finishedAt:l,events:[]};if(e.recordNodeResult(u),await r({type:S.NODE_FAILED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.FAILED,error:c}),this.emitNodeStateChanged(e,t,o,i,k.FAILED,O.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===dt||e.isDataEdgeActive(t.id))}async skipInactiveNode(e,t,o,n,r){const a=new Date,i=[...n.path??[],o.id];await r({type:S.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.SKIPPED,payload:{reason:"branchNotSelected"}});const s={nodeId:o.id,status:O.SKIPPED,inputs:{},startedAt:a,finishedAt:new Date,events:[]};e.recordNodeResult(s),this.emitNodeStateChanged(e,t,o,i,k.SKIPPED,O.SKIPPED,r)}async executeDisabledNode(e,t,o,n,r){const a=new Date,i=[...n.path??[],o.id],s=po.disabledBehaviorOf(o.instance,t.resolved.document.settings);if(await r({type:S.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.SKIPPED,payload:{disabled:!0,behavior:s}}),"skip"===s){const n={nodeId:o.id,status:O.SKIPPED,inputs:{},startedAt:a,finishedAt:new Date,events:[]};return e.recordNodeResult(n),void this.emitNodeStateChanged(e,t,o,i,k.SKIPPED,O.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",a=n?e.valueStore.getPort(n.sourceNodeId,n.sourcePort):Object.values(d)[0];l={[r]:a}}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:O.SUCCEEDED,inputs:d,outputs:l,startedAt:a,finishedAt:new Date,events:[]};e.recordNodeResult(c),this.emitNodeStateChanged(e,t,o,i,k.SUCCEEDED,O.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 gt(`Node '${e.id}' of kind '${e.kind}' produced unknown output(s): ${r.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,unknownOutputs:r});const a=o.outputs.filter(e=>!0===e.required&&!(e.id in t)).map(e=>e.id);if(a.length>0)throw new gt(`Node '${e.id}' of kind '${e.kind}' did not produce required output(s): ${a.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,missingRequired:a});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??""}:lo(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:""}:lo(o)&&(t[e]={credentialId:o.credentialId,credentialType:o.credentialType})}return t}async resolveNodeInputs(e,t,o,n){const r={},a=(t.incomingByNode.get(o.id)??[]).filter(e=>"data"===e.type),i=new Map;for(const e of a){const t=i.get(e.targetPort)??[];t.push(e),i.set(e.targetPort,t)}for(const[t,o]of i)if(1===o.length)r[t]=e.valueStore.getPort(o[0].sourceNodeId,o[0].sourcePort);else{let n,a=!1;for(const t of o){const o=e.valueStore.getPort(t.sourceNodeId,t.sourcePort);r[t.sourcePort]=o,void 0!==o&&(n=o,a=!0)}a&&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[a,i]of Object.entries(n))r[a]=De(i)?await this.evaluateValueTemplate(i,e,t,o):i;return r}async evaluateValueTemplate(e,t,o,n){const r=this.codeSandboxEvaluator;if(!r)throw new gt(`Value template on node '${t.id}' requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator`,"GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{nodeId:t.id});const a=e.language??("expression"===e.mode?"javascript":"text"),i="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:i,language:"typescript"===a?"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 gt(`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 a=n.metadata;return await r.evaluate({code:t,language:"javascript",input:o,vars:a?.vars??void 0,item:a?.item,index:a?.index,abortSignal:n.abortSignal})}async tryPinnedValue(e,t,o,n){if(!(new vo).shouldUsePinnedValue(o))return;const r=this.createPinningService(e),a=this.computeDependencyFingerprints(e,t,o.id);return r.readPinnedValue(t.workflowId,o,n,a)}computeDependencyFingerprints(e,t,o){const n=this.createPinningService(e),r=(new No).getDependencies(t,o),a={};for(const o of r){const r=t.nodes.find(e=>e.id===o);if(r){const i=e.nodeResults.get(o),s=i?.inputs??{},d=this.computeDependencyFingerprints(e,t,o);a[o]=n.computeFingerprint(t.workflowId,r,s,d)}}return a}routeOutgoingEdges(e,t,o,n,r){const a=(t.outgoingByNode.get(o.id)??[]).filter(e=>"data"===e.type);for(const i of a){if(!Object.prototype.hasOwnProperty.call(n,i.sourcePort))continue;const a=n[i.sourcePort];e.activateDataEdge(i.id),i.targetNodeId===dt&&e.valueStore.setWorkflowOutput(i.targetPort,a),this.emitEdgeStateChanged(e,t,o,i,k.SUCCEEDED,O.SUCCEEDED,r),r({type:S.EDGE_VALUE_ROUTED,runId:e.runId,workflowId:t.workflowId,edgeId:i.id,nodeId:o.id,path:[],payload:{edge:i,value:a}}).catch(()=>{})}}emitNodeStateChanged(e,t,o,n,r,a,i){i({type:S.NODE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:n,status:a,payload:{nodeId:o.id,state:r,runId:e.runId,workflowId:t.workflowId,status:a}}).catch(()=>{})}emitEdgeStateChanged(e,t,o,n,r,a,i){i({type:S.EDGE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,edgeId:n.id,nodeId:o.id,path:[],status:a,payload:{edgeId:n.id,state:r,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,status:a}}).catch(()=>{})}createPinningService(e){const t=mo(e.valueStore.getAdapter()??this.valueAdapter);return new wo(t,new vo,new No)}executionLimits(e){return{maxLoopIterations:e.maxLoopIterations??ct,maxForeachIterations:e.maxForeachIterations??ut}}assertNotAborted(e){if(!0===e.abortSignal?.aborted)throw new It(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 Eo{constructor(e){this.catalogue=e}async resolveNodes(e,t,o,...n){const r=new Map;for(const[a,i]of e.entries()){const e=`nodes[${a}]`;if(this.catalogue.has(i.kind,...n))try{const e=await this.catalogue.resolveManifest(i.kind,i,o,...n),t=this.catalogue.getExecutor(i.kind,...n);r.set(i.id,{instance:i,manifest:e,executor:t})}catch(o){t.push({code:"kind.resolution-failed",path:e+".kind",message:`Node '${i.id}' kind '${i.kind}' failed to resolve: ${o.message}`,nodeId:i.id,details:{kind:i.kind}})}else t.push({code:"kind.unknown",path:e+".kind",message:`Node '${i.id}' references kind '${i.kind}' which is not registered in the backend catalogue`,nodeId:i.id,details:{kind:i.kind}})}return r}validateEffectivePorts(e,t,o,n){const r=!0===t.policies?.allowUndeclaredParameters,a=new Set(t.inputs.map(e=>e.id)),i=new Set(t.outputs.map(e=>e.id));for(const i of Object.keys(e.inputBindings??{}))r||a.has(i)||o.push({code:"binding.unknown-port",path:`${n}.inputBindings.${i}`,message:`Node '${e.id}' input binding '${i}' does not refer to an effective input port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveInputs:[...a]}});for(const a of Object.keys(e.outputBindings??{}))r||i.has(a)||o.push({code:"binding.unknown-port",path:`${n}.outputBindings.${a}`,message:`Node '${e.id}' output binding '${a}' does not refer to an effective output port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveOutputs:[...i]}})}}function Ao(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&&Ao(e,t,`${o}.nodes[${r.id}].loop.body`)}}class Oo{resolveEdges(e,t,o){const n=new Set(e.inputs.map(e=>e.id)),r=new Set(e.outputs.map(e=>e.id)),a=[];for(const[i,s]of(e.edges??[]).entries()){const e=`edges[${i}]`,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),a.push(c)}return a}resolveEndpoint(e,t,o,n,r,a,i){const s=e[t];return ge(s)?("source"===t?n.has(s.port):r.has(s.port))?{nodeId:dt,port:s.port}:void a.push({code:"edge.unknown-port",path:`${i}.${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}}):me(s)?o.get(s.nodeId)?{nodeId:s.nodeId,port:s.port}:void a.push({code:"edge.unknown-node",path:`${i}.${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 a.push({code:"edge.invalid-endpoint",path:`${i}.${t}`,message:`Edge '${e.id}' ${t} endpoint is not a valid GraphEndpoint`,edgeId:e.id})}validateDirectionAndType(e,t,o,n,r,a){let i=!0;const s=t.nodeId===dt?void 0:n.get(t.nodeId),d=o.nodeId===dt?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,a),i=!1),!d||l(d)||this.hasPortDirection(d,o.port,"input")||(this.pushPortIssue(e,"target",o,d,r,a),i=!1);else{if(!s||!d)return r.push({code:"edge.boundary-routing",path:a,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:a,message:`Connection edge '${e.id}' endpoints must both be connection ports`,edgeId:e.id,details:{sourcePort:t.port,targetPort:o.port}}),!1}return i}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,a){const i="source"===t?"output":"input";r.push({code:"data"===e.type?"edge.invalid-direction":"edge.type-mismatch",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} port '${o.port}' on node '${o.nodeId}' is not an ${i} port of kind '${n.manifest.kind}'`,edgeId:e.id,nodeId:o.nodeId,details:{port:o.port,expected:i}})}}class ko{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(":"),a=n.slice(0,o),i=n.slice(o+1),s=e.nodeById.get(a),d=s?.manifest.connections?.find(e=>e.id===i)?.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 '${i}' on node '${a}' accepts at most ${l} connection(s) but has ${r.length}`,nodeId:a,edgeId:r[r.length-1].id,details:{port:i,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),a=r?.manifest.kind;if(!o.allowedNodeKinds?.length||a&&o.allowedNodeKinds.includes(a)||n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${a??"unknown"}' is not in the allowed node kinds of target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{allowedNodeKinds:o.allowedNodeKinds}}),a&&o.blockedNodeKinds?.includes(a)&&n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${a}' 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 xo{constructor(e){this.authorizer=e}async validate(e,t,o,n){const r=this.collectReferences(e,t);for(const a of t.credentials??[]){const i=r.find(e=>void 0===e.credentialType||e.credentialType===a.type);if(i){if(this.checkType(i,a))o.push({code:"credential.type-mismatch",path:n,message:`Node '${e.id}' credential '${i.credentialId}' has type '${i.credentialType}' but kind '${t.kind}' requires '${a.type}'`,nodeId:e.id,details:{credentialType:i.credentialType??"",requiredType:a.type}});else if(this.authorizer){if(!await this.authorizer.hasCredential(i)){o.push({code:"credential.not-found",path:n,message:`Node '${e.id}' references credential '${i.credentialId}' which does not exist`,nodeId:e.id,details:{credentialId:i.credentialId}});continue}await this.authorizer.authorize(i,a)||o.push({code:"credential.unauthorized",path:n,message:`Node '${e.id}' is not authorized to use credential '${i.credentialId}'`,nodeId:e.id,details:{credentialId:i.credentialId}})}}else!1!==a.required&&o.push({code:"credential.missing",path:n,message:`Node '${e.id}' does not provide the required credential of type '${a.type}'`,nodeId:e.id,details:{credentialType:a.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];lo(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))lo(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(uo);for(const[r,a]of Object.entries(e.parameters??{}))this.scanPlainSecretValue(a,[r],e,o+".parameters",n,t);for(const[r,a]of Object.entries(e.metadata??{}))this.scanPlainSecretValue(a,[r],e,o+".metadata",n,t)}scanPlainSecretValue(e,t,o,n,r,a,i=0){const s=t[t.length-1];if(r.has(s))a.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>i&&null!==e)if(Array.isArray(e))for(const s of e)this.scanPlainSecretValue(s,[...t,"[]"],o,n,r,a,i+1);else if("object"==typeof e)for(const[s,d]of Object.entries(e))this.scanPlainSecretValue(d,[...t,s],o,n,r,a,i+1)}}class So extends a.ValidationError{constructor(e,t=[]){super(e),this.issues=t,this.name=So.name}}class Do extends a.ValidationError{constructor(e,t){super(e),this.edgeId=t,this.name=Do.name}}class Ro extends s.AuthorizationError{constructor(e){super(e),this.name=Ro.name}}const Po={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},Co=["node","definition","executor","execute","ports","component"];function To(e){if(!e||"object"!=typeof e)return!1;const t=e;return Re(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 $o(e,t){const o=[];for(const n of Object.keys(e))Co.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 Go{constructor(e){this.options=e,this.parameterValidator=new po,this.edgeValidator=new Oo,this.connectionPolicyValidator=new ko,this.nodeValidator=new Eo(e.catalogue),this.credentialValidator=new xo(e.credentialAuthorizer)}async validateOrThrow(e,...t){const o=await this.validate(e,0,...t);if(!o.valid||!o.resolved)throw new So(`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={...Po,...this.options.limits};if(!await this.validateStructure(e,r,t,n,...o))return{valid:!1,issues:n};const a=await this.nodeValidator.resolveNodes(e.nodes,n,this.options.resolutionContext,...o),i=e.nodes.filter(e=>a.has(e.id)).map(e=>a.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 i)this.parameterValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`,s.get(e.instance.id));for(const e of i)this.nodeValidator.validateEffectivePorts(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);const d=this.edgeValidator.resolveEdges(e,a,n),l=new Map,c=new Map;for(const e of d){if(e.targetNodeId!==dt){const t=l.get(e.targetNodeId)??[];t.push(e),l.set(e.targetNodeId,t)}if(e.sourceNodeId!==dt){const t=c.get(e.sourceNodeId)??[];t.push(e),c.set(e.sourceNodeId,t)}}this.connectionPolicyValidator.validate({edges:d,nodeById:a},n),this.validateAcyclicity(i,d,e,n),Ao(e,n);for(const e of i)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 i)await this.credentialValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);return this.validateCapabilities(i,n),n.length>0?{valid:!1,issues:n}:{valid:!0,issues:n,resolved:{document:e,nodes:i,edges:d,nodeById:a,incomingByNode:l,outgoingByNode:c}}}async validateStructure(e,t,o,n,...r){if(!Re(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"}),!ae(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(...$o(e,"$"));for(const t of[...e.inputs,...e.outputs])n.push(...$o(t,"ports"));for(const t of e.nodes)n.push(...$o(t,`nodes[${t.id}]`));for(const t of e.edges)n.push(...$o(t,`edges[${t.id}]`));this.validateUniqueIds(e,n),this.validateLimits(e,t,o,n);try{ve(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,a]of[["input",e.inputs],["output",e.outputs]]){const e="input"===r?o:n;for(const o of a)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 a=new Set;for(const o of e.edges)a.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}):a.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[a,i]of e){if(!i)continue;const e=await this.validate(i,t+1,...n);for(const t of e.issues)o.push({...t,path:`nodes[${r.id}].${a}.${t.path}`,nodeId:t.nodeId??r.id})}}}validateAcyclicity(e,t,o,n){const r=new Set(e.map(e=>e.instance.id)),a=new Map(e.map(e=>[e.instance.id,0]));for(const e of t)r.has(e.sourceNodeId)&&a.has(e.targetNodeId)&&a.set(e.targetNodeId,(a.get(e.targetNodeId)??0)+1);const i=[...a.entries()].filter(([,e])=>0===e).map(([e])=>e),s=[];for(;i.length>0;){const e=i.shift();s.push(e);for(const o of t){if(o.sourceNodeId!==e)continue;if(!a.has(o.targetNodeId))continue;const t=(a.get(o.targetNodeId)??1)-1;a.set(o.targetNodeId,t),0===t&&i.push(o.targetNodeId)}}if(s.length!==a.size){const e=[...a.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===dt&&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??[])Te(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}))}}}e.GraphExecutionPlanner=class extends s.Service{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"}'`),!To(e))throw new vt("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),a=this.buildPlanEdges(e),i=this.buildIncomingMap(a),s=this.buildOutgoingMap(a),d=this.topologicalLayers(r,a);return{resolved:e,workflowId:e.document.id||e.document.name,nodes:r,edges:a,layers:d,incomingByNode:i,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===dt)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===dt)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!==dt),n=new Set(o.map(e=>e.id)),r=t.filter(e=>n.has(e.sourceNodeId)&&n.has(e.targetNodeId)),a=new Map;for(const e of o)a.set(e.id,0);for(const e of r)a.set(e.targetNodeId,(a.get(e.targetNodeId)??0)+1);const i=[],s=new Set;let d=o.filter(e=>0===(a.get(e.id)??0)),l=0;for(;d.length>0;){const e={index:l++,nodes:d};i.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=(a.get(e.targetNodeId)??1)-1;if(a.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 mt({unplannedNodes:e,workflowId:o[0]?.manifest.kind})}return i}},e.GraphExecutionPlanner=i.__decorate([s.service(),i.__metadata("design:paramtypes",[])],e.GraphExecutionPlanner);const Lo=new Set(["engine","valueAdapter","codeSandboxEvaluator","workflowStore"]);function Mo(e,t){const o={};for(const[n,r]of Object.entries(e??{}))Lo.has(n)&&!t.has(n)||(o[n]=r);return o}class Fo extends s.ClientBasedService{constructor(){super()}async initialize(...t){const o=t[0];if(!o||"object"!=typeof o||!o.registry)return this._config=void 0,this._client=void 0,{config:void 0,client:void 0};const n=o.catalogue??o.registry.catalog,r=o.valueAdapter??s.Adapter.current;if(!r)throw new gt("GraphExecutionEngine requires a Decaf adapter for cached/pinned values: pass `valueAdapter` or configure one via `Adapter.setCurrent(...)`","GRAPH_VALUE_ADAPTER_MISSING");const a=o.backend??Xt.current??new Io,i={registry:o.registry,catalogue:n,planner:o.planner??new e.GraphExecutionPlanner,backend:a,valueAdapter:r,eventEmitter:o.eventEmitter??new At,documentValidator:o.documentValidator??new Go({catalogue:n,limits:o.documentLimits,credentialAuthorizer:o.credentialAuthorizer}),authValidator:new jt({enabled:!0===o.authEnabled,...o.authMatch?{match:o.authMatch}:{}}),...o.codeSandboxEvaluator?{codeSandboxEvaluator:o.codeSandboxEvaluator}:{}};this._config=o,this._client=i;const d=new Set(["engine","valueAdapter"]);o.codeSandboxEvaluator&&d.add("codeSandboxEvaluator"),o.workflowStore&&d.add("workflowStore");const l=Mo(a.config,d);return await a.initialize({...l,valueAdapter:r,...o.codeSandboxEvaluator?{codeSandboxEvaluator:o.codeSandboxEvaluator}:{},...o.workflowStore?{workflowStore:o.workflowStore}:{},engine:this}),await(o.onEngineCreated?.(this)),{config:o,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:a}=(await this.logCtx(n,"execute",!0)).for(this.execute);r.debug(`Executing workflow '${e.id||e.name}'`);const i=this.mergeOptions(o);this.assertNotAborted(i);const s=Vt(Mt(a),i.auth);i.auth=s,i.metadata={...i.metadata??{},...s};const d=i.runId??this.generateRunId();i.runId=d;const l=i.path??[],c=new Ot,u=mo(this.valueAdapter);u.seedWorkflowInputs(this.withWorkflowInputDefaults(e,t));const p=new Kt(this.emitter,c,{runId:d,parentRunId:i.parentRunId,workflowId:e.id||e.name,path:l,engine:this,...this.codeSandboxEvaluator?{codeSandboxEvaluator:this.codeSandboxEvaluator}:{}});await p.emit({type:S.VALIDATION_STARTED,status:O.PLANNING});const h=await this.documentValidator.validate(e,0,a);if(!h.valid||!h.resolved)throw await p.emit({type:S.VALIDATION_FAILED,status:O.FAILED,payload:{issues:h.issues}}),new So(`Graph workflow document '${e.id}' failed validation with ${h.issues.length} issue(s)`,h.issues);await p.emit({type:S.VALIDATION_COMPLETED,status:O.PLANNING,payload:{issues:h.issues.length}}),this.assertNotAborted(i);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 qt(d,f,u,c);return p.bindFrame(g),await p.emit({type:S.WORKFLOW_STARTED,runId:d,parentRunId:i.parentRunId,workflowId:f.workflowId,path:l,status:O.RUNNING,payload:{inputs:t}}),await p.emit({type:S.WORKFLOW_PLANNED,runId:d,parentRunId:i.parentRunId,workflowId:f.workflowId,path:l,status:O.PLANNING,payload:{layers:f.layers.length,nodes:f.nodes.length}}),await this.client.backend.execute({document:e,plan:f,inputs:t,options:i,events:p},...n)}get backend(){return this.client.backend}get backendCapabilities(){return zt(this.client.backend)}async listWorkflows(...e){const t=this.client.backend;if("supported"!==zt(t).workflows.list||"function"!=typeof t.listWorkflows)throw new gt(`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"!==zt(o).workflows.get||"function"!=typeof o.getWorkflow)throw new gt(`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=Xt.getOrFail(e);if("supported"!==zt(o).workflows.list||"function"!=typeof o.listWorkflows)throw new gt(`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=Xt.getOrFail(e);if("supported"!==zt(n).workflows.get||"function"!=typeof n.getWorkflow)throw new gt(`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=ao(e);if(0!==o.length){if("unsupported"===t.codeMode)throw new gt(`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 gt("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,S.NODE_PINNED)}async unpinNode(e){const t=this.createPinningService();await t.unpinNode(e),await this.emitPinningEvent(e.nodeId,S.NODE_UNPINNED)}createPinningService(){const e=mo(this.valueAdapter);return new wo(e,new vo,new No)}async emitPinningEvent(e,t){const o=(new Ot).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:ct,maxForeachIterations:ut,usePinnedValues:!0,writeThroughCache:!1,path:[],metadata:{},...this.defaultOptions,...e}}assertNotAborted(e){if(!0===e.abortSignal?.aborted)throw new It(e.runId??"unknown")}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new gt("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 Vo=new Set(["process","require","module","exports","global","globalThis","Function","eval","fetch","XMLHttpRequest","WebSocket","Worker","Deno","Bun","__dispatch"]);class jo extends s.ClientBasedService{constructor(){super()}async initialize(...e){const t=e[0]??{},o=t&&"object"==typeof t?t:{};return this._config=o,this._client=d,{config:o,client:d}}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 gt("Code sandbox received empty code","GRAPH_CODE_SANDBOX_EMPTY_CODE");const n=((e,t)=>"javascript"===t?e:w.transpileModule(e,{compilerOptions:{target:w.ScriptTarget.ES2022,module:w.ModuleKind.None,strict:!0,noEmitHelpers:!0,importHelpers:!1}}).outputText.replace(/^"use strict";\s*/,""))(o,e.language??"javascript");(e=>{if(e.length>1e5)throw new gt("Code exceeds the maximum length of 100000 characters","GRAPH_CODE_SANDBOX_CODE_TOO_LONG",{length:e.length});let t;try{t=m.parse(`async function __validate() {\n${e}\n}`,{ecmaVersion:"latest",sourceType:"script"})}catch{try{t=m.parse(e,{ecmaVersion:"latest",sourceType:"module"})}catch(t){throw new gt("Code failed to parse: "+t.message,"GRAPH_CODE_SANDBOX_PARSE_ERROR",{code:e,error:t.message})}}y.full(t,e=>{const t=e;if("ImportDeclaration"===t.type)throw new gt("Imports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"import"});if("ExportNamedDeclaration"===t.type||"ExportDefaultDeclaration"===t.type)throw new gt("Exports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"export"});if("Identifier"===t.type&&"string"==typeof t.name&&Vo.has(t.name))throw new gt(`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 gt("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 gt("eval() is not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"eval"})})})(n);const r=!(e=>/\breturn\b[\s;]/.test(e))(n),a=r?n.replace(/[\s;]+$/,""):n,i={$input:e.input??{},$vars:e.vars??{},$item:e.item,$index:e.index,$node:e.nodes??{},$output:void 0},s=Object.keys(i),l=r?`return (${a});`:a,c=`"use strict";\nasync function __userFunction(${s.join(", ")}) {\n${l}\n}\n__userFunction(${s.join(", ")}).then(function(__r) { return JSON.stringify({ v: __r }); });`,u=new d.Isolate({memoryLimit:this.defaultMemoryMb}),p=await u.createContext();try{const t=p.global;e.logger&&await this.injectConsole(p,e.logger);for(const[e,o]of Object.entries(i))await t.set(e,new d.ExternalCopy(void 0===o?null:o).copyInto());let o;try{o=await u.compileScript(c,{filename:"graph-code-node.js"})}catch(e){if(!r)throw new gt("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message});{const e=a,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 u.compileScript(t,{filename:"graph-code-node.js"})}catch(e){throw new gt("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message})}}}const l=e.timeoutMs??this.defaultTimeoutMs;let h;try{h=await this.runBounded(o,p,l,e.abortSignal)}catch(e){if(e instanceof gt)throw e;const t=e.message;if(t.includes("timed out")||t.includes("timeout"))throw new gt(`Code execution timed out after ${l} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:l});if(t.includes("memory")||t.includes("heap"))throw new gt(`Code exceeded the memory limit of ${this.defaultMemoryMb} MB`,"GRAPH_CODE_SANDBOX_MEMORY_LIMIT",{memoryMb:this.defaultMemoryMb});throw new gt("Code execution failed: "+t,"GRAPH_CODE_SANDBOX_RUNTIME_ERROR",{code:n,error:t})}if("string"!=typeof h)throw new gt("Code sandbox returned an unexpected non-string result","GRAPH_CODE_SANDBOX_UNEXPECTED_RESULT",{result:h});return JSON.parse(h).v}finally{p.release(),u.dispose()}}async runBounded(e,t,o,n){const r=e.run(t,{timeout:o,promise:!0});r.catch(()=>{});const a=[r];let i,s;try{return a.push(new Promise((e,t)=>{i=setTimeout(()=>{t(new gt(`Code execution timed out after ${o} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:o}))},o+100)})),n&&a.push(new Promise((e,t)=>{const r=()=>{const e="timeout"===n.reason;t(new gt(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(a)}finally{i&&clearTimeout(i),s?.()}}async injectConsole(e,t){const o=new d.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(" "),a=1===n.length?n[0]:n;switch(e){case"log":case"info":default:t.info(r,a);break;case"warn":t.warn(r,a);break;case"error":t.error(r,a);break;case"debug":case"dir":case"dirxml":case"table":t.debug(r,a);break;case"trace":t.trace(r,a);break;case"group":case"groupCollapsed":t.debug("[group] "+r,a);break;case"groupEnd":t.debug("[groupEnd]",void 0);break;case"time":case"timeEnd":case"timeLog":case"count":case"countReset":t.debug(`[${e}] ${r}`,a);break;case"assert":n[0]||t.error("Assertion failed: "+r,a);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 Uo extends a.InternalError{constructor(e){super(e,Uo.name,500)}}class Bo extends a.NotFoundError{constructor(e){super(e),this.name=Bo.name}}class Wo extends a.NotFoundError{constructor(e){super(e),this.name=Wo.name}}class qo{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 Uo(`Method declaration for kind '${this.kind}' is missing a name`);if(this.declarations.has(e.name))throw new Uo(`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 Uo(`Method implementation '${e}' for kind '${this.kind}' is not a function`);if(!this.declarations.has(e))throw new Uo(`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 Uo(`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 Wo(`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 Ho(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 Ko(e,t,o){const n=Ho(t,e.itemIdPath),r=e.itemLabelPath?Ho(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 zo(e,t){switch(t){case"input":return e.inputs;case"output":return e.outputs;default:return e.connections}}function Xo(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 a=zo(o,n.direction);e.forEach((e,t)=>{const{id:o,label:i}=Ko(n,e,t),s=(d={id:o,index:t,label:i??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?ie(n.defaultPort):{id:s,label:i??s,direction:n.direction};l.id=s,l.direction=n.direction,i&&(l.label=i),a.push(l)})}else if("togglePort"===n.type){if(t[n.parameter]!==n.equals)continue;const e=ie(n.port);if(!r(e.direction,e.id))continue;zo(o,e.direction).push(e)}return o}function Jo(e,t){const o=Xo(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),ie(n)}class Yo{async resolve(e,t,o,n,r){if(o){const a=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)})(a))throw new Uo(`resolveManifest provider for kind '${e}' returned a value that does not conform to GraphResolvedNodeManifest`);if(!ae(a))throw new Uo(`resolveManifest provider for kind '${e}' returned a non-JSON-safe resolved manifest`);const i=ie(a);return!i.namespaces?.length&&t.namespaces?.length&&(i.namespaces=t.namespaces.slice()),i}return Jo(t,n.parameters??{})}}const Qo=["edge","literal","expression"];function Zo(e){return Qo.includes(e)}function en(e,t,o){if("string"!=typeof o||!o)throw new Uo(`Manifest for kind '${e}' has a ${t} with an empty port id`);if(te(o))throw new Uo(`Manifest for kind '${e}' has a ${t} with unsafe port id '${o}'`)}function tn(e){return e}function on(e){if(!e)return;const t={...e.metadata??{},...e.parameters??{},...e.state??{}};return e.loop&&(t.loop=e.loop),t}e.GraphNodeCatalogue=class extends s.Service{constructor(){super(),this.entries=new Map,this.resolver=new Yo,this.fallbackContext=new s.Context}withContext(e){return e[e.length-1]instanceof s.Context?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 Uo("Graph node registration is required");if(!e.manifest||"object"!=typeof e.manifest)throw new Uo("Graph node registration is missing a manifest");if(!e.executor||"function"!=typeof e.executor.execute)throw new Uo(`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 Uo("Graph node manifest kind is required and must be a non-empty string");const a=r.kind;if(this.entries.has(a)&&!t.replace)throw new Uo(`Graph node kind '${a}' is already registered; pass { replace: true } to replace it`);try{$e(r)}catch(e){throw new Uo(`Manifest for kind '${a}' 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(en(e,t+" port",r?.id),o.has(r.id))throw new Uo(`Manifest for kind '${e}' declares duplicate static ${t} port id '${r.id}'`);if(o.add(r.id),void 0!==r.defaultMode&&!Zo(r.defaultMode))throw new Uo(`Manifest for kind '${e}' declares invalid default binding mode '${r.defaultMode+""}' on ${t} port '${r.id}'`)}}})(a,r);const i=((e,t)=>{const o=new Set;for(const n of t.parameters){const t=n?.id;if("string"!=typeof t||!t)throw new Uo(`Manifest for kind '${e}' has a parameter with an empty id`);if(te(t))throw new Uo(`Manifest for kind '${e}' has a parameter with unsafe id '${t}'`);if(o.has(t))throw new Uo(`Manifest for kind '${e}' declares duplicate parameter id '${t}'`);o.add(t)}return o})(a,r);((e,t,o)=>{for(const n of t.dynamicPorts??[]){if(!n||"string"!=typeof n.parameter||!n.parameter)throw new Uo(`Manifest for kind '${e}' has a dynamic-port rule without a parameter reference`);if(!o.has(n.parameter))throw new Uo(`Manifest for kind '${e}' has a dynamic-port rule referencing missing parameter '${n.parameter}'`);if("togglePort"===n.type){if(!n.port)throw new Uo(`Manifest for kind '${e}' has a togglePort rule without a port`);en(e,"togglePort rule port",n.port.id)}if("repeatFromParameter"===n.type&&"string"!=typeof n.portIdTemplate)throw new Uo(`Manifest for kind '${e}' has a repeatFromParameter rule without a portIdTemplate`)}})(a,r,i),((e,t)=>{for(const o of t.credentials??[]){if(!Pe(o))throw new Uo(`Manifest for kind '${e}' has a malformed credential requirement`);if(!o.type)throw new Uo(`Manifest for kind '${e}' has a credential requirement with an empty type`)}})(a,r),((e,t)=>{for(const o of t.methods??[])if(!Le(o))throw new Uo(`Manifest for kind '${e}' has a malformed method declaration`)})(a,r);const s=new qo(a,r.methods??[],e.methods??{});return this.entries.set(a,{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 Uo("Graph executor kind is required");if(!t||"function"!=typeof t.execute)throw new Uo(`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 a={kind:e,display:{name:e},inputs:[],outputs:[],parameters:[],policies:{allowUndeclaredParameters:!0,allowUnknownOutputs:!0}};return this.entries.set(e,{registration:{manifest:a,executor:t},methods:new qo(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 Bo(`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),ie(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,a=[];for(const e of o){if(r&&!r.has(e))continue;const o=this.getManifest(e,...t);n&&!n.has(o.display.category??"")||a.push(o)}return a}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)}},e.GraphNodeCatalogue=i.__decorate([s.service(),i.__metadata("design:paramtypes",[])],e.GraphNodeCatalogue),e.GraphNodeExecutorRegistry=class extends s.Service{constructor(t=new e.GraphNodeCatalogue){super(),this.catalogue=t}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 gt("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 Bo)throw new gt(`No graph executor registered for kind '${e}'`,"GRAPH_EXECUTOR_NOT_FOUND",{kind:e});throw t}}},e.GraphNodeExecutorRegistry=i.__decorate([s.service(),i.__metadata("design:paramtypes",[e.GraphNodeCatalogue])],e.GraphNodeExecutorRegistry),e.GraphNodeExecutorResolver=class extends s.Service{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)}},e.GraphNodeExecutorResolver=i.__decorate([s.service(),i.__metadata("design:paramtypes",[Function,Object])],e.GraphNodeExecutorResolver);class nn extends r.Model{constructor(e){super(),r.Model.fromModel(this,e)}execute(e,t){throw new gt(`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)}}function rn(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+""}}e.BreakFlowNode=class extends nn{execute(e,t){throw new Nt(e.inputs.value)}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.break.fields.value.label",placeholder:"graph.node.flow_control.break.fields.value.placeholder",type:"textarea"}),Y({handle:"value"}),i.__metadata("design:type",Object)],e.BreakFlowNode.prototype,"value",void 0),e.BreakFlowNode=i.__decorate([X("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"}}),r.model()],e.BreakFlowNode),e.ErrorBoundaryFlowNode=class extends nn{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 gt("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"]}),a=Object.values(r.nodeResults).find(e=>e.status===O.FAILED);if(a)throw new gt(a.error?.message??"error boundary try body failed",a.error?.code??"GRAPH_ERROR_BOUNDARY",a.error?.details);return{result:r.outputs.result??r.outputs}}catch(r){let a=r;if(o.catch){const i=await n.execute(o.catch,{...e.inputs,error:rn(r)},{parentRunId:t.runId,path:[...t.path,"catch"]});a=i.outputs.error??i.outputs}return{error:a}}finally{o.finally&&await n.execute(o.finally,e.inputs,{parentRunId:t.runId,path:[...t.path,"finally"]})}}},i.__decorate([r.required(),o.uielement("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"}),Y({handle:"value"}),i.__metadata("design:type",Object)],e.ErrorBoundaryFlowNode.prototype,"value",void 0),i.__decorate([Q({handle:"result"}),i.__metadata("design:type",Object)],e.ErrorBoundaryFlowNode.prototype,"result",void 0),i.__decorate([Q({handle:"error"}),i.__metadata("design:type",Object)],e.ErrorBoundaryFlowNode.prototype,"error",void 0),e.ErrorBoundaryFlowNode=i.__decorate([X("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}}),r.model()],e.ErrorBoundaryFlowNode),e.HumanApprovalFlowNode=class extends nn{execute(e){const t=e.inputs.value??e.inputs;return!1===this.approved?{rejected:t}:{approved:t}}},i.__decorate([r.required(),Y({handle:"value"}),i.__metadata("design:type",Object)],e.HumanApprovalFlowNode.prototype,"value",void 0),i.__decorate([o.uielement("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"}),Y({handle:"message",userControlled:!0}),i.__metadata("design:type",String)],e.HumanApprovalFlowNode.prototype,"message",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.human_approval.fields.approved.label",type:"checkbox"}),Y({handle:"approved",userControlled:!0}),i.__metadata("design:type",Boolean)],e.HumanApprovalFlowNode.prototype,"approved",void 0),i.__decorate([Q({handle:"approved"}),i.__metadata("design:type",Object)],e.HumanApprovalFlowNode.prototype,"approvedOut",void 0),i.__decorate([Q({handle:"rejected"}),i.__metadata("design:type",Object)],e.HumanApprovalFlowNode.prototype,"rejectedOut",void 0),e.HumanApprovalFlowNode=i.__decorate([X("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}}),r.model()],e.HumanApprovalFlowNode),e.IfFlowNode=class extends nn{execute(e,t){const o=e.inputs,n=o.value??o;if(!this.condition)throw new gt("If node has no condition configured","GRAPH_IF_NO_CONDITION",{input:o});if(Yt(this.condition))return Zt(this.condition,o,t).then(e=>this.route(e,n));const r=eo(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 gt("If node condition evaluated to false and the else branch is disabled","GRAPH_IF_ELSE_DISABLED",{condition:this.condition})}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.value.label",placeholder:"graph.node.flow_control.if.fields.value.placeholder",type:"textarea"}),Y({handle:"value"}),i.__metadata("design:type",Object)],e.IfFlowNode.prototype,"value",void 0),i.__decorate([r.required(),Q({handle:"then"}),i.__metadata("design:type",Object)],e.IfFlowNode.prototype,"then",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.condition.label",placeholder:"graph.node.flow_control.if.fields.condition.placeholder",type:"code"}),Y({handle:"condition",userControlled:!0,type:"object"}),i.__metadata("design:type",Object)],e.IfFlowNode.prototype,"condition",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.else.label",type:"checkbox"}),Y({handle:"else",userControlled:!0}),i.__metadata("design:type",Boolean)],e.IfFlowNode.prototype,"else",void 0),e.IfFlowNode=i.__decorate([X("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"}}),r.model()],e.IfFlowNode),e.SwitchFlowNode=class extends nn{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,a=r.value??r,i=((e,t)=>t===e||"object"!=typeof t||null===t||Array.isArray(t)?e:{...t,...e})(r,a);for(const e of n)if(await to(e.condition,{input:r,state:i,label:"switch case"},t))return{[e.outputPort]:a};if(!0!==o.hasDefault)throw new gt("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]:a}}static applyMetadata(e){const t=H(this),o=e.defaultPort??"default",n=!0===e.hasDefault,r=t.ports.filter(t=>!e.cases.some(e=>e.outputPort===t.property)),a=r.filter(e=>e.property!==o),i=r.find(e=>e.property===o),s=[...a,...e.cases.map(e=>({property:e.outputPort,name:e.label,direction:g.OUTPUT,label:e.label,required:!1,hidden:!1,path:e.outputPort}))];return n&&i&&s.push(i),{ports:s,size:_(t,{cases:e.cases.length}),dataPatch:{switchMetadata:e}}}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.value.label",placeholder:"graph.node.flow_control.switch.fields.value.placeholder",type:"textarea"}),Y({handle:"value"}),i.__metadata("design:type",Object)],e.SwitchFlowNode.prototype,"value",void 0),i.__decorate([r.required(),Q({handle:"default"}),i.__metadata("design:type",Object)],e.SwitchFlowNode.prototype,"default",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.cases.label",type:"collection"}),i.__metadata("design:type",Object)],e.SwitchFlowNode.prototype,"cases",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.hasDefault.label",type:"checkbox"}),i.__metadata("design:type",Boolean)],e.SwitchFlowNode.prototype,"hasDefault",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.defaultPort.label",type:"text"}),i.__metadata("design:type",String)],e.SwitchFlowNode.prototype,"defaultPort",void 0),e.SwitchFlowNode=i.__decorate([X("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"}}),r.model()],e.SwitchFlowNode);const an={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},sn=t.LoggedEnvironment.accumulate({graph:{workflows:{limits:{...an},allowAnonymousAccess:!1},execution:{maxCodeTimeoutMs:pt}}});function dn(e,t){const o="number"==typeof t?t:Number(t),n=Number.isFinite(o)&&o>0?o:pt,r="number"==typeof e?e:Number(e);return Number.isFinite(r)&&r>0?Math.min(Math.floor(r),n):1e3}const ln=["javascript","typescript"],cn="javascript";e.CodeInputSchema=class extends r.Model{constructor(){super(...arguments),this.language=cn}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.language.label",type:"select"}),r.option([...ln]),r.type(String),i.__metadata("design:type",String)],e.CodeInputSchema.prototype,"language",void 0),i.__decorate([r.required(),o.uielement("code-editor",{label:"graph.node.utility.code.fields.code.label",placeholder:"graph.node.utility.code.fields.code.placeholder"}),Y({handle:"code"}),i.__metadata("design:type",String)],e.CodeInputSchema.prototype,"code",void 0),i.__decorate([o.hidden(),Y({handle:"data"}),i.__metadata("design:type",Object)],e.CodeInputSchema.prototype,"data",void 0),e.CodeInputSchema=i.__decorate([r.model()],e.CodeInputSchema),e.CodeNode=class extends nn{async execute(e,t){const o=e.inputs,n=this.input,r=o.code??e.parameters?.code??n?.code??this.defaultCode,a=n?.language??cn;if(!r||"string"!=typeof r||0===r.trim().length)throw new yt("Code node has no code to execute (input.code is empty)",{input:o});const i=t.engine?.codeSandboxEvaluator;if(!i)throw new gt("Code node execution requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{code:r});const s=sn.graph.execution?.maxCodeTimeoutMs,d="number"==typeof s&&Number.isFinite(s)&&s>0?s:pt,l=dn(this.timeoutMs,d),c=t.metadata,u={code:r,language:a,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:a,length:r.length,timeoutMs:l});const p=await i.evaluate(u);return await t.log("Code node executed",{hasResult:void 0!==p}),{result:p}}},i.__decorate([r.required(),Y({handle:"input",model:e.CodeInputSchema}),i.__metadata("design:type",e.CodeInputSchema)],e.CodeNode.prototype,"input",void 0),i.__decorate([r.min(1),r.max(pt),o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.timeoutMs.label",type:"number"}),Y({handle:"timeoutMs"}),i.__metadata("design:type",Number)],e.CodeNode.prototype,"timeoutMs",void 0),i.__decorate([o.uielement("code-editor",{label:"graph.node.utility.code.fields.defaultCode.label",placeholder:"graph.node.utility.code.fields.defaultCode.placeholder"}),Y({handle:"defaultCode",userControlled:!0}),i.__metadata("design:type",String)],e.CodeNode.prototype,"defaultCode",void 0),i.__decorate([r.required(),Q({handle:"result"}),i.__metadata("design:type",Object)],e.CodeNode.prototype,"result",void 0),e.CodeNode=i.__decorate([X("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"}}),r.model()],e.CodeNode),e.DelayFlowNode=class extends nn{execute(e){return{value:e.inputs.value??e.inputs}}},i.__decorate([r.required(),Y({handle:"value"}),i.__metadata("design:type",Object)],e.DelayFlowNode.prototype,"value",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.delay.fields.timeoutMs.label",type:"number"}),Y({handle:"timeoutMs"}),i.__metadata("design:type",Number)],e.DelayFlowNode.prototype,"timeoutMs",void 0),i.__decorate([r.required(),Q({handle:"value"}),i.__metadata("design:type",Object)],e.DelayFlowNode.prototype,"valueOut",void 0),e.DelayFlowNode=i.__decorate([X("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"}}),r.model()],e.DelayFlowNode),e.LogFlowNode=class extends nn{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}},i.__decorate([r.required(),Y({handle:"value"}),i.__metadata("design:type",Object)],e.LogFlowNode.prototype,"value",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.message.label",placeholder:"graph.node.utility.log.fields.message.placeholder",type:"textarea"}),Y({handle:"message"}),i.__metadata("design:type",String)],e.LogFlowNode.prototype,"message",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.level.label",placeholder:"graph.node.utility.log.fields.level.placeholder",type:"text"}),Y({handle:"level",userControlled:!0}),i.__metadata("design:type",String)],e.LogFlowNode.prototype,"level",void 0),i.__decorate([r.required(),Q({handle:"value"}),i.__metadata("design:type",Object)],e.LogFlowNode.prototype,"valueOut",void 0),e.LogFlowNode=i.__decorate([X("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"}}),r.model()],e.LogFlowNode),e.MapNode=class extends nn{execute(e){return{result:{mapped:e.inputs.value??e.inputs}}}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.map.fields.value.label",placeholder:"graph.node.utility.map.fields.value.placeholder",type:"textarea"}),Y({handle:"value"}),i.__metadata("design:type",Object)],e.MapNode.prototype,"value",void 0),i.__decorate([r.required(),Q({handle:"result"}),i.__metadata("design:type",Object)],e.MapNode.prototype,"result",void 0),e.MapNode=i.__decorate([X("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:{}}}),r.model()],e.MapNode),e.UtilityLogNode=class extends nn{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}},i.__decorate([r.required(),Y({handle:"value"}),i.__metadata("design:type",Object)],e.UtilityLogNode.prototype,"value",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.message.label",placeholder:"graph.node.utility.utility_log.fields.message.placeholder",type:"textarea"}),Y({handle:"message"}),i.__metadata("design:type",String)],e.UtilityLogNode.prototype,"message",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.level.label",placeholder:"graph.node.utility.utility_log.fields.level.placeholder"}),Y({handle:"level",userControlled:!0,type:"string"}),i.__metadata("design:type",String)],e.UtilityLogNode.prototype,"level",void 0),i.__decorate([r.required(),Q({handle:"value"}),i.__metadata("design:type",Object)],e.UtilityLogNode.prototype,"valueOut",void 0),e.UtilityLogNode=i.__decorate([X("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"}}),r.model()],e.UtilityLogNode),e.ChatTriggerNode=class extends nn{execute(e){return{message:e.inputs.message??null,sessionId:e.inputs.sessionId??null,userId:e.inputs.userId??null}}},i.__decorate([r.required(),Q({handle:"message"}),i.__metadata("design:type",String)],e.ChatTriggerNode.prototype,"message",void 0),i.__decorate([r.required(),Q({handle:"sessionId"}),i.__metadata("design:type",String)],e.ChatTriggerNode.prototype,"sessionId",void 0),i.__decorate([r.required(),Q({handle:"userId"}),i.__metadata("design:type",String)],e.ChatTriggerNode.prototype,"userId",void 0),e.ChatTriggerNode=i.__decorate([X("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"}}}),r.model()],e.ChatTriggerNode),e.EventTriggerNode=class extends nn{execute(e){return{payload:e.inputs.payload??null}}},i.__decorate([r.required(),Q({handle:"payload"}),i.__metadata("design:type",Object)],e.EventTriggerNode.prototype,"payload",void 0),e.EventTriggerNode=i.__decorate([X("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"}}}),r.model()],e.EventTriggerNode),e.FormTriggerNode=class extends nn{execute(e){return{payload:e.inputs.payload??null}}},i.__decorate([r.required(),Y({handle:"schema"}),o.uielement("ngx-decaf-model-builder",{label:"graph.node.trigger.form.fields.schema.label",placeholder:"graph.node.trigger.form.fields.schema.placeholder"}),i.__metadata("design:type",Object)],e.FormTriggerNode.prototype,"schema",void 0),i.__decorate([r.required(),Q({handle:"payload"}),i.__metadata("design:type",Object)],e.FormTriggerNode.prototype,"payload",void 0),e.FormTriggerNode=i.__decorate([X("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:[]}}}),r.model()],e.FormTriggerNode),e.ManualTriggerNode=class extends nn{execute(e){return{payload:e.inputs.payload??null}}},i.__decorate([r.required(),Q({handle:"payload"}),i.__metadata("design:type",Object)],e.ManualTriggerNode.prototype,"payload",void 0),e.ManualTriggerNode=i.__decorate([X("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:{}}}}),r.model()],e.ManualTriggerNode),e.ScheduleTriggerNode=class extends nn{execute(e){return{payload:e.inputs.payload??null}}},i.__decorate([r.required(),Y({handle:"cron"}),o.uielement("app-cron-selector-field",{label:"graph.node.trigger.schedule.fields.cron.label",placeholder:"graph.node.trigger.schedule.fields.cron.placeholder"}),i.__metadata("design:type",String)],e.ScheduleTriggerNode.prototype,"cron",void 0),i.__decorate([r.required(),Q({handle:"payload"}),i.__metadata("design:type",Object)],e.ScheduleTriggerNode.prototype,"payload",void 0),e.ScheduleTriggerNode=i.__decorate([X("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"}}}),r.model()],e.ScheduleTriggerNode),e.WebhookTriggerNode=class extends nn{execute(e){return{payload:e.inputs.payload??null}}},i.__decorate([r.required(),Y({handle:"schema"}),o.uielement("ngx-decaf-model-builder",{label:"graph.node.trigger.webhook.fields.schema.label",placeholder:"graph.node.trigger.webhook.fields.schema.placeholder"}),i.__metadata("design:type",Object)],e.WebhookTriggerNode.prototype,"schema",void 0),i.__decorate([r.required(),Q({handle:"payload"}),i.__metadata("design:type",Object)],e.WebhookTriggerNode.prototype,"payload",void 0),e.WebhookTriggerNode=i.__decorate([X("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"}}}),r.model()],e.WebhookTriggerNode),e.AgentNode=class extends nn{execute(e){return{response:"[Agent response] "+(e.inputs.prompt??""),actions:[]}}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.agent.agent.fields.prompt.label",placeholder:"graph.node.agent.agent.fields.prompt.placeholder",type:"textarea"}),Y({handle:"prompt"}),i.__metadata("design:type",String)],e.AgentNode.prototype,"prompt",void 0),i.__decorate([r.required(),Q({handle:"response"}),i.__metadata("design:type",String)],e.AgentNode.prototype,"response",void 0),i.__decorate([r.required(),Q({handle:"actions"}),i.__metadata("design:type",Array)],e.AgentNode.prototype,"actions",void 0),i.__decorate([Z({category:"model",handle:"model"}),i.__metadata("design:type",Object)],e.AgentNode.prototype,"model",void 0),i.__decorate([Z({category:"memory",handle:"memory"}),i.__metadata("design:type",Object)],e.AgentNode.prototype,"memory",void 0),i.__decorate([Z({category:"workspace",handle:"workspace"}),i.__metadata("design:type",Object)],e.AgentNode.prototype,"workspace",void 0),e.AgentNode=i.__decorate([X("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"}}),r.model()],e.AgentNode);const un=[e.AgentNode];function pn(e,t,o,n){const r=t??o;if(null==e)return Math.min(o,r);const a=Number(e);if(!Number.isFinite(a)||0>=a)throw new yt(n+" loop maxIterations must be a positive finite number");return Math.min(Math.floor(a),r)}function hn(e,t,o){const n=t.node.loop,r=t.metadata?.loop;if(!n?.body&&!r?.body)throw new yt(o+" node is missing loop configuration (instance.loop.body)");const a=t=>{const o=e[t]??n?.[t]??r?.[t],a=Number(o);return void 0!==o&&Number.isFinite(a)?a:void 0},i=t=>{const o=e[t]??r?.[t];return"string"==typeof o?o:void 0};return{body:n?.body??r?.body,maxIterations:a("maxIterations"),timeoutMs:a("timeoutMs"),concurrency:a("concurrency"),condition:e.condition??r?.condition,inputPort:i("inputPort"),outputPort:i("outputPort"),itemPort:i("itemPort"),resultPort:i("resultPort"),statePort:i("statePort"),slice:a("slice")}}e.GraphForeachLoopNode=class extends nn{async execute(e,t){const o=hn(this,t,"foreach"),n=e.inputs,r=n.items,a=pn(o.maxIterations,t.limits?.maxForeachIterations,1e3,"foreach");if(!Array.isArray(r))throw new yt("foreach input 'items' must be an array");const i=t.engine;if(!i)throw new gt("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>a)throw new wt(`foreach exceeded max iterations (${l} > ${a})`);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:S.LOOP_STARTED});for(let e=0;l>e;e++){await t.emit({type:S.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 i.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 Nt){const n=o.details?.value;void 0!==n&&f.push(n),m=!0,await t.emit({type:S.LOOP_ITERATION_COMPLETED,iteration:e,metadata:{broken:!0}});break}throw o}await t.emit({type:S.LOOP_ITERATION_COMPLETED,iteration:e})}await t.emit({type:S.LOOP_COMPLETED,metadata:{broken:m}});const y={results:f,completed:f,iterations:f.length,broken:m};return void 0!==g&&(y[p]=g),y}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.items.label",placeholder:"graph.node.loop.foreach.fields.items.placeholder",type:"textarea"}),Y({handle:"items"}),i.__metadata("design:type",Array)],e.GraphForeachLoopNode.prototype,"items",void 0),i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.slice.label",placeholder:"graph.node.loop.foreach.fields.slice.placeholder",type:"number"}),Y({handle:"slice"}),i.__metadata("design:type",Number)],e.GraphForeachLoopNode.prototype,"slice",void 0),i.__decorate([r.required(),Q({handle:"item"}),i.__metadata("design:type",Object)],e.GraphForeachLoopNode.prototype,"item",void 0),i.__decorate([r.required(),Z({handle:"loop",connectionRules:{allowSelf:!0,maxConnections:1}}),i.__metadata("design:type",Object)],e.GraphForeachLoopNode.prototype,"loop",void 0),i.__decorate([r.required(),Q({handle:"completed"}),i.__metadata("design:type",Array)],e.GraphForeachLoopNode.prototype,"completed",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.maxIterations.label",type:"number"}),Y({handle:"maxIterations",userControlled:!0}),i.__metadata("design:type",Number)],e.GraphForeachLoopNode.prototype,"maxIterations",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.condition.label",type:"code"}),Y({handle:"condition",userControlled:!0}),i.__metadata("design:type",Object)],e.GraphForeachLoopNode.prototype,"condition",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.itemPort.label",type:"text"}),Y({handle:"itemPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphForeachLoopNode.prototype,"itemPort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.resultPort.label",type:"text"}),Y({handle:"resultPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphForeachLoopNode.prototype,"resultPort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.statePort.label",type:"text"}),Y({handle:"statePort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphForeachLoopNode.prototype,"statePort",void 0),e.GraphForeachLoopNode=i.__decorate([X("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}}}),r.model()],e.GraphForeachLoopNode);class fn{constructor(){this.expressionEvaluator=new Jt}evaluate(t,o){if(this.isConditionExpression(t))return this.expressionEvaluator.evaluate(t,o);const n=this.resolveValue(t.left,o),r=t.right;switch(t.type){case e.GraphConditionType.TRUTHY:return!!n;case e.GraphConditionType.FALSY:return!n;case e.GraphConditionType.EQUALS:return n===r;case e.GraphConditionType.NOT_EQUALS:return n!==r;case e.GraphConditionType.GREATER_THAN:return Number(n)>Number(r);case e.GraphConditionType.GREATER_THAN_OR_EQUAL:return Number(n)>=Number(r);case e.GraphConditionType.LESS_THAN:return Number(r)>Number(n);case e.GraphConditionType.LESS_THAN_OR_EQUAL:return Number(r)>=Number(n);case e.GraphConditionType.EXISTS:return null!=n;case e.GraphConditionType.CUSTOM:throw new gt("Custom condition evaluators are not supported in v1","GRAPH_CUSTOM_CONDITION_UNSUPPORTED");default:throw new gt(`Unknown condition type '${t.type}'`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition:t})}}async evaluateAsync(e,t,o,n){return Yt(e)?Zt(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}}function gn(e,t,o,n={}){return{id:e,label:t,direction:o,...n}}function mn(e){const t=e,o=F(t),n=o?.metadata?.title;return et(t,n?{name:n}:{})}e.GraphUntilLoopNode=class extends nn{async execute(e,t){const o=hn(this,t,"until"),n=e.inputs,r=pn(o.maxIterations,t.limits?.maxLoopIterations,100,"until"),a=o.condition;if(!a)throw new yt("until node is missing a condition");const i=o.statePort??"state",s=o.inputPort??i,d=o.outputPort??i,l=o.body,c=t.engine;if(!c)throw new gt("until node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;await t.emit({type:S.LOOP_STARTED});let h=!1;do{if(p>=r)throw await t.emit({type:S.LOOP_LIMIT_REACHED,iteration:p}),new wt(`until loop exceeded max iterations (${r})`);await t.emit({type:S.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:S.LOOP_ITERATION_COMPLETED,iteration:p});const e=await(new fn).evaluateAsync(a,u,t,{...n,state:u});await t.emit({type:S.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:e}}),p++,h=e}while(!h);return await t.emit({type:S.LOOP_COMPLETED}),{state:u,iterations:p}}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.state.label",placeholder:"graph.node.loop.until.fields.state.placeholder",type:"textarea"}),Y({handle:"state"}),i.__metadata("design:type",Object)],e.GraphUntilLoopNode.prototype,"state",void 0),i.__decorate([r.required(),Q({handle:"state"}),i.__metadata("design:type",Object)],e.GraphUntilLoopNode.prototype,"stateOut",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.maxIterations.label",type:"number"}),Y({handle:"maxIterations",userControlled:!0}),i.__metadata("design:type",Number)],e.GraphUntilLoopNode.prototype,"maxIterations",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.condition.label",type:"code"}),Y({handle:"condition",userControlled:!0}),i.__metadata("design:type",Object)],e.GraphUntilLoopNode.prototype,"condition",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.statePort.label",type:"text"}),Y({handle:"statePort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphUntilLoopNode.prototype,"statePort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.inputPort.label",type:"text"}),Y({handle:"inputPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphUntilLoopNode.prototype,"inputPort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.outputPort.label",type:"text"}),Y({handle:"outputPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphUntilLoopNode.prototype,"outputPort",void 0),e.GraphUntilLoopNode=i.__decorate([X("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}}}}),r.model()],e.GraphUntilLoopNode),e.GraphWhileLoopNode=class extends nn{async execute(e,t){const o=hn(this,t,"while"),n=e.inputs,r=pn(o.maxIterations,t.limits?.maxLoopIterations,100,"while"),a=o.condition;if(!a)throw new yt("while node is missing a condition");const i=o.statePort??"state",s=o.inputPort??i,d=o.outputPort??i,l=o.body,c=t.engine;if(!c)throw new gt("while node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;for(await t.emit({type:S.LOOP_STARTED});await(new fn).evaluateAsync(a,u,t,{...n,state:u});){if(p>=r)throw await t.emit({type:S.LOOP_LIMIT_REACHED,iteration:p}),new wt(`while loop exceeded max iterations (${r})`);await t.emit({type:S.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:!0}}),await t.emit({type:S.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:S.LOOP_ITERATION_COMPLETED,iteration:p}),p++}return await t.emit({type:S.LOOP_COMPLETED}),{state:u,iterations:p}}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.state.label",placeholder:"graph.node.loop.while.fields.state.placeholder",type:"textarea"}),Y({handle:"state"}),i.__metadata("design:type",Object)],e.GraphWhileLoopNode.prototype,"state",void 0),i.__decorate([r.required(),Q({handle:"state"}),i.__metadata("design:type",Object)],e.GraphWhileLoopNode.prototype,"stateOut",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.maxIterations.label",type:"number"}),Y({handle:"maxIterations",userControlled:!0}),i.__metadata("design:type",Number)],e.GraphWhileLoopNode.prototype,"maxIterations",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.condition.label",type:"code"}),Y({handle:"condition",userControlled:!0}),i.__metadata("design:type",Object)],e.GraphWhileLoopNode.prototype,"condition",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.statePort.label",type:"text"}),Y({handle:"statePort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphWhileLoopNode.prototype,"statePort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.inputPort.label",type:"text"}),Y({handle:"inputPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphWhileLoopNode.prototype,"inputPort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.outputPort.label",type:"text"}),Y({handle:"outputPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphWhileLoopNode.prototype,"outputPort",void 0),e.GraphWhileLoopNode=i.__decorate([X("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}}}}),r.model()],e.GraphWhileLoopNode),e.GraphInputValueNode=class extends nn{execute(e){const t=e.inputs;return{value:t?.value??null}}},i.__decorate([Q({handle:"value",connectionRules:{allowMultiple:!0}}),i.__metadata("design:type",Object)],e.GraphInputValueNode.prototype,"value",void 0),e.GraphInputValueNode=i.__decorate([X("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"}}),r.model()],e.GraphInputValueNode),e.GraphOutputValueNode=class extends nn{execute(e){return{}}},i.__decorate([r.required(),Y({handle:"value"}),i.__metadata("design:type",Object)],e.GraphOutputValueNode.prototype,"value",void 0),e.GraphOutputValueNode=i.__decorate([X("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"}}),r.model()],e.GraphOutputValueNode);const yn={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:[gn("items","graph.node.loop.foreach.ports.input.items.label","input",{required:!0,schema:{type:"array",items:{type:"any"}}}),gn("slice","graph.node.loop.foreach.ports.input.slice.label","input",{schema:{type:"number",integer:!0,min:1}}),gn("state","graph.node.loop.foreach.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[gn("results","graph.node.loop.foreach.ports.output.results.label","output",{schema:{type:"array",items:{type:"any"}}}),gn("completed","graph.node.loop.foreach.ports.output.completed.label","output",{schema:{type:"array",items:{type:"any"}}}),gn("iterations","graph.node.loop.foreach.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}}),gn("broken","graph.node.loop.foreach.ports.output.broken.label","output",{schema:{type:"boolean"}}),gn("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}]},wn={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:[gn("state","graph.node.loop.while.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[gn("state","graph.node.loop.while.ports.output.state.label","output",{schema:{type:"any"}}),gn("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"}]},bn={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:[gn("state","graph.node.loop.until.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[gn("state","graph.node.loop.until.ports.output.state.label","output",{schema:{type:"any"}}),gn("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"}]},_n=[mn(e.GraphInputValueNode),mn(e.GraphOutputValueNode),mn(e.ManualTriggerNode),mn(e.WebhookTriggerNode),mn(e.ScheduleTriggerNode),mn(e.EventTriggerNode),mn(e.FormTriggerNode),mn(e.ChatTriggerNode),(vn=mn(e.IfFlowNode),{...vn,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"}}}]}))(mn(e.SwitchFlowNode)),mn(e.MapNode),mn(e.DelayFlowNode),mn(e.ErrorBoundaryFlowNode),mn(e.HumanApprovalFlowNode),mn(e.CodeNode),mn(e.LogFlowNode),mn(e.UtilityLogNode),mn(e.BreakFlowNode),mn(e.AgentNode),yn,wn,bn];var vn;const Nn=Object.fromEntries(_n.map(e=>[e.kind,e])),In=[e.ManualTriggerNode,e.WebhookTriggerNode,e.ScheduleTriggerNode,e.EventTriggerNode,e.FormTriggerNode,e.ChatTriggerNode],En=[e.IfFlowNode,e.SwitchFlowNode,e.DelayFlowNode,e.ErrorBoundaryFlowNode,e.HumanApprovalFlowNode,e.LogFlowNode,e.BreakFlowNode],An=[e.CodeNode,e.MapNode,e.UtilityLogNode],On=[e.GraphForeachLoopNode,e.GraphWhileLoopNode,e.GraphUntilLoopNode],kn=[e.GraphInputValueNode,e.GraphOutputValueNode],xn={value:e.GraphInputValueNode,result:e.GraphOutputValueNode,"core.trigger.manual":e.ManualTriggerNode,"core.trigger.webhook":e.WebhookTriggerNode,"core.trigger.schedule":e.ScheduleTriggerNode,"core.trigger.event":e.EventTriggerNode,"core.trigger.form":e.FormTriggerNode,"core.trigger.chat":e.ChatTriggerNode,"core.flow.if":e.IfFlowNode,"core.flow.switch":e.SwitchFlowNode,"core.utility.map":e.MapNode,"core.flow.delay":e.DelayFlowNode,"core.flow.errorBoundary":e.ErrorBoundaryFlowNode,"core.flow.humanApproval":e.HumanApprovalFlowNode,"core.utility.code":e.CodeNode,"core.flow.log":e.LogFlowNode,"core.utility.log":e.UtilityLogNode,"core.flow.break":e.BreakFlowNode,"core.agent":e.AgentNode,"core.loop.foreach":e.GraphForeachLoopNode,"core.loop.while":e.GraphWhileLoopNode,"core.loop.until":e.GraphUntilLoopNode};function Sn(e){return{execute:(t,o)=>e.instantiate({...on(o.node),...t.parameters,...o.node.state??{}}).execute(t,o)}}function Dn(){const e=[];for(const[t,o]of Object.entries(Nn)){const n=xn[t];n&&e.push(tn({manifest:o,executor:Sn(n)}))}return e}const Rn=["node","definition","executor","execute","ports","component"];function Pn(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 Cn(e,t){const o=[];for(const n of Object.keys(e))Rn.includes(n)&&o.push(Pn("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 Tn(e,t){t.push(...Cn(e,"$")),e.inputs.forEach((e,o)=>t.push(...Cn(e,`inputs[${o}]`))),e.outputs.forEach((e,o)=>t.push(...Cn(e,`outputs[${o}]`)));for(const o of e.nodes)t.push(...Cn(o,`nodes[${o.id}]`)),o.loop&&(t.push(...Cn(o.loop,`nodes[${o.id}].loop`)),Tn(o.loop.body,t));for(const o of e.edges)t.push(...Cn(o,`edges[${o.id}]`))}function $n(e,t){const o=[];e.nodes.length>t.maxNodes&&o.push(Pn("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(Pn("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=Gn(e);n>t.maxNestingDepth&&o.push(Pn("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(Pn("document.limit.size","$",`Document serializes to ${r} bytes; at most ${t.maxDocumentBytes} bytes are allowed`,{details:{bytes:r,limit:t.maxDocumentBytes}})),o}function Gn(e,t=0){let o=t;for(const n of e.nodes)n.loop?.body&&(o=Math.max(o,Gn(n.loop.body,t+1)));return o}async function Ln(e,t,...o){const n=[];for(const r of e.nodes)t.has(r.kind,...o)||n.push(Pn("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 Ln(r.loop.body,t,...o));return n}async function Mn(e,t={},...o){const n={...an,...t.limits},r=[];if(!Re(e))return r.push(Pn("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(!ae(e))return r.push(Pn("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};Tn(e,r),r.push(...(e=>{const t=[],o=new Set;for(const n of[...e.inputs,...e.outputs])o.has(n.id)?t.push(Pn("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(Pn("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(Pn("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(...$n(e,n)),Ao(e,r);try{ve(e)}catch(e){const t=e instanceof a.ValidationError?e.message:e+"";r.push(Pn("document.structure","$",t))}return t.catalogue&&r.push(...await Ln(e,t.catalogue,...o)),{valid:0===r.length,issues:r}}function Fn(e,t,o={}){const n=e?.owner??null;return!n||n===t||(null==t||""===t)&&!0===o.allowAnonymousAccess}function Vn(e,t){return(e?.owner??null)===(t??null)}function jn(e,t,o){if(!Vn(e,t))throw new s.ForbiddenError(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function Un(e,t,o){if(!Fn(e,t,o))throw new s.ForbiddenError(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function Bn(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>Bn(e)).join(",")}]`;const t=e;return`{${Object.keys(t).filter(e=>void 0!==t[e]).sort().map(e=>`${JSON.stringify(e)}:${Bn(t[e])}`).join(",")}}`}function Wn(e){return p.createHash("sha256").update(Bn(e)).digest("hex")}function qn(e){return new nt({runId:e.runId,workflowId:e.workflowId,...e.ownerUser?{owner:e.ownerUser}:{},status:e.status,...e.documentFingerprint?{documentFingerprint:e.documentFingerprint}:{},...void 0!==e.result?{result:Hn(e.result)}:{},...e.error?{error:Hn(e.error)}:{},createdAt:new Date(e.createdAt),...e.startedAt?{startedAt:new Date(e.startedAt)}:{},...e.finishedAt?{finishedAt:new Date(e.finishedAt)}:{}})}function Hn(e){if(null!=e)return JSON.parse(JSON.stringify(e))}class Kn{constructor(e,t={}){this.sequences=new Map,this.chains=new Map,this.store=e,this.limits={...D,...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 zn{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={...D,...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 a=this.runExecution({...e},t,o,...n).catch(async t=>{const o=Xn(t);try{await this.emitTerminal({...e},S.WORKFLOW_FAILED,o)}catch{}return await this.finalize({...e},"failed",void 0,o,...n)});return this.completions.set(e.runId,a),a}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 a,i,s=!1;const d=this.engine.observe({refresh:async t=>{t.runId===r&&(t.error&&(a=t.error),P((await this.publisher.publish(this.envelopeOf(e,t))).type)?s=!0:t.type===S.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 a=t,await this.emitTerminal(e,S.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=Xn(t);return a=o,s||(await this.emitTerminal(e,S.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 a=t,s||(await this.emitTerminal(e,S.WORKFLOW_CANCELLED,t),s=!0),await this.finalize(e,"cancelled",void 0,t,...n)}try{i=await this.engine.execute(d,o,{runId:r,abortSignal:this.controllers.get(r)?.signal,metadata:{documentFingerprint:l}},...n)}catch(e){a=Xn(e)}const c=this.abortReason(r);let u,p;return"timeout"===c?(u="failed",p=a??{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=a):i?.status===O.SUCCEEDED?u="succeeded":i?.status===O.CANCELLED?(u="cancelled",p=a):(u="failed",p=a??Xn(new gt(i?`Graph run '${r}' failed`:`Graph run '${r}' failed without a result`,"GRAPH_RUN_FAILED",{runId:r}))),s||await this.emitTerminal(e,"succeeded"===u?S.WORKFLOW_COMPLETED:"cancelled"===u?S.WORKFLOW_CANCELLED:S.WORKFLOW_FAILED,p),await this.finalize(e,u,i,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:re(t.payload)?t.payload:{nonSerializable:!0},error:t.error,parentRunId:t.parentRunId,path:t.path}}}function Xn(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+""}}function Jn(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 Yn(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&Re(e.document)&&!Re(e)}function Qn(e){return JSON.parse(JSON.stringify(e))}function Zn(e){if(null==e)return 0;let t;try{t=e.getTime()}catch{return 0}return Number.isFinite(t)?t:0}e.GraphWorkflowService=class extends s.ModelService{constructor(e){super(rt),this.catalogue=e}get limits(){return{...an,...sn.graph.workflows.limits??{}}}get allowAnonymousAccess(){return!0===sn.graph.workflows.allowAnonymousAccess}async saveDocument(e,t,...o){const{ctx:n,ctxArgs:r}=(await this.logCtx(o,"saveDocument",!0)).for(this.saveDocument);if(!Re(t))throw new a.ValidationError("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.ValidationError(`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 Et(i.issues);const s=Jn(n),d=await this.readExistingForWrite(e,r);d&&this.assertWriteOwnership(e,d,s);const l=new Date;if(d)return d.name=t.name,d.document=Qn(t),d.updatedAt=l,this.update(d,...r);const c=new rt({workflowId:e,name:t.name,document:Qn(t),...s?{owner:s}:{},updatedAt:l});return this.create(c,...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 a.NotFoundError(`No graph workflow found for workflowId '${e}'`);if(this.assertOwnership(e,r,Jn(o)),r.document)return Qn(r.document);throw new a.NotFoundError(`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",s.OrderDirection.ASC,...o),r=Jn(t);return n.filter(e=>Fn(e,r,{allowAnonymousAccess:this.allowAnonymousAccess})).sort((e,t)=>Zn(t.updatedAt)-Zn(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 a.NotFoundError(`No graph workflow found for workflowId '${e}'`);return this.assertOwnership(e,r,Jn(o)),r}async validateDocument(e,...t){const{ctx:o}=(await this.logCtx(t,"validateDocument",!0)).for(this.validateDocument);return await Mn(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(!ae(t))throw new a.ValidationError("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(!Yn(t))throw new a.ValidationError("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=Jn(n),s=await this.readExistingForWrite(e,r);s&&this.assertWriteOwnership(e,s,i);const d=new Date;if(s)return s.snapshot=t,await this.applyCanonicalWrapper(s,t,n),s.updatedAt=d,this.update(s,...r);const l=new rt({workflowId:e,snapshot:t,...i?{owner:i}:{},updatedAt:d});return await this.applyCanonicalWrapper(l,t,n),this.create(l,...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,Jn(o)),t}catch{return null}}async readExistingForWrite(e,t){try{return await this.read(e,...t)}catch(e){if(e instanceof a.NotFoundError)return null;throw e}}assertOwnership(e,t,o){Un(t??null,o??null,{allowAnonymousAccess:this.allowAnonymousAccess,resourceKind:"Graph workflow",resourceId:e})}assertWriteOwnership(e,t,o){jn(t??null,o??null,{resourceKind:"Graph workflow",resourceId:e})}async applyCanonicalWrapper(e,t,o){if(!Yn(t))return;if(t.document.id!==e.workflowId)throw new a.ValidationError(`Document id '${t.document.id}' does not match the workflow id '${e.workflowId}' from the request path`);const n=await Mn(t.document,{limits:this.limits,...this.catalogue?{catalogue:this.catalogue}:{}},o);if(!n.valid)throw new Et(n.issues);e.document=Qn(t.document),e.name=t.document.name}},e.GraphWorkflowService=i.__decorate([s.service(rt),i.__metadata("design:paramtypes",[Function])],e.GraphWorkflowService),e.GraphRunModelService=class extends s.ModelService{constructor(){super(nt)}async saveRun(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"saveRun",!0)).for(this.saveRun),n=qn(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)}},e.GraphRunModelService=i.__decorate([s.service(nt),i.__metadata("design:paramtypes",[])],e.GraphRunModelService),e.ConditionExpressionEvaluator=Jt,e.DEFAULT_GRAPH_WORKFLOW_DOCUMENT_LIMITS=an,e.DEFAULT_GRAPH_WORKFLOW_VALIDATION_LIMITS=Po,e.DEFAULT_PINNING_METADATA=bo,e.GRAPH_AGENT_NODES=un,e.GRAPH_BOUNDARY_NODES=kn,e.GRAPH_BUILT_IN_NODE_CLASSES_BY_KIND=xn,e.GRAPH_BUILT_IN_NODE_MANIFESTS=_n,e.GRAPH_BUILT_IN_NODE_MANIFESTS_BY_KIND=Nn,e.GRAPH_CODE_DEFAULT_LANGUAGE=cn,e.GRAPH_CODE_DEFAULT_TIMEOUT_MS=1e3,e.GRAPH_CODE_LANGUAGES=ln,e.GRAPH_CODE_MAX_TIMEOUT_MS=pt,e.GRAPH_DEFAULT_CONCURRENCY=4,e.GRAPH_DEFAULT_MAX_FOREACH_ITERATIONS=1e3,e.GRAPH_DEFAULT_MAX_LOOP_ITERATIONS=100,e.GRAPH_DOCUMENT_FORBIDDEN_FIELD_KEYS=Co,e.GRAPH_FLOW_CONTROL_NODES=En,e.GRAPH_LOCAL_EXECUTION_BACKEND=lt,e.GRAPH_LOOP_KIND={FOREACH:"core.loop.foreach",WHILE:"core.loop.while",UNTIL:"core.loop.until"},e.GRAPH_LOOP_NODES=On,e.GRAPH_MAX_FOREACH_ITERATIONS=ut,e.GRAPH_MAX_LOOP_ITERATIONS=ct,e.GRAPH_PINNING_METADATA_KEY="graph.pinnable",e.GRAPH_PLAIN_SECRET_KEYS=uo,e.GRAPH_TRIGGER_NODES=In,e.GRAPH_UTILITY_NODES=An,e.GRAPH_WORKFLOW_BOUNDARY=dt,e.GRAPH_WORKFLOW_FORBIDDEN_FIELD_KEYS=Rn,e.GraphAuthValidator=jt,e.GraphBreakSignal=Nt,e.GraphConditionEvaluator=fn,e.GraphConnectionPolicyValidator=ko,e.GraphConnectionValidationError=Do,e.GraphCredentialAuthorizationError=Ro,e.GraphCredentialReferenceValidator=xo,e.GraphCycleError=mt,e.GraphDocumentValidationError=So,e.GraphEdgeInstanceValidator=Oo,e.GraphEngineEventSink=Kt,e.GraphEnvironment=sn,e.GraphExecutionBackendRegistry=Xt,e.GraphExecutionContext=Wt,e.GraphExecutionEngine=Fo,e.GraphExecutionError=gt,e.GraphExecutionEventEmitter=At,e.GraphExecutionEventFactory=Ot,e.GraphExecutionFrame=qt,e.GraphExecutionSnapshotMapper=class{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:O.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}}},e.GraphInputError=yt,e.GraphLoopExecutionContext=class{constructor(e,t){this.iteration=e,this.metadata=t}},e.GraphLoopLimitError=wt,e.GraphNode=nn,e.GraphNodeInstanceValidator=Eo,e.GraphNodeManifestResolver=Yo,e.GraphNodeMethodNotFoundError=Wo,e.GraphNodeMethodRegistry=qo,e.GraphNodeNotFoundError=Bo,e.GraphNodeRegistrationError=Uo,e.GraphParameterValidator=po,e.GraphPinningDependencyResolver=No,e.GraphPinningError=bt,e.GraphPinningPolicy=vo,e.GraphPinningService=wo,e.GraphPortError=class extends gt{constructor(e,t){super(e,"GRAPH_PORT_ERROR",t)}},e.GraphPortSchemaResolver=class{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}}},e.GraphRunCancelledError=It,e.GraphRunEventPublisher=Kn,e.GraphRunExecutor=zn,e.GraphRunService=class{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 Kn(o,n.limits),this.executor=new zn(e,t,this.publisher,{onRunCompleted:n.onRunCompleted},n.limits),this.options={...n,limits:{...D,...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.ValidationError("Graph run request must carry a workflow document with an id or a saved workflowId");if(e.workflowId&&!this.options.documentResolver)throw new a.ValidationError("Graph run requests by workflowId require a document resolver");const i=o??t??"anonymous",s=this.activeByCaller.get(i)??new Set;if(s.size>=this.options.limits.maxConcurrentRuns)throw new a.ValidationError(`Graph run rejected: the configured limit of ${this.options.limits.maxConcurrentRuns} concurrent runs per caller is exhausted`);const d=this.generateRunId(),l={runId:d,workflowId:r,ownerUser:t,status:"queued",createdAt:(new Date).toISOString()};this.executor.begin(d),await this.runStore.saveRun({...l},...n);const c=this.documentProviderFor(e,t);return s.add(d),this.activeByCaller.set(i,s),this.callerKeysByRun.set(d,i),this.executor.schedule(l,c,e.inputs??{},...n).catch(()=>{}).finally(()=>this.finishActiveRun(d)),l}async getRun(e,t,...o){const n=await this.runStore.readRun(e,...o);if(!n)throw new a.NotFoundError(`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=>Fn({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 a.NotFoundError(`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 a.NotFoundError(`No graph run found for runId '${e}'`);this.assertWriteOwnership(r,o);const i=this.engine.backend,s=i.resume;if("function"!=typeof s)throw new gt(`Graph execution backend '${i.constructor?.name??"GraphExecutionBackend"}' does not support resume`,"GRAPH_RESUME_UNSUPPORTED_BACKEND",{runId:e});let d;try{d=await s.call(i,e,t,...n)}catch(e){throw(l=e)instanceof gt?new gt(l.message,l.graphCode):l}var l;const c={...d,runId:e,caller:o};return await this.publisher.publish({runId:e,workflowId:r.workflowId,type:S.WORKFLOW_RESUMED,payload:c}),c}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.ValidationError("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.ValidationError("Graph run request is ambiguous: supply either an unsaved workflow document or a saved workflowId, not both");if(!t&&!o)throw new a.ValidationError("Graph run request must supply either an unsaved workflow document or a saved workflowId");if(t&&!Re(e.workflow))throw new a.ValidationError("Graph run request carries a payload that is not a canonical GraphWorkflowDocument");if(void 0!==e.inputs&&!ae(e.inputs))throw new a.ValidationError("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.ValidationError(`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:Wn(t)})}const o=e.workflowId;return async(...e)=>{const n=this.options.documentResolver;if(!n)throw new a.ValidationError("Graph run requests by workflowId require a document resolver");const r=await n.resolve(o,t,...e);return{document:r,fingerprint:Wn(r)}}}assertOwnership(e,t){Un({owner:e.ownerUser},t,{allowAnonymousAccess:!0===this.options.allowAnonymousAccess,resourceKind:"Graph run",resourceId:e.runId})}assertWriteOwnership(e,t){jn({owner:e.ownerUser},t,{resourceKind:"Graph run",resourceId:e.runId})}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new _t("Cannot generate a graph run id: crypto.randomUUID is unavailable in this runtime",{runtime:typeof globalThis.crypto});return e.randomUUID()}},e.GraphStoreError=_t,e.GraphTopology=yo,e.GraphTopologyError=vt,e.GraphValueValidator=class{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 yt(`Missing required ${o} port '${n.name}'`);if(e&&!this.resolver.resolve(n).validate(t[n.name]))throw new yt(`Invalid value for ${o} port '${n.name}'`)}}},e.GraphWorkflowDocumentRejectedError=Et,e.GraphWorkflowDocumentValidator=Go,e.InMemoryGraphRunEventStore=class{constructor(e={}){this.events=new Map,this.listeners=new Map,this.limits={...D,...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=>!P(e.type));if(-1===t)break;e.splice(t,1)}}},e.InMemoryGraphRunStore=class{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=>qn(e))}release(e){this.runs.delete(e)}},e.IsolatedVmCodeSandboxEvaluator=jo,e.LocalGraphExecutionBackend=Io,e.assertGraphResourceOwnership=Un,e.assertGraphResourceWriteOwnership=jn,e.buildGraphExecutionResult=Ht,e.builtInGraphNodeRegistrations=Dn,e.canAccessGraphResource=Fn,e.canAccessGraphResourcePayload=Vn,e.checkGraphValueAgainstSchema=io,e.clampGraphCodeTimeoutMs=dn,e.collectLooseNodeIssues=Ao,e.composeGraphNamespace=xt,e.createGraphValueRepository=mo,e.declaredGraphNodeMethods=e=>e.methods??[],e.decomposeGraphNamespace=kt,e.decomposeGraphNamespaces=Ft,e.defineGraphNode=tn,e.detectGraphCodeModeSurfaces=ao,e.evaluateCodeCondition=Zt,e.evaluateCondition=to,e.evaluateConditionSync=eo,e.findMalformedGraphNamespaces=Ct,e.findUngrantedGraphNamespaces=Pt,e.graphAuthDataFromRecord=Lt,e.graphAuthDataOf=Mt,e.graphDocumentHasCodeMode=e=>ao(e).length>0,e.graphNamespaceCovers=Rt,e.graphNamespacePartsOf=Dt,e.graphNodeConfig=on,e.graphRolesFromNamespaces=Tt,e.graphRunDocumentFingerprint=Wn,e.graphWorkflowOwnerOf=Jn,e.isCodeCondition=Yt,e.isConditionExpression=Qt,e.isGraphCredentialReferenceLike=lo,e.isGraphNamespaceCacheEntryValid=St,e.isGraphResolvedWorkflow=To,e.isPinnable=_o,e.mergeGraphAuthData=Vt,e.registerBuiltInGraphNodes=(e,...t)=>{for(const o of Dn())e.register(o,{},...t);return e},e.resolveGraphBackendCapabilities=zt,e.resolveGraphDynamicPorts=Xo,e.resolveGraphNodeManifest=Jo,e.serializeGraphValueKey=ho,e.stripFacadeOwnedBackendConfig=Mo,e.validateGraphWorkflowDocumentAtBoundary=Mn},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/logging"),require("@decaf-ts/ui-decorators"),require("@decaf-ts/decoration"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/db-decorators"),require("tslib"),require("@decaf-ts/core"),require("isolated-vm"),require("acorn"),require("acorn-walk"),require("typescript"),require("node:crypto")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/logging","@decaf-ts/ui-decorators","@decaf-ts/decoration","@decaf-ts/decorator-validation","@decaf-ts/db-decorators","tslib","@decaf-ts/core","isolated-vm","acorn","acorn-walk","typescript","node:crypto"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["as-graph"]={},e.decafTsLogging,e.decafTsUiDecorators,e.decafTsDecoration,e.decafTsDecoratorValidation,e.decafTsDbDecorators,e.tslib,e.decafTsCore,e.isolatedVm,e.acorn,e.acornWalk,e.typescript,e.node_crypto);
|
|
1
|
+
var e,t;e=this,t=function(e,t,o,n,r,a,i,s,d,l,c,u,p){"use strict";function h(e){var t=Object.create(null);return e&&Object.keys(e).forEach(o=>{if("default"!==o){var n=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(t,o,n.get?n:{enumerable:!0,get:()=>e[o]})}}),t.default=e,Object.freeze(t)}var f,g,m=h(l),y=h(c),w=h(u);r.ValidationKeys.REQUIRED,r.ValidationKeys.MIN,r.ValidationKeys.MIN_LENGTH,r.ValidationKeys.MAX,r.ValidationKeys.MAX_LENGTH,r.ValidationKeys.PATTERN,r.ValidationKeys.URL,r.ValidationKeys.STEP,r.ValidationKeys.DATE,r.ValidationKeys.EMAIL,r.ValidationKeys.PASSWORD,r.ValidationKeys.EQUALS,r.ValidationKeys.DIFF,r.ValidationKeys.LESS_THAN,r.ValidationKeys.LESS_THAN_OR_EQUAL,r.ValidationKeys.GREATER_THAN,r.ValidationKeys.GREATER_THAN_OR_EQUAL,(e=>{e.GRAPH="graph",e.NODE="graph.node",e.EDGE="graph.edge",e.PORT="graph.port",e.STATE="graph.state"})(f||(f={})),(e=>{e.INPUT="input",e.OUTPUT="output",e.CONNECTION="connection"})(g||(g={}));const _={};function b(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 v(e,t){_[e]=t}function N(e,t,o){const n=t?_[t]:void 0;return n?.color?n.color:e||"#64748b"}function E(e,t,o){const n=t?_[t]:void 0;return n?.icon?n.icon:e||"ti-pointer"}const I=["skip","passThroughFirstInput","emitDefaults"];function A(e){return I.includes(e)}var O,k,x,S;(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"})(O||(O={})),(e=>{e.IDLE="idle",e.RUNNING="running",e.BLOCKED="blocked",e.SUCCEEDED="succeeded",e.FAILED="failed",e.SKIPPED="skipped"})(k||(k={})),(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"})(x||(x={})),(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"})(S||(S={}));const D={maxRequestBytes:4e6,maxConcurrentRuns:32,maxEventsPerRun:1e4,maxEventPayloadBytes:256e3,executionTimeoutMs:6e5,eventReplayWindowMs:3e5},R=[S.WORKFLOW_COMPLETED,S.WORKFLOW_FAILED,S.WORKFLOW_CANCELLED];function P(e){return R.includes(e)}function C(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function T(e){const t=n.Metadata.constr(e);if("function"==typeof t)return t;const o=e.constructor;return"function"==typeof o?o:e}function $(e){if(null!=e)return"string"==typeof e?e:e+""}function G(e,t,o){return $(e?.props?.label??e?.props?.name)??$(t?.name)??o??""}function L(e,t,o){const a=V(e,t);if(a?.model&&"function"==typeof a.model&&r.Model.isModel(a.model))return a.model;const i=n.Metadata.type(e,t);if("function"==typeof i&&r.Model.isModel(i))return i;const s=n.Metadata.getPropDesignTypes?.(e,t)?.designTypes||[];for(const e of s)if("function"==typeof e&&r.Model.isModel(e))return e;const d=o?.[r.ValidationKeys.TYPE]?.customTypes||[];for(const e of d)if("function"==typeof e&&r.Model.isModel(e))return e}function M(e,t){const o=[t,e.path??e.property].filter(Boolean).join(".");return{...e,path:o,children:e.children?.map(e=>M(e,o))}}function F(e){const t=T(e);return n.Metadata.get(t,f.NODE)}function V(e,t){const o=T(e);return n.Metadata.get(o,n.Metadata.key(f.PORT,t+""))}function j(e,t,o,r=new Set){const a=V(e,t);if(!a?.schema)return;const i=L(e,t,n.Metadata.validationFor(e,t));if(!i)return;if(r.has(i))return[];const s=new Set(r);return s.add(e),s.add(i),W(i,s).filter(e=>e.direction===o)}function U(e,t,o=new Set){const a=V(e,t);if(!a)return;const i=n.Metadata.validationFor(e,t),s=L(e,t,i);if(a.schema&&s)return;const d=r.Model.uiElementOf(e,t)||void 0,l=r.Model.uiDecorationOf(e,t,"uiprop"),c=n.Metadata.type(e,t),u=$(a.type??i?.[r.ValidationKeys.TYPE]?.customTypes?.[0]?.name??d?.props?.type??l?.type??c?.name),p=(a.expand||s&&!o.has(s))&&s?(()=>{const n=new Set(o);return n.add(e),n.add(s),W(s,n).map(e=>M(e,t))})():void 0;return{property:t,path:t,direction:a.direction,name:t,label:G(d,l,t),type:u?.toLowerCase(),required:!!i?.[r.ValidationKeys.REQUIRED],hidden:!!r.Model.uiIsHidden(e,t),designType:c?.name,element:d,prop:l,validation:i,graph:a,connectionRules:a.connectionRules,composite:!!p?.length,children:p,model:s?.name}}function B(e){return W(T(e))}function W(e,t=new Set){const o=n.Metadata.properties(e)||[],r=[];for(const n of o){const o=n+"",a=V(e,o);if(a?.schema){const n=j(e,o,a.direction,t);if(n){r.push(...n);continue}}const i=U(e,o,t);i&&r.push(i)}return r}function q(e){return e.flatMap(e=>e.children&&e.children.length?q(e.children):[e])}function H(e){const t=T(e),o=r.Model.uiModelOf(t),a=F(t)||{},i=o?.tag||t.name,s=B(t),d=((e,t)=>{const o=t.portGroups||[],r=new Map(o.map(e=>[e.property,e])),a=[],i=n.Metadata.properties(e)||[];for(const t of i){const o=t+"",i=V(e,o);if(!i?.schema)continue;if(!L(e,o,n.Metadata.validationFor(e,o)))continue;const s=r.get(o);a.push(s?{...s,toggle:s.toggle??"all"}:{property:o,toggle:"all"})}for(const e of o)a.some(t=>t.property===e.property)||a.push(e);return a.length?a:void 0})(t,a),l=a.namespaces?.length?a.namespaces:(e=>{if(null==e)return[];let t,o=e;try{o=n.Metadata.constr(e)}catch{o=e}try{t=n.Metadata.get(o,"auth-namespace")}catch{t=void 0}return C(t)??[]})(t),c=l.length?l:void 0;return{name:t.name,tag:i,kind:a.kind||i,category:a.category,color:a.color,effectiveColor:N(a.color,a.category),group:a.group,height:a.height,icon:a.icon,effectiveIcon:E(a.icon,a.category),labels:a.labels||[],maxChildren:a.maxChildren,minWidth:a.minWidth,width:a.width,shape:a.shape,cornerRadius:a.cornerRadius,sizeRules:a.sizeRules,props:o?.props,ui:o,graph:a,ports:s,portGroups:d,namespaces:c}}const K=new Set,z=new Set;function X(e,t,r){return n.Decoration.for(f.NODE).define({decorator:(e,t,r)=>{const a={kind:t?.kind||e,...t};return t=>{const i=n.apply(o.uimodel(e,r),n.metadata(f.NODE,a))(t);var s;return s=t,K.add(s),i}},args:[e,t,r]}).apply()}function J(e,t){return n.Decoration.for(f.PORT).define({decorator:(e,t)=>(o,r)=>{const a={direction:e,...t};return n.apply(n.propMetadata(n.Metadata.key(f.PORT,r),a))(o,r)},args:[e,t]}).apply()}function Y(e){return J(g.INPUT,{...e,schema:!0})}function Q(e){return J(g.OUTPUT,{...e,schema:!0})}function Z(e){return J(g.CONNECTION,e)}o.RenderingEngine.prototype.renderAsNode=(e,t,...o)=>H(e),n.Metadata.nodes=(()=>[...K]).bind(n.Metadata),n.Metadata.workflows=(()=>[...z]).bind(n.Metadata);const ee=["__proto__","prototype","constructor"];function te(e){return ee.includes(e)}function oe(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function ne(e){return null===e||"string"==typeof e||"number"==typeof e&&Number.isFinite(e)||"boolean"==typeof e}function re(e){return!!ne(e)||(Array.isArray(e)?e.every(e=>re(e)):!!oe(e)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&!te(t)&&re(e[t])))}function ae(e){if(void 0===e)return!1;if("number"==typeof e)return Number.isFinite(e);if("function"==typeof e)return!1;if(re(e))return!0;if(Array.isArray(e))return e.every(e=>ae(e));if(oe(e)){const t=Reflect.ownKeys(e);for(const o of t){if("string"!=typeof o)return!1;if(te(o))return!1;if(!ae(e[o]))return!1}return!0}return!1}function ie(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>ie(e));const t={};for(const[o,n]of Object.entries(e))t[o]=ie(n);return t}const se={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"},de={date:"date",datetime:"date-time","date-time":"date-time",duration:"duration"};function le(e){return e?se[e.toLowerCase()]??"any":"any"}function ce(e,t){const o=e[t];if(o&&"object"==typeof o)return o.value}function ue(e,t){const o=ce(e,t);return"number"==typeof o&&Number.isFinite(o)?o:void 0}function pe(e,t,o){const n=e??{},a=(e=>{const t=ce(e,r.ValidationKeys.ENUM);if(Array.isArray(t)&&t.every(ne))return t})(n);if(a)return{type:"enum",values:a};const i=(e=>{const t=e[r.ValidationKeys.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(le(e)){case"string":{const t=(e=>{if(e)return de[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=ue(t,r.ValidationKeys.MIN),a=ue(t,r.ValidationKeys.MAX);return void 0!==n&&(o.min=n),void 0!==a&&(o.max=a),o}case"boolean":return{type:"boolean"};case"array":return((e,t)=>{const o={type:"array",items:he(e,t)},n=ue(e,r.ValidationKeys.MIN),a=ue(e,r.ValidationKeys.MAX);return void 0!==n&&(o.minItems=n),void 0!==a&&(o.maxItems=a),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 he(e,t){if((e=>{const t=e[r.ValidationKeys.LIST];return!!t?.clazz?.length})(e))return{type:"model",name:fe(e)};const o=ce(e,r.ValidationKeys.TYPE);if("string"==typeof o){const e=le(o);return"model"===e?{type:"model",name:o}:{type:e}}if(t&&"array"!==t){const e=le(t);return"model"===e?{type:"model",name:t}:{type:e}}return{type:"any"}}function fe(e){const t=e[r.ValidationKeys.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 ge(e){return"workflow"===e.scope}function me(e){return"node"===e.scope}function ye(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 we(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&&re(t)}return"expression"===t&&2===Object.keys(e).length&&"string"==typeof e.expression}const _e=["any","string","number","boolean","array","object","enum","model"];function be(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&(e=>_e.includes(e))(e.type)}function ve(e,t={seen:[]}){if(t.seen.includes(e))throw new a.ValidationError(`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.ValidationError("Document 'id' is required and must be a non-empty string");if("string"!=typeof e.name||!e.name)throw new a.ValidationError("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.ValidationError("Workflow port 'id' is required and must be a non-empty string");if(o.has(t.id))throw new a.ValidationError(`Workflow port '${t.id}' is declared more than once; workflow port ids must be unique`);if(void 0!==t.schema&&!be(t.schema))throw new a.ValidationError(`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)Ne(t,r);for(const t of e.nodes)t.loop&&Ee(t,t.loop,n),t.errorBoundary&&Ie(t,t.errorBoundary,n);const i=new Set;for(const t of e.edges)Oe(t,i);for(const t of e.edges)ke(t.source,0,o,r,`Edge '${t.id}' source`),ke(t.target,0,o,r,`Edge '${t.id}' target`);if(void 0!==e.settings&&!ae(e.settings))throw new a.ValidationError("Document settings must be JSON-safe (a map of JSON-safe values)");if(void 0!==e.metadata&&!ae(e.metadata))throw new a.ValidationError("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&&!ae(e.ui))throw new a.ValidationError("Document ui must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed")}function Ne(e,t){if("string"!=typeof e.id||!e.id)throw new a.ValidationError("Node 'id' is required and must be a non-empty string");if(t.has(e.id))throw new a.ValidationError(`Node id '${e.id}' is declared more than once; node ids must be unique`);if("string"!=typeof e.kind||!e.kind)throw new a.ValidationError(`Node '${e.id}' must declare a non-empty string 'kind'`);if(void 0===e.parameters||null===e.parameters)throw new a.ValidationError(`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(te(t))throw new a.ValidationError(`Node '${e.id}' input binding key '${t}' is not allowed (unsafe prototype-pollutant key)`);if(!we(o))throw new a.ValidationError(`Node '${e.id}' input binding for '${t}' must be a valid GraphInputBinding (edge, literal, or expression)`);if("literal"===o.mode&&!ae(o.value))throw new a.ValidationError(`Node '${e.id}' literal binding for '${t}' must contain JSON-safe values`);if("expression"===o.mode&&!o.expression)throw new a.ValidationError(`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(te(t))throw new a.ValidationError(`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.ValidationError(`Node '${e.id}' output binding for '${t}' must be an object with enabled and alias settings`)}if(!ae(e.parameters))throw new a.ValidationError(`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.ValidationError(`Node '${e.id}' state must be an object when present`);if(!ae(e.state))throw new a.ValidationError(`Node '${e.id}' state must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`)}}function Ee(e,t,o){if(!t.body||"object"!=typeof t.body)throw new a.ValidationError(`Node '${e.id}' loop configuration requires a body document`);if(ve(t.body,o),!(void 0===t.maxIterations||Number.isFinite(t.maxIterations)&&t.maxIterations>0))throw new a.ValidationError(`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.ValidationError(`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.ValidationError(`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(te(t))throw new a.ValidationError(`Node '${e.id}' loop mapping key '${t}' is not allowed (unsafe prototype-pollutant key)`);Ae(n,e.id,t)}}function Ie(e,t,o){if(!t.try||"object"!=typeof t.try)throw new a.ValidationError(`Node '${e.id}' error-boundary configuration requires a try body document`);ve(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.ValidationError(`Node '${e.id}' error-boundary ${n} body must be a document`);ve(r,o)}}function Ae(e,t,o){if(!e||"object"!=typeof e)throw new a.ValidationError(`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.ValidationError(`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.ValidationError(`Node '${t}' loop mapping '${o}' referencing a node must reference a node id and a port`);break;case"literal":if(!ae(e.value))throw new a.ValidationError(`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.ValidationError(`Node '${t}' loop mapping '${o}' expression references must be non-empty expressions`);break;default:throw new a.ValidationError(`Node '${t}' loop mapping '${o}' must use a workflow, node, literal, or expression reference source`)}}function Oe(e,t){if("string"!=typeof e.id||!e.id)throw new a.ValidationError("Edge 'id' is required and must be a non-empty string");if(t.has(e.id))throw new a.ValidationError(`Edge id '${e.id}' is declared more than once; edge ids must be unique`);if(!ye(e.source))throw new a.ValidationError(`Edge '${e.id}' source endpoint is not a valid GraphEndpoint`);if(!ye(e.target))throw new a.ValidationError(`Edge '${e.id}' target endpoint is not a valid GraphEndpoint`);if("data"!==e.type&&"connection"!==e.type)throw new a.ValidationError(`Edge '${e.id}' type '${e.type+""}' is not a valid edge type (data or connection are allowed)`);if(t.add(e.id),!ae(e))throw new a.ValidationError(`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 ke(e,t,o,n,r){if(ge(e)){if(!o.has(e.port))throw new a.ValidationError(`${r} references workflow port '${e.port}' which is not declared on the document`)}else if(me(e)){if(!n.has(e.nodeId))throw new a.ValidationError(`${r} references node '${e.nodeId}' which is not part of the document`);if("string"!=typeof e.port||!e.port)throw new a.ValidationError(r+" node endpoints must reference a non-empty port identifier")}}const xe=["expression","template"],Se=["javascript","typescript","json","text"];function De(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return!(!(e=>xe.includes(e))(t.mode)||"string"!=typeof t.expression||!t.expression||void 0!==t.language&&!(e=>Se.includes(e))(t.language)||void 0!==t.metadata&&!re(t.metadata))}function Re(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 Pe(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 Ce=["trigger","loop","branching","stateful","retryable","cancellable","parallel","resource"];function Te(e){return Ce.includes(e)}function $e(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 Ge(e){if(!$e(e))throw new a.ValidationError("Graph node manifest does not conform to the required shape");if(!ae(e))throw new a.ValidationError("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 Le(e){return Ge(e),ie(e)}function Me(e){if(!$e(e))throw new a.ValidationError("Serialized graph node manifest does not conform to the required shape");return ie(e)}const Fe=["loadOptions","listSearch","resourceLocator","resourceMapping","validateParameter","action"];function Ve(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.name&&(e=>Fe.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 je(e){const t=e.element?.props?.value,o=t??e.prop?.value??e.validation?.defaultValue;if(void 0!==o&&"function"!=typeof o&&ae(o))try{return JSON.parse(JSON.stringify(o))}catch{return}}function Ue(e){if(e.type&&e.type in de)return{type:"string",format:de[e.type]};const t=(e=>{for(const t of[e.graph?.type,e.element?.props?.type,e.prop?.type])if("string"==typeof t&&"any"!==le(t))return t})(e);return t?pe((e=>{if(!e)return;const t=Object.entries(e).filter(([e])=>e!==r.ValidationKeys.TYPE);return Object.fromEntries(t)})(e.validation),t):pe(e.validation,e.type,e.model)}function Be(e){const t={};for(const[o,n]of Object.entries(e.graph?.metadata??{}))ae(n)&&(t[o]=JSON.parse(JSON.stringify(n)));return Object.keys(t).length?t:void 0}function We(e){switch(e){case"output":return"output";case"connection":return"connection";default:return"input"}}function qe(e){const t=e.graph?.handle;return"connection"!==e.direction&&"string"==typeof t&&t?t:e.path??e.property}function He(e,t){const o={id:qe(e),label:e.label,direction:We(e.direction),schema:Ue(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 a=ot(e.graph?.connectionRules)??t;a&&(o.connectionPolicy=a);const i=(e=>{const t=e.element;if(!t||!ae(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)?ie(n):{}}})(e);i&&(o.element=i);const s=Be(e);return s&&(o.metadata=s),o}function Ke(e){const t={type:"string",id:qe(e),label:e.label,required:e.required};if(e.hidden)return((e,t)=>{const o={...t,type:"hidden"},n=je(e);return void 0!==n&&(o.defaultValue=n),ze(o)})(e,t);const o=je(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=Be(e);if(r&&(t.metadata=r),(e=>{const t=Ye(e);return"code"===t||"code-editor"===t})(e))return ze({...t,type:"code",language:et(e)});const a=Ue(e);switch(a.type){case"number":{const o={...t,type:"number",integer:a.integer,min:a.min,max:a.max},n=Je(e.validation?.step);return void 0!==n&&(o.step=n),ze(o)}case"boolean":return ze({...t,type:"boolean"});case"enum":return ze({...t,type:"options",options:a.values.map(e=>({value:e,label:e+""}))});case"array":{const e={...t,type:"collection"};return void 0!==a.maxItems&&(e.maxItems=a.maxItems),ze(e)}case"object":case"model":return ze({...t,type:"object"});default:return ze({...t,type:"string",multiline:!!Qe(e)||void 0,pattern:Xe(e.validation?.pattern),minLength:Je(e.validation?.minlength),maxLength:Je(e.validation?.maxlength)})}}function ze(e){const t=e;for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return e}function Xe(e){const t=e?.value;return"string"==typeof t?t:void 0}function Je(e){const t=e?.value;return"number"==typeof t&&Number.isFinite(t)?t:void 0}function Ye(e){const t=e.element?.tag;return"string"==typeof t&&t?t:void 0}function Qe(e){return"textarea"===Ye(e)||"textarea"===(e=>{const t=e.element?.props?.type;return"string"==typeof t?t:void 0})(e)}const Ze=["javascript","typescript","json","text"];function et(e){const t=e.element?.props?.language;return"string"==typeof t&&Ze.includes(t)?t:"javascript"}function tt(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 a=((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 a&&(o.icon=a),"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 ot(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 a=t.maxConnections;return"number"==typeof a&&Number.isFinite(a)&&(o.maxConnections=a),Object.keys(o).length?o:void 0}function nt(e,t={}){const o="function"==typeof e?e:e.constructor;if(!F(o))throw new a.ValidationError(`Node '${o?.name??e+""}' is not decorated with @node and cannot produce a manifest`);const n=H(o),r=q(B(o)),i=[],s=[],d=[],l=[],c=ot(n.graph?.connectionRules);for(const e of r)("connection"===e.direction?d:"output"===e.direction?s:i).push(He(e,c)),"input"===e.direction&&l.push(Ke(e));const u={kind:t.kind??n.kind??n.name,display:tt(n,t),inputs:i,outputs:s,parameters:l};return d.length&&(u.connections=d),n.namespaces?.length&&(u.namespaces=n.namespaces.slice()),Ge(u),u}var rt,at;(e=>{e.READABILITY="readability",e.COMPACTNESS="compactness",e.BALANCED="balanced"})(rt||(rt={})),(e=>{e.TIGHT="tight",e.NORMAL="normal",e.COMFORTABLE="comfortable"})(at||(at={})),at.TIGHT,at.NORMAL,at.COMFORTABLE,rt.READABILITY,at.COMFORTABLE,rt.COMPACTNESS,at.TIGHT,rt.BALANCED,at.NORMAL;let it=class extends s.BaseModel{constructor(e){super(e)}};i.__decorate([s.pk({type:String,generated:!1}),n.description("Unique graph run id"),o.uielement("ngx-decaf-crud-field",{label:"graph.run.id.label",readonly:!0}),i.__metadata("design:type",String)],it.prototype,"runId",void 0),i.__decorate([s.column(),r.required(),s.index(),n.description("Workflow document id the run executes"),o.uilistprop("workflowId"),o.uielement("ngx-decaf-crud-field",{label:"graph.run.workflowId.label"}),i.__metadata("design:type",String)],it.prototype,"workflowId",void 0),i.__decorate([s.column(),n.description("Owning user; absent for anonymous callers"),o.uielement("ngx-decaf-crud-field",{label:"graph.run.owner.label"}),i.__metadata("design:type",String)],it.prototype,"owner",void 0),i.__decorate([s.column(),r.required(),r.type(String),s.index(),n.description("Current run lifecycle status"),o.uilistprop("status"),o.uielement("ngx-decaf-crud-field",{label:"graph.run.status.label",readonly:!0}),i.__metadata("design:type",String)],it.prototype,"status",void 0),i.__decorate([s.column(),n.description("Fingerprint of the executed document"),o.uielement("ngx-decaf-crud-field",{label:"graph.run.fingerprint.label",readonly:!0}),i.__metadata("design:type",String)],it.prototype,"documentFingerprint",void 0),i.__decorate([s.column(),n.prop(),n.description("Workflow input values keyed by input port id"),i.__metadata("design:type",Object)],it.prototype,"inputs",void 0),i.__decorate([s.column(),n.prop(),n.description("Execution result, present on successful completion"),i.__metadata("design:type",Object)],it.prototype,"result",void 0),i.__decorate([s.column(),n.prop(),n.description("Structured error payload, present on failure"),i.__metadata("design:type",Object)],it.prototype,"error",void 0),i.__decorate([r.date(),s.column(),n.description("Run creation timestamp"),i.__metadata("design:type",Date)],it.prototype,"createdAt",void 0),i.__decorate([r.date(),s.column(),n.description("Execution start timestamp, once it has started"),i.__metadata("design:type",Date)],it.prototype,"startedAt",void 0),i.__decorate([r.date(),s.column(),n.description("Terminal-state timestamp, once the run has finished"),i.__metadata("design:type",Date)],it.prototype,"finishedAt",void 0),it=i.__decorate([o.uilistmodel("ngx-decaf-list-item",{icon:"ti-player-play"}),o.uimodel("ngx-decaf-crud-form"),n.description("Persistable graph run lifecycle record"),s.table("graph_run"),r.model(),i.__metadata("design:paramtypes",[Object])],it);let st=class extends s.BaseModel{constructor(e){super(e)}};i.__decorate([s.pk({type:String,generated:!1}),i.__metadata("design:type",String)],st.prototype,"workflowId",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],st.prototype,"name",void 0),i.__decorate([s.column(),i.__metadata("design:type",Object)],st.prototype,"document",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],st.prototype,"owner",void 0),i.__decorate([s.column(),i.__metadata("design:type",Object)],st.prototype,"snapshot",void 0),st=i.__decorate([s.table("graph_workflow"),r.model(),i.__metadata("design:paramtypes",[Object])],st);let dt=class extends s.BaseModel{constructor(e){super(e)}};i.__decorate([s.pk({type:String,generated:!1}),i.__metadata("design:type",String)],dt.prototype,"kind",void 0),i.__decorate([s.column(),s.index(),i.__metadata("design:type",String)],dt.prototype,"name",void 0),i.__decorate([s.column(),s.index(),i.__metadata("design:type",String)],dt.prototype,"category",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],dt.prototype,"group",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],dt.prototype,"description",void 0),i.__decorate([s.column(),i.__metadata("design:type",Object)],dt.prototype,"manifest",void 0),dt=i.__decorate([s.table("graph_node"),r.model(),i.__metadata("design:paramtypes",[Object])],dt),v("Trigger",{color:"#3b82f6",icon:"ti-bolt"}),v("Flow Control",{color:"#f59e0b",icon:"ti-arrows-split-2"}),v("Utility",{color:"#0d9488",icon:"ti-tool"}),v("Loop",{color:"#eab308",icon:"ti-repeat"}),v("Workflow",{color:"#f97316",icon:"ti-sitemap"}),v("Pipeline",{color:"#0ea5e9",icon:"ti-git-merge"}),v("Node",{color:"#8b5cf6",icon:"ti-point-filled"}),v("Agent",{color:"#7c3aed",icon:"ti-robot"}),v("model",{color:"#3b82f6",icon:"ti-cpu"}),v("memory",{color:"#10b981",icon:"ti-database"}),v("workspace",{color:"#f59e0b",icon:"ti-folder"});const lt=new Set;function ct(e,t){return e.config[t]}function ut(e){return Array.isArray(e)?e.map(e=>e+"").join(", "):e+""}(()=>{const e=[{key:x.NODE_ID,shouldInclude:e=>null!=ct(e,x.NODE_ID),render:e=>ct(e,x.NODE_ID)+""},{key:x.WORKFLOW_ID,shouldInclude:e=>null!=ct(e,x.WORKFLOW_ID),render:e=>ct(e,x.WORKFLOW_ID)+""},{key:x.RUN_ID,shouldInclude:e=>null!=ct(e,x.RUN_ID),render:e=>ct(e,x.RUN_ID)+""},{key:x.USER,shouldInclude:e=>null!=ct(e,x.USER),render:e=>ct(e,x.USER)+""},{key:x.ROLES,shouldInclude(e){const t=ct(e,x.ROLES);return Array.isArray(t)&&t.length>0},render:e=>ut(ct(e,x.ROLES))},{key:x.NAMESPACES,shouldInclude(e){const t=ct(e,x.NAMESPACES);return Array.isArray(t)&&t.length>0},render:e=>ut(ct(e,x.NAMESPACES))},{key:x.ORGANIZATION,shouldInclude:e=>null!=ct(e,x.ORGANIZATION),render:e=>ct(e,x.ORGANIZATION)+""},{key:x.IP,shouldInclude:e=>null!=ct(e,x.IP),render:e=>ct(e,x.IP)+""}];for(const o of e)lt.has(o.key)||(t.logParameterRegistry.register(o),lt.add(o.key))})();const pt="$workflow",ht="local",ft=1e3,gt=1e4,mt=3e4;var yt,wt;e.GraphPinningStrategy=void 0,(yt=e.GraphPinningStrategy||(e.GraphPinningStrategy={})).MANUAL="manual",yt.AUTOMATIC="automatic",yt.DISABLED="disabled",e.GraphConditionType=void 0,(wt=e.GraphConditionType||(e.GraphConditionType={})).TRUTHY="truthy",wt.FALSY="falsy",wt.EQUALS="equals",wt.NOT_EQUALS="notEquals",wt.GREATER_THAN="greaterThan",wt.GREATER_THAN_OR_EQUAL="greaterThanOrEqual",wt.LESS_THAN="lessThan",wt.LESS_THAN_OR_EQUAL="lessThanOrEqual",wt.EXISTS="exists",wt.CUSTOM="custom";class _t extends a.InternalError{constructor(e,t="GRAPH_EXECUTION_ERROR",o){super(e,_t.name,500),this.graphCode=t,this.details=o,this.name=this.constructor.name}}class bt extends _t{constructor(e){super("Graph workflow contains an unsupported cycle","GRAPH_CYCLE_ERROR",e)}}class vt extends _t{constructor(e,t){super(e,"GRAPH_INPUT_ERROR",t)}}class Nt extends _t{constructor(e,t){super(e,"GRAPH_LOOP_LIMIT_ERROR",t)}}class Et extends _t{constructor(e,t){super(e,"GRAPH_PINNING_ERROR",t)}}class It extends _t{constructor(e,t){super(e,"GRAPH_STORE_ERROR",t)}}class At extends _t{constructor(e,t){super(e,"GRAPH_TOPOLOGY_ERROR",t)}}class Ot extends _t{constructor(e){super("Break signal","GRAPH_BREAK_SIGNAL",{value:e}),this.isBreakSignal=!0,this.name="GraphBreakSignal"}}class kt extends _t{constructor(e){super(`Graph run '${e}' was cancelled`,"GRAPH_RUN_CANCELLED",{runId:e}),this.name=kt.name}}class xt extends a.ValidationError{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=xt.name,this.issues=e}}class St{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 Dt{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 _t("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 Rt(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(),a=o[1].split(",").map(e=>e.trim()).filter(e=>e.length>0);return n&&r&&0!==a.length?{organization:n,departments:a,role:r}:void 0}function Pt(e){return`${e.organization}.${e.departments.join(",")}.${e.role}`}function Ct(e){if(!e||"string"!=typeof e.namespace||!e.parts)return!1;const t=Rt(e.namespace);return!!t&&Pt(t)===Pt(e.parts)}function Tt(e,t){const o="string"==typeof e?e.trim():"";if(o){if(t)for(const e of t)if(e&&e.namespace===o&&Ct(e))return e.parts;return Rt(o)}}function $t(e,t,o={},n){const r=Tt(e,n),a=Tt(t,n);return!(!r||!a)&&r.organization===a.organization&&r.role===a.role&&("exact"===(o.mode??"inherit")?r.departments.length===a.departments.length&&r.departments.every((e,t)=>e===a.departments[t]):r.departments.length<=a.departments.length&&r.departments.every((e,t)=>e===a.departments[t]))}function Gt(e,t,o={},n){return e.filter(e=>!t.some(t=>$t(t,e,o,n)))}function Lt(e){return e.filter(e=>void 0===Rt(e))}function Mt(e,t){const o=new Set;for(const n of e){const e=Tt(n,t);e&&o.add(e.role)}return[...o]}function Ft(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function Vt(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 jt(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 a=Ft(e.roles);a&&(t.roles=a);const i=Ft(e.namespaces);return i&&(t.namespaces=i,t.namespaceCache=Bt(i)),t}function Ut(e){return e?jt({user:Vt(e,"user"),organization:Vt(e,"organization"),ip:Vt(e,"ip"),roles:Vt(e,"roles"),namespaces:Vt(e,"namespaces")}):{}}function Bt(e){const t=[];for(const o of e){const e=Rt(o);e&&t.push({namespace:o,parts:e})}return t}function Wt(...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??Bt(o.namespaces):void 0!==o.namespaceCache&&(t.namespaceCache=o.namespaceCache));return t}class qt{constructor(e={}){this.options=e}get enabled(){return!0===this.options.enabled}validate(e,o,n,r){if(!this.enabled)return;const a=r??this.options.logger??t.Logging.for("GraphAuth"),i=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=C(e.namespaces),o=C(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 '${i}'`,s?.namespaces??[],n,s?.roles??[],a);for(const e of o.nodes)this.assertGranted(`node '${e.id}'`,e.manifest.namespaces??[],n,[],a)}assertGranted(e,t,o,n,r){const a=o.namespaces??[],i=Gt(t,a,this.options.match,o.namespaceCache),d=Mt(a,o.namespaceCache),l=n.filter(e=>!d.includes(e));if(0===i.length&&0===l.length)return;const c=[...new Set([...Lt(t),...Lt(a)])],u=[];throw i.length&&u.push("namespace(s) "+i.join(", ")),l.length&&u.push("role(s) "+l.join(", ")),r.warn(`Graph access denied for ${e} for user ${o.user??"anonymous"}: missing ${u.join(" and ")}${c.length?`; malformed namespace(s) ${c.join(", ")} failed closed`:""}`),new s.ForbiddenError(`Access to ${e} requires ${u.join(" and ")}`)}}class Ht{constructor(e){this.baseOptions=e,this.inner=t.Logging.for("GraphRun").for(this.attributeConfig(e))}attributeConfig(e){return{[x.NODE_ID]:e.nodeId,[x.WORKFLOW_ID]:e.workflowId,[x.RUN_ID]:e.runId,[x.USER]:e.user??null,[x.ROLES]:e.roles,[x.NAMESPACES]:e.namespaces,[x.ORGANIZATION]:e.organization,[x.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:S.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 Kt(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}class zt extends s.Context{constructor(e,t,o,n,r,a,i,s,d={},l,c,u){super(),this.runId=e,this.parentRunId=t,this.workflowId=o,this.document=n,this.node=r,this.manifest=a,this.path=i,this.emitFn=s,this.metadata=d,this.engine=l,this.abortSignal=c,this.limits=u;const p=jt(d);this.accumulate({...p,operation:"execute"});const h="string"==typeof d?.user?d.user:null;this.runLogger=new Ht({runId:e,workflowId:o,nodeId:r.id,user:h,roles:Kt(d?.roles),namespaces:Kt(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 Ut(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:S.NODE_OUTPUT,payload:e})}async log(e,t){await this.emit({type:S.NODE_OUTPUT,payload:{message:e,payload:t}})}}class Xt{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 Jt(e,t,o,n,r){const a=e.valueStore.getWorkflowValues(),i={};for(const[t,o]of e.nodeResults)i[t]=o;const s=[...e.events];return{runId:e.runId,workflowId:t.id||t.name,status:n,document:t,inputs:{...o},outputs:a,nodeResults:i,events:s,startedAt:e.startedAt,finishedAt:e.finishedAt,metadata:r}}class Yt{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:S.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 Qt(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 Zt{static{this._cache={}}static register(e,t){return Zt._cache[e]=t,t}static get(e){const t=e??Zt._currentFlavour;if(t)return Zt._cache[t]}static getOrFail(e){const t=Zt.get(e);if(!t)throw new _t(`No graph execution backend registered under '${e}'`,"GRAPH_EXECUTION_BACKEND_NOT_REGISTERED");return t}static get current(){return Zt.get()}static get currentFlavour(){return Zt._currentFlavour??ht}static setCurrent(e){Zt._currentFlavour=e}static list(){return Object.entries(Zt._cache).map(([e,t])=>({flavour:e,backend:t}))}static unregister(e){e&&(delete Zt._cache[e],Zt._currentFlavour===e&&(Zt._currentFlavour=void 0))}static clear(){for(const e of Object.keys(Zt._cache))delete Zt._cache[e];Zt._currentFlavour=void 0}}class eo{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 _t(`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 _t("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 to(e){return"object"==typeof e&&null!==e&&"type"in e&&"code"===e.type}function oo(e){return"object"==typeof e&&null!==e&&"op"in e&&"string"==typeof e.op}async function no(e,t,o){const n=o.engine?.codeSandboxEvaluator;if(!n)throw new _t("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 ro(e,t,o){if(oo(e))return(new eo).evaluate(e,t);throw((e,t)=>new _t(`Unknown ${t??"flow"} condition type \u2014 must be ConditionExpression (op) or CodeCondition (type: 'code')`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition:e}))(e,o)}async function ao(e,t,o){return to(e)?no(e,t.input,o):ro(e,t.state,t.label)}function io(e,t,o,n){if(e&&"object"==typeof e&&!n.has(e))if(n.add(e),to(e))o.push({nodeId:t,kind:"code-condition"});else if(De(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))lo(e,o,n);else if(Array.isArray(e))for(const r of e)io(r,t,o,n);else for(const r of Object.keys(e))io(e[r],t,o,n)}function so(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});io(e.parameters,n,t,o),io(e.metadata,n,t,o),io(e.state,n,t,o),io(e.loop,n,t,o)}function lo(e,t,o){for(const n of e.nodes??[])so(n,t,o)}function co(e){const t=[];return lo(e,t,new Set),t}function uo(e,t){if(!t)return{valid:!0};switch(t.type){case"any":default:return{valid:!0};case"string":return"string"!=typeof e?po("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}:po("number");case"boolean":return"boolean"!=typeof e?po("boolean"):{valid:!0};case"array":if(!Array.isArray(e))return po("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=uo(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 po(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=uo(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 po(e){return{valid:!1,message:`expected a ${e} value`}}function ho(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 fo=new Set(["loop"]),go=["secret","secrets","password","passwd","token","accessToken","refreshToken","apiKey","api_key","privateKey","credentials"];class mo{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 a=!0===t.policies?.allowUndeclaredParameters,i=new Map(t.parameters.map(e=>[e.id,e]));for(const[r,s]of Object.entries(e.parameters??{})){const d=i.get(r);if(!d){a||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 a of t.parameters)void 0===(e.parameters??{})[a.id]&&(this.isParameterSatisfiedByInput(e,a.id,r)||(!0===a.required||(a.validation??[]).some(e=>"required"===e.kind))&&void 0===a.defaultValue&&o.push({code:"parameter.required-missing",path:`${n}.parameters.${a.id}`,message:`Node '${e.id}' is missing required parameter '${a.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(De(e))return{valid:!0};switch(t.type){case"string":case"code":case"expression":return"string"!=typeof e?po("string"):{valid:!0};case"number":return"number"==typeof e&&Number.isFinite(e)?{valid:!0}:po("number");case"boolean":return"boolean"!=typeof e?po("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}:po("array");case"object":case"resourceLocator":return null===e||"object"!=typeof e||Array.isArray(e)?po("object"):{valid:!0};case"credential":return ho(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 a of Object.keys(e.metadata??{}))fo.has(a)?o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${a}`,message:`Node '${e.id}' metadata key '${a}' is reserved and must not be set directly`,nodeId:e.id}):Array.isArray(r)&&!r.includes(a)&&o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${a}`,message:`Node '${e.id}' metadata key '${a}' 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||A(n)||t.push({code:"disabled.invalid-behavior",path:o+".metadata.disabledBehavior",message:`Node '${e.id}' disabled behavior '${n+""}' is not one of: ${I.join(", ")}`,nodeId:e.id})}validateBindingShapes(e,t,o,n){for(const[r,a]of Object.entries(e.inputBindings??{})){if("literal"===a.mode){const i=t.inputs.find(e=>e.id===r);if(i?.schema){const t=uo(a.value,i.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"!==a.mode||"string"==typeof a.expression&&a.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,a={}){const i=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 i){const o=(e.inputBindings??{})[t];o&&"literal"===o.mode&&!0!==a.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&&(i.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(A(o))return o;const n=t?.disabledBehavior;return A(n)?n:"skip"}}function yo(e){return[e.namespace??"default",e.workflowId,e.nodeId,e.version??"default",e.fingerprint].join(":")}function wo(t){return new e.GraphValueModel({id:yo(t.key),workflowId:t.key.workflowId,nodeId:t.key.nodeId,fingerprint:t.key.fingerprint,...void 0!==t.key.namespace?{namespace:t.key.namespace}:{},...void 0!==t.key.version?{version:t.key.version}:{},pinned:t.pinned,outputs:t.outputs,createdAt:new Date(t.createdAt),updatedAt:new Date(t.updatedAt),...t.expiresAt?{expiresAt:new Date(t.expiresAt)}:{},...t.metadata?{metadata:t.metadata}:{}})}function _o(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}:{}}}function bo(t){return new(0,s.Repository.forModel(e.GraphValueModel,t.alias).constructor)(t)}e.GraphValueModel=class extends s.BaseModel{constructor(e){super(e)}},i.__decorate([s.pk({type:String,generated:!1}),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"id",void 0),i.__decorate([s.column(),s.index(),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"workflowId",void 0),i.__decorate([s.column(),s.index(),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"nodeId",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"fingerprint",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"namespace",void 0),i.__decorate([s.column(),i.__metadata("design:type",String)],e.GraphValueModel.prototype,"version",void 0),i.__decorate([s.column(),i.__metadata("design:type",Boolean)],e.GraphValueModel.prototype,"pinned",void 0),i.__decorate([s.column(),i.__metadata("design:type",Object)],e.GraphValueModel.prototype,"outputs",void 0),i.__decorate([s.column(),i.__metadata("design:type",Date)],e.GraphValueModel.prototype,"createdAt",void 0),i.__decorate([s.column(),i.__metadata("design:type",Date)],e.GraphValueModel.prototype,"updatedAt",void 0),i.__decorate([s.column(),i.__metadata("design:type",Date)],e.GraphValueModel.prototype,"expiresAt",void 0),i.__decorate([s.column(),i.__metadata("design:type",Object)],e.GraphValueModel.prototype,"metadata",void 0),e.GraphValueModel=i.__decorate([s.table("graph_value"),r.model(),i.__metadata("design:paramtypes",[Object])],e.GraphValueModel),e.GraphValueRepository=class extends s.Repository{constructor(t){super(t,e.GraphValueModel,!0),this.runtimeValues=new Map}seedWorkflowInputs(e){this.runtimeValues.set(pt,{...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(pt)??{};o[e]=t,this.runtimeValues.set(pt,o)}getWorkflowValues(){return{...this.runtimeValues.get(pt)??{}}}snapshot(){return Object.fromEntries(this.runtimeValues.entries())}async readCached(e,...t){try{return _o(await this.read(yo(e),...t))}catch{return}}async writeCached(e,t,...o){const n=yo(e);let r;try{r=await this.read(n,...o)}catch{r=void 0}r?await this.update(Object.assign(r,wo(t)),...o):await this.create(wo(t),...o)}async deleteCached(e,...t){try{await this.delete(yo(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=>_o(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}},e.GraphValueRepository=i.__decorate([s.repository(e.GraphValueModel,n.DefaultFlavour),i.__metadata("design:paramtypes",[Function])],e.GraphValueRepository);class vo{static upstreamNodes(e,t,o=!1){const n=new Set,r=[e];for(;r.length;){const e=r.pop(),a=t.get(e)??[];for(const e of a)!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(),a=t.get(e)??[];for(const e of a)!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 No{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 Et(`Node '${e}' not found in plan`);if(!this.policy.canPin(o))throw new Et(`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 Et(`Node '${o}' has no completed output to pin`);const a=r.inputs??{},i=this.dependencyFingerprints(t,o,e.result),s=this.createValueKey(e.document.id,n,a,i),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 a=this.createValueKey(e,t,o,n,r),i=await this.store.readCached(a);if(i&&i.pinned){if(i.expiresAt&&new Date(i.expiresAt)<new Date)return;return i}}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)},a=this.stableSerialize(r);return this.simpleHash(a)}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=a=>{if(n.has(a))return;n.add(a);const i=vo.upstreamNodes(a,e.incomingByNode,!1);for(const e of i)t.has(e)&&r(e);o.push(a)};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 a=o.nodeResults[t],i=a?.inputs??{},s=this.dependencyFingerprints(e,t,o);r[t]=this.computeFingerprint(e.workflowId,n,i,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 Eo={enabled:!0,strategy:"manual",includeDependencies:!0};function Io(e){return!0===e?.enabled&&"disabled"!==e.strategy}class Ao{canPin(e){return Io(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?{...Eo,...t}:{...Eo,enabled:!1}}}class Oo{getDependencies(e,t){return vo.upstreamNodes(t,e.incomingByNode,!1)}getPinSet(e,t){const o=this.getDependencies(e,t);return o.add(t),o}}class ko{constructor(){this.local=!0,this.codeMode="hostSide",Zt.register(ht,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 _t("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 _t("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 _t("LocalGraphExecutionBackend has no writable workflowStore configured; workflow seeding is not supported","GRAPH_BACKEND_SEED_NOT_SUPPORTED");const r=[];for(const a of e)null!==await n.call(o,a.id,a,...t)&&r.push({id:a.id,...void 0!==a.name?{name:a.name}:{}});return r}async execute(e){const{document:t,plan:o,inputs:n,options:r,events:a}=e,i=a,s=i.frame;if(!s)throw new _t("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 i.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===O.FAILED);if(e?.error)throw new _t(e.error.message,e.error.code??"GRAPH_EXECUTION_ERROR",e.error.details);return s.finish(),await i.emit({type:S.WORKFLOW_COMPLETED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:O.SUCCEEDED,payload:{outputs:d.getWorkflowValues()}}),Jt(s,t,n,O.SUCCEEDED,r.metadata)}catch(e){if(e instanceof Ot)throw s.finish(),e;s.finish();const a=this.toErrorPayload(e);return e instanceof kt||!0===r.abortSignal?.aborted?(await i.emit({type:S.WORKFLOW_CANCELLED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:O.CANCELLED,error:a}),Jt(s,t,n,O.CANCELLED,r.metadata)):(await i.emit({type:S.WORKFLOW_FAILED,runId:l,parentRunId:r.parentRunId,workflowId:o.workflowId,path:c,status:O.FAILED,error:a}),Jt(s,t,n,O.FAILED,r.metadata))}}async executeLayer(e,t,o,n,r){const a=Math.max(1,n.concurrency??4),i=[...o];for(;i.length>0;){const o=i.splice(0,a);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 a=new Date,i=[...n.path??[],o.id];await r({type:S.NODE_STARTED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.RUNNING}),this.emitNodeStateChanged(e,t,o,i,k.RUNNING,O.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:O.CACHED,inputs:s,outputs:n.outputs,startedAt:a,finishedAt:d,fromCache:!0,pinned:!0,events:[]};return e.recordNodeResult(l),await r({type:S.NODE_CACHE_HIT,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.CACHED,payload:{outputs:n.outputs}}),await r({type:S.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.SUCCEEDED,payload:{outputs:n.outputs,fromCache:!0}}),void this.emitNodeStateChanged(e,t,o,i,k.SUCCEEDED,O.SUCCEEDED,r)}}try{const d=new zt(e.runId,n.parentRunId,t.workflowId,t.resolved.document,o.instance,o.manifest,i,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:O.SUCCEEDED,inputs:s,outputs:p,startedAt:a,finishedAt:h,events:[]};e.recordNodeResult(f),await r({type:S.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.SUCCEEDED,payload:{outputs:p}}),this.emitNodeStateChanged(e,t,o,i,k.SUCCEEDED,O.SUCCEEDED,r)}catch(d){if(d instanceof Ot)throw d;const l=new Date,c=this.toErrorPayload(d),u={nodeId:o.id,status:O.FAILED,inputs:s,error:c,startedAt:a,finishedAt:l,events:[]};if(e.recordNodeResult(u),await r({type:S.NODE_FAILED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.FAILED,error:c}),this.emitNodeStateChanged(e,t,o,i,k.FAILED,O.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===pt||e.isDataEdgeActive(t.id))}async skipInactiveNode(e,t,o,n,r){const a=new Date,i=[...n.path??[],o.id];await r({type:S.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.SKIPPED,payload:{reason:"branchNotSelected"}});const s={nodeId:o.id,status:O.SKIPPED,inputs:{},startedAt:a,finishedAt:new Date,events:[]};e.recordNodeResult(s),this.emitNodeStateChanged(e,t,o,i,k.SKIPPED,O.SKIPPED,r)}async executeDisabledNode(e,t,o,n,r){const a=new Date,i=[...n.path??[],o.id],s=mo.disabledBehaviorOf(o.instance,t.resolved.document.settings);if(await r({type:S.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:O.SKIPPED,payload:{disabled:!0,behavior:s}}),"skip"===s){const n={nodeId:o.id,status:O.SKIPPED,inputs:{},startedAt:a,finishedAt:new Date,events:[]};return e.recordNodeResult(n),void this.emitNodeStateChanged(e,t,o,i,k.SKIPPED,O.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",a=n?e.valueStore.getPort(n.sourceNodeId,n.sourcePort):Object.values(d)[0];l={[r]:a}}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:O.SUCCEEDED,inputs:d,outputs:l,startedAt:a,finishedAt:new Date,events:[]};e.recordNodeResult(c),this.emitNodeStateChanged(e,t,o,i,k.SUCCEEDED,O.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 _t(`Node '${e.id}' of kind '${e.kind}' produced unknown output(s): ${r.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,unknownOutputs:r});const a=o.outputs.filter(e=>!0===e.required&&!(e.id in t)).map(e=>e.id);if(a.length>0)throw new _t(`Node '${e.id}' of kind '${e.kind}' did not produce required output(s): ${a.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,missingRequired:a});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??""}:ho(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:""}:ho(o)&&(t[e]={credentialId:o.credentialId,credentialType:o.credentialType})}return t}async resolveNodeInputs(e,t,o,n){const r={},a=(t.incomingByNode.get(o.id)??[]).filter(e=>"data"===e.type),i=new Map;for(const e of a){const t=i.get(e.targetPort)??[];t.push(e),i.set(e.targetPort,t)}for(const[t,o]of i)if(1===o.length)r[t]=e.valueStore.getPort(o[0].sourceNodeId,o[0].sourcePort);else{let n,a=!1;for(const t of o){const o=e.valueStore.getPort(t.sourceNodeId,t.sourcePort);r[t.sourcePort]=o,void 0!==o&&(n=o,a=!0)}a&&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[a,i]of Object.entries(n))r[a]=De(i)?await this.evaluateValueTemplate(i,e,t,o):i;return r}async evaluateValueTemplate(e,t,o,n){const r=this.codeSandboxEvaluator;if(!r)throw new _t(`Value template on node '${t.id}' requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator`,"GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{nodeId:t.id});const a=e.language??("expression"===e.mode?"javascript":"text"),i="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:i,language:"typescript"===a?"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 _t(`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 a=n.metadata;return await r.evaluate({code:t,language:"javascript",input:o,vars:a?.vars??void 0,item:a?.item,index:a?.index,abortSignal:n.abortSignal})}async tryPinnedValue(e,t,o,n){if(!(new Ao).shouldUsePinnedValue(o))return;const r=this.createPinningService(e),a=this.computeDependencyFingerprints(e,t,o.id);return r.readPinnedValue(t.workflowId,o,n,a)}computeDependencyFingerprints(e,t,o){const n=this.createPinningService(e),r=(new Oo).getDependencies(t,o),a={};for(const o of r){const r=t.nodes.find(e=>e.id===o);if(r){const i=e.nodeResults.get(o),s=i?.inputs??{},d=this.computeDependencyFingerprints(e,t,o);a[o]=n.computeFingerprint(t.workflowId,r,s,d)}}return a}routeOutgoingEdges(e,t,o,n,r){const a=(t.outgoingByNode.get(o.id)??[]).filter(e=>"data"===e.type);for(const i of a){if(!Object.prototype.hasOwnProperty.call(n,i.sourcePort))continue;const a=n[i.sourcePort];e.activateDataEdge(i.id),i.targetNodeId===pt&&e.valueStore.setWorkflowOutput(i.targetPort,a),this.emitEdgeStateChanged(e,t,o,i,k.SUCCEEDED,O.SUCCEEDED,r),r({type:S.EDGE_VALUE_ROUTED,runId:e.runId,workflowId:t.workflowId,edgeId:i.id,nodeId:o.id,path:[],payload:{edge:i,value:a}}).catch(()=>{})}}emitNodeStateChanged(e,t,o,n,r,a,i){i({type:S.NODE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:n,status:a,payload:{nodeId:o.id,state:r,runId:e.runId,workflowId:t.workflowId,status:a}}).catch(()=>{})}emitEdgeStateChanged(e,t,o,n,r,a,i){i({type:S.EDGE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,edgeId:n.id,nodeId:o.id,path:[],status:a,payload:{edgeId:n.id,state:r,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,status:a}}).catch(()=>{})}createPinningService(e){const t=bo(e.valueStore.getAdapter()??this.valueAdapter);return new No(t,new Ao,new Oo)}executionLimits(e){return{maxLoopIterations:e.maxLoopIterations??ft,maxForeachIterations:e.maxForeachIterations??gt}}assertNotAborted(e){if(!0===e.abortSignal?.aborted)throw new kt(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 xo{constructor(e){this.catalogue=e}async resolveNodes(e,t,o,...n){const r=new Map;for(const[a,i]of e.entries()){const e=`nodes[${a}]`;if(this.catalogue.has(i.kind,...n))try{const e=await this.catalogue.resolveManifest(i.kind,i,o,...n),t=this.catalogue.getExecutor(i.kind,...n);r.set(i.id,{instance:i,manifest:e,executor:t})}catch(o){t.push({code:"kind.resolution-failed",path:e+".kind",message:`Node '${i.id}' kind '${i.kind}' failed to resolve: ${o.message}`,nodeId:i.id,details:{kind:i.kind}})}else t.push({code:"kind.unknown",path:e+".kind",message:`Node '${i.id}' references kind '${i.kind}' which is not registered in the backend catalogue`,nodeId:i.id,details:{kind:i.kind}})}return r}validateEffectivePorts(e,t,o,n){const r=!0===t.policies?.allowUndeclaredParameters,a=new Set(t.inputs.map(e=>e.id)),i=new Set(t.outputs.map(e=>e.id));for(const i of Object.keys(e.inputBindings??{}))r||a.has(i)||o.push({code:"binding.unknown-port",path:`${n}.inputBindings.${i}`,message:`Node '${e.id}' input binding '${i}' does not refer to an effective input port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveInputs:[...a]}});for(const a of Object.keys(e.outputBindings??{}))r||i.has(a)||o.push({code:"binding.unknown-port",path:`${n}.outputBindings.${a}`,message:`Node '${e.id}' output binding '${a}' does not refer to an effective output port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveOutputs:[...i]}})}}function So(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&&So(e,t,`${o}.nodes[${r.id}].loop.body`)}}class Do{resolveEdges(e,t,o){const n=new Set(e.inputs.map(e=>e.id)),r=new Set(e.outputs.map(e=>e.id)),a=[];for(const[i,s]of(e.edges??[]).entries()){const e=`edges[${i}]`,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),a.push(c)}return a}resolveEndpoint(e,t,o,n,r,a,i){const s=e[t];return ge(s)?("source"===t?n.has(s.port):r.has(s.port))?{nodeId:pt,port:s.port}:void a.push({code:"edge.unknown-port",path:`${i}.${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}}):me(s)?o.get(s.nodeId)?{nodeId:s.nodeId,port:s.port}:void a.push({code:"edge.unknown-node",path:`${i}.${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 a.push({code:"edge.invalid-endpoint",path:`${i}.${t}`,message:`Edge '${e.id}' ${t} endpoint is not a valid GraphEndpoint`,edgeId:e.id})}validateDirectionAndType(e,t,o,n,r,a){let i=!0;const s=t.nodeId===pt?void 0:n.get(t.nodeId),d=o.nodeId===pt?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,a),i=!1),!d||l(d)||this.hasPortDirection(d,o.port,"input")||(this.pushPortIssue(e,"target",o,d,r,a),i=!1);else{if(!s||!d)return r.push({code:"edge.boundary-routing",path:a,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:a,message:`Connection edge '${e.id}' endpoints must both be connection ports`,edgeId:e.id,details:{sourcePort:t.port,targetPort:o.port}}),!1}return i}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,a){const i="source"===t?"output":"input";r.push({code:"data"===e.type?"edge.invalid-direction":"edge.type-mismatch",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} port '${o.port}' on node '${o.nodeId}' is not an ${i} port of kind '${n.manifest.kind}'`,edgeId:e.id,nodeId:o.nodeId,details:{port:o.port,expected:i}})}}class Ro{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(":"),a=n.slice(0,o),i=n.slice(o+1),s=e.nodeById.get(a),d=s?.manifest.connections?.find(e=>e.id===i)?.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 '${i}' on node '${a}' accepts at most ${l} connection(s) but has ${r.length}`,nodeId:a,edgeId:r[r.length-1].id,details:{port:i,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),a=r?.manifest.kind;if(!o.allowedNodeKinds?.length||a&&o.allowedNodeKinds.includes(a)||n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${a??"unknown"}' is not in the allowed node kinds of target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{allowedNodeKinds:o.allowedNodeKinds}}),a&&o.blockedNodeKinds?.includes(a)&&n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${a}' 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 Po{constructor(e){this.authorizer=e}async validate(e,t,o,n){const r=this.collectReferences(e,t);for(const a of t.credentials??[]){const i=r.find(e=>void 0===e.credentialType||e.credentialType===a.type);if(i){if(this.checkType(i,a))o.push({code:"credential.type-mismatch",path:n,message:`Node '${e.id}' credential '${i.credentialId}' has type '${i.credentialType}' but kind '${t.kind}' requires '${a.type}'`,nodeId:e.id,details:{credentialType:i.credentialType??"",requiredType:a.type}});else if(this.authorizer){if(!await this.authorizer.hasCredential(i)){o.push({code:"credential.not-found",path:n,message:`Node '${e.id}' references credential '${i.credentialId}' which does not exist`,nodeId:e.id,details:{credentialId:i.credentialId}});continue}await this.authorizer.authorize(i,a)||o.push({code:"credential.unauthorized",path:n,message:`Node '${e.id}' is not authorized to use credential '${i.credentialId}'`,nodeId:e.id,details:{credentialId:i.credentialId}})}}else!1!==a.required&&o.push({code:"credential.missing",path:n,message:`Node '${e.id}' does not provide the required credential of type '${a.type}'`,nodeId:e.id,details:{credentialType:a.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];ho(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))ho(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(go);for(const[r,a]of Object.entries(e.parameters??{}))this.scanPlainSecretValue(a,[r],e,o+".parameters",n,t);for(const[r,a]of Object.entries(e.metadata??{}))this.scanPlainSecretValue(a,[r],e,o+".metadata",n,t)}scanPlainSecretValue(e,t,o,n,r,a,i=0){const s=t[t.length-1];if(r.has(s))a.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>i&&null!==e)if(Array.isArray(e))for(const s of e)this.scanPlainSecretValue(s,[...t,"[]"],o,n,r,a,i+1);else if("object"==typeof e)for(const[s,d]of Object.entries(e))this.scanPlainSecretValue(d,[...t,s],o,n,r,a,i+1)}}class Co extends a.ValidationError{constructor(e,t=[]){super(e),this.issues=t,this.name=Co.name}}class To extends a.ValidationError{constructor(e,t){super(e),this.edgeId=t,this.name=To.name}}class $o extends s.AuthorizationError{constructor(e){super(e),this.name=$o.name}}const Go={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},Lo=["node","definition","executor","execute","ports","component"];function Mo(e){if(!e||"object"!=typeof e)return!1;const t=e;return Re(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 Fo(e,t){const o=[];for(const n of Object.keys(e))Lo.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 Vo{constructor(e){this.options=e,this.parameterValidator=new mo,this.edgeValidator=new Do,this.connectionPolicyValidator=new Ro,this.nodeValidator=new xo(e.catalogue),this.credentialValidator=new Po(e.credentialAuthorizer)}async validateOrThrow(e,...t){const o=await this.validate(e,0,...t);if(!o.valid||!o.resolved)throw new Co(`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={...Go,...this.options.limits};if(!await this.validateStructure(e,r,t,n,...o))return{valid:!1,issues:n};const a=await this.nodeValidator.resolveNodes(e.nodes,n,this.options.resolutionContext,...o),i=e.nodes.filter(e=>a.has(e.id)).map(e=>a.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 i)this.parameterValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`,s.get(e.instance.id));for(const e of i)this.nodeValidator.validateEffectivePorts(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);const d=this.edgeValidator.resolveEdges(e,a,n),l=new Map,c=new Map;for(const e of d){if(e.targetNodeId!==pt){const t=l.get(e.targetNodeId)??[];t.push(e),l.set(e.targetNodeId,t)}if(e.sourceNodeId!==pt){const t=c.get(e.sourceNodeId)??[];t.push(e),c.set(e.sourceNodeId,t)}}this.connectionPolicyValidator.validate({edges:d,nodeById:a},n),this.validateAcyclicity(i,d,e,n),So(e,n);for(const e of i)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 i)await this.credentialValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);return this.validateCapabilities(i,n),n.length>0?{valid:!1,issues:n}:{valid:!0,issues:n,resolved:{document:e,nodes:i,edges:d,nodeById:a,incomingByNode:l,outgoingByNode:c}}}async validateStructure(e,t,o,n,...r){if(!Re(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"}),!ae(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(...Fo(e,"$"));for(const t of[...e.inputs,...e.outputs])n.push(...Fo(t,"ports"));for(const t of e.nodes)n.push(...Fo(t,`nodes[${t.id}]`));for(const t of e.edges)n.push(...Fo(t,`edges[${t.id}]`));this.validateUniqueIds(e,n),this.validateLimits(e,t,o,n);try{ve(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,a]of[["input",e.inputs],["output",e.outputs]]){const e="input"===r?o:n;for(const o of a)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 a=new Set;for(const o of e.edges)a.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}):a.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[a,i]of e){if(!i)continue;const e=await this.validate(i,t+1,...n);for(const t of e.issues)o.push({...t,path:`nodes[${r.id}].${a}.${t.path}`,nodeId:t.nodeId??r.id})}}}validateAcyclicity(e,t,o,n){const r=new Set(e.map(e=>e.instance.id)),a=new Map(e.map(e=>[e.instance.id,0]));for(const e of t)r.has(e.sourceNodeId)&&a.has(e.targetNodeId)&&a.set(e.targetNodeId,(a.get(e.targetNodeId)??0)+1);const i=[...a.entries()].filter(([,e])=>0===e).map(([e])=>e),s=[];for(;i.length>0;){const e=i.shift();s.push(e);for(const o of t){if(o.sourceNodeId!==e)continue;if(!a.has(o.targetNodeId))continue;const t=(a.get(o.targetNodeId)??1)-1;a.set(o.targetNodeId,t),0===t&&i.push(o.targetNodeId)}}if(s.length!==a.size){const e=[...a.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===pt&&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??[])Te(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}))}}}e.GraphExecutionPlanner=class extends s.Service{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"}'`),!Mo(e))throw new At("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),a=this.buildPlanEdges(e),i=this.buildIncomingMap(a),s=this.buildOutgoingMap(a),d=this.topologicalLayers(r,a);return{resolved:e,workflowId:e.document.id||e.document.name,nodes:r,edges:a,layers:d,incomingByNode:i,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===pt)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===pt)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!==pt),n=new Set(o.map(e=>e.id)),r=t.filter(e=>n.has(e.sourceNodeId)&&n.has(e.targetNodeId)),a=new Map;for(const e of o)a.set(e.id,0);for(const e of r)a.set(e.targetNodeId,(a.get(e.targetNodeId)??0)+1);const i=[],s=new Set;let d=o.filter(e=>0===(a.get(e.id)??0)),l=0;for(;d.length>0;){const e={index:l++,nodes:d};i.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=(a.get(e.targetNodeId)??1)-1;if(a.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 bt({unplannedNodes:e,workflowId:o[0]?.manifest.kind})}return i}},e.GraphExecutionPlanner=i.__decorate([s.service(),i.__metadata("design:paramtypes",[])],e.GraphExecutionPlanner);const jo=new Set(["engine","valueAdapter","codeSandboxEvaluator","workflowStore"]);function Uo(e,t){const o={};for(const[n,r]of Object.entries(e??{}))jo.has(n)&&!t.has(n)||(o[n]=r);return o}class Bo extends s.ClientBasedService{constructor(){super()}async initialize(...t){const o=t[0];if(!o||"object"!=typeof o||!o.registry)return this._config=void 0,this._client=void 0,{config:void 0,client:void 0};const n=o.catalogue??o.registry.catalog,r=o.valueAdapter??s.Adapter.current;if(!r)throw new _t("GraphExecutionEngine requires a Decaf adapter for cached/pinned values: pass `valueAdapter` or configure one via `Adapter.setCurrent(...)`","GRAPH_VALUE_ADAPTER_MISSING");const a=o.backend??Zt.current??new ko,i={registry:o.registry,catalogue:n,planner:o.planner??new e.GraphExecutionPlanner,backend:a,valueAdapter:r,eventEmitter:o.eventEmitter??new St,documentValidator:o.documentValidator??new Vo({catalogue:n,limits:o.documentLimits,credentialAuthorizer:o.credentialAuthorizer}),authValidator:new qt({enabled:!0===o.authEnabled,...o.authMatch?{match:o.authMatch}:{}}),...o.codeSandboxEvaluator?{codeSandboxEvaluator:o.codeSandboxEvaluator}:{}};this._config=o,this._client=i;const d=new Set(["engine","valueAdapter"]);o.codeSandboxEvaluator&&d.add("codeSandboxEvaluator"),o.workflowStore&&d.add("workflowStore");const l=Uo(a.config,d);if(await a.initialize({...l,valueAdapter:r,...o.codeSandboxEvaluator?{codeSandboxEvaluator:o.codeSandboxEvaluator}:{},...o.workflowStore?{workflowStore:o.workflowStore}:{},engine:this}),o.seedWorkflows&&o.seedWorkflows.length>0){const e=a.seedWorkflows;if("function"!=typeof e)throw new _t(`Graph execution backend '${a.constructor?.name??"GraphExecutionBackend"}' does not support workflow seeding`,"GRAPH_BACKEND_SEED_NOT_SUPPORTED",{backend:a.constructor?.name??"GraphExecutionBackend"});await e.call(a,o.seedWorkflows,...t.slice(1))}return await(o.onEngineCreated?.(this)),{config:o,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:a}=(await this.logCtx(n,"execute",!0)).for(this.execute);r.debug(`Executing workflow '${e.id||e.name}'`);const i=this.mergeOptions(o);this.assertNotAborted(i);const s=Wt(Ut(a),i.auth);i.auth=s,i.metadata={...i.metadata??{},...s};const d=i.runId??this.generateRunId();i.runId=d;const l=i.path??[],c=new Dt,u=bo(this.valueAdapter);u.seedWorkflowInputs(this.withWorkflowInputDefaults(e,t));const p=new Yt(this.emitter,c,{runId:d,parentRunId:i.parentRunId,workflowId:e.id||e.name,path:l,engine:this,...this.codeSandboxEvaluator?{codeSandboxEvaluator:this.codeSandboxEvaluator}:{}});await p.emit({type:S.VALIDATION_STARTED,status:O.PLANNING});const h=await this.documentValidator.validate(e,0,a);if(!h.valid||!h.resolved)throw await p.emit({type:S.VALIDATION_FAILED,status:O.FAILED,payload:{issues:h.issues}}),new Co(`Graph workflow document '${e.id}' failed validation with ${h.issues.length} issue(s)`,h.issues);await p.emit({type:S.VALIDATION_COMPLETED,status:O.PLANNING,payload:{issues:h.issues.length}}),this.assertNotAborted(i);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 Xt(d,f,u,c);return p.bindFrame(g),await p.emit({type:S.WORKFLOW_STARTED,runId:d,parentRunId:i.parentRunId,workflowId:f.workflowId,path:l,status:O.RUNNING,payload:{inputs:t}}),await p.emit({type:S.WORKFLOW_PLANNED,runId:d,parentRunId:i.parentRunId,workflowId:f.workflowId,path:l,status:O.PLANNING,payload:{layers:f.layers.length,nodes:f.nodes.length}}),await this.client.backend.execute({document:e,plan:f,inputs:t,options:i,events:p},...n)}get backend(){return this.client.backend}get backendCapabilities(){return Qt(this.client.backend)}async listWorkflows(...e){const t=this.client.backend;if("supported"!==Qt(t).workflows.list||"function"!=typeof t.listWorkflows)throw new _t(`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"!==Qt(o).workflows.get||"function"!=typeof o.getWorkflow)throw new _t(`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=Zt.getOrFail(e);if("supported"!==Qt(o).workflows.list||"function"!=typeof o.listWorkflows)throw new _t(`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=Zt.getOrFail(e);if("supported"!==Qt(n).workflows.get||"function"!=typeof n.getWorkflow)throw new _t(`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=co(e);if(0!==o.length){if("unsupported"===t.codeMode)throw new _t(`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 _t("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,S.NODE_PINNED)}async unpinNode(e){const t=this.createPinningService();await t.unpinNode(e),await this.emitPinningEvent(e.nodeId,S.NODE_UNPINNED)}createPinningService(){const e=bo(this.valueAdapter);return new No(e,new Ao,new Oo)}async emitPinningEvent(e,t){const o=(new Dt).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:ft,maxForeachIterations:gt,usePinnedValues:!0,writeThroughCache:!1,path:[],metadata:{},...this.defaultOptions,...e}}assertNotAborted(e){if(!0===e.abortSignal?.aborted)throw new kt(e.runId??"unknown")}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new _t("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 Wo=new Set(["process","require","module","exports","global","globalThis","Function","eval","fetch","XMLHttpRequest","WebSocket","Worker","Deno","Bun","__dispatch"]);class qo extends s.ClientBasedService{constructor(){super()}async initialize(...e){const t=e[0]??{},o=t&&"object"==typeof t?t:{};return this._config=o,this._client=d,{config:o,client:d}}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 _t("Code sandbox received empty code","GRAPH_CODE_SANDBOX_EMPTY_CODE");const n=((e,t)=>"javascript"===t?e:w.transpileModule(e,{compilerOptions:{target:w.ScriptTarget.ES2022,module:w.ModuleKind.None,strict:!0,noEmitHelpers:!0,importHelpers:!1}}).outputText.replace(/^"use strict";\s*/,""))(o,e.language??"javascript");(e=>{if(e.length>1e5)throw new _t("Code exceeds the maximum length of 100000 characters","GRAPH_CODE_SANDBOX_CODE_TOO_LONG",{length:e.length});let t;try{t=m.parse(`async function __validate() {\n${e}\n}`,{ecmaVersion:"latest",sourceType:"script"})}catch{try{t=m.parse(e,{ecmaVersion:"latest",sourceType:"module"})}catch(t){throw new _t("Code failed to parse: "+t.message,"GRAPH_CODE_SANDBOX_PARSE_ERROR",{code:e,error:t.message})}}y.full(t,e=>{const t=e;if("ImportDeclaration"===t.type)throw new _t("Imports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"import"});if("ExportNamedDeclaration"===t.type||"ExportDefaultDeclaration"===t.type)throw new _t("Exports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"export"});if("Identifier"===t.type&&"string"==typeof t.name&&Wo.has(t.name))throw new _t(`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 _t("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 _t("eval() is not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"eval"})})})(n);const r=!(e=>/\breturn\b[\s;]/.test(e))(n),a=r?n.replace(/[\s;]+$/,""):n,i={$input:e.input??{},$vars:e.vars??{},$item:e.item,$index:e.index,$node:e.nodes??{},$output:void 0},s=Object.keys(i),l=r?`return (${a});`:a,c=`"use strict";\nasync function __userFunction(${s.join(", ")}) {\n${l}\n}\n__userFunction(${s.join(", ")}).then(function(__r) { return JSON.stringify({ v: __r }); });`,u=new d.Isolate({memoryLimit:this.defaultMemoryMb}),p=await u.createContext();try{const t=p.global;e.logger&&await this.injectConsole(p,e.logger);for(const[e,o]of Object.entries(i))await t.set(e,new d.ExternalCopy(void 0===o?null:o).copyInto());let o;try{o=await u.compileScript(c,{filename:"graph-code-node.js"})}catch(e){if(!r)throw new _t("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message});{const e=a,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 u.compileScript(t,{filename:"graph-code-node.js"})}catch(e){throw new _t("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message})}}}const l=e.timeoutMs??this.defaultTimeoutMs;let h;try{h=await this.runBounded(o,p,l,e.abortSignal)}catch(e){if(e instanceof _t)throw e;const t=e.message;if(t.includes("timed out")||t.includes("timeout"))throw new _t(`Code execution timed out after ${l} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:l});if(t.includes("memory")||t.includes("heap"))throw new _t(`Code exceeded the memory limit of ${this.defaultMemoryMb} MB`,"GRAPH_CODE_SANDBOX_MEMORY_LIMIT",{memoryMb:this.defaultMemoryMb});throw new _t("Code execution failed: "+t,"GRAPH_CODE_SANDBOX_RUNTIME_ERROR",{code:n,error:t})}if("string"!=typeof h)throw new _t("Code sandbox returned an unexpected non-string result","GRAPH_CODE_SANDBOX_UNEXPECTED_RESULT",{result:h});return JSON.parse(h).v}finally{p.release(),u.dispose()}}async runBounded(e,t,o,n){const r=e.run(t,{timeout:o,promise:!0});r.catch(()=>{});const a=[r];let i,s;try{return a.push(new Promise((e,t)=>{i=setTimeout(()=>{t(new _t(`Code execution timed out after ${o} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:o}))},o+100)})),n&&a.push(new Promise((e,t)=>{const r=()=>{const e="timeout"===n.reason;t(new _t(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(a)}finally{i&&clearTimeout(i),s?.()}}async injectConsole(e,t){const o=new d.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(" "),a=1===n.length?n[0]:n;switch(e){case"log":case"info":default:t.info(r,a);break;case"warn":t.warn(r,a);break;case"error":t.error(r,a);break;case"debug":case"dir":case"dirxml":case"table":t.debug(r,a);break;case"trace":t.trace(r,a);break;case"group":case"groupCollapsed":t.debug("[group] "+r,a);break;case"groupEnd":t.debug("[groupEnd]",void 0);break;case"time":case"timeEnd":case"timeLog":case"count":case"countReset":t.debug(`[${e}] ${r}`,a);break;case"assert":n[0]||t.error("Assertion failed: "+r,a);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 Ho extends a.InternalError{constructor(e){super(e,Ho.name,500)}}class Ko extends a.NotFoundError{constructor(e){super(e),this.name=Ko.name}}class zo extends a.NotFoundError{constructor(e){super(e),this.name=zo.name}}class Xo{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 Ho(`Method declaration for kind '${this.kind}' is missing a name`);if(this.declarations.has(e.name))throw new Ho(`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 Ho(`Method implementation '${e}' for kind '${this.kind}' is not a function`);if(!this.declarations.has(e))throw new Ho(`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 Ho(`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 zo(`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 Jo(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 Yo(e,t,o){const n=Jo(t,e.itemIdPath),r=e.itemLabelPath?Jo(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 Qo(e,t){switch(t){case"input":return e.inputs;case"output":return e.outputs;default:return e.connections}}function Zo(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 a=Qo(o,n.direction);e.forEach((e,t)=>{const{id:o,label:i}=Yo(n,e,t),s=(d={id:o,index:t,label:i??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?ie(n.defaultPort):{id:s,label:i??s,direction:n.direction};l.id=s,l.direction=n.direction,i&&(l.label=i),a.push(l)})}else if("togglePort"===n.type){if(t[n.parameter]!==n.equals)continue;const e=ie(n.port);if(!r(e.direction,e.id))continue;Qo(o,e.direction).push(e)}return o}function en(e,t){const o=Zo(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),ie(n)}class tn{async resolve(e,t,o,n,r){if(o){const a=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)})(a))throw new Ho(`resolveManifest provider for kind '${e}' returned a value that does not conform to GraphResolvedNodeManifest`);if(!ae(a))throw new Ho(`resolveManifest provider for kind '${e}' returned a non-JSON-safe resolved manifest`);const i=ie(a);return!i.namespaces?.length&&t.namespaces?.length&&(i.namespaces=t.namespaces.slice()),i}return en(t,n.parameters??{})}}const on=["edge","literal","expression"];function nn(e){return on.includes(e)}function rn(e,t,o){if("string"!=typeof o||!o)throw new Ho(`Manifest for kind '${e}' has a ${t} with an empty port id`);if(te(o))throw new Ho(`Manifest for kind '${e}' has a ${t} with unsafe port id '${o}'`)}function an(e){return e}function sn(e){if(!e)return;const t={...e.metadata??{},...e.parameters??{},...e.state??{}};return e.loop&&(t.loop=e.loop),t}e.GraphNodeCatalogue=class extends s.Service{constructor(){super(),this.entries=new Map,this.resolver=new tn,this.fallbackContext=new s.Context}withContext(e){return e[e.length-1]instanceof s.Context?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 Ho("Graph node registration is required");if(!e.manifest||"object"!=typeof e.manifest)throw new Ho("Graph node registration is missing a manifest");if(!e.executor||"function"!=typeof e.executor.execute)throw new Ho(`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 Ho("Graph node manifest kind is required and must be a non-empty string");const a=r.kind;if(this.entries.has(a)&&!t.replace)throw new Ho(`Graph node kind '${a}' is already registered; pass { replace: true } to replace it`);try{Ge(r)}catch(e){throw new Ho(`Manifest for kind '${a}' 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(rn(e,t+" port",r?.id),o.has(r.id))throw new Ho(`Manifest for kind '${e}' declares duplicate static ${t} port id '${r.id}'`);if(o.add(r.id),void 0!==r.defaultMode&&!nn(r.defaultMode))throw new Ho(`Manifest for kind '${e}' declares invalid default binding mode '${r.defaultMode+""}' on ${t} port '${r.id}'`)}}})(a,r);const i=((e,t)=>{const o=new Set;for(const n of t.parameters){const t=n?.id;if("string"!=typeof t||!t)throw new Ho(`Manifest for kind '${e}' has a parameter with an empty id`);if(te(t))throw new Ho(`Manifest for kind '${e}' has a parameter with unsafe id '${t}'`);if(o.has(t))throw new Ho(`Manifest for kind '${e}' declares duplicate parameter id '${t}'`);o.add(t)}return o})(a,r);((e,t,o)=>{for(const n of t.dynamicPorts??[]){if(!n||"string"!=typeof n.parameter||!n.parameter)throw new Ho(`Manifest for kind '${e}' has a dynamic-port rule without a parameter reference`);if(!o.has(n.parameter))throw new Ho(`Manifest for kind '${e}' has a dynamic-port rule referencing missing parameter '${n.parameter}'`);if("togglePort"===n.type){if(!n.port)throw new Ho(`Manifest for kind '${e}' has a togglePort rule without a port`);rn(e,"togglePort rule port",n.port.id)}if("repeatFromParameter"===n.type&&"string"!=typeof n.portIdTemplate)throw new Ho(`Manifest for kind '${e}' has a repeatFromParameter rule without a portIdTemplate`)}})(a,r,i),((e,t)=>{for(const o of t.credentials??[]){if(!Pe(o))throw new Ho(`Manifest for kind '${e}' has a malformed credential requirement`);if(!o.type)throw new Ho(`Manifest for kind '${e}' has a credential requirement with an empty type`)}})(a,r),((e,t)=>{for(const o of t.methods??[])if(!Ve(o))throw new Ho(`Manifest for kind '${e}' has a malformed method declaration`)})(a,r);const s=new Xo(a,r.methods??[],e.methods??{});return this.entries.set(a,{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 Ho("Graph executor kind is required");if(!t||"function"!=typeof t.execute)throw new Ho(`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 a={kind:e,display:{name:e},inputs:[],outputs:[],parameters:[],policies:{allowUndeclaredParameters:!0,allowUnknownOutputs:!0}};return this.entries.set(e,{registration:{manifest:a,executor:t},methods:new Xo(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 Ko(`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),ie(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,a=[];for(const e of o){if(r&&!r.has(e))continue;const o=this.getManifest(e,...t);n&&!n.has(o.display.category??"")||a.push(o)}return a}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)}},e.GraphNodeCatalogue=i.__decorate([s.service(),i.__metadata("design:paramtypes",[])],e.GraphNodeCatalogue),e.GraphNodeExecutorRegistry=class extends s.Service{constructor(t=new e.GraphNodeCatalogue){super(),this.catalogue=t}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 _t("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 Ko)throw new _t(`No graph executor registered for kind '${e}'`,"GRAPH_EXECUTOR_NOT_FOUND",{kind:e});throw t}}},e.GraphNodeExecutorRegistry=i.__decorate([s.service(),i.__metadata("design:paramtypes",[e.GraphNodeCatalogue])],e.GraphNodeExecutorRegistry),e.GraphNodeExecutorResolver=class extends s.Service{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)}},e.GraphNodeExecutorResolver=i.__decorate([s.service(),i.__metadata("design:paramtypes",[Function,Object])],e.GraphNodeExecutorResolver);class dn extends r.Model{constructor(e){super(),r.Model.fromModel(this,e)}execute(e,t){throw new _t(`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)}}function ln(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+""}}e.BreakFlowNode=class extends dn{execute(e,t){throw new Ot(e.inputs.value)}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.break.fields.value.label",placeholder:"graph.node.flow_control.break.fields.value.placeholder",type:"textarea"}),Y({handle:"value"}),i.__metadata("design:type",Object)],e.BreakFlowNode.prototype,"value",void 0),e.BreakFlowNode=i.__decorate([X("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"}}),r.model()],e.BreakFlowNode),e.ErrorBoundaryFlowNode=class extends dn{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 _t("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"]}),a=Object.values(r.nodeResults).find(e=>e.status===O.FAILED);if(a)throw new _t(a.error?.message??"error boundary try body failed",a.error?.code??"GRAPH_ERROR_BOUNDARY",a.error?.details);return{result:r.outputs.result??r.outputs}}catch(r){let a=r;if(o.catch){const i=await n.execute(o.catch,{...e.inputs,error:ln(r)},{parentRunId:t.runId,path:[...t.path,"catch"]});a=i.outputs.error??i.outputs}return{error:a}}finally{o.finally&&await n.execute(o.finally,e.inputs,{parentRunId:t.runId,path:[...t.path,"finally"]})}}},i.__decorate([r.required(),o.uielement("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"}),Y({handle:"value"}),i.__metadata("design:type",Object)],e.ErrorBoundaryFlowNode.prototype,"value",void 0),i.__decorate([Q({handle:"result"}),i.__metadata("design:type",Object)],e.ErrorBoundaryFlowNode.prototype,"result",void 0),i.__decorate([Q({handle:"error"}),i.__metadata("design:type",Object)],e.ErrorBoundaryFlowNode.prototype,"error",void 0),e.ErrorBoundaryFlowNode=i.__decorate([X("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}}),r.model()],e.ErrorBoundaryFlowNode),e.HumanApprovalFlowNode=class extends dn{execute(e){const t=e.inputs.value??e.inputs;return!1===this.approved?{rejected:t}:{approved:t}}},i.__decorate([r.required(),Y({handle:"value"}),i.__metadata("design:type",Object)],e.HumanApprovalFlowNode.prototype,"value",void 0),i.__decorate([o.uielement("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"}),Y({handle:"message",userControlled:!0}),i.__metadata("design:type",String)],e.HumanApprovalFlowNode.prototype,"message",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.human_approval.fields.approved.label",type:"checkbox"}),Y({handle:"approved",userControlled:!0}),i.__metadata("design:type",Boolean)],e.HumanApprovalFlowNode.prototype,"approved",void 0),i.__decorate([Q({handle:"approved"}),i.__metadata("design:type",Object)],e.HumanApprovalFlowNode.prototype,"approvedOut",void 0),i.__decorate([Q({handle:"rejected"}),i.__metadata("design:type",Object)],e.HumanApprovalFlowNode.prototype,"rejectedOut",void 0),e.HumanApprovalFlowNode=i.__decorate([X("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}}),r.model()],e.HumanApprovalFlowNode),e.IfFlowNode=class extends dn{execute(e,t){const o=e.inputs,n=o.value??o;if(!this.condition)throw new _t("If node has no condition configured","GRAPH_IF_NO_CONDITION",{input:o});if(to(this.condition))return no(this.condition,o,t).then(e=>this.route(e,n));const r=ro(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 _t("If node condition evaluated to false and the else branch is disabled","GRAPH_IF_ELSE_DISABLED",{condition:this.condition})}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.value.label",placeholder:"graph.node.flow_control.if.fields.value.placeholder",type:"textarea"}),Y({handle:"value"}),i.__metadata("design:type",Object)],e.IfFlowNode.prototype,"value",void 0),i.__decorate([r.required(),Q({handle:"then"}),i.__metadata("design:type",Object)],e.IfFlowNode.prototype,"then",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.condition.label",placeholder:"graph.node.flow_control.if.fields.condition.placeholder",type:"code"}),Y({handle:"condition",userControlled:!0,type:"object"}),i.__metadata("design:type",Object)],e.IfFlowNode.prototype,"condition",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.else.label",type:"checkbox"}),Y({handle:"else",userControlled:!0}),i.__metadata("design:type",Boolean)],e.IfFlowNode.prototype,"else",void 0),e.IfFlowNode=i.__decorate([X("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"}}),r.model()],e.IfFlowNode),e.SwitchFlowNode=class extends dn{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,a=r.value??r,i=((e,t)=>t===e||"object"!=typeof t||null===t||Array.isArray(t)?e:{...t,...e})(r,a);for(const e of n)if(await ao(e.condition,{input:r,state:i,label:"switch case"},t))return{[e.outputPort]:a};if(!0!==o.hasDefault)throw new _t("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]:a}}static applyMetadata(e){const t=H(this),o=e.defaultPort??"default",n=!0===e.hasDefault,r=t.ports.filter(t=>!e.cases.some(e=>e.outputPort===t.property)),a=r.filter(e=>e.property!==o),i=r.find(e=>e.property===o),s=[...a,...e.cases.map(e=>({property:e.outputPort,name:e.label,direction:g.OUTPUT,label:e.label,required:!1,hidden:!1,path:e.outputPort}))];return n&&i&&s.push(i),{ports:s,size:b(t,{cases:e.cases.length}),dataPatch:{switchMetadata:e}}}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.value.label",placeholder:"graph.node.flow_control.switch.fields.value.placeholder",type:"textarea"}),Y({handle:"value"}),i.__metadata("design:type",Object)],e.SwitchFlowNode.prototype,"value",void 0),i.__decorate([r.required(),Q({handle:"default"}),i.__metadata("design:type",Object)],e.SwitchFlowNode.prototype,"default",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.cases.label",type:"collection"}),i.__metadata("design:type",Object)],e.SwitchFlowNode.prototype,"cases",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.hasDefault.label",type:"checkbox"}),i.__metadata("design:type",Boolean)],e.SwitchFlowNode.prototype,"hasDefault",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.defaultPort.label",type:"text"}),i.__metadata("design:type",String)],e.SwitchFlowNode.prototype,"defaultPort",void 0),e.SwitchFlowNode=i.__decorate([X("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"}}),r.model()],e.SwitchFlowNode);const cn={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},un=t.LoggedEnvironment.accumulate({graph:{workflows:{limits:{...cn},allowAnonymousAccess:!1},execution:{maxCodeTimeoutMs:mt}}});function pn(e,t){const o="number"==typeof t?t:Number(t),n=Number.isFinite(o)&&o>0?o:mt,r="number"==typeof e?e:Number(e);return Number.isFinite(r)&&r>0?Math.min(Math.floor(r),n):1e3}const hn=["javascript","typescript"],fn="javascript";e.CodeInputSchema=class extends r.Model{constructor(){super(...arguments),this.language=fn}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.language.label",type:"select"}),r.option([...hn]),r.type(String),i.__metadata("design:type",String)],e.CodeInputSchema.prototype,"language",void 0),i.__decorate([r.required(),o.uielement("code-editor",{label:"graph.node.utility.code.fields.code.label",placeholder:"graph.node.utility.code.fields.code.placeholder"}),Y({handle:"code"}),i.__metadata("design:type",String)],e.CodeInputSchema.prototype,"code",void 0),i.__decorate([o.hidden(),Y({handle:"data"}),i.__metadata("design:type",Object)],e.CodeInputSchema.prototype,"data",void 0),e.CodeInputSchema=i.__decorate([r.model()],e.CodeInputSchema),e.CodeNode=class extends dn{async execute(e,t){const o=e.inputs,n=this.input,r=o.code??e.parameters?.code??n?.code??this.defaultCode,a=n?.language??fn;if(!r||"string"!=typeof r||0===r.trim().length)throw new vt("Code node has no code to execute (input.code is empty)",{input:o});const i=t.engine?.codeSandboxEvaluator;if(!i)throw new _t("Code node execution requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{code:r});const s=un.graph.execution?.maxCodeTimeoutMs,d="number"==typeof s&&Number.isFinite(s)&&s>0?s:mt,l=pn(this.timeoutMs,d),c=t.metadata,u={code:r,language:a,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:a,length:r.length,timeoutMs:l});const p=await i.evaluate(u);return await t.log("Code node executed",{hasResult:void 0!==p}),{result:p}}},i.__decorate([r.required(),Y({handle:"input",model:e.CodeInputSchema}),i.__metadata("design:type",e.CodeInputSchema)],e.CodeNode.prototype,"input",void 0),i.__decorate([r.min(1),r.max(mt),o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.timeoutMs.label",type:"number"}),Y({handle:"timeoutMs"}),i.__metadata("design:type",Number)],e.CodeNode.prototype,"timeoutMs",void 0),i.__decorate([o.uielement("code-editor",{label:"graph.node.utility.code.fields.defaultCode.label",placeholder:"graph.node.utility.code.fields.defaultCode.placeholder"}),Y({handle:"defaultCode",userControlled:!0}),i.__metadata("design:type",String)],e.CodeNode.prototype,"defaultCode",void 0),i.__decorate([r.required(),Q({handle:"result"}),i.__metadata("design:type",Object)],e.CodeNode.prototype,"result",void 0),e.CodeNode=i.__decorate([X("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"}}),r.model()],e.CodeNode),e.DelayFlowNode=class extends dn{execute(e){return{value:e.inputs.value??e.inputs}}},i.__decorate([r.required(),Y({handle:"value"}),i.__metadata("design:type",Object)],e.DelayFlowNode.prototype,"value",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.delay.fields.timeoutMs.label",type:"number"}),Y({handle:"timeoutMs"}),i.__metadata("design:type",Number)],e.DelayFlowNode.prototype,"timeoutMs",void 0),i.__decorate([r.required(),Q({handle:"value"}),i.__metadata("design:type",Object)],e.DelayFlowNode.prototype,"valueOut",void 0),e.DelayFlowNode=i.__decorate([X("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"}}),r.model()],e.DelayFlowNode),e.LogFlowNode=class extends dn{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}},i.__decorate([r.required(),Y({handle:"value"}),i.__metadata("design:type",Object)],e.LogFlowNode.prototype,"value",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.message.label",placeholder:"graph.node.utility.log.fields.message.placeholder",type:"textarea"}),Y({handle:"message"}),i.__metadata("design:type",String)],e.LogFlowNode.prototype,"message",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.level.label",placeholder:"graph.node.utility.log.fields.level.placeholder",type:"text"}),Y({handle:"level",userControlled:!0}),i.__metadata("design:type",String)],e.LogFlowNode.prototype,"level",void 0),i.__decorate([r.required(),Q({handle:"value"}),i.__metadata("design:type",Object)],e.LogFlowNode.prototype,"valueOut",void 0),e.LogFlowNode=i.__decorate([X("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"}}),r.model()],e.LogFlowNode),e.MapNode=class extends dn{execute(e){return{result:{mapped:e.inputs.value??e.inputs}}}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.map.fields.value.label",placeholder:"graph.node.utility.map.fields.value.placeholder",type:"textarea"}),Y({handle:"value"}),i.__metadata("design:type",Object)],e.MapNode.prototype,"value",void 0),i.__decorate([r.required(),Q({handle:"result"}),i.__metadata("design:type",Object)],e.MapNode.prototype,"result",void 0),e.MapNode=i.__decorate([X("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:{}}}),r.model()],e.MapNode),e.UtilityLogNode=class extends dn{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}},i.__decorate([r.required(),Y({handle:"value"}),i.__metadata("design:type",Object)],e.UtilityLogNode.prototype,"value",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.message.label",placeholder:"graph.node.utility.utility_log.fields.message.placeholder",type:"textarea"}),Y({handle:"message"}),i.__metadata("design:type",String)],e.UtilityLogNode.prototype,"message",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.level.label",placeholder:"graph.node.utility.utility_log.fields.level.placeholder"}),Y({handle:"level",userControlled:!0,type:"string"}),i.__metadata("design:type",String)],e.UtilityLogNode.prototype,"level",void 0),i.__decorate([r.required(),Q({handle:"value"}),i.__metadata("design:type",Object)],e.UtilityLogNode.prototype,"valueOut",void 0),e.UtilityLogNode=i.__decorate([X("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"}}),r.model()],e.UtilityLogNode),e.ChatTriggerNode=class extends dn{execute(e){return{message:e.inputs.message??null,sessionId:e.inputs.sessionId??null,userId:e.inputs.userId??null}}},i.__decorate([r.required(),Q({handle:"message"}),i.__metadata("design:type",String)],e.ChatTriggerNode.prototype,"message",void 0),i.__decorate([r.required(),Q({handle:"sessionId"}),i.__metadata("design:type",String)],e.ChatTriggerNode.prototype,"sessionId",void 0),i.__decorate([r.required(),Q({handle:"userId"}),i.__metadata("design:type",String)],e.ChatTriggerNode.prototype,"userId",void 0),e.ChatTriggerNode=i.__decorate([X("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"}}}),r.model()],e.ChatTriggerNode),e.EventTriggerNode=class extends dn{execute(e){return{payload:e.inputs.payload??null}}},i.__decorate([r.required(),Q({handle:"payload"}),i.__metadata("design:type",Object)],e.EventTriggerNode.prototype,"payload",void 0),e.EventTriggerNode=i.__decorate([X("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"}}}),r.model()],e.EventTriggerNode),e.FormTriggerNode=class extends dn{execute(e){return{payload:e.inputs.payload??null}}},i.__decorate([r.required(),Y({handle:"schema"}),o.uielement("ngx-decaf-model-builder",{label:"graph.node.trigger.form.fields.schema.label",placeholder:"graph.node.trigger.form.fields.schema.placeholder"}),i.__metadata("design:type",Object)],e.FormTriggerNode.prototype,"schema",void 0),i.__decorate([r.required(),Q({handle:"payload"}),i.__metadata("design:type",Object)],e.FormTriggerNode.prototype,"payload",void 0),e.FormTriggerNode=i.__decorate([X("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:[]}}}),r.model()],e.FormTriggerNode),e.ManualTriggerNode=class extends dn{execute(e){return{payload:e.inputs.payload??null}}},i.__decorate([r.required(),Q({handle:"payload"}),i.__metadata("design:type",Object)],e.ManualTriggerNode.prototype,"payload",void 0),e.ManualTriggerNode=i.__decorate([X("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:{}}}}),r.model()],e.ManualTriggerNode),e.ScheduleTriggerNode=class extends dn{execute(e){return{payload:e.inputs.payload??null}}},i.__decorate([r.required(),Y({handle:"cron"}),o.uielement("app-cron-selector-field",{label:"graph.node.trigger.schedule.fields.cron.label",placeholder:"graph.node.trigger.schedule.fields.cron.placeholder"}),i.__metadata("design:type",String)],e.ScheduleTriggerNode.prototype,"cron",void 0),i.__decorate([r.required(),Q({handle:"payload"}),i.__metadata("design:type",Object)],e.ScheduleTriggerNode.prototype,"payload",void 0),e.ScheduleTriggerNode=i.__decorate([X("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"}}}),r.model()],e.ScheduleTriggerNode),e.WebhookTriggerNode=class extends dn{execute(e){return{payload:e.inputs.payload??null}}},i.__decorate([r.required(),Y({handle:"schema"}),o.uielement("ngx-decaf-model-builder",{label:"graph.node.trigger.webhook.fields.schema.label",placeholder:"graph.node.trigger.webhook.fields.schema.placeholder"}),i.__metadata("design:type",Object)],e.WebhookTriggerNode.prototype,"schema",void 0),i.__decorate([r.required(),Q({handle:"payload"}),i.__metadata("design:type",Object)],e.WebhookTriggerNode.prototype,"payload",void 0),e.WebhookTriggerNode=i.__decorate([X("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"}}}),r.model()],e.WebhookTriggerNode),e.AgentNode=class extends dn{execute(e){return{response:"[Agent response] "+(e.inputs.prompt??""),actions:[]}}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.agent.agent.fields.prompt.label",placeholder:"graph.node.agent.agent.fields.prompt.placeholder",type:"textarea"}),Y({handle:"prompt"}),i.__metadata("design:type",String)],e.AgentNode.prototype,"prompt",void 0),i.__decorate([r.required(),Q({handle:"response"}),i.__metadata("design:type",String)],e.AgentNode.prototype,"response",void 0),i.__decorate([r.required(),Q({handle:"actions"}),i.__metadata("design:type",Array)],e.AgentNode.prototype,"actions",void 0),i.__decorate([Z({category:"model",handle:"model"}),i.__metadata("design:type",Object)],e.AgentNode.prototype,"model",void 0),i.__decorate([Z({category:"memory",handle:"memory"}),i.__metadata("design:type",Object)],e.AgentNode.prototype,"memory",void 0),i.__decorate([Z({category:"workspace",handle:"workspace"}),i.__metadata("design:type",Object)],e.AgentNode.prototype,"workspace",void 0),e.AgentNode=i.__decorate([X("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"}}),r.model()],e.AgentNode);const gn=[e.AgentNode];function mn(e,t,o,n){const r=t??o;if(null==e)return Math.min(o,r);const a=Number(e);if(!Number.isFinite(a)||0>=a)throw new vt(n+" loop maxIterations must be a positive finite number");return Math.min(Math.floor(a),r)}function yn(e,t,o){const n=t.node.loop,r=t.metadata?.loop;if(!n?.body&&!r?.body)throw new vt(o+" node is missing loop configuration (instance.loop.body)");const a=t=>{const o=e[t]??n?.[t]??r?.[t],a=Number(o);return void 0!==o&&Number.isFinite(a)?a:void 0},i=t=>{const o=e[t]??r?.[t];return"string"==typeof o?o:void 0};return{body:n?.body??r?.body,maxIterations:a("maxIterations"),timeoutMs:a("timeoutMs"),concurrency:a("concurrency"),condition:e.condition??r?.condition,inputPort:i("inputPort"),outputPort:i("outputPort"),itemPort:i("itemPort"),resultPort:i("resultPort"),statePort:i("statePort"),slice:a("slice")}}e.GraphForeachLoopNode=class extends dn{async execute(e,t){const o=yn(this,t,"foreach"),n=e.inputs,r=n.items,a=mn(o.maxIterations,t.limits?.maxForeachIterations,1e3,"foreach");if(!Array.isArray(r))throw new vt("foreach input 'items' must be an array");const i=t.engine;if(!i)throw new _t("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>a)throw new Nt(`foreach exceeded max iterations (${l} > ${a})`);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:S.LOOP_STARTED});for(let e=0;l>e;e++){await t.emit({type:S.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 i.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 Ot){const n=o.details?.value;void 0!==n&&f.push(n),m=!0,await t.emit({type:S.LOOP_ITERATION_COMPLETED,iteration:e,metadata:{broken:!0}});break}throw o}await t.emit({type:S.LOOP_ITERATION_COMPLETED,iteration:e})}await t.emit({type:S.LOOP_COMPLETED,metadata:{broken:m}});const y={results:f,completed:f,iterations:f.length,broken:m};return void 0!==g&&(y[p]=g),y}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.items.label",placeholder:"graph.node.loop.foreach.fields.items.placeholder",type:"textarea"}),Y({handle:"items"}),i.__metadata("design:type",Array)],e.GraphForeachLoopNode.prototype,"items",void 0),i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.slice.label",placeholder:"graph.node.loop.foreach.fields.slice.placeholder",type:"number"}),Y({handle:"slice"}),i.__metadata("design:type",Number)],e.GraphForeachLoopNode.prototype,"slice",void 0),i.__decorate([r.required(),Q({handle:"item"}),i.__metadata("design:type",Object)],e.GraphForeachLoopNode.prototype,"item",void 0),i.__decorate([r.required(),Z({handle:"loop",connectionRules:{allowSelf:!0,maxConnections:1}}),i.__metadata("design:type",Object)],e.GraphForeachLoopNode.prototype,"loop",void 0),i.__decorate([r.required(),Q({handle:"completed"}),i.__metadata("design:type",Array)],e.GraphForeachLoopNode.prototype,"completed",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.maxIterations.label",type:"number"}),Y({handle:"maxIterations",userControlled:!0}),i.__metadata("design:type",Number)],e.GraphForeachLoopNode.prototype,"maxIterations",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.condition.label",type:"code"}),Y({handle:"condition",userControlled:!0}),i.__metadata("design:type",Object)],e.GraphForeachLoopNode.prototype,"condition",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.itemPort.label",type:"text"}),Y({handle:"itemPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphForeachLoopNode.prototype,"itemPort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.resultPort.label",type:"text"}),Y({handle:"resultPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphForeachLoopNode.prototype,"resultPort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.statePort.label",type:"text"}),Y({handle:"statePort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphForeachLoopNode.prototype,"statePort",void 0),e.GraphForeachLoopNode=i.__decorate([X("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}}}),r.model()],e.GraphForeachLoopNode);class wn{constructor(){this.expressionEvaluator=new eo}evaluate(t,o){if(this.isConditionExpression(t))return this.expressionEvaluator.evaluate(t,o);const n=this.resolveValue(t.left,o),r=t.right;switch(t.type){case e.GraphConditionType.TRUTHY:return!!n;case e.GraphConditionType.FALSY:return!n;case e.GraphConditionType.EQUALS:return n===r;case e.GraphConditionType.NOT_EQUALS:return n!==r;case e.GraphConditionType.GREATER_THAN:return Number(n)>Number(r);case e.GraphConditionType.GREATER_THAN_OR_EQUAL:return Number(n)>=Number(r);case e.GraphConditionType.LESS_THAN:return Number(r)>Number(n);case e.GraphConditionType.LESS_THAN_OR_EQUAL:return Number(r)>=Number(n);case e.GraphConditionType.EXISTS:return null!=n;case e.GraphConditionType.CUSTOM:throw new _t("Custom condition evaluators are not supported in v1","GRAPH_CUSTOM_CONDITION_UNSUPPORTED");default:throw new _t(`Unknown condition type '${t.type}'`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition:t})}}async evaluateAsync(e,t,o,n){return to(e)?no(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}}function _n(e,t,o,n={}){return{id:e,label:t,direction:o,...n}}function bn(e){const t=e,o=F(t),n=o?.metadata?.title;return nt(t,n?{name:n}:{})}e.GraphUntilLoopNode=class extends dn{async execute(e,t){const o=yn(this,t,"until"),n=e.inputs,r=mn(o.maxIterations,t.limits?.maxLoopIterations,100,"until"),a=o.condition;if(!a)throw new vt("until node is missing a condition");const i=o.statePort??"state",s=o.inputPort??i,d=o.outputPort??i,l=o.body,c=t.engine;if(!c)throw new _t("until node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;await t.emit({type:S.LOOP_STARTED});let h=!1;do{if(p>=r)throw await t.emit({type:S.LOOP_LIMIT_REACHED,iteration:p}),new Nt(`until loop exceeded max iterations (${r})`);await t.emit({type:S.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:S.LOOP_ITERATION_COMPLETED,iteration:p});const e=await(new wn).evaluateAsync(a,u,t,{...n,state:u});await t.emit({type:S.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:e}}),p++,h=e}while(!h);return await t.emit({type:S.LOOP_COMPLETED}),{state:u,iterations:p}}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.state.label",placeholder:"graph.node.loop.until.fields.state.placeholder",type:"textarea"}),Y({handle:"state"}),i.__metadata("design:type",Object)],e.GraphUntilLoopNode.prototype,"state",void 0),i.__decorate([r.required(),Q({handle:"state"}),i.__metadata("design:type",Object)],e.GraphUntilLoopNode.prototype,"stateOut",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.maxIterations.label",type:"number"}),Y({handle:"maxIterations",userControlled:!0}),i.__metadata("design:type",Number)],e.GraphUntilLoopNode.prototype,"maxIterations",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.condition.label",type:"code"}),Y({handle:"condition",userControlled:!0}),i.__metadata("design:type",Object)],e.GraphUntilLoopNode.prototype,"condition",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.statePort.label",type:"text"}),Y({handle:"statePort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphUntilLoopNode.prototype,"statePort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.inputPort.label",type:"text"}),Y({handle:"inputPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphUntilLoopNode.prototype,"inputPort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.outputPort.label",type:"text"}),Y({handle:"outputPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphUntilLoopNode.prototype,"outputPort",void 0),e.GraphUntilLoopNode=i.__decorate([X("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}}}}),r.model()],e.GraphUntilLoopNode),e.GraphWhileLoopNode=class extends dn{async execute(e,t){const o=yn(this,t,"while"),n=e.inputs,r=mn(o.maxIterations,t.limits?.maxLoopIterations,100,"while"),a=o.condition;if(!a)throw new vt("while node is missing a condition");const i=o.statePort??"state",s=o.inputPort??i,d=o.outputPort??i,l=o.body,c=t.engine;if(!c)throw new _t("while node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;for(await t.emit({type:S.LOOP_STARTED});await(new wn).evaluateAsync(a,u,t,{...n,state:u});){if(p>=r)throw await t.emit({type:S.LOOP_LIMIT_REACHED,iteration:p}),new Nt(`while loop exceeded max iterations (${r})`);await t.emit({type:S.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:!0}}),await t.emit({type:S.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:S.LOOP_ITERATION_COMPLETED,iteration:p}),p++}return await t.emit({type:S.LOOP_COMPLETED}),{state:u,iterations:p}}},i.__decorate([r.required(),o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.state.label",placeholder:"graph.node.loop.while.fields.state.placeholder",type:"textarea"}),Y({handle:"state"}),i.__metadata("design:type",Object)],e.GraphWhileLoopNode.prototype,"state",void 0),i.__decorate([r.required(),Q({handle:"state"}),i.__metadata("design:type",Object)],e.GraphWhileLoopNode.prototype,"stateOut",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.maxIterations.label",type:"number"}),Y({handle:"maxIterations",userControlled:!0}),i.__metadata("design:type",Number)],e.GraphWhileLoopNode.prototype,"maxIterations",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.condition.label",type:"code"}),Y({handle:"condition",userControlled:!0}),i.__metadata("design:type",Object)],e.GraphWhileLoopNode.prototype,"condition",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.statePort.label",type:"text"}),Y({handle:"statePort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphWhileLoopNode.prototype,"statePort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.inputPort.label",type:"text"}),Y({handle:"inputPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphWhileLoopNode.prototype,"inputPort",void 0),i.__decorate([o.uielement("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.outputPort.label",type:"text"}),Y({handle:"outputPort",userControlled:!0}),i.__metadata("design:type",String)],e.GraphWhileLoopNode.prototype,"outputPort",void 0),e.GraphWhileLoopNode=i.__decorate([X("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}}}}),r.model()],e.GraphWhileLoopNode),e.GraphInputValueNode=class extends dn{execute(e){const t=e.inputs;return{value:t?.value??null}}},i.__decorate([Q({handle:"value",connectionRules:{allowMultiple:!0}}),i.__metadata("design:type",Object)],e.GraphInputValueNode.prototype,"value",void 0),e.GraphInputValueNode=i.__decorate([X("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"}}),r.model()],e.GraphInputValueNode),e.GraphOutputValueNode=class extends dn{execute(e){return{}}},i.__decorate([r.required(),Y({handle:"value"}),i.__metadata("design:type",Object)],e.GraphOutputValueNode.prototype,"value",void 0),e.GraphOutputValueNode=i.__decorate([X("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"}}),r.model()],e.GraphOutputValueNode);const vn={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:[_n("items","graph.node.loop.foreach.ports.input.items.label","input",{required:!0,schema:{type:"array",items:{type:"any"}}}),_n("slice","graph.node.loop.foreach.ports.input.slice.label","input",{schema:{type:"number",integer:!0,min:1}}),_n("state","graph.node.loop.foreach.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[_n("results","graph.node.loop.foreach.ports.output.results.label","output",{schema:{type:"array",items:{type:"any"}}}),_n("completed","graph.node.loop.foreach.ports.output.completed.label","output",{schema:{type:"array",items:{type:"any"}}}),_n("iterations","graph.node.loop.foreach.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}}),_n("broken","graph.node.loop.foreach.ports.output.broken.label","output",{schema:{type:"boolean"}}),_n("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}]},Nn={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:[_n("state","graph.node.loop.while.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[_n("state","graph.node.loop.while.ports.output.state.label","output",{schema:{type:"any"}}),_n("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"}]},En={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:[_n("state","graph.node.loop.until.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[_n("state","graph.node.loop.until.ports.output.state.label","output",{schema:{type:"any"}}),_n("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"}]},In=[bn(e.GraphInputValueNode),bn(e.GraphOutputValueNode),bn(e.ManualTriggerNode),bn(e.WebhookTriggerNode),bn(e.ScheduleTriggerNode),bn(e.EventTriggerNode),bn(e.FormTriggerNode),bn(e.ChatTriggerNode),(An=bn(e.IfFlowNode),{...An,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"}}}]}))(bn(e.SwitchFlowNode)),bn(e.MapNode),bn(e.DelayFlowNode),bn(e.ErrorBoundaryFlowNode),bn(e.HumanApprovalFlowNode),bn(e.CodeNode),bn(e.LogFlowNode),bn(e.UtilityLogNode),bn(e.BreakFlowNode),bn(e.AgentNode),vn,Nn,En];var An;const On=Object.fromEntries(In.map(e=>[e.kind,e])),kn=[e.ManualTriggerNode,e.WebhookTriggerNode,e.ScheduleTriggerNode,e.EventTriggerNode,e.FormTriggerNode,e.ChatTriggerNode],xn=[e.IfFlowNode,e.SwitchFlowNode,e.DelayFlowNode,e.ErrorBoundaryFlowNode,e.HumanApprovalFlowNode,e.LogFlowNode,e.BreakFlowNode],Sn=[e.CodeNode,e.MapNode,e.UtilityLogNode],Dn=[e.GraphForeachLoopNode,e.GraphWhileLoopNode,e.GraphUntilLoopNode],Rn=[e.GraphInputValueNode,e.GraphOutputValueNode],Pn={value:e.GraphInputValueNode,result:e.GraphOutputValueNode,"core.trigger.manual":e.ManualTriggerNode,"core.trigger.webhook":e.WebhookTriggerNode,"core.trigger.schedule":e.ScheduleTriggerNode,"core.trigger.event":e.EventTriggerNode,"core.trigger.form":e.FormTriggerNode,"core.trigger.chat":e.ChatTriggerNode,"core.flow.if":e.IfFlowNode,"core.flow.switch":e.SwitchFlowNode,"core.utility.map":e.MapNode,"core.flow.delay":e.DelayFlowNode,"core.flow.errorBoundary":e.ErrorBoundaryFlowNode,"core.flow.humanApproval":e.HumanApprovalFlowNode,"core.utility.code":e.CodeNode,"core.flow.log":e.LogFlowNode,"core.utility.log":e.UtilityLogNode,"core.flow.break":e.BreakFlowNode,"core.agent":e.AgentNode,"core.loop.foreach":e.GraphForeachLoopNode,"core.loop.while":e.GraphWhileLoopNode,"core.loop.until":e.GraphUntilLoopNode};function Cn(e){return{execute:(t,o)=>e.instantiate({...sn(o.node),...t.parameters,...o.node.state??{}}).execute(t,o)}}function Tn(){const e=[];for(const[t,o]of Object.entries(On)){const n=Pn[t];n&&e.push(an({manifest:o,executor:Cn(n)}))}return e}const $n=["node","definition","executor","execute","ports","component"];function Gn(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 Ln(e,t){const o=[];for(const n of Object.keys(e))$n.includes(n)&&o.push(Gn("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 Mn(e,t){t.push(...Ln(e,"$")),e.inputs.forEach((e,o)=>t.push(...Ln(e,`inputs[${o}]`))),e.outputs.forEach((e,o)=>t.push(...Ln(e,`outputs[${o}]`)));for(const o of e.nodes)t.push(...Ln(o,`nodes[${o.id}]`)),o.loop&&(t.push(...Ln(o.loop,`nodes[${o.id}].loop`)),Mn(o.loop.body,t));for(const o of e.edges)t.push(...Ln(o,`edges[${o.id}]`))}function Fn(e,t){const o=[];e.nodes.length>t.maxNodes&&o.push(Gn("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(Gn("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=Vn(e);n>t.maxNestingDepth&&o.push(Gn("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(Gn("document.limit.size","$",`Document serializes to ${r} bytes; at most ${t.maxDocumentBytes} bytes are allowed`,{details:{bytes:r,limit:t.maxDocumentBytes}})),o}function Vn(e,t=0){let o=t;for(const n of e.nodes)n.loop?.body&&(o=Math.max(o,Vn(n.loop.body,t+1)));return o}async function jn(e,t,...o){const n=[];for(const r of e.nodes)t.has(r.kind,...o)||n.push(Gn("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 jn(r.loop.body,t,...o));return n}async function Un(e,t={},...o){const n={...cn,...t.limits},r=[];if(!Re(e))return r.push(Gn("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(!ae(e))return r.push(Gn("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};Mn(e,r),r.push(...(e=>{const t=[],o=new Set;for(const n of[...e.inputs,...e.outputs])o.has(n.id)?t.push(Gn("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(Gn("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(Gn("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(...Fn(e,n)),So(e,r);try{ve(e)}catch(e){const t=e instanceof a.ValidationError?e.message:e+"";r.push(Gn("document.structure","$",t))}return t.catalogue&&r.push(...await jn(e,t.catalogue,...o)),{valid:0===r.length,issues:r}}function Bn(e,t,o={}){const n=e?.owner??null;return!n||n===t||(null==t||""===t)&&!0===o.allowAnonymousAccess}function Wn(e,t){return(e?.owner??null)===(t??null)}function qn(e,t,o){if(!Wn(e,t))throw new s.ForbiddenError(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function Hn(e,t,o){if(!Bn(e,t,o))throw new s.ForbiddenError(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function Kn(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>Kn(e)).join(",")}]`;const t=e;return`{${Object.keys(t).filter(e=>void 0!==t[e]).sort().map(e=>`${JSON.stringify(e)}:${Kn(t[e])}`).join(",")}}`}function zn(e){return p.createHash("sha256").update(Kn(e)).digest("hex")}function Xn(e){return new it({runId:e.runId,workflowId:e.workflowId,...e.ownerUser?{owner:e.ownerUser}:{},status:e.status,...e.documentFingerprint?{documentFingerprint:e.documentFingerprint}:{},...void 0!==e.result?{result:Jn(e.result)}:{},...e.error?{error:Jn(e.error)}:{},createdAt:new Date(e.createdAt),...e.startedAt?{startedAt:new Date(e.startedAt)}:{},...e.finishedAt?{finishedAt:new Date(e.finishedAt)}:{}})}function Jn(e){if(null!=e)return JSON.parse(JSON.stringify(e))}class Yn{constructor(e,t={}){this.sequences=new Map,this.chains=new Map,this.store=e,this.limits={...D,...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 Qn{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={...D,...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 a=this.runExecution({...e},t,o,...n).catch(async t=>{const o=Zn(t);try{await this.emitTerminal({...e},S.WORKFLOW_FAILED,o)}catch{}return await this.finalize({...e},"failed",void 0,o,...n)});return this.completions.set(e.runId,a),a}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 a,i,s=!1;const d=this.engine.observe({refresh:async t=>{t.runId===r&&(t.error&&(a=t.error),P((await this.publisher.publish(this.envelopeOf(e,t))).type)?s=!0:t.type===S.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 a=t,await this.emitTerminal(e,S.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=Zn(t);return a=o,s||(await this.emitTerminal(e,S.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 a=t,s||(await this.emitTerminal(e,S.WORKFLOW_CANCELLED,t),s=!0),await this.finalize(e,"cancelled",void 0,t,...n)}try{i=await this.engine.execute(d,o,{runId:r,abortSignal:this.controllers.get(r)?.signal,metadata:{documentFingerprint:l}},...n)}catch(e){a=Zn(e)}const c=this.abortReason(r);let u,p;return"timeout"===c?(u="failed",p=a??{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=a):i?.status===O.SUCCEEDED?u="succeeded":i?.status===O.CANCELLED?(u="cancelled",p=a):(u="failed",p=a??Zn(new _t(i?`Graph run '${r}' failed`:`Graph run '${r}' failed without a result`,"GRAPH_RUN_FAILED",{runId:r}))),s||await this.emitTerminal(e,"succeeded"===u?S.WORKFLOW_COMPLETED:"cancelled"===u?S.WORKFLOW_CANCELLED:S.WORKFLOW_FAILED,p),await this.finalize(e,u,i,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:re(t.payload)?t.payload:{nonSerializable:!0},error:t.error,parentRunId:t.parentRunId,path:t.path}}}function Zn(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+""}}function er(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 tr(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&Re(e.document)&&!Re(e)}function or(e){return JSON.parse(JSON.stringify(e))}function nr(e){if(null==e)return 0;let t;try{t=e.getTime()}catch{return 0}return Number.isFinite(t)?t:0}e.GraphWorkflowService=class extends s.ModelService{constructor(e){super(st),this.catalogue=e}get limits(){return{...cn,...un.graph.workflows.limits??{}}}get allowAnonymousAccess(){return!0===un.graph.workflows.allowAnonymousAccess}async saveDocument(e,t,...o){const{ctx:n,ctxArgs:r}=(await this.logCtx(o,"saveDocument",!0)).for(this.saveDocument);if(!Re(t))throw new a.ValidationError("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.ValidationError(`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 xt(i.issues);const s=er(n),d=await this.readExistingForWrite(e,r);d&&this.assertWriteOwnership(e,d,s);const l=new Date;if(d)return d.name=t.name,d.document=or(t),d.updatedAt=l,this.update(d,...r);const c=new st({workflowId:e,name:t.name,document:or(t),...s?{owner:s}:{},updatedAt:l});return this.create(c,...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 s.ForbiddenError)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 a.NotFoundError(`No graph workflow found for workflowId '${e}'`);if(this.assertOwnership(e,r,er(o)),r.document)return or(r.document);throw new a.NotFoundError(`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",s.OrderDirection.ASC,...o),r=er(t);return n.filter(e=>Bn(e,r,{allowAnonymousAccess:this.allowAnonymousAccess})).sort((e,t)=>nr(t.updatedAt)-nr(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 a.NotFoundError(`No graph workflow found for workflowId '${e}'`);return this.assertOwnership(e,r,er(o)),r}async validateDocument(e,...t){const{ctx:o}=(await this.logCtx(t,"validateDocument",!0)).for(this.validateDocument);return await Un(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(!ae(t))throw new a.ValidationError("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(!tr(t))throw new a.ValidationError("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=er(n),s=await this.readExistingForWrite(e,r);s&&this.assertWriteOwnership(e,s,i);const d=new Date;if(s)return s.snapshot=t,await this.applyCanonicalWrapper(s,t,n),s.updatedAt=d,this.update(s,...r);const l=new st({workflowId:e,snapshot:t,...i?{owner:i}:{},updatedAt:d});return await this.applyCanonicalWrapper(l,t,n),this.create(l,...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,er(o)),t}catch{return null}}async readExistingForWrite(e,t){try{return await this.read(e,...t)}catch(e){if(e instanceof a.NotFoundError)return null;throw e}}assertOwnership(e,t,o){Hn(t??null,o??null,{allowAnonymousAccess:this.allowAnonymousAccess,resourceKind:"Graph workflow",resourceId:e})}assertWriteOwnership(e,t,o){qn(t??null,o??null,{resourceKind:"Graph workflow",resourceId:e})}async applyCanonicalWrapper(e,t,o){if(!tr(t))return;if(t.document.id!==e.workflowId)throw new a.ValidationError(`Document id '${t.document.id}' does not match the workflow id '${e.workflowId}' from the request path`);const n=await Un(t.document,{limits:this.limits,...this.catalogue?{catalogue:this.catalogue}:{}},o);if(!n.valid)throw new xt(n.issues);e.document=or(t.document),e.name=t.document.name}},e.GraphWorkflowService=i.__decorate([s.service(st),i.__metadata("design:paramtypes",[Function])],e.GraphWorkflowService),e.GraphRunModelService=class extends s.ModelService{constructor(){super(it)}async saveRun(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"saveRun",!0)).for(this.saveRun),n=Xn(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)}},e.GraphRunModelService=i.__decorate([s.service(it),i.__metadata("design:paramtypes",[])],e.GraphRunModelService),e.GraphNodeModelService=class extends s.ModelService{constructor(){super(dt)}async upsertManifest(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"upsertManifest",!0)).for(this.upsertManifest),n=(e=>new dt({kind:e.kind,name:e.display?.name,category:e.display?.category,group:e.display?.group,description:e.display?.description,manifest:Me(Le(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",s.OrderDirection.ASC,...t)}async listManifests(...e){return(await this.listNodes(...e)).map(e=>(e=>{if(!e.manifest)throw new a.ValidationError(`Graph node row '${e.kind}' has no manifest to convert`);return Me(Le(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 a.NotFoundError(`Graph node kind '${e}' is not registered`)}}},e.GraphNodeModelService=i.__decorate([s.service(dt),i.__metadata("design:paramtypes",[])],e.GraphNodeModelService),e.ConditionExpressionEvaluator=eo,e.DEFAULT_GRAPH_WORKFLOW_DOCUMENT_LIMITS=cn,e.DEFAULT_GRAPH_WORKFLOW_VALIDATION_LIMITS=Go,e.DEFAULT_PINNING_METADATA=Eo,e.GRAPH_AGENT_NODES=gn,e.GRAPH_BOUNDARY_NODES=Rn,e.GRAPH_BUILT_IN_NODE_CLASSES_BY_KIND=Pn,e.GRAPH_BUILT_IN_NODE_MANIFESTS=In,e.GRAPH_BUILT_IN_NODE_MANIFESTS_BY_KIND=On,e.GRAPH_CODE_DEFAULT_LANGUAGE=fn,e.GRAPH_CODE_DEFAULT_TIMEOUT_MS=1e3,e.GRAPH_CODE_LANGUAGES=hn,e.GRAPH_CODE_MAX_TIMEOUT_MS=mt,e.GRAPH_DEFAULT_CONCURRENCY=4,e.GRAPH_DEFAULT_MAX_FOREACH_ITERATIONS=1e3,e.GRAPH_DEFAULT_MAX_LOOP_ITERATIONS=100,e.GRAPH_DOCUMENT_FORBIDDEN_FIELD_KEYS=Lo,e.GRAPH_FLOW_CONTROL_NODES=xn,e.GRAPH_LOCAL_EXECUTION_BACKEND=ht,e.GRAPH_LOOP_KIND={FOREACH:"core.loop.foreach",WHILE:"core.loop.while",UNTIL:"core.loop.until"},e.GRAPH_LOOP_NODES=Dn,e.GRAPH_MAX_FOREACH_ITERATIONS=gt,e.GRAPH_MAX_LOOP_ITERATIONS=ft,e.GRAPH_PINNING_METADATA_KEY="graph.pinnable",e.GRAPH_PLAIN_SECRET_KEYS=go,e.GRAPH_TRIGGER_NODES=kn,e.GRAPH_UTILITY_NODES=Sn,e.GRAPH_WORKFLOW_BOUNDARY=pt,e.GRAPH_WORKFLOW_FORBIDDEN_FIELD_KEYS=$n,e.GraphAuthValidator=qt,e.GraphBreakSignal=Ot,e.GraphConditionEvaluator=wn,e.GraphConnectionPolicyValidator=Ro,e.GraphConnectionValidationError=To,e.GraphCredentialAuthorizationError=$o,e.GraphCredentialReferenceValidator=Po,e.GraphCycleError=bt,e.GraphDocumentValidationError=Co,e.GraphEdgeInstanceValidator=Do,e.GraphEngineEventSink=Yt,e.GraphEnvironment=un,e.GraphExecutionBackendRegistry=Zt,e.GraphExecutionContext=zt,e.GraphExecutionEngine=Bo,e.GraphExecutionError=_t,e.GraphExecutionEventEmitter=St,e.GraphExecutionEventFactory=Dt,e.GraphExecutionFrame=Xt,e.GraphExecutionSnapshotMapper=class{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:O.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}}},e.GraphInputError=vt,e.GraphLoopExecutionContext=class{constructor(e,t){this.iteration=e,this.metadata=t}},e.GraphLoopLimitError=Nt,e.GraphNode=dn,e.GraphNodeInstanceValidator=xo,e.GraphNodeManifestResolver=tn,e.GraphNodeMethodNotFoundError=zo,e.GraphNodeMethodRegistry=Xo,e.GraphNodeNotFoundError=Ko,e.GraphNodeRegistrationError=Ho,e.GraphParameterValidator=mo,e.GraphPinningDependencyResolver=Oo,e.GraphPinningError=Et,e.GraphPinningPolicy=Ao,e.GraphPinningService=No,e.GraphPortError=class extends _t{constructor(e,t){super(e,"GRAPH_PORT_ERROR",t)}},e.GraphPortSchemaResolver=class{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}}},e.GraphRunCancelledError=kt,e.GraphRunEventPublisher=Yn,e.GraphRunExecutor=Qn,e.GraphRunService=class{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 Yn(o,n.limits),this.executor=new Qn(e,t,this.publisher,{onRunCompleted:n.onRunCompleted},n.limits),this.options={...n,limits:{...D,...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.ValidationError("Graph run request must carry a workflow document with an id or a saved workflowId");if(e.workflowId&&!this.options.documentResolver)throw new a.ValidationError("Graph run requests by workflowId require a document resolver");const i=o??t??"anonymous",s=this.activeByCaller.get(i)??new Set;if(s.size>=this.options.limits.maxConcurrentRuns)throw new a.ValidationError(`Graph run rejected: the configured limit of ${this.options.limits.maxConcurrentRuns} concurrent runs per caller is exhausted`);const d=this.generateRunId(),l={runId:d,workflowId:r,ownerUser:t,status:"queued",createdAt:(new Date).toISOString()};this.executor.begin(d),await this.runStore.saveRun({...l},...n);const c=this.documentProviderFor(e,t);return s.add(d),this.activeByCaller.set(i,s),this.callerKeysByRun.set(d,i),this.executor.schedule(l,c,e.inputs??{},...n).catch(()=>{}).finally(()=>this.finishActiveRun(d)),l}async getRun(e,t,...o){const n=await this.runStore.readRun(e,...o);if(!n)throw new a.NotFoundError(`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=>Bn({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 a.NotFoundError(`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 a.NotFoundError(`No graph run found for runId '${e}'`);this.assertWriteOwnership(r,o);const i=this.engine.backend,s=i.resume;if("function"!=typeof s)throw new _t(`Graph execution backend '${i.constructor?.name??"GraphExecutionBackend"}' does not support resume`,"GRAPH_RESUME_UNSUPPORTED_BACKEND",{runId:e});let d;try{d=await s.call(i,e,t,...n)}catch(e){throw(l=e)instanceof _t?new _t(l.message,l.graphCode):l}var l;const c={...d,runId:e,caller:o};return await this.publisher.publish({runId:e,workflowId:r.workflowId,type:S.WORKFLOW_RESUMED,payload:c}),c}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.ValidationError("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.ValidationError("Graph run request is ambiguous: supply either an unsaved workflow document or a saved workflowId, not both");if(!t&&!o)throw new a.ValidationError("Graph run request must supply either an unsaved workflow document or a saved workflowId");if(t&&!Re(e.workflow))throw new a.ValidationError("Graph run request carries a payload that is not a canonical GraphWorkflowDocument");if(void 0!==e.inputs&&!ae(e.inputs))throw new a.ValidationError("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.ValidationError(`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:zn(t)})}const o=e.workflowId;return async(...e)=>{const n=this.options.documentResolver;if(!n)throw new a.ValidationError("Graph run requests by workflowId require a document resolver");const r=await n.resolve(o,t,...e);return{document:r,fingerprint:zn(r)}}}assertOwnership(e,t){Hn({owner:e.ownerUser},t,{allowAnonymousAccess:!0===this.options.allowAnonymousAccess,resourceKind:"Graph run",resourceId:e.runId})}assertWriteOwnership(e,t){qn({owner:e.ownerUser},t,{resourceKind:"Graph run",resourceId:e.runId})}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new It("Cannot generate a graph run id: crypto.randomUUID is unavailable in this runtime",{runtime:typeof globalThis.crypto});return e.randomUUID()}},e.GraphStoreError=It,e.GraphTopology=vo,e.GraphTopologyError=At,e.GraphValueValidator=class{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 vt(`Missing required ${o} port '${n.name}'`);if(e&&!this.resolver.resolve(n).validate(t[n.name]))throw new vt(`Invalid value for ${o} port '${n.name}'`)}}},e.GraphWorkflowDocumentRejectedError=xt,e.GraphWorkflowDocumentValidator=Vo,e.InMemoryGraphRunEventStore=class{constructor(e={}){this.events=new Map,this.listeners=new Map,this.limits={...D,...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=>!P(e.type));if(-1===t)break;e.splice(t,1)}}},e.InMemoryGraphRunStore=class{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=>Xn(e))}release(e){this.runs.delete(e)}},e.IsolatedVmCodeSandboxEvaluator=qo,e.LocalGraphExecutionBackend=ko,e.assertGraphResourceOwnership=Hn,e.assertGraphResourceWriteOwnership=qn,e.buildGraphExecutionResult=Jt,e.builtInGraphNodeRegistrations=Tn,e.canAccessGraphResource=Bn,e.canAccessGraphResourcePayload=Wn,e.checkGraphValueAgainstSchema=uo,e.clampGraphCodeTimeoutMs=pn,e.collectLooseNodeIssues=So,e.composeGraphNamespace=Pt,e.createGraphValueRepository=bo,e.declaredGraphNodeMethods=e=>e.methods??[],e.decomposeGraphNamespace=Rt,e.decomposeGraphNamespaces=Bt,e.defineGraphNode=an,e.detectGraphCodeModeSurfaces=co,e.evaluateCodeCondition=no,e.evaluateCondition=ao,e.evaluateConditionSync=ro,e.findMalformedGraphNamespaces=Lt,e.findUngrantedGraphNamespaces=Gt,e.graphAuthDataFromRecord=jt,e.graphAuthDataOf=Ut,e.graphDocumentHasCodeMode=e=>co(e).length>0,e.graphNamespaceCovers=$t,e.graphNamespacePartsOf=Tt,e.graphNodeConfig=sn,e.graphRolesFromNamespaces=Mt,e.graphRunDocumentFingerprint=zn,e.graphWorkflowOwnerOf=er,e.isCodeCondition=to,e.isConditionExpression=oo,e.isGraphCredentialReferenceLike=ho,e.isGraphNamespaceCacheEntryValid=Ct,e.isGraphResolvedWorkflow=Mo,e.isPinnable=Io,e.mergeGraphAuthData=Wt,e.registerBuiltInGraphNodes=(e,...t)=>{for(const o of Tn())e.register(o,{},...t);return e},e.resolveGraphBackendCapabilities=Qt,e.resolveGraphDynamicPorts=Zo,e.resolveGraphNodeManifest=en,e.serializeGraphValueKey=yo,e.stripFacadeOwnedBackendConfig=Uo,e.validateGraphWorkflowDocumentAtBoundary=Un},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/logging"),require("@decaf-ts/ui-decorators"),require("@decaf-ts/decoration"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/db-decorators"),require("tslib"),require("@decaf-ts/core"),require("isolated-vm"),require("acorn"),require("acorn-walk"),require("typescript"),require("node:crypto")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/logging","@decaf-ts/ui-decorators","@decaf-ts/decoration","@decaf-ts/decorator-validation","@decaf-ts/db-decorators","tslib","@decaf-ts/core","isolated-vm","acorn","acorn-walk","typescript","node:crypto"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["as-graph"]={},e.decafTsLogging,e.decafTsUiDecorators,e.decafTsDecoration,e.decafTsDecoratorValidation,e.decafTsDbDecorators,e.tslib,e.decafTsCore,e.isolatedVm,e.acorn,e.acornWalk,e.typescript,e.node_crypto);
|
|
2
2
|
//# sourceMappingURL=as-graph.cjs.map
|