@decaf-ts/as-graph 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- 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/engine/index.cjs +1 -0
- package/lib/cjs/engine/index.cjs.map +1 -1
- package/lib/cjs/engine/loops/ConditionEvaluator.cjs +116 -0
- package/lib/cjs/engine/loops/ConditionEvaluator.cjs.map +1 -0
- package/lib/cjs/engine/loops/GraphConditionEvaluator.cjs +25 -2
- package/lib/cjs/engine/loops/GraphConditionEvaluator.cjs.map +1 -1
- package/lib/cjs/engine/loops/index.cjs +1 -0
- package/lib/cjs/engine/loops/index.cjs.map +1 -1
- package/lib/cjs/engine/runs/GraphRunService.cjs +60 -3
- package/lib/cjs/engine/runs/GraphRunService.cjs.map +1 -1
- package/lib/cjs/engine/runs/InMemoryGraphRunStore.cjs +33 -0
- package/lib/cjs/engine/runs/InMemoryGraphRunStore.cjs.map +1 -1
- package/lib/cjs/engine/runs/ownership.cjs +100 -11
- package/lib/cjs/engine/runs/ownership.cjs.map +1 -1
- package/lib/cjs/engine/services/GraphRunModelService.cjs +16 -0
- package/lib/cjs/engine/services/GraphRunModelService.cjs.map +1 -1
- package/lib/cjs/engine/services/GraphWorkflowService.cjs +122 -4
- package/lib/cjs/engine/services/GraphWorkflowService.cjs.map +1 -1
- package/lib/cjs/nest/graph/GraphRunController.cjs +208 -28
- package/lib/cjs/nest/graph/GraphRunController.cjs.map +1 -1
- package/lib/cjs/nest/graph/GraphWorkflowController.cjs +97 -14
- package/lib/cjs/nest/graph/GraphWorkflowController.cjs.map +1 -1
- package/lib/cjs/nest/graph/servingDates.cjs +53 -0
- package/lib/cjs/nest/graph/servingDates.cjs.map +1 -0
- package/lib/cjs/nest/graph/servingErrors.cjs +65 -0
- package/lib/cjs/nest/graph/servingErrors.cjs.map +1 -0
- package/lib/cjs/node/flow/if/node.cjs +27 -9
- package/lib/cjs/node/flow/if/node.cjs.map +1 -1
- package/lib/cjs/node/flow/loop/until/node.cjs +5 -2
- package/lib/cjs/node/flow/loop/until/node.cjs.map +1 -1
- package/lib/cjs/node/flow/loop/while/node.cjs +8 -2
- package/lib/cjs/node/flow/loop/while/node.cjs.map +1 -1
- package/lib/cjs/node/flow/switch/node.cjs +2 -37
- package/lib/cjs/node/flow/switch/node.cjs.map +1 -1
- package/lib/cjs/ram/GraphRunStore.cjs +14 -0
- package/lib/cjs/ram/GraphRunStore.cjs.map +1 -1
- package/lib/esm/engine/index.js +1 -0
- package/lib/esm/engine/index.js.map +1 -1
- package/lib/esm/engine/loops/ConditionEvaluator.js +108 -0
- package/lib/esm/engine/loops/ConditionEvaluator.js.map +1 -0
- package/lib/esm/engine/loops/GraphConditionEvaluator.js +25 -2
- package/lib/esm/engine/loops/GraphConditionEvaluator.js.map +1 -1
- package/lib/esm/engine/loops/index.js +1 -0
- package/lib/esm/engine/loops/index.js.map +1 -1
- package/lib/esm/engine/runs/GraphRunService.js +61 -4
- package/lib/esm/engine/runs/GraphRunService.js.map +1 -1
- package/lib/esm/engine/runs/InMemoryGraphRunStore.js +33 -0
- package/lib/esm/engine/runs/InMemoryGraphRunStore.js.map +1 -1
- package/lib/esm/engine/runs/ownership.js +97 -11
- package/lib/esm/engine/runs/ownership.js.map +1 -1
- package/lib/esm/engine/services/GraphRunModelService.js +16 -0
- package/lib/esm/engine/services/GraphRunModelService.js.map +1 -1
- package/lib/esm/engine/services/GraphWorkflowService.js +124 -6
- package/lib/esm/engine/services/GraphWorkflowService.js.map +1 -1
- package/lib/esm/nest/graph/GraphExecutionModule.js.map +1 -1
- package/lib/esm/nest/graph/GraphRunController.js +209 -29
- package/lib/esm/nest/graph/GraphRunController.js.map +1 -1
- package/lib/esm/nest/graph/GraphWorkflowController.js +98 -15
- package/lib/esm/nest/graph/GraphWorkflowController.js.map +1 -1
- package/lib/esm/nest/graph/servingDates.js +49 -0
- package/lib/esm/nest/graph/servingDates.js.map +1 -0
- package/lib/esm/nest/graph/servingErrors.js +60 -0
- package/lib/esm/nest/graph/servingErrors.js.map +1 -0
- package/lib/esm/node/flow/if/node.js +27 -9
- package/lib/esm/node/flow/if/node.js.map +1 -1
- package/lib/esm/node/flow/loop/until/node.js +5 -2
- package/lib/esm/node/flow/loop/until/node.js.map +1 -1
- package/lib/esm/node/flow/loop/while/node.js +8 -2
- package/lib/esm/node/flow/loop/while/node.js.map +1 -1
- package/lib/esm/node/flow/switch/node.js +2 -37
- package/lib/esm/node/flow/switch/node.js.map +1 -1
- package/lib/esm/ram/GraphRunStore.js +14 -0
- package/lib/esm/ram/GraphRunStore.js.map +1 -1
- package/lib/esm/shared/graph/document/GraphFlowBuilder.js.map +1 -1
- package/lib/types/engine/index.d.cts +1 -0
- package/lib/types/engine/index.d.mts +1 -0
- package/lib/types/engine/loops/ConditionEvaluator.d.cts +87 -0
- package/lib/types/engine/loops/ConditionEvaluator.d.mts +87 -0
- package/lib/types/engine/loops/GraphConditionEvaluator.d.cts +27 -7
- package/lib/types/engine/loops/GraphConditionEvaluator.d.mts +27 -7
- package/lib/types/engine/loops/index.d.cts +1 -0
- package/lib/types/engine/loops/index.d.mts +1 -0
- package/lib/types/engine/runs/GraphRunService.d.cts +41 -1
- package/lib/types/engine/runs/GraphRunService.d.mts +41 -1
- package/lib/types/engine/runs/InMemoryGraphRunStore.d.cts +29 -0
- package/lib/types/engine/runs/InMemoryGraphRunStore.d.mts +29 -0
- package/lib/types/engine/runs/ownership.d.cts +89 -4
- package/lib/types/engine/runs/ownership.d.mts +89 -4
- package/lib/types/engine/runs/types.d.cts +12 -1
- package/lib/types/engine/runs/types.d.mts +12 -1
- package/lib/types/engine/services/GraphRunModelService.d.cts +13 -0
- package/lib/types/engine/services/GraphRunModelService.d.mts +13 -0
- package/lib/types/engine/services/GraphWorkflowService.d.cts +52 -2
- package/lib/types/engine/services/GraphWorkflowService.d.mts +52 -2
- package/lib/types/engine/types.d.cts +11 -4
- package/lib/types/engine/types.d.mts +11 -4
- package/lib/types/nest/graph/GraphExecutionModule.d.cts +6 -1
- package/lib/types/nest/graph/GraphExecutionModule.d.mts +6 -1
- package/lib/types/nest/graph/GraphRunController.d.cts +69 -14
- package/lib/types/nest/graph/GraphRunController.d.mts +69 -14
- package/lib/types/nest/graph/GraphWorkflowController.d.cts +50 -17
- package/lib/types/nest/graph/GraphWorkflowController.d.mts +50 -17
- package/lib/types/nest/graph/servingDates.d.cts +35 -0
- package/lib/types/nest/graph/servingDates.d.mts +35 -0
- package/lib/types/nest/graph/servingErrors.d.cts +42 -0
- package/lib/types/nest/graph/servingErrors.d.mts +42 -0
- package/lib/types/node/flow/if/node.d.cts +20 -8
- package/lib/types/node/flow/if/node.d.mts +20 -8
- package/lib/types/node/flow/loop/until/node.d.cts +4 -1
- package/lib/types/node/flow/loop/until/node.d.mts +4 -1
- package/lib/types/node/flow/loop/while/node.d.cts +4 -1
- package/lib/types/node/flow/loop/while/node.d.mts +4 -1
- package/lib/types/ram/GraphRunStore.d.cts +12 -0
- package/lib/types/ram/GraphRunStore.d.mts +12 -0
- package/lib/types/shared/graph/document/GraphFlowBuilder.d.cts +5 -5
- package/lib/types/shared/graph/document/GraphFlowBuilder.d.mts +5 -5
- package/lib/types/shared/graph/types.d.cts +8 -1
- package/lib/types/shared/graph/types.d.mts +8 -1
- package/package.json +1 -1
package/dist/as-graph.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{logParameterRegistry as e,Logging as t,LoggedEnvironment as o}from"@decaf-ts/logging";import{RenderingEngine as n,uimodel as i,uielement as r,uilistprop as a,uilistmodel as s,hidden as d}from"@decaf-ts/ui-decorators";import{Metadata as l,Decoration as c,apply as u,metadata as p,propMetadata as h,description as f,prop as g,DefaultFlavour as m}from"@decaf-ts/decoration";import{ValidationKeys as y,Model as w,required as b,type as v,date as I,model as E,option as N,min as O,max as A}from"@decaf-ts/decorator-validation";import{ValidationError as x,InternalError as k,NotFoundError as _}from"@decaf-ts/db-decorators";import{__decorate as D,__metadata as P}from"tslib";import{pk as $,column as S,index as R,table as C,BaseModel as T,ForbiddenError as L,Context as j,AuthorizationError as M,service as G,Service as U,repository as F,Repository as B,ClientBasedService as q,Adapter as V,ModelService as W}from"@decaf-ts/core";import H from"isolated-vm";import*as K from"acorn";import*as z from"acorn-walk";import*as J from"typescript";import{createHash as X}from"node:crypto";var Y,Q;y.REQUIRED,y.MIN,y.MIN_LENGTH,y.MAX,y.MAX_LENGTH,y.PATTERN,y.URL,y.STEP,y.DATE,y.EMAIL,y.PASSWORD,y.EQUALS,y.DIFF,y.LESS_THAN,y.LESS_THAN_OR_EQUAL,y.GREATER_THAN,y.GREATER_THAN_OR_EQUAL,(e=>{e.GRAPH="graph",e.NODE="graph.node",e.EDGE="graph.edge",e.PORT="graph.port",e.STATE="graph.state"})(Y||(Y={})),(e=>{e.INPUT="input",e.OUTPUT="output",e.CONNECTION="connection"})(Q||(Q={}));const Z={};function ee(e,t={}){let o=e.width??96,n=e.height??96;for(const i of e.sizeRules??[]){if("parameterCount"!==i.type)continue;const e=t[i.parameter]??0;e>0&&("width"===i.dimension?o+=e*i.perItem:n+=e*i.perItem)}return{width:o,height:n}}function te(e,t){Z[e]=t}function oe(e,t,o){const n=t?Z[t]:void 0;return n?.color?n.color:e||"#64748b"}function ne(e,t,o){const n=t?Z[t]:void 0;return n?.icon?n.icon:e||"ti-pointer"}const ie=["skip","passThroughFirstInput","emitDefaults"];function re(e){return ie.includes(e)}var ae,se,de,le;(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"})(ae||(ae={})),(e=>{e.IDLE="idle",e.RUNNING="running",e.BLOCKED="blocked",e.SUCCEEDED="succeeded",e.FAILED="failed",e.SKIPPED="skipped"})(se||(se={})),(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"})(de||(de={})),(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.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"})(le||(le={}));const ce={maxRequestBytes:4e6,maxConcurrentRuns:32,maxEventsPerRun:1e4,maxEventPayloadBytes:256e3,executionTimeoutMs:6e5,eventReplayWindowMs:3e5},ue=[le.WORKFLOW_COMPLETED,le.WORKFLOW_FAILED,le.WORKFLOW_CANCELLED];function pe(e){return ue.includes(e)}function he(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function fe(e){const t=l.constr(e);if("function"==typeof t)return t;const o=e.constructor;return"function"==typeof o?o:e}function ge(e){if(null!=e)return"string"==typeof e?e:e+""}function me(e,t,o){return ge(e?.props?.label??e?.props?.name)??ge(t?.name)??o??""}function ye(e,t,o){const n=ve(e,t);if(n?.model&&"function"==typeof n.model&&w.isModel(n.model))return n.model;const i=l.type(e,t);if("function"==typeof i&&w.isModel(i))return i;const r=l.getPropDesignTypes?.(e,t)?.designTypes||[];for(const e of r)if("function"==typeof e&&w.isModel(e))return e;const a=o?.[y.TYPE]?.customTypes||[];for(const e of a)if("function"==typeof e&&w.isModel(e))return e}function we(e,t){const o=[t,e.path??e.property].filter(Boolean).join(".");return{...e,path:o,children:e.children?.map(e=>we(e,o))}}function be(e){const t=fe(e);return l.get(t,Y.NODE)}function ve(e,t){const o=fe(e);return l.get(o,l.key(Y.PORT,t+""))}function Ie(e,t,o,n=new Set){const i=ve(e,t);if(!i?.schema)return;const r=ye(e,t,l.validationFor(e,t));if(!r)return;if(n.has(r))return[];const a=new Set(n);return a.add(e),a.add(r),Oe(r,a).filter(e=>e.direction===o)}function Ee(e,t,o=new Set){const n=ve(e,t);if(!n)return;const i=l.validationFor(e,t),r=ye(e,t,i);if(n.schema&&r)return;const a=w.uiElementOf(e,t)||void 0,s=w.uiDecorationOf(e,t,"uiprop"),d=l.type(e,t),c=ge(n.type??i?.[y.TYPE]?.customTypes?.[0]?.name??a?.props?.type??s?.type??d?.name),u=(n.expand||r&&!o.has(r))&&r?(()=>{const n=new Set(o);return n.add(e),n.add(r),Oe(r,n).map(e=>we(e,t))})():void 0;return{property:t,path:t,direction:n.direction,name:t,label:me(a,s,t),type:c?.toLowerCase(),required:!!i?.[y.REQUIRED],hidden:!!w.uiIsHidden(e,t),designType:d?.name,element:a,prop:s,validation:i,graph:n,connectionRules:n.connectionRules,composite:!!u?.length,children:u,model:r?.name}}function Ne(e){return Oe(fe(e))}function Oe(e,t=new Set){const o=l.properties(e)||[],n=[];for(const i of o){const o=i+"",r=ve(e,o);if(r?.schema){const i=Ie(e,o,r.direction,t);if(i){n.push(...i);continue}}const a=Ee(e,o,t);a&&n.push(a)}return n}function Ae(e){return e.flatMap(e=>e.children&&e.children.length?Ae(e.children):[e])}function xe(e){const t=fe(e),o=w.uiModelOf(t),n=be(t)||{},i=o?.tag||t.name,r=Ne(t),a=((e,t)=>{const o=t.portGroups||[],n=new Map(o.map(e=>[e.property,e])),i=[],r=l.properties(e)||[];for(const t of r){const o=t+"",r=ve(e,o);if(!r?.schema)continue;if(!ye(e,o,l.validationFor(e,o)))continue;const a=n.get(o);i.push(a?{...a,toggle:a.toggle??"all"}:{property:o,toggle:"all"})}for(const e of o)i.some(t=>t.property===e.property)||i.push(e);return i.length?i:void 0})(t,n),s=n.namespaces?.length?n.namespaces:(e=>{if(null==e)return[];let t,o=e;try{o=l.constr(e)}catch{o=e}try{t=l.get(o,"auth-namespace")}catch{t=void 0}return he(t)??[]})(t),d=s.length?s:void 0;return{name:t.name,tag:i,kind:n.kind||i,category:n.category,color:n.color,effectiveColor:oe(n.color,n.category),group:n.group,height:n.height,icon:n.icon,effectiveIcon:ne(n.icon,n.category),labels:n.labels||[],maxChildren:n.maxChildren,minWidth:n.minWidth,width:n.width,shape:n.shape,cornerRadius:n.cornerRadius,sizeRules:n.sizeRules,props:o?.props,ui:o,graph:n,ports:r,portGroups:a,namespaces:d}}const ke=new Set,_e=new Set;function De(e,t,o){return c.for(Y.NODE).define({decorator:(e,t,o)=>{const n={kind:t?.kind||e,...t};return t=>{const r=u(i(e,o),p(Y.NODE,n))(t);var a;return a=t,ke.add(a),r}},args:[e,t,o]}).apply()}function Pe(e,t){return c.for(Y.PORT).define({decorator:(e,t)=>(o,n)=>{const i={direction:e,...t};return u(h(l.key(Y.PORT,n),i))(o,n)},args:[e,t]}).apply()}function $e(e){return Pe(Q.INPUT,{...e,schema:!0})}function Se(e){return Pe(Q.OUTPUT,{...e,schema:!0})}function Re(e){return Pe(Q.CONNECTION,e)}n.prototype.renderAsNode=(e,t,...o)=>xe(e),l.nodes=(()=>[...ke]).bind(l),l.workflows=(()=>[..._e]).bind(l);const Ce=["__proto__","prototype","constructor"];function Te(e){return Ce.includes(e)}function Le(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function je(e){return null===e||"string"==typeof e||"number"==typeof e&&Number.isFinite(e)||"boolean"==typeof e}function Me(e){return!!je(e)||(Array.isArray(e)?e.every(e=>Me(e)):!!Le(e)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&!Te(t)&&Me(e[t])))}function Ge(e){if(void 0===e)return!1;if("number"==typeof e)return Number.isFinite(e);if("function"==typeof e)return!1;if(Me(e))return!0;if(Array.isArray(e))return e.every(e=>Ge(e));if(Le(e)){const t=Reflect.ownKeys(e);for(const o of t){if("string"!=typeof o)return!1;if(Te(o))return!1;if(!Ge(e[o]))return!1}return!0}return!1}function Ue(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>Ue(e));const t={};for(const[o,n]of Object.entries(e))t[o]=Ue(n);return t}const Fe={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"},Be={date:"date",datetime:"date-time","date-time":"date-time",duration:"duration"};function qe(e){return e?Fe[e.toLowerCase()]??"any":"any"}function Ve(e,t){const o=e[t];if(o&&"object"==typeof o)return o.value}function We(e,t){const o=Ve(e,t);return"number"==typeof o&&Number.isFinite(o)?o:void 0}function He(e,t,o){const n=e??{},i=(e=>{const t=Ve(e,y.ENUM);if(Array.isArray(t)&&t.every(je))return t})(n);if(i)return{type:"enum",values:i};const r=(e=>{const t=e[y.TYPE],o=t?.customTypes?.[0],n="function"==typeof o?o.name:o?.name;if(n)return n})(n)??o;return r?{type:"model",name:r}:((e,t)=>{switch(qe(e)){case"string":{const t=(e=>{if(e)return Be[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=We(t,y.MIN),i=We(t,y.MAX);return void 0!==n&&(o.min=n),void 0!==i&&(o.max=i),o}case"boolean":return{type:"boolean"};case"array":return((e,t)=>{const o={type:"array",items:Ke(e,t)},n=We(e,y.MIN),i=We(e,y.MAX);return void 0!==n&&(o.minItems=n),void 0!==i&&(o.maxItems=i),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 Ke(e,t){if((e=>{const t=e[y.LIST];return!!t?.clazz?.length})(e))return{type:"model",name:ze(e)};const o=Ve(e,y.TYPE);if("string"==typeof o){const e=qe(o);return"model"===e?{type:"model",name:o}:{type:e}}if(t&&"array"!==t){const e=qe(t);return"model"===e?{type:"model",name:t}:{type:e}}return{type:"any"}}function ze(e){const t=e[y.LIST],o=t?.clazz?.[0];if("function"!=typeof o)return"any";if(o.name)return o.name;try{const e=o();if("function"==typeof e&&e.name)return e.name}catch{return"any"}return"any"}function Je(e){return"workflow"===e.scope}function Xe(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 Qe(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&&Me(t)}return"expression"===t&&2===Object.keys(e).length&&"string"==typeof e.expression}const Ze=["any","string","number","boolean","array","object","enum","model"];function et(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&(e=>Ze.includes(e))(e.type)}function tt(e,t={seen:[]}){if(t.seen.includes(e))throw new x(`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 x("Document 'id' is required and must be a non-empty string");if("string"!=typeof e.name||!e.name)throw new x("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 x("Workflow port 'id' is required and must be a non-empty string");if(o.has(t.id))throw new x(`Workflow port '${t.id}' is declared more than once; workflow port ids must be unique`);if(void 0!==t.schema&&!et(t.schema))throw new x(`Workflow port '${t.id}' schema must be a valid GraphValueSchema`);o.add(t.id)}const n={seen:[...t.seen,e]},i=new Set;for(const t of e.nodes)ot(t,i);for(const t of e.nodes)t.loop&&nt(t,t.loop,n),t.errorBoundary&&it(t,t.errorBoundary,n);const r=new Set;for(const t of e.edges)at(t,r);for(const t of e.edges)st(t.source,0,o,i,`Edge '${t.id}' source`),st(t.target,0,o,i,`Edge '${t.id}' target`);if(void 0!==e.settings&&!Ge(e.settings))throw new x("Document settings must be JSON-safe (a map of JSON-safe values)");if(void 0!==e.metadata&&!Ge(e.metadata))throw new x("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&&!Ge(e.ui))throw new x("Document ui must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed")}function ot(e,t){if("string"!=typeof e.id||!e.id)throw new x("Node 'id' is required and must be a non-empty string");if(t.has(e.id))throw new x(`Node id '${e.id}' is declared more than once; node ids must be unique`);if("string"!=typeof e.kind||!e.kind)throw new x(`Node '${e.id}' must declare a non-empty string 'kind'`);if(void 0===e.parameters||null===e.parameters)throw new x(`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 x(`Node '${e.id}' input binding key '${t}' is not allowed (unsafe prototype-pollutant key)`);if(!Qe(o))throw new x(`Node '${e.id}' input binding for '${t}' must be a valid GraphInputBinding (edge, literal, or expression)`);if("literal"===o.mode&&!Ge(o.value))throw new x(`Node '${e.id}' literal binding for '${t}' must contain JSON-safe values`);if("expression"===o.mode&&!o.expression)throw new x(`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 x(`Node '${e.id}' output binding key '${t}' is not allowed (unsafe prototype-pollutant key)`);if(!o||"object"!=typeof o||Array.isArray(o))throw new x(`Node '${e.id}' output binding for '${t}' must be an object with enabled and alias settings`)}if(!Ge(e.parameters))throw new x(`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 x(`Node '${e.id}' state must be an object when present`);if(!Ge(e.state))throw new x(`Node '${e.id}' state must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`)}}function nt(e,t,o){if(!t.body||"object"!=typeof t.body)throw new x(`Node '${e.id}' loop configuration requires a body document`);if(tt(t.body,o),!(void 0===t.maxIterations||Number.isFinite(t.maxIterations)&&t.maxIterations>0))throw new x(`Node '${e.id}' loop maxIterations must be a positive number`);if(void 0!==t.timeoutMs&&("number"!=typeof t.timeoutMs||0>=t.timeoutMs))throw new x(`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 x(`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 x(`Node '${e.id}' loop mapping key '${t}' is not allowed (unsafe prototype-pollutant key)`);rt(n,e.id,t)}}function it(e,t,o){if(!t.try||"object"!=typeof t.try)throw new x(`Node '${e.id}' error-boundary configuration requires a try body document`);tt(t.try,o);for(const[n,i]of[["catch",t.catch],["finally",t.finally]])if(void 0!==i){if(!i||"object"!=typeof i)throw new x(`Node '${e.id}' error-boundary ${n} body must be a document`);tt(i,o)}}function rt(e,t,o){if(!e||"object"!=typeof e)throw new x(`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 x(`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 x(`Node '${t}' loop mapping '${o}' referencing a node must reference a node id and a port`);break;case"literal":if(!Ge(e.value))throw new x(`Node '${t}' loop mapping '${o}' literal references must be JSON-safe values`);break;case"expression":if("string"!=typeof e.expression||!e.expression)throw new x(`Node '${t}' loop mapping '${o}' expression references must be non-empty expressions`);break;default:throw new x(`Node '${t}' loop mapping '${o}' must use a workflow, node, literal, or expression reference source`)}}function at(e,t){if("string"!=typeof e.id||!e.id)throw new x("Edge 'id' is required and must be a non-empty string");if(t.has(e.id))throw new x(`Edge id '${e.id}' is declared more than once; edge ids must be unique`);if(!Ye(e.source))throw new x(`Edge '${e.id}' source endpoint is not a valid GraphEndpoint`);if(!Ye(e.target))throw new x(`Edge '${e.id}' target endpoint is not a valid GraphEndpoint`);if("data"!==e.type&&"connection"!==e.type)throw new x(`Edge '${e.id}' type '${e.type+""}' is not a valid edge type (data or connection are allowed)`);if(t.add(e.id),!Ge(e))throw new x(`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 st(e,t,o,n,i){if(Je(e)){if(!o.has(e.port))throw new x(`${i} references workflow port '${e.port}' which is not declared on the document`)}else if(Xe(e)){if(!n.has(e.nodeId))throw new x(`${i} references node '${e.nodeId}' which is not part of the document`);if("string"!=typeof e.port||!e.port)throw new x(i+" node endpoints must reference a non-empty port identifier")}}const dt=["expression","template"],lt=["javascript","typescript","json","text"];function ct(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return!(!(e=>dt.includes(e))(t.mode)||"string"!=typeof t.expression||!t.expression||void 0!==t.language&&!(e=>lt.includes(e))(t.language)||void 0!==t.metadata&&!Me(t.metadata))}function ut(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 pt(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 ht=["trigger","loop","branching","stateful","retryable","cancellable","parallel","resource"];function ft(e){return ht.includes(e)}function gt(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 x("Graph node manifest does not conform to the required shape");if(!Ge(e))throw new x("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 mt=["loadOptions","listSearch","resourceLocator","resourceMapping","validateParameter","action"];function yt(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.name&&(e=>mt.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 wt(e){const t=e.element?.props?.value,o=t??e.prop?.value??e.validation?.defaultValue;if(void 0!==o&&"function"!=typeof o&&Ge(o))try{return JSON.parse(JSON.stringify(o))}catch{return}}function bt(e){if(e.type&&e.type in Be)return{type:"string",format:Be[e.type]};const t=(e=>{for(const t of[e.graph?.type,e.element?.props?.type,e.prop?.type])if("string"==typeof t&&"any"!==qe(t))return t})(e);return t?He((e=>{if(!e)return;const t=Object.entries(e).filter(([e])=>e!==y.TYPE);return Object.fromEntries(t)})(e.validation),t):He(e.validation,e.type,e.model)}function vt(e){const t={};for(const[o,n]of Object.entries(e.graph?.metadata??{}))Ge(n)&&(t[o]=JSON.parse(JSON.stringify(n)));return Object.keys(t).length?t:void 0}function It(e){switch(e){case"output":return"output";case"connection":return"connection";default:return"input"}}function Et(e){const t=e.graph?.handle;return"connection"!==e.direction&&"string"==typeof t&&t?t:e.path??e.property}function Nt(e,t){const o={id:Et(e),label:e.label,direction:It(e.direction),schema:bt(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 i=e.graph?.handle;"string"==typeof i&&(o.handle=i);const r=Rt(e.graph?.connectionRules)??t;r&&(o.connectionPolicy=r);const a=(e=>{const t=e.element;if(!t||!Ge(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)?Ue(n):{}}})(e);a&&(o.element=a);const s=vt(e);return s&&(o.metadata=s),o}function Ot(e){const t={type:"string",id:Et(e),label:e.label,required:e.required};if(e.hidden)return((e,t)=>{const o={...t,type:"hidden"},n=wt(e);return void 0!==n&&(o.defaultValue=n),At(o)})(e,t);const o=wt(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 i=vt(e);if(i&&(t.metadata=i),(e=>{const t=_t(e);return"code"===t||"code-editor"===t})(e))return At({...t,type:"code",language:$t(e)});const r=bt(e);switch(r.type){case"number":{const o={...t,type:"number",integer:r.integer,min:r.min,max:r.max},n=kt(e.validation?.step);return void 0!==n&&(o.step=n),At(o)}case"boolean":return At({...t,type:"boolean"});case"enum":return At({...t,type:"options",options:r.values.map(e=>({value:e,label:e+""}))});case"array":{const e={...t,type:"collection"};return void 0!==r.maxItems&&(e.maxItems=r.maxItems),At(e)}case"object":case"model":return At({...t,type:"object"});default:return At({...t,type:"string",multiline:!!Dt(e)||void 0,pattern:xt(e.validation?.pattern),minLength:kt(e.validation?.minlength),maxLength:kt(e.validation?.maxlength)})}}function At(e){const t=e;for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return e}function xt(e){const t=e?.value;return"string"==typeof t?t:void 0}function kt(e){const t=e?.value;return"number"==typeof t&&Number.isFinite(t)?t:void 0}function _t(e){const t=e.element?.tag;return"string"==typeof t&&t?t:void 0}function Dt(e){return"textarea"===_t(e)||"textarea"===(e=>{const t=e.element?.props?.type;return"string"==typeof t?t:void 0})(e)}const Pt=["javascript","typescript","json","text"];function $t(e){const t=e.element?.props?.language;return"string"==typeof t&&Pt.includes(t)?t:"javascript"}function St(e,t){const o={name:t.name??e.name},n=e.graph?.metadata?.description??void 0;"string"==typeof n&&n&&(o.description=n);const i=t.category??e.category;"string"==typeof i&&i&&(o.category=i),"string"==typeof e.group&&e.group&&(o.group=e.group),Array.isArray(e.labels)&&(o.labels=e.labels.slice());const r=((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 r&&(o.icon=r),"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 Rt(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 i=t.blockedKinds;Array.isArray(i)&&i.every(e=>"string"==typeof e)&&(o.blockedNodeKinds=i);const r=t.maxConnections;return"number"==typeof r&&Number.isFinite(r)&&(o.maxConnections=r),Object.keys(o).length?o:void 0}function Ct(e,t={}){const o="function"==typeof e?e:e.constructor;if(!be(o))throw new x(`Node '${o?.name??e+""}' is not decorated with @node and cannot produce a manifest`);const n=xe(o),i=Ae(Ne(o)),r=[],a=[],s=[],d=[],l=Rt(n.graph?.connectionRules);for(const e of i)("connection"===e.direction?s:"output"===e.direction?a:r).push(Nt(e,l)),"input"===e.direction&&d.push(Ot(e));const c={kind:t.kind??n.kind??n.name,display:St(n,t),inputs:r,outputs:a,parameters:d};return s.length&&(c.connections=s),n.namespaces?.length&&(c.namespaces=n.namespaces.slice()),gt(c),c}let Tt=class extends T{constructor(e){super(e)}};D([$({type:String,generated:!1}),f("Unique graph run id"),r("ngx-decaf-crud-field",{label:"graph.run.id.label",readonly:!0}),P("design:type",String)],Tt.prototype,"runId",void 0),D([S(),b(),R(),f("Workflow document id the run executes"),a("workflowId"),r("ngx-decaf-crud-field",{label:"graph.run.workflowId.label"}),P("design:type",String)],Tt.prototype,"workflowId",void 0),D([S(),f("Owning user; absent for anonymous callers"),r("ngx-decaf-crud-field",{label:"graph.run.owner.label"}),P("design:type",String)],Tt.prototype,"owner",void 0),D([S(),b(),v(String),R(),f("Current run lifecycle status"),a("status"),r("ngx-decaf-crud-field",{label:"graph.run.status.label",readonly:!0}),P("design:type",String)],Tt.prototype,"status",void 0),D([S(),f("Fingerprint of the executed document"),r("ngx-decaf-crud-field",{label:"graph.run.fingerprint.label",readonly:!0}),P("design:type",String)],Tt.prototype,"documentFingerprint",void 0),D([S(),g(),f("Workflow input values keyed by input port id"),P("design:type",Object)],Tt.prototype,"inputs",void 0),D([S(),g(),f("Execution result, present on successful completion"),P("design:type",Object)],Tt.prototype,"result",void 0),D([S(),g(),f("Structured error payload, present on failure"),P("design:type",Object)],Tt.prototype,"error",void 0),D([I(),S(),f("Run creation timestamp"),P("design:type",Date)],Tt.prototype,"createdAt",void 0),D([I(),S(),f("Execution start timestamp, once it has started"),P("design:type",Date)],Tt.prototype,"startedAt",void 0),D([I(),S(),f("Terminal-state timestamp, once the run has finished"),P("design:type",Date)],Tt.prototype,"finishedAt",void 0),Tt=D([s("ngx-decaf-list-item",{icon:"ti-player-play"}),i("ngx-decaf-crud-form"),f("Persistable graph run lifecycle record"),C("graph_run"),E(),P("design:paramtypes",[Object])],Tt);let Lt=class extends T{constructor(e){super(e)}};D([$({type:String,generated:!1}),P("design:type",String)],Lt.prototype,"workflowId",void 0),D([S(),P("design:type",String)],Lt.prototype,"name",void 0),D([S(),P("design:type",Object)],Lt.prototype,"document",void 0),D([S(),P("design:type",String)],Lt.prototype,"owner",void 0),D([S(),P("design:type",Object)],Lt.prototype,"snapshot",void 0),Lt=D([C("graph_workflow"),E(),P("design:paramtypes",[Object])],Lt),te("Trigger",{color:"#3b82f6",icon:"ti-bolt"}),te("Flow Control",{color:"#f59e0b",icon:"ti-arrows-split-2"}),te("Utility",{color:"#0d9488",icon:"ti-tool"}),te("Loop",{color:"#eab308",icon:"ti-repeat"}),te("Workflow",{color:"#f97316",icon:"ti-sitemap"}),te("Pipeline",{color:"#0ea5e9",icon:"ti-git-merge"}),te("Node",{color:"#8b5cf6",icon:"ti-point-filled"}),te("Agent",{color:"#7c3aed",icon:"ti-robot"}),te("model",{color:"#3b82f6",icon:"ti-cpu"}),te("memory",{color:"#10b981",icon:"ti-database"}),te("workspace",{color:"#f59e0b",icon:"ti-folder"});const jt=new Set;function Mt(e,t){return e.config[t]}function Gt(e){return Array.isArray(e)?e.map(e=>e+"").join(", "):e+""}(()=>{const t=[{key:de.NODE_ID,shouldInclude:e=>null!=Mt(e,de.NODE_ID),render:e=>Mt(e,de.NODE_ID)+""},{key:de.WORKFLOW_ID,shouldInclude:e=>null!=Mt(e,de.WORKFLOW_ID),render:e=>Mt(e,de.WORKFLOW_ID)+""},{key:de.RUN_ID,shouldInclude:e=>null!=Mt(e,de.RUN_ID),render:e=>Mt(e,de.RUN_ID)+""},{key:de.USER,shouldInclude:e=>null!=Mt(e,de.USER),render:e=>Mt(e,de.USER)+""},{key:de.ROLES,shouldInclude(e){const t=Mt(e,de.ROLES);return Array.isArray(t)&&t.length>0},render:e=>Gt(Mt(e,de.ROLES))},{key:de.NAMESPACES,shouldInclude(e){const t=Mt(e,de.NAMESPACES);return Array.isArray(t)&&t.length>0},render:e=>Gt(Mt(e,de.NAMESPACES))},{key:de.ORGANIZATION,shouldInclude:e=>null!=Mt(e,de.ORGANIZATION),render:e=>Mt(e,de.ORGANIZATION)+""},{key:de.IP,shouldInclude:e=>null!=Mt(e,de.IP),render:e=>Mt(e,de.IP)+""}];for(const o of t)jt.has(o.key)||(e.register(o),jt.add(o.key))})();const Ut="$workflow",Ft=4,Bt=100,qt=1e3,Vt=1e3,Wt=1e4,Ht=3e4,Kt="graph.pinnable";var zt,Jt;(e=>{e.MANUAL="manual",e.AUTOMATIC="automatic",e.DISABLED="disabled"})(zt||(zt={})),(e=>{e.TRUTHY="truthy",e.FALSY="falsy",e.EQUALS="equals",e.NOT_EQUALS="notEquals",e.GREATER_THAN="greaterThan",e.GREATER_THAN_OR_EQUAL="greaterThanOrEqual",e.LESS_THAN="lessThan",e.LESS_THAN_OR_EQUAL="lessThanOrEqual",e.EXISTS="exists",e.CUSTOM="custom"})(Jt||(Jt={}));const Xt={FOREACH:"core.loop.foreach",WHILE:"core.loop.while",UNTIL:"core.loop.until"};class Yt extends k{constructor(e,t="GRAPH_EXECUTION_ERROR",o){super(e,Yt.name,500),this.graphCode=t,this.details=o,this.name=this.constructor.name}}class Qt extends Yt{constructor(e){super("Graph workflow contains an unsupported cycle","GRAPH_CYCLE_ERROR",e)}}class Zt extends Yt{constructor(e,t){super(e,"GRAPH_INPUT_ERROR",t)}}class eo extends Yt{constructor(e,t){super(e,"GRAPH_LOOP_LIMIT_ERROR",t)}}class to extends Yt{constructor(e,t){super(e,"GRAPH_PINNING_ERROR",t)}}class oo extends Yt{constructor(e,t){super(e,"GRAPH_PORT_ERROR",t)}}class no extends Yt{constructor(e,t){super(e,"GRAPH_STORE_ERROR",t)}}class io extends Yt{constructor(e,t){super(e,"GRAPH_TOPOLOGY_ERROR",t)}}class ro extends Yt{constructor(e){super("Break signal","GRAPH_BREAK_SIGNAL",{value:e}),this.isBreakSignal=!0,this.name="GraphBreakSignal"}}class ao extends Yt{constructor(e){super(`Graph run '${e}' was cancelled`,"GRAPH_RUN_CANCELLED",{runId:e}),this.name=ao.name}}class so extends x{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=so.name,this.issues=e}}class lo{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 co{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 Yt("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 uo(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(),i=o[2].trim(),r=o[1].split(",").map(e=>e.trim()).filter(e=>e.length>0);return n&&i&&0!==r.length?{organization:n,departments:r,role:i}:void 0}function po(e){return`${e.organization}.${e.departments.join(",")}.${e.role}`}function ho(e){if(!e||"string"!=typeof e.namespace||!e.parts)return!1;const t=uo(e.namespace);return!!t&&po(t)===po(e.parts)}function fo(e,t){const o="string"==typeof e?e.trim():"";if(o){if(t)for(const e of t)if(e&&e.namespace===o&&ho(e))return e.parts;return uo(o)}}function go(e,t,o={},n){const i=fo(e,n),r=fo(t,n);return!(!i||!r)&&i.organization===r.organization&&i.role===r.role&&("exact"===(o.mode??"inherit")?i.departments.length===r.departments.length&&i.departments.every((e,t)=>e===r.departments[t]):i.departments.length<=r.departments.length&&i.departments.every((e,t)=>e===r.departments[t]))}function mo(e,t,o={},n){return e.filter(e=>!t.some(t=>go(t,e,o,n)))}function yo(e){return e.filter(e=>void 0===uo(e))}function wo(e,t){const o=new Set;for(const n of e){const e=fo(n,t);e&&o.add(e.role)}return[...o]}function bo(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function vo(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 Io(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 i=e.ip;"string"==typeof i&&i&&(t.ip=i);const r=bo(e.roles);r&&(t.roles=r);const a=bo(e.namespaces);return a&&(t.namespaces=a,t.namespaceCache=No(a)),t}function Eo(e){return e?Io({user:vo(e,"user"),organization:vo(e,"organization"),ip:vo(e,"ip"),roles:vo(e,"roles"),namespaces:vo(e,"namespaces")}):{}}function No(e){const t=[];for(const o of e){const e=uo(o);e&&t.push({namespace:o,parts:e})}return t}function Oo(...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??No(o.namespaces):void 0!==o.namespaceCache&&(t.namespaceCache=o.namespaceCache));return t}class Ao{constructor(e={}){this.options=e}get enabled(){return!0===this.options.enabled}validate(e,o,n,i){if(!this.enabled)return;const r=i??this.options.logger??t.for("GraphAuth"),a=e.id||e.name||o.workflowId,s=(e=>{if(!e||"object"!=typeof e)return;const t=e.auth;return t&&"object"==typeof t&&!Array.isArray(t)?(e=>{if(!e)return;const t=he(e.namespaces),o=he(e.roles);if(!t&&!o)return;const n={};return t&&(n.namespaces=t),o&&(n.roles=o),n})(t):void 0})(e.metadata);this.assertGranted(`workflow '${a}'`,s?.namespaces??[],n,s?.roles??[],r);for(const e of o.nodes)this.assertGranted(`node '${e.id}'`,e.manifest.namespaces??[],n,[],r)}assertGranted(e,t,o,n,i){const r=o.namespaces??[],a=mo(t,r,this.options.match,o.namespaceCache),s=wo(r,o.namespaceCache),d=n.filter(e=>!s.includes(e));if(0===a.length&&0===d.length)return;const l=[...new Set([...yo(t),...yo(r)])],c=[];throw a.length&&c.push("namespace(s) "+a.join(", ")),d.length&&c.push("role(s) "+d.join(", ")),i.warn(`Graph access denied for ${e} for user ${o.user??"anonymous"}: missing ${c.join(" and ")}${l.length?`; malformed namespace(s) ${l.join(", ")} failed closed`:""}`),new L(`Access to ${e} requires ${c.join(" and ")}`)}}class xo{constructor(e){this.baseOptions=e,this.inner=t.for("GraphRun").for(this.attributeConfig(e))}attributeConfig(e){return{[de.NODE_ID]:e.nodeId,[de.WORKFLOW_ID]:e.workflowId,[de.RUN_ID]:e.runId,[de.USER]:e.user??null,[de.ROLES]:e.roles,[de.NAMESPACES]:e.namespaces,[de.ORGANIZATION]:e.organization,[de.IP]:e.ip}}emit(e,t,o){const n="string"==typeof t?t:t instanceof Error?t.message:t+"",i={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&&(i.roles=this.baseOptions.roles),void 0!==this.baseOptions.namespaces&&(i.namespaces=this.baseOptions.namespaces),void 0!==this.baseOptions.organization&&(i.organization=this.baseOptions.organization),void 0!==this.baseOptions.ip&&(i.ip=this.baseOptions.ip),void 0!==o&&(i.payload=o),this.baseOptions.forward({type:le.GRAPH_RUN_LOG,payload:i}).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 ko(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}class _o extends j{constructor(e,t,o,n,i,r,a,s,d={},l,c,u){super(),this.runId=e,this.parentRunId=t,this.workflowId=o,this.document=n,this.node=i,this.manifest=r,this.path=a,this.emitFn=s,this.metadata=d,this.engine=l,this.abortSignal=c,this.limits=u;const p=Io(d);this.accumulate({...p,operation:"execute"});const h="string"==typeof d?.user?d.user:null;this.runLogger=new xo({runId:e,workflowId:o,nodeId:i.id,user:h,roles:ko(d?.roles),namespaces:ko(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 Eo(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:le.NODE_OUTPUT,payload:e})}async log(e,t){await this.emit({type:le.NODE_OUTPUT,payload:{message:e,payload:t}})}}class Do{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 Po(e,t,o,n,i){const r=e.valueStore.getWorkflowValues(),a={};for(const[t,o]of e.nodeResults)a[t]=o;const s=[...e.events];return{runId:e.runId,workflowId:t.id||t.name,status:n,document:t,inputs:{...o},outputs:r,nodeResults:a,events:s,startedAt:e.startedAt,finishedAt:e.finishedAt,metadata:i}}class $o{constructor(e){this.catalogue=e}async resolveNodes(e,t,o,...n){const i=new Map;for(const[r,a]of e.entries()){const e=`nodes[${r}]`;if(this.catalogue.has(a.kind,...n))try{const e=await this.catalogue.resolveManifest(a.kind,a,o,...n),t=this.catalogue.getExecutor(a.kind,...n);i.set(a.id,{instance:a,manifest:e,executor:t})}catch(o){t.push({code:"kind.resolution-failed",path:e+".kind",message:`Node '${a.id}' kind '${a.kind}' failed to resolve: ${o.message}`,nodeId:a.id,details:{kind:a.kind}})}else t.push({code:"kind.unknown",path:e+".kind",message:`Node '${a.id}' references kind '${a.kind}' which is not registered in the backend catalogue`,nodeId:a.id,details:{kind:a.kind}})}return i}validateEffectivePorts(e,t,o,n){const i=!0===t.policies?.allowUndeclaredParameters,r=new Set(t.inputs.map(e=>e.id)),a=new Set(t.outputs.map(e=>e.id));for(const a of Object.keys(e.inputBindings??{}))i||r.has(a)||o.push({code:"binding.unknown-port",path:`${n}.inputBindings.${a}`,message:`Node '${e.id}' input binding '${a}' does not refer to an effective input port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveInputs:[...r]}});for(const r of Object.keys(e.outputBindings??{}))i||a.has(r)||o.push({code:"binding.unknown-port",path:`${n}.outputBindings.${r}`,message:`Node '${e.id}' output binding '${r}' does not refer to an effective output port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveOutputs:[...a]}})}}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 i of e.nodes){n.has(i.id)||t.push({code:"topology.loose-node",path:`${o}.nodes[${i.id}]`,message:`Node '${i.id}' is connected to nothing; every node must participate in at least one edge`,nodeId:i.id});const e=i.loop?.body;e&&So(e,t,`${o}.nodes[${i.id}].loop.body`)}}function Ro(e,t){if(!t)return{valid:!0};switch(t.type){case"any":default:return{valid:!0};case"string":return"string"!=typeof e?Co("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}:Co("number");case"boolean":return"boolean"!=typeof e?Co("boolean"):{valid:!0};case"array":if(!Array.isArray(e))return Co("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=Ro(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 Co(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=Ro(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 Co(e){return{valid:!1,message:`expected a ${e} value`}}function To(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 Lo=new Set(["loop"]),jo=["secret","secrets","password","passwd","token","accessToken","refreshToken","apiKey","api_key","privateKey","credentials"];class Mo{validate(e,t,o,n,i){this.validateParameters(e,t,o,n,i),this.validateMetadataKeys(e,t,o,n),this.validateDisabledBehavior(e,o,n),this.validateBindingShapes(e,t,o,n)}validateParameters(e,t,o,n,i){const r=!0===t.policies?.allowUndeclaredParameters,a=new Map(t.parameters.map(e=>[e.id,e]));for(const[i,s]of Object.entries(e.parameters??{})){const d=a.get(i);if(!d){r||o.push({code:"parameter.undeclared",path:`${n}.parameters.${i}`,message:`Node '${e.id}' sets parameter '${i}' 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.${i}`,message:`Node '${e.id}' parameter '${i}' 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.${i}`,message:`Node '${e.id}' parameter '${i}' is invalid: ${l.message}`,nodeId:e.id,details:{expectedType:d.type}})}for(const r of t.parameters)void 0===(e.parameters??{})[r.id]&&(this.isParameterSatisfiedByInput(e,r.id,i)||(!0===r.required||(r.validation??[]).some(e=>"required"===e.kind))&&void 0===r.defaultValue&&o.push({code:"parameter.required-missing",path:`${n}.parameters.${r.id}`,message:`Node '${e.id}' is missing required parameter '${r.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(ct(e))return{valid:!0};switch(t.type){case"string":case"code":case"expression":return"string"!=typeof e?Co("string"):{valid:!0};case"number":return"number"==typeof e&&Number.isFinite(e)?{valid:!0}:Co("number");case"boolean":return"boolean"!=typeof e?Co("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}:Co("array");case"object":case"resourceLocator":return null===e||"object"!=typeof e||Array.isArray(e)?Co("object"):{valid:!0};case"credential":return To(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 i=t.metadata?.allowedInstanceMetadataKeys;for(const r of Object.keys(e.metadata??{}))Lo.has(r)?o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${r}`,message:`Node '${e.id}' metadata key '${r}' is reserved and must not be set directly`,nodeId:e.id}):Array.isArray(i)&&!i.includes(r)&&o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${r}`,message:`Node '${e.id}' metadata key '${r}' 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||re(n)||t.push({code:"disabled.invalid-behavior",path:o+".metadata.disabledBehavior",message:`Node '${e.id}' disabled behavior '${n+""}' is not one of: ${ie.join(", ")}`,nodeId:e.id})}validateBindingShapes(e,t,o,n){for(const[i,r]of Object.entries(e.inputBindings??{})){if("literal"===r.mode){const a=t.inputs.find(e=>e.id===i);if(a?.schema){const t=Ro(r.value,a.schema);t.valid||o.push({code:"binding.literal-invalid",path:`${n}.inputBindings.${i}`,message:`Node '${e.id}' literal binding for '${i}' is schema-invalid: ${t.message}`,nodeId:e.id})}}"expression"!==r.mode||"string"==typeof r.expression&&r.expression.trim()||o.push({code:"binding.expression-invalid",path:`${n}.inputBindings.${i}`,message:`Node '${e.id}' expression binding for '${i}' must contain a non-empty expression`,nodeId:e.id})}}validateBindingSatisfaction(e,t,o,n,i,r={}){const a=new Set(o.filter(e=>"data"===e.type).map(e=>e.targetPort)),s=new Set(Object.entries(e.inputBindings??{}).map(([e])=>e));for(const t of a){const o=(e.inputBindings??{})[t];o&&"literal"===o.mode&&!0!==r.allowLiteralAndEdgeBindings&&n.push({code:"binding.conflict",path:`${i}.inputBindings.${t}`,message:`Node '${e.id}' input '${t}' has both an incoming edge and a literal binding`,nodeId:e.id})}for(const o of t.inputs)!0===o.required&&(a.has(o.id)||s.has(o.id)||void 0===(e.parameters??{})[o.id]&&n.push({code:"topology.required-input-unsatisfiable",path:i+".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(re(o))return o;const n=t?.disabledBehavior;return re(n)?n:"skip"}}class Go{resolveEdges(e,t,o){const n=new Set(e.inputs.map(e=>e.id)),i=new Set(e.outputs.map(e=>e.id)),r=[];for(const[a,s]of(e.edges??[]).entries()){const e=`edges[${a}]`,d=this.resolveEndpoint(s,"source",t,n,i,o,e),l=this.resolveEndpoint(s,"target",t,n,i,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),r.push(c)}return r}resolveEndpoint(e,t,o,n,i,r,a){const s=e[t];return Je(s)?("source"===t?n.has(s.port):i.has(s.port))?{nodeId:Ut,port:s.port}:void r.push({code:"edge.unknown-port",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} references workflow port '${s.port}' which is not declared on the document boundary`,edgeId:e.id,details:{scope:"workflow",port:s.port}}):Xe(s)?o.get(s.nodeId)?{nodeId:s.nodeId,port:s.port}:void r.push({code:"edge.unknown-node",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} references node '${s.nodeId}' which is not part of the document or did not resolve`,edgeId:e.id,nodeId:s.nodeId}):void r.push({code:"edge.invalid-endpoint",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} endpoint is not a valid GraphEndpoint`,edgeId:e.id})}validateDirectionAndType(e,t,o,n,i,r){let a=!0;const s=t.nodeId===Ut?void 0:n.get(t.nodeId),d=o.nodeId===Ut?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,i,r),a=!1),!d||l(d)||this.hasPortDirection(d,o.port,"input")||(this.pushPortIssue(e,"target",o,d,i,r),a=!1);else{if(!s||!d)return i.push({code:"edge.boundary-routing",path:r,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 i.push({code:"edge.type-mismatch",path:r,message:`Connection edge '${e.id}' endpoints must both be connection ports`,edgeId:e.id,details:{sourcePort:t.port,targetPort:o.port}}),!1}return a}hasPortDirection(e,t,o){return("input"===o?e.manifest.inputs:"output"===o?e.manifest.outputs:e.manifest.connections??[]).some(e=>e.id===t)}pushPortIssue(e,t,o,n,i,r){const a="source"===t?"output":"input";i.push({code:"data"===e.type?"edge.invalid-direction":"edge.type-mismatch",path:`${r}.${t}`,message:`Edge '${e.id}' ${t} port '${o.port}' on node '${o.nodeId}' is not an ${a} port of kind '${n.manifest.kind}'`,edgeId:e.id,nodeId:o.nodeId,details:{port:o.port,expected:a}})}}class Uo{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}`,i=o.get(e);i?t.push({code:"connection.duplicate-edge",path:`edges[${n.id}]`,message:`Edge '${n.id}' duplicates the routing of edge '${i.id}' (${e})`,edgeId:n.id,details:{duplicateOf:i.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),i=n?.manifest.connections?.find(e=>e.id===o.targetPort)?.connectionPolicy;this.validateEdgePolicy(o,e.nodeById,i,t)}for(const[n,i]of o){const o=n.lastIndexOf(":"),r=n.slice(0,o),a=n.slice(o+1),s=e.nodeById.get(r),d=s?.manifest.connections?.find(e=>e.id===a)?.connectionPolicy;if(!d)continue;const l=void 0!==d.maxConnections?d.maxConnections:!1===d.allowMultiple?1:1/0;i.length>l&&t.push({code:"connection.max-connections",path:`edges[${i[i.length-1].id}]`,message:`Connection port '${a}' on node '${r}' accepts at most ${l} connection(s) but has ${i.length}`,nodeId:r,edgeId:i[i.length-1].id,details:{port:a,max:l,actual:i.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 i=t.get(e.sourceNodeId),r=i?.manifest.kind;if(!o.allowedNodeKinds?.length||r&&o.allowedNodeKinds.includes(r)||n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${r??"unknown"}' is not in the allowed node kinds of target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{allowedNodeKinds:o.allowedNodeKinds}}),r&&o.blockedNodeKinds?.includes(r)&&n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${r}' is blocked by target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{blockedNodeKinds:o.blockedNodeKinds}}),o.allowedPortCategories?.length){const t=i?.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 Fo{constructor(e){this.authorizer=e}async validate(e,t,o,n){const i=this.collectReferences(e,t);for(const r of t.credentials??[]){const a=i.find(e=>void 0===e.credentialType||e.credentialType===r.type);if(a){if(this.checkType(a,r))o.push({code:"credential.type-mismatch",path:n,message:`Node '${e.id}' credential '${a.credentialId}' has type '${a.credentialType}' but kind '${t.kind}' requires '${r.type}'`,nodeId:e.id,details:{credentialType:a.credentialType??"",requiredType:r.type}});else if(this.authorizer){if(!await this.authorizer.hasCredential(a)){o.push({code:"credential.not-found",path:n,message:`Node '${e.id}' references credential '${a.credentialId}' which does not exist`,nodeId:e.id,details:{credentialId:a.credentialId}});continue}await this.authorizer.authorize(a,r)||o.push({code:"credential.unauthorized",path:n,message:`Node '${e.id}' is not authorized to use credential '${a.credentialId}'`,nodeId:e.id,details:{credentialId:a.credentialId}})}}else!1!==r.required&&o.push({code:"credential.missing",path:n,message:`Node '${e.id}' does not provide the required credential of type '${r.type}'`,nodeId:e.id,details:{credentialType:r.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];To(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))To(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(jo);for(const[i,r]of Object.entries(e.parameters??{}))this.scanPlainSecretValue(r,[i],e,o+".parameters",n,t);for(const[i,r]of Object.entries(e.metadata??{}))this.scanPlainSecretValue(r,[i],e,o+".metadata",n,t)}scanPlainSecretValue(e,t,o,n,i,r,a=0){const s=t[t.length-1];if(i.has(s))r.push({code:"credential.plain-secret",path:`${n}.${t.join(".")}`,message:`Node '${o.id}' carries plain secret material in '${t.join(".")}'; workflow documents may only hold credential references`,nodeId:o.id});else if(8>a&&null!==e)if(Array.isArray(e))for(const s of e)this.scanPlainSecretValue(s,[...t,"[]"],o,n,i,r,a+1);else if("object"==typeof e)for(const[s,d]of Object.entries(e))this.scanPlainSecretValue(d,[...t,s],o,n,i,r,a+1)}}class Bo extends x{constructor(e,t=[]){super(e),this.issues=t,this.name=Bo.name}}class qo extends x{constructor(e,t){super(e),this.edgeId=t,this.name=qo.name}}class Vo extends M{constructor(e){super(e),this.name=Vo.name}}const Wo={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},Ho=["node","definition","executor","execute","ports","component"];function Ko(e){if(!e||"object"!=typeof e)return!1;const t=e;return ut(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 zo(e,t){const o=[];for(const n of Object.keys(e))Ho.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 Jo{constructor(e){this.options=e,this.parameterValidator=new Mo,this.edgeValidator=new Go,this.connectionPolicyValidator=new Uo,this.nodeValidator=new $o(e.catalogue),this.credentialValidator=new Fo(e.credentialAuthorizer)}async validateOrThrow(e,...t){const o=await this.validate(e,0,...t);if(!o.valid||!o.resolved)throw new Bo(`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=[],i={...Wo,...this.options.limits};if(!await this.validateStructure(e,i,t,n,...o))return{valid:!1,issues:n};const r=await this.nodeValidator.resolveNodes(e.nodes,n,this.options.resolutionContext,...o),a=e.nodes.filter(e=>r.has(e.id)).map(e=>r.get(e.id)),s=(e=>{const t=new Map;for(const o of e.edges??[]){if("data"!==o.type)continue;const e=o.target;if("node"!==e.scope)continue;const n=t.get(e.nodeId)??new Set;n.add(e.port),t.set(e.nodeId,n)}return t})(e);for(const e of a)this.parameterValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`,s.get(e.instance.id));for(const e of a)this.nodeValidator.validateEffectivePorts(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);const d=this.edgeValidator.resolveEdges(e,r,n),l=new Map,c=new Map;for(const e of d){if(e.targetNodeId!==Ut){const t=l.get(e.targetNodeId)??[];t.push(e),l.set(e.targetNodeId,t)}if(e.sourceNodeId!==Ut){const t=c.get(e.sourceNodeId)??[];t.push(e),c.set(e.sourceNodeId,t)}}this.connectionPolicyValidator.validate({edges:d,nodeById:r},n),this.validateAcyclicity(a,d,e,n),So(e,n);for(const e of a)this.parameterValidator.validateBindingSatisfaction(e.instance,e.manifest,l.get(e.instance.id)??[],n,`nodes[${e.instance.id}]`,{allowLiteralAndEdgeBindings:this.options.allowLiteralAndEdgeBindings});this.validateRequiredWorkflowOutputs(e,c,n);for(const e of a)await this.credentialValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);return this.validateCapabilities(a,n),n.length>0?{valid:!1,issues:n}:{valid:!0,issues:n,resolved:{document:e,nodes:a,edges:d,nodeById:r,incomingByNode:l,outgoingByNode:c}}}async validateStructure(e,t,o,n,...i){if(!ut(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"}),!Ge(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(...zo(e,"$"));for(const t of[...e.inputs,...e.outputs])n.push(...zo(t,"ports"));for(const t of e.nodes)n.push(...zo(t,`nodes[${t.id}]`));for(const t of e.edges)n.push(...zo(t,`edges[${t.id}]`));this.validateUniqueIds(e,n),this.validateLimits(e,t,o,n);try{tt(e)}catch(e){n.push({code:"document.structure",path:"$",message:e instanceof Error?e.message:e+""})}return await this.validateNestedBodies(e,o,n,...i),!0}validateUniqueIds(e,t){const o=new Set,n=new Set;for(const[i,r]of[["input",e.inputs],["output",e.outputs]]){const e="input"===i?o:n;for(const o of r)e.has(o.id)?t.push({code:"document.duplicate-port-id",path:`${"input"===i?"inputs":"outputs"}[${o.id}]`,message:`Workflow ${i} port '${o.id}' is declared more than once; workflow port ids must be unique`}):e.add(o.id)}const i=new Set;for(const o of e.nodes)i.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}):i.add(o.id);const r=new Set;for(const o of e.edges)r.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}):r.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 i=Buffer.byteLength(JSON.stringify(e),"utf8");i>t.maxDocumentBytes&&n.push({code:"document.limit.size",path:"$",message:`Document serializes to ${i} bytes; at most ${t.maxDocumentBytes} bytes are allowed`,details:{bytes:i,limit:t.maxDocumentBytes}})}async validateNestedBodies(e,t,o,...n){for(const i of e.nodes){const e=[["loop.body",i.loop?.body],["errorBoundary.try",i.errorBoundary?.try],["errorBoundary.catch",i.errorBoundary?.catch],["errorBoundary.finally",i.errorBoundary?.finally]];for(const[r,a]of e){if(!a)continue;const e=await this.validate(a,t+1,...n);for(const t of e.issues)o.push({...t,path:`nodes[${i.id}].${r}.${t.path}`,nodeId:t.nodeId??i.id})}}}validateAcyclicity(e,t,o,n){const i=new Set(e.map(e=>e.instance.id)),r=new Map(e.map(e=>[e.instance.id,0]));for(const e of t)i.has(e.sourceNodeId)&&r.has(e.targetNodeId)&&r.set(e.targetNodeId,(r.get(e.targetNodeId)??0)+1);const a=[...r.entries()].filter(([,e])=>0===e).map(([e])=>e),s=[];for(;a.length>0;){const e=a.shift();s.push(e);for(const o of t){if(o.sourceNodeId!==e)continue;if(!r.has(o.targetNodeId))continue;const t=(r.get(o.targetNodeId)??1)-1;r.set(o.targetNodeId,t),0===t&&a.push(o.targetNodeId)}}if(s.length!==r.size){const e=[...r.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===Ut&&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??[])ft(n)||t.push({code:"capability.invalid",path:`nodes[${o.instance.id}]`,message:`Kind '${e.kind}' declares unknown capability '${n+""}'`,nodeId:o.instance.id,details:{capability:n+""}});!0!==e.policies?.allowUndeclaredParameters&&o.instance.loop&&((e.capabilities??[]).includes("loop")||t.push({code:"capability.loop-not-supported",path:`nodes[${o.instance.id}].loop`,message:`Node '${o.instance.id}' carries loop configuration but kind '${e.kind}' does not declare the 'loop' capability`,nodeId:o.instance.id}))}}}let Xo=class extends U{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"}'`),!Ko(e))throw new io("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 i=this.buildPlanNodes(e),r=this.buildPlanEdges(e),a=this.buildIncomingMap(r),s=this.buildOutgoingMap(r),d=this.topologicalLayers(i,r);return{resolved:e,workflowId:e.document.id||e.document.name,nodes:i,edges:r,layers:d,incomingByNode:a,outgoingByNode:s}}buildPlanNodes(e){return e.nodes.map(e=>({id:e.instance.id,kind:e.manifest.kind,instance:e.instance,manifest:e.manifest,executor:e.executor,inputPorts:e.manifest.inputs.map(e=>e.id),outputPorts:e.manifest.outputs.map(e=>e.id),connectionPorts:(e.manifest.connections??[]).map(e=>e.id),metadata:e.instance.metadata}))}buildPlanEdges(e){return e.edges.map(e=>({id:e.id,type:e.type,sourceNodeId:e.sourceNodeId,sourcePort:e.sourcePort,targetNodeId:e.targetNodeId,targetPort:e.targetPort,...void 0!==e.label?{label:e.label}:{},metadata:e.metadata}))}buildIncomingMap(e){const t=new Map;for(const o of e){if(o.targetNodeId===Ut)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===Ut)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!==Ut),n=new Set(o.map(e=>e.id)),i=t.filter(e=>n.has(e.sourceNodeId)&&n.has(e.targetNodeId)),r=new Map;for(const e of o)r.set(e.id,0);for(const e of i)r.set(e.targetNodeId,(r.get(e.targetNodeId)??0)+1);const a=[],s=new Set;let d=o.filter(e=>0===(r.get(e.id)??0)),l=0;for(;d.length>0;){const e={index:l++,nodes:d};a.push(e);const t=[];for(const e of d){s.add(e.id);const n=i.filter(t=>t.sourceNodeId===e.id);for(const e of n){const n=(r.get(e.targetNodeId)??1)-1;if(r.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 Qt({unplannedNodes:e,workflowId:o[0]?.manifest.kind})}return a}};Xo=D([G(),P("design:paramtypes",[])],Xo);let Yo=class extends T{constructor(e){super(e)}};function Qo(e){return[e.namespace??"default",e.workflowId,e.nodeId,e.version??"default",e.fingerprint].join(":")}function Zo(e){return new Yo({id:Qo(e.key),workflowId:e.key.workflowId,nodeId:e.key.nodeId,fingerprint:e.key.fingerprint,...void 0!==e.key.namespace?{namespace:e.key.namespace}:{},...void 0!==e.key.version?{version:e.key.version}:{},pinned:e.pinned,outputs:e.outputs,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt),...e.expiresAt?{expiresAt:new Date(e.expiresAt)}:{},...e.metadata?{metadata:e.metadata}:{}})}function en(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}:{}}}D([$({type:String,generated:!1}),P("design:type",String)],Yo.prototype,"id",void 0),D([S(),R(),P("design:type",String)],Yo.prototype,"workflowId",void 0),D([S(),R(),P("design:type",String)],Yo.prototype,"nodeId",void 0),D([S(),P("design:type",String)],Yo.prototype,"fingerprint",void 0),D([S(),P("design:type",String)],Yo.prototype,"namespace",void 0),D([S(),P("design:type",String)],Yo.prototype,"version",void 0),D([S(),P("design:type",Boolean)],Yo.prototype,"pinned",void 0),D([S(),P("design:type",Object)],Yo.prototype,"outputs",void 0),D([S(),P("design:type",Date)],Yo.prototype,"createdAt",void 0),D([S(),P("design:type",Date)],Yo.prototype,"updatedAt",void 0),D([S(),P("design:type",Date)],Yo.prototype,"expiresAt",void 0),D([S(),P("design:type",Object)],Yo.prototype,"metadata",void 0),Yo=D([C("graph_value"),E(),P("design:paramtypes",[Object])],Yo);let tn=class extends B{constructor(e){super(e,Yo,!0),this.runtimeValues=new Map}seedWorkflowInputs(e){this.runtimeValues.set(Ut,{...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(Ut)??{};o[e]=t,this.runtimeValues.set(Ut,o)}getWorkflowValues(){return{...this.runtimeValues.get(Ut)??{}}}snapshot(){return Object.fromEntries(this.runtimeValues.entries())}async readCached(e,...t){try{return en(await this.read(Qo(e),...t))}catch{return}}async writeCached(e,t,...o){const n=Qo(e);let i;try{i=await this.read(n,...o)}catch{i=void 0}i?await this.update(Object.assign(i,Zo(t)),...o):await this.create(Zo(t),...o)}async deleteCached(e,...t){try{await this.delete(Qo(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=>en(e)).filter(t=>((e,t)=>!(void 0!==t.workflowId&&e.workflowId!==t.workflowId||void 0!==t.nodeId&&e.nodeId!==t.nodeId||void 0!==t.namespace&&e.namespace!==t.namespace||void 0!==t.version&&e.version!==t.version||void 0!==t.fingerprint&&e.fingerprint!==t.fingerprint))(t.key,e))}async clearRun(e,...t){const o=await this.select().execute(...t);for(const e of o)await this.delete(e.id,...t)}readRuntimeValues(e){return this.runtimeValues.get(e)}writeRuntimeValues(e,t){this.runtimeValues.set(e,{...t})}getAdapter(){return this.adapter}};function on(e){return new(0,B.forModel(Yo,e.alias).constructor)(e)}tn=D([F(Yo,m),P("design:paramtypes",[Function])],tn);class nn{static upstreamNodes(e,t,o=!1){const n=new Set,i=[e];for(;i.length;){const e=i.pop(),r=t.get(e)??[];for(const e of r)!o&&this.isBoundary(e.sourceNodeId)||n.has(e.sourceNodeId)||(n.add(e.sourceNodeId),i.push(e.sourceNodeId))}return n}static downstreamNodes(e,t,o=!1){const n=new Set,i=[e];for(;i.length;){const e=i.pop(),r=t.get(e)??[];for(const e of r)!o&&this.isBoundary(e.targetNodeId)||n.has(e.targetNodeId)||(n.add(e.targetNodeId),i.push(e.targetNodeId))}return n}static isBoundary(e){return"$workflow"===e}}class rn{constructor(e,t,o){this.store=e,this.policy=t,this.dependencyResolver=o}async pinNode(e){const t=e.plan,o=e.includeDependencies??1?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 to(`Node '${e}' not found in plan`);if(!this.policy.canPin(o))throw new to(`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),i=e.result.nodeResults[o];if(!i||!i.outputs)throw new to(`Node '${o}' has no completed output to pin`);const r=i.inputs??{},a=this.dependencyFingerprints(t,o,e.result),s=this.createValueKey(e.document.id,n,r,a),d=(new Date).toISOString(),l={key:s,outputs:i.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,i){const r=this.createValueKey(e,t,o,n,i),a=await this.store.readCached(r);if(a&&a.pinned){if(a.expiresAt&&new Date(a.expiresAt)<new Date)return;return a}}createValueKey(e,t,o,n,i){return{workflowId:e,nodeId:t.id,fingerprint:this.computeFingerprint(e,t,o,n),namespace:i}}computeFingerprint(e,t,o,n){const i={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)},r=this.stableSerialize(i);return this.simpleHash(r)}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,i=r=>{if(n.has(r))return;n.add(r);const a=nn.upstreamNodes(r,e.incomingByNode,!1);for(const e of a)t.has(e)&&i(e);o.push(r)};for(const e of t)i(e);return o}dependencyFingerprints(e,t,o){const n=this.dependencyResolver.getDependencies(e,t),i={};for(const t of n){const n=e.nodes.find(e=>e.id===t);if(n){const r=o.nodeResults[t],a=r?.inputs??{},s=this.dependencyFingerprints(e,t,o);i[t]=this.computeFingerprint(e.workflowId,n,a,s)}}return i}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 an={enabled:!0,strategy:"manual",includeDependencies:!0};function sn(e){return!0===e?.enabled&&"disabled"!==e.strategy}class dn{canPin(e){return sn(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?{...an,...t}:{...an,enabled:!1}}}class ln{getDependencies(e,t){return nn.upstreamNodes(t,e.incomingByNode,!1)}getPinSet(e,t){const o=this.getDependencies(e,t);return o.add(t),o}}class cn extends q{constructor(){super()}async initialize(...e){const t=e[0];if(!t||"object"!=typeof t||!t.registry)return this._config=void 0,this._client=void 0,{config:void 0,client:void 0};const o=t.catalogue??t.registry.catalog,n=t.valueAdapter??V.current;if(!n)throw new Yt("GraphExecutionEngine requires a Decaf adapter for cached/pinned values: pass `valueAdapter` or configure one via `Adapter.setCurrent(...)`","GRAPH_VALUE_ADAPTER_MISSING");const i={registry:t.registry,catalogue:o,planner:t.planner??new Xo,valueAdapter:n,eventEmitter:t.eventEmitter??new lo,documentValidator:t.documentValidator??new Jo({catalogue:o,limits:t.documentLimits,credentialAuthorizer:t.credentialAuthorizer}),authValidator:new Ao({enabled:!0===t.authEnabled,...t.authMatch?{match:t.authMatch}:{}}),...t.codeSandboxEvaluator?{codeSandboxEvaluator:t.codeSandboxEvaluator}:{}};return this._config=t,this._client=i,await(t.onEngineCreated?.(this)),{config:t,client:i}}get codeSandboxEvaluator(){return this.client.codeSandboxEvaluator}get emitter(){return this.client.eventEmitter}get planner(){return this.client.planner}get valueAdapter(){return this.client.valueAdapter}get defaultOptions(){return this.config.defaultOptions??{}}get documentValidator(){return this.client.documentValidator}observe(e){return this.emitter.observe(e)}unObserve(e){this.emitter.unObserve(e)}async dispatchEvent(e){await this.emitter.updateObservers(e)}async execute(e,t={},o={},...n){const{log:i,ctx:r}=(await this.logCtx(n,"execute",!0)).for(this.execute);i.debug(`Executing workflow '${e.id||e.name}'`);const a=this.mergeOptions(o);this.assertNotAborted(a);const s=Oo(Eo(r),a.auth);a.auth=s,a.metadata={...a.metadata??{},...s};const d=a.runId??this.generateRunId(),l=a.path??[],c=new co,u=on(this.valueAdapter);u.seedWorkflowInputs(this.withWorkflowInputDefaults(e,t));const p=async t=>{await this.emitEvent(m,{type:t.type??le.NODE_OUTPUT,runId:d,parentRunId:a.parentRunId,workflowId:e.id||e.name,nodeId:t.nodeId,path:t.path??l,...t})},h=async t=>{const o=c.create({id:"",sequence:0,timestamp:new Date,runId:d,parentRunId:a.parentRunId,workflowId:e.id||e.name,path:l,...t});await this.emitter.updateObservers(o)};await h({type:le.VALIDATION_STARTED,status:ae.PLANNING});const f=await this.documentValidator.validate(e,0,r);if(!f.valid||!f.resolved)throw await h({type:le.VALIDATION_FAILED,status:ae.FAILED,payload:{issues:f.issues}}),new Bo(`Graph workflow document '${e.id}' failed validation with ${f.issues.length} issue(s)`,f.issues);await h({type:le.VALIDATION_COMPLETED,status:ae.PLANNING,payload:{issues:f.issues.length}}),this.assertNotAborted(a);const g=await this.planner.plan(f.resolved);this.client.authValidator.validate(e,g,s,i),i.debug(`Authorized workflow '${e.id||e.name}' for user ${s.user??"anonymous"}`);const m=new Do(d,g,u,c);await this.emitEvent(m,{type:le.WORKFLOW_STARTED,runId:d,parentRunId:a.parentRunId,workflowId:g.workflowId,path:l,status:ae.RUNNING,payload:{inputs:t}}),await this.emitEvent(m,{type:le.WORKFLOW_PLANNED,runId:d,parentRunId:a.parentRunId,workflowId:g.workflowId,path:l,status:ae.PLANNING,payload:{layers:g.layers.length,nodes:g.nodes.length}});try{for(const e of g.layers)this.assertNotAborted(a),await this.executeLayer(m,g,e.nodes,a,p);this.assertNotAborted(a);const o=[...m.nodeResults.values()].find(e=>e.status===ae.FAILED);if(o?.error)throw new Yt(o.error.message,o.error.code??"GRAPH_EXECUTION_ERROR",o.error.details);return m.finish(),await this.emitEvent(m,{type:le.WORKFLOW_COMPLETED,runId:d,parentRunId:a.parentRunId,workflowId:g.workflowId,path:l,status:ae.SUCCEEDED,payload:{outputs:u.getWorkflowValues()}}),Po(m,e,t,ae.SUCCEEDED,a.metadata)}catch(o){if(o instanceof ro)throw m.finish(),o;m.finish();const n=this.toErrorPayload(o);return o instanceof ao||!0===a.abortSignal?.aborted?(await this.emitEvent(m,{type:le.WORKFLOW_CANCELLED,runId:d,parentRunId:a.parentRunId,workflowId:g.workflowId,path:l,status:ae.CANCELLED,error:n}),Po(m,e,t,ae.CANCELLED,a.metadata)):(await this.emitEvent(m,{type:le.WORKFLOW_FAILED,runId:d,parentRunId:a.parentRunId,workflowId:g.workflowId,path:l,status:ae.FAILED,error:n}),Po(m,e,t,ae.FAILED,a.metadata))}}async pinNode(e){const t=this.createPinningService();await t.pinNode(e),await this.emitPinningEvent(e.nodeId,le.NODE_PINNED)}async unpinNode(e){const t=this.createPinningService();await t.unpinNode(e),await this.emitPinningEvent(e.nodeId,le.NODE_UNPINNED)}createPinningService(){const e=on(this.valueAdapter);return new rn(e,new dn,new ln)}async emitPinningEvent(e,t){const o=(new co).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}async executeLayer(e,t,o,n,i){const r=Math.max(1,n.concurrency??4),a=[...o];for(;a.length>0;){const o=a.splice(0,r);await Promise.all(o.map(o=>this.executeNode(e,t,o,n,i)))}}async executeNode(e,t,o,n,i){if(this.assertNotAborted(n),!this.isNodeActivated(e,t,o))return void await this.skipInactiveNode(e,t,o,n);if(!0===o.instance.disabled)return void await this.executeDisabledNode(e,t,o,n);const r=new Date,a=[...n.path??[],o.id];await this.emitEvent(e,{type:le.NODE_STARTED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:ae.RUNNING}),this.emitNodeStateChanged(e,t,o,a,se.RUNNING,ae.RUNNING);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);const i=new Date,d={nodeId:o.id,status:ae.CACHED,inputs:s,outputs:n.outputs,startedAt:r,finishedAt:i,fromCache:!0,pinned:!0,events:[]};return e.recordNodeResult(d),await this.emitEvent(e,{type:le.NODE_CACHE_HIT,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:ae.CACHED,payload:{outputs:n.outputs}}),await this.emitEvent(e,{type:le.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:ae.SUCCEEDED,payload:{outputs:n.outputs,fromCache:!0}}),void this.emitNodeStateChanged(e,t,o,a,se.SUCCEEDED,ae.SUCCEEDED)}}try{const d=new _o(e.runId,n.parentRunId,t.workflowId,t.resolved.document,o.instance,o.manifest,a,i,n.metadata,this,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);const h=new Date,f={nodeId:o.id,status:ae.SUCCEEDED,inputs:s,outputs:p,startedAt:r,finishedAt:h,events:[]};e.recordNodeResult(f),await this.emitEvent(e,{type:le.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:ae.SUCCEEDED,payload:{outputs:p}}),this.emitNodeStateChanged(e,t,o,a,se.SUCCEEDED,ae.SUCCEEDED)}catch(i){if(i instanceof ro)throw i;const d=new Date,l=this.toErrorPayload(i),c={nodeId:o.id,status:ae.FAILED,inputs:s,error:l,startedAt:r,finishedAt:d,events:[]};if(e.recordNodeResult(c),await this.emitEvent(e,{type:le.NODE_FAILED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:ae.FAILED,error:l}),this.emitNodeStateChanged(e,t,o,a,se.FAILED,ae.FAILED),n.failFast??1)throw i}}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===Ut||e.isDataEdgeActive(t.id))}async skipInactiveNode(e,t,o,n){const i=new Date,r=[...n.path??[],o.id];await this.emitEvent(e,{type:le.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:r,status:ae.SKIPPED,payload:{reason:"branchNotSelected"}});const a={nodeId:o.id,status:ae.SKIPPED,inputs:{},startedAt:i,finishedAt:new Date,events:[]};e.recordNodeResult(a),this.emitNodeStateChanged(e,t,o,r,se.SKIPPED,ae.SKIPPED)}async executeDisabledNode(e,t,o,n){const i=new Date,r=[...n.path??[],o.id],a=Mo.disabledBehaviorOf(o.instance,t.resolved.document.settings);if(await this.emitEvent(e,{type:le.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:r,status:ae.SKIPPED,payload:{disabled:!0,behavior:a}}),"skip"===a){const n={nodeId:o.id,status:ae.SKIPPED,inputs:{},startedAt:i,finishedAt:new Date,events:[]};return e.recordNodeResult(n),void this.emitNodeStateChanged(e,t,o,r,se.SKIPPED,ae.SKIPPED)}const s=await this.resolveNodeInputs(e,t,o,n);let d;if("passThroughFirstInput"===a){const n=(t.incomingByNode.get(o.id)??[]).find(e=>"data"===e.type),i=o.manifest.outputs[0]?.id??"value",r=n?e.valueStore.getPort(n.sourceNodeId,n.sourcePort):Object.values(s)[0];d={[i]:r}}else{d={};for(const e of o.manifest.outputs)d[e.id]=e.metadata?.defaultValue}e.valueStore.setNodeOutputs(o.id,d),this.routeOutgoingEdges(e,t,o,d);const l={nodeId:o.id,status:ae.SUCCEEDED,inputs:s,outputs:d,startedAt:i,finishedAt:new Date,events:[]};e.recordNodeResult(l),this.emitNodeStateChanged(e,t,o,r,se.SUCCEEDED,ae.SUCCEEDED)}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)),i=Object.keys(t).filter(e=>!n.has(e));if(i.length>0)throw new Yt(`Node '${e.id}' of kind '${e.kind}' produced unknown output(s): ${i.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,unknownOutputs:i});const r=o.outputs.filter(e=>!0===e.required&&!(e.id in t)).map(e=>e.id);if(r.length>0)throw new Yt(`Node '${e.id}' of kind '${e.kind}' did not produce required output(s): ${r.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,missingRequired:r});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??""}:To(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:""}:To(o)&&(t[e]={credentialId:o.credentialId,credentialType:o.credentialType})}return t}async resolveNodeInputs(e,t,o,n){const i={},r=(t.incomingByNode.get(o.id)??[]).filter(e=>"data"===e.type),a=new Map;for(const e of r){const t=a.get(e.targetPort)??[];t.push(e),a.set(e.targetPort,t)}for(const[t,o]of a)if(1===o.length)i[t]=e.valueStore.getPort(o[0].sourceNodeId,o[0].sourcePort);else{let n,r=!1;for(const t of o){const o=e.valueStore.getPort(t.sourceNodeId,t.sourcePort);i[t.sourcePort]=o,void 0!==o&&(n=o,r=!0)}r&&void 0===i[t]&&(i[t]=n)}const s=o.instance.inputBindings??{};for(const e of o.manifest.inputs){const t=s[e.id];if("literal"===t?.mode)i[e.id]=t.value;else if("expression"===t?.mode)i[e.id]=await this.evaluateExpressionBinding(o,t.expression,i,n);else if(void 0===i[e.id]){const t=e.metadata?.defaultValue;void 0!==t&&(i[e.id]=t)}}return i}async resolveNodeParameters(e,t,o){const n=e.instance.parameters??{},i={};for(const[r,a]of Object.entries(n))i[r]=ct(a)?await this.evaluateValueTemplate(a,e,t,o):a;return i}async evaluateValueTemplate(e,t,o,n){const i=this.codeSandboxEvaluator;if(!i)throw new Yt(`Value template on node '${t.id}' requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator`,"GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{nodeId:t.id});const r=e.language??("expression"===e.mode?"javascript":"text"),a="template"===e.mode?(e=>`\`${e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\{\{\s*([\s\S]*?)\s*\}\}/g,(e,t)=>`\${${t}}`)}\``)(e.expression):e.expression,s=n.metadata;return await i.evaluate({code:a,language:"typescript"===r?"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 i=this.codeSandboxEvaluator;if(!i)throw new Yt(`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 r=n.metadata;return await i.evaluate({code:t,language:"javascript",input:o,vars:r?.vars??void 0,item:r?.item,index:r?.index,abortSignal:n.abortSignal})}async tryPinnedValue(e,t,o,n){if(!(new dn).shouldUsePinnedValue(o))return;const i=this.createPinningService(),r=this.computeDependencyFingerprints(e,t,o.id);return i.readPinnedValue(t.workflowId,o,n,r)}computeDependencyFingerprints(e,t,o){const n=this.createPinningService(),i=(new ln).getDependencies(t,o),r={};for(const o of i){const i=t.nodes.find(e=>e.id===o);if(i){const a=e.nodeResults.get(o),s=a?.inputs??{},d=this.computeDependencyFingerprints(e,t,o);r[o]=n.computeFingerprint(t.workflowId,i,s,d)}}return r}routeOutgoingEdges(e,t,o,n){const i=(t.outgoingByNode.get(o.id)??[]).filter(e=>"data"===e.type);for(const r of i){if(!Object.prototype.hasOwnProperty.call(n,r.sourcePort))continue;const i=n[r.sourcePort];e.activateDataEdge(r.id),r.targetNodeId===Ut&&e.valueStore.setWorkflowOutput(r.targetPort,i),this.emitEdgeStateChanged(e,t,o,r,se.SUCCEEDED,ae.SUCCEEDED),this.emitEvent(e,{type:le.EDGE_VALUE_ROUTED,runId:e.runId,workflowId:t.workflowId,edgeId:r.id,nodeId:o.id,path:[],payload:{edge:r,value:i}}).catch(()=>{})}}async emitEvent(e,t){const o=e.eventFactory.create({id:"",sequence:0,timestamp:new Date,...t});e.appendEvent(o),await this.emitter.updateObservers(o)}emitNodeStateChanged(e,t,o,n,i,r){this.emitEvent(e,{type:le.NODE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:n,status:r,payload:{nodeId:o.id,state:i,runId:e.runId,workflowId:t.workflowId,status:r}}).catch(()=>{})}emitEdgeStateChanged(e,t,o,n,i,r){this.emitEvent(e,{type:le.EDGE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,edgeId:n.id,nodeId:o.id,path:[],status:r,payload:{edgeId:n.id,state:i,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,status:r}}).catch(()=>{})}mergeOptions(e){return{concurrency:4,failFast:!0,validateInputs:!0,validateOutputs:!0,maxLoopIterations:Vt,maxForeachIterations:Wt,usePinnedValues:!0,writeThroughCache:!1,path:[],metadata:{},...this.defaultOptions,...e}}executionLimits(e){return{maxLoopIterations:e.maxLoopIterations??Vt,maxForeachIterations:e.maxForeachIterations??Wt}}assertNotAborted(e){if(!0===e.abortSignal?.aborted)throw new ao(e.runId??"unknown")}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new Yt("Cannot generate a graph run id: crypto.randomUUID is unavailable in this runtime","GRAPH_RUN_ID_ERROR",{runtime:typeof globalThis.crypto});return e.randomUUID()}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+""}}}const un=new Set(["process","require","module","exports","global","globalThis","Function","eval","fetch","XMLHttpRequest","WebSocket","Worker","Deno","Bun","__dispatch"]);class pn extends q{constructor(){super()}async initialize(...e){const t=e[0]??{},o=t&&"object"==typeof t?t:{};return this._config=o,this._client=H,{config:o,client:H}}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 Yt("Code sandbox received empty code","GRAPH_CODE_SANDBOX_EMPTY_CODE");const n=((e,t)=>"javascript"===t?e:J.transpileModule(e,{compilerOptions:{target:J.ScriptTarget.ES2022,module:J.ModuleKind.None,strict:!0,noEmitHelpers:!0,importHelpers:!1}}).outputText.replace(/^"use strict";\s*/,""))(o,e.language??"javascript");(e=>{if(e.length>1e5)throw new Yt("Code exceeds the maximum length of 100000 characters","GRAPH_CODE_SANDBOX_CODE_TOO_LONG",{length:e.length});let t;try{t=K.parse(`async function __validate() {\n${e}\n}`,{ecmaVersion:"latest",sourceType:"script"})}catch{try{t=K.parse(e,{ecmaVersion:"latest",sourceType:"module"})}catch(t){throw new Yt("Code failed to parse: "+t.message,"GRAPH_CODE_SANDBOX_PARSE_ERROR",{code:e,error:t.message})}}z.full(t,e=>{const t=e;if("ImportDeclaration"===t.type)throw new Yt("Imports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"import"});if("ExportNamedDeclaration"===t.type||"ExportDefaultDeclaration"===t.type)throw new Yt("Exports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"export"});if("Identifier"===t.type&&"string"==typeof t.name&&un.has(t.name))throw new Yt(`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 Yt("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 Yt("eval() is not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"eval"})})})(n);const i=!(e=>/\breturn\b[\s;]/.test(e))(n),r=i?n.replace(/[\s;]+$/,""):n,a={$input:e.input??{},$vars:e.vars??{},$item:e.item,$index:e.index,$node:e.nodes??{},$output:void 0},s=Object.keys(a),d=i?`return (${r});`:r,l=`"use strict";\nasync function __userFunction(${s.join(", ")}) {\n${d}\n}\n__userFunction(${s.join(", ")}).then(function(__r) { return JSON.stringify({ v: __r }); });`,c=new H.Isolate({memoryLimit:this.defaultMemoryMb}),u=await c.createContext();try{const t=u.global;e.logger&&await this.injectConsole(u,e.logger);for(const[e,o]of Object.entries(a))await t.set(e,new H.ExternalCopy(void 0===o?null:o).copyInto());let o;try{o=await c.compileScript(l,{filename:"graph-code-node.js"})}catch(e){if(!i)throw new Yt("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message});{const e=r,t=`"use strict";\nasync function __userFunction(${s.join(", ")}) {\n${e}\n}\n__userFunction(${s.join(", ")}).then(function(__r) { return JSON.stringify({ v: __r }); });`;try{o=await c.compileScript(t,{filename:"graph-code-node.js"})}catch(e){throw new Yt("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message})}}}const d=e.timeoutMs??this.defaultTimeoutMs;let p;try{p=await this.runBounded(o,u,d,e.abortSignal)}catch(e){if(e instanceof Yt)throw e;const t=e.message;if(t.includes("timed out")||t.includes("timeout"))throw new Yt(`Code execution timed out after ${d} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:d});if(t.includes("memory")||t.includes("heap"))throw new Yt(`Code exceeded the memory limit of ${this.defaultMemoryMb} MB`,"GRAPH_CODE_SANDBOX_MEMORY_LIMIT",{memoryMb:this.defaultMemoryMb});throw new Yt("Code execution failed: "+t,"GRAPH_CODE_SANDBOX_RUNTIME_ERROR",{code:n,error:t})}if("string"!=typeof p)throw new Yt("Code sandbox returned an unexpected non-string result","GRAPH_CODE_SANDBOX_UNEXPECTED_RESULT",{result:p});return JSON.parse(p).v}finally{u.release(),c.dispose()}}async runBounded(e,t,o,n){const i=e.run(t,{timeout:o,promise:!0});i.catch(()=>{});const r=[i];let a,s;try{return r.push(new Promise((e,t)=>{a=setTimeout(()=>{t(new Yt(`Code execution timed out after ${o} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:o}))},o+100)})),n&&r.push(new Promise((e,t)=>{const i=()=>{const e="timeout"===n.reason;t(new Yt(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?i():(n.addEventListener("abort",i,{once:!0}),s=()=>n.removeEventListener("abort",i))})),await Promise.race(r)}finally{a&&clearTimeout(a),s?.()}}async injectConsole(e,t){const o=new H.Reference((e,o)=>{let n;try{n=JSON.parse(o)}catch{n=[o]}const i=n.map(e=>"string"==typeof e?e:JSON.stringify(e)).join(" "),r=1===n.length?n[0]:n;switch(e){case"log":case"info":default:t.info(i,r);break;case"warn":t.warn(i,r);break;case"error":t.error(i,r);break;case"debug":case"dir":case"dirxml":case"table":t.debug(i,r);break;case"trace":t.trace(i,r);break;case"group":case"groupCollapsed":t.debug("[group] "+i,r);break;case"groupEnd":t.debug("[groupEnd]",void 0);break;case"time":case"timeEnd":case"timeLog":case"count":case"countReset":t.debug(`[${e}] ${i}`,r);break;case"assert":n[0]||t.error("Assertion failed: "+i,r);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 hn extends k{constructor(e){super(e,hn.name,500)}}class fn extends _{constructor(e){super(e),this.name=fn.name}}class gn extends _{constructor(e){super(e),this.name=gn.name}}class mn{constructor(e,t,o={}){this.kind=e,this.declarations=new Map,this.implementations=new Map;for(const e of t){if("string"!=typeof e?.name||!e.name)throw new hn(`Method declaration for kind '${this.kind}' is missing a name`);if(this.declarations.has(e.name))throw new hn(`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 hn(`Method implementation '${e}' for kind '${this.kind}' is not a function`);if(!this.declarations.has(e))throw new hn(`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 hn(`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 gn(`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 yn(e,t){if(!t)return;let o=e;for(const e of t.split(".")){if(!o||"object"!=typeof o)return;o=o[e]}return o}function wn(e,t,o){const n=yn(t,e.itemIdPath),i=e.itemLabelPath?yn(t,e.itemLabelPath):void 0;return{id:"string"==typeof n&&n||"number"==typeof n&&Number.isFinite(n)&&n+""||o+"",label:"string"==typeof i?i:void 0}}function bn(e,t){switch(t){case"input":return e.inputs;case"output":return e.outputs;default:return e.connections}}function vn(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))},i=(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 r=bn(o,n.direction);e.forEach((e,t)=>{const{id:o,label:a}=wn(n,e,t),s=(d={id:o,index:t,label:a??o},n.portIdTemplate.replaceAll("${id}",d.id).replaceAll("${index}",d.index+"").replaceAll("${label}",d.label));var d;if(!i(n.direction,s))return;const l=n.defaultPort?Ue(n.defaultPort):{id:s,label:a??s,direction:n.direction};l.id=s,l.direction=n.direction,a&&(l.label=a),r.push(l)})}else if("togglePort"===n.type){if(t[n.parameter]!==n.equals)continue;const e=Ue(n.port);if(!i(e.direction,e.id))continue;bn(o,e.direction).push(e)}return o}function In(e,t){const o=vn(e,t),n={kind:e.kind,display:e.display,inputs:[...e.inputs,...o.inputs],outputs:[...e.outputs,...o.outputs],parameters:e.parameters},i=[...e.connections??[],...o.connections];return i.length&&(n.connections=i),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),Ue(n)}class En{async resolve(e,t,o,n,i){if(o){const r=await o(n,i);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)})(r))throw new hn(`resolveManifest provider for kind '${e}' returned a value that does not conform to GraphResolvedNodeManifest`);if(!Ge(r))throw new hn(`resolveManifest provider for kind '${e}' returned a non-JSON-safe resolved manifest`);const a=Ue(r);return!a.namespaces?.length&&t.namespaces?.length&&(a.namespaces=t.namespaces.slice()),a}return In(t,n.parameters??{})}}const Nn=["edge","literal","expression"];function On(e){return Nn.includes(e)}function An(e,t,o){if("string"!=typeof o||!o)throw new hn(`Manifest for kind '${e}' has a ${t} with an empty port id`);if(Te(o))throw new hn(`Manifest for kind '${e}' has a ${t} with unsafe port id '${o}'`)}let xn=class extends U{constructor(){super(),this.entries=new Map,this.resolver=new En,this.fallbackContext=new j}withContext(e){return e[e.length-1]instanceof j?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 hn("Graph node registration is required");if(!e.manifest||"object"!=typeof e.manifest)throw new hn("Graph node registration is missing a manifest");if(!e.executor||"function"!=typeof e.executor.execute)throw new hn(`Graph node registration for kind '${e.manifest?.kind+""}' is missing an executor`)})(e);const i=e.manifest;if("string"!=typeof i.kind||!i.kind.trim())throw new hn("Graph node manifest kind is required and must be a non-empty string");const r=i.kind;if(this.entries.has(r)&&!t.replace)throw new hn(`Graph node kind '${r}' is already registered; pass { replace: true } to replace it`);try{gt(i)}catch(e){throw new hn(`Manifest for kind '${r}' 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 i of n){if(An(e,t+" port",i?.id),o.has(i.id))throw new hn(`Manifest for kind '${e}' declares duplicate static ${t} port id '${i.id}'`);if(o.add(i.id),void 0!==i.defaultMode&&!On(i.defaultMode))throw new hn(`Manifest for kind '${e}' declares invalid default binding mode '${i.defaultMode+""}' on ${t} port '${i.id}'`)}}})(r,i);const a=((e,t)=>{const o=new Set;for(const n of t.parameters){const t=n?.id;if("string"!=typeof t||!t)throw new hn(`Manifest for kind '${e}' has a parameter with an empty id`);if(Te(t))throw new hn(`Manifest for kind '${e}' has a parameter with unsafe id '${t}'`);if(o.has(t))throw new hn(`Manifest for kind '${e}' declares duplicate parameter id '${t}'`);o.add(t)}return o})(r,i);((e,t,o)=>{for(const n of t.dynamicPorts??[]){if(!n||"string"!=typeof n.parameter||!n.parameter)throw new hn(`Manifest for kind '${e}' has a dynamic-port rule without a parameter reference`);if(!o.has(n.parameter))throw new hn(`Manifest for kind '${e}' has a dynamic-port rule referencing missing parameter '${n.parameter}'`);if("togglePort"===n.type){if(!n.port)throw new hn(`Manifest for kind '${e}' has a togglePort rule without a port`);An(e,"togglePort rule port",n.port.id)}if("repeatFromParameter"===n.type&&"string"!=typeof n.portIdTemplate)throw new hn(`Manifest for kind '${e}' has a repeatFromParameter rule without a portIdTemplate`)}})(r,i,a),((e,t)=>{for(const o of t.credentials??[]){if(!pt(o))throw new hn(`Manifest for kind '${e}' has a malformed credential requirement`);if(!o.type)throw new hn(`Manifest for kind '${e}' has a credential requirement with an empty type`)}})(r,i),((e,t)=>{for(const o of t.methods??[])if(!yt(o))throw new hn(`Manifest for kind '${e}' has a malformed method declaration`)})(r,i);const s=new mn(r,i.methods??[],e.methods??{});return this.entries.set(r,{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 hn("Graph executor kind is required");if(!t||"function"!=typeof t.execute)throw new hn(`Executor registered for kind '${e}' is missing an execute method`);const i=this.entries.get(e);if(i)return i.registration={...i.registration,executor:t},this;const r={kind:e,display:{name:e},inputs:[],outputs:[],parameters:[],policies:{allowUndeclaredParameters:!0,allowUnknownOutputs:!0}};return this.entries.set(e,{registration:{manifest:r,executor:t},methods:new mn(e,[],{}),placeholderManifest:!0}),this}unregister(e,...t){const{log:o}=this.logCtx(this.withContext(t),"unregister").for(this.unregister);return o.debug(`Unregistering graph node kind '${e}'`),this.entries.delete(e),this}has(e,...t){return this.logCtx(this.withContext(t),"has").for(this.has),this.entries.has(e)}entry(e){const t=this.entries.get(e);if(!t)throw new fn(`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),Ue(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,i=e?.kinds?.length?new Set(e.kinds):void 0,r=[];for(const e of o){if(i&&!i.has(e))continue;const o=this.getManifest(e,...t);n&&!n.has(o.display.category??"")||r.push(o)}return r}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 i=this.entry(e);return this.resolver.resolve(e,i.registration.manifest,i.registration.resolveManifest,t,o)}};xn=D([G(),P("design:paramtypes",[])],xn);let kn=class extends U{constructor(e=new xn){super(),this.catalogue=e}get catalog(){return this.catalogue}register(e,t,...o){const{log:n}=this.logCtx(o,"register").for(this.register);if(n.debug(`Registering graph executor for kind '${e}'`),!e)throw new Yt("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 fn)throw new Yt(`No graph executor registered for kind '${e}'`,"GRAPH_EXECUTOR_NOT_FOUND",{kind:e});throw t}}};kn=D([G(),P("design:paramtypes",[xn])],kn);let _n=class extends U{constructor(e,t){super(),this.registry=e,this.defaultExecutor=t}resolve(e,...t){const{log:o}=this.logCtx(t,"resolve").for(this.resolve);return o.debug(`Resolving graph executor for kind '${e}'`),this.registry.has(e,...t)?this.registry.resolve(e,...t):this.defaultExecutor?this.defaultExecutor:this.registry.resolve(e,...t)}};function Dn(e){return e}function Pn(e){return e.methods??[]}function $n(e){if(!e)return;const t={...e.metadata??{},...e.parameters??{},...e.state??{}};return e.loop&&(t.loop=e.loop),t}_n=D([G(),P("design:paramtypes",[Function,Object])],_n);class Sn extends w{constructor(e){super(),w.fromModel(this,e)}execute(e,t){throw new Yt(`Graph node kind '${this.constructor.name}' does not implement execute`,"GRAPH_NODE_EXECUTE_NOT_IMPLEMENTED",{kind:this.constructor.name})}static applyMetadata(e){return null}static instantiate(e){return new this(e)}}let Rn=class extends Sn{execute(e,t){throw new ro(e.inputs.value)}};function Cn(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+""}}D([b(),r("ngx-decaf-crud-field",{label:"graph.node.flow_control.break.fields.value.label",placeholder:"graph.node.flow_control.break.fields.value.placeholder",type:"textarea"}),$e({handle:"value"}),P("design:type",Object)],Rn.prototype,"value",void 0),Rn=D([De("core.flow.break",{kind:"core.flow.break",category:"Flow Control",color:"#f59e0b",icon:"ti-square-arrow-right",width:96,height:96,labels:["flow","break","loop","control"],metadata:{title:"graph.node.flow_control.break.name",description:"graph.node.flow_control.break.description"}}),E()],Rn);let Tn=class extends Sn{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 Yt("errorBoundary node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");try{const i=await n.execute(o.try,e.inputs,{parentRunId:t.runId,path:[...t.path,"try"]}),r=Object.values(i.nodeResults).find(e=>e.status===ae.FAILED);if(r)throw new Yt(r.error?.message??"error boundary try body failed",r.error?.code??"GRAPH_ERROR_BOUNDARY",r.error?.details);return{result:i.outputs.result??i.outputs}}catch(i){let r=i;if(o.catch){const a=await n.execute(o.catch,{...e.inputs,error:Cn(i)},{parentRunId:t.runId,path:[...t.path,"catch"]});r=a.outputs.error??a.outputs}return{error:r}}finally{o.finally&&await n.execute(o.finally,e.inputs,{parentRunId:t.runId,path:[...t.path,"finally"]})}}};D([b(),r("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"}),$e({handle:"value"}),P("design:type",Object)],Tn.prototype,"value",void 0),D([Se({handle:"result"}),P("design:type",Object)],Tn.prototype,"result",void 0),D([Se({handle:"error"}),P("design:type",Object)],Tn.prototype,"error",void 0),Tn=D([De("core.flow.errorBoundary",{kind:"core.flow.errorBoundary",category:"Flow Control",color:"#f59e0b",icon:"ti-shield-check",width:96,height:96,labels:["flow","error","try-catch"],metadata:{title:"graph.node.flow_control.error_boundary.name",description:"graph.node.flow_control.error_boundary.description",finally:!1}}),E()],Tn);let Ln=class extends Sn{execute(e){const t=e.inputs.value??e.inputs;return!1===this.approved?{rejected:t}:{approved:t}}};D([b(),$e({handle:"value"}),P("design:type",Object)],Ln.prototype,"value",void 0),D([r("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"}),$e({handle:"message",userControlled:!0}),P("design:type",String)],Ln.prototype,"message",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.flow_control.human_approval.fields.approved.label",type:"checkbox"}),$e({handle:"approved",userControlled:!0}),P("design:type",Boolean)],Ln.prototype,"approved",void 0),D([Se({handle:"approved"}),P("design:type",Object)],Ln.prototype,"approvedOut",void 0),D([Se({handle:"rejected"}),P("design:type",Object)],Ln.prototype,"rejectedOut",void 0),Ln=D([De("core.flow.humanApproval",{kind:"core.flow.humanApproval",category:"Flow Control",color:"#f59e0b",icon:"ti-user-check",width:96,height:96,labels:["flow","approval","suspend"],metadata:{title:"graph.node.flow_control.human_approval.name",description:"graph.node.flow_control.human_approval.description",approvers:[],timeoutMs:864e5}}),E()],Ln);class jn{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 Yt(`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 Yt("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}}let Mn=class extends Sn{execute(e){const t=e.inputs,o=t.value??t;if(!this.condition)throw new Yt("If node has no condition configured","GRAPH_IF_NO_CONDITION",{input:t});const n=(new jn).evaluate(this.condition,((e,t)=>t===e||"object"!=typeof t||null===t||Array.isArray(t)?e:{...t,...e})(t,o));if(n)return{then:o};if(!0===this.else)return{else:o};throw new Yt("If node condition evaluated to false and the else branch is disabled","GRAPH_IF_ELSE_DISABLED",{condition:this.condition})}};async function Gn(e,t,o,n){if("object"==typeof(i=e)&&null!==i&&"type"in i&&"code"===i.type){const t=n.engine?.codeSandboxEvaluator;if(!t)throw new Yt("Code conditions require a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{code:e.code});await n.log("Evaluating code condition",{language:e.language??"javascript"});const i=n.metadata;return!!await t.evaluate({code:e.code,language:e.language,input:o,vars:i?.vars??void 0,item:i?.item,index:i?.index,nodes:i?.nodes??void 0,logger:n.logger,abortSignal:n.abortSignal})}var i;if((e=>"object"==typeof e&&null!==e&&"op"in e&&"string"==typeof e.op)(e))return(new jn).evaluate(e,t);throw new Yt("Unknown switch case condition type \u2014 must be ConditionExpression (op) or CodeCondition (type: 'code')","GRAPH_UNKNOWN_SWITCH_CONDITION",{condition:e})}D([b(),r("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.value.label",placeholder:"graph.node.flow_control.if.fields.value.placeholder",type:"textarea"}),$e({handle:"value"}),P("design:type",Object)],Mn.prototype,"value",void 0),D([b(),Se({handle:"then"}),P("design:type",Object)],Mn.prototype,"then",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.condition.label",placeholder:"graph.node.flow_control.if.fields.condition.placeholder",type:"code"}),$e({handle:"condition",userControlled:!0,type:"object"}),P("design:type",Object)],Mn.prototype,"condition",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.else.label",type:"checkbox"}),$e({handle:"else",userControlled:!0}),P("design:type",Boolean)],Mn.prototype,"else",void 0),Mn=D([De("core.flow.if",{kind:"core.flow.if",category:"Flow Control",color:"#f59e0b",icon:"ti-arrows-split-2",width:96,height:96,labels:["flow","conditional","branch"],metadata:{title:"graph.node.flow_control.if.name",description:"graph.node.flow_control.if.description"}}),E()],Mn);let Un=class extends Sn{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,i=e.inputs,r=i.value??i,a=((e,t)=>t===e||"object"!=typeof t||null===t||Array.isArray(t)?e:{...t,...e})(i,r);for(const e of n)if(await Gn(e.condition,a,i,t))return{[e.outputPort]:r};if(!0!==o.hasDefault)throw new Yt("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]:r}}static applyMetadata(e){const t=xe(this),o=e.defaultPort??"default",n=!0===e.hasDefault,i=t.ports.filter(t=>!e.cases.some(e=>e.outputPort===t.property)),r=i.filter(e=>e.property!==o),a=i.find(e=>e.property===o),s=[...r,...e.cases.map(e=>({property:e.outputPort,name:e.label,direction:Q.OUTPUT,label:e.label,required:!1,hidden:!1,path:e.outputPort}))];return n&&a&&s.push(a),{ports:s,size:ee(t,{cases:e.cases.length}),dataPatch:{switchMetadata:e}}}};D([b(),r("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.value.label",placeholder:"graph.node.flow_control.switch.fields.value.placeholder",type:"textarea"}),$e({handle:"value"}),P("design:type",Object)],Un.prototype,"value",void 0),D([b(),Se({handle:"default"}),P("design:type",Object)],Un.prototype,"default",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.cases.label",type:"collection"}),P("design:type",Object)],Un.prototype,"cases",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.hasDefault.label",type:"checkbox"}),P("design:type",Boolean)],Un.prototype,"hasDefault",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.defaultPort.label",type:"text"}),P("design:type",String)],Un.prototype,"defaultPort",void 0),Un=D([De("core.flow.switch",{kind:"core.flow.switch",category:"Flow Control",color:"#f59e0b",icon:"ti-arrows-shuffle",width:120,height:140,sizeRules:[{type:"parameterCount",parameter:"cases",dimension:"height",perItem:24}],labels:["flow","switch","multi-branch"],metadata:{title:"graph.node.flow_control.switch.name",description:"graph.node.flow_control.switch.description"}}),E()],Un);const Fn={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},Bn=o.accumulate({graph:{workflows:{limits:{...Fn},allowAnonymousAccess:!1},execution:{maxCodeTimeoutMs:Ht}}}),qn=1e3;function Vn(e,t){const o="number"==typeof e?e:Number(e);return Number.isFinite(o)&&o>0?Math.min(Math.floor(o),t):1e3}const Wn=["javascript","typescript"],Hn="javascript";let Kn=class extends w{constructor(){super(...arguments),this.language=Hn}};D([b(),r("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.language.label",type:"select"}),N([...Wn]),v(String),P("design:type",String)],Kn.prototype,"language",void 0),D([b(),r("code-editor",{label:"graph.node.utility.code.fields.code.label",placeholder:"graph.node.utility.code.fields.code.placeholder"}),$e({handle:"code"}),P("design:type",String)],Kn.prototype,"code",void 0),D([d(),$e({handle:"data"}),P("design:type",Object)],Kn.prototype,"data",void 0),Kn=D([E()],Kn);let zn=class extends Sn{async execute(e,t){const o=e.inputs,n=this.input,i=o.code??e.parameters?.code??n?.code??this.defaultCode,r=n?.language??Hn;if(!i||"string"!=typeof i||0===i.trim().length)throw new Zt("Code node has no code to execute (input.code is empty)",{input:o});const a=t.engine?.codeSandboxEvaluator;if(!a)throw new Yt("Code node execution requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{code:i});const s=Bn.graph.execution?.maxCodeTimeoutMs??Ht,d=Vn(this.timeoutMs,s),l=t.metadata,c={code:i,language:r,input:o,vars:l?.vars??void 0,item:l?.item,index:l?.index,nodes:l?.nodes??void 0,logger:t.logger,timeoutMs:d,abortSignal:t.abortSignal};await t.log("Executing code node",{language:r,length:i.length,timeoutMs:d});const u=await a.evaluate(c);return await t.log("Code node executed",{hasResult:void 0!==u}),{result:u}}};D([b(),$e({handle:"input",model:Kn}),P("design:type",Kn)],zn.prototype,"input",void 0),D([O(1),A(Ht),r("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.timeoutMs.label",type:"number"}),$e({handle:"timeoutMs"}),P("design:type",Number)],zn.prototype,"timeoutMs",void 0),D([r("code-editor",{label:"graph.node.utility.code.fields.defaultCode.label",placeholder:"graph.node.utility.code.fields.defaultCode.placeholder"}),$e({handle:"defaultCode",userControlled:!0}),P("design:type",String)],zn.prototype,"defaultCode",void 0),D([b(),Se({handle:"result"}),P("design:type",Object)],zn.prototype,"result",void 0),zn=D([De("core.utility.code",{kind:"core.utility.code",category:"Utility",color:"#0d9488",icon:"ti-code",width:96,height:96,labels:["utility","code","sandbox","transform"],metadata:{title:"graph.node.utility.code.name",description:"graph.node.utility.code.description"}}),E()],zn);let Jn=class extends Sn{execute(e){return{value:e.inputs.value??e.inputs}}};D([b(),$e({handle:"value"}),P("design:type",Object)],Jn.prototype,"value",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.utility.delay.fields.timeoutMs.label",type:"number"}),$e({handle:"timeoutMs"}),P("design:type",Number)],Jn.prototype,"timeoutMs",void 0),D([b(),Se({handle:"value"}),P("design:type",Object)],Jn.prototype,"valueOut",void 0),Jn=D([De("core.flow.delay",{kind:"core.flow.delay",category:"Utility",color:"#0d9488",icon:"ti-clock-hour-4",width:96,height:96,labels:["flow","delay","wait"],metadata:{title:"graph.node.utility.delay.name",description:"graph.node.utility.delay.description"}}),E()],Jn);let Xn=class extends Sn{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}};D([b(),$e({handle:"value"}),P("design:type",Object)],Xn.prototype,"value",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.message.label",placeholder:"graph.node.utility.log.fields.message.placeholder",type:"textarea"}),$e({handle:"message"}),P("design:type",String)],Xn.prototype,"message",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.level.label",placeholder:"graph.node.utility.log.fields.level.placeholder",type:"text"}),$e({handle:"level",userControlled:!0}),P("design:type",String)],Xn.prototype,"level",void 0),D([b(),Se({handle:"value"}),P("design:type",Object)],Xn.prototype,"valueOut",void 0),Xn=D([De("core.flow.log",{kind:"core.flow.log",category:"Utility",color:"#0d9488",icon:"ti-terminal",width:96,height:96,labels:["flow","log","debug","utility"],metadata:{title:"graph.node.utility.log.name",description:"graph.node.utility.log.description"}}),E()],Xn);let Yn=class extends Sn{execute(e){return{result:{mapped:e.inputs.value??e.inputs}}}};D([b(),r("ngx-decaf-crud-field",{label:"graph.node.utility.map.fields.value.label",placeholder:"graph.node.utility.map.fields.value.placeholder",type:"textarea"}),$e({handle:"value"}),P("design:type",Object)],Yn.prototype,"value",void 0),D([b(),Se({handle:"result"}),P("design:type",Object)],Yn.prototype,"result",void 0),Yn=D([De("core.utility.map",{kind:"core.utility.map",category:"Utility",color:"#0d9488",icon:"ti-arrows-right-left",width:96,height:96,labels:["utility","map","transform"],metadata:{title:"graph.node.utility.map.name",description:"graph.node.utility.map.description",mapper:{}}}),E()],Yn);let Qn=class extends Sn{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}};D([b(),$e({handle:"value"}),P("design:type",Object)],Qn.prototype,"value",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.message.label",placeholder:"graph.node.utility.utility_log.fields.message.placeholder",type:"textarea"}),$e({handle:"message"}),P("design:type",String)],Qn.prototype,"message",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.level.label",placeholder:"graph.node.utility.utility_log.fields.level.placeholder"}),$e({handle:"level",userControlled:!0,type:"string"}),P("design:type",String)],Qn.prototype,"level",void 0),D([b(),Se({handle:"value"}),P("design:type",Object)],Qn.prototype,"valueOut",void 0),Qn=D([De("core.utility.log",{kind:"core.utility.log",category:"Utility",color:"#0d9488",icon:"ti-terminal",width:96,height:96,labels:["utility","log","debug","observability"],metadata:{title:"graph.node.utility.utility_log.name",description:"graph.node.utility.utility_log.description"}}),E()],Qn);let Zn=class extends Sn{execute(e){return{message:e.inputs.message??null,sessionId:e.inputs.sessionId??null,userId:e.inputs.userId??null}}};D([b(),Se({handle:"message"}),P("design:type",String)],Zn.prototype,"message",void 0),D([b(),Se({handle:"sessionId"}),P("design:type",String)],Zn.prototype,"sessionId",void 0),D([b(),Se({handle:"userId"}),P("design:type",String)],Zn.prototype,"userId",void 0),Zn=D([De("core.trigger.chat",{kind:"core.trigger.chat",category:"Trigger",color:"#3b82f6",icon:"ti-message-circle",width:96,height:96,labels:["trigger","chat","entrypoint"],metadata:{title:"graph.node.trigger.chat.name",description:"graph.node.trigger.chat.description",trigger:{type:"chat"}}}),E()],Zn);let ei=class extends Sn{execute(e){return{payload:e.inputs.payload??null}}};D([b(),Se({handle:"payload"}),P("design:type",Object)],ei.prototype,"payload",void 0),ei=D([De("core.trigger.event",{kind:"core.trigger.event",category:"Trigger",color:"#3b82f6",icon:"ti-broadcast",width:96,height:96,labels:["trigger","event","bus"],metadata:{title:"graph.node.trigger.event.name",description:"graph.node.trigger.event.description",trigger:{type:"event",topic:"default"}}}),E()],ei);let ti=class extends Sn{execute(e){return{payload:e.inputs.payload??null}}};D([b(),$e({handle:"schema"}),r("ngx-decaf-model-builder",{label:"graph.node.trigger.form.fields.schema.label",placeholder:"graph.node.trigger.form.fields.schema.placeholder"}),P("design:type",Object)],ti.prototype,"schema",void 0),D([b(),Se({handle:"payload"}),P("design:type",Object)],ti.prototype,"payload",void 0),ti=D([De("core.trigger.form",{kind:"core.trigger.form",category:"Trigger",color:"#3b82f6",icon:"ti-forms",width:96,height:96,labels:["trigger","form","public"],metadata:{title:"graph.node.trigger.form.name",description:"graph.node.trigger.form.description",trigger:{type:"form",fields:[]}}}),E()],ti);let oi=class extends Sn{execute(e){return{payload:e.inputs.payload??null}}};D([b(),Se({handle:"payload"}),P("design:type",Object)],oi.prototype,"payload",void 0),oi=D([De("core.trigger.manual",{kind:"core.trigger.manual",category:"Trigger",color:"#3b82f6",icon:"ti-hand-click",width:96,height:96,labels:["trigger","manual","entrypoint"],metadata:{title:"graph.node.trigger.manual.name",description:"graph.node.trigger.manual.description",trigger:{type:"manual",inputSchema:{}}}}),E()],oi);let ni=class extends Sn{execute(e){return{payload:e.inputs.payload??null}}};D([b(),$e({handle:"cron"}),r("app-cron-selector-field",{label:"graph.node.trigger.schedule.fields.cron.label",placeholder:"graph.node.trigger.schedule.fields.cron.placeholder"}),P("design:type",String)],ni.prototype,"cron",void 0),D([b(),Se({handle:"payload"}),P("design:type",Object)],ni.prototype,"payload",void 0),ni=D([De("core.trigger.schedule",{kind:"core.trigger.schedule",category:"Trigger",color:"#3b82f6",icon:"ti-calendar-time",width:96,height:96,labels:["trigger","schedule","cron"],metadata:{title:"graph.node.trigger.schedule.name",description:"graph.node.trigger.schedule.description",trigger:{type:"schedule",schedule:"0 * * * *",timezone:"UTC"}}}),E()],ni);let ii=class extends Sn{execute(e){return{payload:e.inputs.payload??null}}};D([b(),$e({handle:"schema"}),r("ngx-decaf-model-builder",{label:"graph.node.trigger.webhook.fields.schema.label",placeholder:"graph.node.trigger.webhook.fields.schema.placeholder"}),P("design:type",Object)],ii.prototype,"schema",void 0),D([b(),Se({handle:"payload"}),P("design:type",Object)],ii.prototype,"payload",void 0),ii=D([De("core.trigger.webhook",{kind:"core.trigger.webhook",category:"Trigger",color:"#3b82f6",icon:"ti-webhook",width:96,height:96,labels:["trigger","webhook","http"],metadata:{title:"graph.node.trigger.webhook.name",description:"graph.node.trigger.webhook.description",trigger:{type:"webhook",path:"/webhook",method:"POST",auth:"none",responseMode:"onReceived"}}}),E()],ii);let ri=class extends Sn{execute(e){return{response:"[Agent response] "+(e.inputs.prompt??""),actions:[]}}};D([b(),r("ngx-decaf-crud-field",{label:"graph.node.agent.agent.fields.prompt.label",placeholder:"graph.node.agent.agent.fields.prompt.placeholder",type:"textarea"}),$e({handle:"prompt"}),P("design:type",String)],ri.prototype,"prompt",void 0),D([b(),Se({handle:"response"}),P("design:type",String)],ri.prototype,"response",void 0),D([b(),Se({handle:"actions"}),P("design:type",Array)],ri.prototype,"actions",void 0),D([Re({category:"model",handle:"model"}),P("design:type",Object)],ri.prototype,"model",void 0),D([Re({category:"memory",handle:"memory"}),P("design:type",Object)],ri.prototype,"memory",void 0),D([Re({category:"workspace",handle:"workspace"}),P("design:type",Object)],ri.prototype,"workspace",void 0),ri=D([De("core.agent",{kind:"core.agent",category:"Agent",width:140,height:120,labels:["agent","ai","orchestrator"],metadata:{title:"graph.node.agent.agent.name",description:"graph.node.agent.agent.description",shape:"rectangle"}}),E()],ri);const ai=[ri];function si(e,t,o,n){const i=t??o;if(null==e)return Math.min(o,i);const r=Number(e);if(!Number.isFinite(r)||0>=r)throw new Zt(n+" loop maxIterations must be a positive finite number");return Math.min(Math.floor(r),i)}function di(e,t,o){const n=t.node.loop,i=t.metadata?.loop;if(!n?.body&&!i?.body)throw new Zt(o+" node is missing loop configuration (instance.loop.body)");const r=t=>{const o=e[t]??n?.[t]??i?.[t],r=Number(o);return void 0!==o&&Number.isFinite(r)?r:void 0},a=t=>{const o=e[t]??i?.[t];return"string"==typeof o?o:void 0};return{body:n?.body??i?.body,maxIterations:r("maxIterations"),timeoutMs:r("timeoutMs"),concurrency:r("concurrency"),condition:e.condition??i?.condition,inputPort:a("inputPort"),outputPort:a("outputPort"),itemPort:a("itemPort"),resultPort:a("resultPort"),statePort:a("statePort"),slice:r("slice")}}let li=class extends Sn{async execute(e,t){const o=di(this,t,"foreach"),n=e.inputs,i=n.items,r=si(o.maxIterations,t.limits?.maxForeachIterations,1e3,"foreach");if(!Array.isArray(i))throw new Zt("foreach input 'items' must be an array");const a=t.engine;if(!a)throw new Yt("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(i.length/d):i.length;if(l>r)throw new eo(`foreach exceeded max iterations (${l} > ${r})`);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:le.LOOP_STARTED});for(let e=0;l>e;e++){await t.emit({type:le.LOOP_ITERATION_STARTED,iteration:e});const o=d>1?i.slice(e*d,e*d+d):i[e],n={[c]:o,index:e};d>1&&(n.slice=o),void 0!==g&&(n[p]=g);try{const i=await a.execute(h,n,{parentRunId:t.runId,path:[...t.path,"iteration:"+e],metadata:{item:o,index:e,slice:d},auth:t.auth},t);f.push(i.outputs[u]),void 0!==i.outputs[p]&&(g=i.outputs[p])}catch(o){if(o instanceof ro){const n=o.details?.value;void 0!==n&&f.push(n),m=!0,await t.emit({type:le.LOOP_ITERATION_COMPLETED,iteration:e,metadata:{broken:!0}});break}throw o}await t.emit({type:le.LOOP_ITERATION_COMPLETED,iteration:e})}await t.emit({type:le.LOOP_COMPLETED,metadata:{broken:m}});const y={results:f,completed:f,iterations:f.length,broken:m};return void 0!==g&&(y[p]=g),y}};D([b(),r("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.items.label",placeholder:"graph.node.loop.foreach.fields.items.placeholder",type:"textarea"}),$e({handle:"items"}),P("design:type",Array)],li.prototype,"items",void 0),D([b(),r("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.slice.label",placeholder:"graph.node.loop.foreach.fields.slice.placeholder",type:"number"}),$e({handle:"slice"}),P("design:type",Number)],li.prototype,"slice",void 0),D([b(),Se({handle:"item"}),P("design:type",Object)],li.prototype,"item",void 0),D([b(),Re({handle:"loop",connectionRules:{allowSelf:!0,maxConnections:1}}),P("design:type",Object)],li.prototype,"loop",void 0),D([b(),Se({handle:"completed"}),P("design:type",Array)],li.prototype,"completed",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.maxIterations.label",type:"number"}),$e({handle:"maxIterations",userControlled:!0}),P("design:type",Number)],li.prototype,"maxIterations",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.condition.label",type:"code"}),$e({handle:"condition",userControlled:!0}),P("design:type",Object)],li.prototype,"condition",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.itemPort.label",type:"text"}),$e({handle:"itemPort",userControlled:!0}),P("design:type",String)],li.prototype,"itemPort",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.resultPort.label",type:"text"}),$e({handle:"resultPort",userControlled:!0}),P("design:type",String)],li.prototype,"resultPort",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.statePort.label",type:"text"}),$e({handle:"statePort",userControlled:!0}),P("design:type",String)],li.prototype,"statePort",void 0),li=D([De("graph-foreach-loop-node",{kind:"core.loop.foreach",category:"Loop",color:"#eab308",icon:"ti-repeat",width:120,height:140,labels:["loop","iteration","foreach"],metadata:{title:"graph.node.loop.foreach.name",description:"graph.node.loop.foreach.description",loop:{maxIterations:100,itemPort:"item",resultPort:"result",slice:1}}}),E()],li);class ci{constructor(){this.expressionEvaluator=new jn}evaluate(e,t){if(this.isConditionExpression(e))return this.expressionEvaluator.evaluate(e,t);const o=this.resolveValue(e.left,t),n=e.right;switch(e.type){case Jt.TRUTHY:return!!o;case Jt.FALSY:return!o;case Jt.EQUALS:return o===n;case Jt.NOT_EQUALS:return o!==n;case Jt.GREATER_THAN:return Number(o)>Number(n);case Jt.GREATER_THAN_OR_EQUAL:return Number(o)>=Number(n);case Jt.LESS_THAN:return Number(n)>Number(o);case Jt.LESS_THAN_OR_EQUAL:return Number(n)>=Number(o);case Jt.EXISTS:return null!=o;case Jt.CUSTOM:throw new Yt("Custom condition evaluators are not supported in v1","GRAPH_CUSTOM_CONDITION_UNSUPPORTED");default:throw new Yt(`Unknown condition type '${e.type}'`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition:e})}}resolveValue(e,t){if(!e)return t;const o=e.split(".");let n=t;for(const e of o){if(null==n)return;n=n[e]}return n}isConditionExpression(e){return"string"==typeof e.op}}let ui=class extends Sn{async execute(e,t){const o=di(this,t,"until"),n=e.inputs,i=si(o.maxIterations,t.limits?.maxLoopIterations,100,"until"),r=o.condition;if(!r)throw new Zt("until node is missing a condition");const a=o.statePort??"state",s=o.inputPort??a,d=o.outputPort??a,l=o.body,c=t.engine;if(!c)throw new Yt("until node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;await t.emit({type:le.LOOP_STARTED});let h=!1;do{if(p>=i)throw await t.emit({type:le.LOOP_LIMIT_REACHED,iteration:p}),new eo(`until loop exceeded max iterations (${i})`);await t.emit({type:le.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:le.LOOP_ITERATION_COMPLETED,iteration:p});const e=(new ci).evaluate(r,u);await t.emit({type:le.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:e}}),p++,h=e}while(!h);return await t.emit({type:le.LOOP_COMPLETED}),{state:u,iterations:p}}};D([b(),r("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.state.label",placeholder:"graph.node.loop.until.fields.state.placeholder",type:"textarea"}),$e({handle:"state"}),P("design:type",Object)],ui.prototype,"state",void 0),D([b(),Se({handle:"state"}),P("design:type",Object)],ui.prototype,"stateOut",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.maxIterations.label",type:"number"}),$e({handle:"maxIterations",userControlled:!0}),P("design:type",Number)],ui.prototype,"maxIterations",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.condition.label",type:"code"}),$e({handle:"condition",userControlled:!0}),P("design:type",Object)],ui.prototype,"condition",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.statePort.label",type:"text"}),$e({handle:"statePort",userControlled:!0}),P("design:type",String)],ui.prototype,"statePort",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.inputPort.label",type:"text"}),$e({handle:"inputPort",userControlled:!0}),P("design:type",String)],ui.prototype,"inputPort",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.outputPort.label",type:"text"}),$e({handle:"outputPort",userControlled:!0}),P("design:type",String)],ui.prototype,"outputPort",void 0),ui=D([De("graph-until-loop-node",{kind:"core.loop.until",category:"Loop",color:"#eab308",icon:"ti-player-stop",width:96,height:96,labels:["loop","conditional","until"],metadata:{title:"graph.node.loop.until.name",description:"graph.node.loop.until.description",loop:{maxIterations:50,statePort:"state",condition:{type:"greaterThanOrEqual",left:"iteration",right:2}}}}),E()],ui);let pi=class extends Sn{async execute(e,t){const o=di(this,t,"while"),n=e.inputs,i=si(o.maxIterations,t.limits?.maxLoopIterations,100,"while"),r=o.condition;if(!r)throw new Zt("while node is missing a condition");const a=o.statePort??"state",s=o.inputPort??a,d=o.outputPort??a,l=o.body,c=t.engine;if(!c)throw new Yt("while node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;for(await t.emit({type:le.LOOP_STARTED});(new ci).evaluate(r,u);){if(p>=i)throw await t.emit({type:le.LOOP_LIMIT_REACHED,iteration:p}),new eo(`while loop exceeded max iterations (${i})`);await t.emit({type:le.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:!0}}),await t.emit({type:le.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:le.LOOP_ITERATION_COMPLETED,iteration:p}),p++}return await t.emit({type:le.LOOP_COMPLETED}),{state:u,iterations:p}}};D([b(),r("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.state.label",placeholder:"graph.node.loop.while.fields.state.placeholder",type:"textarea"}),$e({handle:"state"}),P("design:type",Object)],pi.prototype,"state",void 0),D([b(),Se({handle:"state"}),P("design:type",Object)],pi.prototype,"stateOut",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.maxIterations.label",type:"number"}),$e({handle:"maxIterations",userControlled:!0}),P("design:type",Number)],pi.prototype,"maxIterations",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.condition.label",type:"code"}),$e({handle:"condition",userControlled:!0}),P("design:type",Object)],pi.prototype,"condition",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.statePort.label",type:"text"}),$e({handle:"statePort",userControlled:!0}),P("design:type",String)],pi.prototype,"statePort",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.inputPort.label",type:"text"}),$e({handle:"inputPort",userControlled:!0}),P("design:type",String)],pi.prototype,"inputPort",void 0),D([r("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.outputPort.label",type:"text"}),$e({handle:"outputPort",userControlled:!0}),P("design:type",String)],pi.prototype,"outputPort",void 0),pi=D([De("graph-while-loop-node",{kind:"core.loop.while",category:"Loop",color:"#eab308",icon:"ti-arrows-loop",width:96,height:96,labels:["loop","conditional","while"],metadata:{title:"graph.node.loop.while.name",description:"graph.node.loop.while.description",loop:{maxIterations:50,statePort:"state",condition:{type:"lessThan",left:"iteration",right:3}}}}),E()],pi);let hi=class extends Sn{execute(e){const t=e.inputs;return{value:t?.value??null}}};D([Se({handle:"value",connectionRules:{allowMultiple:!0}}),P("design:type",Object)],hi.prototype,"value",void 0),hi=D([De("graph-input-value-node",{kind:"value",category:"Boundary",color:"#0f766e",icon:"ti-circle-plus",labels:["workflow","input","value"],metadata:{title:"graph.node.boundary.input.name",description:"graph.node.boundary.input.description"}}),E()],hi);let fi=class extends Sn{execute(e){return{}}};function gi(e,t,o,n={}){return{id:e,label:t,direction:o,...n}}function mi(e){const t=e,o=be(t),n=o?.metadata?.title;return Ct(t,n?{name:n}:{})}D([b(),$e({handle:"value"}),P("design:type",Object)],fi.prototype,"value",void 0),fi=D([De("graph-output-value-node",{kind:"result",category:"Boundary",color:"#0f766e",icon:"ti-circle-minus",width:96,height:96,labels:["workflow","output","value"],metadata:{title:"graph.node.boundary.output.name",description:"graph.node.boundary.output.description"}}),E()],fi);const yi={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:[gi("items","graph.node.loop.foreach.ports.input.items.label","input",{required:!0,schema:{type:"array",items:{type:"any"}}}),gi("slice","graph.node.loop.foreach.ports.input.slice.label","input",{schema:{type:"number",integer:!0,min:1}}),gi("state","graph.node.loop.foreach.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[gi("results","graph.node.loop.foreach.ports.output.results.label","output",{schema:{type:"array",items:{type:"any"}}}),gi("completed","graph.node.loop.foreach.ports.output.completed.label","output",{schema:{type:"array",items:{type:"any"}}}),gi("iterations","graph.node.loop.foreach.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}}),gi("broken","graph.node.loop.foreach.ports.output.broken.label","output",{schema:{type:"boolean"}}),gi("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}]},wi={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:[gi("state","graph.node.loop.while.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[gi("state","graph.node.loop.while.ports.output.state.label","output",{schema:{type:"any"}}),gi("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"}]},bi={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:[gi("state","graph.node.loop.until.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[gi("state","graph.node.loop.until.ports.output.state.label","output",{schema:{type:"any"}}),gi("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"}]},vi=[mi(hi),mi(fi),mi(oi),mi(ii),mi(ni),mi(ei),mi(ti),mi(Zn),(Ii=mi(Mn),{...Ii,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"}}}]}))(mi(Un)),mi(Yn),mi(Jn),mi(Tn),mi(Ln),mi(zn),mi(Xn),mi(Qn),mi(Rn),mi(ri),yi,wi,bi];var Ii;const Ei=Object.fromEntries(vi.map(e=>[e.kind,e])),Ni=[oi,ii,ni,ei,ti,Zn],Oi=[Mn,Un,Jn,Tn,Ln,Xn,Rn],Ai=[zn,Yn,Qn],xi=[li,pi,ui],ki=[hi,fi],_i={value:hi,result:fi,"core.trigger.manual":oi,"core.trigger.webhook":ii,"core.trigger.schedule":ni,"core.trigger.event":ei,"core.trigger.form":ti,"core.trigger.chat":Zn,"core.flow.if":Mn,"core.flow.switch":Un,"core.utility.map":Yn,"core.flow.delay":Jn,"core.flow.errorBoundary":Tn,"core.flow.humanApproval":Ln,"core.utility.code":zn,"core.flow.log":Xn,"core.utility.log":Qn,"core.flow.break":Rn,"core.agent":ri,"core.loop.foreach":li,"core.loop.while":pi,"core.loop.until":ui};function Di(e){return{execute:(t,o)=>e.instantiate({...$n(o.node),...t.parameters,...o.node.state??{}}).execute(t,o)}}function Pi(){const e=[];for(const[t,o]of Object.entries(Ei)){const n=_i[t];n&&e.push(Dn({manifest:o,executor:Di(n)}))}return e}function $i(e,...t){for(const o of Pi())e.register(o,{},...t);return e}class Si{resolve(e){const t=this.createValidator(e);return{name:e.name,required:e.required,validate:t}}resolveAll(e){const t={};for(const o of e)t[o.name]=this.resolve(o);return t}createValidator(e){switch((e.type??e.designType??"").toLowerCase()){case"string":return e=>"string"==typeof e;case"number":return e=>"number"==typeof e;case"boolean":return e=>"boolean"==typeof e;case"date":return e=>e instanceof Date||"string"==typeof e&&!isNaN(Date.parse(e));case"array":return e=>Array.isArray(e);case"bigint":return e=>"bigint"==typeof e;default:return()=>!0}}}class Ri{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 Zt(`Missing required ${o} port '${n.name}'`);if(e&&!this.resolver.resolve(n).validate(t[n.name]))throw new Zt(`Invalid value for ${o} port '${n.name}'`)}}}const Ci=["node","definition","executor","execute","ports","component"];function Ti(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 Li(e,t){const o=[];for(const n of Object.keys(e))Ci.includes(n)&&o.push(Ti("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 ji(e,t){t.push(...Li(e,"$")),e.inputs.forEach((e,o)=>t.push(...Li(e,`inputs[${o}]`))),e.outputs.forEach((e,o)=>t.push(...Li(e,`outputs[${o}]`)));for(const o of e.nodes)t.push(...Li(o,`nodes[${o.id}]`)),o.loop&&(t.push(...Li(o.loop,`nodes[${o.id}].loop`)),ji(o.loop.body,t));for(const o of e.edges)t.push(...Li(o,`edges[${o.id}]`))}function Mi(e,t){const o=[];e.nodes.length>t.maxNodes&&o.push(Ti("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(Ti("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=Gi(e);n>t.maxNestingDepth&&o.push(Ti("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 i=Buffer.byteLength(JSON.stringify(e),"utf8");return i>t.maxDocumentBytes&&o.push(Ti("document.limit.size","$",`Document serializes to ${i} bytes; at most ${t.maxDocumentBytes} bytes are allowed`,{details:{bytes:i,limit:t.maxDocumentBytes}})),o}function Gi(e,t=0){let o=t;for(const n of e.nodes)n.loop?.body&&(o=Math.max(o,Gi(n.loop.body,t+1)));return o}async function Ui(e,t,...o){const n=[];for(const i of e.nodes)t.has(i.kind,...o)||n.push(Ti("node.unknown-kind",`nodes[${i.id}].kind`,`Node '${i.id}' references kind '${i.kind}' which is not registered in the backend catalogue`,{nodeId:i.id,details:{kind:i.kind}})),i.loop?.body&&n.push(...await Ui(i.loop.body,t,...o));return n}async function Fi(e,t={},...o){const n={...Fn,...t.limits},i=[];if(!ut(e))return i.push(Ti("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:i};if(!Ge(e))return i.push(Ti("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:i};ji(e,i),i.push(...(e=>{const t=[],o=new Set;for(const n of[...e.inputs,...e.outputs])o.has(n.id)?t.push(Ti("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(Ti("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 i=new Set;for(const o of e.edges)i.has(o.id)?t.push(Ti("document.duplicate-edge-id",`edges[${o.id}]`,`Edge '${o.id}' is declared more than once; edge ids must be unique`,{edgeId:o.id})):i.add(o.id);return t})(e)),i.push(...Mi(e,n)),So(e,i);try{tt(e)}catch(e){const t=e instanceof x?e.message:e+"";i.push(Ti("document.structure","$",t))}return t.catalogue&&i.push(...await Ui(e,t.catalogue,...o)),{valid:0===i.length,issues:i}}class Bi{constructor(e,t){this.iteration=e,this.metadata=t}}function qi(e,t,o){const n=e?.owner??null;if(n&&n!==t&&(null!=t&&""!==t||!0!==o.allowAnonymousAccess))throw new L(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function Vi(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>Vi(e)).join(",")}]`;const t=e;return`{${Object.keys(t).filter(e=>void 0!==t[e]).sort().map(e=>`${JSON.stringify(e)}:${Vi(t[e])}`).join(",")}}`}function Wi(e){return X("sha256").update(Vi(e)).digest("hex")}class Hi{constructor(e={}){this.events=new Map,this.listeners=new Map,this.limits={...ce,...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=>!pe(e.type));if(-1===t)break;e.splice(t,1)}}}class Ki{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}release(e){this.runs.delete(e)}}class zi{constructor(e,t={}){this.sequences=new Map,this.chains=new Map,this.store=e,this.limits={...ce,...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()},i=(this.chains.get(t)??Promise.resolve()).then(()=>this.store.append(n));return this.chains.set(t,i.catch(()=>{})),await i,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 Ji{constructor(e,t,o,n={},i={}){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={...ce,...i}}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 i=this.completions.get(e.runId);if(i)return i;const r=this.runExecution({...e},t,o,...n).catch(async t=>{const o=Xi(t);try{await this.emitTerminal({...e},le.WORKFLOW_FAILED,o)}catch{}return await this.finalize({...e},"failed",void 0,o,...n)});return this.completions.set(e.runId,r),r}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 i=e.runId;let r,a,s=!1;const d=this.engine.observe({refresh:async t=>{t.runId===i&&(t.error&&(r=t.error),pe((await this.publisher.publish(this.envelopeOf(e,t))).type)?s=!0:t.type===le.WORKFLOW_STARTED&&"validating"===e.status&&(e.status="running",await this.persist(e,...n)))}});this.armTimeout(i);try{if(this.isAborted(i)){const t={name:"GraphRunCancelledError",message:`Graph run '${i}' was cancelled before execution started`,code:"GRAPH_RUN_CANCELLED"};return r=t,await this.emitTerminal(e,le.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=Xi(t);return r=o,s||(await this.emitTerminal(e,le.WORKFLOW_FAILED,o),s=!0),await this.finalize(e,"failed",void 0,o,...n)}if(this.isAborted(i)){const t={name:"GraphRunCancelledError",message:`Graph run '${i}' was cancelled before execution started`,code:"GRAPH_RUN_CANCELLED"};return r=t,s||(await this.emitTerminal(e,le.WORKFLOW_CANCELLED,t),s=!0),await this.finalize(e,"cancelled",void 0,t,...n)}try{a=await this.engine.execute(d,o,{runId:i,abortSignal:this.controllers.get(i)?.signal,metadata:{documentFingerprint:l}},...n)}catch(e){r=Xi(e)}const c=this.abortReason(i);let u,p;return"timeout"===c?(u="failed",p=r??{name:"GraphRunTimeoutError",message:`Graph run '${i}' exceeded the configured execution timeout of ${this.limits.executionTimeoutMs}ms`,code:"GRAPH_RUN_TIMEOUT"}):"user"===c?(u="cancelled",p=r):a?.status===ae.SUCCEEDED?u="succeeded":a?.status===ae.CANCELLED?(u="cancelled",p=r):(u="failed",p=r??Xi(new Yt(a?`Graph run '${i}' failed`:`Graph run '${i}' failed without a result`,"GRAPH_RUN_FAILED",{runId:i}))),s||await this.emitTerminal(e,"succeeded"===u?le.WORKFLOW_COMPLETED:"cancelled"===u?le.WORKFLOW_CANCELLED:le.WORKFLOW_FAILED,p),await this.finalize(e,u,a,p,...n)}finally{d();const e=this.timeouts.get(i);e&&(clearTimeout(e),this.timeouts.delete(i))}}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,...i){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,...i);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:Me(t.payload)?t.payload:{nonSerializable:!0},error:t.error,parentRunId:t.parentRunId,path:t.path}}}function Xi(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 Yi{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 zi(o,n.limits),this.executor=new Ji(e,t,this.publisher,{onRunCompleted:n.onRunCompleted},n.limits),this.options={...n,limits:{...ce,...n.limits}}}get limits(){return this.options.limits}async createRun(e,t,o,...n){this.validateCreateRequest(e);const i=e.workflowId??e.workflow?.id??"";if(!i)throw new x("Graph run request must carry a workflow document with an id or a saved workflowId");if(e.workflowId&&!this.options.documentResolver)throw new x("Graph run requests by workflowId require a document resolver");const r=o??t??"anonymous",a=this.activeByCaller.get(r)??new Set;if(a.size>=this.options.limits.maxConcurrentRuns)throw new x(`Graph run rejected: the configured limit of ${this.options.limits.maxConcurrentRuns} concurrent runs per caller is exhausted`);const s=this.generateRunId(),d={runId:s,workflowId:i,ownerUser:t,status:"queued",createdAt:(new Date).toISOString()};this.executor.begin(s),await this.runStore.saveRun({...d},...n);const l=this.documentProviderFor(e,t);return a.add(s),this.activeByCaller.set(r,a),this.callerKeysByRun.set(s,r),this.executor.schedule(d,l,e.inputs??{},...n).catch(()=>{}).finally(()=>this.finishActiveRun(s)),d}async getRun(e,t,...o){const n=await this.runStore.readRun(e,...o);if(!n)throw new _(`No graph run found for runId '${e}'`);return this.assertOwnership(n,t),n}async cancelRun(e,t,...o){const n=await this.runStore.readRun(e,...o);if(!n)throw new _(`No graph run found for runId '${e}'`);return this.assertOwnership(n,t),"succeeded"===(i=n.status)||"failed"===i||"cancelled"===i||(this.executor.abort(e,"user"),n.status="cancelled",n.finishedAt=(new Date).toISOString(),await this.runStore.saveRun({...n},...o)),n;var i}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 i=await this.createRun(e,t,o,...n);return this.waitForRun(i.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 x("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 x("Graph run request is ambiguous: supply either an unsaved workflow document or a saved workflowId, not both");if(!t&&!o)throw new x("Graph run request must supply either an unsaved workflow document or a saved workflowId");if(t&&!ut(e.workflow))throw new x("Graph run request carries a payload that is not a canonical GraphWorkflowDocument");if(void 0!==e.inputs&&!Ge(e.inputs))throw new x("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 x(`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:Wi(t)})}const o=e.workflowId;return async(...e)=>{const n=this.options.documentResolver;if(!n)throw new x("Graph run requests by workflowId require a document resolver");const i=await n.resolve(o,t,...e);return{document:i,fingerprint:Wi(i)}}}assertOwnership(e,t){qi({owner:e.ownerUser},t,{allowAnonymousAccess:!0===this.options.allowAnonymousAccess,resourceKind:"Graph run",resourceId:e.runId})}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new no("Cannot generate a graph run id: crypto.randomUUID is unavailable in this runtime",{runtime:typeof globalThis.crypto});return e.randomUUID()}}function Qi(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 Zi(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&ut(e.document)&&!ut(e)}function er(e){return JSON.parse(JSON.stringify(e))}let tr=class extends W{constructor(e){super(Lt),this.catalogue=e}get limits(){return{...Fn,...Bn.graph.workflows.limits??{}}}get allowAnonymousAccess(){return!0===Bn.graph.workflows.allowAnonymousAccess}async saveDocument(e,t,...o){const{ctx:n,ctxArgs:i}=(await this.logCtx(o,"saveDocument",!0)).for(this.saveDocument);if(!ut(t))throw new x("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 x(`Document id '${t.id}' does not match the workflow id '${e}' from the request path`);const r=await this.validateDocument(t,n);if(!r.valid)throw new so(r.issues);const a=Qi(n);let s;try{s=await this.read(e,...i)}catch{s=null}this.assertOwnership(e,s,a);const d=new Date;if(s)return s.name=t.name,s.document=er(t),s.updatedAt=d,this.update(s,...i);const l=new Lt({workflowId:e,name:t.name,document:er(t),...a?{owner:a}:{},updatedAt:d});return this.create(l,...i)}async getDocument(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"getDocument",!0)).for(this.getDocument);let i;try{i=await this.read(e,...n)}catch{i=null}if(!i)throw new _(`No graph workflow found for workflowId '${e}'`);if(this.assertOwnership(e,i,Qi(o)),i.document)return er(i.document);throw new _(`Graph workflow '${e}' has no canonical document; legacy definition/state snapshots are no longer supported (DECAF-50 \xa74.26 R2-2)`)}async validateDocument(e,...t){const{ctx:o}=(await this.logCtx(t,"validateDocument",!0)).for(this.validateDocument);return await Fi(e,{limits:this.limits,...this.catalogue?{catalogue:this.catalogue}:{}},o)}async saveSnapshot(e,t,...o){const{ctx:n,ctxArgs:i}=(await this.logCtx(o,"saveSnapshot",!0)).for(this.saveSnapshot);if(!Ge(t))throw new x("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(!Zi(t))throw new x("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 r=Qi(n);let a;try{a=await this.read(e,...i)}catch{a=null}this.assertOwnership(e,a,r);const s=new Date;if(a)return a.snapshot=t,await this.applyCanonicalWrapper(a,t,n),a.updatedAt=s,this.update(a,...i);const d=new Lt({workflowId:e,snapshot:t,...r?{owner:r}:{},updatedAt:s});return await this.applyCanonicalWrapper(d,t,n),this.create(d,...i)}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,Qi(o)),t}catch{return null}}assertOwnership(e,t,o){qi(t??null,o??null,{allowAnonymousAccess:this.allowAnonymousAccess,resourceKind:"Graph workflow",resourceId:e})}async applyCanonicalWrapper(e,t,o){if(!Zi(t))return;if(t.document.id!==e.workflowId)throw new x(`Document id '${t.document.id}' does not match the workflow id '${e.workflowId}' from the request path`);const n=await Fi(t.document,{limits:this.limits,...this.catalogue?{catalogue:this.catalogue}:{}},o);if(!n.valid)throw new so(n.issues);e.document=er(t.document),e.name=t.document.name}};function or(e){if(null!=e)return JSON.parse(JSON.stringify(e))}tr=D([G(Lt),P("design:paramtypes",[Function])],tr);let nr=class extends W{constructor(){super(Tt)}async saveRun(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"saveRun",!0)).for(this.saveRun),n=(e=>new Tt({runId:e.runId,workflowId:e.workflowId,...e.ownerUser?{owner:e.ownerUser}:{},status:e.status,...e.documentFingerprint?{documentFingerprint:e.documentFingerprint}:{},...void 0!==e.result?{result:or(e.result)}:{},...e.error?{error:or(e.error)}:{},createdAt:new Date(e.createdAt),...e.startedAt?{startedAt:new Date(e.startedAt)}:{},...e.finishedAt?{finishedAt:new Date(e.finishedAt)}:{}}))(e);let i;try{i=await super.read(e.runId,...o)}catch{i=null}if(i)return i.workflowId=n.workflowId,i.owner=n.owner,i.status=n.status,i.documentFingerprint=n.documentFingerprint,i.result=n.result,i.error=n.error,i.startedAt=n.startedAt,i.finishedAt=n.finishedAt,void await this.update(i,...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}}};nr=D([G(Tt),P("design:paramtypes",[])],nr);class ir{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:ae.SUCCEEDED,lastValue:t.payload?.value,updatedAt:t.timestamp.toISOString()});const n=[...e.events];return{runId:e.runId,status:e.status,nodes:t,edges:o,outputs:e.outputs,events:n}}}export{ri as AgentNode,Rn as BreakFlowNode,Zn as ChatTriggerNode,Kn as CodeInputSchema,zn as CodeNode,jn as ConditionExpressionEvaluator,Fn as DEFAULT_GRAPH_WORKFLOW_DOCUMENT_LIMITS,Wo as DEFAULT_GRAPH_WORKFLOW_VALIDATION_LIMITS,an as DEFAULT_PINNING_METADATA,Jn as DelayFlowNode,Tn as ErrorBoundaryFlowNode,ei as EventTriggerNode,ti as FormTriggerNode,ai as GRAPH_AGENT_NODES,ki as GRAPH_BOUNDARY_NODES,_i as GRAPH_BUILT_IN_NODE_CLASSES_BY_KIND,vi as GRAPH_BUILT_IN_NODE_MANIFESTS,Ei as GRAPH_BUILT_IN_NODE_MANIFESTS_BY_KIND,Hn as GRAPH_CODE_DEFAULT_LANGUAGE,qn as GRAPH_CODE_DEFAULT_TIMEOUT_MS,Wn as GRAPH_CODE_LANGUAGES,Ht as GRAPH_CODE_MAX_TIMEOUT_MS,Ft as GRAPH_DEFAULT_CONCURRENCY,qt as GRAPH_DEFAULT_MAX_FOREACH_ITERATIONS,Bt as GRAPH_DEFAULT_MAX_LOOP_ITERATIONS,Ho as GRAPH_DOCUMENT_FORBIDDEN_FIELD_KEYS,Oi as GRAPH_FLOW_CONTROL_NODES,Xt as GRAPH_LOOP_KIND,xi as GRAPH_LOOP_NODES,Wt as GRAPH_MAX_FOREACH_ITERATIONS,Vt as GRAPH_MAX_LOOP_ITERATIONS,Kt as GRAPH_PINNING_METADATA_KEY,jo as GRAPH_PLAIN_SECRET_KEYS,Ni as GRAPH_TRIGGER_NODES,Ai as GRAPH_UTILITY_NODES,Ut as GRAPH_WORKFLOW_BOUNDARY,Ci as GRAPH_WORKFLOW_FORBIDDEN_FIELD_KEYS,Ao as GraphAuthValidator,ro as GraphBreakSignal,ci as GraphConditionEvaluator,Jt as GraphConditionType,Uo as GraphConnectionPolicyValidator,qo as GraphConnectionValidationError,Vo as GraphCredentialAuthorizationError,Fo as GraphCredentialReferenceValidator,Qt as GraphCycleError,Bo as GraphDocumentValidationError,Go as GraphEdgeInstanceValidator,Bn as GraphEnvironment,_o as GraphExecutionContext,cn as GraphExecutionEngine,Yt as GraphExecutionError,lo as GraphExecutionEventEmitter,co as GraphExecutionEventFactory,Do as GraphExecutionFrame,Xo as GraphExecutionPlanner,ir as GraphExecutionSnapshotMapper,li as GraphForeachLoopNode,Zt as GraphInputError,hi as GraphInputValueNode,Bi as GraphLoopExecutionContext,eo as GraphLoopLimitError,Sn as GraphNode,xn as GraphNodeCatalogue,kn as GraphNodeExecutorRegistry,_n as GraphNodeExecutorResolver,$o as GraphNodeInstanceValidator,En as GraphNodeManifestResolver,gn as GraphNodeMethodNotFoundError,mn as GraphNodeMethodRegistry,fn as GraphNodeNotFoundError,hn as GraphNodeRegistrationError,fi as GraphOutputValueNode,Mo as GraphParameterValidator,ln as GraphPinningDependencyResolver,to as GraphPinningError,dn as GraphPinningPolicy,rn as GraphPinningService,zt as GraphPinningStrategy,oo as GraphPortError,Si as GraphPortSchemaResolver,ao as GraphRunCancelledError,zi as GraphRunEventPublisher,Ji as GraphRunExecutor,nr as GraphRunModelService,Yi as GraphRunService,no as GraphStoreError,nn as GraphTopology,io as GraphTopologyError,ui as GraphUntilLoopNode,Yo as GraphValueModel,tn as GraphValueRepository,Ri as GraphValueValidator,pi as GraphWhileLoopNode,so as GraphWorkflowDocumentRejectedError,Jo as GraphWorkflowDocumentValidator,tr as GraphWorkflowService,Ln as HumanApprovalFlowNode,Mn as IfFlowNode,Hi as InMemoryGraphRunEventStore,Ki as InMemoryGraphRunStore,pn as IsolatedVmCodeSandboxEvaluator,Xn as LogFlowNode,oi as ManualTriggerNode,Yn as MapNode,ni as ScheduleTriggerNode,Un as SwitchFlowNode,Qn as UtilityLogNode,ii as WebhookTriggerNode,qi as assertGraphResourceOwnership,Po as buildGraphExecutionResult,Pi as builtInGraphNodeRegistrations,Ro as checkGraphValueAgainstSchema,Vn as clampGraphCodeTimeoutMs,So as collectLooseNodeIssues,po as composeGraphNamespace,on as createGraphValueRepository,Pn as declaredGraphNodeMethods,uo as decomposeGraphNamespace,No as decomposeGraphNamespaces,Dn as defineGraphNode,yo as findMalformedGraphNamespaces,mo as findUngrantedGraphNamespaces,Io as graphAuthDataFromRecord,Eo as graphAuthDataOf,go as graphNamespaceCovers,fo as graphNamespacePartsOf,$n as graphNodeConfig,wo as graphRolesFromNamespaces,Wi as graphRunDocumentFingerprint,Qi as graphWorkflowOwnerOf,To as isGraphCredentialReferenceLike,ho as isGraphNamespaceCacheEntryValid,Ko as isGraphResolvedWorkflow,sn as isPinnable,Oo as mergeGraphAuthData,$i as registerBuiltInGraphNodes,vn as resolveGraphDynamicPorts,In as resolveGraphNodeManifest,Qo as serializeGraphValueKey,Fi as validateGraphWorkflowDocumentAtBoundary};
|
|
1
|
+
import{logParameterRegistry as e,Logging as t,LoggedEnvironment as o}from"@decaf-ts/logging";import{RenderingEngine as n,uimodel as r,uielement as i,uilistprop as a,uilistmodel as s,hidden as d}from"@decaf-ts/ui-decorators";import{Metadata as l,Decoration as c,apply as u,metadata as p,propMetadata as h,description as f,prop as g,DefaultFlavour as m}from"@decaf-ts/decoration";import{ValidationKeys as y,Model as w,required as b,type as v,date as I,model as E,option as N,min as O,max as A}from"@decaf-ts/decorator-validation";import{ValidationError as x,InternalError as k,NotFoundError as _}from"@decaf-ts/db-decorators";import{__decorate as D,__metadata as $}from"tslib";import{pk as P,column as S,index as R,table as C,BaseModel as T,ForbiddenError as L,Context as j,AuthorizationError as M,service as G,Service as U,repository as F,Repository as B,ClientBasedService as q,Adapter as W,ModelService as V,OrderDirection as H}from"@decaf-ts/core";import K from"isolated-vm";import*as z from"acorn";import*as J from"acorn-walk";import*as X from"typescript";import{createHash as Y}from"node:crypto";var Q,Z;y.REQUIRED,y.MIN,y.MIN_LENGTH,y.MAX,y.MAX_LENGTH,y.PATTERN,y.URL,y.STEP,y.DATE,y.EMAIL,y.PASSWORD,y.EQUALS,y.DIFF,y.LESS_THAN,y.LESS_THAN_OR_EQUAL,y.GREATER_THAN,y.GREATER_THAN_OR_EQUAL,(e=>{e.GRAPH="graph",e.NODE="graph.node",e.EDGE="graph.edge",e.PORT="graph.port",e.STATE="graph.state"})(Q||(Q={})),(e=>{e.INPUT="input",e.OUTPUT="output",e.CONNECTION="connection"})(Z||(Z={}));const ee={};function te(e,t={}){let o=e.width??96,n=e.height??96;for(const r of e.sizeRules??[]){if("parameterCount"!==r.type)continue;const e=t[r.parameter]??0;e>0&&("width"===r.dimension?o+=e*r.perItem:n+=e*r.perItem)}return{width:o,height:n}}function oe(e,t){ee[e]=t}function ne(e,t,o){const n=t?ee[t]:void 0;return n?.color?n.color:e||"#64748b"}function re(e,t,o){const n=t?ee[t]:void 0;return n?.icon?n.icon:e||"ti-pointer"}const ie=["skip","passThroughFirstInput","emitDefaults"];function ae(e){return ie.includes(e)}var se,de,le,ce;(e=>{e.PENDING="pending",e.PLANNING="planning",e.RUNNING="running",e.SUCCEEDED="succeeded",e.FAILED="failed",e.SKIPPED="skipped",e.CANCELLED="cancelled",e.CACHED="cached"})(se||(se={})),(e=>{e.IDLE="idle",e.RUNNING="running",e.BLOCKED="blocked",e.SUCCEEDED="succeeded",e.FAILED="failed",e.SKIPPED="skipped"})(de||(de={})),(e=>{e.NODE_ID="nodeId",e.WORKFLOW_ID="workflowId",e.RUN_ID="runId",e.USER="user",e.ROLES="roles",e.NAMESPACES="namespaces",e.ORGANIZATION="organization",e.IP="ip"})(le||(le={})),(e=>{e.WORKFLOW_STARTED="workflow.started",e.WORKFLOW_PLANNED="workflow.planned",e.WORKFLOW_COMPLETED="workflow.completed",e.WORKFLOW_FAILED="workflow.failed",e.WORKFLOW_CANCELLED="workflow.cancelled",e.NODE_QUEUED="node.queued",e.NODE_STARTED="node.started",e.NODE_OUTPUT="node.output",e.NODE_COMPLETED="node.completed",e.NODE_FAILED="node.failed",e.NODE_SKIPPED="node.skipped",e.NODE_CACHE_HIT="node.cacheHit",e.NODE_PINNED="node.pinned",e.NODE_UNPINNED="node.unpinned",e.NODE_STATE_CHANGED="node.stateChanged",e.EDGE_VALUE_ROUTED="edge.valueRouted",e.EDGE_STATE_CHANGED="edge.stateChanged",e.GRAPH_RUN_LOG="graph.run.log",e.LOOP_STARTED="loop.started",e.LOOP_ITERATION_STARTED="loop.iteration.started",e.LOOP_ITERATION_COMPLETED="loop.iteration.completed",e.LOOP_CONDITION_EVALUATED="loop.condition.evaluated",e.LOOP_COMPLETED="loop.completed",e.LOOP_LIMIT_REACHED="loop.limitReached",e.VALIDATION_STARTED="validation.started",e.VALIDATION_FAILED="validation.failed",e.VALIDATION_COMPLETED="validation.completed",e.STORE_READ="store.read",e.STORE_WRITE="store.write",e.STORE_DELETE="store.delete"})(ce||(ce={}));const ue={maxRequestBytes:4e6,maxConcurrentRuns:32,maxEventsPerRun:1e4,maxEventPayloadBytes:256e3,executionTimeoutMs:6e5,eventReplayWindowMs:3e5},pe=[ce.WORKFLOW_COMPLETED,ce.WORKFLOW_FAILED,ce.WORKFLOW_CANCELLED];function he(e){return pe.includes(e)}function fe(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function ge(e){const t=l.constr(e);if("function"==typeof t)return t;const o=e.constructor;return"function"==typeof o?o:e}function me(e){if(null!=e)return"string"==typeof e?e:e+""}function ye(e,t,o){return me(e?.props?.label??e?.props?.name)??me(t?.name)??o??""}function we(e,t,o){const n=Ie(e,t);if(n?.model&&"function"==typeof n.model&&w.isModel(n.model))return n.model;const r=l.type(e,t);if("function"==typeof r&&w.isModel(r))return r;const i=l.getPropDesignTypes?.(e,t)?.designTypes||[];for(const e of i)if("function"==typeof e&&w.isModel(e))return e;const a=o?.[y.TYPE]?.customTypes||[];for(const e of a)if("function"==typeof e&&w.isModel(e))return e}function be(e,t){const o=[t,e.path??e.property].filter(Boolean).join(".");return{...e,path:o,children:e.children?.map(e=>be(e,o))}}function ve(e){const t=ge(e);return l.get(t,Q.NODE)}function Ie(e,t){const o=ge(e);return l.get(o,l.key(Q.PORT,t+""))}function Ee(e,t,o,n=new Set){const r=Ie(e,t);if(!r?.schema)return;const i=we(e,t,l.validationFor(e,t));if(!i)return;if(n.has(i))return[];const a=new Set(n);return a.add(e),a.add(i),Ae(i,a).filter(e=>e.direction===o)}function Ne(e,t,o=new Set){const n=Ie(e,t);if(!n)return;const r=l.validationFor(e,t),i=we(e,t,r);if(n.schema&&i)return;const a=w.uiElementOf(e,t)||void 0,s=w.uiDecorationOf(e,t,"uiprop"),d=l.type(e,t),c=me(n.type??r?.[y.TYPE]?.customTypes?.[0]?.name??a?.props?.type??s?.type??d?.name),u=(n.expand||i&&!o.has(i))&&i?(()=>{const n=new Set(o);return n.add(e),n.add(i),Ae(i,n).map(e=>be(e,t))})():void 0;return{property:t,path:t,direction:n.direction,name:t,label:ye(a,s,t),type:c?.toLowerCase(),required:!!r?.[y.REQUIRED],hidden:!!w.uiIsHidden(e,t),designType:d?.name,element:a,prop:s,validation:r,graph:n,connectionRules:n.connectionRules,composite:!!u?.length,children:u,model:i?.name}}function Oe(e){return Ae(ge(e))}function Ae(e,t=new Set){const o=l.properties(e)||[],n=[];for(const r of o){const o=r+"",i=Ie(e,o);if(i?.schema){const r=Ee(e,o,i.direction,t);if(r){n.push(...r);continue}}const a=Ne(e,o,t);a&&n.push(a)}return n}function xe(e){return e.flatMap(e=>e.children&&e.children.length?xe(e.children):[e])}function ke(e){const t=ge(e),o=w.uiModelOf(t),n=ve(t)||{},r=o?.tag||t.name,i=Oe(t),a=((e,t)=>{const o=t.portGroups||[],n=new Map(o.map(e=>[e.property,e])),r=[],i=l.properties(e)||[];for(const t of i){const o=t+"",i=Ie(e,o);if(!i?.schema)continue;if(!we(e,o,l.validationFor(e,o)))continue;const a=n.get(o);r.push(a?{...a,toggle:a.toggle??"all"}:{property:o,toggle:"all"})}for(const e of o)r.some(t=>t.property===e.property)||r.push(e);return r.length?r:void 0})(t,n),s=n.namespaces?.length?n.namespaces:(e=>{if(null==e)return[];let t,o=e;try{o=l.constr(e)}catch{o=e}try{t=l.get(o,"auth-namespace")}catch{t=void 0}return fe(t)??[]})(t),d=s.length?s:void 0;return{name:t.name,tag:r,kind:n.kind||r,category:n.category,color:n.color,effectiveColor:ne(n.color,n.category),group:n.group,height:n.height,icon:n.icon,effectiveIcon:re(n.icon,n.category),labels:n.labels||[],maxChildren:n.maxChildren,minWidth:n.minWidth,width:n.width,shape:n.shape,cornerRadius:n.cornerRadius,sizeRules:n.sizeRules,props:o?.props,ui:o,graph:n,ports:i,portGroups:a,namespaces:d}}const _e=new Set,De=new Set;function $e(e,t,o){return c.for(Q.NODE).define({decorator:(e,t,o)=>{const n={kind:t?.kind||e,...t};return t=>{const i=u(r(e,o),p(Q.NODE,n))(t);var a;return a=t,_e.add(a),i}},args:[e,t,o]}).apply()}function Pe(e,t){return c.for(Q.PORT).define({decorator:(e,t)=>(o,n)=>{const r={direction:e,...t};return u(h(l.key(Q.PORT,n),r))(o,n)},args:[e,t]}).apply()}function Se(e){return Pe(Z.INPUT,{...e,schema:!0})}function Re(e){return Pe(Z.OUTPUT,{...e,schema:!0})}function Ce(e){return Pe(Z.CONNECTION,e)}n.prototype.renderAsNode=(e,t,...o)=>ke(e),l.nodes=(()=>[..._e]).bind(l),l.workflows=(()=>[...De]).bind(l);const Te=["__proto__","prototype","constructor"];function Le(e){return Te.includes(e)}function je(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function Me(e){return null===e||"string"==typeof e||"number"==typeof e&&Number.isFinite(e)||"boolean"==typeof e}function Ge(e){return!!Me(e)||(Array.isArray(e)?e.every(e=>Ge(e)):!!je(e)&&Reflect.ownKeys(e).every(t=>"string"==typeof t&&!Le(t)&&Ge(e[t])))}function Ue(e){if(void 0===e)return!1;if("number"==typeof e)return Number.isFinite(e);if("function"==typeof e)return!1;if(Ge(e))return!0;if(Array.isArray(e))return e.every(e=>Ue(e));if(je(e)){const t=Reflect.ownKeys(e);for(const o of t){if("string"!=typeof o)return!1;if(Le(o))return!1;if(!Ue(e[o]))return!1}return!0}return!1}function Fe(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>Fe(e));const t={};for(const[o,n]of Object.entries(e))t[o]=Fe(n);return t}const Be={string:"string",char:"string",text:"string",textarea:"string",radio:"string",select:"string",number:"number",integer:"number",float:"number",double:"number",decimal:"number",boolean:"boolean",bool:"boolean",checkbox:"boolean",array:"array",list:"array",set:"array",object:"object",model:"model",any:"any",unknown:"any",enum:"enum"},qe={date:"date",datetime:"date-time","date-time":"date-time",duration:"duration"};function We(e){return e?Be[e.toLowerCase()]??"any":"any"}function Ve(e,t){const o=e[t];if(o&&"object"==typeof o)return o.value}function He(e,t){const o=Ve(e,t);return"number"==typeof o&&Number.isFinite(o)?o:void 0}function Ke(e,t,o){const n=e??{},r=(e=>{const t=Ve(e,y.ENUM);if(Array.isArray(t)&&t.every(Me))return t})(n);if(r)return{type:"enum",values:r};const i=(e=>{const t=e[y.TYPE],o=t?.customTypes?.[0],n="function"==typeof o?o.name:o?.name;if(n)return n})(n)??o;return i?{type:"model",name:i}:((e,t)=>{switch(We(e)){case"string":{const t=(e=>{if(e)return qe[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=He(t,y.MIN),r=He(t,y.MAX);return void 0!==n&&(o.min=n),void 0!==r&&(o.max=r),o}case"boolean":return{type:"boolean"};case"array":return((e,t)=>{const o={type:"array",items:ze(e,t)},n=He(e,y.MIN),r=He(e,y.MAX);return void 0!==n&&(o.minItems=n),void 0!==r&&(o.maxItems=r),o})(t,e);case"object":return{type:"object",properties:{}};case"enum":return{type:"enum",values:[]};case"model":return{type:"model",name:e??"any"};default:return{type:"any"}}})(t,n)}function ze(e,t){if((e=>{const t=e[y.LIST];return!!t?.clazz?.length})(e))return{type:"model",name:Je(e)};const o=Ve(e,y.TYPE);if("string"==typeof o){const e=We(o);return"model"===e?{type:"model",name:o}:{type:e}}if(t&&"array"!==t){const e=We(t);return"model"===e?{type:"model",name:t}:{type:e}}return{type:"any"}}function Je(e){const t=e[y.LIST],o=t?.clazz?.[0];if("function"!=typeof o)return"any";if(o.name)return o.name;try{const e=o();if("function"==typeof e&&e.name)return e.name}catch{return"any"}return"any"}function Xe(e){return"workflow"===e.scope}function Ye(e){return"node"===e.scope}function Qe(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"workflow"===t.scope?"string"==typeof t.port&&2===Reflect.ownKeys(t).length:"node"===t.scope&&"string"==typeof t.nodeId&&"string"==typeof t.port&&3===Reflect.ownKeys(t).length}function Ze(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e.mode;if("edge"===t)return 1===Reflect.ownKeys(e).length;if("literal"===t){const t=e.value;return 2===Object.keys(e).length&&Ge(t)}return"expression"===t&&2===Object.keys(e).length&&"string"==typeof e.expression}const et=["any","string","number","boolean","array","object","enum","model"];function tt(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&(e=>et.includes(e))(e.type)}function ot(e,t={seen:[]}){if(t.seen.includes(e))throw new x(`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 x("Document 'id' is required and must be a non-empty string");if("string"!=typeof e.name||!e.name)throw new x("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 x("Workflow port 'id' is required and must be a non-empty string");if(o.has(t.id))throw new x(`Workflow port '${t.id}' is declared more than once; workflow port ids must be unique`);if(void 0!==t.schema&&!tt(t.schema))throw new x(`Workflow port '${t.id}' schema must be a valid GraphValueSchema`);o.add(t.id)}const n={seen:[...t.seen,e]},r=new Set;for(const t of e.nodes)nt(t,r);for(const t of e.nodes)t.loop&&rt(t,t.loop,n),t.errorBoundary&&it(t,t.errorBoundary,n);const i=new Set;for(const t of e.edges)st(t,i);for(const t of e.edges)dt(t.source,0,o,r,`Edge '${t.id}' source`),dt(t.target,0,o,r,`Edge '${t.id}' target`);if(void 0!==e.settings&&!Ue(e.settings))throw new x("Document settings must be JSON-safe (a map of JSON-safe values)");if(void 0!==e.metadata&&!Ue(e.metadata))throw new x("Document metadata must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed");if(void 0!==e.ui&&!Ue(e.ui))throw new x("Document ui must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed")}function nt(e,t){if("string"!=typeof e.id||!e.id)throw new x("Node 'id' is required and must be a non-empty string");if(t.has(e.id))throw new x(`Node id '${e.id}' is declared more than once; node ids must be unique`);if("string"!=typeof e.kind||!e.kind)throw new x(`Node '${e.id}' must declare a non-empty string 'kind'`);if(void 0===e.parameters||null===e.parameters)throw new x(`Node '${e.id}' parameters must be present (an empty object when there are none)`);if(t.add(e.id),e.inputBindings)for(const[t,o]of Object.entries(e.inputBindings)){if(Le(t))throw new x(`Node '${e.id}' input binding key '${t}' is not allowed (unsafe prototype-pollutant key)`);if(!Ze(o))throw new x(`Node '${e.id}' input binding for '${t}' must be a valid GraphInputBinding (edge, literal, or expression)`);if("literal"===o.mode&&!Ue(o.value))throw new x(`Node '${e.id}' literal binding for '${t}' must contain JSON-safe values`);if("expression"===o.mode&&!o.expression)throw new x(`Node '${e.id}' expression binding for '${t}' must contain a non-empty expression`)}if(e.outputBindings)for(const[t,o]of Object.entries(e.outputBindings)){if(Le(t))throw new x(`Node '${e.id}' output binding key '${t}' is not allowed (unsafe prototype-pollutant key)`);if(!o||"object"!=typeof o||Array.isArray(o))throw new x(`Node '${e.id}' output binding for '${t}' must be an object with enabled and alias settings`)}if(!Ue(e.parameters))throw new x(`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 x(`Node '${e.id}' state must be an object when present`);if(!Ue(e.state))throw new x(`Node '${e.id}' state must be JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`)}}function rt(e,t,o){if(!t.body||"object"!=typeof t.body)throw new x(`Node '${e.id}' loop configuration requires a body document`);if(ot(t.body,o),!(void 0===t.maxIterations||Number.isFinite(t.maxIterations)&&t.maxIterations>0))throw new x(`Node '${e.id}' loop maxIterations must be a positive number`);if(void 0!==t.timeoutMs&&("number"!=typeof t.timeoutMs||0>=t.timeoutMs))throw new x(`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 x(`Node '${e.id}' loop concurrency must be a positive number`);for(const o of[t.inputMappings,t.outputMappings])if(o)for(const[t,n]of Object.entries(o)){if(Le(t))throw new x(`Node '${e.id}' loop mapping key '${t}' is not allowed (unsafe prototype-pollutant key)`);at(n,e.id,t)}}function it(e,t,o){if(!t.try||"object"!=typeof t.try)throw new x(`Node '${e.id}' error-boundary configuration requires a try body document`);ot(t.try,o);for(const[n,r]of[["catch",t.catch],["finally",t.finally]])if(void 0!==r){if(!r||"object"!=typeof r)throw new x(`Node '${e.id}' error-boundary ${n} body must be a document`);ot(r,o)}}function at(e,t,o){if(!e||"object"!=typeof e)throw new x(`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 x(`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 x(`Node '${t}' loop mapping '${o}' referencing a node must reference a node id and a port`);break;case"literal":if(!Ue(e.value))throw new x(`Node '${t}' loop mapping '${o}' literal references must be JSON-safe values`);break;case"expression":if("string"!=typeof e.expression||!e.expression)throw new x(`Node '${t}' loop mapping '${o}' expression references must be non-empty expressions`);break;default:throw new x(`Node '${t}' loop mapping '${o}' must use a workflow, node, literal, or expression reference source`)}}function st(e,t){if("string"!=typeof e.id||!e.id)throw new x("Edge 'id' is required and must be a non-empty string");if(t.has(e.id))throw new x(`Edge id '${e.id}' is declared more than once; edge ids must be unique`);if(!Qe(e.source))throw new x(`Edge '${e.id}' source endpoint is not a valid GraphEndpoint`);if(!Qe(e.target))throw new x(`Edge '${e.id}' target endpoint is not a valid GraphEndpoint`);if("data"!==e.type&&"connection"!==e.type)throw new x(`Edge '${e.id}' type '${e.type+""}' is not a valid edge type (data or connection are allowed)`);if(t.add(e.id),!Ue(e))throw new x(`Edge '${e.id}' contains values that are not JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys, or unsafe prototype keys are not allowed`)}function dt(e,t,o,n,r){if(Xe(e)){if(!o.has(e.port))throw new x(`${r} references workflow port '${e.port}' which is not declared on the document`)}else if(Ye(e)){if(!n.has(e.nodeId))throw new x(`${r} references node '${e.nodeId}' which is not part of the document`);if("string"!=typeof e.port||!e.port)throw new x(r+" node endpoints must reference a non-empty port identifier")}}const lt=["expression","template"],ct=["javascript","typescript","json","text"];function ut(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return!(!(e=>lt.includes(e))(t.mode)||"string"!=typeof t.expression||!t.expression||void 0!==t.language&&!(e=>ct.includes(e))(t.language)||void 0!==t.metadata&&!Ge(t.metadata))}function pt(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.name&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.nodes)&&Array.isArray(t.edges)}function ht(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.type&&(void 0===t.required||"boolean"==typeof t.required)&&(void 0===t.displayName||"string"==typeof t.displayName)&&(void 0===t.allowedOperations||Array.isArray(t.allowedOperations)&&t.allowedOperations.every(e=>"string"==typeof e))}const ft=["trigger","loop","branching","stateful","retryable","cancellable","parallel","resource"];function gt(e){return ft.includes(e)}function mt(e){if(!(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.kind&&"object"==typeof t.display&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.parameters)})(e))throw new x("Graph node manifest does not conform to the required shape");if(!Ue(e))throw new x("Graph node manifest contains values that are not JSON-safe: functions, class instances, undefined, NaN/Infinity, symbol keys or unsafe prototype keys are not allowed on manifests")}const yt=["loadOptions","listSearch","resourceLocator","resourceMapping","validateParameter","action"];function wt(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.name&&(e=>yt.includes(e))(t.type)&&(void 0===t.parameter||"string"==typeof t.parameter)&&(void 0===t.dependencies||Array.isArray(t.dependencies)&&t.dependencies.every(e=>"string"==typeof e))}function bt(e){const t=e.element?.props?.value,o=t??e.prop?.value??e.validation?.defaultValue;if(void 0!==o&&"function"!=typeof o&&Ue(o))try{return JSON.parse(JSON.stringify(o))}catch{return}}function vt(e){if(e.type&&e.type in qe)return{type:"string",format:qe[e.type]};const t=(e=>{for(const t of[e.graph?.type,e.element?.props?.type,e.prop?.type])if("string"==typeof t&&"any"!==We(t))return t})(e);return t?Ke((e=>{if(!e)return;const t=Object.entries(e).filter(([e])=>e!==y.TYPE);return Object.fromEntries(t)})(e.validation),t):Ke(e.validation,e.type,e.model)}function It(e){const t={};for(const[o,n]of Object.entries(e.graph?.metadata??{}))Ue(n)&&(t[o]=JSON.parse(JSON.stringify(n)));return Object.keys(t).length?t:void 0}function Et(e){switch(e){case"output":return"output";case"connection":return"connection";default:return"input"}}function Nt(e){const t=e.graph?.handle;return"connection"!==e.direction&&"string"==typeof t&&t?t:e.path??e.property}function Ot(e,t){const o={id:Nt(e),label:e.label,direction:Et(e.direction),schema:vt(e)};e.required&&(o.required=!0),e.hidden&&(o.hidden=!0);const n=e.graph?.category;"string"==typeof n&&(o.category=n),!0===e.graph?.userControlled&&(o.configurable=!0);const r=e.graph?.handle;"string"==typeof r&&(o.handle=r);const i=Ct(e.graph?.connectionRules)??t;i&&(o.connectionPolicy=i);const a=(e=>{const t=e.element;if(!t||!Ue(t))return;const o=t.tag;if("string"!=typeof o)return;const n=t.props;return{tag:o,serialize:!0===t.serialize,props:n&&"object"==typeof n&&!Array.isArray(n)?Fe(n):{}}})(e);a&&(o.element=a);const s=It(e);return s&&(o.metadata=s),o}function At(e){const t={type:"string",id:Nt(e),label:e.label,required:e.required};if(e.hidden)return((e,t)=>{const o={...t,type:"hidden"},n=bt(e);return void 0!==n&&(o.defaultValue=n),xt(o)})(e,t);const o=bt(e);void 0!==o&&(t.defaultValue=o);const n=(e=>{const t=e.element?.props?.placeholder??e.prop?.placeholder;return"string"==typeof t?t:void 0})(e);n&&(t.placeholder=n);const r=It(e);if(r&&(t.metadata=r),(e=>{const t=Dt(e);return"code"===t||"code-editor"===t})(e))return xt({...t,type:"code",language:St(e)});const i=vt(e);switch(i.type){case"number":{const o={...t,type:"number",integer:i.integer,min:i.min,max:i.max},n=_t(e.validation?.step);return void 0!==n&&(o.step=n),xt(o)}case"boolean":return xt({...t,type:"boolean"});case"enum":return xt({...t,type:"options",options:i.values.map(e=>({value:e,label:e+""}))});case"array":{const e={...t,type:"collection"};return void 0!==i.maxItems&&(e.maxItems=i.maxItems),xt(e)}case"object":case"model":return xt({...t,type:"object"});default:return xt({...t,type:"string",multiline:!!$t(e)||void 0,pattern:kt(e.validation?.pattern),minLength:_t(e.validation?.minlength),maxLength:_t(e.validation?.maxlength)})}}function xt(e){const t=e;for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return e}function kt(e){const t=e?.value;return"string"==typeof t?t:void 0}function _t(e){const t=e?.value;return"number"==typeof t&&Number.isFinite(t)?t:void 0}function Dt(e){const t=e.element?.tag;return"string"==typeof t&&t?t:void 0}function $t(e){return"textarea"===Dt(e)||"textarea"===(e=>{const t=e.element?.props?.type;return"string"==typeof t?t:void 0})(e)}const Pt=["javascript","typescript","json","text"];function St(e){const t=e.element?.props?.language;return"string"==typeof t&&Pt.includes(t)?t:"javascript"}function Rt(e,t){const o={name:t.name??e.name},n=e.graph?.metadata?.description??void 0;"string"==typeof n&&n&&(o.description=n);const r=t.category??e.category;"string"==typeof r&&r&&(o.category=r),"string"==typeof e.group&&e.group&&(o.group=e.group),Array.isArray(e.labels)&&(o.labels=e.labels.slice());const i=((e,t)=>{if(t.icon)return t.icon;const o=e.effectiveIcon??e.icon;return"string"==typeof o?{type:"catalogue",name:o}:{type:"catalogue",name:"ph:circuitry"}})(e,t);return i&&(o.icon=i),"string"==typeof e.color&&e.color&&(o.color=e.color),"number"==typeof e.width&&Number.isFinite(e.width)&&(o.width=e.width),"number"==typeof e.minWidth&&Number.isFinite(e.minWidth)&&(o.minWidth=e.minWidth),"number"==typeof e.height&&Number.isFinite(e.height)&&(o.height=e.height),"string"==typeof e.shape&&(o.shape=e.shape),"number"==typeof e.cornerRadius&&Number.isFinite(e.cornerRadius)&&(o.cornerRadius=e.cornerRadius),Array.isArray(e.sizeRules)&&(o.sizeRules=e.sizeRules),o}function Ct(e){if(!e)return;const t=e,o={};"boolean"==typeof t.allowSelf&&(o.allowSelf=t.allowSelf),"boolean"==typeof t.allowMultiple&&(o.allowMultiple=t.allowMultiple);const n=t.allowedKinds;Array.isArray(n)&&n.every(e=>"string"==typeof e)&&(o.allowedNodeKinds=n);const r=t.blockedKinds;Array.isArray(r)&&r.every(e=>"string"==typeof e)&&(o.blockedNodeKinds=r);const i=t.maxConnections;return"number"==typeof i&&Number.isFinite(i)&&(o.maxConnections=i),Object.keys(o).length?o:void 0}function Tt(e,t={}){const o="function"==typeof e?e:e.constructor;if(!ve(o))throw new x(`Node '${o?.name??e+""}' is not decorated with @node and cannot produce a manifest`);const n=ke(o),r=xe(Oe(o)),i=[],a=[],s=[],d=[],l=Ct(n.graph?.connectionRules);for(const e of r)("connection"===e.direction?s:"output"===e.direction?a:i).push(Ot(e,l)),"input"===e.direction&&d.push(At(e));const c={kind:t.kind??n.kind??n.name,display:Rt(n,t),inputs:i,outputs:a,parameters:d};return s.length&&(c.connections=s),n.namespaces?.length&&(c.namespaces=n.namespaces.slice()),mt(c),c}let Lt=class extends T{constructor(e){super(e)}};D([P({type:String,generated:!1}),f("Unique graph run id"),i("ngx-decaf-crud-field",{label:"graph.run.id.label",readonly:!0}),$("design:type",String)],Lt.prototype,"runId",void 0),D([S(),b(),R(),f("Workflow document id the run executes"),a("workflowId"),i("ngx-decaf-crud-field",{label:"graph.run.workflowId.label"}),$("design:type",String)],Lt.prototype,"workflowId",void 0),D([S(),f("Owning user; absent for anonymous callers"),i("ngx-decaf-crud-field",{label:"graph.run.owner.label"}),$("design:type",String)],Lt.prototype,"owner",void 0),D([S(),b(),v(String),R(),f("Current run lifecycle status"),a("status"),i("ngx-decaf-crud-field",{label:"graph.run.status.label",readonly:!0}),$("design:type",String)],Lt.prototype,"status",void 0),D([S(),f("Fingerprint of the executed document"),i("ngx-decaf-crud-field",{label:"graph.run.fingerprint.label",readonly:!0}),$("design:type",String)],Lt.prototype,"documentFingerprint",void 0),D([S(),g(),f("Workflow input values keyed by input port id"),$("design:type",Object)],Lt.prototype,"inputs",void 0),D([S(),g(),f("Execution result, present on successful completion"),$("design:type",Object)],Lt.prototype,"result",void 0),D([S(),g(),f("Structured error payload, present on failure"),$("design:type",Object)],Lt.prototype,"error",void 0),D([I(),S(),f("Run creation timestamp"),$("design:type",Date)],Lt.prototype,"createdAt",void 0),D([I(),S(),f("Execution start timestamp, once it has started"),$("design:type",Date)],Lt.prototype,"startedAt",void 0),D([I(),S(),f("Terminal-state timestamp, once the run has finished"),$("design:type",Date)],Lt.prototype,"finishedAt",void 0),Lt=D([s("ngx-decaf-list-item",{icon:"ti-player-play"}),r("ngx-decaf-crud-form"),f("Persistable graph run lifecycle record"),C("graph_run"),E(),$("design:paramtypes",[Object])],Lt);let jt=class extends T{constructor(e){super(e)}};D([P({type:String,generated:!1}),$("design:type",String)],jt.prototype,"workflowId",void 0),D([S(),$("design:type",String)],jt.prototype,"name",void 0),D([S(),$("design:type",Object)],jt.prototype,"document",void 0),D([S(),$("design:type",String)],jt.prototype,"owner",void 0),D([S(),$("design:type",Object)],jt.prototype,"snapshot",void 0),jt=D([C("graph_workflow"),E(),$("design:paramtypes",[Object])],jt),oe("Trigger",{color:"#3b82f6",icon:"ti-bolt"}),oe("Flow Control",{color:"#f59e0b",icon:"ti-arrows-split-2"}),oe("Utility",{color:"#0d9488",icon:"ti-tool"}),oe("Loop",{color:"#eab308",icon:"ti-repeat"}),oe("Workflow",{color:"#f97316",icon:"ti-sitemap"}),oe("Pipeline",{color:"#0ea5e9",icon:"ti-git-merge"}),oe("Node",{color:"#8b5cf6",icon:"ti-point-filled"}),oe("Agent",{color:"#7c3aed",icon:"ti-robot"}),oe("model",{color:"#3b82f6",icon:"ti-cpu"}),oe("memory",{color:"#10b981",icon:"ti-database"}),oe("workspace",{color:"#f59e0b",icon:"ti-folder"});const Mt=new Set;function Gt(e,t){return e.config[t]}function Ut(e){return Array.isArray(e)?e.map(e=>e+"").join(", "):e+""}(()=>{const t=[{key:le.NODE_ID,shouldInclude:e=>null!=Gt(e,le.NODE_ID),render:e=>Gt(e,le.NODE_ID)+""},{key:le.WORKFLOW_ID,shouldInclude:e=>null!=Gt(e,le.WORKFLOW_ID),render:e=>Gt(e,le.WORKFLOW_ID)+""},{key:le.RUN_ID,shouldInclude:e=>null!=Gt(e,le.RUN_ID),render:e=>Gt(e,le.RUN_ID)+""},{key:le.USER,shouldInclude:e=>null!=Gt(e,le.USER),render:e=>Gt(e,le.USER)+""},{key:le.ROLES,shouldInclude(e){const t=Gt(e,le.ROLES);return Array.isArray(t)&&t.length>0},render:e=>Ut(Gt(e,le.ROLES))},{key:le.NAMESPACES,shouldInclude(e){const t=Gt(e,le.NAMESPACES);return Array.isArray(t)&&t.length>0},render:e=>Ut(Gt(e,le.NAMESPACES))},{key:le.ORGANIZATION,shouldInclude:e=>null!=Gt(e,le.ORGANIZATION),render:e=>Gt(e,le.ORGANIZATION)+""},{key:le.IP,shouldInclude:e=>null!=Gt(e,le.IP),render:e=>Gt(e,le.IP)+""}];for(const o of t)Mt.has(o.key)||(e.register(o),Mt.add(o.key))})();const Ft="$workflow",Bt=4,qt=100,Wt=1e3,Vt=1e3,Ht=1e4,Kt=3e4,zt="graph.pinnable";var Jt,Xt;(e=>{e.MANUAL="manual",e.AUTOMATIC="automatic",e.DISABLED="disabled"})(Jt||(Jt={})),(e=>{e.TRUTHY="truthy",e.FALSY="falsy",e.EQUALS="equals",e.NOT_EQUALS="notEquals",e.GREATER_THAN="greaterThan",e.GREATER_THAN_OR_EQUAL="greaterThanOrEqual",e.LESS_THAN="lessThan",e.LESS_THAN_OR_EQUAL="lessThanOrEqual",e.EXISTS="exists",e.CUSTOM="custom"})(Xt||(Xt={}));const Yt={FOREACH:"core.loop.foreach",WHILE:"core.loop.while",UNTIL:"core.loop.until"};class Qt extends k{constructor(e,t="GRAPH_EXECUTION_ERROR",o){super(e,Qt.name,500),this.graphCode=t,this.details=o,this.name=this.constructor.name}}class Zt extends Qt{constructor(e){super("Graph workflow contains an unsupported cycle","GRAPH_CYCLE_ERROR",e)}}class eo extends Qt{constructor(e,t){super(e,"GRAPH_INPUT_ERROR",t)}}class to extends Qt{constructor(e,t){super(e,"GRAPH_LOOP_LIMIT_ERROR",t)}}class oo extends Qt{constructor(e,t){super(e,"GRAPH_PINNING_ERROR",t)}}class no extends Qt{constructor(e,t){super(e,"GRAPH_PORT_ERROR",t)}}class ro extends Qt{constructor(e,t){super(e,"GRAPH_STORE_ERROR",t)}}class io extends Qt{constructor(e,t){super(e,"GRAPH_TOPOLOGY_ERROR",t)}}class ao extends Qt{constructor(e){super("Break signal","GRAPH_BREAK_SIGNAL",{value:e}),this.isBreakSignal=!0,this.name="GraphBreakSignal"}}class so extends Qt{constructor(e){super(`Graph run '${e}' was cancelled`,"GRAPH_RUN_CANCELLED",{runId:e}),this.name=so.name}}class lo extends x{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=lo.name,this.issues=e}}class co{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 uo{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 Qt("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 po(e){if("string"!=typeof e)return;const t=e.trim();if(!t)return;const o=t.split(".");if(3!==o.length)return;const n=o[0].trim(),r=o[2].trim(),i=o[1].split(",").map(e=>e.trim()).filter(e=>e.length>0);return n&&r&&0!==i.length?{organization:n,departments:i,role:r}:void 0}function ho(e){return`${e.organization}.${e.departments.join(",")}.${e.role}`}function fo(e){if(!e||"string"!=typeof e.namespace||!e.parts)return!1;const t=po(e.namespace);return!!t&&ho(t)===ho(e.parts)}function go(e,t){const o="string"==typeof e?e.trim():"";if(o){if(t)for(const e of t)if(e&&e.namespace===o&&fo(e))return e.parts;return po(o)}}function mo(e,t,o={},n){const r=go(e,n),i=go(t,n);return!(!r||!i)&&r.organization===i.organization&&r.role===i.role&&("exact"===(o.mode??"inherit")?r.departments.length===i.departments.length&&r.departments.every((e,t)=>e===i.departments[t]):r.departments.length<=i.departments.length&&r.departments.every((e,t)=>e===i.departments[t]))}function yo(e,t,o={},n){return e.filter(e=>!t.some(t=>mo(t,e,o,n)))}function wo(e){return e.filter(e=>void 0===po(e))}function bo(e,t){const o=new Set;for(const n of e){const e=go(n,t);e&&o.add(e.role)}return[...o]}function vo(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}function Io(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 Eo(e){if(!e)return{};const t={},o=e.user;"string"==typeof o&&o&&(t.user=o);const n=e.organization;"string"==typeof n&&n&&(t.organization=n);const r=e.ip;"string"==typeof r&&r&&(t.ip=r);const i=vo(e.roles);i&&(t.roles=i);const a=vo(e.namespaces);return a&&(t.namespaces=a,t.namespaceCache=Oo(a)),t}function No(e){return e?Eo({user:Io(e,"user"),organization:Io(e,"organization"),ip:Io(e,"ip"),roles:Io(e,"roles"),namespaces:Io(e,"namespaces")}):{}}function Oo(e){const t=[];for(const o of e){const e=po(o);e&&t.push({namespace:o,parts:e})}return t}function Ao(...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??Oo(o.namespaces):void 0!==o.namespaceCache&&(t.namespaceCache=o.namespaceCache));return t}class xo{constructor(e={}){this.options=e}get enabled(){return!0===this.options.enabled}validate(e,o,n,r){if(!this.enabled)return;const i=r??this.options.logger??t.for("GraphAuth"),a=e.id||e.name||o.workflowId,s=(e=>{if(!e||"object"!=typeof e)return;const t=e.auth;return t&&"object"==typeof t&&!Array.isArray(t)?(e=>{if(!e)return;const t=fe(e.namespaces),o=fe(e.roles);if(!t&&!o)return;const n={};return t&&(n.namespaces=t),o&&(n.roles=o),n})(t):void 0})(e.metadata);this.assertGranted(`workflow '${a}'`,s?.namespaces??[],n,s?.roles??[],i);for(const e of o.nodes)this.assertGranted(`node '${e.id}'`,e.manifest.namespaces??[],n,[],i)}assertGranted(e,t,o,n,r){const i=o.namespaces??[],a=yo(t,i,this.options.match,o.namespaceCache),s=bo(i,o.namespaceCache),d=n.filter(e=>!s.includes(e));if(0===a.length&&0===d.length)return;const l=[...new Set([...wo(t),...wo(i)])],c=[];throw a.length&&c.push("namespace(s) "+a.join(", ")),d.length&&c.push("role(s) "+d.join(", ")),r.warn(`Graph access denied for ${e} for user ${o.user??"anonymous"}: missing ${c.join(" and ")}${l.length?`; malformed namespace(s) ${l.join(", ")} failed closed`:""}`),new L(`Access to ${e} requires ${c.join(" and ")}`)}}class ko{constructor(e){this.baseOptions=e,this.inner=t.for("GraphRun").for(this.attributeConfig(e))}attributeConfig(e){return{[le.NODE_ID]:e.nodeId,[le.WORKFLOW_ID]:e.workflowId,[le.RUN_ID]:e.runId,[le.USER]:e.user??null,[le.ROLES]:e.roles,[le.NAMESPACES]:e.namespaces,[le.ORGANIZATION]:e.organization,[le.IP]:e.ip}}emit(e,t,o){const n="string"==typeof t?t:t instanceof Error?t.message:t+"",r={level:e,message:n,timestamp:(new Date).toISOString(),runId:this.baseOptions.runId,workflowId:this.baseOptions.workflowId,nodeId:this.baseOptions.nodeId,user:this.baseOptions.user??null};void 0!==this.baseOptions.roles&&(r.roles=this.baseOptions.roles),void 0!==this.baseOptions.namespaces&&(r.namespaces=this.baseOptions.namespaces),void 0!==this.baseOptions.organization&&(r.organization=this.baseOptions.organization),void 0!==this.baseOptions.ip&&(r.ip=this.baseOptions.ip),void 0!==o&&(r.payload=o),this.baseOptions.forward({type:ce.GRAPH_RUN_LOG,payload:r}).catch(()=>{}),{benchmark:(e,t)=>this.inner.benchmark(e,t),fatal:(e,t)=>this.inner.fatal(e,t),critical:(e,t)=>this.inner.critical(e,t),silly:(e,t)=>this.inner.silly(e,t),trace:(e,t)=>this.inner.trace(e,t),verbose:(e,t)=>this.inner.verbose(e,t),info:(e,t)=>this.inner.info(e,t),warn:(e,t)=>this.inner.warn(e,t),error:(e,t)=>this.inner.error(e,t),debug:(e,t)=>this.inner.debug(e,t)}[e](n,o)}benchmark(e,t){this.emit("benchmark",e,t)}fatal(e,t,o){this.emit("fatal",e,t??o)}critical(e,t,o){this.emit("critical",e,t??o)}silly(e,t,o){this.emit("silly",e,"object"==typeof t?t:o)}trace(e,t){this.emit("trace",e,t)}verbose(e,t,o){this.emit("verbose",e,"object"==typeof t?t:o)}info(e,t){this.emit("info",e,t)}error(e,t,o){this.emit("error",e,t??o)}warn(e,t){this.emit("warn",e,t)}debug(e,t){this.emit("debug",e,t)}action(e,t,o){this.inner.action(e,t,o)}setConfig(){}for(e,t,...o){return this}clear(){return this}get root(){return this.inner.root}}function _o(e){if(!Array.isArray(e))return;const t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length?t:void 0}class Do extends j{constructor(e,t,o,n,r,i,a,s,d={},l,c,u){super(),this.runId=e,this.parentRunId=t,this.workflowId=o,this.document=n,this.node=r,this.manifest=i,this.path=a,this.emitFn=s,this.metadata=d,this.engine=l,this.abortSignal=c,this.limits=u;const p=Eo(d);this.accumulate({...p,operation:"execute"});const h="string"==typeof d?.user?d.user:null;this.runLogger=new ko({runId:e,workflowId:o,nodeId:r.id,user:h,roles:_o(d?.roles),namespaces:_o(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 No(this)}async emit(e){await this.emitFn({...e,runId:this.runId,parentRunId:this.parentRunId,workflowId:this.workflowId,nodeId:this.node.id,path:e.path??this.path})}async progress(e){await this.emit({type:ce.NODE_OUTPUT,payload:e})}async log(e,t){await this.emit({type:ce.NODE_OUTPUT,payload:{message:e,payload:t}})}}class $o{constructor(e,t,o,n){this.nodeResults=new Map,this.events=[],this.activeDataEdges=new Set,this.runId=e,this.plan=t,this.valueStore=o,this.eventFactory=n,this.startedAt=new Date}recordNodeResult(e){this.nodeResults.set(e.nodeId,e)}activateDataEdge(e){this.activeDataEdges.add(e)}isDataEdgeActive(e){return this.activeDataEdges.has(e)}appendEvent(e){this.events.push(e)}finish(){this.finishedAt=new Date}}function Po(e,t,o,n,r){const i=e.valueStore.getWorkflowValues(),a={};for(const[t,o]of e.nodeResults)a[t]=o;const s=[...e.events];return{runId:e.runId,workflowId:t.id||t.name,status:n,document:t,inputs:{...o},outputs:i,nodeResults:a,events:s,startedAt:e.startedAt,finishedAt:e.finishedAt,metadata:r}}class So{constructor(e){this.catalogue=e}async resolveNodes(e,t,o,...n){const r=new Map;for(const[i,a]of e.entries()){const e=`nodes[${i}]`;if(this.catalogue.has(a.kind,...n))try{const e=await this.catalogue.resolveManifest(a.kind,a,o,...n),t=this.catalogue.getExecutor(a.kind,...n);r.set(a.id,{instance:a,manifest:e,executor:t})}catch(o){t.push({code:"kind.resolution-failed",path:e+".kind",message:`Node '${a.id}' kind '${a.kind}' failed to resolve: ${o.message}`,nodeId:a.id,details:{kind:a.kind}})}else t.push({code:"kind.unknown",path:e+".kind",message:`Node '${a.id}' references kind '${a.kind}' which is not registered in the backend catalogue`,nodeId:a.id,details:{kind:a.kind}})}return r}validateEffectivePorts(e,t,o,n){const r=!0===t.policies?.allowUndeclaredParameters,i=new Set(t.inputs.map(e=>e.id)),a=new Set(t.outputs.map(e=>e.id));for(const a of Object.keys(e.inputBindings??{}))r||i.has(a)||o.push({code:"binding.unknown-port",path:`${n}.inputBindings.${a}`,message:`Node '${e.id}' input binding '${a}' does not refer to an effective input port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveInputs:[...i]}});for(const i of Object.keys(e.outputBindings??{}))r||a.has(i)||o.push({code:"binding.unknown-port",path:`${n}.outputBindings.${i}`,message:`Node '${e.id}' output binding '${i}' does not refer to an effective output port of kind '${t.kind}'`,nodeId:e.id,details:{effectiveOutputs:[...a]}})}}function Ro(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&&Ro(e,t,`${o}.nodes[${r.id}].loop.body`)}}function Co(e,t){if(!t)return{valid:!0};switch(t.type){case"any":default:return{valid:!0};case"string":return"string"!=typeof e?To("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}:To("number");case"boolean":return"boolean"!=typeof e?To("boolean"):{valid:!0};case"array":if(!Array.isArray(e))return To("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=Co(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 To(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=Co(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 To(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 jo=new Set(["loop"]),Mo=["secret","secrets","password","passwd","token","accessToken","refreshToken","apiKey","api_key","privateKey","credentials"];class Go{validate(e,t,o,n,r){this.validateParameters(e,t,o,n,r),this.validateMetadataKeys(e,t,o,n),this.validateDisabledBehavior(e,o,n),this.validateBindingShapes(e,t,o,n)}validateParameters(e,t,o,n,r){const i=!0===t.policies?.allowUndeclaredParameters,a=new Map(t.parameters.map(e=>[e.id,e]));for(const[r,s]of Object.entries(e.parameters??{})){const d=a.get(r);if(!d){i||o.push({code:"parameter.undeclared",path:`${n}.parameters.${r}`,message:`Node '${e.id}' sets parameter '${r}' which is not declared by kind '${t.kind}'`,nodeId:e.id,details:{kind:t.kind}});continue}if(void 0===s){o.push({code:"parameter.invalid",path:`${n}.parameters.${r}`,message:`Node '${e.id}' parameter '${r}' must not be undefined`,nodeId:e.id});continue}const l=this.checkParameterValue(s,d);l.valid||o.push({code:"parameter.type-mismatch",path:`${n}.parameters.${r}`,message:`Node '${e.id}' parameter '${r}' is invalid: ${l.message}`,nodeId:e.id,details:{expectedType:d.type}})}for(const i of t.parameters)void 0===(e.parameters??{})[i.id]&&(this.isParameterSatisfiedByInput(e,i.id,r)||(!0===i.required||(i.validation??[]).some(e=>"required"===e.kind))&&void 0===i.defaultValue&&o.push({code:"parameter.required-missing",path:`${n}.parameters.${i.id}`,message:`Node '${e.id}' is missing required parameter '${i.id}' declared by kind '${t.kind}'`,nodeId:e.id}))}isParameterSatisfiedByInput(e,t,o){return void 0!==(e.inputBindings??{})[t]||!0===o?.has(t)}checkParameterValue(e,t){if(ut(e))return{valid:!0};switch(t.type){case"string":case"code":case"expression":return"string"!=typeof e?To("string"):{valid:!0};case"number":return"number"==typeof e&&Number.isFinite(e)?{valid:!0}:To("number");case"boolean":return"boolean"!=typeof e?To("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}:To("array");case"object":case"resourceLocator":return null===e||"object"!=typeof e||Array.isArray(e)?To("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 i of Object.keys(e.metadata??{}))jo.has(i)?o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${i}`,message:`Node '${e.id}' metadata key '${i}' is reserved and must not be set directly`,nodeId:e.id}):Array.isArray(r)&&!r.includes(i)&&o.push({code:"metadata.key-not-allowed",path:`${n}.metadata.${i}`,message:`Node '${e.id}' metadata key '${i}' is not in the allowed metadata keys of kind '${t.kind}'`,nodeId:e.id})}validateDisabledBehavior(e,t,o){!0!==e.disabled&&!1!==e.disabled&&void 0!==e.disabled&&t.push({code:"disabled.invalid",path:o+".disabled",message:`Node '${e.id}' disabled flag must be a boolean`,nodeId:e.id});const n=(e.metadata??{}).disabledBehavior;void 0===n||ae(n)||t.push({code:"disabled.invalid-behavior",path:o+".metadata.disabledBehavior",message:`Node '${e.id}' disabled behavior '${n+""}' is not one of: ${ie.join(", ")}`,nodeId:e.id})}validateBindingShapes(e,t,o,n){for(const[r,i]of Object.entries(e.inputBindings??{})){if("literal"===i.mode){const a=t.inputs.find(e=>e.id===r);if(a?.schema){const t=Co(i.value,a.schema);t.valid||o.push({code:"binding.literal-invalid",path:`${n}.inputBindings.${r}`,message:`Node '${e.id}' literal binding for '${r}' is schema-invalid: ${t.message}`,nodeId:e.id})}}"expression"!==i.mode||"string"==typeof i.expression&&i.expression.trim()||o.push({code:"binding.expression-invalid",path:`${n}.inputBindings.${r}`,message:`Node '${e.id}' expression binding for '${r}' must contain a non-empty expression`,nodeId:e.id})}}validateBindingSatisfaction(e,t,o,n,r,i={}){const a=new Set(o.filter(e=>"data"===e.type).map(e=>e.targetPort)),s=new Set(Object.entries(e.inputBindings??{}).map(([e])=>e));for(const t of a){const o=(e.inputBindings??{})[t];o&&"literal"===o.mode&&!0!==i.allowLiteralAndEdgeBindings&&n.push({code:"binding.conflict",path:`${r}.inputBindings.${t}`,message:`Node '${e.id}' input '${t}' has both an incoming edge and a literal binding`,nodeId:e.id})}for(const o of t.inputs)!0===o.required&&(a.has(o.id)||s.has(o.id)||void 0===(e.parameters??{})[o.id]&&n.push({code:"topology.required-input-unsatisfiable",path:r+".parameters",message:`Node '${e.id}' required input '${o.id}' has no incoming edge or binding`,nodeId:e.id,details:{port:o.id}}))}static disabledBehaviorOf(e,t){const o=(e.metadata??{}).disabledBehavior;if(ae(o))return o;const n=t?.disabledBehavior;return ae(n)?n:"skip"}}class Uo{resolveEdges(e,t,o){const n=new Set(e.inputs.map(e=>e.id)),r=new Set(e.outputs.map(e=>e.id)),i=[];for(const[a,s]of(e.edges??[]).entries()){const e=`edges[${a}]`,d=this.resolveEndpoint(s,"source",t,n,r,o,e),l=this.resolveEndpoint(s,"target",t,n,r,o,e);if(!d||!l)continue;if(!this.validateDirectionAndType(s,d,l,t,o,e))continue;const c={id:s.id,type:s.type,sourceNodeId:d.nodeId,sourcePort:d.port,targetNodeId:l.nodeId,targetPort:l.port,metadata:s.metadata,edge:s};void 0!==s.label&&(c.label=s.label),i.push(c)}return i}resolveEndpoint(e,t,o,n,r,i,a){const s=e[t];return Xe(s)?("source"===t?n.has(s.port):r.has(s.port))?{nodeId:Ft,port:s.port}:void i.push({code:"edge.unknown-port",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} references workflow port '${s.port}' which is not declared on the document boundary`,edgeId:e.id,details:{scope:"workflow",port:s.port}}):Ye(s)?o.get(s.nodeId)?{nodeId:s.nodeId,port:s.port}:void i.push({code:"edge.unknown-node",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} references node '${s.nodeId}' which is not part of the document or did not resolve`,edgeId:e.id,nodeId:s.nodeId}):void i.push({code:"edge.invalid-endpoint",path:`${a}.${t}`,message:`Edge '${e.id}' ${t} endpoint is not a valid GraphEndpoint`,edgeId:e.id})}validateDirectionAndType(e,t,o,n,r,i){let a=!0;const s=t.nodeId===Ft?void 0:n.get(t.nodeId),d=o.nodeId===Ft?void 0:n.get(o.nodeId),l=e=>!0===e?.manifest.policies?.allowUndeclaredParameters;if("data"===e.type)!s||l(s)||this.hasPortDirection(s,t.port,"output")||(this.pushPortIssue(e,"source",t,s,r,i),a=!1),!d||l(d)||this.hasPortDirection(d,o.port,"input")||(this.pushPortIssue(e,"target",o,d,r,i),a=!1);else{if(!s||!d)return r.push({code:"edge.boundary-routing",path:i,message:`Connection edge '${e.id}' must connect two node connection ports; the workflow boundary only routes data`,edgeId:e.id}),!1;if(!(l(s)||l(d)||this.hasPortDirection(s,t.port,"connection")&&this.hasPortDirection(d,o.port,"connection")))return r.push({code:"edge.type-mismatch",path:i,message:`Connection edge '${e.id}' endpoints must both be connection ports`,edgeId:e.id,details:{sourcePort:t.port,targetPort:o.port}}),!1}return a}hasPortDirection(e,t,o){return("input"===o?e.manifest.inputs:"output"===o?e.manifest.outputs:e.manifest.connections??[]).some(e=>e.id===t)}pushPortIssue(e,t,o,n,r,i){const a="source"===t?"output":"input";r.push({code:"data"===e.type?"edge.invalid-direction":"edge.type-mismatch",path:`${i}.${t}`,message:`Edge '${e.id}' ${t} port '${o.port}' on node '${o.nodeId}' is not an ${a} port of kind '${n.manifest.kind}'`,edgeId:e.id,nodeId:o.nodeId,details:{port:o.port,expected:a}})}}class Fo{validate(e,t){this.validateDuplicates(e.edges,t),this.validatePolicies(e,t)}validateDuplicates(e,t){const o=new Map;for(const n of e){const e=`${n.sourceNodeId}:${n.sourcePort}->${n.targetNodeId}:${n.targetPort}`,r=o.get(e);r?t.push({code:"connection.duplicate-edge",path:`edges[${n.id}]`,message:`Edge '${n.id}' duplicates the routing of edge '${r.id}' (${e})`,edgeId:n.id,details:{duplicateOf:r.id,routing:e}}):o.set(e,n)}}validatePolicies(e,t){const o=new Map;for(const t of e.edges){if("connection"!==t.type)continue;const e=`${t.targetNodeId}:${t.targetPort}`,n=o.get(e)??[];n.push(t),o.set(e,n)}for(const o of e.edges){if("connection"!==o.type)continue;const n=e.nodeById.get(o.targetNodeId),r=n?.manifest.connections?.find(e=>e.id===o.targetPort)?.connectionPolicy;this.validateEdgePolicy(o,e.nodeById,r,t)}for(const[n,r]of o){const o=n.lastIndexOf(":"),i=n.slice(0,o),a=n.slice(o+1),s=e.nodeById.get(i),d=s?.manifest.connections?.find(e=>e.id===a)?.connectionPolicy;if(!d)continue;const l=void 0!==d.maxConnections?d.maxConnections:!1===d.allowMultiple?1:1/0;r.length>l&&t.push({code:"connection.max-connections",path:`edges[${r[r.length-1].id}]`,message:`Connection port '${a}' on node '${i}' accepts at most ${l} connection(s) but has ${r.length}`,nodeId:i,edgeId:r[r.length-1].id,details:{port:a,max:l,actual:r.length}})}}validateEdgePolicy(e,t,o,n){if(e.sourceNodeId===e.targetNodeId&&!o?.allowSelf)return void n.push({code:"connection.self-connection",path:`edges[${e.id}]`,message:`Edge '${e.id}' connects node '${e.sourceNodeId}' to itself, which the target port policy does not allow`,edgeId:e.id,nodeId:e.sourceNodeId});if(!o)return;const r=t.get(e.sourceNodeId),i=r?.manifest.kind;if(!o.allowedNodeKinds?.length||i&&o.allowedNodeKinds.includes(i)||n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${i??"unknown"}' is not in the allowed node kinds of target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{allowedNodeKinds:o.allowedNodeKinds}}),i&&o.blockedNodeKinds?.includes(i)&&n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source kind '${i}' is blocked by target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{blockedNodeKinds:o.blockedNodeKinds}}),o.allowedPortCategories?.length){const t=r?.manifest.connections?.find(t=>t.id===e.sourcePort)?.category;t&&o.allowedPortCategories.includes(t)||n.push({code:"connection.policy",path:`edges[${e.id}]`,message:`Connection edge '${e.id}' source port '${e.sourcePort}' category '${t??"unknown"}' is not in the allowed port categories of target port '${e.targetPort}'`,edgeId:e.id,nodeId:e.sourceNodeId,details:{allowedPortCategories:o.allowedPortCategories}})}}}class Bo{constructor(e){this.authorizer=e}async validate(e,t,o,n){const r=this.collectReferences(e,t);for(const i of t.credentials??[]){const a=r.find(e=>void 0===e.credentialType||e.credentialType===i.type);if(a){if(this.checkType(a,i))o.push({code:"credential.type-mismatch",path:n,message:`Node '${e.id}' credential '${a.credentialId}' has type '${a.credentialType}' but kind '${t.kind}' requires '${i.type}'`,nodeId:e.id,details:{credentialType:a.credentialType??"",requiredType:i.type}});else if(this.authorizer){if(!await this.authorizer.hasCredential(a)){o.push({code:"credential.not-found",path:n,message:`Node '${e.id}' references credential '${a.credentialId}' which does not exist`,nodeId:e.id,details:{credentialId:a.credentialId}});continue}await this.authorizer.authorize(a,i)||o.push({code:"credential.unauthorized",path:n,message:`Node '${e.id}' is not authorized to use credential '${a.credentialId}'`,nodeId:e.id,details:{credentialId:a.credentialId}})}}else!1!==i.required&&o.push({code:"credential.missing",path:n,message:`Node '${e.id}' does not provide the required credential of type '${i.type}'`,nodeId:e.id,details:{credentialType:i.type}})}this.scanPlainSecrets(e,o,n)}collectReferences(e,t){const o=[];for(const n of t.parameters){if("credential"!==n.type)continue;const t=(e.parameters??{})[n.id];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(Mo);for(const[r,i]of Object.entries(e.parameters??{}))this.scanPlainSecretValue(i,[r],e,o+".parameters",n,t);for(const[r,i]of Object.entries(e.metadata??{}))this.scanPlainSecretValue(i,[r],e,o+".metadata",n,t)}scanPlainSecretValue(e,t,o,n,r,i,a=0){const s=t[t.length-1];if(r.has(s))i.push({code:"credential.plain-secret",path:`${n}.${t.join(".")}`,message:`Node '${o.id}' carries plain secret material in '${t.join(".")}'; workflow documents may only hold credential references`,nodeId:o.id});else if(8>a&&null!==e)if(Array.isArray(e))for(const s of e)this.scanPlainSecretValue(s,[...t,"[]"],o,n,r,i,a+1);else if("object"==typeof e)for(const[s,d]of Object.entries(e))this.scanPlainSecretValue(d,[...t,s],o,n,r,i,a+1)}}class qo extends x{constructor(e,t=[]){super(e),this.issues=t,this.name=qo.name}}class Wo extends x{constructor(e,t){super(e),this.edgeId=t,this.name=Wo.name}}class Vo extends M{constructor(e){super(e),this.name=Vo.name}}const Ho={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},Ko=["node","definition","executor","execute","ports","component"];function zo(e){if(!e||"object"!=typeof e)return!1;const t=e;return pt(t.document)&&Array.isArray(t.nodes)&&Array.isArray(t.edges)&&t.nodeById instanceof Map&&t.incomingByNode instanceof Map&&t.outgoingByNode instanceof Map&&t.nodes.every(e=>null!==e&&"object"==typeof e&&"object"==typeof e.instance&&"object"==typeof e.manifest&&"object"==typeof e.executor)}function Jo(e,t){const o=[];for(const n of Object.keys(e))Ko.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 Xo{constructor(e){this.options=e,this.parameterValidator=new Go,this.edgeValidator=new Uo,this.connectionPolicyValidator=new Fo,this.nodeValidator=new So(e.catalogue),this.credentialValidator=new Bo(e.credentialAuthorizer)}async validateOrThrow(e,...t){const o=await this.validate(e,0,...t);if(!o.valid||!o.resolved)throw new qo(`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={...Ho,...this.options.limits};if(!await this.validateStructure(e,r,t,n,...o))return{valid:!1,issues:n};const i=await this.nodeValidator.resolveNodes(e.nodes,n,this.options.resolutionContext,...o),a=e.nodes.filter(e=>i.has(e.id)).map(e=>i.get(e.id)),s=(e=>{const t=new Map;for(const o of e.edges??[]){if("data"!==o.type)continue;const e=o.target;if("node"!==e.scope)continue;const n=t.get(e.nodeId)??new Set;n.add(e.port),t.set(e.nodeId,n)}return t})(e);for(const e of a)this.parameterValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`,s.get(e.instance.id));for(const e of a)this.nodeValidator.validateEffectivePorts(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);const d=this.edgeValidator.resolveEdges(e,i,n),l=new Map,c=new Map;for(const e of d){if(e.targetNodeId!==Ft){const t=l.get(e.targetNodeId)??[];t.push(e),l.set(e.targetNodeId,t)}if(e.sourceNodeId!==Ft){const t=c.get(e.sourceNodeId)??[];t.push(e),c.set(e.sourceNodeId,t)}}this.connectionPolicyValidator.validate({edges:d,nodeById:i},n),this.validateAcyclicity(a,d,e,n),Ro(e,n);for(const e of a)this.parameterValidator.validateBindingSatisfaction(e.instance,e.manifest,l.get(e.instance.id)??[],n,`nodes[${e.instance.id}]`,{allowLiteralAndEdgeBindings:this.options.allowLiteralAndEdgeBindings});this.validateRequiredWorkflowOutputs(e,c,n);for(const e of a)await this.credentialValidator.validate(e.instance,e.manifest,n,`nodes[${e.instance.id}]`);return this.validateCapabilities(a,n),n.length>0?{valid:!1,issues:n}:{valid:!0,issues:n,resolved:{document:e,nodes:a,edges:d,nodeById:i,incomingByNode:l,outgoingByNode:c}}}async validateStructure(e,t,o,n,...r){if(!pt(e))return n.push({code:"document.shape",path:"$",message:"Payload is not a canonical GraphWorkflowDocument: id and name must be strings and inputs, outputs, nodes and edges must be arrays"}),!1;if(e.id&&e.id.trim()||n.push({code:"document.empty-id",path:"$.id",message:"Workflow document id must be a non-empty string"}),!Ue(e))return n.push({code:"document.json-unsafe",path:"$",message:"Document contains JSON-unsafe values: functions, class instances, undefined, NaN/Infinity, symbol keys and unsafe prototype keys are rejected"}),!1;n.push(...Jo(e,"$"));for(const t of[...e.inputs,...e.outputs])n.push(...Jo(t,"ports"));for(const t of e.nodes)n.push(...Jo(t,`nodes[${t.id}]`));for(const t of e.edges)n.push(...Jo(t,`edges[${t.id}]`));this.validateUniqueIds(e,n),this.validateLimits(e,t,o,n);try{ot(e)}catch(e){n.push({code:"document.structure",path:"$",message:e instanceof Error?e.message:e+""})}return await this.validateNestedBodies(e,o,n,...r),!0}validateUniqueIds(e,t){const o=new Set,n=new Set;for(const[r,i]of[["input",e.inputs],["output",e.outputs]]){const e="input"===r?o:n;for(const o of i)e.has(o.id)?t.push({code:"document.duplicate-port-id",path:`${"input"===r?"inputs":"outputs"}[${o.id}]`,message:`Workflow ${r} port '${o.id}' is declared more than once; workflow port ids must be unique`}):e.add(o.id)}const r=new Set;for(const o of e.nodes)r.has(o.id)?t.push({code:"document.duplicate-node-id",path:`nodes[${o.id}]`,message:`Node '${o.id}' is declared more than once; node ids must be unique`,nodeId:o.id}):r.add(o.id);const i=new Set;for(const o of e.edges)i.has(o.id)?t.push({code:"document.duplicate-edge-id",path:`edges[${o.id}]`,message:`Edge '${o.id}' is declared more than once; edge ids must be unique`,edgeId:o.id}):i.add(o.id)}validateLimits(e,t,o,n){e.nodes.length>t.maxNodes&&n.push({code:"document.limit.nodes",path:"$.nodes",message:`Document declares ${e.nodes.length} nodes; at most ${t.maxNodes} are allowed`,details:{count:e.nodes.length,limit:t.maxNodes}}),e.edges.length>t.maxEdges&&n.push({code:"document.limit.edges",path:"$.edges",message:`Document declares ${e.edges.length} edges; at most ${t.maxEdges} are allowed`,details:{count:e.edges.length,limit:t.maxEdges}}),o>t.maxNestingDepth&&n.push({code:"document.limit.depth",path:"$",message:`Document nests loop bodies ${o} levels deep; at most ${t.maxNestingDepth} levels are allowed`,details:{depth:o,limit:t.maxNestingDepth}});const r=Buffer.byteLength(JSON.stringify(e),"utf8");r>t.maxDocumentBytes&&n.push({code:"document.limit.size",path:"$",message:`Document serializes to ${r} bytes; at most ${t.maxDocumentBytes} bytes are allowed`,details:{bytes:r,limit:t.maxDocumentBytes}})}async validateNestedBodies(e,t,o,...n){for(const r of e.nodes){const e=[["loop.body",r.loop?.body],["errorBoundary.try",r.errorBoundary?.try],["errorBoundary.catch",r.errorBoundary?.catch],["errorBoundary.finally",r.errorBoundary?.finally]];for(const[i,a]of e){if(!a)continue;const e=await this.validate(a,t+1,...n);for(const t of e.issues)o.push({...t,path:`nodes[${r.id}].${i}.${t.path}`,nodeId:t.nodeId??r.id})}}}validateAcyclicity(e,t,o,n){const r=new Set(e.map(e=>e.instance.id)),i=new Map(e.map(e=>[e.instance.id,0]));for(const e of t)r.has(e.sourceNodeId)&&i.has(e.targetNodeId)&&i.set(e.targetNodeId,(i.get(e.targetNodeId)??0)+1);const a=[...i.entries()].filter(([,e])=>0===e).map(([e])=>e),s=[];for(;a.length>0;){const e=a.shift();s.push(e);for(const o of t){if(o.sourceNodeId!==e)continue;if(!i.has(o.targetNodeId))continue;const t=(i.get(o.targetNodeId)??1)-1;i.set(o.targetNodeId,t),0===t&&a.push(o.targetNodeId)}}if(s.length!==i.size){const e=[...i.keys()].filter(e=>!s.includes(e));n.push({code:"topology.cycle",path:"$.edges",message:`Workflow '${o.id}' contains an unsupported cycle involving node(s): ${e.join(", ")}`,details:{cyclicNodes:e}})}}validateRequiredWorkflowOutputs(e,t,o){const n=new Set;for(const e of t.values())for(const t of e)t.targetNodeId===Ft&&n.add(t.targetPort);for(const t of e.outputs)!0===t.required&&void 0===t.defaultValue&&(n.has(t.id)||o.push({code:"topology.required-output-unsatisfiable",path:`outputs[${t.id}]`,message:`Required workflow output '${t.id}' has no incoming edge from any node`}))}validateCapabilities(e,t){for(const o of e){const e=o.manifest;for(const n of e.capabilities??[])gt(n)||t.push({code:"capability.invalid",path:`nodes[${o.instance.id}]`,message:`Kind '${e.kind}' declares unknown capability '${n+""}'`,nodeId:o.instance.id,details:{capability:n+""}});!0!==e.policies?.allowUndeclaredParameters&&o.instance.loop&&((e.capabilities??[]).includes("loop")||t.push({code:"capability.loop-not-supported",path:`nodes[${o.instance.id}].loop`,message:`Node '${o.instance.id}' carries loop configuration but kind '${e.kind}' does not declare the 'loop' capability`,nodeId:o.instance.id}))}}}let Yo=class extends U{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"}'`),!zo(e))throw new io("GraphExecutionPlanner.plan accepts only a GraphResolvedWorkflow produced by the nine-stage validation gate; raw workflow definitions and inline node definitions are rejected",{received:(n=e,n&&"object"==typeof n?{reason:"input is not a GraphResolvedWorkflow",looksLikeWorkflowDefinition:"nodes"in n&&"relations"in n&&!("nodeById"in n),hasResolvedNodes:Array.isArray(n.nodes)}:{reason:"input is not an object"})});var n;const r=this.buildPlanNodes(e),i=this.buildPlanEdges(e),a=this.buildIncomingMap(i),s=this.buildOutgoingMap(i),d=this.topologicalLayers(r,i);return{resolved:e,workflowId:e.document.id||e.document.name,nodes:r,edges:i,layers:d,incomingByNode:a,outgoingByNode:s}}buildPlanNodes(e){return e.nodes.map(e=>({id:e.instance.id,kind:e.manifest.kind,instance:e.instance,manifest:e.manifest,executor:e.executor,inputPorts:e.manifest.inputs.map(e=>e.id),outputPorts:e.manifest.outputs.map(e=>e.id),connectionPorts:(e.manifest.connections??[]).map(e=>e.id),metadata:e.instance.metadata}))}buildPlanEdges(e){return e.edges.map(e=>({id:e.id,type:e.type,sourceNodeId:e.sourceNodeId,sourcePort:e.sourcePort,targetNodeId:e.targetNodeId,targetPort:e.targetPort,...void 0!==e.label?{label:e.label}:{},metadata:e.metadata}))}buildIncomingMap(e){const t=new Map;for(const o of e){if(o.targetNodeId===Ft)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===Ft)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!==Ft),n=new Set(o.map(e=>e.id)),r=t.filter(e=>n.has(e.sourceNodeId)&&n.has(e.targetNodeId)),i=new Map;for(const e of o)i.set(e.id,0);for(const e of r)i.set(e.targetNodeId,(i.get(e.targetNodeId)??0)+1);const a=[],s=new Set;let d=o.filter(e=>0===(i.get(e.id)??0)),l=0;for(;d.length>0;){const e={index:l++,nodes:d};a.push(e);const t=[];for(const e of d){s.add(e.id);const n=r.filter(t=>t.sourceNodeId===e.id);for(const e of n){const n=(i.get(e.targetNodeId)??1)-1;if(i.set(e.targetNodeId,n),0===n&&!s.has(e.targetNodeId)){const n=o.find(t=>t.id===e.targetNodeId);n&&t.push(n)}}}d=t}if(s.size!==o.length){const e=o.filter(e=>!s.has(e.id)).map(e=>e.id);throw new Zt({unplannedNodes:e,workflowId:o[0]?.manifest.kind})}return a}};Yo=D([G(),$("design:paramtypes",[])],Yo);let Qo=class extends T{constructor(e){super(e)}};function Zo(e){return[e.namespace??"default",e.workflowId,e.nodeId,e.version??"default",e.fingerprint].join(":")}function en(e){return new Qo({id:Zo(e.key),workflowId:e.key.workflowId,nodeId:e.key.nodeId,fingerprint:e.key.fingerprint,...void 0!==e.key.namespace?{namespace:e.key.namespace}:{},...void 0!==e.key.version?{version:e.key.version}:{},pinned:e.pinned,outputs:e.outputs,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt),...e.expiresAt?{expiresAt:new Date(e.expiresAt)}:{},...e.metadata?{metadata:e.metadata}:{}})}function tn(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}:{}}}D([P({type:String,generated:!1}),$("design:type",String)],Qo.prototype,"id",void 0),D([S(),R(),$("design:type",String)],Qo.prototype,"workflowId",void 0),D([S(),R(),$("design:type",String)],Qo.prototype,"nodeId",void 0),D([S(),$("design:type",String)],Qo.prototype,"fingerprint",void 0),D([S(),$("design:type",String)],Qo.prototype,"namespace",void 0),D([S(),$("design:type",String)],Qo.prototype,"version",void 0),D([S(),$("design:type",Boolean)],Qo.prototype,"pinned",void 0),D([S(),$("design:type",Object)],Qo.prototype,"outputs",void 0),D([S(),$("design:type",Date)],Qo.prototype,"createdAt",void 0),D([S(),$("design:type",Date)],Qo.prototype,"updatedAt",void 0),D([S(),$("design:type",Date)],Qo.prototype,"expiresAt",void 0),D([S(),$("design:type",Object)],Qo.prototype,"metadata",void 0),Qo=D([C("graph_value"),E(),$("design:paramtypes",[Object])],Qo);let on=class extends B{constructor(e){super(e,Qo,!0),this.runtimeValues=new Map}seedWorkflowInputs(e){this.runtimeValues.set(Ft,{...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(Ft)??{};o[e]=t,this.runtimeValues.set(Ft,o)}getWorkflowValues(){return{...this.runtimeValues.get(Ft)??{}}}snapshot(){return Object.fromEntries(this.runtimeValues.entries())}async readCached(e,...t){try{return tn(await this.read(Zo(e),...t))}catch{return}}async writeCached(e,t,...o){const n=Zo(e);let r;try{r=await this.read(n,...o)}catch{r=void 0}r?await this.update(Object.assign(r,en(t)),...o):await this.create(en(t),...o)}async deleteCached(e,...t){try{await this.delete(Zo(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=>tn(e)).filter(t=>((e,t)=>!(void 0!==t.workflowId&&e.workflowId!==t.workflowId||void 0!==t.nodeId&&e.nodeId!==t.nodeId||void 0!==t.namespace&&e.namespace!==t.namespace||void 0!==t.version&&e.version!==t.version||void 0!==t.fingerprint&&e.fingerprint!==t.fingerprint))(t.key,e))}async clearRun(e,...t){const o=await this.select().execute(...t);for(const e of o)await this.delete(e.id,...t)}readRuntimeValues(e){return this.runtimeValues.get(e)}writeRuntimeValues(e,t){this.runtimeValues.set(e,{...t})}getAdapter(){return this.adapter}};function nn(e){return new(0,B.forModel(Qo,e.alias).constructor)(e)}on=D([F(Qo,m),$("design:paramtypes",[Function])],on);class rn{static upstreamNodes(e,t,o=!1){const n=new Set,r=[e];for(;r.length;){const e=r.pop(),i=t.get(e)??[];for(const e of i)!o&&this.isBoundary(e.sourceNodeId)||n.has(e.sourceNodeId)||(n.add(e.sourceNodeId),r.push(e.sourceNodeId))}return n}static downstreamNodes(e,t,o=!1){const n=new Set,r=[e];for(;r.length;){const e=r.pop(),i=t.get(e)??[];for(const e of i)!o&&this.isBoundary(e.targetNodeId)||n.has(e.targetNodeId)||(n.add(e.targetNodeId),r.push(e.targetNodeId))}return n}static isBoundary(e){return"$workflow"===e}}class an{constructor(e,t,o){this.store=e,this.policy=t,this.dependencyResolver=o}async pinNode(e){const t=e.plan,o=e.includeDependencies??1?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 oo(`Node '${e}' not found in plan`);if(!this.policy.canPin(o))throw new oo(`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 oo(`Node '${o}' has no completed output to pin`);const i=r.inputs??{},a=this.dependencyFingerprints(t,o,e.result),s=this.createValueKey(e.document.id,n,i,a),d=(new Date).toISOString(),l={key:s,outputs:r.outputs,pinned:!0,createdAt:d,updatedAt:d,metadata:{...e.result.metadata,nodeId:o}};await this.store.writeCached(s,l)}}async unpinNode(e){const t={workflowId:e.document.id,nodeId:e.nodeId,fingerprint:e.fingerprint,namespace:e.namespace};await this.store.deleteCached(t)}async readPinnedValue(e,t,o,n,r){const i=this.createValueKey(e,t,o,n,r),a=await this.store.readCached(i);if(a&&a.pinned){if(a.expiresAt&&new Date(a.expiresAt)<new Date)return;return a}}createValueKey(e,t,o,n,r){return{workflowId:e,nodeId:t.id,fingerprint:this.computeFingerprint(e,t,o,n),namespace:r}}computeFingerprint(e,t,o,n){const r={workflowId:e,nodeId:t.id,nodeKind:t.kind,parameters:this.stableSerialize(t.instance.parameters??{}),inputBindings:this.stableSerialize(t.instance.inputBindings??{}),metadata:this.stableSerialize(this.relevantMetadata(t)),inputs:this.stableSerialize(o),dependencyFingerprints:this.stableSerialize(n)},i=this.stableSerialize(r);return this.simpleHash(i)}relevantMetadata(e){const t={...e.metadata??{}};return delete t.ui,delete t.position,delete t.visual,t}topologicalOrder(e,t){const o=[],n=new Set,r=i=>{if(n.has(i))return;n.add(i);const a=rn.upstreamNodes(i,e.incomingByNode,!1);for(const e of a)t.has(e)&&r(e);o.push(i)};for(const e of t)r(e);return o}dependencyFingerprints(e,t,o){const n=this.dependencyResolver.getDependencies(e,t),r={};for(const t of n){const n=e.nodes.find(e=>e.id===t);if(n){const i=o.nodeResults[t],a=i?.inputs??{},s=this.dependencyFingerprints(e,t,o);r[t]=this.computeFingerprint(e.workflowId,n,a,s)}}return r}stableSerialize(e){return null===e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?`[${e.map(e=>this.stableSerialize(e)).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${this.stableSerialize(e[t])}`).join(",")}}`}simpleHash(e){let t=0;for(let o=0;o<e.length;o++)t=(t<<5)-t+e.charCodeAt(o),t|=0;return`fp_${Math.abs(t).toString(16).padStart(8,"0")}_${e.length}`}}const sn={enabled:!0,strategy:"manual",includeDependencies:!0};function dn(e){return!0===e?.enabled&&"disabled"!==e.strategy}class ln{canPin(e){return dn(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?{...sn,...t}:{...sn,enabled:!1}}}class cn{getDependencies(e,t){return rn.upstreamNodes(t,e.incomingByNode,!1)}getPinSet(e,t){const o=this.getDependencies(e,t);return o.add(t),o}}class un extends q{constructor(){super()}async initialize(...e){const t=e[0];if(!t||"object"!=typeof t||!t.registry)return this._config=void 0,this._client=void 0,{config:void 0,client:void 0};const o=t.catalogue??t.registry.catalog,n=t.valueAdapter??W.current;if(!n)throw new Qt("GraphExecutionEngine requires a Decaf adapter for cached/pinned values: pass `valueAdapter` or configure one via `Adapter.setCurrent(...)`","GRAPH_VALUE_ADAPTER_MISSING");const r={registry:t.registry,catalogue:o,planner:t.planner??new Yo,valueAdapter:n,eventEmitter:t.eventEmitter??new co,documentValidator:t.documentValidator??new Xo({catalogue:o,limits:t.documentLimits,credentialAuthorizer:t.credentialAuthorizer}),authValidator:new xo({enabled:!0===t.authEnabled,...t.authMatch?{match:t.authMatch}:{}}),...t.codeSandboxEvaluator?{codeSandboxEvaluator:t.codeSandboxEvaluator}:{}};return this._config=t,this._client=r,await(t.onEngineCreated?.(this)),{config:t,client:r}}get codeSandboxEvaluator(){return this.client.codeSandboxEvaluator}get emitter(){return this.client.eventEmitter}get planner(){return this.client.planner}get valueAdapter(){return this.client.valueAdapter}get defaultOptions(){return this.config.defaultOptions??{}}get documentValidator(){return this.client.documentValidator}observe(e){return this.emitter.observe(e)}unObserve(e){this.emitter.unObserve(e)}async dispatchEvent(e){await this.emitter.updateObservers(e)}async execute(e,t={},o={},...n){const{log:r,ctx:i}=(await this.logCtx(n,"execute",!0)).for(this.execute);r.debug(`Executing workflow '${e.id||e.name}'`);const a=this.mergeOptions(o);this.assertNotAborted(a);const s=Ao(No(i),a.auth);a.auth=s,a.metadata={...a.metadata??{},...s};const d=a.runId??this.generateRunId(),l=a.path??[],c=new uo,u=nn(this.valueAdapter);u.seedWorkflowInputs(this.withWorkflowInputDefaults(e,t));const p=async t=>{await this.emitEvent(m,{type:t.type??ce.NODE_OUTPUT,runId:d,parentRunId:a.parentRunId,workflowId:e.id||e.name,nodeId:t.nodeId,path:t.path??l,...t})},h=async t=>{const o=c.create({id:"",sequence:0,timestamp:new Date,runId:d,parentRunId:a.parentRunId,workflowId:e.id||e.name,path:l,...t});await this.emitter.updateObservers(o)};await h({type:ce.VALIDATION_STARTED,status:se.PLANNING});const f=await this.documentValidator.validate(e,0,i);if(!f.valid||!f.resolved)throw await h({type:ce.VALIDATION_FAILED,status:se.FAILED,payload:{issues:f.issues}}),new qo(`Graph workflow document '${e.id}' failed validation with ${f.issues.length} issue(s)`,f.issues);await h({type:ce.VALIDATION_COMPLETED,status:se.PLANNING,payload:{issues:f.issues.length}}),this.assertNotAborted(a);const g=await this.planner.plan(f.resolved);this.client.authValidator.validate(e,g,s,r),r.debug(`Authorized workflow '${e.id||e.name}' for user ${s.user??"anonymous"}`);const m=new $o(d,g,u,c);await this.emitEvent(m,{type:ce.WORKFLOW_STARTED,runId:d,parentRunId:a.parentRunId,workflowId:g.workflowId,path:l,status:se.RUNNING,payload:{inputs:t}}),await this.emitEvent(m,{type:ce.WORKFLOW_PLANNED,runId:d,parentRunId:a.parentRunId,workflowId:g.workflowId,path:l,status:se.PLANNING,payload:{layers:g.layers.length,nodes:g.nodes.length}});try{for(const e of g.layers)this.assertNotAborted(a),await this.executeLayer(m,g,e.nodes,a,p);this.assertNotAborted(a);const o=[...m.nodeResults.values()].find(e=>e.status===se.FAILED);if(o?.error)throw new Qt(o.error.message,o.error.code??"GRAPH_EXECUTION_ERROR",o.error.details);return m.finish(),await this.emitEvent(m,{type:ce.WORKFLOW_COMPLETED,runId:d,parentRunId:a.parentRunId,workflowId:g.workflowId,path:l,status:se.SUCCEEDED,payload:{outputs:u.getWorkflowValues()}}),Po(m,e,t,se.SUCCEEDED,a.metadata)}catch(o){if(o instanceof ao)throw m.finish(),o;m.finish();const n=this.toErrorPayload(o);return o instanceof so||!0===a.abortSignal?.aborted?(await this.emitEvent(m,{type:ce.WORKFLOW_CANCELLED,runId:d,parentRunId:a.parentRunId,workflowId:g.workflowId,path:l,status:se.CANCELLED,error:n}),Po(m,e,t,se.CANCELLED,a.metadata)):(await this.emitEvent(m,{type:ce.WORKFLOW_FAILED,runId:d,parentRunId:a.parentRunId,workflowId:g.workflowId,path:l,status:se.FAILED,error:n}),Po(m,e,t,se.FAILED,a.metadata))}}async pinNode(e){const t=this.createPinningService();await t.pinNode(e),await this.emitPinningEvent(e.nodeId,ce.NODE_PINNED)}async unpinNode(e){const t=this.createPinningService();await t.unpinNode(e),await this.emitPinningEvent(e.nodeId,ce.NODE_UNPINNED)}createPinningService(){const e=nn(this.valueAdapter);return new an(e,new ln,new cn)}async emitPinningEvent(e,t){const o=(new uo).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}async executeLayer(e,t,o,n,r){const i=Math.max(1,n.concurrency??4),a=[...o];for(;a.length>0;){const o=a.splice(0,i);await Promise.all(o.map(o=>this.executeNode(e,t,o,n,r)))}}async executeNode(e,t,o,n,r){if(this.assertNotAborted(n),!this.isNodeActivated(e,t,o))return void await this.skipInactiveNode(e,t,o,n);if(!0===o.instance.disabled)return void await this.executeDisabledNode(e,t,o,n);const i=new Date,a=[...n.path??[],o.id];await this.emitEvent(e,{type:ce.NODE_STARTED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.RUNNING}),this.emitNodeStateChanged(e,t,o,a,de.RUNNING,se.RUNNING);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);const r=new Date,d={nodeId:o.id,status:se.CACHED,inputs:s,outputs:n.outputs,startedAt:i,finishedAt:r,fromCache:!0,pinned:!0,events:[]};return e.recordNodeResult(d),await this.emitEvent(e,{type:ce.NODE_CACHE_HIT,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.CACHED,payload:{outputs:n.outputs}}),await this.emitEvent(e,{type:ce.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.SUCCEEDED,payload:{outputs:n.outputs,fromCache:!0}}),void this.emitNodeStateChanged(e,t,o,a,de.SUCCEEDED,se.SUCCEEDED)}}try{const d=new Do(e.runId,n.parentRunId,t.workflowId,t.resolved.document,o.instance,o.manifest,a,r,n.metadata,this,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);const h=new Date,f={nodeId:o.id,status:se.SUCCEEDED,inputs:s,outputs:p,startedAt:i,finishedAt:h,events:[]};e.recordNodeResult(f),await this.emitEvent(e,{type:ce.NODE_COMPLETED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.SUCCEEDED,payload:{outputs:p}}),this.emitNodeStateChanged(e,t,o,a,de.SUCCEEDED,se.SUCCEEDED)}catch(r){if(r instanceof ao)throw r;const d=new Date,l=this.toErrorPayload(r),c={nodeId:o.id,status:se.FAILED,inputs:s,error:l,startedAt:i,finishedAt:d,events:[]};if(e.recordNodeResult(c),await this.emitEvent(e,{type:ce.NODE_FAILED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:a,status:se.FAILED,error:l}),this.emitNodeStateChanged(e,t,o,a,de.FAILED,se.FAILED),n.failFast??1)throw r}}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===Ft||e.isDataEdgeActive(t.id))}async skipInactiveNode(e,t,o,n){const r=new Date,i=[...n.path??[],o.id];await this.emitEvent(e,{type:ce.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:se.SKIPPED,payload:{reason:"branchNotSelected"}});const a={nodeId:o.id,status:se.SKIPPED,inputs:{},startedAt:r,finishedAt:new Date,events:[]};e.recordNodeResult(a),this.emitNodeStateChanged(e,t,o,i,de.SKIPPED,se.SKIPPED)}async executeDisabledNode(e,t,o,n){const r=new Date,i=[...n.path??[],o.id],a=Go.disabledBehaviorOf(o.instance,t.resolved.document.settings);if(await this.emitEvent(e,{type:ce.NODE_SKIPPED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:i,status:se.SKIPPED,payload:{disabled:!0,behavior:a}}),"skip"===a){const n={nodeId:o.id,status:se.SKIPPED,inputs:{},startedAt:r,finishedAt:new Date,events:[]};return e.recordNodeResult(n),void this.emitNodeStateChanged(e,t,o,i,de.SKIPPED,se.SKIPPED)}const s=await this.resolveNodeInputs(e,t,o,n);let d;if("passThroughFirstInput"===a){const n=(t.incomingByNode.get(o.id)??[]).find(e=>"data"===e.type),r=o.manifest.outputs[0]?.id??"value",i=n?e.valueStore.getPort(n.sourceNodeId,n.sourcePort):Object.values(s)[0];d={[r]:i}}else{d={};for(const e of o.manifest.outputs)d[e.id]=e.metadata?.defaultValue}e.valueStore.setNodeOutputs(o.id,d),this.routeOutgoingEdges(e,t,o,d);const l={nodeId:o.id,status:se.SUCCEEDED,inputs:s,outputs:d,startedAt:r,finishedAt:new Date,events:[]};e.recordNodeResult(l),this.emitNodeStateChanged(e,t,o,i,de.SUCCEEDED,se.SUCCEEDED)}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 Qt(`Node '${e.id}' of kind '${e.kind}' produced unknown output(s): ${r.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,unknownOutputs:r});const i=o.outputs.filter(e=>!0===e.required&&!(e.id in t)).map(e=>e.id);if(i.length>0)throw new Qt(`Node '${e.id}' of kind '${e.kind}' did not produce required output(s): ${i.join(", ")}`,"GRAPH_OUTPUT_VALIDATION_FAILED",{nodeId:e.id,missingRequired:i});return t}collectCredentials(e){const t={};for(const o of e.manifest.parameters){if("credential"!==o.type)continue;const n=(e.instance.parameters??{})[o.id];"string"==typeof n&&n.length>0?t[o.id]={credentialId:n,credentialType:o.credentialType??""}: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={},i=(t.incomingByNode.get(o.id)??[]).filter(e=>"data"===e.type),a=new Map;for(const e of i){const t=a.get(e.targetPort)??[];t.push(e),a.set(e.targetPort,t)}for(const[t,o]of a)if(1===o.length)r[t]=e.valueStore.getPort(o[0].sourceNodeId,o[0].sourcePort);else{let n,i=!1;for(const t of o){const o=e.valueStore.getPort(t.sourceNodeId,t.sourcePort);r[t.sourcePort]=o,void 0!==o&&(n=o,i=!0)}i&&void 0===r[t]&&(r[t]=n)}const s=o.instance.inputBindings??{};for(const e of o.manifest.inputs){const t=s[e.id];if("literal"===t?.mode)r[e.id]=t.value;else if("expression"===t?.mode)r[e.id]=await this.evaluateExpressionBinding(o,t.expression,r,n);else if(void 0===r[e.id]){const t=e.metadata?.defaultValue;void 0!==t&&(r[e.id]=t)}}return r}async resolveNodeParameters(e,t,o){const n=e.instance.parameters??{},r={};for(const[i,a]of Object.entries(n))r[i]=ut(a)?await this.evaluateValueTemplate(a,e,t,o):a;return r}async evaluateValueTemplate(e,t,o,n){const r=this.codeSandboxEvaluator;if(!r)throw new Qt(`Value template on node '${t.id}' requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator`,"GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{nodeId:t.id});const i=e.language??("expression"===e.mode?"javascript":"text"),a="template"===e.mode?(e=>`\`${e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\{\{\s*([\s\S]*?)\s*\}\}/g,(e,t)=>`\${${t}}`)}\``)(e.expression):e.expression,s=n.metadata;return await r.evaluate({code:a,language:"typescript"===i?"typescript":"javascript",input:o,vars:s?.vars??void 0,item:s?.item,index:s?.index,abortSignal:n.abortSignal})}async evaluateExpressionBinding(e,t,o,n){const r=this.codeSandboxEvaluator;if(!r)throw new Qt(`Expression binding on node '${e.id}' requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator`,"GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{nodeId:e.id,expression:t});const i=n.metadata;return await r.evaluate({code:t,language:"javascript",input:o,vars:i?.vars??void 0,item:i?.item,index:i?.index,abortSignal:n.abortSignal})}async tryPinnedValue(e,t,o,n){if(!(new ln).shouldUsePinnedValue(o))return;const r=this.createPinningService(),i=this.computeDependencyFingerprints(e,t,o.id);return r.readPinnedValue(t.workflowId,o,n,i)}computeDependencyFingerprints(e,t,o){const n=this.createPinningService(),r=(new cn).getDependencies(t,o),i={};for(const o of r){const r=t.nodes.find(e=>e.id===o);if(r){const a=e.nodeResults.get(o),s=a?.inputs??{},d=this.computeDependencyFingerprints(e,t,o);i[o]=n.computeFingerprint(t.workflowId,r,s,d)}}return i}routeOutgoingEdges(e,t,o,n){const r=(t.outgoingByNode.get(o.id)??[]).filter(e=>"data"===e.type);for(const i of r){if(!Object.prototype.hasOwnProperty.call(n,i.sourcePort))continue;const r=n[i.sourcePort];e.activateDataEdge(i.id),i.targetNodeId===Ft&&e.valueStore.setWorkflowOutput(i.targetPort,r),this.emitEdgeStateChanged(e,t,o,i,de.SUCCEEDED,se.SUCCEEDED),this.emitEvent(e,{type:ce.EDGE_VALUE_ROUTED,runId:e.runId,workflowId:t.workflowId,edgeId:i.id,nodeId:o.id,path:[],payload:{edge:i,value:r}}).catch(()=>{})}}async emitEvent(e,t){const o=e.eventFactory.create({id:"",sequence:0,timestamp:new Date,...t});e.appendEvent(o),await this.emitter.updateObservers(o)}emitNodeStateChanged(e,t,o,n,r,i){this.emitEvent(e,{type:ce.NODE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,path:n,status:i,payload:{nodeId:o.id,state:r,runId:e.runId,workflowId:t.workflowId,status:i}}).catch(()=>{})}emitEdgeStateChanged(e,t,o,n,r,i){this.emitEvent(e,{type:ce.EDGE_STATE_CHANGED,runId:e.runId,workflowId:t.workflowId,edgeId:n.id,nodeId:o.id,path:[],status:i,payload:{edgeId:n.id,state:r,runId:e.runId,workflowId:t.workflowId,nodeId:o.id,status:i}}).catch(()=>{})}mergeOptions(e){return{concurrency:4,failFast:!0,validateInputs:!0,validateOutputs:!0,maxLoopIterations:Vt,maxForeachIterations:Ht,usePinnedValues:!0,writeThroughCache:!1,path:[],metadata:{},...this.defaultOptions,...e}}executionLimits(e){return{maxLoopIterations:e.maxLoopIterations??Vt,maxForeachIterations:e.maxForeachIterations??Ht}}assertNotAborted(e){if(!0===e.abortSignal?.aborted)throw new so(e.runId??"unknown")}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new Qt("Cannot generate a graph run id: crypto.randomUUID is unavailable in this runtime","GRAPH_RUN_ID_ERROR",{runtime:typeof globalThis.crypto});return e.randomUUID()}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+""}}}const pn=new Set(["process","require","module","exports","global","globalThis","Function","eval","fetch","XMLHttpRequest","WebSocket","Worker","Deno","Bun","__dispatch"]);class hn extends q{constructor(){super()}async initialize(...e){const t=e[0]??{},o=t&&"object"==typeof t?t:{};return this._config=o,this._client=K,{config:o,client:K}}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 Qt("Code sandbox received empty code","GRAPH_CODE_SANDBOX_EMPTY_CODE");const n=((e,t)=>"javascript"===t?e:X.transpileModule(e,{compilerOptions:{target:X.ScriptTarget.ES2022,module:X.ModuleKind.None,strict:!0,noEmitHelpers:!0,importHelpers:!1}}).outputText.replace(/^"use strict";\s*/,""))(o,e.language??"javascript");(e=>{if(e.length>1e5)throw new Qt("Code exceeds the maximum length of 100000 characters","GRAPH_CODE_SANDBOX_CODE_TOO_LONG",{length:e.length});let t;try{t=z.parse(`async function __validate() {\n${e}\n}`,{ecmaVersion:"latest",sourceType:"script"})}catch{try{t=z.parse(e,{ecmaVersion:"latest",sourceType:"module"})}catch(t){throw new Qt("Code failed to parse: "+t.message,"GRAPH_CODE_SANDBOX_PARSE_ERROR",{code:e,error:t.message})}}J.full(t,e=>{const t=e;if("ImportDeclaration"===t.type)throw new Qt("Imports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"import"});if("ExportNamedDeclaration"===t.type||"ExportDefaultDeclaration"===t.type)throw new Qt("Exports are not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"export"});if("Identifier"===t.type&&"string"==typeof t.name&&pn.has(t.name))throw new Qt(`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 Qt("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 Qt("eval() is not allowed in Code nodes.","GRAPH_CODE_SANDBOX_FORBIDDEN_TOKEN",{token:"eval"})})})(n);const r=!(e=>/\breturn\b[\s;]/.test(e))(n),i=r?n.replace(/[\s;]+$/,""):n,a={$input:e.input??{},$vars:e.vars??{},$item:e.item,$index:e.index,$node:e.nodes??{},$output:void 0},s=Object.keys(a),d=r?`return (${i});`:i,l=`"use strict";\nasync function __userFunction(${s.join(", ")}) {\n${d}\n}\n__userFunction(${s.join(", ")}).then(function(__r) { return JSON.stringify({ v: __r }); });`,c=new K.Isolate({memoryLimit:this.defaultMemoryMb}),u=await c.createContext();try{const t=u.global;e.logger&&await this.injectConsole(u,e.logger);for(const[e,o]of Object.entries(a))await t.set(e,new K.ExternalCopy(void 0===o?null:o).copyInto());let o;try{o=await c.compileScript(l,{filename:"graph-code-node.js"})}catch(e){if(!r)throw new Qt("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message});{const e=i,t=`"use strict";\nasync function __userFunction(${s.join(", ")}) {\n${e}\n}\n__userFunction(${s.join(", ")}).then(function(__r) { return JSON.stringify({ v: __r }); });`;try{o=await c.compileScript(t,{filename:"graph-code-node.js"})}catch(e){throw new Qt("Code failed to compile: "+e.message,"GRAPH_CODE_SANDBOX_COMPILE_ERROR",{code:n,error:e.message})}}}const d=e.timeoutMs??this.defaultTimeoutMs;let p;try{p=await this.runBounded(o,u,d,e.abortSignal)}catch(e){if(e instanceof Qt)throw e;const t=e.message;if(t.includes("timed out")||t.includes("timeout"))throw new Qt(`Code execution timed out after ${d} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:d});if(t.includes("memory")||t.includes("heap"))throw new Qt(`Code exceeded the memory limit of ${this.defaultMemoryMb} MB`,"GRAPH_CODE_SANDBOX_MEMORY_LIMIT",{memoryMb:this.defaultMemoryMb});throw new Qt("Code execution failed: "+t,"GRAPH_CODE_SANDBOX_RUNTIME_ERROR",{code:n,error:t})}if("string"!=typeof p)throw new Qt("Code sandbox returned an unexpected non-string result","GRAPH_CODE_SANDBOX_UNEXPECTED_RESULT",{result:p});return JSON.parse(p).v}finally{u.release(),c.dispose()}}async runBounded(e,t,o,n){const r=e.run(t,{timeout:o,promise:!0});r.catch(()=>{});const i=[r];let a,s;try{return i.push(new Promise((e,t)=>{a=setTimeout(()=>{t(new Qt(`Code execution timed out after ${o} ms`,"GRAPH_CODE_SANDBOX_TIMEOUT",{timeoutMs:o}))},o+100)})),n&&i.push(new Promise((e,t)=>{const r=()=>{const e="timeout"===n.reason;t(new Qt(e?`Code execution timed out after ${o} ms`:"Code execution aborted",e?"GRAPH_CODE_SANDBOX_TIMEOUT":"GRAPH_CODE_SANDBOX_ABORTED",{timeoutMs:o,reason:n.reason}))};n.aborted?r():(n.addEventListener("abort",r,{once:!0}),s=()=>n.removeEventListener("abort",r))})),await Promise.race(i)}finally{a&&clearTimeout(a),s?.()}}async injectConsole(e,t){const o=new K.Reference((e,o)=>{let n;try{n=JSON.parse(o)}catch{n=[o]}const r=n.map(e=>"string"==typeof e?e:JSON.stringify(e)).join(" "),i=1===n.length?n[0]:n;switch(e){case"log":case"info":default:t.info(r,i);break;case"warn":t.warn(r,i);break;case"error":t.error(r,i);break;case"debug":case"dir":case"dirxml":case"table":t.debug(r,i);break;case"trace":t.trace(r,i);break;case"group":case"groupCollapsed":t.debug("[group] "+r,i);break;case"groupEnd":t.debug("[groupEnd]",void 0);break;case"time":case"timeEnd":case"timeLog":case"count":case"countReset":t.debug(`[${e}] ${r}`,i);break;case"assert":n[0]||t.error("Assertion failed: "+r,i);case"clear":}});await e.evalClosure("\n function __ser() {\n var out = [];\n for (var i = 0; i < arguments.length; i++) {\n var a = arguments[i];\n try { out.push(typeof a === 'object' ? JSON.parse(JSON.stringify(a)) : a); }\n catch (e) { out.push(String(a)); }\n }\n return JSON.stringify(out);\n }\n function __call(level) {\n return function() {\n $0.applySync(undefined, [level, __ser.apply(null, arguments)]);\n };\n }\n globalThis.console = {\n log: __call('log'),\n info: __call('info'),\n warn: __call('warn'),\n error: __call('error'),\n debug: __call('debug'),\n trace: __call('trace'),\n dir: __call('dir'),\n dirxml: __call('dirxml'),\n table: __call('table'),\n group: __call('group'),\n groupCollapsed: __call('groupCollapsed'),\n groupEnd: __call('groupEnd'),\n time: __call('time'),\n timeEnd: __call('timeEnd'),\n timeLog: __call('timeLog'),\n assert: __call('assert'),\n count: __call('count'),\n countReset: __call('countReset'),\n clear: __call('clear')\n };\n ",[o]),o.release()}}class fn extends k{constructor(e){super(e,fn.name,500)}}class gn extends _{constructor(e){super(e),this.name=gn.name}}class mn extends _{constructor(e){super(e),this.name=mn.name}}class yn{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 fn(`Method declaration for kind '${this.kind}' is missing a name`);if(this.declarations.has(e.name))throw new fn(`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 fn(`Method implementation '${e}' for kind '${this.kind}' is not a function`);if(!this.declarations.has(e))throw new fn(`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 fn(`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 mn(`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 wn(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 bn(e,t,o){const n=wn(t,e.itemIdPath),r=e.itemLabelPath?wn(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 vn(e,t){switch(t){case"input":return e.inputs;case"output":return e.outputs;default:return e.connections}}function In(e,t){const o={inputs:[],outputs:[],connections:[]},n={input:new Set((e.inputs??[]).map(e=>e.id)),output:new Set((e.outputs??[]).map(e=>e.id)),connection:new Set((e.connections??[]).map(e=>e.id))},r=(e,t)=>{const o=n[e];return!o.has(t)&&(o.add(t),!0)};for(const n of e.dynamicPorts??[])if("repeatFromParameter"===n.type){const e=t[n.parameter];if(!Array.isArray(e))continue;const i=vn(o,n.direction);e.forEach((e,t)=>{const{id:o,label:a}=bn(n,e,t),s=(d={id:o,index:t,label:a??o},n.portIdTemplate.replaceAll("${id}",d.id).replaceAll("${index}",d.index+"").replaceAll("${label}",d.label));var d;if(!r(n.direction,s))return;const l=n.defaultPort?Fe(n.defaultPort):{id:s,label:a??s,direction:n.direction};l.id=s,l.direction=n.direction,a&&(l.label=a),i.push(l)})}else if("togglePort"===n.type){if(t[n.parameter]!==n.equals)continue;const e=Fe(n.port);if(!r(e.direction,e.id))continue;vn(o,e.direction).push(e)}return o}function En(e,t){const o=In(e,t),n={kind:e.kind,display:e.display,inputs:[...e.inputs,...o.inputs],outputs:[...e.outputs,...o.outputs],parameters:e.parameters},r=[...e.connections??[],...o.connections];return r.length&&(n.connections=r),e.dynamicPorts?.length&&(n.dynamicPorts=e.dynamicPorts),e.credentials?.length&&(n.credentials=e.credentials),e.capabilities?.length&&(n.capabilities=e.capabilities),e.policies&&(n.policies=e.policies),e.metadata&&(n.metadata=e.metadata),e.namespaces?.length&&(n.namespaces=e.namespaces),Fe(n)}class Nn{async resolve(e,t,o,n,r){if(o){const i=await o(n,r);if(!(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return"string"==typeof t.kind&&"object"==typeof t.display&&null!==t.display&&Array.isArray(t.inputs)&&Array.isArray(t.outputs)&&Array.isArray(t.parameters)})(i))throw new fn(`resolveManifest provider for kind '${e}' returned a value that does not conform to GraphResolvedNodeManifest`);if(!Ue(i))throw new fn(`resolveManifest provider for kind '${e}' returned a non-JSON-safe resolved manifest`);const a=Fe(i);return!a.namespaces?.length&&t.namespaces?.length&&(a.namespaces=t.namespaces.slice()),a}return En(t,n.parameters??{})}}const On=["edge","literal","expression"];function An(e){return On.includes(e)}function xn(e,t,o){if("string"!=typeof o||!o)throw new fn(`Manifest for kind '${e}' has a ${t} with an empty port id`);if(Le(o))throw new fn(`Manifest for kind '${e}' has a ${t} with unsafe port id '${o}'`)}let kn=class extends U{constructor(){super(),this.entries=new Map,this.resolver=new Nn,this.fallbackContext=new j}withContext(e){return e[e.length-1]instanceof j?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 fn("Graph node registration is required");if(!e.manifest||"object"!=typeof e.manifest)throw new fn("Graph node registration is missing a manifest");if(!e.executor||"function"!=typeof e.executor.execute)throw new fn(`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 fn("Graph node manifest kind is required and must be a non-empty string");const i=r.kind;if(this.entries.has(i)&&!t.replace)throw new fn(`Graph node kind '${i}' is already registered; pass { replace: true } to replace it`);try{mt(r)}catch(e){throw new fn(`Manifest for kind '${i}' is not JSON-serializable: ${e.message}`)}((e,t)=>{const o=[["input",t.inputs],["output",t.outputs],["connection",t.connections??[]]];for(const[t,n]of o){const o=new Set;for(const r of n){if(xn(e,t+" port",r?.id),o.has(r.id))throw new fn(`Manifest for kind '${e}' declares duplicate static ${t} port id '${r.id}'`);if(o.add(r.id),void 0!==r.defaultMode&&!An(r.defaultMode))throw new fn(`Manifest for kind '${e}' declares invalid default binding mode '${r.defaultMode+""}' on ${t} port '${r.id}'`)}}})(i,r);const a=((e,t)=>{const o=new Set;for(const n of t.parameters){const t=n?.id;if("string"!=typeof t||!t)throw new fn(`Manifest for kind '${e}' has a parameter with an empty id`);if(Le(t))throw new fn(`Manifest for kind '${e}' has a parameter with unsafe id '${t}'`);if(o.has(t))throw new fn(`Manifest for kind '${e}' declares duplicate parameter id '${t}'`);o.add(t)}return o})(i,r);((e,t,o)=>{for(const n of t.dynamicPorts??[]){if(!n||"string"!=typeof n.parameter||!n.parameter)throw new fn(`Manifest for kind '${e}' has a dynamic-port rule without a parameter reference`);if(!o.has(n.parameter))throw new fn(`Manifest for kind '${e}' has a dynamic-port rule referencing missing parameter '${n.parameter}'`);if("togglePort"===n.type){if(!n.port)throw new fn(`Manifest for kind '${e}' has a togglePort rule without a port`);xn(e,"togglePort rule port",n.port.id)}if("repeatFromParameter"===n.type&&"string"!=typeof n.portIdTemplate)throw new fn(`Manifest for kind '${e}' has a repeatFromParameter rule without a portIdTemplate`)}})(i,r,a),((e,t)=>{for(const o of t.credentials??[]){if(!ht(o))throw new fn(`Manifest for kind '${e}' has a malformed credential requirement`);if(!o.type)throw new fn(`Manifest for kind '${e}' has a credential requirement with an empty type`)}})(i,r),((e,t)=>{for(const o of t.methods??[])if(!wt(o))throw new fn(`Manifest for kind '${e}' has a malformed method declaration`)})(i,r);const s=new yn(i,r.methods??[],e.methods??{});return this.entries.set(i,{registration:e,methods:s,placeholderManifest:!1}),this}registerExecutor(e,t,...o){const{log:n}=this.logCtx(this.withContext(o),"registerExecutor").for(this.registerExecutor);if(n.debug(`Registering graph executor for kind '${e}'`),"string"!=typeof e||!e.trim())throw new fn("Graph executor kind is required");if(!t||"function"!=typeof t.execute)throw new fn(`Executor registered for kind '${e}' is missing an execute method`);const r=this.entries.get(e);if(r)return r.registration={...r.registration,executor:t},this;const i={kind:e,display:{name:e},inputs:[],outputs:[],parameters:[],policies:{allowUndeclaredParameters:!0,allowUnknownOutputs:!0}};return this.entries.set(e,{registration:{manifest:i,executor:t},methods:new yn(e,[],{}),placeholderManifest:!0}),this}unregister(e,...t){const{log:o}=this.logCtx(this.withContext(t),"unregister").for(this.unregister);return o.debug(`Unregistering graph node kind '${e}'`),this.entries.delete(e),this}has(e,...t){return this.logCtx(this.withContext(t),"has").for(this.has),this.entries.has(e)}entry(e){const t=this.entries.get(e);if(!t)throw new gn(`No graph node kind '${e}' is registered in the catalogue`);return t}getManifest(e,...t){return this.logCtx(this.withContext(t),"getManifest").for(this.getManifest),Fe(this.entry(e).registration.manifest)}getExecutor(e,...t){return this.logCtx(this.withContext(t),"getExecutor").for(this.getExecutor),this.entry(e).registration.executor}getMethodDeclaration(e,t,...o){return this.logCtx(this.withContext(o),"getMethodDeclaration").for(this.getMethodDeclaration),this.entry(e).methods.getDeclaration(t)}getMethod(e,t,...o){return this.logCtx(this.withContext(o),"getMethod").for(this.getMethod),this.entry(e).methods.getDeclaration(t),this.entry(e).methods.get(t)}listMethodDeclarations(e,...t){return this.logCtx(this.withContext(t),"listMethodDeclarations").for(this.listMethodDeclarations),this.entry(e).methods.list()}listManifests(e,...t){this.logCtx(this.withContext(t),"listManifests").for(this.listManifests);const o=[...this.entries.keys()].sort(),n=e?.categories?.length?new Set(e.categories):void 0,r=e?.kinds?.length?new Set(e.kinds):void 0,i=[];for(const e of o){if(r&&!r.has(e))continue;const o=this.getManifest(e,...t);n&&!n.has(o.display.category??"")||i.push(o)}return i}listKinds(...e){return this.logCtx(this.withContext(e),"listKinds").for(this.listKinds),[...this.entries.keys()].sort()}get size(){return this.entries.size}async resolveManifest(e,t,o,...n){this.logCtx(this.withContext(n),"resolveManifest").for(this.resolveManifest);const r=this.entry(e);return this.resolver.resolve(e,r.registration.manifest,r.registration.resolveManifest,t,o)}};kn=D([G(),$("design:paramtypes",[])],kn);let _n=class extends U{constructor(e=new kn){super(),this.catalogue=e}get catalog(){return this.catalogue}register(e,t,...o){const{log:n}=this.logCtx(o,"register").for(this.register);if(n.debug(`Registering graph executor for kind '${e}'`),!e)throw new Qt("Graph executor kind is required");return this.catalogue.registerExecutor(e,t,...o),this}unregister(e,...t){const{log:o}=this.logCtx(t,"unregister").for(this.unregister);return o.debug(`Unregistering graph executor for kind '${e}'`),this.catalogue.unregister(e,...t),this}has(e,...t){return this.logCtx(t,"has").for(this.has),this.catalogue.has(e,...t)}resolve(e,...t){this.logCtx(t,"resolve").for(this.resolve);try{return this.catalogue.getExecutor(e,...t)}catch(t){if(t instanceof gn)throw new Qt(`No graph executor registered for kind '${e}'`,"GRAPH_EXECUTOR_NOT_FOUND",{kind:e});throw t}}};_n=D([G(),$("design:paramtypes",[kn])],_n);let Dn=class extends U{constructor(e,t){super(),this.registry=e,this.defaultExecutor=t}resolve(e,...t){const{log:o}=this.logCtx(t,"resolve").for(this.resolve);return o.debug(`Resolving graph executor for kind '${e}'`),this.registry.has(e,...t)?this.registry.resolve(e,...t):this.defaultExecutor?this.defaultExecutor:this.registry.resolve(e,...t)}};function $n(e){return e}function Pn(e){return e.methods??[]}function Sn(e){if(!e)return;const t={...e.metadata??{},...e.parameters??{},...e.state??{}};return e.loop&&(t.loop=e.loop),t}Dn=D([G(),$("design:paramtypes",[Function,Object])],Dn);class Rn extends w{constructor(e){super(),w.fromModel(this,e)}execute(e,t){throw new Qt(`Graph node kind '${this.constructor.name}' does not implement execute`,"GRAPH_NODE_EXECUTE_NOT_IMPLEMENTED",{kind:this.constructor.name})}static applyMetadata(e){return null}static instantiate(e){return new this(e)}}let Cn=class extends Rn{execute(e,t){throw new ao(e.inputs.value)}};function Tn(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+""}}D([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.break.fields.value.label",placeholder:"graph.node.flow_control.break.fields.value.placeholder",type:"textarea"}),Se({handle:"value"}),$("design:type",Object)],Cn.prototype,"value",void 0),Cn=D([$e("core.flow.break",{kind:"core.flow.break",category:"Flow Control",color:"#f59e0b",icon:"ti-square-arrow-right",width:96,height:96,labels:["flow","break","loop","control"],metadata:{title:"graph.node.flow_control.break.name",description:"graph.node.flow_control.break.description"}}),E()],Cn);let Ln=class extends Rn{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 Qt("errorBoundary node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");try{const r=await n.execute(o.try,e.inputs,{parentRunId:t.runId,path:[...t.path,"try"]}),i=Object.values(r.nodeResults).find(e=>e.status===se.FAILED);if(i)throw new Qt(i.error?.message??"error boundary try body failed",i.error?.code??"GRAPH_ERROR_BOUNDARY",i.error?.details);return{result:r.outputs.result??r.outputs}}catch(r){let i=r;if(o.catch){const a=await n.execute(o.catch,{...e.inputs,error:Tn(r)},{parentRunId:t.runId,path:[...t.path,"catch"]});i=a.outputs.error??a.outputs}return{error:i}}finally{o.finally&&await n.execute(o.finally,e.inputs,{parentRunId:t.runId,path:[...t.path,"finally"]})}}};D([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.error_boundary.fields.value.label",placeholder:"graph.node.flow_control.error_boundary.fields.value.placeholder",type:"textarea"}),Se({handle:"value"}),$("design:type",Object)],Ln.prototype,"value",void 0),D([Re({handle:"result"}),$("design:type",Object)],Ln.prototype,"result",void 0),D([Re({handle:"error"}),$("design:type",Object)],Ln.prototype,"error",void 0),Ln=D([$e("core.flow.errorBoundary",{kind:"core.flow.errorBoundary",category:"Flow Control",color:"#f59e0b",icon:"ti-shield-check",width:96,height:96,labels:["flow","error","try-catch"],metadata:{title:"graph.node.flow_control.error_boundary.name",description:"graph.node.flow_control.error_boundary.description",finally:!1}}),E()],Ln);let jn=class extends Rn{execute(e){const t=e.inputs.value??e.inputs;return!1===this.approved?{rejected:t}:{approved:t}}};D([b(),Se({handle:"value"}),$("design:type",Object)],jn.prototype,"value",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.human_approval.fields.message.label",placeholder:"graph.node.flow_control.human_approval.fields.message.placeholder",type:"textarea"}),Se({handle:"message",userControlled:!0}),$("design:type",String)],jn.prototype,"message",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.human_approval.fields.approved.label",type:"checkbox"}),Se({handle:"approved",userControlled:!0}),$("design:type",Boolean)],jn.prototype,"approved",void 0),D([Re({handle:"approved"}),$("design:type",Object)],jn.prototype,"approvedOut",void 0),D([Re({handle:"rejected"}),$("design:type",Object)],jn.prototype,"rejectedOut",void 0),jn=D([$e("core.flow.humanApproval",{kind:"core.flow.humanApproval",category:"Flow Control",color:"#f59e0b",icon:"ti-user-check",width:96,height:96,labels:["flow","approval","suspend"],metadata:{title:"graph.node.flow_control.human_approval.name",description:"graph.node.flow_control.human_approval.description",approvers:[],timeoutMs:864e5}}),E()],jn);class Mn{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 Qt(`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 Qt("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 Gn(e){return"object"==typeof e&&null!==e&&"type"in e&&"code"===e.type}function Un(e){return"object"==typeof e&&null!==e&&"op"in e&&"string"==typeof e.op}async function Fn(e,t,o){const n=o.engine?.codeSandboxEvaluator;if(!n)throw new Qt("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 Bn(e,t,o){if(Un(e))return(new Mn).evaluate(e,t);throw((e,t)=>new Qt(`Unknown ${t??"flow"} condition type \u2014 must be ConditionExpression (op) or CodeCondition (type: 'code')`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition:e}))(e,o)}async function qn(e,t,o){return Gn(e)?Fn(e,t.input,o):Bn(e,t.state,t.label)}let Wn=class extends Rn{execute(e,t){const o=e.inputs,n=o.value??o;if(!this.condition)throw new Qt("If node has no condition configured","GRAPH_IF_NO_CONDITION",{input:o});if(Gn(this.condition))return Fn(this.condition,o,t).then(e=>this.route(e,n));const r=Bn(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 Qt("If node condition evaluated to false and the else branch is disabled","GRAPH_IF_ELSE_DISABLED",{condition:this.condition})}};D([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.value.label",placeholder:"graph.node.flow_control.if.fields.value.placeholder",type:"textarea"}),Se({handle:"value"}),$("design:type",Object)],Wn.prototype,"value",void 0),D([b(),Re({handle:"then"}),$("design:type",Object)],Wn.prototype,"then",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.condition.label",placeholder:"graph.node.flow_control.if.fields.condition.placeholder",type:"code"}),Se({handle:"condition",userControlled:!0,type:"object"}),$("design:type",Object)],Wn.prototype,"condition",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.if.fields.else.label",type:"checkbox"}),Se({handle:"else",userControlled:!0}),$("design:type",Boolean)],Wn.prototype,"else",void 0),Wn=D([$e("core.flow.if",{kind:"core.flow.if",category:"Flow Control",color:"#f59e0b",icon:"ti-arrows-split-2",width:96,height:96,labels:["flow","conditional","branch"],metadata:{title:"graph.node.flow_control.if.name",description:"graph.node.flow_control.if.description"}}),E()],Wn);let Vn=class extends Rn{async execute(e,t){const o=((e,t)=>{const o={cases:t.cases??[],defaultPort:t.defaultPort??"default",hasDefault:!0===t.hasDefault},n=e.node.metadata?.switch;return n&&Array.isArray(n.cases)?{cases:n.cases,defaultPort:n.defaultPort??o.defaultPort,hasDefault:!0===n.hasDefault||o.hasDefault}:o})(t,this),n=o.cases,r=e.inputs,i=r.value??r,a=((e,t)=>t===e||"object"!=typeof t||null===t||Array.isArray(t)?e:{...t,...e})(r,i);for(const e of n)if(await qn(e.condition,{input:r,state:a,label:"switch case"},t))return{[e.outputPort]:i};if(!0!==o.hasDefault)throw new Qt("No switch case matched and default port is not enabled","GRAPH_SWITCH_NO_MATCH",{cases:n.map(e=>e.id)});const s=o.defaultPort??"default";return{[s]:i}}static applyMetadata(e){const t=ke(this),o=e.defaultPort??"default",n=!0===e.hasDefault,r=t.ports.filter(t=>!e.cases.some(e=>e.outputPort===t.property)),i=r.filter(e=>e.property!==o),a=r.find(e=>e.property===o),s=[...i,...e.cases.map(e=>({property:e.outputPort,name:e.label,direction:Z.OUTPUT,label:e.label,required:!1,hidden:!1,path:e.outputPort}))];return n&&a&&s.push(a),{ports:s,size:te(t,{cases:e.cases.length}),dataPatch:{switchMetadata:e}}}};D([b(),i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.value.label",placeholder:"graph.node.flow_control.switch.fields.value.placeholder",type:"textarea"}),Se({handle:"value"}),$("design:type",Object)],Vn.prototype,"value",void 0),D([b(),Re({handle:"default"}),$("design:type",Object)],Vn.prototype,"default",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.cases.label",type:"collection"}),$("design:type",Object)],Vn.prototype,"cases",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.hasDefault.label",type:"checkbox"}),$("design:type",Boolean)],Vn.prototype,"hasDefault",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.flow_control.switch.fields.defaultPort.label",type:"text"}),$("design:type",String)],Vn.prototype,"defaultPort",void 0),Vn=D([$e("core.flow.switch",{kind:"core.flow.switch",category:"Flow Control",color:"#f59e0b",icon:"ti-arrows-shuffle",width:120,height:140,sizeRules:[{type:"parameterCount",parameter:"cases",dimension:"height",perItem:24}],labels:["flow","switch","multi-branch"],metadata:{title:"graph.node.flow_control.switch.name",description:"graph.node.flow_control.switch.description"}}),E()],Vn);const Hn={maxDocumentBytes:2e6,maxNestingDepth:10,maxNodes:500,maxEdges:1e3},Kn=o.accumulate({graph:{workflows:{limits:{...Hn},allowAnonymousAccess:!1},execution:{maxCodeTimeoutMs:Kt}}}),zn=1e3;function Jn(e,t){const o="number"==typeof e?e:Number(e);return Number.isFinite(o)&&o>0?Math.min(Math.floor(o),t):1e3}const Xn=["javascript","typescript"],Yn="javascript";let Qn=class extends w{constructor(){super(...arguments),this.language=Yn}};D([b(),i("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.language.label",type:"select"}),N([...Xn]),v(String),$("design:type",String)],Qn.prototype,"language",void 0),D([b(),i("code-editor",{label:"graph.node.utility.code.fields.code.label",placeholder:"graph.node.utility.code.fields.code.placeholder"}),Se({handle:"code"}),$("design:type",String)],Qn.prototype,"code",void 0),D([d(),Se({handle:"data"}),$("design:type",Object)],Qn.prototype,"data",void 0),Qn=D([E()],Qn);let Zn=class extends Rn{async execute(e,t){const o=e.inputs,n=this.input,r=o.code??e.parameters?.code??n?.code??this.defaultCode,i=n?.language??Yn;if(!r||"string"!=typeof r||0===r.trim().length)throw new eo("Code node has no code to execute (input.code is empty)",{input:o});const a=t.engine?.codeSandboxEvaluator;if(!a)throw new Qt("Code node execution requires a CodeSandboxEvaluator to be registered in GraphExecutionEngineConfig.codeSandboxEvaluator","GRAPH_CODE_SANDBOX_NOT_CONFIGURED",{code:r});const s=Kn.graph.execution?.maxCodeTimeoutMs??Kt,d=Jn(this.timeoutMs,s),l=t.metadata,c={code:r,language:i,input:o,vars:l?.vars??void 0,item:l?.item,index:l?.index,nodes:l?.nodes??void 0,logger:t.logger,timeoutMs:d,abortSignal:t.abortSignal};await t.log("Executing code node",{language:i,length:r.length,timeoutMs:d});const u=await a.evaluate(c);return await t.log("Code node executed",{hasResult:void 0!==u}),{result:u}}};D([b(),Se({handle:"input",model:Qn}),$("design:type",Qn)],Zn.prototype,"input",void 0),D([O(1),A(Kt),i("ngx-decaf-crud-field",{label:"graph.node.utility.code.fields.timeoutMs.label",type:"number"}),Se({handle:"timeoutMs"}),$("design:type",Number)],Zn.prototype,"timeoutMs",void 0),D([i("code-editor",{label:"graph.node.utility.code.fields.defaultCode.label",placeholder:"graph.node.utility.code.fields.defaultCode.placeholder"}),Se({handle:"defaultCode",userControlled:!0}),$("design:type",String)],Zn.prototype,"defaultCode",void 0),D([b(),Re({handle:"result"}),$("design:type",Object)],Zn.prototype,"result",void 0),Zn=D([$e("core.utility.code",{kind:"core.utility.code",category:"Utility",color:"#0d9488",icon:"ti-code",width:96,height:96,labels:["utility","code","sandbox","transform"],metadata:{title:"graph.node.utility.code.name",description:"graph.node.utility.code.description"}}),E()],Zn);let er=class extends Rn{execute(e){return{value:e.inputs.value??e.inputs}}};D([b(),Se({handle:"value"}),$("design:type",Object)],er.prototype,"value",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.utility.delay.fields.timeoutMs.label",type:"number"}),Se({handle:"timeoutMs"}),$("design:type",Number)],er.prototype,"timeoutMs",void 0),D([b(),Re({handle:"value"}),$("design:type",Object)],er.prototype,"valueOut",void 0),er=D([$e("core.flow.delay",{kind:"core.flow.delay",category:"Utility",color:"#0d9488",icon:"ti-clock-hour-4",width:96,height:96,labels:["flow","delay","wait"],metadata:{title:"graph.node.utility.delay.name",description:"graph.node.utility.delay.description"}}),E()],er);let tr=class extends Rn{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}};D([b(),Se({handle:"value"}),$("design:type",Object)],tr.prototype,"value",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.message.label",placeholder:"graph.node.utility.log.fields.message.placeholder",type:"textarea"}),Se({handle:"message"}),$("design:type",String)],tr.prototype,"message",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.utility.log.fields.level.label",placeholder:"graph.node.utility.log.fields.level.placeholder",type:"text"}),Se({handle:"level",userControlled:!0}),$("design:type",String)],tr.prototype,"level",void 0),D([b(),Re({handle:"value"}),$("design:type",Object)],tr.prototype,"valueOut",void 0),tr=D([$e("core.flow.log",{kind:"core.flow.log",category:"Utility",color:"#0d9488",icon:"ti-terminal",width:96,height:96,labels:["flow","log","debug","utility"],metadata:{title:"graph.node.utility.log.name",description:"graph.node.utility.log.description"}}),E()],tr);let or=class extends Rn{execute(e){return{result:{mapped:e.inputs.value??e.inputs}}}};D([b(),i("ngx-decaf-crud-field",{label:"graph.node.utility.map.fields.value.label",placeholder:"graph.node.utility.map.fields.value.placeholder",type:"textarea"}),Se({handle:"value"}),$("design:type",Object)],or.prototype,"value",void 0),D([b(),Re({handle:"result"}),$("design:type",Object)],or.prototype,"result",void 0),or=D([$e("core.utility.map",{kind:"core.utility.map",category:"Utility",color:"#0d9488",icon:"ti-arrows-right-left",width:96,height:96,labels:["utility","map","transform"],metadata:{title:"graph.node.utility.map.name",description:"graph.node.utility.map.description",mapper:{}}}),E()],or);let nr=class extends Rn{execute(e,t){const o=e.inputs.value,n=this.level??"info";return t.logger[n](this.message??"Log node",{value:o}),{value:o}}};D([b(),Se({handle:"value"}),$("design:type",Object)],nr.prototype,"value",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.message.label",placeholder:"graph.node.utility.utility_log.fields.message.placeholder",type:"textarea"}),Se({handle:"message"}),$("design:type",String)],nr.prototype,"message",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.utility.utility_log.fields.level.label",placeholder:"graph.node.utility.utility_log.fields.level.placeholder"}),Se({handle:"level",userControlled:!0,type:"string"}),$("design:type",String)],nr.prototype,"level",void 0),D([b(),Re({handle:"value"}),$("design:type",Object)],nr.prototype,"valueOut",void 0),nr=D([$e("core.utility.log",{kind:"core.utility.log",category:"Utility",color:"#0d9488",icon:"ti-terminal",width:96,height:96,labels:["utility","log","debug","observability"],metadata:{title:"graph.node.utility.utility_log.name",description:"graph.node.utility.utility_log.description"}}),E()],nr);let rr=class extends Rn{execute(e){return{message:e.inputs.message??null,sessionId:e.inputs.sessionId??null,userId:e.inputs.userId??null}}};D([b(),Re({handle:"message"}),$("design:type",String)],rr.prototype,"message",void 0),D([b(),Re({handle:"sessionId"}),$("design:type",String)],rr.prototype,"sessionId",void 0),D([b(),Re({handle:"userId"}),$("design:type",String)],rr.prototype,"userId",void 0),rr=D([$e("core.trigger.chat",{kind:"core.trigger.chat",category:"Trigger",color:"#3b82f6",icon:"ti-message-circle",width:96,height:96,labels:["trigger","chat","entrypoint"],metadata:{title:"graph.node.trigger.chat.name",description:"graph.node.trigger.chat.description",trigger:{type:"chat"}}}),E()],rr);let ir=class extends Rn{execute(e){return{payload:e.inputs.payload??null}}};D([b(),Re({handle:"payload"}),$("design:type",Object)],ir.prototype,"payload",void 0),ir=D([$e("core.trigger.event",{kind:"core.trigger.event",category:"Trigger",color:"#3b82f6",icon:"ti-broadcast",width:96,height:96,labels:["trigger","event","bus"],metadata:{title:"graph.node.trigger.event.name",description:"graph.node.trigger.event.description",trigger:{type:"event",topic:"default"}}}),E()],ir);let ar=class extends Rn{execute(e){return{payload:e.inputs.payload??null}}};D([b(),Se({handle:"schema"}),i("ngx-decaf-model-builder",{label:"graph.node.trigger.form.fields.schema.label",placeholder:"graph.node.trigger.form.fields.schema.placeholder"}),$("design:type",Object)],ar.prototype,"schema",void 0),D([b(),Re({handle:"payload"}),$("design:type",Object)],ar.prototype,"payload",void 0),ar=D([$e("core.trigger.form",{kind:"core.trigger.form",category:"Trigger",color:"#3b82f6",icon:"ti-forms",width:96,height:96,labels:["trigger","form","public"],metadata:{title:"graph.node.trigger.form.name",description:"graph.node.trigger.form.description",trigger:{type:"form",fields:[]}}}),E()],ar);let sr=class extends Rn{execute(e){return{payload:e.inputs.payload??null}}};D([b(),Re({handle:"payload"}),$("design:type",Object)],sr.prototype,"payload",void 0),sr=D([$e("core.trigger.manual",{kind:"core.trigger.manual",category:"Trigger",color:"#3b82f6",icon:"ti-hand-click",width:96,height:96,labels:["trigger","manual","entrypoint"],metadata:{title:"graph.node.trigger.manual.name",description:"graph.node.trigger.manual.description",trigger:{type:"manual",inputSchema:{}}}}),E()],sr);let dr=class extends Rn{execute(e){return{payload:e.inputs.payload??null}}};D([b(),Se({handle:"cron"}),i("app-cron-selector-field",{label:"graph.node.trigger.schedule.fields.cron.label",placeholder:"graph.node.trigger.schedule.fields.cron.placeholder"}),$("design:type",String)],dr.prototype,"cron",void 0),D([b(),Re({handle:"payload"}),$("design:type",Object)],dr.prototype,"payload",void 0),dr=D([$e("core.trigger.schedule",{kind:"core.trigger.schedule",category:"Trigger",color:"#3b82f6",icon:"ti-calendar-time",width:96,height:96,labels:["trigger","schedule","cron"],metadata:{title:"graph.node.trigger.schedule.name",description:"graph.node.trigger.schedule.description",trigger:{type:"schedule",schedule:"0 * * * *",timezone:"UTC"}}}),E()],dr);let lr=class extends Rn{execute(e){return{payload:e.inputs.payload??null}}};D([b(),Se({handle:"schema"}),i("ngx-decaf-model-builder",{label:"graph.node.trigger.webhook.fields.schema.label",placeholder:"graph.node.trigger.webhook.fields.schema.placeholder"}),$("design:type",Object)],lr.prototype,"schema",void 0),D([b(),Re({handle:"payload"}),$("design:type",Object)],lr.prototype,"payload",void 0),lr=D([$e("core.trigger.webhook",{kind:"core.trigger.webhook",category:"Trigger",color:"#3b82f6",icon:"ti-webhook",width:96,height:96,labels:["trigger","webhook","http"],metadata:{title:"graph.node.trigger.webhook.name",description:"graph.node.trigger.webhook.description",trigger:{type:"webhook",path:"/webhook",method:"POST",auth:"none",responseMode:"onReceived"}}}),E()],lr);let cr=class extends Rn{execute(e){return{response:"[Agent response] "+(e.inputs.prompt??""),actions:[]}}};D([b(),i("ngx-decaf-crud-field",{label:"graph.node.agent.agent.fields.prompt.label",placeholder:"graph.node.agent.agent.fields.prompt.placeholder",type:"textarea"}),Se({handle:"prompt"}),$("design:type",String)],cr.prototype,"prompt",void 0),D([b(),Re({handle:"response"}),$("design:type",String)],cr.prototype,"response",void 0),D([b(),Re({handle:"actions"}),$("design:type",Array)],cr.prototype,"actions",void 0),D([Ce({category:"model",handle:"model"}),$("design:type",Object)],cr.prototype,"model",void 0),D([Ce({category:"memory",handle:"memory"}),$("design:type",Object)],cr.prototype,"memory",void 0),D([Ce({category:"workspace",handle:"workspace"}),$("design:type",Object)],cr.prototype,"workspace",void 0),cr=D([$e("core.agent",{kind:"core.agent",category:"Agent",width:140,height:120,labels:["agent","ai","orchestrator"],metadata:{title:"graph.node.agent.agent.name",description:"graph.node.agent.agent.description",shape:"rectangle"}}),E()],cr);const ur=[cr];function pr(e,t,o,n){const r=t??o;if(null==e)return Math.min(o,r);const i=Number(e);if(!Number.isFinite(i)||0>=i)throw new eo(n+" loop maxIterations must be a positive finite number");return Math.min(Math.floor(i),r)}function hr(e,t,o){const n=t.node.loop,r=t.metadata?.loop;if(!n?.body&&!r?.body)throw new eo(o+" node is missing loop configuration (instance.loop.body)");const i=t=>{const o=e[t]??n?.[t]??r?.[t],i=Number(o);return void 0!==o&&Number.isFinite(i)?i:void 0},a=t=>{const o=e[t]??r?.[t];return"string"==typeof o?o:void 0};return{body:n?.body??r?.body,maxIterations:i("maxIterations"),timeoutMs:i("timeoutMs"),concurrency:i("concurrency"),condition:e.condition??r?.condition,inputPort:a("inputPort"),outputPort:a("outputPort"),itemPort:a("itemPort"),resultPort:a("resultPort"),statePort:a("statePort"),slice:i("slice")}}let fr=class extends Rn{async execute(e,t){const o=hr(this,t,"foreach"),n=e.inputs,r=n.items,i=pr(o.maxIterations,t.limits?.maxForeachIterations,1e3,"foreach");if(!Array.isArray(r))throw new eo("foreach input 'items' must be an array");const a=t.engine;if(!a)throw new Qt("foreach node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");const s=Number(n.slice??o.slice??1),d=Number.isFinite(s)&&s>0?Math.floor(s):1,l=d>1?Math.ceil(r.length/d):r.length;if(l>i)throw new to(`foreach exceeded max iterations (${l} > ${i})`);const c=o.itemPort??"item",u=o.resultPort??"result",p=o.statePort??"state",h=o.body,f=[];let g=n.state,m=!1;await t.emit({type:ce.LOOP_STARTED});for(let e=0;l>e;e++){await t.emit({type:ce.LOOP_ITERATION_STARTED,iteration:e});const o=d>1?r.slice(e*d,e*d+d):r[e],n={[c]:o,index:e};d>1&&(n.slice=o),void 0!==g&&(n[p]=g);try{const r=await a.execute(h,n,{parentRunId:t.runId,path:[...t.path,"iteration:"+e],metadata:{item:o,index:e,slice:d},auth:t.auth},t);f.push(r.outputs[u]),void 0!==r.outputs[p]&&(g=r.outputs[p])}catch(o){if(o instanceof ao){const n=o.details?.value;void 0!==n&&f.push(n),m=!0,await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:e,metadata:{broken:!0}});break}throw o}await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:e})}await t.emit({type:ce.LOOP_COMPLETED,metadata:{broken:m}});const y={results:f,completed:f,iterations:f.length,broken:m};return void 0!==g&&(y[p]=g),y}};D([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.items.label",placeholder:"graph.node.loop.foreach.fields.items.placeholder",type:"textarea"}),Se({handle:"items"}),$("design:type",Array)],fr.prototype,"items",void 0),D([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.slice.label",placeholder:"graph.node.loop.foreach.fields.slice.placeholder",type:"number"}),Se({handle:"slice"}),$("design:type",Number)],fr.prototype,"slice",void 0),D([b(),Re({handle:"item"}),$("design:type",Object)],fr.prototype,"item",void 0),D([b(),Ce({handle:"loop",connectionRules:{allowSelf:!0,maxConnections:1}}),$("design:type",Object)],fr.prototype,"loop",void 0),D([b(),Re({handle:"completed"}),$("design:type",Array)],fr.prototype,"completed",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.maxIterations.label",type:"number"}),Se({handle:"maxIterations",userControlled:!0}),$("design:type",Number)],fr.prototype,"maxIterations",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.condition.label",type:"code"}),Se({handle:"condition",userControlled:!0}),$("design:type",Object)],fr.prototype,"condition",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.itemPort.label",type:"text"}),Se({handle:"itemPort",userControlled:!0}),$("design:type",String)],fr.prototype,"itemPort",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.resultPort.label",type:"text"}),Se({handle:"resultPort",userControlled:!0}),$("design:type",String)],fr.prototype,"resultPort",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.foreach.fields.statePort.label",type:"text"}),Se({handle:"statePort",userControlled:!0}),$("design:type",String)],fr.prototype,"statePort",void 0),fr=D([$e("graph-foreach-loop-node",{kind:"core.loop.foreach",category:"Loop",color:"#eab308",icon:"ti-repeat",width:120,height:140,labels:["loop","iteration","foreach"],metadata:{title:"graph.node.loop.foreach.name",description:"graph.node.loop.foreach.description",loop:{maxIterations:100,itemPort:"item",resultPort:"result",slice:1}}}),E()],fr);class gr{constructor(){this.expressionEvaluator=new Mn}evaluate(e,t){if(this.isConditionExpression(e))return this.expressionEvaluator.evaluate(e,t);const o=this.resolveValue(e.left,t),n=e.right;switch(e.type){case Xt.TRUTHY:return!!o;case Xt.FALSY:return!o;case Xt.EQUALS:return o===n;case Xt.NOT_EQUALS:return o!==n;case Xt.GREATER_THAN:return Number(o)>Number(n);case Xt.GREATER_THAN_OR_EQUAL:return Number(o)>=Number(n);case Xt.LESS_THAN:return Number(n)>Number(o);case Xt.LESS_THAN_OR_EQUAL:return Number(n)>=Number(o);case Xt.EXISTS:return null!=o;case Xt.CUSTOM:throw new Qt("Custom condition evaluators are not supported in v1","GRAPH_CUSTOM_CONDITION_UNSUPPORTED");default:throw new Qt(`Unknown condition type '${e.type}'`,"GRAPH_UNKNOWN_CONDITION_TYPE",{condition:e})}}async evaluateAsync(e,t,o,n){return Gn(e)?Fn(e,n,o):this.evaluate(e,t)}resolveValue(e,t){if(!e)return t;const o=e.split(".");let n=t;for(const e of o){if(null==n)return;n=n[e]}return n}isConditionExpression(e){return"string"==typeof e.op}}let mr=class extends Rn{async execute(e,t){const o=hr(this,t,"until"),n=e.inputs,r=pr(o.maxIterations,t.limits?.maxLoopIterations,100,"until"),i=o.condition;if(!i)throw new eo("until node is missing a condition");const a=o.statePort??"state",s=o.inputPort??a,d=o.outputPort??a,l=o.body,c=t.engine;if(!c)throw new Qt("until node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;await t.emit({type:ce.LOOP_STARTED});let h=!1;do{if(p>=r)throw await t.emit({type:ce.LOOP_LIMIT_REACHED,iteration:p}),new to(`until loop exceeded max iterations (${r})`);await t.emit({type:ce.LOOP_ITERATION_STARTED,iteration:p}),u=(await c.execute(l,{[s]:u,iteration:p},{parentRunId:t.runId,path:[...t.path,"iteration:"+p],auth:t.auth},t)).outputs[d],await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:p});const e=await(new gr).evaluateAsync(i,u,t,{...n,state:u});await t.emit({type:ce.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:e}}),p++,h=e}while(!h);return await t.emit({type:ce.LOOP_COMPLETED}),{state:u,iterations:p}}};D([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.state.label",placeholder:"graph.node.loop.until.fields.state.placeholder",type:"textarea"}),Se({handle:"state"}),$("design:type",Object)],mr.prototype,"state",void 0),D([b(),Re({handle:"state"}),$("design:type",Object)],mr.prototype,"stateOut",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.maxIterations.label",type:"number"}),Se({handle:"maxIterations",userControlled:!0}),$("design:type",Number)],mr.prototype,"maxIterations",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.condition.label",type:"code"}),Se({handle:"condition",userControlled:!0}),$("design:type",Object)],mr.prototype,"condition",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.statePort.label",type:"text"}),Se({handle:"statePort",userControlled:!0}),$("design:type",String)],mr.prototype,"statePort",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.inputPort.label",type:"text"}),Se({handle:"inputPort",userControlled:!0}),$("design:type",String)],mr.prototype,"inputPort",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.until.fields.outputPort.label",type:"text"}),Se({handle:"outputPort",userControlled:!0}),$("design:type",String)],mr.prototype,"outputPort",void 0),mr=D([$e("graph-until-loop-node",{kind:"core.loop.until",category:"Loop",color:"#eab308",icon:"ti-player-stop",width:96,height:96,labels:["loop","conditional","until"],metadata:{title:"graph.node.loop.until.name",description:"graph.node.loop.until.description",loop:{maxIterations:50,statePort:"state",condition:{type:"greaterThanOrEqual",left:"iteration",right:2}}}}),E()],mr);let yr=class extends Rn{async execute(e,t){const o=hr(this,t,"while"),n=e.inputs,r=pr(o.maxIterations,t.limits?.maxLoopIterations,100,"while"),i=o.condition;if(!i)throw new eo("while node is missing a condition");const a=o.statePort??"state",s=o.inputPort??a,d=o.outputPort??a,l=o.body,c=t.engine;if(!c)throw new Qt("while node requires engine access","GRAPH_ENGINE_NOT_AVAILABLE");let u=n.state,p=0;for(await t.emit({type:ce.LOOP_STARTED});await(new gr).evaluateAsync(i,u,t,{...n,state:u});){if(p>=r)throw await t.emit({type:ce.LOOP_LIMIT_REACHED,iteration:p}),new to(`while loop exceeded max iterations (${r})`);await t.emit({type:ce.LOOP_CONDITION_EVALUATED,iteration:p,payload:{result:!0}}),await t.emit({type:ce.LOOP_ITERATION_STARTED,iteration:p}),u=(await c.execute(l,{[s]:u,iteration:p},{parentRunId:t.runId,path:[...t.path,"iteration:"+p],auth:t.auth},t)).outputs[d],await t.emit({type:ce.LOOP_ITERATION_COMPLETED,iteration:p}),p++}return await t.emit({type:ce.LOOP_COMPLETED}),{state:u,iterations:p}}};D([b(),i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.state.label",placeholder:"graph.node.loop.while.fields.state.placeholder",type:"textarea"}),Se({handle:"state"}),$("design:type",Object)],yr.prototype,"state",void 0),D([b(),Re({handle:"state"}),$("design:type",Object)],yr.prototype,"stateOut",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.maxIterations.label",type:"number"}),Se({handle:"maxIterations",userControlled:!0}),$("design:type",Number)],yr.prototype,"maxIterations",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.condition.label",type:"code"}),Se({handle:"condition",userControlled:!0}),$("design:type",Object)],yr.prototype,"condition",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.statePort.label",type:"text"}),Se({handle:"statePort",userControlled:!0}),$("design:type",String)],yr.prototype,"statePort",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.inputPort.label",type:"text"}),Se({handle:"inputPort",userControlled:!0}),$("design:type",String)],yr.prototype,"inputPort",void 0),D([i("ngx-decaf-crud-field",{label:"graph.node.loop.while.fields.outputPort.label",type:"text"}),Se({handle:"outputPort",userControlled:!0}),$("design:type",String)],yr.prototype,"outputPort",void 0),yr=D([$e("graph-while-loop-node",{kind:"core.loop.while",category:"Loop",color:"#eab308",icon:"ti-arrows-loop",width:96,height:96,labels:["loop","conditional","while"],metadata:{title:"graph.node.loop.while.name",description:"graph.node.loop.while.description",loop:{maxIterations:50,statePort:"state",condition:{type:"lessThan",left:"iteration",right:3}}}}),E()],yr);let wr=class extends Rn{execute(e){const t=e.inputs;return{value:t?.value??null}}};D([Re({handle:"value",connectionRules:{allowMultiple:!0}}),$("design:type",Object)],wr.prototype,"value",void 0),wr=D([$e("graph-input-value-node",{kind:"value",category:"Boundary",color:"#0f766e",icon:"ti-circle-plus",labels:["workflow","input","value"],metadata:{title:"graph.node.boundary.input.name",description:"graph.node.boundary.input.description"}}),E()],wr);let br=class extends Rn{execute(e){return{}}};function vr(e,t,o,n={}){return{id:e,label:t,direction:o,...n}}function Ir(e){const t=e,o=ve(t),n=o?.metadata?.title;return Tt(t,n?{name:n}:{})}D([b(),Se({handle:"value"}),$("design:type",Object)],br.prototype,"value",void 0),br=D([$e("graph-output-value-node",{kind:"result",category:"Boundary",color:"#0f766e",icon:"ti-circle-minus",width:96,height:96,labels:["workflow","output","value"],metadata:{title:"graph.node.boundary.output.name",description:"graph.node.boundary.output.description"}}),E()],br);const Er={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:[vr("items","graph.node.loop.foreach.ports.input.items.label","input",{required:!0,schema:{type:"array",items:{type:"any"}}}),vr("slice","graph.node.loop.foreach.ports.input.slice.label","input",{schema:{type:"number",integer:!0,min:1}}),vr("state","graph.node.loop.foreach.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[vr("results","graph.node.loop.foreach.ports.output.results.label","output",{schema:{type:"array",items:{type:"any"}}}),vr("completed","graph.node.loop.foreach.ports.output.completed.label","output",{schema:{type:"array",items:{type:"any"}}}),vr("iterations","graph.node.loop.foreach.ports.output.iterations.label","output",{schema:{type:"number",integer:!0,min:0}}),vr("broken","graph.node.loop.foreach.ports.output.broken.label","output",{schema:{type:"boolean"}}),vr("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}]},Nr={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:[vr("state","graph.node.loop.while.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[vr("state","graph.node.loop.while.ports.output.state.label","output",{schema:{type:"any"}}),vr("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"}]},Or={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:[vr("state","graph.node.loop.until.ports.input.state.label","input",{schema:{type:"any"}})],outputs:[vr("state","graph.node.loop.until.ports.output.state.label","output",{schema:{type:"any"}}),vr("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"}]},Ar=[Ir(wr),Ir(br),Ir(sr),Ir(lr),Ir(dr),Ir(ir),Ir(ar),Ir(rr),(xr=Ir(Wn),{...xr,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"}}}]}))(Ir(Vn)),Ir(or),Ir(er),Ir(Ln),Ir(jn),Ir(Zn),Ir(tr),Ir(nr),Ir(Cn),Ir(cr),Er,Nr,Or];var xr;const kr=Object.fromEntries(Ar.map(e=>[e.kind,e])),_r=[sr,lr,dr,ir,ar,rr],Dr=[Wn,Vn,er,Ln,jn,tr,Cn],$r=[Zn,or,nr],Pr=[fr,yr,mr],Sr=[wr,br],Rr={value:wr,result:br,"core.trigger.manual":sr,"core.trigger.webhook":lr,"core.trigger.schedule":dr,"core.trigger.event":ir,"core.trigger.form":ar,"core.trigger.chat":rr,"core.flow.if":Wn,"core.flow.switch":Vn,"core.utility.map":or,"core.flow.delay":er,"core.flow.errorBoundary":Ln,"core.flow.humanApproval":jn,"core.utility.code":Zn,"core.flow.log":tr,"core.utility.log":nr,"core.flow.break":Cn,"core.agent":cr,"core.loop.foreach":fr,"core.loop.while":yr,"core.loop.until":mr};function Cr(e){return{execute:(t,o)=>e.instantiate({...Sn(o.node),...t.parameters,...o.node.state??{}}).execute(t,o)}}function Tr(){const e=[];for(const[t,o]of Object.entries(kr)){const n=Rr[t];n&&e.push($n({manifest:o,executor:Cr(n)}))}return e}function Lr(e,...t){for(const o of Tr())e.register(o,{},...t);return e}class jr{resolve(e){const t=this.createValidator(e);return{name:e.name,required:e.required,validate:t}}resolveAll(e){const t={};for(const o of e)t[o.name]=this.resolve(o);return t}createValidator(e){switch((e.type??e.designType??"").toLowerCase()){case"string":return e=>"string"==typeof e;case"number":return e=>"number"==typeof e;case"boolean":return e=>"boolean"==typeof e;case"date":return e=>e instanceof Date||"string"==typeof e&&!isNaN(Date.parse(e));case"array":return e=>Array.isArray(e);case"bigint":return e=>"bigint"==typeof e;default:return()=>!0}}}class Mr{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 eo(`Missing required ${o} port '${n.name}'`);if(e&&!this.resolver.resolve(n).validate(t[n.name]))throw new eo(`Invalid value for ${o} port '${n.name}'`)}}}const Gr=["node","definition","executor","execute","ports","component"];function Ur(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 Fr(e,t){const o=[];for(const n of Object.keys(e))Gr.includes(n)&&o.push(Ur("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 Br(e,t){t.push(...Fr(e,"$")),e.inputs.forEach((e,o)=>t.push(...Fr(e,`inputs[${o}]`))),e.outputs.forEach((e,o)=>t.push(...Fr(e,`outputs[${o}]`)));for(const o of e.nodes)t.push(...Fr(o,`nodes[${o.id}]`)),o.loop&&(t.push(...Fr(o.loop,`nodes[${o.id}].loop`)),Br(o.loop.body,t));for(const o of e.edges)t.push(...Fr(o,`edges[${o.id}]`))}function qr(e,t){const o=[];e.nodes.length>t.maxNodes&&o.push(Ur("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(Ur("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=Wr(e);n>t.maxNestingDepth&&o.push(Ur("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(Ur("document.limit.size","$",`Document serializes to ${r} bytes; at most ${t.maxDocumentBytes} bytes are allowed`,{details:{bytes:r,limit:t.maxDocumentBytes}})),o}function Wr(e,t=0){let o=t;for(const n of e.nodes)n.loop?.body&&(o=Math.max(o,Wr(n.loop.body,t+1)));return o}async function Vr(e,t,...o){const n=[];for(const r of e.nodes)t.has(r.kind,...o)||n.push(Ur("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 Vr(r.loop.body,t,...o));return n}async function Hr(e,t={},...o){const n={...Hn,...t.limits},r=[];if(!pt(e))return r.push(Ur("document.shape","$","Payload is not a canonical GraphWorkflowDocument: id and name must be strings and inputs, outputs, nodes and edges must be arrays")),{valid:!1,issues:r};if(!Ue(e))return r.push(Ur("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};Br(e,r),r.push(...(e=>{const t=[],o=new Set;for(const n of[...e.inputs,...e.outputs])o.has(n.id)?t.push(Ur("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(Ur("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(Ur("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(...qr(e,n)),Ro(e,r);try{ot(e)}catch(e){const t=e instanceof x?e.message:e+"";r.push(Ur("document.structure","$",t))}return t.catalogue&&r.push(...await Vr(e,t.catalogue,...o)),{valid:0===r.length,issues:r}}class Kr{constructor(e,t){this.iteration=e,this.metadata=t}}function zr(e,t,o={}){const n=e?.owner??null;return!n||n===t||(null==t||""===t)&&!0===o.allowAnonymousAccess}function Jr(e,t){return(e?.owner??null)===(t??null)}function Xr(e,t,o){if(!Jr(e,t))throw new L(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function Yr(e,t,o){if(!zr(e,t,o))throw new L(`${o.resourceKind} '${o.resourceId}' is owned by another user`)}function Qr(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>Qr(e)).join(",")}]`;const t=e;return`{${Object.keys(t).filter(e=>void 0!==t[e]).sort().map(e=>`${JSON.stringify(e)}:${Qr(t[e])}`).join(",")}}`}function Zr(e){return Y("sha256").update(Qr(e)).digest("hex")}class ei{constructor(e={}){this.events=new Map,this.listeners=new Map,this.limits={...ue,...e}}async append(e){let t=this.events.get(e.runId);t||(t=[],this.events.set(e.runId,t)),t.push(e),this.enforceRetention(t);for(const t of this.listeners.get(e.runId)??[])try{t(e)}catch{}}async listAfter(e,t){const o=this.events.get(e);return o?o.filter(e=>e.sequence>t):[]}subscribe(e,t){let o=this.listeners.get(e);return o||(o=new Set,this.listeners.set(e,o)),o.add(t),()=>{o.delete(t),0===o.size&&this.listeners.delete(e)}}release(e){this.events.delete(e),this.listeners.delete(e)}enforceRetention(e){const t=this.limits.maxEventsPerRun;for(;e.length>t;){const t=e.findIndex(e=>!he(e.type));if(-1===t)break;e.splice(t,1)}}}function ti(e){return new Lt({runId:e.runId,workflowId:e.workflowId,...e.ownerUser?{owner:e.ownerUser}:{},status:e.status,...e.documentFingerprint?{documentFingerprint:e.documentFingerprint}:{},...void 0!==e.result?{result:oi(e.result)}:{},...e.error?{error:oi(e.error)}:{},createdAt:new Date(e.createdAt),...e.startedAt?{startedAt:new Date(e.startedAt)}:{},...e.finishedAt?{finishedAt:new Date(e.finishedAt)}:{}})}function oi(e){if(null!=e)return JSON.parse(JSON.stringify(e))}class ni{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=>ti(e))}release(e){this.runs.delete(e)}}class ri{constructor(e,t={}){this.sequences=new Map,this.chains=new Map,this.store=e,this.limits={...ue,...t}}async publish(e){const t=e.runId,o=(this.sequences.get(t)??0)+1;this.sequences.set(t,o);const n={...e,payload:this.limitPayload(e.payload),sequence:o,timestamp:(new Date).toISOString()},r=(this.chains.get(t)??Promise.resolve()).then(()=>this.store.append(n));return this.chains.set(t,r.catch(()=>{})),await r,n}lastSequence(e){return this.sequences.get(e)??0}release(e){this.sequences.delete(e),this.chains.delete(e)}limitPayload(e){if(void 0===e)return;let t;try{t=JSON.stringify(e)}catch{return{nonSerializable:!0}}return t.length>this.limits.maxEventPayloadBytes?{truncated:!0,reason:"event payload exceeds the configured byte limit",bytes:t.length}:e}}class ii{constructor(e,t,o,n={},r={}){this.controllers=new Map,this.completions=new Map,this.timeouts=new Map,this.engine=e,this.runStore=t,this.publisher=o,this.hooks=n,this.limits={...ue,...r}}begin(e){const t=this.controllers.get(e);if(t)return t;const o=new AbortController;return this.controllers.set(e,o),o}abort(e,t){const o=this.controllers.get(e);return!!o&&(o.signal.aborted||o.abort(t),!0)}isAborted(e){return!0===this.controllers.get(e)?.signal.aborted}abortReason(e){const t=this.controllers.get(e)?.signal;if(t?.aborted)return"timeout"===t.reason?"timeout":"user"}waitFor(e){return this.completions.get(e)}schedule(e,t,o,...n){const r=this.completions.get(e.runId);if(r)return r;const i=this.runExecution({...e},t,o,...n).catch(async t=>{const o=ai(t);try{await this.emitTerminal({...e},ce.WORKFLOW_FAILED,o)}catch{}return await this.finalize({...e},"failed",void 0,o,...n)});return this.completions.set(e.runId,i),i}release(e){this.controllers.delete(e),this.completions.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.publisher.release(e)}armTimeout(e){const t=setTimeout(()=>{this.timeouts.delete(e),this.abort(e,"timeout")},this.limits.executionTimeoutMs);this.timeouts.set(e,t)}async runExecution(e,t,o,...n){const r=e.runId;let i,a,s=!1;const d=this.engine.observe({refresh:async t=>{t.runId===r&&(t.error&&(i=t.error),he((await this.publisher.publish(this.envelopeOf(e,t))).type)?s=!0:t.type===ce.WORKFLOW_STARTED&&"validating"===e.status&&(e.status="running",await this.persist(e,...n)))}});this.armTimeout(r);try{if(this.isAborted(r)){const t={name:"GraphRunCancelledError",message:`Graph run '${r}' was cancelled before execution started`,code:"GRAPH_RUN_CANCELLED"};return i=t,await this.emitTerminal(e,ce.WORKFLOW_CANCELLED,t),s=!0,await this.finalize(e,"cancelled",void 0,t,...n)}let d,l;e.status="validating",e.startedAt=(new Date).toISOString(),await this.persist(e,...n);try{({document:d,fingerprint:l}=await t(...n)),e.documentFingerprint=l,await this.persist(e,...n)}catch(t){const o=ai(t);return i=o,s||(await this.emitTerminal(e,ce.WORKFLOW_FAILED,o),s=!0),await this.finalize(e,"failed",void 0,o,...n)}if(this.isAborted(r)){const t={name:"GraphRunCancelledError",message:`Graph run '${r}' was cancelled before execution started`,code:"GRAPH_RUN_CANCELLED"};return i=t,s||(await this.emitTerminal(e,ce.WORKFLOW_CANCELLED,t),s=!0),await this.finalize(e,"cancelled",void 0,t,...n)}try{a=await this.engine.execute(d,o,{runId:r,abortSignal:this.controllers.get(r)?.signal,metadata:{documentFingerprint:l}},...n)}catch(e){i=ai(e)}const c=this.abortReason(r);let u,p;return"timeout"===c?(u="failed",p=i??{name:"GraphRunTimeoutError",message:`Graph run '${r}' exceeded the configured execution timeout of ${this.limits.executionTimeoutMs}ms`,code:"GRAPH_RUN_TIMEOUT"}):"user"===c?(u="cancelled",p=i):a?.status===se.SUCCEEDED?u="succeeded":a?.status===se.CANCELLED?(u="cancelled",p=i):(u="failed",p=i??ai(new Qt(a?`Graph run '${r}' failed`:`Graph run '${r}' failed without a result`,"GRAPH_RUN_FAILED",{runId:r}))),s||await this.emitTerminal(e,"succeeded"===u?ce.WORKFLOW_COMPLETED:"cancelled"===u?ce.WORKFLOW_CANCELLED:ce.WORKFLOW_FAILED,p),await this.finalize(e,u,a,p,...n)}finally{d();const e=this.timeouts.get(r);e&&(clearTimeout(e),this.timeouts.delete(r))}}async emitTerminal(e,t,o){await this.publisher.publish({runId:e.runId,workflowId:e.workflowId,type:t,error:o})}async finalize(e,t,o,n,...r){e.status=t,o&&(e.result=o),n&&(e.error=n),e.startedAt||(e.startedAt=(new Date).toISOString()),e.finishedAt=(new Date).toISOString(),await this.persist(e,...r);try{await(this.hooks.onRunCompleted?.(e,o))}catch{}return e}async persist(e,...t){await this.runStore.saveRun({...e},...t)}envelopeOf(e,t){return{runId:e.runId,workflowId:t.workflowId??e.workflowId,type:t.type,nodeId:t.nodeId,edgeId:t.edgeId,payload:void 0===t.payload?void 0:Ge(t.payload)?t.payload:{nonSerializable:!0},error:t.error,parentRunId:t.parentRunId,path:t.path}}}function ai(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 si{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 ri(o,n.limits),this.executor=new ii(e,t,this.publisher,{onRunCompleted:n.onRunCompleted},n.limits),this.options={...n,limits:{...ue,...n.limits}}}get limits(){return this.options.limits}async createRun(e,t,o,...n){this.validateCreateRequest(e);const r=e.workflowId??e.workflow?.id??"";if(!r)throw new x("Graph run request must carry a workflow document with an id or a saved workflowId");if(e.workflowId&&!this.options.documentResolver)throw new x("Graph run requests by workflowId require a document resolver");const i=o??t??"anonymous",a=this.activeByCaller.get(i)??new Set;if(a.size>=this.options.limits.maxConcurrentRuns)throw new x(`Graph run rejected: the configured limit of ${this.options.limits.maxConcurrentRuns} concurrent runs per caller is exhausted`);const s=this.generateRunId(),d={runId:s,workflowId:r,ownerUser:t,status:"queued",createdAt:(new Date).toISOString()};this.executor.begin(s),await this.runStore.saveRun({...d},...n);const l=this.documentProviderFor(e,t);return a.add(s),this.activeByCaller.set(i,a),this.callerKeysByRun.set(s,i),this.executor.schedule(d,l,e.inputs??{},...n).catch(()=>{}).finally(()=>this.finishActiveRun(s)),d}async getRun(e,t,...o){const n=await this.runStore.readRun(e,...o);if(!n)throw new _(`No graph run found for runId '${e}'`);return this.assertOwnership(n,t),n}async listRunsByWorkflow(e,t,...o){return(await this.runStore.listRuns(e,...o)).filter(e=>zr({owner:e.owner},t,{allowAnonymousAccess:!0===this.options.allowAnonymousAccess})).sort((e,t)=>{const o=e.updatedAt instanceof Date?e.updatedAt.getTime():NaN,n=t.updatedAt instanceof Date?t.updatedAt.getTime():NaN;return(Number.isFinite(n)?n:0)-(Number.isFinite(o)?o:0)})}async cancelRun(e,t,...o){const n=await this.runStore.readRun(e,...o);if(!n)throw new _(`No graph run found for runId '${e}'`);return this.assertWriteOwnership(n,t),"succeeded"===(r=n.status)||"failed"===r||"cancelled"===r||(this.executor.abort(e,"user"),n.status="cancelled",n.finishedAt=(new Date).toISOString(),await this.runStore.saveRun({...n},...o)),n;var r}async 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 x("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 x("Graph run request is ambiguous: supply either an unsaved workflow document or a saved workflowId, not both");if(!t&&!o)throw new x("Graph run request must supply either an unsaved workflow document or a saved workflowId");if(t&&!pt(e.workflow))throw new x("Graph run request carries a payload that is not a canonical GraphWorkflowDocument");if(void 0!==e.inputs&&!Ue(e.inputs))throw new x("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 x(`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:Zr(t)})}const o=e.workflowId;return async(...e)=>{const n=this.options.documentResolver;if(!n)throw new x("Graph run requests by workflowId require a document resolver");const r=await n.resolve(o,t,...e);return{document:r,fingerprint:Zr(r)}}}assertOwnership(e,t){Yr({owner:e.ownerUser},t,{allowAnonymousAccess:!0===this.options.allowAnonymousAccess,resourceKind:"Graph run",resourceId:e.runId})}assertWriteOwnership(e,t){Xr({owner:e.ownerUser},t,{resourceKind:"Graph run",resourceId:e.runId})}generateRunId(){const e=globalThis.crypto;if(!e||"function"!=typeof e.randomUUID)throw new ro("Cannot generate a graph run id: crypto.randomUUID is unavailable in this runtime",{runtime:typeof globalThis.crypto});return e.randomUUID()}}function di(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 li(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&pt(e.document)&&!pt(e)}function ci(e){return JSON.parse(JSON.stringify(e))}function ui(e){if(null==e)return 0;let t;try{t=e.getTime()}catch{return 0}return Number.isFinite(t)?t:0}let pi=class extends V{constructor(e){super(jt),this.catalogue=e}get limits(){return{...Hn,...Kn.graph.workflows.limits??{}}}get allowAnonymousAccess(){return!0===Kn.graph.workflows.allowAnonymousAccess}async saveDocument(e,t,...o){const{ctx:n,ctxArgs:r}=(await this.logCtx(o,"saveDocument",!0)).for(this.saveDocument);if(!pt(t))throw new x("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 x(`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 lo(i.issues);const a=di(n);let s;try{s=await this.read(e,...r)}catch{s=null}s&&this.assertWriteOwnership(e,s,a);const d=new Date;if(s)return s.name=t.name,s.document=ci(t),s.updatedAt=d,this.update(s,...r);const l=new jt({workflowId:e,name:t.name,document:ci(t),...a?{owner:a}:{},updatedAt:d});return this.create(l,...r)}async getDocument(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"getDocument",!0)).for(this.getDocument);let r;try{r=await this.read(e,...n)}catch{r=null}if(!r)throw new _(`No graph workflow found for workflowId '${e}'`);if(this.assertOwnership(e,r,di(o)),r.document)return ci(r.document);throw new _(`Graph workflow '${e}' has no canonical document; legacy definition/state snapshots are no longer supported (DECAF-50 \xa74.26 R2-2)`)}async listWorkflows(...e){const{ctx:t,ctxArgs:o}=(await this.logCtx(e,"listWorkflows",!0)).for(this.listWorkflows),n=await this.listBy("workflowId",H.ASC,...o),r=di(t);return n.filter(e=>zr(e,r,{allowAnonymousAccess:this.allowAnonymousAccess})).sort((e,t)=>ui(t.updatedAt)-ui(e.updatedAt))}async assertAccess(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"assertAccess",!0)).for(this.assertAccess);let r;try{r=await this.read(e,...n)}catch{r=null}if(!r)throw new _(`No graph workflow found for workflowId '${e}'`);return this.assertOwnership(e,r,di(o)),r}async validateDocument(e,...t){const{ctx:o}=(await this.logCtx(t,"validateDocument",!0)).for(this.validateDocument);return await Hr(e,{limits:this.limits,...this.catalogue?{catalogue:this.catalogue}:{}},o)}async saveSnapshot(e,t,...o){const{ctx:n,ctxArgs:r}=(await this.logCtx(o,"saveSnapshot",!0)).for(this.saveSnapshot);if(!Ue(t))throw new x("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(!li(t))throw new x("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=di(n);let a;try{a=await this.read(e,...r)}catch{a=null}a&&this.assertWriteOwnership(e,a,i);const s=new Date;if(a)return a.snapshot=t,await this.applyCanonicalWrapper(a,t,n),a.updatedAt=s,this.update(a,...r);const d=new jt({workflowId:e,snapshot:t,...i?{owner:i}:{},updatedAt:s});return await this.applyCanonicalWrapper(d,t,n),this.create(d,...r)}async loadSnapshot(e,...t){const{ctx:o,ctxArgs:n}=(await this.logCtx(t,"loadSnapshot",!0)).for(this.loadSnapshot);try{const t=await this.read(e,...n);return this.assertOwnership(e,t,di(o)),t}catch{return null}}assertOwnership(e,t,o){Yr(t??null,o??null,{allowAnonymousAccess:this.allowAnonymousAccess,resourceKind:"Graph workflow",resourceId:e})}assertWriteOwnership(e,t,o){Xr(t??null,o??null,{resourceKind:"Graph workflow",resourceId:e})}async applyCanonicalWrapper(e,t,o){if(!li(t))return;if(t.document.id!==e.workflowId)throw new x(`Document id '${t.document.id}' does not match the workflow id '${e.workflowId}' from the request path`);const n=await Hr(t.document,{limits:this.limits,...this.catalogue?{catalogue:this.catalogue}:{}},o);if(!n.valid)throw new lo(n.issues);e.document=ci(t.document),e.name=t.document.name}};pi=D([G(jt),$("design:paramtypes",[Function])],pi);let hi=class extends V{constructor(){super(Lt)}async saveRun(e,...t){const{ctxArgs:o}=(await this.logCtx(t,"saveRun",!0)).for(this.saveRun),n=ti(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)}};hi=D([G(Lt),$("design:paramtypes",[])],hi);class fi{map(e){const t={};for(const[o,n]of Object.entries(e.nodeResults))t[o]={status:n.status,startedAt:n.startedAt?.toISOString(),finishedAt:n.finishedAt?.toISOString(),error:n.error,outputs:n.outputs,fromCache:n.fromCache,pinned:n.pinned};const o={};for(const t of e.events)t.edgeId&&"edge.valueRouted"===t.type&&(o[t.edgeId]={status:se.SUCCEEDED,lastValue:t.payload?.value,updatedAt:t.timestamp.toISOString()});const n=[...e.events];return{runId:e.runId,status:e.status,nodes:t,edges:o,outputs:e.outputs,events:n}}}export{cr as AgentNode,Cn as BreakFlowNode,rr as ChatTriggerNode,Qn as CodeInputSchema,Zn as CodeNode,Mn as ConditionExpressionEvaluator,Hn as DEFAULT_GRAPH_WORKFLOW_DOCUMENT_LIMITS,Ho as DEFAULT_GRAPH_WORKFLOW_VALIDATION_LIMITS,sn as DEFAULT_PINNING_METADATA,er as DelayFlowNode,Ln as ErrorBoundaryFlowNode,ir as EventTriggerNode,ar as FormTriggerNode,ur as GRAPH_AGENT_NODES,Sr as GRAPH_BOUNDARY_NODES,Rr as GRAPH_BUILT_IN_NODE_CLASSES_BY_KIND,Ar as GRAPH_BUILT_IN_NODE_MANIFESTS,kr as GRAPH_BUILT_IN_NODE_MANIFESTS_BY_KIND,Yn as GRAPH_CODE_DEFAULT_LANGUAGE,zn as GRAPH_CODE_DEFAULT_TIMEOUT_MS,Xn as GRAPH_CODE_LANGUAGES,Kt as GRAPH_CODE_MAX_TIMEOUT_MS,Bt as GRAPH_DEFAULT_CONCURRENCY,Wt as GRAPH_DEFAULT_MAX_FOREACH_ITERATIONS,qt as GRAPH_DEFAULT_MAX_LOOP_ITERATIONS,Ko as GRAPH_DOCUMENT_FORBIDDEN_FIELD_KEYS,Dr as GRAPH_FLOW_CONTROL_NODES,Yt as GRAPH_LOOP_KIND,Pr as GRAPH_LOOP_NODES,Ht as GRAPH_MAX_FOREACH_ITERATIONS,Vt as GRAPH_MAX_LOOP_ITERATIONS,zt as GRAPH_PINNING_METADATA_KEY,Mo as GRAPH_PLAIN_SECRET_KEYS,_r as GRAPH_TRIGGER_NODES,$r as GRAPH_UTILITY_NODES,Ft as GRAPH_WORKFLOW_BOUNDARY,Gr as GRAPH_WORKFLOW_FORBIDDEN_FIELD_KEYS,xo as GraphAuthValidator,ao as GraphBreakSignal,gr as GraphConditionEvaluator,Xt as GraphConditionType,Fo as GraphConnectionPolicyValidator,Wo as GraphConnectionValidationError,Vo as GraphCredentialAuthorizationError,Bo as GraphCredentialReferenceValidator,Zt as GraphCycleError,qo as GraphDocumentValidationError,Uo as GraphEdgeInstanceValidator,Kn as GraphEnvironment,Do as GraphExecutionContext,un as GraphExecutionEngine,Qt as GraphExecutionError,co as GraphExecutionEventEmitter,uo as GraphExecutionEventFactory,$o as GraphExecutionFrame,Yo as GraphExecutionPlanner,fi as GraphExecutionSnapshotMapper,fr as GraphForeachLoopNode,eo as GraphInputError,wr as GraphInputValueNode,Kr as GraphLoopExecutionContext,to as GraphLoopLimitError,Rn as GraphNode,kn as GraphNodeCatalogue,_n as GraphNodeExecutorRegistry,Dn as GraphNodeExecutorResolver,So as GraphNodeInstanceValidator,Nn as GraphNodeManifestResolver,mn as GraphNodeMethodNotFoundError,yn as GraphNodeMethodRegistry,gn as GraphNodeNotFoundError,fn as GraphNodeRegistrationError,br as GraphOutputValueNode,Go as GraphParameterValidator,cn as GraphPinningDependencyResolver,oo as GraphPinningError,ln as GraphPinningPolicy,an as GraphPinningService,Jt as GraphPinningStrategy,no as GraphPortError,jr as GraphPortSchemaResolver,so as GraphRunCancelledError,ri as GraphRunEventPublisher,ii as GraphRunExecutor,hi as GraphRunModelService,si as GraphRunService,ro as GraphStoreError,rn as GraphTopology,io as GraphTopologyError,mr as GraphUntilLoopNode,Qo as GraphValueModel,on as GraphValueRepository,Mr as GraphValueValidator,yr as GraphWhileLoopNode,lo as GraphWorkflowDocumentRejectedError,Xo as GraphWorkflowDocumentValidator,pi as GraphWorkflowService,jn as HumanApprovalFlowNode,Wn as IfFlowNode,ei as InMemoryGraphRunEventStore,ni as InMemoryGraphRunStore,hn as IsolatedVmCodeSandboxEvaluator,tr as LogFlowNode,sr as ManualTriggerNode,or as MapNode,dr as ScheduleTriggerNode,Vn as SwitchFlowNode,nr as UtilityLogNode,lr as WebhookTriggerNode,Yr as assertGraphResourceOwnership,Xr as assertGraphResourceWriteOwnership,Po as buildGraphExecutionResult,Tr as builtInGraphNodeRegistrations,zr as canAccessGraphResource,Jr as canAccessGraphResourcePayload,Co as checkGraphValueAgainstSchema,Jn as clampGraphCodeTimeoutMs,Ro as collectLooseNodeIssues,ho as composeGraphNamespace,nn as createGraphValueRepository,Pn as declaredGraphNodeMethods,po as decomposeGraphNamespace,Oo as decomposeGraphNamespaces,$n as defineGraphNode,Fn as evaluateCodeCondition,qn as evaluateCondition,Bn as evaluateConditionSync,wo as findMalformedGraphNamespaces,yo as findUngrantedGraphNamespaces,Eo as graphAuthDataFromRecord,No as graphAuthDataOf,mo as graphNamespaceCovers,go as graphNamespacePartsOf,Sn as graphNodeConfig,bo as graphRolesFromNamespaces,Zr as graphRunDocumentFingerprint,di as graphWorkflowOwnerOf,Gn as isCodeCondition,Un as isConditionExpression,Lo as isGraphCredentialReferenceLike,fo as isGraphNamespaceCacheEntryValid,zo as isGraphResolvedWorkflow,dn as isPinnable,Ao as mergeGraphAuthData,Lr as registerBuiltInGraphNodes,In as resolveGraphDynamicPorts,En as resolveGraphNodeManifest,Zo as serializeGraphValueKey,Hr as validateGraphWorkflowDocumentAtBoundary};
|
|
2
2
|
//# sourceMappingURL=as-graph.js.map
|