@makaio/framework 1.0.0-dev-1783940945655 → 1.0.0-dev-1783973359164

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/dist/.makaio-build.json +2 -2
  2. package/dist/adapter-subsystem/index.d.mts +10 -0
  3. package/dist/adapter-subsystem/index.mjs +1 -1
  4. package/dist/authority-state-bootstrap-CEuKScnL.mjs +1 -0
  5. package/dist/bus/index.d.mts +31 -31
  6. package/dist/bus/index.mjs +1 -1
  7. package/dist/{canonical-model-CVRCW9h7.mjs → canonical-model-C31NaBJs.mjs} +1 -1
  8. package/dist/clients/index.d.mts +5 -5
  9. package/dist/contracts/adapter/index.d.mts +2 -2
  10. package/dist/contracts/adapter/schemas/session-lineage.d.mts +1 -1
  11. package/dist/contracts/canonical-model/index.d.mts +1 -1
  12. package/dist/contracts/canonical-model/index.mjs +1 -1
  13. package/dist/contracts/client/index.d.mts +1 -1
  14. package/dist/contracts/extension/index.d.mts +2 -2
  15. package/dist/contracts/facet/index.d.mts +1 -1
  16. package/dist/contracts/index.d.mts +228 -160
  17. package/dist/contracts/index.mjs +1 -1
  18. package/dist/contracts/native-session-supervisor/index.d.mts +2 -2
  19. package/dist/contracts/session/index.d.mts +3 -3
  20. package/dist/contracts/shared/index.d.mts +1 -1
  21. package/dist/contracts/variant/index.d.mts +1 -1
  22. package/dist/contracts/workflow/index.d.mts +3 -3
  23. package/dist/contracts/workflow/index.mjs +1 -1
  24. package/dist/{detached-extension-handle-CTaQoolf.mjs → detached-extension-handle-vDK194QV.mjs} +1 -1
  25. package/dist/drizzle/0026_m_mrgvi7fq.sql +16 -0
  26. package/dist/drizzle/0027_m_mrgw0uzg.sql +1 -0
  27. package/dist/drizzle/0028_m_mrgx04i1.sql +1 -0
  28. package/dist/drizzle/0029_terminal-authority.sql +1 -0
  29. package/dist/drizzle/meta/_journal.json +28 -0
  30. package/dist/{index-Do7Wgio_2.d.mts → index-BDr2Ba122.d.mts} +1 -1
  31. package/dist/{index-p6dWV52m.d.mts → index-BKZAAWo2.d.mts} +330 -330
  32. package/dist/{index-CB2XTzvd.d.mts → index-Bbr5LEUc.d.mts} +1 -1
  33. package/dist/{index-5s_dN3cg2.d.mts → index-BmsPH78f2.d.mts} +33 -5
  34. package/dist/{index-BsEvzFey.d.mts → index-ButbwvVY.d.mts} +6 -6
  35. package/dist/{index-D5IEq4_E.d.mts → index-C2C1qH1Y.d.mts} +6 -4
  36. package/dist/{index-BtL7ONuM.d.mts → index-C6LZOiDv.d.mts} +149 -1
  37. package/dist/{index-DxatNFz7.d.mts → index-COC9jCdc.d.mts} +12 -12
  38. package/dist/{index-BcejR1Jc.d.mts → index-CtjLeK1F.d.mts} +1 -1
  39. package/dist/{index-Cw3cjGAT.d.mts → index-Cx8jGKOs.d.mts} +11 -11
  40. package/dist/{index-DNc1yLQs.d.mts → index-DHGW7dFf.d.mts} +8 -8
  41. package/dist/{index-DlUPWOh4.d.mts → index-DNkR5yTY.d.mts} +2876 -709
  42. package/dist/{index-iJP-l15K.d.mts → index-DXBiCH2y.d.mts} +27 -1
  43. package/dist/{index-CW6-0k3Z.d.mts → index-DlAfs3RD.d.mts} +105 -105
  44. package/dist/{index-sCOlgPyj.d.mts → index-DpZbaS7y.d.mts} +388 -388
  45. package/dist/{index-C9Q1E8Y-.d.mts → index-x2gFj3BK.d.mts} +38 -38
  46. package/dist/kernel/extension/index.d.mts +1 -1
  47. package/dist/kernel/index.d.mts +2 -2
  48. package/dist/kernel/observability/index.d.mts +1 -1
  49. package/dist/{load-extensions-BtUrq2_t.mjs → load-extensions-nqL5WAKj.mjs} +1 -1
  50. package/dist/mcp-http-server/index.d.mts +27 -90
  51. package/dist/mcp-http-server/index.mjs +1 -1
  52. package/dist/{namespace-CQBSXm1U.d.mts → namespace-B0uZIZYT.d.mts} +20 -20
  53. package/dist/{namespace-CfgtqUWS.d.mts → namespace-BoA6u44C.d.mts} +156 -156
  54. package/dist/{namespace-CpyL93kW.d.mts → namespace-CCZXyxSe.d.mts} +9 -9
  55. package/dist/{namespace-D3SQQgxa2.d.mts → namespace-CukqFYHf2.d.mts} +1 -1
  56. package/dist/{namespace-CGgOLxiW2.d.mts → namespace-rO-C2Dgu2.d.mts} +2 -2
  57. package/dist/package-BYpWkSuQ.mjs +1 -0
  58. package/dist/package-CsFFT9iR.mjs +7 -0
  59. package/dist/{package-CdBiknf3.d.mts → package-DG9GSY8M.d.mts} +52 -1
  60. package/dist/package.json +1 -1
  61. package/dist/rules/index.mjs +1 -1
  62. package/dist/runtime-node/extension-validation.mjs +1 -1
  63. package/dist/runtime-node/index.d.mts +4 -89
  64. package/dist/runtime-node/index.mjs +24 -24
  65. package/dist/runtime-node/makaio-config.mjs +1 -1
  66. package/dist/runtime-node/workflow-worker/index.d.mts +2 -2
  67. package/dist/runtime-node/workflow-worker/index.mjs +1 -1
  68. package/dist/runtime-node/workflow-worker/worker-entry.mjs +1 -1
  69. package/dist/{schema-BnTOFCdU.d.mts → schema-aOwmHxaF.d.mts} +1 -1
  70. package/dist/{schemas--uwN5dfK2.d.mts → schemas-CoJCTFod2.d.mts} +19 -19
  71. package/dist/{schemas-C17AifUQ.d.mts → schemas-OaBqeEUT.d.mts} +156 -156
  72. package/dist/schemas-th_nuC5t.mjs +1 -0
  73. package/dist/service-base/index.d.mts +4 -3
  74. package/dist/service-base/index.mjs +1 -1
  75. package/dist/services/agent-runtime/index.d.mts +2 -2
  76. package/dist/services/agent-runtime/namespace.d.mts +1 -1
  77. package/dist/services/agent-runtime/schemas.d.mts +1 -1
  78. package/dist/services/context-rules/index.d.mts +3 -3
  79. package/dist/services/execution-target/index.d.mts +1 -1
  80. package/dist/services/filesystem/namespace.d.mts +6 -6
  81. package/dist/services/filesystem/schemas.d.mts +3 -3
  82. package/dist/services/index.d.mts +104 -104
  83. package/dist/services/index.mjs +1 -1
  84. package/dist/services/session/index.d.mts +5 -5
  85. package/dist/services/session/messages/namespace.d.mts +1 -1
  86. package/dist/services/session/session-events/namespace.d.mts +1 -1
  87. package/dist/services/session/storage/namespace.d.mts +1 -1
  88. package/dist/services/session/storage/schema.d.mts +1 -1
  89. package/dist/services/settings/namespace.d.mts +16 -16
  90. package/dist/services/settings/storage/extension-configs/namespace.d.mts +3 -3
  91. package/dist/services/subagent/index.d.mts +2 -2
  92. package/dist/services/subagent/index.mjs +1 -1
  93. package/dist/services/subagent-template/index.d.mts +2 -2
  94. package/dist/services/subagent-template/namespace.d.mts +1 -1
  95. package/dist/services/subagent-template/schemas.d.mts +1 -1
  96. package/dist/services/tools/index.mjs +1 -1
  97. package/dist/{session-lineage-BLw8iWAj.d.mts → session-lineage-YShrn77v.d.mts} +1 -1
  98. package/dist/storage/drizzle/index.d.mts +8 -1
  99. package/dist/storage/drizzle/index.mjs +1 -1
  100. package/dist/tools/index.d.mts +1 -1
  101. package/dist/{tools-C8vqn1KY.mjs → tools-PC_L6g2m.mjs} +1 -1
  102. package/dist/{transition-Bfe8VVc1.d.mts → transition-CwUIm1hJ.d.mts} +8 -0
  103. package/dist/{types-q95p55BF.d.mts → types-BaDYigzD.d.mts} +567 -256
  104. package/dist/workflow-DFJYGjq_.mjs +1 -0
  105. package/dist/workflow-engine/index.d.mts +690 -87
  106. package/dist/workflow-engine/index.mjs +1 -1
  107. package/dist/workflow-engine/package.d.mts +1 -1
  108. package/dist/workflow-engine/package.mjs +1 -1
  109. package/dist/workflow-engine/workflow-orchestrator.mjs +1 -1
  110. package/dist/workflow-worker-BEFjCccX.mjs +1 -0
  111. package/package.json +9 -8
  112. package/dist/loop-gate-handlers-0a3dIY8O.mjs +0 -1
  113. package/dist/package-0gVhAVkO.mjs +0 -7
  114. package/dist/package-BwvGaKwn.mjs +0 -1
  115. package/dist/schemas-D6lj9NMg.mjs +0 -1
  116. package/dist/workflow-CvVAZ89A.mjs +0 -1
  117. package/dist/workflow-worker-CudfEstp.mjs +0 -1
  118. /package/dist/{await-trigger-D623tvig.mjs → await-trigger-DP-fTQc4.mjs} +0 -0
  119. /package/dist/{descriptor-to-package-D5SWf6TL.mjs → descriptor-to-package-Rs-OjOQU.mjs} +0 -0
  120. /package/dist/{esm-oHhRYTEn.mjs → esm-C_WW4-pP.mjs} +0 -0
@@ -1 +1 @@
1
- import{C as e,F as t,G as n,N as r,S as i,T as a,V as o,Y as s,j as c,v as l}from"../loop-gate-handlers-0a3dIY8O.mjs";import{a as u,c as d,i as f,l as p,n as m,o as h,r as g,s as _,t as v}from"../package-0gVhAVkO.mjs";import{JsonValueSchema as y,WorkflowFrameStateSchema as b}from"@makaio/framework/contracts";const x=new Set([...b.shape.status.options]);function S(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function C(e){if(!S(e))return!1;for(let t of Object.values(e))if(!S(t)||typeof t.status!=`string`||!x.has(t.status)||`result`in t&&t.result!==void 0&&!y.safeParse(t.result).success)return!1;return!0}function w(e){let t={trigger:S(e.trigger)?e.trigger:{},steps:C(e.steps)?e.steps:{},inputs:y.safeParse(e.inputs).success?e.inputs:{}};return`item`in e&&(t.item=e.item),typeof e.index==`number`&&(t.index=e.index),t}export{f as WorkflowEngineService,v as WorkflowEngineToken,u as WorkflowExecutor,i as WorkflowStorageNamespace,e as WorkflowStorageSubjects,w as buildWorkflowExpressionContextFromResolvedInputs,m as createWorkflowEnginePackage,_ as getWorkflowState,d as initializeWorkflowState,p as patchWorkflowState,h as registerDrizzleWorkflowStorage,l as runShellStep,a as workflowDefinitionsDual,g as workflowEnginePackage,c as workflowExecutionStateDual,r as workflowExecutionStateEventsDual,t as workflowExecutionsDual,o as workflowStepSpansDual,n as worklogFrameEntriesDual,s as worklogSummariesDual};
1
+ import{A as e,B as t,C as n,D as r,I as i,K as a,O as o,R as s,X as c,et as l,nt as u}from"../authority-state-bootstrap-CEuKScnL.mjs";import{a as d,c as f,i as p,l as m,n as h,o as g,r as _,s as v,t as y}from"../package-CsFFT9iR.mjs";import{JsonValueSchema as b,WorkflowFrameStateSchema as x}from"@makaio/framework/contracts";const S=new Set([...x.shape.status.options]);function C(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function w(e){if(!C(e))return!1;for(let t of Object.values(e))if(!C(t)||typeof t.status!=`string`||!S.has(t.status)||`result`in t&&t.result!==void 0&&!b.safeParse(t.result).success)return!1;return!0}function T(e){let t={trigger:C(e.trigger)?e.trigger:{},steps:w(e.steps)?e.steps:{},inputs:b.safeParse(e.inputs).success?e.inputs:{}};return`item`in e&&(t.item=e.item),typeof e.index==`number`&&(t.index=e.index),t}export{p as WorkflowEngineService,y as WorkflowEngineToken,d as WorkflowExecutor,r as WorkflowStorageNamespace,o as WorkflowStorageSubjects,T as buildWorkflowExpressionContextFromResolvedInputs,h as createWorkflowEnginePackage,v as getWorkflowState,f as initializeWorkflowState,m as patchWorkflowState,g as registerDrizzleWorkflowStorage,n as runShellStep,e as workflowDefinitionsDual,_ as workflowEnginePackage,i as workflowExecutionStateDual,s as workflowExecutionStateEventsDual,t as workflowExecutionsDual,u as workflowFinalizationsDual,a as workflowStepSpansDual,c as worklogFrameEntriesDual,l as worklogSummariesDual};
@@ -1,2 +1,2 @@
1
- import { n as createWorkflowEnginePackage, r as workflowEnginePackage, t as WorkflowEngineToken } from "../package-CdBiknf3.mjs";
1
+ import { n as createWorkflowEnginePackage, r as workflowEnginePackage, t as WorkflowEngineToken } from "../package-DG9GSY8M.mjs";
2
2
  export { WorkflowEngineToken, createWorkflowEnginePackage, workflowEnginePackage };
@@ -1 +1 @@
1
- import{n as e,r as t,t as n}from"../package-0gVhAVkO.mjs";export{n as WorkflowEngineToken,e as createWorkflowEnginePackage,t as workflowEnginePackage};
1
+ import{n as e,r as t,t as n}from"../package-CsFFT9iR.mjs";export{n as WorkflowEngineToken,e as createWorkflowEnginePackage,t as workflowEnginePackage};
@@ -1 +1 @@
1
- import{C as e,Z as t,a as n,b as r,i,m as a,n as o,o as s,s as c,t as l}from"../loop-gate-handlers-0a3dIY8O.mjs";import{WORKFLOW_CANCELLED_REASON as u}from"@makaio/framework/contracts";async function d(n,r,i,a){let o=await g(n,r,i);return await n.request(e.setExecution,{execution:o}),i===`completed`?await n.emit(t.execution.completed,{executionId:r.executionId,workflowId:r.workflowId,totalDuration:0,completedAt:o.completedAt}):await n.emit(t.execution.cancelled,{executionId:r.executionId,workflowId:r.workflowId,reason:a,completedAt:o.completedAt}),i===`cancelled`?{executionId:r.executionId,workflowId:r.workflowId,status:`cancelled`,...a===void 0?{}:{reason:a}}:{executionId:r.executionId,workflowId:r.workflowId,status:`completed`}}function f(e,t){return t.status===`completed`?{executionId:e.executionId,workflowId:e.workflowId,status:`completed`,...t.artifact===void 0?{}:{artifact:t.artifact}}:t.status===`cancelled`?{executionId:e.executionId,workflowId:e.workflowId,status:`cancelled`,...t.reason===void 0?{}:{reason:t.reason}}:t.status===`paused`?{executionId:e.executionId,workflowId:e.workflowId,status:`paused`,pausedAtGateId:t.pausedAtGateId,pausedAtFrameId:t.pausedAtFrameId}:{executionId:e.executionId,workflowId:e.workflowId,status:`failed`,error:t.error}}function p(e){let t,n=()=>{t=a({bus:e.bus,activeExecutions:e.activeExecutions,shellAbortControllers:e.shellAbortControllers,activeRunnerSteps:e.activeRunnerSteps,cancelTimeoutMs:r.cancelTimeoutMs},e.executionId,u).catch(t=>(console.error(`[WorkflowOrchestrator] Failed to persist cancellation for ${e.executionId}:`,t),!1))};return e.signal.addEventListener(`abort`,n,{once:!0}),e.signal.aborted&&n(),async()=>(e.signal.removeEventListener(`abort`,n),t??!1)}async function m(t,n){let r=await t.requestOptional(e.getExecution,{executionId:n});return r.handled?r.data.execution?.startedAt??void 0:void 0}async function h(e,t){return{id:t.executionId,workflowId:t.workflowId,coordinatorSessionId:t.coordinatorSessionId,status:`running`,inputs:t.inputs,config:t.config??{},startedAt:await m(e,t.executionId)??Date.now(),triggerPayload:t.triggerPayload,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef},scope:t.scope}}async function g(e,t,n){let r=Date.now();return{id:t.executionId,workflowId:t.workflowId,coordinatorSessionId:t.coordinatorSessionId,status:n,inputs:t.inputs,config:t.config??{},startedAt:await m(e,t.executionId)??r,completedAt:r,triggerPayload:t.triggerPayload,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef},scope:t.scope}}async function _(e,t,r,i,a,c,l,d,f){let p=e.suspensionStrategy===`wait-in-process`?void 0:await v(e.executionId,l,{required:!0}),m=await n({definition:t,execution:r,runContext:i,zodSchema:f?.artifact,bus:l}),h=new s(e.executionId,e.workflowId,t,r,a,l,d,void 0,m,{context:e.context,env:e.env},{suspensionStrategy:e.suspensionStrategy,resumeFrames:p,runtimeLoopGates:c}),g=h.buildExpressionContext(),_=await o(t.root,h,g);return _.status===`failed`?{status:`failed`,error:_.error}:_.status===`paused`?{status:`paused`,pausedAtGateId:_.pausedAtGateId,pausedAtFrameId:_.pausedAtFrameId}:_.status===`cancelled`||d.aborted?{status:`cancelled`,reason:u}:{status:`completed`,artifact:m?.current}}async function v(t,n,r={}){try{let a=await n.requestOptional(e.listFrames,{executionId:t});if(!a.handled){if(r.required===!0)throw Error(`Frame storage handler is required to resume execution '${t}'.`);return}return a.data.frames.length===0?void 0:i(a.data.frames)}catch(e){if(r.required===!0)throw e;return}}function y(e,t){return{executionId:e.executionId,workflowId:e.workflowId,source:e.source,definitionSnapshot:e.source.kind===`definition`?e.definition??t:t,workerManifest:{packages:[]},inputs:e.inputs,config:e.config??{},scope:e.scope,triggerPayload:e.triggerPayload,...e.artifactRef===void 0?{}:{artifactRef:e.artifactRef},...e.executionHints===void 0?{}:{executionHints:e.executionHints},coordinatorSessionId:e.coordinatorSessionId,cancelSubject:e.cancelSubject,context:e.context,env:e.env,createdAt:Date.now(),suspensionStrategy:e.suspensionStrategy}}async function b(n,r,i,a,o){i.status=`paused`,await n.request(e.setExecution,{execution:i}),await n.emit(t.execution.paused,{executionId:r.executionId,workflowId:r.workflowId,pausedAtGateId:a,pausedAtFrameId:o})}async function x(e,n,r,i,a,o){r===`completed`?await e.emit(t.execution.completed,{executionId:n.executionId,workflowId:n.workflowId,totalDuration:a-i.startedAt,completedAt:a}):r===`cancelled`?await e.emit(t.execution.cancelled,{executionId:n.executionId,workflowId:n.workflowId,reason:u,completedAt:a}):await e.emit(t.execution.failed,{executionId:n.executionId,workflowId:n.workflowId,error:o??`Workflow execution failed`,completedAt:a})}async function S(t){let{config:n,loaded:r,bus:i,signal:a}=t,{definition:o}=r;if(a.aborted)return d(i,n,`cancelled`,u);let s=await h(i,n),m=y(n,o);await c(i,s,m,o);let g=new Map(r.runtimeHandlers),v=r.runtimeLoopGates??new Map,S=new Map,C=new Map,w=new Map;S.set(n.executionId,{execution:s,workflow:o,runContext:m,runtimeHandlers:g,runtimeLoopGates:new Map(v)});let T=p({signal:a,executionId:n.executionId,bus:i,activeExecutions:S,shellAbortControllers:C,activeRunnerSteps:w}),E={status:`completed`},D=!1;try{o.root.nodes.length>0&&(l(o,v),E=await _(n,o,s,m,g,v,i,a,r.zodSchemas))}catch(e){E={status:`failed`,error:e instanceof Error?e.message:String(e)}}finally{D=await T(),S.clear()}if(D)return f(n,{status:`cancelled`,reason:u});if((a.aborted||s.status===`cancelled`)&&(E={status:`cancelled`,reason:u}),E.status===`paused`)return await b(i,n,s,E.pausedAtGateId,E.pausedAtFrameId),f(n,E);let O=Date.now(),k=E.status===`failed`?E.error:void 0;return s.status=E.status,s.completedAt=O,s.error=k,await i.request(e.setExecution,{execution:s}),await x(i,n,E.status,s,O,k),f(n,E)}export{S as runWorkflowOrchestrator};
1
+ import{O as e,T as t,_ as n,c as r,i,it as a,l as o,o as s,r as c,s as l,t as u}from"../authority-state-bootstrap-CEuKScnL.mjs";import{WORKFLOW_CANCELLED_REASON as d}from"@makaio/framework/contracts";async function f(t,n,r,i){let o=await _(t,n,r);return await t.request(e.setExecution,{execution:o}),r===`completed`?await t.emit(a.execution.completed,{executionId:n.executionId,workflowId:n.workflowId,totalDuration:0,completedAt:o.completedAt}):await t.emit(a.execution.cancelled,{executionId:n.executionId,workflowId:n.workflowId,reason:i,completedAt:o.completedAt}),r===`cancelled`?{executionId:n.executionId,workflowId:n.workflowId,status:`cancelled`,...i===void 0?{}:{reason:i}}:{executionId:n.executionId,workflowId:n.workflowId,status:`completed`}}function p(e,t){return t.status===`completed`?{executionId:e.executionId,workflowId:e.workflowId,status:`completed`,...t.artifact===void 0?{}:{artifact:t.artifact}}:t.status===`cancelled`?{executionId:e.executionId,workflowId:e.workflowId,status:`cancelled`,...t.reason===void 0?{}:{reason:t.reason}}:t.status===`paused`?{executionId:e.executionId,workflowId:e.workflowId,status:`paused`,pausedAtGateId:t.pausedAtGateId,pausedAtFrameId:t.pausedAtFrameId}:{executionId:e.executionId,workflowId:e.workflowId,status:`failed`,error:t.error}}function m(e){let r,i=()=>{r=n({bus:e.bus,activeExecutions:e.activeExecutions,shellAbortControllers:e.shellAbortControllers,activeRunnerSteps:e.activeRunnerSteps,durableLifecycleTransitions:e.durableLifecycleTransitions,lifecyclePublications:e.lifecyclePublications,publishingLifecycleExecutions:e.publishingLifecycleExecutions,cancelTimeoutMs:t.cancelTimeoutMs},e.executionId,d).catch(t=>(console.error(`[WorkflowOrchestrator] Failed to persist cancellation for ${e.executionId}:`,t),!1))};return e.signal.addEventListener(`abort`,i,{once:!0}),e.signal.aborted&&i(),async()=>(e.signal.removeEventListener(`abort`,i),r??!1)}async function h(t,n){let r=await t.requestOptional(e.getExecution,{executionId:n});return r.handled?r.data.execution?.startedAt??void 0:void 0}async function g(e,t){return{id:t.executionId,workflowId:t.workflowId,coordinatorSessionId:t.coordinatorSessionId,status:`running`,inputs:t.inputs,config:t.config??{},startedAt:await h(e,t.executionId)??Date.now(),triggerPayload:t.triggerPayload,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef},scope:t.scope}}async function _(e,t,n){let r=Date.now();return{id:t.executionId,workflowId:t.workflowId,coordinatorSessionId:t.coordinatorSessionId,status:n,inputs:t.inputs,config:t.config??{},startedAt:await h(e,t.executionId)??r,completedAt:r,triggerPayload:t.triggerPayload,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef},scope:t.scope}}async function v(e,t,n,a,o,s,c,u,f){let p=e.suspensionStrategy===`wait-in-process`?void 0:await y(e.executionId,c,{required:!0}),m=await l({definition:t,execution:n,runContext:a,zodSchema:f?.artifact,bus:c}),h=new r(e.executionId,e.workflowId,t,n,o,c,u,void 0,m,{context:e.context,env:e.env},{suspensionStrategy:e.suspensionStrategy,resumeFrames:p,runtimeLoopGates:s}),g=h.buildExpressionContext(),_=await i(t.root,h,g);return _.status===`failed`?{status:`failed`,error:_.error}:_.status===`paused`?{status:`paused`,pausedAtGateId:_.pausedAtGateId,pausedAtFrameId:_.pausedAtFrameId}:_.status===`cancelled`||u.aborted?{status:`cancelled`,reason:d}:{status:`completed`,artifact:m?.current}}async function y(t,n,r={}){try{let i=await n.requestOptional(e.listFrames,{executionId:t});if(!i.handled){if(r.required===!0)throw Error(`Frame storage handler is required to resume execution '${t}'.`);return}return i.data.frames.length===0?void 0:s(i.data.frames)}catch(e){if(r.required===!0)throw e;return}}function b(e,t){return{executionId:e.executionId,workflowId:e.workflowId,source:e.source,definitionSnapshot:e.source.kind===`definition`?e.definition??t:t,workerManifest:{packages:[]},inputs:e.inputs,config:e.config??{},scope:e.scope,triggerPayload:e.triggerPayload,...e.artifactRef===void 0?{}:{artifactRef:e.artifactRef},...e.executionHints===void 0?{}:{executionHints:e.executionHints},coordinatorSessionId:e.coordinatorSessionId,cancelSubject:e.cancelSubject,context:e.context,env:e.env,createdAt:Date.now(),suspensionStrategy:e.suspensionStrategy,...e.terminalAuthority===void 0?{}:{terminalAuthority:e.terminalAuthority}}}async function x(t,n,r,i,o){r.status=`paused`,await t.request(e.setExecution,{execution:r}),await t.emit(a.execution.paused,{executionId:n.executionId,workflowId:n.workflowId,pausedAtGateId:i,pausedAtFrameId:o})}async function S(e,t,n,r,i,o){n===`completed`?await e.emit(a.execution.completed,{executionId:t.executionId,workflowId:t.workflowId,totalDuration:i-r.startedAt,completedAt:i}):n===`cancelled`?await e.emit(a.execution.cancelled,{executionId:t.executionId,workflowId:t.workflowId,reason:d,completedAt:i}):await e.emit(a.execution.failed,{executionId:t.executionId,workflowId:t.workflowId,error:o??`Workflow execution failed`,completedAt:i})}async function C(t){let{config:n,loaded:r,bus:i,signal:a}=t,{definition:s}=r;if(a.aborted)return n.terminalAuthority===`authority`?{executionId:n.executionId,workflowId:n.workflowId,status:`cancelled`,reason:d}:f(i,n,`cancelled`,d);let l=await g(i,n),h=b(n,s);n.terminalAuthority===`authority`?await u(i,h,s):await o(i,l,h,s);let _=new Map(r.runtimeHandlers),y=r.runtimeLoopGates??new Map,C=new Map,w=new Map,T=new Map,E=new Map,D=new Map,O=new Set;C.set(n.executionId,{execution:l,workflow:s,runContext:h,runtimeHandlers:_,runtimeLoopGates:new Map(y)});let k=n.terminalAuthority===`authority`?async()=>!1:m({signal:a,executionId:n.executionId,bus:i,activeExecutions:C,shellAbortControllers:w,activeRunnerSteps:T,durableLifecycleTransitions:E,lifecyclePublications:D,publishingLifecycleExecutions:O}),A={status:`completed`},j=!1;try{s.root.nodes.length>0&&(c(s,y),A=await v(n,s,l,h,_,y,i,a,r.zodSchemas))}catch(e){A={status:`failed`,error:e instanceof Error?e.message:String(e)}}finally{j=await k(),C.clear()}if(j)return p(n,{status:`cancelled`,reason:d});if((a.aborted||l.status===`cancelled`)&&(A={status:`cancelled`,reason:d}),A.status===`paused`)return n.terminalAuthority!==`authority`&&await x(i,n,l,A.pausedAtGateId,A.pausedAtFrameId),p(n,A);if(n.terminalAuthority===`authority`)return p(n,A);let M=Date.now(),N=A.status===`failed`?A.error:void 0;return l.status=A.status,l.completedAt=M,l.error=N,await i.request(e.setExecution,{execution:l}),await S(i,n,A.status,l,M,N),p(n,A)}export{C as runWorkflowOrchestrator};
@@ -0,0 +1 @@
1
+ import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{n as r,o as i,t as a}from"./await-trigger-DP-fTQc4.mjs";import{basename as o,join as s}from"node:path";import{createBusInstance as c}from"@makaio/framework/bus";import{AdapterSubjects as l,FrameworkContractNamespaces as u,FrameworkStorageNamespaces as d,WorkerNodeCapabilitiesSchema as f,WorkerNodeSubjects as p,WorkflowWorkerConfigSchema as m}from"@makaio/framework/contracts";import{AdapterRuntimeSubjects as h,registerAdapterRuntimeIdentityHandlers as g}from"@makaio/framework/services/adapter-runtime";import{ExtensionCoordinator as _,KernelSubjects as v}from"@makaio/framework/kernel";import{AdapterSubsystemSubjects as y}from"@makaio/framework/services/adapter-subsystem";import{createClientsCorePackage as b}from"@makaio/framework/clients";import{AdapterSubsystemToken as x,createAdapterSubsystemContributionProcessor as S,createAdapterSubsystemPackage as C}from"@makaio/framework/adapter-subsystem";import{ToolRegistryToken as w,createSubagentServicePackage as T,createToolContributionProcessor as E,sessionBridgePackage as D,sessionPackage as O,sessionStoragePackage as k,toolRegistryPackage as ee}from"@makaio/framework/services";import{runWorkflowOrchestrator as A}from"@makaio/framework/workflow-engine/workflow-orchestrator";function j(e){return e.on(l.getCapabilities,async t=>{let{adapterName:n,adapterId:r}=t.payload;if(r){await t.next();return}if(n){let r=await e.requestOptional(h.resolveId,{adapterName:n}),i=r.handled?r.data.adapterId:void 0;i&&(t.payload.adapterId=i)}await t.next()},{priority:20})}function M(e){let{coordinator:t,configRepository:n,platformDefaults:r,prepareAuthRuntime:i,runtimeSnapshotHandlerPriority:a,runtimeDefinitionHandlerPriority:o}=e,s=C({configRepository:n,coordinator:t,platformDefaults:r,...i!==void 0&&{prepareAuthRuntime:i},...a!==void 0&&{runtimeSnapshotHandlerPriority:a},...o!==void 0&&{runtimeDefinitionHandlerPriority:o}});return t.registerContributionProcessor(S({getAdapterSubsystemService:()=>t.getExtensionService(x)})),{adapterSubsystemPackage:s}}function N(e){let{bus:t,currentMachineId:n}=e,r=g(t,{currentMachineId:n,listKnownAdapterNames:e.listKnownAdapterNames??(async()=>{let{configs:e}=await t.request(y.listAdapterConfigs,{});return e.map(e=>e.name)})}),i=j(t);return{cleanup:()=>{r.cleanup(),i()}}}function P(e,t){if(!(e instanceof Error))return!1;let{rootPackageName:n,subpath:r}=te(t),i=(r===void 0?[t]:[t,n]).flatMap(e=>[`Cannot find package '${e}'`,`Cannot find module '${e}'`,`Cannot find package "${e}"`,`Cannot find module "${e}"`]),a=e;return(a.code===`ERR_MODULE_NOT_FOUND`||a.code===`MODULE_NOT_FOUND`)&&i.some(t=>e.message.includes(t))||a.code===`ERR_PACKAGE_PATH_NOT_EXPORTED`&&r!==void 0&&e.message.includes(`Package subpath '${r}' is not defined by "exports"`)&&ne(e.message,n)?!0:i.some(t=>e.message.includes(t))}async function F(e){try{return await import(e)}catch(t){if(P(t,e))return null;throw t}}function te(e){let t=e.split(`/`);return e.startsWith(`@`)?{rootPackageName:t.slice(0,2).join(`/`),subpath:t.length>2?`./${t.slice(2).join(`/`)}`:void 0}:{rootPackageName:t[0]??e,subpath:t.length>1?`./${t.slice(1).join(`/`)}`:void 0}}function ne(e,t){let n=t,r=t.replaceAll(`/`,`\\`);return e.includes(`/${n}/package.json`)||e.includes(`\\${r}\\package.json`)}var re=n(((e,t)=>{t.exports={name:`piscina`,version:`5.2.0`,description:`A fast, efficient Node.js Worker Thread Pool implementation`,main:`./dist/main.js`,types:`./dist/index.d.ts`,exports:{types:`./dist/index.d.ts`,import:`./dist/esm-wrapper.mjs`,require:`./dist/main.js`},engines:{node:`>=20.x`},scripts:{build:`tsc && gen-esm-wrapper . dist/esm-wrapper.mjs`,lint:`eslint`,test:`node scripts/run-tests.js`,"test:jest":`jest --config test/jest/jest.config.js`,"test:ci":`npm run lint && npm run build && npm run test:coverage && npm run test:jest`,"test:coverage":`node scripts/run-tests.js --coverage`,prepack:`npm run build`,benchmark:`node --allow-natives-syntax benchmark/index.js --scope all`,"benchmark:ci":`node --allow-natives-syntax benchmark/index.js --scope all --reporter json | jq '.[] | .name, .opsSec'`,"benchmark:simple":`node --allow-natives-syntax benchmark/index.js --scope simple:all`,"benchmark:simple:default":`node --allow-natives-syntax benchmark/index.js --scope simple`,"benchmark:simple:async":`node --allow-natives-syntax benchmark/index.js --scope simple:async`,"benchmark:startup":`node --allow-natives-syntax benchmark/index.js --scope startup`,"benchmark:queue":`node --allow-natives-syntax benchmark/index.js --scope queue`},repository:{type:`git`,url:`git+https://github.com/piscinajs/piscina.git`},keywords:[`fast`,`worker threads`,`thread pool`,`wade wilson`],author:`James M Snell <jasnell@gmail.com>`,contributors:[`Anna Henningsen <anna@addaleax.net>`,`Matteo Collina <matteo.collina@gmail.com>`,`Carlos Fuentes <me@metcoder.dev>`],license:`MIT`,devDependencies:{"@types/jest":`^30.0.0`,"@types/node":`^22.4.1`,"abort-controller":`^3.0.0`,"bench-node":`^0.7.0`,"concat-stream":`^2.0.0`,eslint:`^9.16.0`,"gen-esm-wrapper":`^1.1.1`,glob:`^13.0.1`,jest:`^30.2.0`,neostandard:`^0.13.0`,"ts-jest":`^29.4.6`,tsx:`^4.20.3`,typescript:`5.8.3`},optionalDependencies:{"@napi-rs/nice":`^1.0.4`},bugs:{url:`https://github.com/piscinajs/piscina/issues`},homepage:`https://github.com/piscinajs/piscina#readme`,directories:{example:`examples`,test:`test`}}})),I=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.kFieldCount=e.kResponseCountField=e.kRequestCountField=e.kQueueOptions=e.kValue=e.kTransferable=e.kWorkerData=e.kMovable=void 0,e.kMovable=Symbol(`Piscina.kMovable`),e.kWorkerData=Symbol(`Piscina.kWorkerData`),e.kTransferable=Symbol.for(`Piscina.transferable`),e.kValue=Symbol.for(`Piscina.valueOf`),e.kQueueOptions=Symbol.for(`Piscina.queueOptions`),e.kRequestCountField=0,e.kResponseCountField=1,e.kFieldCount=2})),L=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AbortError=void 0,e.onabort=t,e.AbortError=class extends Error{constructor(e){super(`The task has been aborted`,{cause:e})}get name(){return`AbortError`}};function t(e,t){return`addEventListener`in e?(e.addEventListener(`abort`,t,{once:!0}),()=>e.removeEventListener(`abort`,t)):(e.once(`abort`,t),()=>e.removeListener(`abort`,t))}})),R=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.commonState=t.READY=void 0,t.isTransferable=a,t.isMovable=o,t.markMovable=s,t.maybeFileURLToPath=c,t.getAvailableParallelism=l,t.promiseResolvers=u;let n=e(`node:url`),r=e(`node:os`),i=I();t.READY=`_WORKER_READY`;function a(e){return typeof e==`object`&&!!e&&i.kTransferable in e&&i.kValue in e}function o(e){return a(e)&&e[i.kMovable]===!0}function s(e){Object.defineProperty(e,i.kMovable,{enumerable:!1,configurable:!0,writable:!0,value:!0})}t.commonState={isWorkerThread:!1,workerData:void 0};function c(e){return e.startsWith(`file:`)?(0,n.fileURLToPath)(new n.URL(e)):e}function l(){return(0,r.availableParallelism)()}function u(){if(Promise.withResolvers!=null)return Promise.withResolvers();let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}})),ie=n((t=>{var n=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,`__esModule`,{value:!0}),t.ArrayTaskQueue=void 0;let r=n(e(`node:assert`));t.ArrayTaskQueue=class{constructor(){this.tasks=[]}get size(){return this.tasks.length}shift(){return this.tasks.shift()??null}push(e){this.tasks.push(e)}remove(e){let t=this.tasks.indexOf(e);r.default.notStrictEqual(t,-1),this.tasks.splice(t,1)}}})),ae=n((t=>{var n=t&&t.__classPrivateFieldGet||function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},r=t&&t.__classPrivateFieldSet||function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},i=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},a;Object.defineProperty(t,`__esModule`,{value:!0}),t.FixedQueue=void 0;let o=i(e(`node:assert`)),s=2048,c=s-1;var l=class{constructor(){this.bottom=0,this.top=0,this.list=Array(s),this.next=null}isEmpty(){return this.top===this.bottom}isFull(){return(this.top+1&c)===this.bottom}push(e){this.list[this.top]=e,this.top=this.top+1&c}shift(){let e=this.list[this.bottom];return e===void 0?null:(this.list[this.bottom]=void 0,this.bottom=this.bottom+1&c,e)}remove(e){let t=this.list.indexOf(e);o.default.notStrictEqual(t,-1);let n=t;for(;;){let e=n+1&c;if(this.list[n]=this.list[e],this.list[n]===void 0)break;if(e===t){this.list[n]=void 0;break}n=e}this.top=this.top-1&c}};t.FixedQueue=class{constructor(){a.set(this,0),this.head=this.tail=new l}isEmpty(){return this.head.isEmpty()}push(e){var t;this.head.isFull()&&(this.head=this.head.next=new l),this.head.push(e),r(this,a,(t=n(this,a,`f`),t++,t),`f`)}shift(){var e;let t=this.tail,i=t.shift();return i!==null&&r(this,a,(e=n(this,a,`f`),e--,e),`f`),t.isEmpty()&&t.next!==null&&(this.tail=t.next,t.next=null),i}remove(e){var t;let i=null,o=this.tail;for(;;){if(o.list.includes(e)){o.remove(e),r(this,a,(t=n(this,a,`f`),t--,t),`f`);break}if(o.next===null)break;i=o,o=o.next}o.isEmpty()&&(i===null?o.next!==null&&(this.tail=o.next):o.next===null?this.head=i:i.next=o.next)}get size(){return n(this,a,`f`)}},a=new WeakMap})),oe=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.TaskInfo=t.FixedQueue=t.ArrayTaskQueue=void 0,t.isTaskQueue=l;let n=e(`node:perf_hooks`),r=e(`node:async_hooks`),i=L(),a=R(),o=I();var s=ie();Object.defineProperty(t,`ArrayTaskQueue`,{enumerable:!0,get:function(){return s.ArrayTaskQueue}});var c=ae();Object.defineProperty(t,`FixedQueue`,{enumerable:!0,get:function(){return c.FixedQueue}});function l(e){return typeof e==`object`&&!!e&&`size`in e&&typeof e.shift==`function`&&typeof e.remove==`function`&&typeof e.push==`function`}let u=0;t.TaskInfo=class extends r.AsyncResource{constructor({task:e,transferList:t,filename:r,name:i,abortSignal:s,triggerAsyncId:c},l){super(`Piscina.Task`,{requireManualDestroy:!0,triggerAsyncId:c}),this.workerInfo=null,this.aborted=!1,this._abortListener=()=>{this.aborted=!0},this._abortCleaner=null,this.callback=l,this.task=e,this.transferList=t,(0,a.isMovable)(e)&&(this.transferList??=[],this.transferList=this.transferList.concat(e[o.kTransferable]),this.task=e[o.kValue]),this.filename=r,this.name=i,this.taskId=u++,this.abortSignal=s,this.created=n.performance.now(),this.started=0}onAbort(e){this._abortListener=()=>{this.aborted=!0,e()}}setAbortListener(e){this._abortCleaner=(0,i.onabort)(e,this._abortListener)}releaseTask(){let e=this.task;return this.task=null,e}onResponse(e){}done(e,t){var n;this.runInAsyncScope(this.callback,null,e,t),this.emitDestroy(),(n=this._abortCleaner)==null||n.call(this)}get[o.kQueueOptions](){return this.task?.[o.kQueueOptions]??null}get interface(){return{taskId:this.taskId,filename:this.filename,name:this.name,created:this.created,isAbortable:this.abortSignal!==null,[o.kQueueOptions]:this[o.kQueueOptions]}}}})),z=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Errors=void 0,e.Errors={ThreadTermination:()=>Error(`Terminating worker thread`),FilenameNotProvided:()=>Error(`filename must be provided to run() or in options object`),TaskQueueAtLimit:()=>Error(`Task queue is at limit`),NoTaskQueueAvailable:()=>Error(`No task queue available and all Workers are busy`),CloseTimeout:()=>Error(`Close operation timed out`)}})),B=n((t=>{var n=t&&t.__classPrivateFieldSet||function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},r=t&&t.__classPrivateFieldGet||function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},i,a;Object.defineProperty(t,`__esModule`,{value:!0}),t.PiscinaHistogramHandler=void 0;let o=e(`node:perf_hooks`);t.PiscinaHistogramHandler=class e{constructor(){i.set(this,void 0),a.set(this,void 0),n(this,i,(0,o.createHistogram)(),`f`),n(this,a,(0,o.createHistogram)(),`f`)}get runTimeSummary(){return e.createHistogramSummary(r(this,i,`f`))}get waitTimeSummary(){return e.createHistogramSummary(r(this,a,`f`))}get runTimeCount(){return r(this,i,`f`).count}recordRunTime(t){r(this,i,`f`).record(e.toHistogramIntegerNano(t))}recordWaitTime(t){r(this,a,`f`).record(e.toHistogramIntegerNano(t))}resetWaitTime(){r(this,a,`f`).reset()}resetRunTime(){r(this,i,`f`).reset()}static createHistogramSummary(e){let{mean:t,stddev:n,min:r,max:i}=e;return{average:t/1e3,mean:t/1e3,stddev:n/1e3,min:r/1e3,max:i/1e3,p0_001:e.percentile(.001)/1e3,p0_01:e.percentile(.01)/1e3,p0_1:e.percentile(.1)/1e3,p1:e.percentile(1)/1e3,p2_5:e.percentile(2.5)/1e3,p10:e.percentile(10)/1e3,p25:e.percentile(25)/1e3,p50:e.percentile(50)/1e3,p75:e.percentile(75)/1e3,p90:e.percentile(90)/1e3,p97_5:e.percentile(97.5)/1e3,p99:e.percentile(99)/1e3,p99_9:e.percentile(99.9)/1e3,p99_99:e.percentile(99.99)/1e3,p99_999:e.percentile(99.999)/1e3}}static toHistogramIntegerNano(e){return Math.max(1,Math.trunc(e*1e3))}},i=new WeakMap,a=new WeakMap})),se=n((t=>{var n=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,`__esModule`,{value:!0}),t.AsynchronouslyCreatedResourcePool=t.AsynchronouslyCreatedResource=void 0;let r=n(e(`node:assert`));t.AsynchronouslyCreatedResource=class{constructor(){this.onreadyListeners=[],this.ondestroyListeners=[]}markAsReady(){let e=this.onreadyListeners;(0,r.default)(e!=null),this.onreadyListeners=null;for(let t of e)t()}isReady(){return this.onreadyListeners==null}onReady(e){if(this.onreadyListeners==null){e();return}this.onreadyListeners.push(e)}onDestroy(e){this.ondestroyListeners!=null&&this.ondestroyListeners.push(e)}markAsDestroyed(){let e=this.ondestroyListeners;(0,r.default)(e!=null),this.ondestroyListeners=null;for(let t of e)t()}isDestroyed(){return this.ondestroyListeners==null}},t.AsynchronouslyCreatedResourcePool=class{constructor(e){this.pendingItems=new Set,this.readyItems=new Set,this.maximumUsage=e,this.onAvailableListeners=[],this.onTaskDoneListeners=[]}add(e){this.pendingItems.add(e),e.onReady(()=>{this.pendingItems.has(e)&&(this.pendingItems.delete(e),this.readyItems.add(e),this.maybeAvailable(e))})}delete(e){this.pendingItems.delete(e),this.readyItems.delete(e)}*[Symbol.iterator](){yield*this.pendingItems,yield*this.readyItems}get size(){return this.pendingItems.size+this.readyItems.size}maybeAvailable(e){if(e.currentUsage()<this.maximumUsage)for(let t of this.onAvailableListeners)t(e)}onAvailable(e){this.onAvailableListeners.push(e)}taskDone(e){for(let t=0;t<this.onTaskDoneListeners.length;t++)this.onTaskDoneListeners[t](e)}onTaskDone(e){this.onTaskDoneListeners.push(e)}getCurrentUsage(){let e=0;for(let t of this.readyItems){let n=t.currentUsage();Number.isFinite(n)&&(e+=n)}return e}}})),V=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LeastBusyBalancer=t;function t(e){let{maximumUsage:t}=e;return(e,n)=>{let r=null,i=t;for(let t of n){if(t.currentUsage===0){r=t;break}t.isRunningAbortableTask||e.isAbortable===!1&&t.currentUsage<i&&(r=t,i=t.currentUsage)}return r}}})),H=n((t=>{var n=t&&t.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=t&&t.__exportStar||function(e,t){for(var r in e)r!==`default`&&!Object.prototype.hasOwnProperty.call(t,r)&&n(t,e,r)},i=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,`__esModule`,{value:!0}),t.AsynchronouslyCreatedResourcePool=t.WorkerInfo=void 0;let a=e(`node:worker_threads`),o=e(`node:perf_hooks`),s=i(e(`node:assert`)),c=z(),l=I(),u=B(),d=se();Object.defineProperty(t,`AsynchronouslyCreatedResourcePool`,{enumerable:!0,get:function(){return d.AsynchronouslyCreatedResourcePool}}),r(V(),t),t.WorkerInfo=class extends d.AsynchronouslyCreatedResource{constructor({worker:e,port:t,enableHistogram:n},r){super(),this.idleTimeout=null,this.lastSeenResponseCount=0,this.terminating=!1,this.destroyed=!1;let{filename:i,...s}=e;this.worker=new a.Worker(i,s),this.port=t,this.onMessage=r,this.port.on(`message`,this._handleResponse.bind(this)),this.taskInfos=new Map,this.sharedBuffer=new Int32Array(new SharedArrayBuffer(l.kFieldCount*Int32Array.BYTES_PER_ELEMENT)),this.histogram=n?(0,o.createHistogram)():null}get id(){return this.worker.threadId}onWorkerMessage(e){this.worker.on(`message`,e)}onWorkerError(e){this.worker.on(`error`,e)}onWorkerExit(e){this.worker.on(`exit`,e)}onPortClose(e){this.port.on(`close`,e)}init(e,t){return this.worker.postMessage(e,t),this}workerRef(){return this.worker.ref(),this}workerUnref(){return this.worker.unref(),this}destroy(){if(!(this.terminating||this.destroyed)){this.terminating=!0,this.clearIdleTimeout(),this.worker.terminate(),this.port.close();for(let e of this.taskInfos.values())e.done(c.Errors.ThreadTermination());this.taskInfos.clear(),this.terminating=!1,this.destroyed=!0,this.markAsDestroyed()}}setIdleTimeout(e,t,...n){this.idleTimeout=setTimeout(e,t,...n).unref()}clearIdleTimeout(){this.idleTimeout!=null&&(clearTimeout(this.idleTimeout),this.idleTimeout=null)}ref(){return this.port.ref(),this}unref(){return this.port.unref(),this}_handleResponse(e){var t;(t=this.histogram)==null||t.record(u.PiscinaHistogramHandler.toHistogramIntegerNano(e?.time)),this.onMessage(e),this.taskInfos.size===0&&this.unref()}postTask(e){(0,s.default)(!this.taskInfos.has(e.taskId)),(0,s.default)(!this.terminating&&!this.destroyed);let t={task:e.releaseTask(),taskId:e.taskId,filename:e.filename,name:e.name,histogramEnabled:this.histogram==null?0:1};try{this.port.postMessage(t,e.transferList),queueMicrotask(()=>this.clearIdleTimeout()),e.workerInfo=this,this.taskInfos.set(e.taskId,e),this.ref(),Atomics.add(this.sharedBuffer,l.kRequestCountField,1),Atomics.notify(this.sharedBuffer,l.kRequestCountField,1)}catch(t){e.done(t)}}processPendingMessages(){if(this.destroyed)return;let e=Atomics.load(this.sharedBuffer,l.kResponseCountField);if(e!==this.lastSeenResponseCount){this.lastSeenResponseCount=e;let t;for(;(t=(0,a.receiveMessageOnPort)(this.port))!=null;)this._handleResponse(t.message)}}isRunningAbortableTask(){if(this.taskInfos.size!==1)return!1;let[[,e]]=this.taskInfos;return e.abortSignal!=null}currentUsage(){return this.isRunningAbortableTask()?1/0:this.taskInfos.size}popTask(e){let t=this.taskInfos.get(e)??null;return t!=null&&this.taskInfos.delete(e),t}get interface(){let e=this;return{get id(){return e.worker.threadId},get currentUsage(){return e.currentUsage()},get isRunningAbortableTask(){return e.isRunningAbortableTask()},get histogram(){return e.histogram==null?null:u.PiscinaHistogramHandler.createHistogramSummary(e.histogram)},get terminating(){return e.terminating},get destroyed(){return e.destroyed},[l.kWorkerData]:e}}}})),U=n((t=>{var n=t&&t.__classPrivateFieldSet||function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},r=t&&t.__classPrivateFieldGet||function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},i,a,o,s;Object.defineProperty(t,`__esModule`,{value:!0}),t.workerData=t.isWorkerThread=t.move=t.ArrayTaskQueue=t.FixedQueue=t.version=t.queueOptionsSymbol=t.valueSymbol=t.transferableSymbol=t.Piscina=void 0;let c=e(`node:worker_threads`),l=e(`node:events`),u=e(`node:path`),d=e(`node:util`),f=e(`node:perf_hooks`),p=e(`node:timers/promises`),m=re();Object.defineProperty(t,`version`,{enumerable:!0,get:function(){return m.version}});let h=I();Object.defineProperty(t,`queueOptionsSymbol`,{enumerable:!0,get:function(){return h.kQueueOptions}}),Object.defineProperty(t,`transferableSymbol`,{enumerable:!0,get:function(){return h.kTransferable}}),Object.defineProperty(t,`valueSymbol`,{enumerable:!0,get:function(){return h.kValue}});let g=oe();Object.defineProperty(t,`ArrayTaskQueue`,{enumerable:!0,get:function(){return g.ArrayTaskQueue}}),Object.defineProperty(t,`FixedQueue`,{enumerable:!0,get:function(){return g.FixedQueue}});let _=H(),v=L(),y=B(),b=z(),x=R(),S=(0,x.getAvailableParallelism)(),C={filename:null,name:`default`,minThreads:Math.max(Math.floor(S/2),1),maxThreads:S*1.5,idleTimeout:0,maxQueue:1/0,concurrentTasksPerWorker:1,atomics:`sync`,taskQueue:new g.ArrayTaskQueue,niceIncrement:0,trackUnmanagedFds:!0,closeTimeout:3e4,recordTiming:!0,workerHistogram:!1},w={transferList:void 0,filename:null,signal:null,name:null},T={force:!1};var E=class{constructor(e){i.set(this,void 0),n(this,i,e,`f`)}get[(i=new WeakMap,h.kTransferable)](){return r(this,i,`f`)}get[h.kValue](){return r(this,i,`f`)}},D=class{constructor(e){a.set(this,void 0),n(this,a,e,`f`)}get[(a=new WeakMap,h.kTransferable)](){return r(this,a,`f`).buffer}get[h.kValue](){return r(this,a,`f`)}},O=class{constructor(e,t){this.skipQueue=[],this.completed=0,this.histogram=null,this.start=f.performance.now(),this.inProcessPendingMessages=!1,this.startingUp=!1,this.closingUp=!1,this.workerFailsDuringBootstrap=!1,this.destroying=!1,this.publicInterface=e,this.taskQueue=t.taskQueue??new g.FixedQueue;let n=t.filename?(0,x.maybeFileURLToPath)(t.filename):null;this.options={...C,...t,filename:n,maxQueue:0},this.options.recordTiming&&(this.histogram=new y.PiscinaHistogramHandler),t.maxThreads!==void 0&&this.options.minThreads>=t.maxThreads&&(this.options.minThreads=t.maxThreads),t.minThreads!==void 0&&this.options.maxThreads<=t.minThreads&&(this.options.maxThreads=t.minThreads),t.maxQueue===`auto`?this.options.maxQueue=this.options.maxThreads**2:this.options.maxQueue=t.maxQueue??C.maxQueue,this.balancer=this.options.loadBalancer??(0,_.LeastBusyBalancer)({maximumUsage:this.options.concurrentTasksPerWorker}),this.workers=new _.AsynchronouslyCreatedResourcePool(this.options.concurrentTasksPerWorker),this.workers.onTaskDone(this._onWorkerTaskDone.bind(this)),this.maxCapacity=this.options.maxThreads*this.options.concurrentTasksPerWorker,this.startingUp=!0,this._ensureMinimumWorkers(),this.startingUp=!1,this._needsDrain=!1}_ensureMinimumWorkers(){if(!(this.closingUp||this.destroying))for(;this.workers.size<this.options.minThreads;)this._addNewWorker()}_addNewWorker(){if(this.closingUp===!0)return;let{port1:e,port2:t}=new c.MessageChannel,n=new _.WorkerInfo({worker:{filename:(0,u.resolve)(__dirname,`worker.js`),env:this.options.env,argv:this.options.argv,execArgv:this.options.execArgv,resourceLimits:this.options.resourceLimits,workerData:this.options.workerData,trackUnmanagedFds:this.options.trackUnmanagedFds},port:e,enableHistogram:this.options.workerHistogram},i.bind(this)),r={filename:this.options.filename,name:this.options.name,port:t,sharedBuffer:n.sharedBuffer,atomics:this.options.atomics,niceIncrement:this.options.niceIncrement};n.onDestroy(()=>{this.publicInterface.emit(`workerDestroy`,n.interface)}),n.onWorkerMessage(s.bind(this)),n.onWorkerError(l.bind(this)),n.onWorkerExit(f.bind(this)),n.onPortClose(()=>{n.workerRef()}),this.startingUp===!0?(n.markAsReady(),queueMicrotask(()=>{this.publicInterface.emit(`workerCreate`,n.interface),this._onWorkerReady(n)})):n.onReady(()=>{this.publicInterface.emit(`workerCreate`,n.interface),this._onWorkerReady(n)}),n.init(r,[t]).workerUnref(),this.workers.add(n);function i(e){let{taskId:t,result:r}=e,i=n.popTask(t);if(this.workers.taskDone(n),i==null){let t=Error(`Unexpected message from Worker: ${(0,d.inspect)(e)}`);this.publicInterface.emit(`error`,t)}else i.done(e.error,r);this._processPendingMessages()}function a(){n.currentUsage()===0&&n.unref(),n.isReady()===!1&&n.markAsReady()}function o(e){this.publicInterface.emit(`message`,e)}function s(e){e instanceof Object&&x.READY in e||typeof e==`object`&&e&&x.READY in e?a():o.call(this,e)}function l(e){this._onError(n,e,!1)}function f(e){if(this.destroying===!1){let t=Error(`worker exited with code: ${e}`);this._onError(n,t,!0)}}}_onError(e,t,n){let r=[...e.taskInfos.values()];if(e.taskInfos.clear(),this._removeWorker(e),e.isReady()&&!this.workerFailsDuringBootstrap?this._ensureMinimumWorkers():this.workerFailsDuringBootstrap=!0,r.length>0)for(let e of r)e.done(t,null);else n||this.publicInterface.emit(`error`,t)}_processPendingMessages(){if(!(this.inProcessPendingMessages||this.options.atomics===`disabled`)){this.inProcessPendingMessages=!0;try{for(let e of this.workers)e.processPendingMessages()}finally{this.inProcessPendingMessages=!1}}}_removeWorker(e){e.destroy(),this.workers.delete(e)}_removeTaskFromQueue(e){this.taskQueue.remove(e);let t=this.skipQueue.indexOf(e);t!==-1&&this.skipQueue.splice(t,1)}_onWorkerReady(e){this._onWorkerAvailable(e)}_onWorkerTaskDone(e){this._onWorkerAvailable(e)}_onWorkerAvailable(e){let t=null;for(;this.taskQueue.size>0||this.skipQueue.length>0;){let e=this.skipQueue.shift()||this.taskQueue.shift();if(t??=[...this.workers].map(e=>e.interface),!this._distributeTask(e,t))if(this.workers.size<this.options.maxThreads){this._addNewWorker();continue}else break}this.options.idleTimeout!==1/0&&e.currentUsage()===0&&this.workers.size>this.options.minThreads&&e.setIdleTimeout(()=>{e.currentUsage()===0&&this.workers.size>this.options.minThreads&&this._removeWorker(e)},this.options.idleTimeout)}_distributeTask(e,t){var n;if(e.aborted)return!0;let r=this.balancer(e.interface,t);if(r!=null&&r[h.kWorkerData]!=null){let t=f.performance.now();return(n=this.histogram)==null||n.recordWaitTime(t-e.created),e.started=t,r[h.kWorkerData].postTask(e),queueMicrotask(()=>this._maybeDrain()),!0}return e.abortSignal==null?this.taskQueue.push(e):this.skipQueue.push(e),!1}runTask(e,t){let{filename:n,name:r}=t,{transferList:i=[]}=t;if(n??=this.options.filename,r??=this.options.name,typeof n!=`string`)return Promise.reject(b.Errors.FilenameNotProvided());n=(0,x.maybeFileURLToPath)(n);let a;if(this.closingUp||this.destroying){let e=new AbortController;e.abort(`queue is being terminated`),a=e.signal}else a=t.signal??null;let{promise:o,resolve:s,reject:c}=(0,x.promiseResolvers)(),l=new g.TaskInfo({task:e,transferList:i,filename:n,name:r,abortSignal:a,triggerAsyncId:this.publicInterface.asyncResource.asyncId()},(e,t)=>{var n;this.completed++,l.started&&((n=this.histogram)==null||n.recordRunTime(f.performance.now()-l.started)),e===null?s(t):c(e),queueMicrotask(this._maybeDrain.bind(this))});if(a!=null){if(a.aborted)return c(new v.AbortError(a.reason)),o;l.onAbort(()=>{c(new v.AbortError(a.reason)),l.workerInfo==null?this._removeTaskFromQueue(l):(this._removeWorker(l.workerInfo),this._ensureMinimumWorkers())}),l.setAbortListener(a)}if(this.taskQueue.size>0){let e=this.options.maxQueue+this.pendingCapacity();return this.taskQueue.size>=e?this.options.maxQueue===0?c(b.Errors.NoTaskQueueAvailable()):c(b.Errors.TaskQueueAtLimit()):(this.taskQueue.push(l),this.workers.size<this.options.maxThreads&&this._addNewWorker()),queueMicrotask(this._maybeDrain.bind(this)),o}let u=[...this.workers.readyItems].map(e=>e.interface);return this._distributeTask(l,u)||(this.workers.size<this.options.maxThreads&&this._addNewWorker(),this.options.maxQueue<=0&&this.pendingCapacity()===0&&c(b.Errors.NoTaskQueueAvailable())),queueMicrotask(this._maybeDrain.bind(this)),o}pendingCapacity(){return this.workers.pendingItems.size*this.options.concurrentTasksPerWorker}_maybeDrain(){let{maxCapacity:e}=this,t=this.workers.getCurrentUsage();e===t?(this._needsDrain=!0,queueMicrotask(()=>this.publicInterface.emit(`needsDrain`))):e>t&&this._needsDrain&&(this._needsDrain=!1,queueMicrotask(()=>this.publicInterface.emit(`drain`)))}async destroy(){for(this.destroying=!0;this.skipQueue.length>0;)this.skipQueue.shift().done(Error(`Terminating worker thread`));for(;this.taskQueue.size>0;)this.taskQueue.shift().done(Error(`Terminating worker thread`));let e=[];for(;this.workers.size>0;){let[t]=this.workers;e.push((0,l.once)(t.worker,`exit`)),this._removeWorker(t)}await Promise.allSettled(e),this.destroying=!1}async close(e){if(this.closingUp=!0,e.force){let e=this.skipQueue.length;for(let t=0;t<e;t++){let e=this.skipQueue.shift();e.workerInfo===null?e.done(new v.AbortError(`pool is closed`)):this.skipQueue.push(e)}let t=this.taskQueue.size;for(let e=0;e<t;e++){let e=this.taskQueue.shift();e.workerInfo===null?e.done(new v.AbortError(`pool is closed`)):this.taskQueue.push(e)}}let t=()=>new Promise(e=>{let t=this.workers.size;if(t===0){e();return}let n=0,r=r=>{r.taskInfos.size===0&&n++,t===n&&e()};this.workers.onTaskDone(r);for(let e of this.workers)r(e),this.workers.onTaskDone(r)}),n=async e=>{throw await(0,p.setTimeout)(e,null,{ref:!1}),b.Errors.CloseTimeout()};try{await Promise.race([t(),n(this.options.closeTimeout)])}catch(e){this.publicInterface.emit(`error`,e)}finally{await this.destroy(),this.publicInterface.emit(`close`),this.closingUp=!1}}},k=class e extends l.EventEmitterAsyncResource{constructor(e={}){let t={...e,"__proto__":null};if(super({...t,name:`Piscina`}),o.set(this,void 0),s.set(this,null),typeof t.filename!=`string`&&t.filename!=null)throw TypeError(`options.filename must be a string or null`);if(typeof t.name!=`string`&&t.name!=null)throw TypeError(`options.name must be a string or null`);if(t.minThreads!==void 0&&(typeof t.minThreads!=`number`||t.minThreads<0))throw TypeError(`options.minThreads must be a non-negative integer`);if(t.maxThreads!==void 0&&(typeof t.maxThreads!=`number`||t.maxThreads<1))throw TypeError(`options.maxThreads must be a positive integer`);if(t.minThreads!==void 0&&t.maxThreads!==void 0&&t.minThreads>t.maxThreads)throw RangeError(`options.minThreads and options.maxThreads must not conflict`);if(t.idleTimeout!==void 0&&(typeof t.idleTimeout!=`number`||t.idleTimeout<0))throw TypeError(`options.idleTimeout must be a non-negative integer`);if(t.maxQueue!==void 0&&t.maxQueue!==`auto`&&(typeof t.maxQueue!=`number`||t.maxQueue<0))throw TypeError(`options.maxQueue must be a non-negative integer`);if(t.concurrentTasksPerWorker!==void 0&&(typeof t.concurrentTasksPerWorker!=`number`||t.concurrentTasksPerWorker<1))throw TypeError(`options.concurrentTasksPerWorker must be a positive integer`);if(t.atomics!=null&&(typeof t.atomics!=`string`||![`sync`,`async`,`disabled`].includes(t.atomics)))throw TypeError(`options.atomics should be a value of sync, sync or disabled.`);if(t.resourceLimits!==void 0&&(typeof t.resourceLimits!=`object`||t.resourceLimits===null))throw TypeError(`options.resourceLimits must be an object`);if(t.taskQueue!==void 0&&!(0,g.isTaskQueue)(t.taskQueue))throw TypeError(`options.taskQueue must be a TaskQueue object`);if(t.niceIncrement!==void 0&&(typeof t.niceIncrement!=`number`||t.niceIncrement<0&&process.platform!==`win32`))throw TypeError(`options.niceIncrement must be a non-negative integer on Unix systems`);if(t.trackUnmanagedFds!==void 0&&typeof t.trackUnmanagedFds!=`boolean`)throw TypeError(`options.trackUnmanagedFds must be a boolean value`);if(t.closeTimeout!==void 0&&(typeof t.closeTimeout!=`number`||t.closeTimeout<0))throw TypeError(`options.closeTimeout must be a non-negative integer`);if(t.loadBalancer!==void 0&&(typeof t.loadBalancer!=`function`||t.loadBalancer.length<1))throw TypeError(`options.loadBalancer must be a function with at least two args`);if(t.workerHistogram!==void 0&&typeof t.workerHistogram!=`boolean`)throw TypeError(`options.workerHistogram must be a boolean`);n(this,o,new O(this,t),`f`)}run(e,t=w){if(typeof t!=`object`||!t)return Promise.reject(TypeError(`options must be an object`));let{transferList:n,signal:i}=t,a=Object.prototype.hasOwnProperty.call(t,`filename`)?t.filename:null,s=Object.prototype.hasOwnProperty.call(t,`name`)?t.name:null;return n!==void 0&&!Array.isArray(n)?Promise.reject(TypeError(`transferList argument must be an Array`)):a!=null&&typeof a!=`string`?Promise.reject(TypeError(`filename argument must be a string`)):s!=null&&typeof s!=`string`?Promise.reject(TypeError(`name argument must be a string`)):i!=null&&typeof i!=`object`?Promise.reject(TypeError(`signal argument must be an object`)):r(this,o,`f`).runTask(e,{transferList:n,filename:a,name:s,signal:i})}async close(e=T){if(typeof e!=`object`||!e)throw TypeError(`options must be an object`);let{force:t}=e;return t!==void 0&&typeof t!=`boolean`?Promise.reject(TypeError(`force argument must be a boolean`)):(t??=T.force,r(this,o,`f`).close({force:t}))}destroy(){return r(this,o,`f`).destroy()}[(o=new WeakMap,s=new WeakMap,Symbol.dispose)](){this.close()}[Symbol.asyncDispose](){return this.close()}get maxThreads(){return r(this,o,`f`).options.maxThreads}get minThreads(){return r(this,o,`f`).options.minThreads}get options(){return r(this,o,`f`).options}get threads(){let e=[];for(let t of r(this,o,`f`).workers)e.push(t.worker);return e}get idleThreads(){let e=0;for(let t of r(this,o,`f`).workers.readyItems)t.currentUsage()===0&&e++;return e}get queueSize(){let e=r(this,o,`f`);return Math.max(e.taskQueue.size+e.skipQueue.length-e.pendingCapacity(),0)}get completed(){return r(this,o,`f`).completed}get histogram(){if(r(this,s,`f`)==null){let e={get runTime(){return this.histogram?.runTimeSummary},get waitTime(){return this.histogram?.waitTimeSummary},resetRunTime(){var e;(e=this.histogram)==null||e.resetRunTime()},resetWaitTime(){var e;(e=this.histogram)==null||e.resetWaitTime()}};Object.defineProperty(e,`histogram`,{value:r(this,o,`f`).histogram,writable:!1,enumerable:!1,configurable:!1}),n(this,s,e,`f`)}return r(this,s,`f`)}get utilization(){if(r(this,o,`f`).histogram==null)return 0;let e=r(this,o,`f`).histogram.runTimeCount;if(e===0)return 0;let t=this.duration*r(this,o,`f`).options.maxThreads;return r(this,o,`f`).histogram.runTimeSummary.mean/1e3*e/t}get duration(){return f.performance.now()-r(this,o,`f`).start}get needsDrain(){return r(this,o,`f`)._needsDrain}static get isWorkerThread(){return x.commonState.isWorkerThread}static get workerData(){return x.commonState.workerData}static get version(){return m.version}static get Piscina(){return e}static get FixedQueue(){return g.FixedQueue}static get ArrayTaskQueue(){return g.ArrayTaskQueue}static move(e){return typeof e==`object`&&e&&typeof e!=`function`&&((0,x.isTransferable)(e)||(e=d.types.isArrayBufferView(e)?new D(e):new E(e)),(0,x.markMovable)(e)),e}static get transferableSymbol(){return h.kTransferable}static get valueSymbol(){return h.kValue}static get queueOptionsSymbol(){return h.kQueueOptions}};t.default=k,t.Piscina=k,t.move=k.move,t.isWorkerThread=k.isWorkerThread,t.workerData=k.workerData})),W=t(n(((e,t)=>{t.exports=(e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(U()).default}))(),1),G=W.default;W.default.ArrayTaskQueue,W.default.FixedQueue,W.default.Piscina,W.default.isWorkerThread,W.default.move,W.default.queueOptionsSymbol,W.default.transferableSymbol,W.default.valueSymbol,W.default.version,W.default.workerData;var K=class{pool;constructor(e){this.pool=new G({filename:e.workerEntry,maxThreads:e.maxConcurrency??4,idleTimeout:e.idleTimeoutMs??3e4})}async run(e,t){return this.pool.run(e,{signal:t})}onMessage(e){return this.pool.on(`message`,e),()=>this.pool.off(`message`,e)}async dispose(){await this.pool.destroy()}},q=class{options;manifest;pool;constructor(e){this.options=e,this.manifest=e.manifest}async run(e,t,n){return this.pool??=new K(this.options),this.pool.run({config:e,manifest:n??this.manifest},t)}runWithReadiness(e,t,n){this.pool??=new K(this.options);let r=this.pool,a,o=!1,s,c=new Promise((t,n)=>{s=n,a=r.onMessage(n=>{i(n)&&(n.executionId!==e.executionId||n.cancelSubject!==e.cancelSubject||(o=!0,a?.(),t(n)))})}),l=r.run({config:e,manifest:n??this.manifest},t);return l.then(()=>{o||(o=!0,a?.(),s(Error(`Workflow worker completed before ready signal: ${e.executionId}`)))},e=>{o||(o=!0,a?.(),s(e instanceof Error?e:Error(String(e))))}),{result:l,ready:c}}async dispose(){await this.pool?.dispose()}};function J(e){return e.mode===`source`?s(e.moduleDir,`workflow-worker`,`worker-entry.ts`):s(e.moduleDir,`workflow-worker`,`worker-entry.mjs`)}function ce(e,t){let n=t.executionHints?.requirements?.capabilities??[];if(n.length===0)return e;let r=e?.customCapabilities??[];return{...e,customCapabilities:[...new Set([...r,...n])]}}var Y=class{options;constructor(e){this.options=e}run(e,t,n,r){let i=n??this.options.manifest,a=ce(this.options.requirements,e),o=r?.dispatchMetadata;return this.options.dispatch({config:e,...i!==void 0&&{manifest:i},...a!==void 0&&{requirements:a},...o!==void 0&&{metadata:o}},t)}},X=class{#e;constructor(e){this.#e=e.bus}async run(e,t,n){let i=m.parse(e),o=await r(i);return A({config:await a(i,o,this.#e,t),loaded:o,bus:this.#e,signal:t})}};function le(){return{packages:[]}}function ue(e){let t=o(e.runtimeModuleDir)===`src`?`source`:`dist`,n=Z({moduleDir:e.runtimeModuleDir,defaultWorkerEntryMode:t,runner:e.workflowRunner,bus:e.bus});return{...n!==void 0&&{workflowRunner:n},executorConfig:{busUrl:e.busUrl,busAuth:{kind:`none`},platformDefaults:e.platformDefaults,makaioHome:e.makaioHome}}}function Z(e){let{runner:t}=e;if(t)switch(t.mode){case void 0:case`in-process`:if(e.bus===void 0)throw Error(`InProcessWorkflowRunner requires a bus instance. Pass 'bus' to createNodeWorkflowRunner when runner.mode is 'in-process'.`);return new X({bus:e.bus});case`worker-node`:{let n=e.bus,r=t.dispatch??(n===void 0?void 0:(e,t)=>n.request(p.dispatch,{config:e.config,manifest:e.manifest,requirements:e.requirements,metadata:e.metadata},{signal:t}));if(r===void 0)throw Error(`WorkerNodeRunner requires either a dispatch function or a bus instance. Pass 'bus' to createNodeWorkflowRunner when runner.mode is 'worker-node'.`);return new Y({dispatch:r,...t.manifest!==void 0&&{manifest:t.manifest},...t.requirements!==void 0&&{requirements:t.requirements}})}case`piscina`:return new q({workerEntry:t.workerEntry??J({moduleDir:e.moduleDir,mode:t.workerEntryMode??e.defaultWorkerEntryMode}),manifest:t.manifest??le(),maxConcurrency:t.maxConcurrency,idleTimeoutMs:t.idleTimeoutMs})}}function Q(e){return e instanceof Error?e:Error(String(e??`WorkerNode wait aborted`))}function de(e){return typeof e.runWithReadiness==`function`}const $={persistentStorage:!0,customCapabilities:[`workflow.local-runtime`,`workflow.thin-runner`],suspensionStrategy:`wait-in-process`};var fe=class{options;environment=`piscina`;baseCapabilities;constructor(e){this.options=e,this.baseCapabilities=f.parse({...$,...e.baseCapabilities,suspensionStrategy:e.baseCapabilities?.suspensionStrategy??$.suspensionStrategy})}get id(){return this.options.id}get displayName(){return this.options.displayName}async provision(e){let t=new AbortController,n=de(this.options.runner)?this.options.runner.runWithReadiness(e.workerConfig,t.signal,e.workerManifest):{result:this.options.runner.run(e.workerConfig,t.signal,e.workerManifest),ready:void 0},r=n.result,i=n.ready?.then(e=>({adapters:e.adapters}));return i?.catch(()=>void 0),r.catch(()=>void 0),{nodeId:e.nodeId,...i!==void 0&&{ready:i},waitForResult:async e=>{if(e.aborted)return t.abort(e.reason),Promise.reject(Q(e.reason));let n,i=new Promise((e,t)=>{n=t}),a=()=>{t.abort(e.reason),n(Q(e.reason))};e.addEventListener(`abort`,a,{once:!0});try{return await Promise.race([r,i])}finally{e.removeEventListener(`abort`,a)}},cancel:e=>(t.abort(e??`WorkerNode cancelled`),Promise.resolve()),terminate:()=>(t.abort(`WorkerNode terminated`),Promise.resolve())}}};async function pe(e){let t=c();t.registerNamespaces([...u,...d]);let{context:n}=e,r=new _(t,{surface:`headless`,extensionContextBase:{cwd:n.cwd,platform:n.platform,homedir:n.homedir,makaioHome:n.makaioHome,username:n.username,machineId:n.machineId,tryImport:F}}),i,a,o=()=>(a??=(async()=>{try{i?.cleanup()}finally{i=void 0;try{await r.shutdown()}finally{await t.disconnect()}}})(),a);try{await e.connectAuthority(t);let a=[...e.contributedPackages,...await e.loadContributedPackages?.(t)??[]],{adapterSubsystemPackage:s}=M({coordinator:r,configRepository:e.configRepository,platformDefaults:{cwd:n.cwd},runtimeSnapshotHandlerPriority:1,runtimeDefinitionHandlerPriority:1,...e.prepareAuthRuntime!==void 0&&{prepareAuthRuntime:e.prepareAuthRuntime}}),c=b({definitions:a.flatMap(e=>e.clients??[]),binaryResolutionPolicy:`global-only`});r.registerContributionProcessor(E()),r.load([k,D,O,T(1),ee,c,s,...a]),await r.startAll(),i=N({bus:t,currentMachineId:n.machineId});let l=r.getExtensionService(w);if(l===void 0)throw Error(`Isolated workflow tool registry did not start.`);for(let t of e.toolsets)await l.register(t);return await t.emit(v.ready,{machineId:n.machineId}),{bus:t,coordinator:r,machineId:n.machineId,shutdown:o}}catch(e){throw await o().catch(()=>void 0),e}}export{X as a,q as c,N as d,M as f,ue as i,P as l,fe as n,Y as o,j as p,Z as r,J as s,pe as t,F as u};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@makaio/framework",
3
- "version": "1.0.0-dev-1783940945655",
3
+ "version": "1.0.0-dev-1783973359164",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/makaio-ai/makaio-framework.git",
@@ -29,12 +29,6 @@
29
29
  "ws": "^8.21.0",
30
30
  "zod": "4.4.3"
31
31
  },
32
- "peerDependencies": {
33
- "react": "^18.0.0 || ^19.0.0",
34
- "react-dom": "^18.0.0 || ^19.0.0",
35
- "react-resizable": "3.1.3",
36
- "vitest": "^4.1.0"
37
- },
38
32
  "peerDependenciesMeta": {
39
33
  "react": {
40
34
  "optional": true
@@ -531,5 +525,12 @@
531
525
  "types": "./dist/utils/workspace-root.d.mts",
532
526
  "default": "./dist/utils/workspace-root.mjs"
533
527
  }
528
+ },
529
+ "private": false,
530
+ "peerDependencies": {
531
+ "react": "^18.0.0 || ^19.0.0",
532
+ "react-dom": "^18.0.0 || ^19.0.0",
533
+ "react-resizable": "3.1.3",
534
+ "vitest": "^4.1.0"
534
535
  }
535
- }
536
+ }
@@ -1 +0,0 @@
1
- import{o as e}from"./chunk-DTipWd-i.mjs";import{t}from"./ajv-DfHhgdS5.mjs";import{z as n}from"zod";import{execFile as r}from"node:child_process";import{isAbsolute as i,relative as a,resolve as o}from"node:path";import{realpathSync as s}from"node:fs";import{localSubject as c}from"@makaio/framework/core";import{NoHandlerError as l}from"@makaio/framework/bus";import{AgentSubjects as u,ArtifactSubjects as d,ExecutionLinkListQuerySchema as f,ExecutionLinkSchema as p,ExecutionListQuerySchema as m,ExecutionStatusSchema as h,ExecutionsByArtifactRefsQuerySchema as g,GateInstanceListQuerySchema as _,JsonPatchOperationSchema as v,JsonValueSchema as y,SessionSubjects as b,SpanRecordSchema as x,SubagentSubjects as S,WORKFLOW_CANCELLED_REASON as ee,WorkLogFrameEntrySchema as te,WorkerNodeSubjects as ne,WorkflowDefinitionSchema as re,WorkflowError as ie,WorkflowErrorCode as ae,WorkflowExecutionSchema as C,WorkflowFrameStateSchema as oe,WorkflowGateInstanceSchema as w,WorkflowListQuerySchema as se,WorkflowRunContextSchema as ce,WorkflowSchemas as le,WorkflowSubjects as ue,WorkflowSubjects as T,WorkflowWorkerSourceSchema as de,createStepCancelSubject as fe,walkWorkflowDefinition as pe}from"@makaio/framework/contracts";import{index as E,primaryKey as D,uniqueIndex as me}from"drizzle-orm/sqlite-core";import{index as O,primaryKey as he,uniqueIndex as ge}from"drizzle-orm/pg-core";import{defineDualTable as k}from"@makaio/framework/storage/drizzle";import{sql as _e}from"drizzle-orm";import{createStorageNamespaceDefinition as ve}from"@makaio/framework/storage";import{evaluateSync as A,resolveTemplate as j}from"@makaio/framework/expression";import*as ye from"node:os";function be(e){return{scopeType:e.textEnum(`scope_type`,{enum:[`global`,`workspace`,`session`,`external`]}).notNull().$type(),scopeKind:e.text(`scope_kind`).notNull().default(``),scopeId:e.text(`scope_id`).notNull().default(``)}}const xe=k(`workflow_definitions`,e=>({id:e.text(`id`).primaryKey(),name:e.text(`name`).notNull(),description:e.text(`description`),root:e.jsonCol(`root`).notNull(),inputSchema:e.jsonCol(`input_schema`),configSchema:e.jsonCol(`config_schema`),outputSchema:e.jsonCol(`output_schema`),state:e.jsonCol(`state`),artifact:e.jsonCol(`artifact`),triggers:e.jsonCol(`triggers`),...be(e),createdAt:e.epochMs(`created_at`).notNull(),updatedAt:e.epochMs(`updated_at`).notNull(),canvasLayout:e.jsonCol(`canvas_layout`),source:e.jsonCol(`source`),executionHints:e.jsonCol(`execution_hints`)}),{sqlite:e=>[me(`uniq_workflow_definitions_name_scope`).on(e.name,e.scopeType,e.scopeKind,e.scopeId),E(`idx_workflow_definitions_scope`).on(e.scopeType,e.scopeKind,e.scopeId)],postgres:e=>[ge(`uniq_workflow_definitions_name_scope`).on(e.name,e.scopeType,e.scopeKind,e.scopeId),O(`idx_workflow_definitions_scope`).on(e.scopeType,e.scopeKind,e.scopeId)]}),Se=xe.sqlite,M=k(`workflow_executions`,e=>({id:e.text(`id`).primaryKey(),workflowId:e.text(`workflow_id`).notNull(),coordinatorSessionId:e.text(`coordinator_session_id`),status:e.textEnum(`status`,{enum:[`pending`,`running`,`paused`,`completed`,`failed`,`cancelled`]}).notNull(),inputs:e.jsonCol(`inputs`),error:e.text(`error`),reason:e.text(`reason`),startedAt:e.epochMs(`started_at`).notNull(),completedAt:e.epochMs(`completed_at`),externalSettlementFingerprint:e.text(`external_settlement_fingerprint`),externalRegistrationFrameId:e.text(`external_registration_frame_id`),triggerPayload:e.jsonCol(`trigger_payload`),artifactKind:e.text(`artifact_kind`),artifactId:e.text(`artifact_id`),...be(e)}),{sqlite:e=>[E(`idx_workflow_executions_status`).on(e.status),E(`idx_workflow_executions_scope_started`).on(e.scopeType,e.scopeKind,e.scopeId,e.startedAt),E(`idx_workflow_executions_workflow_started`).on(e.workflowId,e.startedAt),E(`idx_workflow_executions_artifact`).on(e.artifactKind,e.artifactId,e.startedAt)],postgres:e=>[O(`idx_workflow_executions_status`).on(e.status),O(`idx_workflow_executions_scope_started`).on(e.scopeType,e.scopeKind,e.scopeId,e.startedAt),O(`idx_workflow_executions_workflow_started`).on(e.workflowId,e.startedAt),O(`idx_workflow_executions_artifact`).on(e.artifactKind,e.artifactId,e.startedAt)]}),Ce=M.sqlite,we=k(`workflow_execution_frames`,e=>({frameId:e.text(`frame_id`).primaryKey(),executionId:e.text(`execution_id`).notNull().references(()=>M.columnPair(`id`),{onDelete:`cascade`}),nodeId:e.text(`node_id`).notNull(),nodeType:e.text(`node_type`).notNull().$type(),path:e.jsonCol(`path`).notNull(),parentFrameId:e.text(`parent_frame_id`),status:e.text(`status`).notNull().default(`pending`).$type(),attempt:e.int4(`attempt`).notNull().default(0),iteration:e.int4(`iteration`),branchKey:e.text(`branch_key`),output:e.jsonCol(`output`),outputPresent:e.bool(`output_present`).notNull().default(!1),error:e.text(`error`),startedAt:e.epochMs(`started_at`),completedAt:e.epochMs(`completed_at`)}),{sqlite:e=>[E(`idx_workflow_execution_frames_execution`).on(e.executionId),E(`idx_workflow_execution_frames_parent`).on(e.parentFrameId)],postgres:e=>[O(`idx_workflow_execution_frames_execution`).on(e.executionId),O(`idx_workflow_execution_frames_parent`).on(e.parentFrameId)]}),Te=we.sqlite,Ee=k(`workflow_gate_instances`,e=>({id:e.text(`id`).primaryKey(),executionId:e.text(`execution_id`).notNull().references(()=>M.columnPair(`id`),{onDelete:`cascade`}),nodeId:e.text(`node_id`).notNull(),frameId:e.text(`frame_id`).notNull(),schema:e.jsonCol(`schema`).notNull(),prompt:e.text(`prompt`),status:e.text(`status`).notNull().default(`waiting`).$type(),autoAction:e.textEnum(`auto_action`,{enum:[`approve`,`reject`]}).notNull().default(`reject`),timeoutMs:e.int4(`timeout_ms`),resumeData:e.jsonCol(`resume_data`),reason:e.text(`reason`),resumeDataPresent:e.bool(`resume_data_present`).notNull().default(!1),createdAt:e.epochMs(`created_at`).notNull(),resolvedAt:e.epochMs(`resolved_at`)}),{sqlite:e=>[E(`idx_workflow_gate_instances_execution`).on(e.executionId),E(`idx_workflow_gate_instances_frame`).on(e.frameId)],postgres:e=>[O(`idx_workflow_gate_instances_execution`).on(e.executionId),O(`idx_workflow_gate_instances_frame`).on(e.frameId)]}),De=Ee.sqlite,Oe=k(`workflow_step_spans`,e=>({executionId:e.text(`execution_id`).notNull().references(()=>M.columnPair(`id`),{onDelete:`cascade`}),frameId:e.text(`frame_id`).notNull(),stepId:e.text(`step_id`).notNull(),stepType:e.text(`step_type`).notNull(),status:e.text(`status`).$type().notNull(),startedAt:e.epochMs(`started_at`),completedAt:e.epochMs(`completed_at`),durationMs:e.int4(`duration_ms`),inputTokens:e.int4(`input_tokens`),outputTokens:e.int4(`output_tokens`),estimatedCost:e.float8(`estimated_cost`),toolCallCount:e.int4(`tool_call_count`),input:e.text(`input`),output:e.text(`output`)}),{sqlite:e=>[D({columns:[e.executionId,e.frameId]}),E(`idx_workflow_step_spans_status`).on(e.status)],postgres:e=>[he({columns:[e.executionId,e.frameId]}),O(`idx_workflow_step_spans_status`).on(e.status)]}),ke=Oe.sqlite,Ae=k(`workflow_execution_links`,e=>({sourceExecutionId:e.text(`source_execution_id`).notNull().references(()=>M.columnPair(`id`),{onDelete:`cascade`}),targetExecutionId:e.text(`target_execution_id`).notNull().references(()=>M.columnPair(`id`),{onDelete:`cascade`}),linkType:e.text(`link_type`).$type().notNull(),metadata:e.jsonCol(`metadata`)}),{sqlite:e=>[D({columns:[e.sourceExecutionId,e.targetExecutionId]}),E(`idx_workflow_execution_links_target`).on(e.targetExecutionId)],postgres:e=>[he({columns:[e.sourceExecutionId,e.targetExecutionId]}),O(`idx_workflow_execution_links_target`).on(e.targetExecutionId)]}),je=Ae.sqlite,Me=k(`workflow_run_contexts`,e=>({executionId:e.text(`execution_id`).primaryKey().references(()=>M.columnPair(`id`),{onDelete:`cascade`}),workflowId:e.text(`workflow_id`).notNull(),coordinatorSessionId:e.text(`coordinator_session_id`).notNull(),sourceKind:e.text(`source_kind`).notNull(),sourcePath:e.text(`source_path`),sourceFilename:e.text(`source_filename`),sourceCode:e.text(`source_code`),definitionSnapshot:e.jsonCol(`definition_snapshot`),workerManifest:e.jsonCol(`worker_manifest`).notNull(),inputs:e.jsonCol(`inputs`),config:e.jsonCol(`config`).notNull().default(_e`'{}'`),triggerPayload:e.jsonCol(`trigger_payload`).notNull(),artifactRef:e.jsonCol(`artifact_ref`),executionHints:e.jsonCol(`execution_hints`),dispatchMetadata:e.jsonCol(`dispatch_metadata`),scopeType:e.textEnum(`scope_type`,{enum:[`global`,`workspace`,`session`,`external`]}).notNull().default(`global`).$type(),scopeKind:e.text(`scope_kind`).notNull().default(``),scopeId:e.text(`scope_id`).notNull().default(``),cancelSubject:e.text(`cancel_subject`).notNull(),context:e.jsonCol(`context`).notNull(),env:e.jsonCol(`env`).notNull(),createdAt:e.epochMs(`created_at`).notNull(),suspensionStrategy:e.text(`suspension_strategy`).$type()}),{sqlite:e=>[E(`idx_run_contexts_workflow`).on(e.workflowId)],postgres:e=>[O(`idx_run_contexts_workflow`).on(e.workflowId)]}),Ne=Me.sqlite,Pe=k(`worklog_summaries`,e=>({executionId:e.text(`execution_id`).primaryKey().references(()=>M.columnPair(`id`),{onDelete:`cascade`}),workflowId:e.text(`workflow_id`).notNull(),workflowName:e.text(`workflow_name`),status:e.textEnum(`status`,{enum:[`pending`,`running`,`paused`,`completed`,`failed`,`cancelled`]}).notNull(),startedAt:e.epochMs(`started_at`).notNull(),completedAt:e.epochMs(`completed_at`),durationMs:e.int4(`duration_ms`),totalInputTokens:e.int4(`total_input_tokens`),totalOutputTokens:e.int4(`total_output_tokens`),totalEstimatedCost:e.float8(`total_estimated_cost`),error:e.text(`error`),failedNodeId:e.text(`failed_node_id`)}),{sqlite:e=>[E(`idx_worklog_summaries_workflow_started`).on(e.workflowId,e.startedAt),E(`idx_worklog_summaries_status`).on(e.status)],postgres:e=>[O(`idx_worklog_summaries_workflow_started`).on(e.workflowId,e.startedAt),O(`idx_worklog_summaries_status`).on(e.status)]}),Fe=Pe.sqlite,Ie=k(`worklog_frame_entries`,e=>({frameId:e.text(`frame_id`).primaryKey(),executionId:e.text(`execution_id`).notNull().references(()=>M.columnPair(`id`),{onDelete:`cascade`}),nodeId:e.text(`node_id`).notNull(),nodeType:e.text(`node_type`).notNull().$type(),path:e.jsonCol(`path`).notNull(),status:e.textEnum(`status`,{enum:[`pending`,`running`,`waiting`,`completed`,`failed`,`skipped`,`cancelled`]}).notNull(),attempt:e.int4(`attempt`).notNull().default(0),iteration:e.int4(`iteration`),branchKey:e.text(`branch_key`),startedAt:e.epochMs(`started_at`),completedAt:e.epochMs(`completed_at`),durationMs:e.int4(`duration_ms`),inputTokens:e.int4(`input_tokens`),outputTokens:e.int4(`output_tokens`),estimatedCost:e.float8(`estimated_cost`),error:e.text(`error`)}),{sqlite:e=>[E(`idx_worklog_frame_entries_execution`).on(e.executionId)],postgres:e=>[O(`idx_worklog_frame_entries_execution`).on(e.executionId)]}),Le=Ie.sqlite,Re=k(`worklog_artifact_writes`,e=>({id:e.text(`id`).primaryKey(),executionId:e.text(`execution_id`).notNull().references(()=>M.columnPair(`id`),{onDelete:`cascade`}),frameId:e.text(`frame_id`).notNull(),nodeId:e.text(`node_id`).notNull(),artifact:e.jsonCol(`artifact`).notNull(),revision:e.text(`revision`),writtenAt:e.epochMs(`written_at`).notNull()}),{sqlite:e=>[E(`idx_worklog_artifact_writes_execution`).on(e.executionId)],postgres:e=>[O(`idx_worklog_artifact_writes_execution`).on(e.executionId)]}),ze=Re.sqlite,Be=k(`worklog_gate_events`,e=>({id:e.text(`id`).primaryKey(),executionId:e.text(`execution_id`).notNull().references(()=>M.columnPair(`id`),{onDelete:`cascade`}),nodeId:e.text(`node_id`).notNull(),frameId:e.text(`frame_id`).notNull(),status:e.textEnum(`status`,{enum:[`waiting`,`resumed`,`rejected`,`timed-out`,`cancelled`]}).notNull().$type(),prompt:e.text(`prompt`),openedAt:e.epochMs(`opened_at`).notNull(),resolvedAt:e.epochMs(`resolved_at`),resumeData:e.jsonCol(`resume_data`)}),{sqlite:e=>[E(`idx_worklog_gate_events_execution`).on(e.executionId),E(`idx_worklog_gate_events_status`).on(e.status)],postgres:e=>[O(`idx_worklog_gate_events_execution`).on(e.executionId),O(`idx_worklog_gate_events_status`).on(e.status)]}),Ve=Be.sqlite,He=k(`workflow_execution_state`,e=>({executionId:e.text(`execution_id`).primaryKey().references(()=>M.columnPair(`id`),{onDelete:`cascade`}),sequence:e.int4(`sequence`).notNull().default(0),value:e.jsonCol(`value`).notNull(),updatedAt:e.epochMs(`updated_at`).notNull()})),Ue=He.sqlite,We=k(`workflow_execution_state_events`,e=>({executionId:e.text(`execution_id`).notNull().references(()=>M.columnPair(`id`),{onDelete:`cascade`}),sequence:e.int4(`sequence`).notNull(),patch:e.jsonCol(`patch`).notNull(),value:e.jsonCol(`value`).notNull(),createdAt:e.epochMs(`created_at`).notNull()}),{sqlite:e=>[D({columns:[e.executionId,e.sequence]})],postgres:e=>[he({columns:[e.executionId,e.sequence]})]}),Ge=We.sqlite,Ke=n.object({executionId:n.string().min(1),status:h.optional(),error:n.string().nullable().optional(),reason:n.string().nullable().optional(),completedAt:n.number().nullable().optional()}),qe=n.enum([`completed`,`failed`,`cancelled`]),Je=te.extend({status:n.literal(`running`),startedAt:n.number().int().nonnegative()}),Ye=te.extend({status:qe,startedAt:n.number().int().nonnegative(),completedAt:n.number().int().nonnegative(),durationMs:n.number().int().nonnegative()}),Xe=ve(`workflow`,{schemas:{get:{request:n.object({id:n.string()}),response:n.object({workflow:re.nullable()})},set:{request:n.object({workflow:re}),response:n.object({id:n.string()})},delete:{request:n.object({id:n.string()}),response:n.object({deleted:n.boolean()})},list:{request:se,response:n.object({workflows:n.array(re)})},getExecution:{request:n.object({executionId:n.string()}),response:n.object({execution:C.nullable()})},setExecution:{request:n.object({execution:C}),response:n.object({id:n.string()})},setExecutionStart:{request:n.object({execution:C,runContext:ce,initialState:y.optional(),executionLinks:n.array(p).optional()}),response:n.object({id:n.string(),executionId:n.string()})},setExternalExecutionStart:c({request:n.object({execution:C.extend({status:n.literal(`running`)}),frame:Je.optional()}),response:n.object({executionId:n.string(),frameId:n.string().optional()})}),settleExternalExecution:c({request:n.object({executionId:n.string().min(1),status:qe,error:n.string().min(1).optional(),reason:n.string().min(1).optional(),completedAt:n.number().int().nonnegative().optional(),frame:Ye.optional()}),response:n.object({success:n.boolean()})}),updateExecution:{request:Ke,response:n.object({success:n.boolean()})},cancelPausedExecution:{request:n.object({executionId:n.string().min(1),completedAt:n.number(),reason:n.string().optional()}),response:n.object({cancelled:n.boolean(),gates:n.array(w.extend({status:n.literal(`cancelled`)}))})},listExecutions:{request:m,response:n.object({executions:n.array(C)})},listExecutionsByArtifactRefs:{request:g,response:n.object({executionsByRef:n.record(n.string(),n.array(C))})},setFrame:{request:n.object({executionId:n.string().min(1),frame:oe}),response:n.object({frameId:n.string()})},getFrame:{request:n.object({frameId:n.string().min(1)}),response:n.object({frame:oe.nullable()})},listFrames:{request:n.object({executionId:n.string().min(1)}),response:n.object({frames:n.array(oe)})},setGateInstance:{request:n.object({gate:w}),response:n.object({id:n.string()})},resolveWaitingGateInstance:{request:n.object({gate:w.extend({status:n.enum([`resumed`,`rejected`])})}),response:n.object({accepted:n.boolean()})},restorePausedGateResumeState:{request:n.object({execution:C.extend({status:n.literal(`paused`)}),gate:w.extend({status:n.literal(`waiting`)})}),response:n.object({executionId:n.string(),gateId:n.string()})},getGateInstance:{request:n.object({executionId:n.string().min(1),nodeId:n.string().min(1),frameId:n.string().min(1).optional()}),response:n.object({gate:w.nullable()})},listGateInstances:{request:_,response:n.object({gates:n.array(w)})},listPausedGateTimeouts:c({request:n.object({}),response:n.object({gates:n.array(w)})}),setSpan:{request:n.object({span:x}),response:n.object({id:n.string()})},listSpans:{request:n.object({executionId:n.string()}),response:n.object({spans:n.array(x)})},setExecutionLink:{request:n.object({link:p}),response:n.object({id:n.string()})},listExecutionLinks:{request:f,response:n.object({links:n.array(p)})},setRunContext:c({request:n.object({runContext:ce}),response:n.object({executionId:n.string()})}),getRunContext:c({request:n.object({executionId:n.string().min(1)}),response:n.object({runContext:ce.nullable()})}),initializeState:c({request:n.object({executionId:n.string().min(1),initialValue:y}),response:n.object({})}),getState:c({request:n.object({executionId:n.string().min(1)}),response:n.object({state:n.object({executionId:n.string().min(1),sequence:n.number().int().nonnegative(),value:y}).nullable()})}),patchState:c({request:n.object({executionId:n.string().min(1),expectedSequence:n.number().int().nonnegative(),nextValue:y}),response:n.object({executionId:n.string().min(1),sequence:n.number().int().positive(),patch:n.array(v),value:y})})},extensions:{drizzle:{workflowDefinitions:Se,workflowExecutions:Ce,workflowExecutionFrames:Te,workflowGateInstances:De,workflowStepSpans:ke,workflowExecutionLinks:je,workflowRunContexts:Ne,worklogSummaries:Fe,worklogFrameEntries:Le,worklogArtifactWrites:ze,worklogGateEvents:Ve,workflowExecutionState:Ue,workflowExecutionStateEvents:Ge}}}),N=Xe.subjects;var Ze=e(t(),1);function Qe(e,t){let n=[];return $e(n,``,e,t),n}function $e(e,t,n,r){if(Array.isArray(n)&&Array.isArray(r)){tt(e,t,n,r);return}if(nt(n)&&nt(r)){et(e,t,n,r);return}at(n,r)||e.push({op:`replace`,path:t,value:r})}function et(e,t,n,r){let i=Array.from(new Set([...Object.keys(n),...Object.keys(r)])).sort();for(let a of i){let i=rt(n,a),o=rt(r,a),s=`${t}/${it(a)}`;if(!i&&o){e.push({op:`add`,path:s,value:r[a]});continue}if(i&&!o){e.push({op:`remove`,path:s});continue}$e(e,s,n[a],r[a])}}function tt(e,t,n,r){let i=Math.min(n.length,r.length);for(let a=0;a<i;a++)$e(e,`${t}/${String(a)}`,n[a],r[a]);for(let i=n.length-1;i>=r.length;i--)e.push({op:`remove`,path:`${t}/${String(i)}`});for(let i=n.length;i<r.length;i++)e.push({op:`add`,path:`${t}/${String(i)}`,value:r[i]})}function nt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rt(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function it(e){return e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}function at(e,t){return Object.is(e,t)}const ot={stepTimeoutMs:300*1e3,stepCooldownMs:500,busAuth:{kind:`none`},platformDefaults:{cwd:process.cwd()},cancelTimeoutMs:1e4},st=new Ze.default({allErrors:!0,strict:!1}),ct=new Map,lt=new Map;function ut(e){let t=e.$id;return typeof t==`string`?t:void 0}function dt(e,t,n){let r=ut(t);return r===void 0?`workflow:${e}:${n}`:`schema-id:${r}`}function ft(e,t){try{return JSON.stringify(pt(t))}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`Workflow '${e}' state schema is invalid: ${n}`)}}function pt(e){if(Array.isArray(e))return e.map(pt);if(typeof e!=`object`||!e)return e;let t=e;return Object.fromEntries(Object.keys(t).sort().map(e=>[e,pt(t[e])]))}function mt(e,t,n){let r=lt.get(t);if(r!==void 0&&r!==n)throw Error(`Workflow '${e}' state schema reuses JSON Schema $id '${t}' with different content`);return st.getSchema(t)}function ht(e){return e==null||e.length===0?`schema validation failed`:e.map(e=>`${e.instancePath.length>0?e.instancePath:`<root>`} ${e.message??`is invalid`}`).join(`; `)}function gt(e,t){let n=ft(e,t),r=dt(e,t,n),i=ct.get(r);if(i!==void 0)return i;let a=ut(t);if(a!==void 0){let t=mt(e,a,n);if(t!==void 0)return ct.set(r,t),t}try{let e=st.compile(t);return ct.set(r,e),a!==void 0&&lt.set(a,n),e}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`Workflow '${e}' state schema is invalid: ${n}`)}}function _t(e,t,n){if(e.state===void 0)return;let r=gt(e.id,e.state.schema);if(r(t))return;let i=n===`initial`?`initial state`:`next state`;throw Error(`Workflow '${e.id}' ${i} does not match workflow state schema: ${ht(r.errors)}`)}function vt(e){if(e.state===void 0)return;let t=e.state.initial===void 0?{}:e.state.initial;return _t(e,t,`initial`),t}function P(e){return`${e}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function yt(e,t,n){let r=e?j(e,n):t,c=o(t),l=o(i(r)?r:o(t,r)),u,d;try{u=s(c),d=s(l)}catch{return null}let f=a(process.platform===`win32`?u.toLowerCase():u,process.platform===`win32`?d.toLowerCase():d);return f===``||!f.startsWith(`..`)&&!i(f)?d:null}function bt(e){return e instanceof Error&&(`code`in e||`killed`in e)}function xt(e){let t=e[0];return t===void 0||t.trim()===``?null:t}function St(e){let{command:t,cwd:n,env:i,timeoutMs:a,signal:o}=e,s=xt(t);if(s===null)return Promise.reject(Error(`Shell step command is empty`));let c=t.slice(1);return new Promise((e,t)=>{let l=null,u=!1,d=r(s,c,{cwd:n,env:{...process.env,...i},timeout:0,maxBuffer:10*1024*1024,shell:!1},(n,r,i)=>{n?t(Object.assign(n,{stdout:r,stderr:i,aborted:u})):e({stdout:r,stderr:i})}),f=()=>{d.exitCode===null&&(d.kill(`SIGTERM`),l=setTimeout(()=>{d.exitCode===null&&d.kill(`SIGKILL`)},5e3))},p=setTimeout(()=>{f()},a);if(d.on(`close`,()=>{clearTimeout(p),l!==null&&clearTimeout(l)}),o){let e=()=>{u=!0,f()};o.aborted?e():(o.addEventListener(`abort`,e,{once:!0}),d.on(`close`,()=>o.removeEventListener(`abort`,e)))}})}async function Ct(e){let{step:t,workspaceRoot:n,expressionContext:r,signal:i}=e,a=yt(t.cwd,n,r);if(a===null)return{status:`failed`,error:`Shell step cwd '${t.cwd}' is outside workspace root '${n}'`};let o=t.command.map(e=>j(e,r));if(xt(o)===null)return{status:`failed`,error:`Shell step command is empty`};let s=Object.fromEntries(Object.entries(t.env??{}).map(([e,t])=>[e,j(t,r)])),c=t.timeoutMs??3e5;try{let{stdout:e}=await St({command:o,cwd:a,env:s,timeoutMs:c,signal:i});return{status:`completed`,stdout:e}}catch(e){if(!bt(e))return{status:`failed`,error:String(e)};let t=e.aborted===!0,n=!t&&(e.killed===!0||e.signal!=null);return{status:`failed`,error:t?`Command cancelled`:n?`Command timed out after ${c}ms`:e.stderr?.trim()||e.stdout?.trim()||e.message}}}async function wt(e,t,n){if(!(await e.request(N.updateExecution,{executionId:t.id,status:n.status,error:n.error,reason:n.reason,completedAt:n.completedAt})).success)throw Error(`Workflow execution not found: ${t.id}`)}async function Tt(e,t,n,r){t.status=`completed`,t.completedAt=Date.now();try{await wt(e.bus,t,{status:t.status,completedAt:t.completedAt}),await e.bus.emit(T.execution.completed,{executionId:n,workflowId:t.workflowId,totalDuration:t.completedAt-r,completedAt:t.completedAt})}finally{e.activeExecutions.delete(n)}}async function F(e,t,n,r,i){t.status=`failed`,t.error=r,t.completedAt=Date.now();try{await wt(e.bus,t,{status:t.status,error:t.error,completedAt:t.completedAt});try{await i?.()}catch(e){console.error(`[WorkflowFinalizer] Failed to run failure pre-emit hook:`,e)}await e.bus.emit(T.execution.failed,{executionId:n,workflowId:t.workflowId,error:r,completedAt:t.completedAt})}finally{e.activeExecutions.delete(n)}}function Et(e,t,n){let{activeRunnerSteps:r,bus:i}=e,a=`${t}:`;for(let[e,o]of r){if(!e.startsWith(a))continue;let r=e.slice(a.length);o.controller.abort(),i.emit(fe(o.cancelSubject),{executionId:t,stepId:r,reason:n}).catch(t=>{console.error(`[WorkflowFinalizer] Failed to emit cancellation for ${e}:`,t)})}}async function Dt(e,t,n){let r=await e.bus.request(N.getExecution,{executionId:t});if(r.execution==null)return!1;let i=r.execution.workflowId;if(i===void 0)throw Error(`Paused execution ${t} is missing stored workflowId`);let a=Date.now(),{cancelled:o,gates:s}=await e.bus.request(N.cancelPausedExecution,{executionId:t,completedAt:a,reason:n});if(!o)return!1;for(let n of s)await e.bus.emit(T.gate.resolved,{executionId:t,stepId:n.nodeId,stepType:`gate`,frameId:n.frameId,source:`cancelled`}).catch(e=>{console.error(`[WorkflowFinalizer] Failed to emit cancelled gate resolution for ${n.frameId}:`,e)});return await e.bus.emit(T.execution.cancelled,{executionId:t,workflowId:i,reason:n,completedAt:a}),e.activeExecutions.delete(t),!0}async function Ot(e,t,n){let r=e.activeExecutions.get(t);if(!r||r.execution.status!==`running`)return Dt(e,t,n);let{execution:i}=r;i.status=`cancelled`,i.reason=n,i.completedAt=Date.now();try{for(let[n,r]of e.shellAbortControllers)n.startsWith(`${t}:`)&&(r.abort(),e.shellAbortControllers.delete(n));Et(e,t,n),await wt(e.bus,i,{status:i.status,reason:n,completedAt:i.completedAt}),await e.bus.emit(T.execution.cancelled,{executionId:t,workflowId:i.workflowId,reason:n,completedAt:i.completedAt})}finally{e.activeExecutions.delete(t)}return!0}const kt=[`darwin`,`linux`,`win32`];function At(e){return kt.find(t=>t===e)??`linux`}function jt(e,t){return t}function Mt(e,t){return{...t}}function Nt(e){return e.reason instanceof Error?e.reason.message:typeof e.reason==`string`&&e.reason.length>0?e.reason:ee}async function Pt(e,t,n){let r=e.activeExecutions.get(t);if(!r||r.execution.status!==`running`)return;let i=e.buildFinalizerDeps(),{execution:a}=await i.bus.request(N.getExecution,{executionId:t});a?.status===`running`&&(r.execution=a,await Ot(i,t,Nt(n))||console.error(`[WorkflowExecutor] Failed to persist runner cancellation for ${t}: execution not active`))}async function Ft(e,t){if(t.pausedAtGateId===void 0||t.pausedAtFrameId===void 0)throw Error(`Paused runner result for '${t.executionId}' is missing gate identity`);let{bus:n}=e.buildFinalizerDeps(),{execution:r}=await n.request(N.getExecution,{executionId:t.executionId});if(r?.status!==`running`){let n=e.activeExecutions.get(t.executionId);n!==void 0&&r?.status===`paused`&&(n.execution.status=`paused`,e.activeExecutions.delete(t.executionId));return}let i={...r,status:`paused`};await n.request(N.setExecution,{execution:i});let a=e.activeExecutions.get(t.executionId);a!==void 0&&(a.execution=i),await n.emit(T.execution.paused,{executionId:t.executionId,workflowId:t.workflowId,pausedAtGateId:t.pausedAtGateId,pausedAtFrameId:t.pausedAtFrameId}),e.activeExecutions.delete(t.executionId)}async function It(e,t){let n=e.activeExecutions.get(t.executionId);if(!n||n.execution.status!==`running`)return;let r=e.buildFinalizerDeps(),{execution:i}=await r.bus.request(N.getExecution,{executionId:t.executionId});if(i?.status===`running`){if(n.execution=i,t.status===`completed`){await Tt(r,n.execution,t.executionId,n.execution.startedAt);return}if(t.status===`cancelled`){await Ot(r,t.executionId,t.reason??ee);return}if(t.status===`failed`){await F(r,n.execution,t.executionId,t.error);return}}}function Lt(e,t){return{source:{kind:`path`,path:t.filePath},executionId:t.executionId,workflowId:t.workflowId,triggerPayload:t.sanitizedTriggerPayload,inputs:t.boundInputs,config:t.boundConfig,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef},...t.executionHints===void 0?{}:{executionHints:t.executionHints},scope:t.scope,busUrl:e.config.busUrl,busAuth:e.config.busAuth,context:e.resolveWorkflowContext(t.workspaceRoot),env:e.config.platformDefaults.env??{},coordinatorSessionId:t.coordinatorSessionId,cancelSubject:`workflow.${t.executionId}.cancel`,suspensionStrategy:`wait-in-process`}}function Rt(e,t){let{executionId:n}=t,{workflowRunner:r,workflowAbortControllers:i,executionTasks:a,activeExecutions:o}=e,s=new AbortController;i.set(n,s);let c=Lt(e,t);return Promise.resolve().then(()=>r.run(c,s.signal)).then(async t=>{if(t.status===`paused`){await Ft(e,t);return}await It(e,t)}).catch(async t=>{if(s.signal.aborted){await Pt(e,n,s.signal).catch(e=>{console.error(`[WorkflowExecutor] Failed to persist file runner cancellation for ${n}:`,e)});return}let r=o.get(n);if(r){let i=t instanceof Error?t.message:String(t);await F(e.buildFinalizerDeps(),r.execution,n,i).catch(e=>{console.error(`[WorkflowExecutor] Failed to persist file runner boot failure for ${n}:`,e)})}}).finally(()=>{i.delete(n),a.delete(n),o.delete(n)})}function zt(e,t){let{config:n}=e,r=t.definitionSnapshot??(t.source.kind===`definition`?t.workflow:void 0);return{source:t.source,...r===void 0?{}:{definition:r},executionId:t.executionId,workflowId:t.workflowId,triggerPayload:t.sanitizedTriggerPayload,inputs:t.boundInputs,config:t.boundConfig,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef},...t.executionHints===void 0?{}:{executionHints:t.executionHints},scope:t.scope,busUrl:n.busUrl,busAuth:n.busAuth,context:e.resolveWorkflowContext(t.workspaceRoot),env:n.platformDefaults.env??{},coordinatorSessionId:t.coordinatorSessionId,cancelSubject:`workflow.${t.executionId}.cancel`,suspensionStrategy:t.suspensionStrategy??`wait-in-process`}}function Bt(e,t){let{executionId:n}=t,{workflowRunner:r,workflowAbortControllers:i,executionTasks:a,activeExecutions:o}=e,s=new AbortController;i.set(n,s);let c=zt(e,t),l=t.dispatchMetadata===void 0?void 0:{dispatchMetadata:t.dispatchMetadata};return Promise.resolve().then(()=>r.run(c,s.signal,void 0,l)).then(async t=>{if(t.status===`paused`){await Ft(e,t);return}await It(e,t)}).catch(async t=>{if(s.signal.aborted){await Pt(e,n,s.signal).catch(e=>{console.error(`[WorkflowExecutor] Failed to persist runner cancellation for ${n}:`,e)});return}let r=o.get(n);if(r){let i=t instanceof Error?t.message:String(t);await F(e.buildFinalizerDeps(),r.execution,n,i).catch(e=>{console.error(`[WorkflowExecutor] Failed to persist runner boot failure for ${n}:`,e)})}}).finally(()=>{i.delete(n),a.delete(n),o.delete(n)})}function Vt(e,t,n={}){let r=Ht(e,n);return{executionId:e.executionId,workflowId:e.workflowId,workflow:t,...e.definitionSnapshot===void 0?{}:{definitionSnapshot:e.definitionSnapshot},source:e.source,coordinatorSessionId:e.coordinatorSessionId,sanitizedTriggerPayload:e.triggerPayload,boundInputs:e.inputs,boundConfig:e.config??{},...e.artifactRef===void 0?{}:{artifactRef:e.artifactRef},...e.executionHints===void 0?{}:{executionHints:e.executionHints},scope:e.scope,workspaceRoot:e.context.repoPath,suspensionStrategy:e.suspensionStrategy,...r===void 0?{}:{dispatchMetadata:r}}}function Ht(e,t){return t.resume===!0?{...e.dispatchMetadata,resume:!0}:e.dispatchMetadata}const Ut=/(?:^|[_-])(authorization|token|cookie|password|set[_-]?cookie|api[_-]?key|secret|credential|private[_-]?key|api[_-]?secret)(?:$|[_-])/i;function Wt(e){if(!e)return;let t={remainingBytes:65536},n={},r=Object.entries(e).slice(0,100);for(let[e,i]of r){if(t.remainingBytes<=0)break;let r=Gt(e,i,0,t);r!==void 0&&(n[e]=r)}return Object.keys(n).length>0?n:void 0}function Gt(e,t,n,r){if(!(r.remainingBytes<=0||n>6)&&(r.remainingBytes-=e.length,!(r.remainingBytes<=0))){if(Ut.test(e))return r.remainingBytes-=10,`[REDACTED]`;if(t===null)return r.remainingBytes-=4,null;if(typeof t==`string`){let e=t.slice(0,2e3);return r.remainingBytes-=e.length,e}if(typeof t==`number`||typeof t==`boolean`)return r.remainingBytes-=String(t).length,t;if(Array.isArray(t)){let i=[];for(let a of t.slice(0,100)){if(r.remainingBytes<=0)break;let t=Gt(e,a,n+1,r);t!==void 0&&i.push(t)}return i}if(typeof t==`object`){let e={},i=Object.entries(t).slice(0,100);for(let[t,a]of i){if(r.remainingBytes<=0)break;let i=Gt(t,a,n+1,r);i!==void 0&&(e[t]=i)}return e}}}function Kt(e){return(e?.requirements?.capabilities??[]).length>0}function qt(e,t,n){let r=t?.requirements?.capabilities??[];if(Kt(t))return{run:(t,i)=>e.request(ne.dispatch,{config:t,requirements:{customCapabilities:r},...n===void 0?{}:{metadata:n}},{signal:i})}}function Jt(e,t){let n=qt(e.bus,t.executionHints,t.dispatchMetadata);return n===void 0?e.workflowRunner===void 0?e.runExecution(t.executionId).finally(()=>{e.executionTasks.delete(t.executionId)}):Bt(e.buildRunnerTaskDeps(e.workflowRunner),t):Bt(e.buildRunnerTaskDeps(n),t)}async function Yt(e,t,n,r){let i=vt(r);await e.request(N.setExecutionStart,{execution:t,runContext:n,initialState:i})}async function Xt(e,t){try{await e.emit(T.execution.started,t)}catch(e){console.error(`[WorkflowExecutor] execution.started listener failed:`,e)}}async function Zt(e,t){await e.request(b.close,{sessionId:t}).catch(e=>{console.error(`[WorkflowExecutor] Failed to close coordinator session "${t}" after launch failure:`,e)})}function Qt(e,t,n,r,i,a,o,s,c){let l={id:t,workflowId:n.id,coordinatorSessionId:r,status:`running`,inputs:i,config:a,startedAt:Date.now(),triggerPayload:o,...c.artifactRef===void 0?{}:{artifactRef:c.artifactRef},scope:s};return e.set(t,{execution:l,workflow:n,runContext:c,runtimeHandlers:new Map,runtimeLoopGates:new Map}),l}async function $t(e,t,n,r,i){await e.request(N.setExecutionStart,{execution:t,runContext:n,...r===void 0?{}:{initialState:r},...i!==void 0&&i.length>0?{executionLinks:[...i]}:{}})}function en(e,t){let n=e?.source;if(n===void 0)return;let r=de.parse(n);return r.kind===`path`&&!i(r.path)?{...r,path:o(t,r.path)}:r}function tn(e,t,n){return en(t,n)??{kind:`definition`,workflowId:e}}function nn(e,t,n,r){if(!(t.kind===`definition`||e.workflowRunner!==void 0||Kt(n)))throw new ie(ae.NOT_EXECUTABLE,`Workflow source execution '${r}' requires a workflow runner or WorkerNode capability requirements.`)}async function rn(e,t,n,r){return e.set(t,n),await r,t}async function an(e,t){let{workflow:n}=await e.request(N.get,{id:t});if(!n)throw Error(`Workflow not found: ${t}`);return n}function on(e,t){if(e===void 0&&t===void 0)return;let n=[...new Set([...e?.capabilities??[],...t?.capabilities??[]])];return{...e,...t,...n.length>0&&{capabilities:n}}}function sn(e,t){if(e===void 0&&t===void 0)return;let n=on(e?.requirements,t?.requirements),r=e?.providers!==void 0||t?.providers!==void 0?{...e?.providers,...t?.providers}:void 0;return{...e,...t,...n!==void 0&&{requirements:n},...r!==void 0&&{providers:r}}}async function cn(e,t,n,r){let{sessionId:i}=await e.request(b.create,{parentSessionId:t,branchKind:`coordinator`,title:`Workflow: ${n}`,targetWorkingDirectory:r});return i}async function ln(e,t,n={}){let r=await an(e.bus,t);return un(e,t,{...n,workflow:r})}async function un(e,t,n){let{bus:r,activeExecutions:i,executionTasks:a}=e,{workflow:o,parentSessionId:s,triggerPayload:c,artifactRef:l,executionHints:u,scopeOverride:d}=n,f=P(`wfx`),p=Wt(c),m=jt(o,n.input===void 0?{}:n.input),h=Mt(o,n.config??{}),g=d??o.scope,_=sn(o.executionHints,u),v=await e.resolveExecutionWorkspaceRoot(s),y=n.executionSource??tn(t,_,v),b=n.definitionSnapshot??(y.kind===`definition`?o:void 0);nn(e,y,_,t);let x=await cn(r,s,o.name,v),S=!1;try{let s=e.buildRunContext({executionId:f,workflowId:t,coordinatorSessionId:x,source:y,...b===void 0?{}:{definitionSnapshot:b},inputs:m,config:h,scope:g,triggerPayload:p??{},...l===void 0?{}:{artifactRef:l},..._===void 0?{}:{executionHints:_},workspaceRoot:v}),c=Qt(i,f,o,x,m,h,p,g,s);await $t(r,c,s,y.kind===`definition`?vt(o):void 0,n.executionLinks?.(f));let u=c.startedAt,d=Xt(r,{executionId:f,workflowId:t,coordinatorSessionId:x,startedAt:u,...l===void 0?{}:{artifactRef:l}}),ee=Jt(e,{executionId:f,workflowId:t,workflow:o,...b===void 0?{}:{definitionSnapshot:b},source:y,coordinatorSessionId:x,sanitizedTriggerPayload:p??{},boundInputs:m,boundConfig:h,scope:g,...l===void 0?{}:{artifactRef:l},..._===void 0?{}:{executionHints:_},workspaceRoot:v,suspensionStrategy:s.suspensionStrategy});return S=!0,rn(a,f,ee,d)}catch(e){throw S||(i.delete(f),a.delete(f),await Zt(r,x)),e}}function dn(e,t,n,r,i){e.set(t.id,{execution:t,workflow:{id:t.workflowId,name:n,scope:r,root:{id:`${t.workflowId}-root`,type:`sequence`,nodes:[]}},runContext:i,runtimeHandlers:new Map,runtimeLoopGates:new Map})}async function fn(e,t,n,r){let{sessionId:i}=await e.request(b.create,{...t===void 0?{}:{parentSessionId:t},branchKind:`coordinator`,title:`Workflow: ${n}`,targetWorkingDirectory:r});return i}async function pn(e,t,n={}){let{bus:r,activeExecutions:i,executionTasks:a}=e,{artifactRef:o,executionHints:s,parentSessionId:c,triggerPayload:l,scopeOverride:u}=n,d=P(`wfx`),f=Wt(l),p=n.input===void 0?{}:n.input,m=n.config??{},h=u??{type:`global`},g=await e.resolveExecutionWorkspaceRoot(c),_=await fn(r,c,t,g),v=d,y={id:d,workflowId:v,coordinatorSessionId:_,status:`running`,inputs:p,config:m,startedAt:Date.now(),triggerPayload:f,...o===void 0?{}:{artifactRef:o},scope:h},b=!1;try{let{workflowRunner:c}=e;if(c===void 0)throw Error(`[WorkflowExecutor] startFileExecution called without a workflow runner`);let l=e.buildRunContext({executionId:d,workflowId:v,coordinatorSessionId:_,source:{kind:`path`,path:t},inputs:p,config:m,scope:h,triggerPayload:f??{},...o===void 0?{}:{artifactRef:o},...s===void 0?{}:{executionHints:s},workspaceRoot:g});await $t(r,y,l,void 0,n.executionLinks?.(d)),dn(i,y,t,h,l);let u=Xt(r,{executionId:d,workflowId:v,coordinatorSessionId:_,startedAt:y.startedAt,...o===void 0?{}:{artifactRef:o}}),x=Rt(e.buildRunnerTaskDeps(c),{executionId:d,workflowId:v,filePath:t,coordinatorSessionId:_,sanitizedTriggerPayload:f??{},boundInputs:p,boundConfig:m,...o===void 0?{}:{artifactRef:o},...s===void 0?{}:{executionHints:s},scope:h,workspaceRoot:g});return b=!0,rn(a,d,x,u)}catch(e){throw b||(i.delete(d),a.delete(d),await Zt(r,_)),e}}function mn(e){let t={};for(let[n,r]of Object.entries(e))r.status===`completed`?t[n]={status:`completed`,output:r.output}:r.status===`skipped`&&(t[n]={status:`skipped`});return t}function I(e){let t={...e,input:e.inputs,steps:e.frames};return{...t,ctx:t}}function hn(){return{context:{repoPath:process.cwd(),makaioHome:process.env.MAKAIO_HOME??`${ye.homedir()}/.makaio`,os:process.platform===`win32`?`win32`:process.platform===`darwin`?`darwin`:`linux`,arch:process.arch},env:{}}}function gn(e){return{...e,path:[...e.path]}}function _n(e){if(e===`station`||e===`delegate-agent`||e===`delegate-role`||e===`gate`)return e}function vn(e,t){let n=_n(t.nodeType);if(n===void 0||t.status!==`running`&&t.status!==`completed`&&t.status!==`failed`&&t.status!==`skipped`)return;let r=t.startedAt!==void 0&&t.completedAt!==void 0?Math.max(0,t.completedAt-t.startedAt):void 0;return{executionId:e,frameId:t.frameId,stepId:t.nodeId,stepType:n,status:t.status,...t.startedAt===void 0?{}:{startedAt:t.startedAt},...t.completedAt===void 0?{}:{completedAt:t.completedAt},...r===void 0?{}:{durationMs:r},...t.output===void 0?{}:{output:JSON.stringify(t.output)}}}var yn=class e{executionId;workflowId;definition;execution;runtimeHandlers;bus;signal;frameRegistry;framePersistenceTasks=new Map;artifactBinding;constructor(e,t,n,r,i,a,o,s,c,l=hn(),u={}){this.executionId=e,this.workflowId=t,this.definition=n,this.execution=r,this.runtimeHandlers=i,this.bus=a,this.signal=o,this.frameRegistry=s??new Map,this.artifactBinding=c,this.platformContext=l.context,this.env=l.env,this.suspensionStrategy=u.suspensionStrategy??`wait-in-process`,this.resumeFrames=u.resumeFrames,this.runtimeLoopGates=u.runtimeLoopGates??new Map}platformContext;env;suspensionStrategy;resumeFrames;runtimeLoopGates;withSignal(t){return new e(this.executionId,this.workflowId,this.definition,this.execution,this.runtimeHandlers,this.bus,t,this.frameRegistry,this.artifactBinding,{context:this.platformContext,env:this.env},{suspensionStrategy:this.suspensionStrategy,resumeFrames:this.resumeFrames,runtimeLoopGates:this.runtimeLoopGates})}buildExpressionContext(){return{inputs:this.execution.inputs,config:this.execution.config??{},trigger:this.execution.triggerPayload??{},frames:{},previousSteps:{}}}createFrame(e){let t=P(`frm`),n=[...e.path,t],r={frameId:t,nodeId:e.nodeId,nodeType:e.nodeType,path:n,parentFrameId:e.parentFrameId,status:`pending`,attempt:0,iteration:e.iteration,branchKey:e.branchKey};return this.frameRegistry.set(t,r),this.persistFrame(r).catch(()=>void 0),r}async persistFrame(e,t={}){let n=t.requireFrameStorage===!0||this.suspensionStrategy!==`wait-in-process`,r=gn(e),i=vn(this.executionId,r),a=(this.framePersistenceTasks.get(e.frameId)??Promise.resolve()).catch(()=>void 0).then(async()=>{n?await this.bus.request(N.setFrame,{executionId:this.executionId,frame:r}):await this.bus.requestOptional(N.setFrame,{executionId:this.executionId,frame:r}),i!==void 0&&await this.bus.requestOptional(N.setSpan,{span:i})}).catch(t=>{if(n)throw t;console.warn(`[RuntimeContext] Failed to persist frame ${e.frameId}:`,t)});this.framePersistenceTasks.set(e.frameId,a);try{await a}finally{this.framePersistenceTasks.get(e.frameId)===a&&this.framePersistenceTasks.delete(e.frameId)}}async updateFrame(e,t,n={}){let r=this.frameRegistry.get(e);if(!r)throw Error(`Frame not found: ${e}`);Object.assign(r,t),await this.persistFrame(r,n)}getFrame(e){return this.frameRegistry.get(e)}getFramesByNodeId(e){let t=[];for(let n of this.frameRegistry.values())n.nodeId===e&&t.push(n);return t.sort((e,t)=>(e.startedAt??0)-(t.startedAt??0))}async emitFrameStarted(e){try{await this.bus.emit(T.frame.started,{executionId:this.executionId,frameId:e.frameId,nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,parentFrameId:e.parentFrameId,startedAt:e.startedAt})}catch(t){console.error(`[RuntimeContext] frame.started observer failed for ${e.frameId}:`,t)}}async emitFrameCompleted(e,t){try{await this.bus.emit(T.frame.completed,{executionId:this.executionId,frameId:e.frameId,nodeId:e.nodeId,output:e.output,duration:t,completedAt:e.completedAt})}catch(t){console.error(`[RuntimeContext] frame.completed observer failed for ${e.frameId}:`,t)}}async emitFrameFailed(e,t,n){try{await this.bus.emit(T.frame.failed,{executionId:this.executionId,frameId:e.frameId,nodeId:e.nodeId,error:t,duration:n,completedAt:e.completedAt})}catch(t){console.error(`[RuntimeContext] frame.failed observer failed for ${e.frameId}:`,t)}}};function bn(e){return{kind:`workflow-execution`,id:e,displayName:`Workflow Engine`}}function xn(e,t,n){return{inputs:n.inputs,config:n.config??{},trigger:n.triggerPayload,scope:n.scope,context:n.context,env:n.env,execution:{id:t.id,workflowId:t.workflowId,scope:t.scope},workflow:{id:e.id,name:e.name,scope:e.scope}}}function Sn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Cn(e){if(e!=null){if(Sn(e)&&typeof e.kind==`string`&&typeof e.id==`string`)return{kind:e.kind,id:e.id};throw Error(`Artifact resolve expression must return an object with string kind and id fields.`)}}function wn(e){if(e!==void 0){if(Sn(e))return e;throw Error(`Artifact create expression must return an object.`)}}async function Tn(e){let{bindingOptions:t,binding:n,existingArtifactRef:r,executionId:i,scope:a,initialData:o,bus:s}=e,c=null;if(r!==void 0){let e=await s.request(d.query,{kind:r.kind,ids:[r.id],currentOnly:!0});if(e.artifacts.length>0)c=e.artifacts[0];else return}else c=(await s.request(d.create,{kind:n.kind,schemaVersion:n.schemaVersion,scope:a??n.scope,data:o??{},relations:[],actor:bn(i)})).artifact;return{current:c,schemaVersion:n.schemaVersion,statusPath:t.statusPath,zodSchema:t.schema}}async function En(e){let{definition:t,execution:n,runContext:r,zodSchema:i,bus:a}=e,o=t.artifact;if(o===void 0)return;let s=xn(t,n,r),c=r.artifactRef??(o.resolve===void 0?void 0:Cn(A(o.resolve,s))),l=c===void 0&&o.create!==void 0?wn(A(o.create,s)):void 0,u=await Tn({bindingOptions:{kind:o.kind,schemaVersion:o.schemaVersion,scope:o.scope,...o.resolve===void 0?{}:{resolve:o.resolve},...o.create===void 0?{}:{create:o.create},...o.statusPath===void 0?{}:{statusPath:o.statusPath},...i===void 0?{}:{schema:i}},binding:o,existingArtifactRef:c,executionId:n.id,scope:o.scope,initialData:l,bus:a});if(u===void 0)throw Error(`Workflow artifact binding could not be resolved for the configured artifact reference.`);return u}const Dn=new WeakMap;function On(e,t){let n=(Dn.get(e)??Promise.resolve()).catch(()=>void 0).then(t);return Dn.set(e,n.then(()=>void 0,()=>void 0)),n}function kn(e,t){switch(t.operation){case`set`:return t.data;case`merge`:return{...e,...t.data};case`append`:{let n={...e};for(let[r,i]of Object.entries(t.data)){let t=e[r];Array.isArray(t)&&Array.isArray(i)?n[r]=[...t,...i]:n[r]=i}return n}}}function An(e,t,n){let[r,...i]=t;if(i.length===0)return{...e,[r]:n};let a=e[r]!==null&&typeof e[r]==`object`&&!Array.isArray(e[r])?e[r]:{};return{...e,[r]:An(a,i,n)}}function jn(e,t,n){return An(e,t.startsWith(`/`)?t.slice(1).split(`/`):t.split(`.`),n)}function Mn(e,t,n){if(n===`set`||n===`functional`)return[];let r=[];for(let n of Object.keys(t))e[n]!==t[n]&&r.push(`/${n}`);return r}async function Nn(e,t){if(typeof t==`function`)return{nextData:await t(Object.freeze({...e})),operationLabel:`functional`,changedPaths:[]};let n=kn(e,t),r=Mn(e,n,t.operation);return{nextData:n,operationLabel:t.operation,changedPaths:r}}function Pn(e){let{executionId:t,frameId:n,bindingState:r,bus:i}=e,a=Object.freeze({...r.current.data}),o=async e=>On(r,async()=>{let a=r.current,{nextData:o,operationLabel:s,changedPaths:c}=await Nn(a.data,e);if(r.zodSchema!==void 0){let e=r.zodSchema.safeParse(o);if(!e.success)throw Error(`Artifact data validation failed: ${e.error.message}`)}let l=await i.request(d.revise,{previous:{refClass:`artifact`,kind:a.kind,id:a.id,revision:a.revision},revision:{kind:a.kind,schemaVersion:r.schemaVersion,scope:a.scope,data:o,relations:a.relations,actor:bn(t)}});r.current=l.artifact;let u=l.artifact.revision;return i.emit(ue.artifact.updated,{executionId:t,frameId:n,artifactRef:{kind:l.artifact.kind,id:l.artifact.id},paths:c,operation:s,revision:u}).catch(e=>{console.error(`[ArtifactContext] Failed to emit artifact.updated event:`,e)}),u});return{data:a,updateArtifact:o,updateStatus:async e=>{if(r.statusPath===void 0)throw Error(`updateStatus() called but no statusPath is configured on the artifact binding. Set statusPath in the .artifact() builder call to use updateStatus().`);let t=r.statusPath;return o(n=>jn(n,t,e))}}}function Fn(e,t){return{async get(){return(await t.request(T.state.get,{executionId:e})).value},async update(n){let r=await t.request(T.state.get,{executionId:e}),i=structuredClone(r.value),a=await n(i),o=a===void 0?i:a,s=Qe(r.value,o);return(await t.request(T.state.patch,{executionId:e,expectedSequence:r.sequence,patch:s,nextValue:o})).value}}}async function In(e,t,n){if(t.signal.aborted)return{status:`cancelled`};let r=await t.bus.requestOptional(T.resolveRole,{roleId:e.roleId});if(!r.handled)return{status:`failed`,error:e.unresolvedRoleError};let i=j(e.prompt,I(n)),a=e.completion===void 0?r.data:{...r.data,completion:e.completion};return Ln({...e,task:i,resolvedConfig:a},t)}async function Ln(e,t){if(t.signal.aborted)return{status:`cancelled`};let n=await t.bus.requestOptional(S.spawn,{parentSessionId:t.execution.coordinatorSessionId??t.executionId,depth:1,config:Hn(e.task,e.resolvedConfig,e.outputSchema)});if(!n.handled)return{status:`failed`,error:e.unavailableRuntimeError};let r=await Rn(e,t,n.data.subagentId,{attempts:5}),i=await Un(e,t,n.data.subagentId);return i===`aborted`?{status:`cancelled`}:(r||await Rn(e,t,n.data.subagentId,{attempts:1}),i.handled?t.signal.aborted||i.data.status===`cancelled`?{status:`cancelled`}:i.data.status===`completed`?{status:`completed`,output:i.data.result??null}:{status:`failed`,error:`${e.nodeLabel} '${e.nodeId}' subagent ${i.data.status}: ${i.data.error??`no result`}`}:{status:`failed`,error:e.unavailableAwaitError})}async function Rn(e,t,n,r){if(e.frameId===void 0)return!0;try{let i=await zn(t,n,r.attempts);return i===void 0?!1:(await t.bus.emit(T.frame.sessionLinked,{executionId:t.executionId,frameId:e.frameId,sessionId:i}),!0)}catch(t){return console.warn(`[workflow-engine] Failed to emit frame.sessionLinked for frame '${e.frameId}' and subagent '${n}'`,t),!1}}async function zn(e,t,n){for(let r=0;r<n;r+=1){if(e.signal?.aborted)return;let i=await Bn(e,t);if(i===void 0||!i.handled)return;if(i.data.childSessionId!==void 0)return i.data.childSessionId;if(r<n-1&&!await Vn(e.signal,20))return}}async function Bn(e,t){try{return await e.bus.requestOptional(S.getStatus,{subagentId:t},{timeout:25,signal:e.signal})}catch{return}}function Vn(e,t){return e.aborted?Promise.resolve(!1):new Promise(n=>{let r,i=t=>{r!==void 0&&(clearTimeout(r),r=void 0),e.removeEventListener(`abort`,a),n(t)},a=()=>i(!1);r=setTimeout(()=>i(!0),t),e.addEventListener(`abort`,a,{once:!0}),e.aborted&&i(!1)})}function Hn(e,t,n){return{task:e,adapterName:t.adapterName,...t.model===void 0?{}:{model:t.model},...t.reasoningEffort===void 0?{}:{reasoningEffort:t.reasoningEffort},...t.harnessId===void 0?{}:{harnessId:t.harnessId},...t.systemPrompt===void 0?{}:{systemPrompt:t.systemPrompt},...t.contextMode===void 0?{}:{contextMode:t.contextMode},...t.providerContext===void 0?{}:{providerContext:t.providerContext},...t.completion===void 0?{}:{completion:t.completion},...n===void 0?{}:{responseSchema:n}}}async function Un(e,t,n){if(t.signal.aborted)return await Wn(e,t,n),`aborted`;let r=t.bus.requestOptional(S.await,{subagentId:n,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}},{timeout:0});if(t.signal.aborted)return await Wn(e,t,n),`aborted`;let i,a=new Promise(e=>{i=()=>e(`aborted`),t.signal.addEventListener(`abort`,i,{once:!0})}),o=await Promise.race([r,a]);return i!==void 0&&t.signal.removeEventListener(`abort`,i),o===`aborted`&&await Wn(e,t,n),o}async function Wn(e,t,n){try{await t.bus.requestOptional(S.kill,{subagentId:n,reason:`Workflow execution '${t.executionId}' cancelled ${e.cancellationLabel} '${e.nodeId}'`})}catch(t){console.warn(`[workflow-engine] Best-effort subagent kill failed for '${n}' (${e.cancellationLabel} '${e.nodeId}')`,t)}}async function Gn(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=mn(n.frames),a=t.runtimeHandlers.get(e.id);if(a===void 0)return Kn(e,t,n,r);let o=t.artifactBinding!==void 0&&r!==void 0?Pn({executionId:t.executionId,frameId:r,bindingState:t.artifactBinding,bus:t.bus}):void 0,s=t.definition.state===void 0?void 0:Fn(t.executionId,t.bus);async function c(n){if(r===void 0){console.warn(`[station-node] updateProgress called without frameId for node '${e.id}'; skipping emit`);return}let i=le[`execution.progress`].parse({executionId:t.executionId,workflowId:t.workflowId,frameId:r,nodeId:e.id,progress:n,emittedAt:Date.now()});try{await t.bus.emit(T.execution.progress,i)}catch(t){console.error(`[station-node] execution.progress observer failed for ${e.id}:`,t)}}let l;try{l=await a({...t.platformContext,env:t.env,executionId:t.executionId,workflowId:t.workflowId,inputs:t.execution.inputs,config:t.execution.config??{},trigger:t.execution.triggerPayload??{},previousSteps:i,...n.item!==void 0&&{item:n.item},...n.index!==void 0&&{index:n.index},...n.previous!==void 0&&{previous:n.previous},signal:t.signal,...o!==void 0&&{artifact:o},...s!==void 0&&{state:s},bus:t.bus,updateProgress:c})}catch(e){return{status:`failed`,error:e instanceof Error?e.message:String(e)}}return{status:`completed`,output:l}}async function Kn(e,t,n,r){if(e.role===void 0)return{status:`failed`,error:`No handler registered for station node '${e.id}'`};let i=e.outputSchema===void 0?void 0:{schema:e.outputSchema};return In({nodeId:e.id,nodeLabel:`Station node`,roleId:e.role,prompt:e.prompt,...i===void 0?{}:{outputSchema:i},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.completion===void 0?{}:{completion:e.completion},unresolvedRoleError:`No runtime handler registered for station node '${e.id}', and role '${e.role}' could not be resolved`,unavailableRuntimeError:`Subagent runtime is not available for station node '${e.id}'`,unavailableAwaitError:`Subagent runtime cannot await station node '${e.id}'`,cancellationLabel:`station`,...r===void 0?{}:{frameId:r}},t,n)}async function qn(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=await t.bus.requestOptional(T.resolveAgent,{agentId:e.agentId});if(!i.handled)return{status:`failed`,error:`Agent '${e.agentId}' could not be resolved for delegate-agent node '${e.id}'`};if(t.signal.aborted)return{status:`cancelled`};let a=sr(e,n);if(a.status===`failed`)return a;let o=e.outputSchema===void 0?void 0:{schema:e.outputSchema};return Ln({nodeId:e.id,nodeLabel:`Delegate-agent node`,task:a.task,resolvedConfig:i.data,...o===void 0?{}:{outputSchema:o},unavailableRuntimeError:`Subagent runtime is not available for delegate-agent node '${e.id}'`,unavailableAwaitError:`Subagent runtime cannot await delegate-agent node '${e.id}'`,cancellationLabel:`delegate-agent`,...r===void 0?{}:{frameId:r}},t)}async function Jn(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=await t.bus.requestOptional(T.resolveRole,{roleId:e.role});if(!i.handled)return{status:`failed`,error:`Role '${e.role}' could not be resolved for delegate-role node '${e.id}'`};let a=e.outputSchema===void 0?void 0:{schema:e.outputSchema},o=j(e.prompt,I(n)),s=nr(e,i.data),c={node:e,task:o,resolvedRole:s,...a===void 0?{}:{outputSchema:a},...r===void 0?{}:{frameId:r}};return rr(s)?Yn(c,t):Ln({nodeId:e.id,nodeLabel:`Delegate-role node`,task:o,resolvedConfig:s,...a===void 0?{}:{outputSchema:a},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},unavailableRuntimeError:`Subagent runtime is not available for delegate-role node '${e.id}'`,unavailableAwaitError:`Subagent runtime cannot await delegate-role node '${e.id}'`,cancellationLabel:`delegate-role`,...r===void 0?{}:{frameId:r}},t)}async function Yn(e,t){let{node:n}=e,r=n.timeoutMs??3e5,i,a=or(t.signal);try{let n=await Xn(e,t);return`status`in n?n:(i=n.sessionId,t.signal.aborted?{status:`cancelled`}:await Zn(e,t,{abortLink:a,childSessionId:i,timeoutMs:r}))}catch(e){if(t.signal.aborted)return{status:`cancelled`};let r=e instanceof Error?e.message:String(e);return{status:`failed`,error:`Delegate-role node '${n.id}' session turn failed: ${r}`}}finally{a.controller.abort(),a.cleanup(),i!==void 0&&await ar(t,n.id,i)}}async function Xn(e,t){let n=await t.bus.requestOptional(b.create,{sessionId:er(t,e),parentSessionId:t.execution.coordinatorSessionId??t.executionId,branchKind:`subagent`,title:`Workflow delegate-role '${e.node.id}'`});if(!n.handled)return{status:`failed`,error:`Session runtime is not available for delegate-role node '${e.node.id}'`};let r=n.data.sessionId;return await ir(e,t,r),(await t.bus.requestOptional(b.agent.attachResolved,{sessionId:r,agent:tr(e.resolvedRole),role:`lead`},{signal:t.signal}).catch(async n=>{throw await ar(t,e.node.id,r),n})).handled?{sessionId:r}:(await ar(t,e.node.id,r),{status:`failed`,error:`Session runtime cannot attach delegate-role node '${e.node.id}'`})}async function Zn(e,t,n){let r=t.bus.once(u.complete,{timeoutMs:n.timeoutMs,filter:{sessionId:n.childSessionId},signal:n.abortLink.controller.signal});r.catch(()=>void 0);let i=await Qn(e,t,n);if(`status`in i)return i;let a=await $n(e,t,n,i.turnId);if(a.status===`failed`)return a;let o=await r;return t.signal.aborted?{status:`cancelled`}:o.payload.outcome===`error`?{status:`failed`,error:`Delegate-role node '${e.node.id}' agent error: ${o.payload.error??`no result`}`}:{status:`completed`,output:o.payload.message??null}}async function Qn(e,t,n){let r=await t.bus.requestOptional(b.sendMessage,{sessionId:n.childSessionId,message:e.task,...e.outputSchema===void 0?{}:{responseSchema:e.outputSchema},source:`system`},{signal:t.signal});return r.handled?{turnId:r.data.turnId}:(n.abortLink.controller.abort(),{status:`failed`,error:`Session runtime cannot send delegate-role node '${e.node.id}'`})}async function $n(e,t,n,r){let i=await t.bus.requestOptional(b.turn.await,{sessionId:n.childSessionId,turnId:r,timeoutMs:n.timeoutMs},{timeout:0,signal:t.signal});return i.handled?i.data.completion.success?{status:`completed`}:{status:`failed`,error:`Delegate-role node '${e.node.id}' session turn failed: ${i.data.completion.error??`no result`}`}:(n.abortLink.controller.abort(),{status:`failed`,error:`Session runtime cannot await delegate-role node '${e.node.id}'`})}function er(e,t){return`session-workflow-${e.executionId}-${t.frameId??t.node.id}`}function tr(e){return{kind:`adapter`,adapterName:e.adapterName,...e.model===void 0?{}:{model:e.model},...e.reasoningEffort===void 0?{}:{reasoningEffort:e.reasoningEffort},...e.systemPrompt===void 0?{}:{systemPrompt:e.systemPrompt},...e.providerContext?.state===`resolved`?{providerConfigId:e.providerContext.providerConfigId}:{},...e.providerContext===void 0?{}:{providerContext:e.providerContext}}}function nr(e,t){return e.completion===void 0?t:{...t,completion:e.completion}}function rr(e){return e.completion===`turn`&&e.harnessId===void 0&&e.contextMode===void 0}async function ir(e,t,n){if(e.frameId!==void 0)try{await t.bus.emit(T.frame.sessionLinked,{executionId:t.executionId,frameId:e.frameId,sessionId:n})}catch(t){console.warn(`[workflow-engine] Failed to emit frame.sessionLinked for frame '${e.frameId}' and session '${n}'`,t)}}async function ar(e,t,n){try{await e.bus.requestOptional(b.close,{sessionId:n})}catch(e){console.warn(`[workflow-engine] Failed to close delegate-role session '${n}' for node '${t}'`,e)}}function or(e){let t=new AbortController;if(e.aborted)return t.abort(),{controller:t,cleanup:()=>void 0};let n=()=>t.abort();return e.addEventListener(`abort`,n,{once:!0}),{controller:t,cleanup:()=>e.removeEventListener(`abort`,n)}}function sr(e,t){try{let n=I(t);return{status:`completed`,task:cr(e.inputExpression===void 0?n:A(e.inputExpression,n))}}catch(t){let n=t instanceof Error?t.message:String(t);return{status:`failed`,error:`delegate-agent node '${e.id}': input expression evaluation failed: ${n}`}}}function cr(e){if(typeof e==`string`)return e;if(e===void 0)return``;try{return JSON.stringify(e,null,2)??``}catch{return String(e)}}function lr(e,t,n,r){try{let i=A(n,I(r));return Array.isArray(i)?i:{status:`failed`,error:`${t} node '${e}': collection expression did not resolve to an array (got ${typeof i})`}}catch(n){return{status:`failed`,error:`${t} node '${e}': collection expression evaluation failed: ${n instanceof Error?n.message:String(n)}`}}}function ur(e,t,n){for(let r of[...e.nodes].reverse()){let e=n.getFramesByNodeId(r.id);for(let n of e)if(n.parentFrameId===t&&n.status===`completed`)return n.output}}function dr(e,t,n){return ur(e.body,t,n)}function fr(e){if(e.length===0)return;let t=new Map,n=new Map;for(let r of e){n.set(r.frameId,r);let e=t.get(r.nodeId)??[];e.push(r),t.set(r.nodeId,e)}return{byNodeId:t,byFrameId:n}}const pr=new Set([`completed`,`skipped`,`waiting`]);function L(e,t,n){let r=e?.byNodeId.get(t)??[],i=n.statuses??pr;return r.find(e=>e.parentFrameId===n.parentFrameId&&e.branchKey===n.branchKey&&e.iteration===n.iteration&&i.has(e.status))}function R(e,t,n){let r={...e.frames,[t]:n};return{...e,frames:r,previousSteps:mn(r),output:n.status===`completed`?n.output:e.output}}function z(e,t){if(typeof AbortSignal.any==`function`)return AbortSignal.any([e,t]);let n=new AbortController,r=()=>n.abort();return e.addEventListener(`abort`,r,{once:!0}),t.addEventListener(`abort`,r,{once:!0}),n.signal}const mr=new Set([`completed`,`running`]);function hr(e,t){return e.status===`running`&&t.pauseSignal?.aborted===!0&&!t.outerSignal.aborted}async function gr(e,t,n,r,i,a,o=`all-settled`){if(t.signal.aborted)return{status:`cancelled`};let s=Object.entries(e.branches);if(s.length===0)return{status:`completed`,output:yr({},o)};let c=new AbortController,l=new AbortController,u=t.suspensionStrategy!==`wait-in-process`,d=o===`fail-fast`?z(c.signal,l.signal):u?l.signal:void 0,f=d===void 0?t.signal:z(t.signal,d),p=f===t.signal?t:t.withSignal(f),m=s.map(([s,c])=>_r(s,c,e,p,n,r,i,a,{outerSignal:t.signal,pauseSignal:o===`fail-fast`||u?l.signal:void 0}));if(o===`all-settled`){let e=await Promise.all(u?m.map(e=>e.then(e=>(e.status===`paused`&&l.abort(),e))):m),t=e.find(e=>e.status===`paused`);return t===void 0?{status:`completed`,output:yr(br(s,e),o)}:t}let h=await vr(s,m,c,l);return h.type===`cancelled`?{status:`cancelled`}:h.type===`paused`?h.outcome:h.type===`failed`?{status:`failed`,error:h.error}:{status:`completed`,output:yr(br(s,h.outcomes),o)}}async function _r(e,t,n,r,i,a,o,s,c){if(r.signal.aborted)return{status:`cancelled`};let l=L(r.resumeFrames,n.id,{parentFrameId:o,branchKey:e,statuses:mr});if(l?.status===`completed`)return{status:`completed`,...l.output===void 0?{}:{output:l.output}};let u=l??r.createFrame({nodeId:n.id,nodeType:`parallel`,path:s,parentFrameId:o,branchKey:e});if(r.signal.aborted)return hr(u,c)||await $(u,r),{status:`cancelled`};l===void 0&&await X(u,r);let d;try{d=await a(t,r,i,u.frameId,u.path)}catch(e){let t=e instanceof Error?e.message:String(e);return await Q(u,r,t),{status:`failed`,error:t}}switch(d.status){case`completed`:{let e=ur(t,u.frameId,r);return await Z(u,r,e),{status:`completed`,output:e}}case`skipped`:return await Z(u,r),{status:`completed`};case`cancelled`:return hr(u,c)||await $(u,r),{status:`cancelled`};case`paused`:return d;case`failed`:return await Q(u,r,d.error),{status:`failed`,error:d.error}}}async function vr(e,t,n,r){let i,a,o=t.map(e=>e.then(e=>(e.status===`failed`&&i===void 0?(i=e.error,n.abort()):e.status===`paused`&&a===void 0&&(a=e,r.abort()),e),e=>{let t=e instanceof Error?e.message:String(e);return i===void 0&&(i=t,n.abort()),{status:`failed`,error:t}})),s=await Promise.all(o);return a===void 0?s.some(e=>e.status===`cancelled`)&&i===void 0?{type:`cancelled`}:i===void 0?{type:`completed`,outcomes:s}:{type:`failed`,error:i}:{type:`paused`,outcome:a}}function yr(e,t){return{mode:t,branches:e}}function br(e,t){let n={};for(let r=0;r<e.length;r++){let[i]=e[r],a=t[r];n[i]=xr(a)}return n}function xr(e){switch(e.status){case`completed`:return{status:`fulfilled`,...e.output===void 0?{}:{value:e.output}};case`skipped`:return{status:`fulfilled`,value:null};case`cancelled`:return{status:`cancelled`};case`paused`:return{status:`paused`,pausedAtGateId:e.pausedAtGateId,pausedAtFrameId:e.pausedAtFrameId};case`failed`:return{status:`rejected`,reason:e.error}}}const Sr=new Ze.default({allErrors:!0,strict:!1});function B(e,t){if(t===void 0)return{status:`ok`};try{return{status:`ok`,validator:Sr.compile(t)}}catch(t){return{status:`failed`,error:`Gate '${e}' has an invalid resumeSchema: ${t instanceof Error?t.message:String(t)}`}}}function V(e,t){return e===void 0||e(t)?{valid:!0}:{valid:!1,error:Cr(e.errors??[])}}function H(e,t,n){let r=B(e,t);return r.status===`failed`?{valid:!1,error:r.error}:V(r.validator,n)}function Cr(e){return e.length===0?`schema validation failed`:e.map(e=>`${e.instancePath.length>0?e.instancePath:`/`} ${e.message??`is invalid`}`).join(`; `)}function wr(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}const Tr={action:`approve`,source:`timeout`};function Er(e){return e===void 0?{}:{reason:e}}async function Dr(e,t,n,r){let i=()=>{t.value&&(t.value=!1,e.reject(`cancelled`))};n.addEventListener(`abort`,i,{once:!0}),n.aborted&&i();let a=[e.promise],o;if(r!==null){let e=wr();o=setTimeout(()=>{t.value&&(t.value=!1,n.removeEventListener(`abort`,i),e.reject(`timed-out`))},r),a.push(e.promise)}try{let e=await Promise.race(a);return n.removeEventListener(`abort`,i),o!==void 0&&clearTimeout(o),{action:e.action,resumeData:e.resumeData,timedOut:!1,wasCancelled:!1,reason:e.reason}}catch(e){return o!==void 0&&clearTimeout(o),n.removeEventListener(`abort`,i),e===`timed-out`?{action:`reject`,resumeData:null,timedOut:!0,wasCancelled:!1}:{action:`reject`,resumeData:null,timedOut:!1,wasCancelled:!0}}}async function Or(e,t,n,r,i,a){let o={required:e.suspensionStrategy!==`wait-in-process`};if(a.timedOut){let a=Date.now();if(r.autoAction===`approve`){let s=V(i,Tr);return s.valid?(await U(e,{...r,status:`resumed`,resumeData:Tr,resolvedAt:a},o),await W(e,t.id,n,{action:`approve`,source:`timeout`}),{status:`completed`,output:{resumeData:Tr}}):(await U(e,{...r,status:`timed-out`,resolvedAt:a},o),await W(e,t.id,n,{action:`reject`,source:`timeout`}),{status:`failed`,error:`Gate '${t.id}' auto-approve timeout resume data does not match resumeSchema: ${s.error}`})}return await U(e,{...r,status:`timed-out`,resolvedAt:a},o),await W(e,t.id,n,{action:`reject`,source:`timeout`}),{status:`failed`,error:`Gate '${t.id}' timed out after ${String(r.timeoutMs)}ms and auto-rejected`}}if(a.wasCancelled||e.signal.aborted)return await U(e,{...r,status:`cancelled`,resolvedAt:Date.now()},o),await W(e,t.id,n,{source:`cancelled`}),{status:`cancelled`};let s=Date.now();await U(e,{...r,status:a.action===`reject`?`rejected`:`resumed`,resumeData:a.resumeData,...Er(a.reason),resolvedAt:s},o);try{await e.bus.emit(T.gate.resumed,{executionId:e.executionId,frameId:n,nodeId:t.id,resumeData:a.resumeData}),await W(e,t.id,n,{action:a.action,source:`user`,...Er(a.reason)})}catch(e){console.error(`[GateNode] gate.resumed emit failed for '${t.id}':`,e)}return{status:`completed`,output:{resumeData:a.resumeData}}}async function kr(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=e.resumeSchema??{};if(t.suspensionStrategy!==`wait-in-process`){let n=await Nr(t,e,r);if(n!==void 0)return n}let a=B(e.id,e.resumeSchema);return a.status===`failed`?{status:`failed`,error:a.error}:Ar(t,e,n,r,i,a.validator)}async function Ar(e,t,n,r,i,a){let o=j(t.prompt,I(n)),s={executionId:e.executionId,nodeId:t.id,frameId:r,schema:i,prompt:o,status:`waiting`,autoAction:t.autoAction,timeoutMs:t.timeoutMs,createdAt:Date.now()},c=e.suspensionStrategy!==`wait-in-process`;if(await U(e,s,{required:c}),await e.updateFrame(r,{status:`waiting`},{requireFrameStorage:c}),c)return await jr(e,t,r,i,o,s.createdAt),{status:`paused`,pausedAtGateId:t.id,pausedAtFrameId:r};let u={value:!0},d=wr(),f=e.bus.on(T.gate.respond,async n=>{let{executionId:i,gateId:o,frameId:s,action:c,resumeData:f,reason:p}=n.payload;if(i!==e.executionId||o!==t.id||s!==void 0&&s!==r){try{await n.next()}catch(e){if(e instanceof l)n.setResult({accepted:!1});else throw e}return}if(!u.value){n.setResult({accepted:!1});return}if(!V(a,f).valid){n.setResult({accepted:!1});return}u.value=!1,n.setResult({accepted:!0}),d.resolve({action:c,resumeData:f,reason:p})});await jr(e,t,r,i,o,s.createdAt);let p=await Dr(d,u,e.signal,t.timeoutMs);return f(),Or(e,t,r,s,a,p)}async function jr(e,t,n,r,i,a){try{await e.bus.emit(T.gate.suspended,{executionId:e.executionId,frameId:n,nodeId:t.id,schema:r,prompt:i,...t.title!==void 0&&{title:t.title},autoAction:t.autoAction,timeoutMs:t.timeoutMs,openedAt:a})}catch(e){console.error(`[GateNode] gate.suspended emit failed for '${t.id}':`,e)}}async function Mr(e,t,n){if(e.suspensionStrategy!==`wait-in-process`)return(await e.bus.request(N.getGateInstance,{executionId:e.executionId,nodeId:t,frameId:n})).gate;let r=await e.bus.requestOptional(N.getGateInstance,{executionId:e.executionId,nodeId:t,frameId:n});return r.handled?r.data.gate:null}async function Nr(e,t,n){let r=await Mr(e,t.id,n);if((r?.status===`resumed`||r?.status===`rejected`)&&r.resumeData!==void 0){let i=H(t.id,r.schema,r.resumeData);if(!i.valid)return{status:`failed`,error:`Gate '${t.id}' persisted resumeData is invalid: ${i.error}`};try{await e.bus.emit(T.gate.resumed,{executionId:e.executionId,frameId:n,nodeId:t.id,resumeData:r.resumeData})}catch(e){console.error(`[GateNode] gate.resumed emit failed for '${t.id}':`,e)}return await W(e,t.id,n,{action:r.status===`rejected`?`reject`:`approve`,source:`user`,...Er(r.reason)}),{status:`completed`,output:{resumeData:r.resumeData}}}if(r?.status===`waiting`){if(r.timeoutMs!==null&&Date.now()>=r.createdAt+r.timeoutMs){let i=B(t.id,r.schema);return i.status===`failed`?{status:`failed`,error:i.error}:Or(e,t,n,r,i.validator,{action:`reject`,resumeData:null,timedOut:!0,wasCancelled:!1})}return{status:`paused`,pausedAtGateId:t.id,pausedAtFrameId:n}}if((r?.status===`resumed`||r?.status===`rejected`)&&r.resumeData===void 0)return{status:`failed`,error:`Gate '${t.id}' has status '${r.status}' but resumeData is missing — cannot reconstruct output`};if(r!==null)return{status:`failed`,error:`Gate '${t.id}' cannot resume from status '${r.status}'`}}async function U(e,t,n={}){try{n.required===!0?await e.bus.request(N.setGateInstance,{gate:t}):await e.bus.requestOptional(N.setGateInstance,{gate:t})}catch(e){if(n.required===!0)throw e;console.warn(`[GateNode] Failed to upsert gate instance for '${t.nodeId}':`,e)}}async function W(e,t,n,r){try{await e.bus.emit(T.gate.resolved,{executionId:e.executionId,stepId:t,stepType:`gate`,frameId:n,...r})}catch(e){console.error(`[GateNode] gate.resolved emit failed for '${t}':`,e)}}function G(e){return{status:`fulfilled`,...e===void 0?{}:{value:e}}}const Pr=new Set([`completed`,`running`]);function Fr(e,t){return e.status===`running`&&t.pauseSignal?.aborted===!0&&!t.outerSignal.aborted}async function Ir(e,t,n,r,i,a){if(t.signal.aborted)return{status:`cancelled`};let o=lr(e.id,`iterate`,e.collection,n);if(!Array.isArray(o))return o;let s=o;if(s.length===0)return{status:`completed`,output:Br([])};let c=await Lr(s,e,t,n,r,i,a,e.concurrency!==void 0&&e.concurrency>0?e.concurrency:0);if(t.signal.aborted&&c.every(e=>e.status===`cancelled`))return{status:`cancelled`};let l=c.find(e=>e.status===`paused`);return l===void 0?{status:`completed`,output:Br(c)}:{status:`paused`,pausedAtGateId:l.pausedAtGateId,pausedAtFrameId:l.pausedAtFrameId}}async function Lr(e,t,n,r,i,a,o,s){let c=new AbortController,l=n.suspensionStrategy!==`wait-in-process`,u=l?z(n.signal,c.signal):n.signal,d=u===n.signal?n:n.withSignal(u),f={outerSignal:n.signal,...l?{pauseSignal:c.signal}:{}};if(s===0){let n=e.map((e,n)=>zr(e,n,t,d,r,i,a,o,f));return Promise.all(l?n.map(e=>Rr(e,c)):n)}let p=Array(e.length);for(let n=0;n<e.length;n+=s){if(d.signal.aborted){for(let t=n;t<e.length;t++)p[t]={status:`cancelled`};break}let u=Math.min(n+s,e.length),m=[];for(let s=n;s<u;s++)m.push(zr(e[s],s,t,d,r,i,a,o,f));let h=await Promise.all(l?m.map(e=>Rr(e,c)):m);for(let e=0;e<h.length;e++)p[n+e]=h[e];if(h.some(e=>e.status===`paused`)){for(let t=u;t<e.length;t++)p[t]={status:`cancelled`};break}}return p}function Rr(e,t){return e.then(e=>(e.status===`paused`&&t.abort(),e))}async function zr(e,t,n,r,i,a,o,s,c){if(r.signal.aborted)return{status:`cancelled`};let l={...i,item:e,index:t},u=L(r.resumeFrames,n.id,{parentFrameId:o,iteration:t,statuses:Pr});if(u?.status===`completed`)return G(u.output);let d=u??r.createFrame({nodeId:n.id,nodeType:`iterate`,path:s,parentFrameId:o,iteration:t});if(r.signal.aborted)return Fr(d,c)||await $(d,r),{status:`cancelled`};u===void 0&&await X(d,r);let f;try{f=await a(n.body,r,l,d.frameId,d.path)}catch(e){let t=e instanceof Error?e.message:String(e);return await Q(d,r,t),{status:`rejected`,reason:t}}switch(f.status){case`completed`:{let e=dr(n,d.frameId,r);return await Z(d,r,e),G(e)}case`skipped`:return await Z(d,r),G();case`cancelled`:return Fr(d,c)||await $(d,r),{status:`cancelled`};case`paused`:return f;case`failed`:return await Q(d,r,f.error),{status:`rejected`,reason:f.error}}}function Br(e){return{items:e}}const Vr=new Set([`completed`,`running`]);async function Hr(e,t,n,r,i,a){if(t.signal.aborted)return{status:`cancelled`};let o=lr(e.id,`iterate-chain`,e.collection,n);if(!Array.isArray(o))return o;let s=o;if(s.length===0)return{status:`completed`,output:Wr([])};let c=[],l;for(let o=0;o<s.length;o++){if(t.signal.aborted)return{status:`cancelled`};let u=s[o],d=await Ur(u,o,l,e,t,n,r,i,a);switch(c.push(d),d.status){case`fulfilled`:l=d.value;break;case`rejected`:return{status:`failed`,error:d.reason};case`cancelled`:return{status:`cancelled`};case`paused`:return{status:`paused`,pausedAtGateId:d.pausedAtGateId,pausedAtFrameId:d.pausedAtFrameId}}}return{status:`completed`,output:Wr(c)}}async function Ur(e,t,n,r,i,a,o,s,c){if(i.signal.aborted)return{status:`cancelled`};let l={...a,item:e,index:t,...n!==void 0&&{previous:n}},u=L(i.resumeFrames,r.id,{parentFrameId:s,iteration:t,statuses:Vr});if(u?.status===`completed`)return G(u.output);let d=u??i.createFrame({nodeId:r.id,nodeType:`iterate-chain`,path:c,parentFrameId:s,iteration:t});if(i.signal.aborted)return await $(d,i),{status:`cancelled`};u===void 0&&await X(d,i);let f;try{f=await o(r.body,i,l,d.frameId,d.path)}catch(e){let t=e instanceof Error?e.message:String(e);return await Q(d,i,t),{status:`rejected`,reason:t}}switch(f.status){case`completed`:{let e=dr(r,d.frameId,i);return await Z(d,i,e),G(e)}case`skipped`:return await Z(d,i),G();case`cancelled`:return await $(d,i),{status:`cancelled`};case`paused`:return f;case`failed`:return await Q(d,i,f.error),{status:`rejected`,reason:f.error}}}function Wr(e){return{items:e}}async function Gr(e,t,n,r){let i=()=>{t.value&&(t.value=!1,e.reject(`cancelled`))};n.addEventListener(`abort`,i,{once:!0}),n.aborted&&i();let a=[e.promise],o;if(r!==null){let e=new Promise((e,a)=>{o=setTimeout(()=>{t.value&&(t.value=!1,n.removeEventListener(`abort`,i),a(`timed-out`))},r)});a.push(e)}try{return{status:`resolved`,value:await Promise.race(a)}}catch(e){if(e===`timed-out`)return{status:`timed-out`};if(e===`cancelled`)return{status:`cancelled`};throw e}finally{o!==void 0&&clearTimeout(o),n.removeEventListener(`abort`,i)}}const K={action:`approve`,source:`timeout`};async function q(e,t,n){try{n?await e.bus.request(N.setGateInstance,{gate:t}):await e.bus.requestOptional(N.setGateInstance,{gate:t})}catch(e){if(n)throw e;console.warn(`[LoopNode] Failed to upsert escalation gate for '${t.nodeId}':`,e)}}async function Kr(e,t,n,r,i,a){try{await e.bus.emit(T.gate.suspended,{executionId:e.executionId,frameId:n,nodeId:t.id,schema:r,prompt:i,...t.gate.escalation?.title!==void 0&&{title:t.gate.escalation.title},autoAction:t.gate.escalation?.autoAction??`reject`,timeoutMs:t.gate.escalation?.timeoutMs??null,openedAt:a})}catch(e){console.error(`[LoopNode] gate.suspended emit failed for '${t.id}':`,e)}}async function J(e,t,n,r){try{await e.bus.emit(T.gate.resolved,{executionId:e.executionId,stepId:t,stepType:`gate`,frameId:n,...r})}catch(e){console.error(`[LoopNode] gate.resolved emit failed for '${t}':`,e)}}function qr(e){let{node:t,ctx:n,parentFrameId:r,validator:i,pending:a,deferred:o}=e;return n.bus.on(T.gate.respond,async e=>{let{executionId:s,gateId:c,frameId:u,action:d,resumeData:f,reason:p}=e.payload;if(s!==n.executionId||c!==t.id||u!==void 0&&u!==r){try{await e.next()}catch(t){if(t instanceof l)e.setResult({accepted:!1});else throw t}return}if(!a.value){e.setResult({accepted:!1});return}if(!V(i,f).valid){e.setResult({accepted:!1});return}a.value=!1,e.setResult({accepted:!0}),o.resolve({action:d,resumeData:f,reason:p})})}async function Jr(e,t,n,r,i,a,o){let s=B(e.id,e.gate.escalation?.resumeSchema);if(s.status===`failed`)return{status:`failed`,error:s.error};let c={value:!0},l=wr(),u=qr({node:e,ctx:t,parentFrameId:n,validator:s.validator,pending:c,deferred:l});await Kr(t,e,n,r.schema,r.prompt??``,r.createdAt);try{let s=await Gr(l,c,t.signal,r.timeoutMs);return s.status===`timed-out`?Zr(t,e,n,r,i,a,o,!1):s.status===`resolved`?Yr(t,e.id,n,r,s.value,i,a,o):(await q(t,{...r,status:`cancelled`,resolvedAt:Date.now()},!1),await J(t,e.id,n,{source:`cancelled`}),{status:`cancelled`})}finally{u()}}async function Yr(e,t,n,r,i,a,o,s){let c=Date.now(),l=i.action===`reject`?`rejected`:`resumed`;await q(e,{...r,status:l,resumeData:i.resumeData,...i.reason===void 0?{}:{reason:i.reason},resolvedAt:c},!1);try{await e.bus.emit(T.gate.resumed,{executionId:e.executionId,frameId:n,nodeId:t,resumeData:i.resumeData}),await J(e,t,n,{action:i.action,source:`user`,...i.reason===void 0?{}:{reason:i.reason}})}catch(e){console.error(`[LoopNode] gate.resumed emit failed for '${t}':`,e)}return{status:`completed`,output:Y(`escalate`,o,a,s,i.resumeData)}}async function Xr(e,t,n,r,i,a,o){let s=e.gate.escalation;if(s===void 0)return{status:`completed`,output:Y(`escalate`,a,i,o)};let c=j(s.prompt,I(n)),l=s.resumeSchema??{},u={executionId:t.executionId,nodeId:e.id,frameId:r,schema:l,prompt:c,status:`waiting`,autoAction:s.autoAction??`reject`,timeoutMs:s.timeoutMs??null,createdAt:Date.now()},d=t.suspensionStrategy!==`wait-in-process`;return await q(t,u,d),await t.updateFrame(r,{status:`waiting`},{requireFrameStorage:d}),d?(await Kr(t,e,r,l,c,u.createdAt),{status:`paused`,pausedAtGateId:e.id,pausedAtFrameId:r}):Jr(e,t,r,u,i,a,o)}async function Zr(e,t,n,r,i,a,o,s=!0){let c=Date.now();if(r.autoAction===`approve`){let l=H(t.id,r.schema,K);return l.valid?(await q(e,{...r,status:`resumed`,resumeData:K,resolvedAt:c},s),await J(e,t.id,n,{action:`approve`,source:`timeout`}),{status:`completed`,output:Y(`escalate`,a,i,o,K)}):(await q(e,{...r,status:`timed-out`,resolvedAt:c},s),await J(e,t.id,n,{action:`reject`,source:`timeout`}),{status:`failed`,error:`Loop '${t.id}' escalation gate auto-approve timeout resume data does not match resumeSchema: ${l.error}`})}return await q(e,{...r,status:`timed-out`,resolvedAt:c},s),await J(e,t.id,n,{action:`reject`,source:`timeout`}),{status:`failed`,error:`Loop '${t.id}' escalation gate timed out after ${String(r.timeoutMs)}ms and auto-rejected`}}async function Qr(e,t,n){if(e.suspensionStrategy!==`wait-in-process`)return(await e.bus.request(N.getGateInstance,{executionId:e.executionId,nodeId:t,frameId:n})).gate;let r=await e.bus.requestOptional(N.getGateInstance,{executionId:e.executionId,nodeId:t,frameId:n});return r.handled?r.data.gate:null}async function $r(e,t,n,r,i,a){let o=await Qr(e,t.id,n);if(o!==null){if((o.status===`resumed`||o.status===`rejected`)&&o.resumeData!==void 0){let s=H(t.id,o.schema,o.resumeData);if(!s.valid)return{status:`failed`,error:`Loop '${t.id}' escalation gate resumeData is invalid: ${s.error}`};try{await e.bus.emit(T.gate.resumed,{executionId:e.executionId,frameId:n,nodeId:t.id,resumeData:o.resumeData})}catch(e){console.error(`[LoopNode] gate.resumed emit failed for '${t.id}':`,e)}return await J(e,t.id,n,{action:o.status===`rejected`?`reject`:`approve`,source:`user`,...o.reason===void 0?{}:{reason:o.reason}}),{status:`completed`,output:Y(`escalate`,i,r,a,o.resumeData)}}return o.status===`waiting`?o.timeoutMs!==null&&Date.now()>=o.createdAt+o.timeoutMs?Zr(e,t,n,o,r,i,a):{status:`paused`,pausedAtGateId:t.id,pausedAtFrameId:n}:(o.status===`resumed`||o.status===`rejected`)&&o.resumeData===void 0?{status:`failed`,error:`Loop '${t.id}' escalation gate has status '${o.status}' but resumeData is missing`}:{status:`failed`,error:`Loop '${t.id}' escalation gate cannot resume from status '${o.status}'`}}}const ei=new Set([`completed`,`running`]);async function ti(e,t,n,r,i,a,o){let s=L(n.resumeFrames,e.id,{parentFrameId:a,iteration:t,statuses:ei});if(s?.status===`completed`)return{terminal:!1,output:s.output??null,replayed:!0,gateExpressionCtx:ri(e,n,r,s.frameId)};let c=s??n.createFrame({nodeId:e.id,nodeType:`loop`,path:o,parentFrameId:a,iteration:t});if(n.signal.aborted)return await $(c,n),{terminal:!0,outcome:{status:`cancelled`}};s===void 0&&await X(c,n);let l=await ii(e,c,n,r,i);if(l!==void 0)return{terminal:!0,outcome:l};let u=ur(e.body,c.frameId,n)??null;return await Z(c,n,u),{terminal:!1,output:u,replayed:!1,gateExpressionCtx:ri(e,n,r,c.frameId)}}function ni(e,t,n,r){return L(n.resumeFrames,e.id,{parentFrameId:r,iteration:t,statuses:ei})!==void 0}function ri(e,t,n,r){let i=n;for(let n of e.body.nodes){let e=t.getFramesByNodeId(n.id).find(e=>e.parentFrameId===r&&e.status===`completed`);e!==void 0&&(i=R(i,n.id,{status:`completed`,...e.output===void 0?{}:{output:e.output}}))}return i}async function ii(e,t,n,r,i){let a;try{a=await i(e.body,n,r,t.frameId,t.path)}catch(e){let r=e instanceof Error?e.message:String(e);return await Q(t,n,r),{status:`failed`,error:r}}switch(a.status){case`failed`:return await Q(t,n,a.error),{status:`failed`,error:a.error};case`cancelled`:return await $(t,n),{status:`cancelled`};case`paused`:return a;case`skipped`:case`completed`:return}}function ai(e,t,n,r,i){let a=null;if(e.gate.input!==void 0)try{let t=I(r);a=A(e.gate.input,t)}catch(t){let n=t instanceof Error?t.message:String(t);return{status:`failed`,error:`Loop node '${e.id}': gate input expression evaluation failed: ${n}`}}let o=e.gate.config??null,s=i(a,o,{executionId:n.executionId,nodeId:e.id,round:t+1,maxRounds:e.maxRounds});return s.kind===`loop`&&t+1>=e.maxRounds?{kind:`escalate`,reason:`max_rounds_reached`}:s}async function oi(e,t,n,r,i,a){if(t.signal.aborted)return{status:`cancelled`};let o=t.runtimeLoopGates.get(e.gate.handler);if(o===void 0)return{status:`failed`,error:`Loop node '${e.id}': no gate handler registered for '${e.gate.handler}'`};let s=[],c=0;for(;;){if(t.signal.aborted)return{status:`cancelled`};let l=await ti(e,c,t,n,r,i,a);if(l.terminal)return l.outcome;if(s.push(l.output),l.replayed){if(c++,ni(e,c,t,i))continue;if(e.gate.escalation!==void 0&&t.suspensionStrategy!==`wait-in-process`){let n=await $r(t,e,i,{kind:`escalate`,reason:`resumed_from_gate`},c,s);if(n!==void 0)return n}continue}let u=ai(e,c,t,l.gateExpressionCtx,o);if(`status`in u)return u;if(u.kind===`pass`)return{status:`completed`,output:Y(`pass`,c+1,u,s)};if(u.kind===`escalate`)return e.gate.escalation===void 0?{status:`completed`,output:Y(`escalate`,c+1,u,s)}:Xr(e,t,n,i,u,c+1,s);c++}}function Y(e,t,n,r,i){return{outcome:e,rounds:t,lastGateOutcome:n,bodyOutputs:r,...i===void 0?{}:{resumeData:i}}}async function X(e,t){e.status=`running`,e.startedAt=Date.now(),await t.persistFrame(e),await t.emitFrameStarted(e)}async function Z(e,t,n){let r=Date.now(),i=e.startedAt===void 0?void 0:Math.max(0,r-e.startedAt);e.status=`completed`,e.output=n,e.completedAt=r,await t.persistFrame(e),await t.emitFrameCompleted(e,i)}async function Q(e,t,n){let r=Date.now(),i=e.startedAt===void 0?void 0:Math.max(0,r-e.startedAt);e.status=`failed`,e.error=n,e.completedAt=r,await t.persistFrame(e),await t.emitFrameFailed(e,n,i)}async function si(e,t){e.status=`skipped`,e.completedAt=Date.now(),await t.persistFrame(e)}async function $(e,t){e.status=`cancelled`,e.completedAt=Date.now(),await t.persistFrame(e)}function ci(e,t){return!!A(e,I(t))}async function li(e,t,n,r,i,a=[]){if(t.signal.aborted)return{status:`cancelled`};switch(e.type){case`sequence`:return r(e,t,n,i,a);case`station`:return Gn(e,t,n,i);case`delegate-agent`:return qn(e,t,n,i);case`delegate-role`:return Jn(e,t,n,i);case`parallel`:return gr(e,t,n,r,i??``,a,e.mode??`all-settled`);case`gate`:return kr(e,t,n,i??``);case`iterate`:return Ir(e,t,n,r,i??``,a);case`iterate-chain`:return Hr(e,t,n,r,i??``,a);case`loop`:return oi(e,t,n,r,i??``,a);default:return{status:`failed`,error:`Unknown node type: ${String(e.type)}`}}}const ui=new Set([`completed`,`skipped`,`waiting`,`running`]);function di(e){return e.type===`parallel`||e.type===`iterate`||e.type===`iterate-chain`||e.type===`loop`}function fi(e,t,n){return L(e.resumeFrames,t.id,{parentFrameId:n,...di(t)?{statuses:ui}:{}})}function pi(e,t,n){if(n?.status===`completed`)return R(e,t.id,{status:`completed`,...n.output===void 0?{}:{output:n.output}});if(n?.status===`skipped`)return R(e,t.id,{status:`skipped`})}async function mi(e,t,n,r,i,a,o){try{return{result:ci(e,i)}}catch(e){let i=e instanceof Error?e.message:String(e);return await Q(r.createFrame({nodeId:n.id,nodeType:n.type,path:a,parentFrameId:o}),r,`'${t}' condition evaluation failed: ${i}`),{status:`failed`,error:`'${t}' condition evaluation failed for '${n.id}': ${i}`}}}async function hi(e,t,n,r,i,a){let o=a??t.createFrame({nodeId:e.id,nodeType:e.type,path:r,parentFrameId:i});if(t.signal.aborted)return await $(o,t),{updatedCtx:n,outcome:{status:`cancelled`}};a===void 0&&await X(o,t);let s;try{s=await li(e,t,n,gi,o.frameId,o.path)}catch(e){let r=e instanceof Error?e.message:String(e);return await Q(o,t,r),{updatedCtx:n,outcome:{status:`failed`,error:r}}}switch(s.status){case`completed`:return await Z(o,t,s.output),{updatedCtx:R(n,e.id,{status:`completed`,output:s.output})};case`skipped`:return await si(o,t),{updatedCtx:R(n,e.id,{status:`skipped`})};case`cancelled`:return await $(o,t),{updatedCtx:n,outcome:{status:`cancelled`}};case`paused`:return{updatedCtx:n,outcome:s};case`failed`:return await Q(o,t,s.error),{updatedCtx:n,outcome:{status:`failed`,error:s.error}}}}async function gi(e,t,n,r,i=[]){let a=n;for(let n of e.nodes){if(t.signal.aborted)return{status:`cancelled`};let e=fi(t,n,r),o=pi(a,n,e);if(o!==void 0){a=o;continue}if(n.when!==void 0){let e=await mi(n.when,`when`,n,t,a,i,r);if(`status`in e)return e;if(!e.result){await si(t.createFrame({nodeId:n.id,nodeType:n.type,path:i,parentFrameId:r}),t),a=R(a,n.id,{status:`skipped`});continue}}if(n.skip!==void 0){let e=await mi(n.skip,`skip`,n,t,a,i,r);if(`status`in e)return e;if(e.result){await si(t.createFrame({nodeId:n.id,nodeType:n.type,path:i,parentFrameId:r}),t),a=R(a,n.id,{status:`skipped`});continue}}let s=e?.status===`waiting`&&n.type===`gate`||(e?.status===`running`||e?.status===`waiting`)&&di(n)?e:void 0,{updatedCtx:c,outcome:l}=await hi(n,t,a,i,r,s);if(a=c,l!==void 0)return l}return{status:`completed`}}function _i(e,t){let n=new Set;if(pe(e.root,{enter(e){if(e.type!==`loop`)return;let r=e;t.has(r.gate.handler)||n.add(r.gate.handler)}}),n.size>0)throw Error(`Workflow '${e.id}' is missing loop gate handler(s): ${[...n].join(`, `)}`)}export{Ue as A,ke as B,N as C,we as D,Te as E,M as F,Ie as G,ze as H,De as I,Fe as J,Ve as K,Ee as L,Ge as M,We as N,je as O,Ce as P,Ne as R,Xe as S,xe as T,Re as U,Oe as V,Le as W,le as X,Pe as Y,T as Z,P as _,En as a,ot as b,ln as c,Jt as d,Vt as f,Tt as g,F as h,fr as i,He as j,Ae as k,pn as l,Ot as m,gi as n,yn as o,At as p,Be as q,H as r,Yt as s,_i as t,un as u,Ct as v,Se as w,Qe as x,_t as y,Me as z};