@makaio/framework 1.0.0-dev-1787949057928 → 1.0.0-dev-1788511348215

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 (79) hide show
  1. package/dist/.makaio-build.json +2 -2
  2. package/dist/attempt-record-codec-dC9LSFUE.mjs +1 -0
  3. package/dist/authority-state-bootstrap-eitx6Ukn.mjs +1 -0
  4. package/dist/bus/index.mjs +1 -1
  5. package/dist/capabilities-DEvmD9VJ.mjs +1 -0
  6. package/dist/contracts/artifact/index.d.mts +1 -1
  7. package/dist/contracts/capabilities/index.d.mts +2 -2
  8. package/dist/contracts/capabilities/index.mjs +1 -1
  9. package/dist/contracts/client/index.d.mts +1 -1
  10. package/dist/contracts/extension/index.d.mts +2 -2
  11. package/dist/contracts/index.d.mts +12 -12
  12. package/dist/contracts/index.mjs +1 -1
  13. package/dist/contracts/worker/index.d.mts +2 -0
  14. package/dist/contracts/worker/index.mjs +1 -0
  15. package/dist/contracts/workflow/index.d.mts +1 -1
  16. package/dist/contracts/workflow/index.mjs +1 -1
  17. package/dist/{execution-attempt-repository-BJ2W6wwx.d.mts → execution-attempt-repository-DY4KTptE.d.mts} +359 -57
  18. package/dist/{index-8NdPPzUh2.d.mts → index-6trZYnUP2.d.mts} +12 -12
  19. package/dist/{index-CPi0UpRh.d.mts → index-B_8bA2JW.d.mts} +1 -1
  20. package/dist/{index-DfUpqwBa2.d.mts → index-BmilK-co2.d.mts} +53 -53
  21. package/dist/{index-CMekqu_D.d.mts → index-C6aSnO8m.d.mts} +42 -42
  22. package/dist/{index-BUwDmh1I.d.mts → index-CDud4NAm.d.mts} +10 -10
  23. package/dist/{index-CYjgoYeX.d.mts → index-DHH-93YD.d.mts} +1 -1
  24. package/dist/{index-B9io6JAL.d.mts → index-DI2lS7VT.d.mts} +1 -1
  25. package/dist/{index-cLB38AWX.d.mts → index-DNI6UF9h.d.mts} +60 -60
  26. package/dist/{index-NUByQvlg.d.mts → index-DXtQRehh.d.mts} +14 -14
  27. package/dist/{index-CVNbBtA-.d.mts → index-Wbd_syN2.d.mts} +112 -112
  28. package/dist/kernel/extension/index.d.mts +1 -1
  29. package/dist/kernel/index.d.mts +2 -2
  30. package/dist/kernel/observability/index.d.mts +1 -1
  31. package/dist/{namespace-C06lJSuj.d.mts → namespace-K23m4b0n.d.mts} +6 -6
  32. package/dist/package-Cgjpm9om.mjs +7 -0
  33. package/dist/{package-BNFTUFLB.d.mts → package-efR90JGe.d.mts} +59 -30
  34. package/dist/package.json +1 -1
  35. package/dist/runtime-node/index.d.mts +1 -1
  36. package/dist/runtime-node/index.mjs +1 -1
  37. package/dist/runtime-node/makaio-config.d.mts +2 -2
  38. package/dist/runtime-node/makaio-config.mjs +1 -1
  39. package/dist/runtime-node/workflow-execution-bus-access.mjs +1 -1
  40. package/dist/runtime-node/workflow-worker/index.d.mts +2 -2
  41. package/dist/runtime-node/workflow-worker/index.mjs +1 -1
  42. package/dist/{schemas-OWvBn7AH.d.mts → schemas-BCXvEWyF.d.mts} +4 -4
  43. package/dist/{schemas-BAv9RB9M.d.mts → schemas-D7EeKBDJ.d.mts} +3 -3
  44. package/dist/services/adapter-subsystem/index.d.mts +2 -2
  45. package/dist/services/adapter-subsystem/namespace.d.mts +1 -1
  46. package/dist/services/filesystem/namespace.d.mts +6 -6
  47. package/dist/services/filesystem/schemas.d.mts +3 -3
  48. package/dist/services/index.d.mts +9 -9
  49. package/dist/services/provider-context/index.d.mts +1 -1
  50. package/dist/services/session/index.d.mts +1 -1
  51. package/dist/services/settings/namespace.d.mts +2 -2
  52. package/dist/services/subagent-template/index.d.mts +1 -1
  53. package/dist/services/subagent-template/schemas.d.mts +1 -1
  54. package/dist/worker-CARV52hT.mjs +1 -0
  55. package/dist/worker-CLsRbzpk.mjs +1 -0
  56. package/dist/workflow-BomH9DBB.mjs +1 -0
  57. package/dist/workflow-engine/execution-attempt-repository.d.mts +2 -2
  58. package/dist/workflow-engine/execution-attempt-repository.mjs +1 -1
  59. package/dist/workflow-engine/index.d.mts +178 -23
  60. package/dist/workflow-engine/index.mjs +1 -1
  61. package/dist/workflow-engine/package.d.mts +1 -1
  62. package/dist/workflow-engine/package.mjs +1 -1
  63. package/dist/workflow-engine/testing/index.d.mts +30 -9
  64. package/dist/workflow-engine/testing/index.mjs +1 -1
  65. package/dist/workflow-engine/testing/sqlite.d.mts +3 -2
  66. package/dist/workflow-engine/testing/sqlite.mjs +20 -20
  67. package/dist/workflow-engine/workflow-orchestrator.mjs +1 -1
  68. package/dist/workflow-worker-Dul-wcOR.mjs +1 -0
  69. package/package.json +4 -4
  70. package/dist/attempt-record-codec-BYfYkj4M.mjs +0 -1
  71. package/dist/authority-state-bootstrap-CLYus369.mjs +0 -1
  72. package/dist/capabilities-BUwuA7XX.mjs +0 -1
  73. package/dist/contracts/worker-node/index.d.mts +0 -2
  74. package/dist/contracts/worker-node/index.mjs +0 -1
  75. package/dist/package-B01gmu75.mjs +0 -7
  76. package/dist/worker-node-CjuQb9hl.mjs +0 -1
  77. package/dist/worker-node-Dtf9ilsR.mjs +0 -1
  78. package/dist/workflow-C4mck_NW.mjs +0 -1
  79. package/dist/workflow-worker-aNbdgqml.mjs +0 -1
@@ -1 +0,0 @@
1
- import{o as e}from"./chunk-DTipWd-i.mjs";import{t}from"./ajv-krzJXh1X.mjs";import{z as n}from"zod";import{execFile as r}from"node:child_process";import{isDeepStrictEqual as i}from"node:util";import{isAbsolute as a,relative as o,resolve as s}from"node:path";import{realpathSync as c}from"node:fs";import{localSubject as l}from"@makaio/framework/core";import{NoHandlerError as u}from"@makaio/framework/bus";import{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,WorkflowFinalizationClaimSchema as w,WorkflowFinalizerIdSchema as oe,WorkflowFrameStateSchema as se,WorkflowGateInstanceSchema as T,WorkflowListQuerySchema as ce,WorkflowRunContextSchema as le,WorkflowSchemas as ue,WorkflowSubjects as de,WorkflowSubjects as E,createStepCancelSubject as fe,createWorkflowDelegateResultFinalizerNamespace as pe,walkWorkflowDefinition as me}from"@makaio/framework/contracts";import{index as D,primaryKey as he,uniqueIndex as ge}from"drizzle-orm/sqlite-core";import{index as O,primaryKey as _e,uniqueIndex as ve}from"drizzle-orm/pg-core";import{defineDualTable as k}from"@makaio/framework/storage/drizzle";import{sql as ye}from"drizzle-orm";import{createStorageNamespaceDefinition as be}from"@makaio/framework/storage";import{evaluateSync as A,resolveTemplate as j}from"@makaio/framework/expression";import*as xe from"node:os";const Se=k(`workflow_finalizations`,e=>({executionId:e.text(`execution_id`).primaryKey().references(()=>M.columnPair(`id`),{onDelete:`cascade`}),workflowId:e.text(`workflow_id`).notNull(),finalizerId:e.text(`finalizer_id`).notNull(),transitionKey:e.text(`transition_key`).notNull(),claimToken:e.text(`claim_token`).notNull(),intent:e.jsonCol(`intent`).notNull(),state:e.textEnum(`state`,{enum:[`claimed`,`acknowledged`,`failed`]}).notNull(),claimedAt:e.epochMs(`claimed_at`).notNull(),settledAt:e.epochMs(`settled_at`),failure:e.text(`failure`),publishedAt:e.epochMs(`published_at`)}),{sqlite:e=>[ge(`uniq_workflow_finalizations_transition`).on(e.transitionKey),D(`idx_workflow_finalizations_recovery`).on(e.finalizerId,e.state)],postgres:e=>[ve(`uniq_workflow_finalizations_transition`).on(e.transitionKey),O(`idx_workflow_finalizations_recovery`).on(e.finalizerId,e.state)]}),Ce=Se.sqlite;Se.postgres;function we(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 Te=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`),...we(e),createdAt:e.epochMs(`created_at`).notNull(),updatedAt:e.epochMs(`updated_at`).notNull(),canvasLayout:e.jsonCol(`canvas_layout`),source:e.jsonCol(`source`),executableSource:e.jsonCol(`executable_source`),requirements:e.jsonCol(`requirements`),successFinalizerId:e.text(`success_finalizer_id`)}),{sqlite:e=>[ge(`uniq_workflow_definitions_name_scope`).on(e.name,e.scopeType,e.scopeKind,e.scopeId),D(`idx_workflow_definitions_scope`).on(e.scopeType,e.scopeKind,e.scopeId)],postgres:e=>[ve(`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)]}),Ee=Te.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`,`finalizing`,`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`),...we(e)}),{sqlite:e=>[D(`idx_workflow_executions_status`).on(e.status),D(`idx_workflow_executions_scope_started`).on(e.scopeType,e.scopeKind,e.scopeId,e.startedAt),D(`idx_workflow_executions_workflow_started`).on(e.workflowId,e.startedAt),D(`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)]}),De=M.sqlite,Oe=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=>[D(`idx_workflow_execution_frames_execution`).on(e.executionId),D(`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)]}),ke=Oe.sqlite,Ae=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=>[D(`idx_workflow_gate_instances_execution`).on(e.executionId),D(`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)]}),je=Ae.sqlite,Me=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=>[he({columns:[e.executionId,e.frameId]}),D(`idx_workflow_step_spans_status`).on(e.status)],postgres:e=>[_e({columns:[e.executionId,e.frameId]}),O(`idx_workflow_step_spans_status`).on(e.status)]}),Ne=Me.sqlite,Pe=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=>[he({columns:[e.sourceExecutionId,e.targetExecutionId]}),D(`idx_workflow_execution_links_target`).on(e.targetExecutionId)],postgres:e=>[_e({columns:[e.sourceExecutionId,e.targetExecutionId]}),O(`idx_workflow_execution_links_target`).on(e.targetExecutionId)]}),Fe=Pe.sqlite,Ie=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(ye`'{}'`),triggerPayload:e.jsonCol(`trigger_payload`).notNull(),triggerMode:e.textEnum(`trigger_mode`,{enum:[`immediate`,`await-trigger`]}).notNull().default(`immediate`).$type(),artifactRef:e.jsonCol(`artifact_ref`),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(),env:e.jsonCol(`env`).notNull(),createdAt:e.epochMs(`created_at`).notNull(),suspensionStrategy:e.text(`suspension_strategy`).$type(),terminalAuthority:e.text(`terminal_authority`).$type(),materializationSpec:e.jsonCol(`materialization_spec`)}),{sqlite:e=>[D(`idx_run_contexts_workflow`).on(e.workflowId)],postgres:e=>[O(`idx_run_contexts_workflow`).on(e.workflowId)]}),Le=Ie.sqlite,Re=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`,`finalizing`,`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=>[D(`idx_worklog_summaries_workflow_started`).on(e.workflowId,e.startedAt),D(`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)]}),ze=Re.sqlite,Be=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=>[D(`idx_worklog_frame_entries_execution`).on(e.executionId)],postgres:e=>[O(`idx_worklog_frame_entries_execution`).on(e.executionId)]}),Ve=Be.sqlite,He=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=>[D(`idx_worklog_artifact_writes_execution`).on(e.executionId)],postgres:e=>[O(`idx_worklog_artifact_writes_execution`).on(e.executionId)]}),Ue=He.sqlite,We=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=>[D(`idx_worklog_gate_events_execution`).on(e.executionId),D(`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)]}),Ge=We.sqlite,Ke=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()})),qe=Ke.sqlite,Je=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=>[he({columns:[e.executionId,e.sequence]})],postgres:e=>[_e({columns:[e.executionId,e.sequence]})]}),Ye=Je.sqlite,Xe=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()}),Ze=n.enum([`completed`,`failed`,`cancelled`]),Qe=te.extend({status:n.literal(`running`),startedAt:n.number().int().nonnegative()}),$e=te.extend({status:Ze,startedAt:n.number().int().nonnegative(),completedAt:n.number().int().nonnegative(),durationMs:n.number().int().nonnegative()}),et=be(`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:ce,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:le,initialState:y.optional(),executionLinks:n.array(p).optional()}),response:n.object({id:n.string(),executionId:n.string()})},setExternalExecutionStart:l({request:n.object({execution:C.extend({status:n.literal(`running`)}),frame:Qe.optional()}),response:n.object({executionId:n.string(),frameId:n.string().optional()})}),settleExternalExecution:l({request:n.object({executionId:n.string().min(1),status:Ze,error:n.string().min(1).optional(),reason:n.string().min(1).optional(),completedAt:n.number().int().nonnegative().optional(),frame:$e.optional()}),response:n.object({success:n.boolean()})}),updateExecution:{request:Xe,response:n.object({success:n.boolean()})},pauseRunningExecution:l({request:n.object({executionId:n.string().min(1)}),response:n.object({paused:n.boolean()})}),claimFinalization:l({request:n.object({claim:w}),response:n.object({claimed:n.boolean()})}),listClaimedFinalizations:l({request:n.object({finalizerId:oe}),response:n.object({claims:n.array(w)})}),listUnpublishedFinalizations:l({request:n.object({finalizerId:oe}),response:n.object({claims:n.array(w)})}),publishFinalization:l({request:n.object({claim:w}),response:n.object({})}),acknowledgeFinalization:l({request:n.object({executionId:n.string().min(1),claimToken:n.string().min(1),settledAt:n.number().int().nonnegative()}),response:n.object({acknowledged:n.boolean()})}),failFinalization:l({request:n.object({executionId:n.string().min(1),claimToken:n.string().min(1),error:n.string().min(1),settledAt:n.number().int().nonnegative()}),response:n.object({failed: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(T.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:se}),response:n.object({frameId:n.string()})},getFrame:{request:n.object({frameId:n.string().min(1)}),response:n.object({frame:se.nullable()})},listFrames:{request:n.object({executionId:n.string().min(1)}),response:n.object({frames:n.array(se)})},setGateInstance:{request:n.object({gate:T}),response:n.object({id:n.string()})},resolveWaitingGateInstance:{request:n.object({gate:T.extend({status:n.enum([`resumed`,`rejected`])})}),response:n.object({accepted:n.boolean()})},restorePausedGateResumeState:{request:n.object({execution:C.extend({status:n.literal(`paused`)}),gate:T.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:T.nullable()})},listGateInstances:{request:_,response:n.object({gates:n.array(T)})},listPausedGateTimeouts:l({request:n.object({}),response:n.object({gates:n.array(T)})}),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:l({request:n.object({runContext:le,initialState:y.optional()}),response:n.object({executionId:n.string()})}),getRunContext:l({request:n.object({executionId:n.string().min(1)}),response:n.object({runContext:le.nullable()})}),initializeState:l({request:n.object({executionId:n.string().min(1),initialValue:y}),response:n.object({})}),getState:l({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:l({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:Ee,workflowExecutions:De,workflowExecutionFrames:ke,workflowGateInstances:je,workflowStepSpans:Ne,workflowExecutionLinks:Fe,workflowRunContexts:Le,worklogSummaries:ze,worklogFrameEntries:Ve,worklogArtifactWrites:Ue,worklogGateEvents:Ge,workflowExecutionState:qe,workflowExecutionStateEvents:Ye,workflowFinalizations:Ce}}}),N=et.subjects;var tt=e(t(),1);function nt(e){let t=e.transport?.peer;if(t?.authenticated!==!0||t.kind!==`workflow-execution-attempt`)return null;let n=t.id,r=t.claims?.executionId;return typeof n!=`string`||n.length===0||typeof r!=`string`||r.length===0?null:{executionAttemptId:n,executionId:r}}function rt(e,t){return e.origin.local?!0:nt(e)?.executionId===t}function it(e,t){let n=[];return at(n,``,e,t),n}function at(e,t,n,r){if(Array.isArray(n)&&Array.isArray(r)){st(e,t,n,r);return}if(ct(n)&&ct(r)){ot(e,t,n,r);return}dt(n,r)||e.push({op:`replace`,path:t,value:r})}function ot(e,t,n,r){let i=Array.from(new Set([...Object.keys(n),...Object.keys(r)])).sort();for(let a of i){let i=lt(n,a),o=lt(r,a),s=`${t}/${ut(a)}`;if(!i&&o){e.push({op:`add`,path:s,value:r[a]});continue}if(i&&!o){e.push({op:`remove`,path:s});continue}at(e,s,n[a],r[a])}}function st(e,t,n,r){let i=Math.min(n.length,r.length);for(let a=0;a<i;a++)at(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 ct(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function lt(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ut(e){return e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}function dt(e,t){return Object.is(e,t)}const ft={stepTimeoutMs:300*1e3,stepCooldownMs:500,busAuth:{kind:`none`},platformDefaults:{cwd:process.cwd()},cancelTimeoutMs:1e4},pt=new tt.default({allErrors:!0,strict:!1}),mt=new Map,ht=new Map;function gt(e){let t=e.$id;return typeof t==`string`?t:void 0}function _t(e,t,n){let r=gt(t);return r===void 0?`workflow:${e}:${n}`:`schema-id:${r}`}function vt(e,t){try{return JSON.stringify(yt(t))}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`Workflow '${e}' state schema is invalid: ${n}`)}}function yt(e){if(Array.isArray(e))return e.map(yt);if(typeof e!=`object`||!e)return e;let t=e;return Object.fromEntries(Object.keys(t).sort().map(e=>[e,yt(t[e])]))}function bt(e,t,n){let r=ht.get(t);if(r!==void 0&&r!==n)throw Error(`Workflow '${e}' state schema reuses JSON Schema $id '${t}' with different content`);return pt.getSchema(t)}function xt(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 St(e,t){let n=vt(e,t),r=_t(e,t,n),i=mt.get(r);if(i!==void 0)return i;let a=gt(t);if(a!==void 0){let t=bt(e,a,n);if(t!==void 0)return mt.set(r,t),t}try{let e=pt.compile(t);return mt.set(r,e),a!==void 0&&ht.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 Ct(e,t,n){if(e.state===void 0)return;let r=St(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: ${xt(r.errors)}`)}function wt(e){if(e.state===void 0)return;let t=e.state.initial===void 0?{}:e.state.initial;return Ct(e,t,`initial`),t}function Tt(e){return`${e}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Et(e,t,n){let r=e?j(e,n):t,i=s(t),l=s(a(r)?r:s(t,r)),u,d;try{u=c(i),d=c(l)}catch{return null}let f=o(process.platform===`win32`?u.toLowerCase():u,process.platform===`win32`?d.toLowerCase():d);return f===``||!f.startsWith(`..`)&&!a(f)?d:null}function Dt(e){return e instanceof Error&&(`code`in e||`killed`in e)}function Ot(e){let t=e[0];return t===void 0||t.trim()===``?null:t}function kt(e){let{command:t,cwd:n,env:i,timeoutMs:a,signal:o}=e,s=Ot(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 At(e){let{step:t,workspaceRoot:n,expressionContext:r,signal:i}=e,a=Et(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(Ot(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 kt({command:o,cwd:a,env:s,timeoutMs:c,signal:i});return{status:`completed`,stdout:e}}catch(e){if(!Dt(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 jt(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}`)}function Mt(e,t){return e===t||t===`completed`&&e===`finalizing`}async function Nt(e,t,n){let r=e.durableLifecycleTransitions.get(t)??Promise.resolve(),i=Promise.withResolvers(),a=r.catch(()=>void 0).then(()=>i.promise);e.durableLifecycleTransitions.set(t,a),await r.catch(()=>void 0);try{return await n()}finally{i.resolve(),e.durableLifecycleTransitions.get(t)===a&&e.durableLifecycleTransitions.delete(t)}}async function P(e,t,n,r){let i,a,o=!0,s=await Nt(e,t,async()=>{let s=await n(),c=Promise.withResolvers(),l=e.lifecyclePublications.get(t)??Promise.resolve();return o=!e.publishingLifecycleExecutions.has(t),a=l.catch(()=>void 0).then(async()=>{await c.promise,e.publishingLifecycleExecutions.add(t);try{await r(s)}finally{e.publishingLifecycleExecutions.delete(t)}}),e.lifecyclePublications.set(t,a),i=c.resolve,s});if(i?.(),a!==void 0){let n=a;n.then(()=>{e.lifecyclePublications.get(t)===n&&e.lifecyclePublications.delete(t)},()=>{e.lifecyclePublications.get(t)===n&&e.lifecyclePublications.delete(t)}),o&&await n}return s}async function Pt(e,t,n){if(!(await e.bus.request(t.finalizeSubject,n)).accepted){let r=`Workflow success finalizer "${t.finalizerId}" rejected transition ${n.transitionKey}`,i=Date.now(),{failed:a}=await e.bus.request(N.failFinalization,{executionId:n.executionId,claimToken:n.claimToken,error:r,settledAt:i});return}}async function Ft(e){for(let t of e.successFinalizers?.values()??[]){let{claims:n}=await e.bus.request(N.listClaimedFinalizations,{finalizerId:t.finalizerId});for(let r of n)await Pt(e,t,r);let{claims:r}=await e.bus.request(N.listUnpublishedFinalizations,{finalizerId:t.finalizerId});for(let t of r)await e.bus.request(N.publishFinalization,{claim:t})}}async function It(e,t,n,r){let i=e.resolveSuccessFinalizerId?.(n),a=i===void 0?void 0:e.successFinalizers?.get(i);if(i!==void 0&&a===void 0){await F(e,t,n,`Workflow success finalizer "${i}" is unavailable`);return}if(a!==void 0){let r=Date.now(),i={executionId:n,workflowId:t.workflowId,finalizerId:a.finalizerId,transitionKey:`${n}:terminal`,claimToken:crypto.randomUUID(),intent:{status:`completed`,completedAt:r},claimedAt:r};await P(e,n,async()=>(await e.bus.request(N.getExecution,{executionId:n})).execution?.status!==`running`||!(await e.bus.request(N.claimFinalization,{claim:i})).claimed?!1:(t.status=`finalizing`,e.activeExecutions.delete(n),!0),async t=>{t&&await Pt(e,a,i)});return}let o=Date.now();await P(e,n,async()=>(await e.bus.request(N.getExecution,{executionId:n})).execution?.status===`running`?(t.status=`completed`,t.completedAt=o,await jt(e.bus,t,{status:t.status,completedAt:o}),e.activeExecutions.delete(n),!0):!1,async i=>{i&&await e.bus.emit(E.execution.completed,{executionId:n,workflowId:t.workflowId,totalDuration:o-r,completedAt:o})})}async function F(e,t,n,r,i){let a=Date.now();await P(e,n,async()=>(await e.bus.request(N.getExecution,{executionId:n})).execution?.status===`running`?(t.status=`failed`,t.error=r,t.completedAt=a,await jt(e.bus,t,{status:t.status,error:r,completedAt:a}),e.activeExecutions.delete(n),!0):!1,async o=>{if(o){try{await i?.()}catch(e){console.error(`[WorkflowFinalizer] Failed to run failure pre-emit hook:`,e)}await e.bus.emit(E.execution.failed,{executionId:n,workflowId:t.workflowId,error:r,completedAt:a})}})}function Lt(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 Rt(e,t,n){let r=await e.bus.request(N.getExecution,{executionId:t});if(r.execution==null)return;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 e.activeExecutions.delete(t),{workflowId:i,completedAt:a,gates:s}}async function zt(e,t,n){let r=e.activeExecutions.get(t);if(!r||r.execution.status!==`running`)return Rt(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));Lt(e,t,n),await jt(e.bus,i,{status:i.status,reason:n,completedAt:i.completedAt})}finally{e.activeExecutions.delete(t)}return{workflowId:i.workflowId,completedAt:i.completedAt,gates:[]}}async function Bt(e,t,n){return await P(e,t,()=>zt(e,t,n),async r=>{if(r!==void 0){for(let n of r.gates)await e.bus.emit(E.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)});await e.bus.emit(E.execution.cancelled,{executionId:t,workflowId:r.workflowId,reason:n,completedAt:r.completedAt})}})!==void 0}function Vt(e,t){return t}function Ht(e,t){return{...t}}function Ut(e){return e.reason instanceof Error?e.reason.message:typeof e.reason==`string`&&e.reason.length>0?e.reason:ee}async function Wt(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 Bt(i,t,Ut(n))||console.error(`[WorkflowExecutor] Failed to persist runner cancellation for ${t}: execution not active`))}async function Gt(e,t){if(t.pausedAtGateId===void 0||t.pausedAtFrameId===void 0)throw Error(`Paused runner result for '${t.executionId}' is missing gate identity`);let n=e.buildFinalizerDeps();await P(n,t.executionId,async()=>{let{paused:r}=await n.bus.request(N.pauseRunningExecution,{executionId:t.executionId});if(!r){let{execution:e}=await n.bus.request(N.getExecution,{executionId:t.executionId});if(e?.status!==`paused`)return!1}let i=e.activeExecutions.get(t.executionId);return i!==void 0&&(i.execution.status=`paused`),e.activeExecutions.delete(t.executionId),r},async e=>{e&&await n.bus.emit(E.execution.paused,{executionId:t.executionId,workflowId:t.workflowId,pausedAtGateId:t.pausedAtGateId,pausedAtFrameId:t.pausedAtFrameId})})}async function Kt(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 It(r,n.execution,t.executionId,n.execution.startedAt);return}if(t.status===`cancelled`){await Bt(r,t.executionId,t.reason??ee);return}if(t.status===`failed`){await F(r,n.execution,t.executionId,t.error);return}}}async function qt(e,t){let{result:n}=t;if(t.state===`authority-committed`){let{execution:t}=await e.buildFinalizerDeps().bus.request(N.getExecution,{executionId:n.executionId});if(!t||t.workflowId!==n.workflowId||!Mt(t.status,n.status))throw Error(`Authority-committed runner result was not durably converged for '${n.executionId}'`);e.activeExecutions.delete(n.executionId);return}if(n.status===`paused`){await Gt(e,n);return}await Kt(e,n)}function Jt(e,t){return{source:{kind:`path`,path:t.filePath},executionId:t.executionId,workflowId:t.workflowId,triggerPayload:t.sanitizedTriggerPayload,triggerMode:t.triggerMode,inputs:t.boundInputs,config:t.boundConfig,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef},scope:t.scope,busUrl:e.config.busUrl,busAuth:e.config.busAuth,env:e.config.platformDefaults.env??{},coordinatorSessionId:t.coordinatorSessionId,cancelSubject:`workflow.${t.executionId}.cancel`,suspensionStrategy:`wait-in-process`,materializationSpec:t.materializationSpec}}function Yt(e,t){let{executionId:n}=t,{workflowRunner:r,workflowAbortControllers:i,executionTasks:a,activeExecutions:o}=e,s=new AbortController;i.set(n,s);let c=Jt(e,t);return Promise.resolve().then(()=>r.run(c,s.signal)).then(async t=>{await qt(e,t)}).catch(async t=>{if(s.signal.aborted){await Wt(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 Xt(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},scope:t.scope,busUrl:n.busUrl,busAuth:n.busAuth,env:n.platformDefaults.env??{},coordinatorSessionId:t.coordinatorSessionId,cancelSubject:`workflow.${t.executionId}.cancel`,suspensionStrategy:t.suspensionStrategy??`wait-in-process`,...t.terminalAuthority!==void 0&&{terminalAuthority:t.terminalAuthority},...t.materializationSpec===void 0?{}:{materializationSpec:t.materializationSpec}}}function Zt(e,t){let{executionId:n}=t,{workflowRunner:r,workflowAbortControllers:i,executionTasks:a,activeExecutions:o}=e,s=new AbortController;i.set(n,s);let c=Xt(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=>{await qt(e,t)}).catch(async t=>{if(s.signal.aborted){await Wt(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 Qt(e,t,n={}){let r=$t(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},scope:e.scope,...e.materializationSpec===void 0?{}:{materializationSpec:e.materializationSpec},suspensionStrategy:e.suspensionStrategy,terminalAuthority:e.terminalAuthority??`authority`,...r===void 0?{}:{dispatchMetadata:r}}}function $t(e,t){return t.resume===!0?{...e.dispatchMetadata,resume:!0}:e.dispatchMetadata}const en=/(?:^|[_-])(authorization|token|cookie|password|set[_-]?cookie|api[_-]?key|secret|credential|private[_-]?key|api[_-]?secret)(?:$|[_-])/i;function tn(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=nn(e,i,0,t);r!==void 0&&(n[e]=r)}return Object.keys(n).length>0?n:void 0}function nn(e,t,n,r){if(!(r.remainingBytes<=0||n>6)&&(r.remainingBytes-=e.length,!(r.remainingBytes<=0))){if(en.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=nn(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=nn(t,a,n+1,r);i!==void 0&&(e[t]=i)}return e}}}async function rn(e){let{authority:t,executionId:n,dispatch:r}=e,i=await t.createAttempt(n),a=t.waitForOutcome(i.executionAttemptId);if(a===void 0)throw Error(`No outcome waiter for attempt '${i.executionAttemptId}': waiter was not installed during attempt creation`);a.catch(()=>void 0);try{await r(i.executionAttemptId)}catch(e){return an({authority:t,executionId:n,executionAttemptId:i.executionAttemptId,outcomePromise:a,dispatchError:e})}return on(a)}async function an(e){let{authority:t,executionId:n,executionAttemptId:r,outcomePromise:i,dispatchError:a}=e,o;try{o=await t.abandonPendingAttempt(r,n)}catch(e){throw t.discardWaiter(r),AggregateError([a,e],`Dispatch acknowledgement failed and pending attempt '${r}' could not be abandoned`,{cause:a})}switch(o.kind){case`abandoned`:case`already-abandoned`:throw t.discardWaiter(r),a;case`allocated`:case`provisioning`:case`already-settled`:return on(i);case`fenced`:t.settleOutcome(r,{kind:`fenced`});try{return await on(i)}catch(e){throw AggregateError([a,e],`Dispatch acknowledgement failed after attempt '${r}' was fenced`,{cause:a})}}}async function on(e){return{state:`authority-committed`,result:await e}}function sn(e){return e===void 0?!1:(e.customCapabilities??[]).length>0||e.persistentStorage!==void 0||e.maxRuntimeMs!==void 0||e.recoverableAllocation!==void 0||e.materializationModes!==void 0&&e.materializationModes.length>0}function cn(e){let{bus:t,requirements:n,dispatchMetadata:r,authority:i}=e;if(sn(n))return{run:(e,a)=>rn({authority:i,executionId:e.executionId,dispatch:i=>t.request(ne.dispatch,{executionAttemptId:i,config:e,requirements:n,...r===void 0?{}:{metadata:r}},{signal:a})})}}function ln(e,t){if(e.executionAttemptAuthority!==void 0){let n=cn({bus:e.bus,requirements:t.workflow.requirements,dispatchMetadata:t.dispatchMetadata,authority:e.executionAttemptAuthority});if(n!==void 0)return Zt(e.buildRunnerTaskDeps(n),{...t,terminalAuthority:`authority`})}return e.workflowRunner===void 0?e.runExecution(t.executionId).finally(()=>{e.executionTasks.delete(t.executionId)}):Zt(e.buildRunnerTaskDeps(e.workflowRunner),t)}async function un(e,t,n,r){let i=wt(r);await e.request(N.setExecutionStart,{execution:t,runContext:n,initialState:i})}async function dn(e,t){try{await e.emit(E.execution.started,t)}catch(e){console.error(`[WorkflowExecutor] execution.started listener failed:`,e)}}async function fn(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 pn(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 mn(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 hn(e,t){return e.executableSource??{kind:`definition`,workflowId:t}}function gn(e,t){return e.kind===`definition`||t!==void 0}function _n(e,t,n){if(!(t.kind===`definition`||e.workflowRunner!==void 0))throw new ie(ae.NOT_EXECUTABLE,`Workflow source execution '${n}' requires a workflow runner.`)}async function vn(e,t,n){if(t.source.kind===`path`){if(n!==void 0)return n;for(let n of e.materializationSpecResolvers){let e=await n.resolve({executionId:t.executionId,workflowId:t.workflowId,sourcePath:t.source.path,workspaceRoot:t.workspaceRoot});if(e!==void 0)return e}throw Error(`[WorkflowExecutor] path-backed execution requires a resolved materializationSpec`)}}async function yn(e,t,n){let r=await vn(e,t,n);return{source:t.source.kind===`path`&&r!==void 0?{kind:`path`,path:r.sourcePath}:t.source,materializationSpec:r}}async function bn(e,t,n,r){return e.set(t,n),await r,t}async function xn(e,t){let{workflow:n}=await e.request(N.get,{id:t});if(!n)throw Error(`Workflow not found: ${t}`);return n}async function Sn(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 Cn(e,t,n={}){let r=await xn(e.bus,t);return wn(e,t,{...n,workflow:r})}async function wn(e,t,n){let{bus:r,activeExecutions:i,executionTasks:a}=e,{workflow:o,parentSessionId:s,triggerPayload:c,artifactRef:l,scopeOverride:u}=n,d=Tt(`wfx`),f=tn(c),p=Vt(o,n.input===void 0?{}:n.input),m=Ht(o,n.config??{}),h=u??o.scope,g=await e.resolveExecutionWorkspaceRoot(s),_=n.executionSource??hn(o,t),v=n.definitionSnapshot??o;_n(e,_,t);let{source:y,materializationSpec:b}=await yn(e,{executionId:d,workflowId:t,source:_,workspaceRoot:g},n.materializationSpec),x=await Sn(r,s,o.name,g),S=!1;try{let s=e.buildRunContext({executionId:d,workflowId:t,coordinatorSessionId:x,source:y,...v===void 0?{}:{definitionSnapshot:v},inputs:p,config:m,scope:h,triggerPayload:f??{},triggerMode:`immediate`,...l===void 0?{}:{artifactRef:l},...b===void 0?{}:{materializationSpec:b}}),c=pn(i,d,o,x,p,m,f,h,s);await mn(r,c,s,_.kind===`definition`?wt(o):void 0,n.executionLinks?.(d));let u=c.startedAt,g=dn(r,{executionId:d,workflowId:t,coordinatorSessionId:x,startedAt:u,...l===void 0?{}:{artifactRef:l}}),ee=ln(e,{executionId:d,workflowId:t,workflow:o,...gn(_,n.definitionSnapshot)?{definitionSnapshot:v}:{},source:_,coordinatorSessionId:x,sanitizedTriggerPayload:f??{},boundInputs:p,boundConfig:m,scope:h,...l===void 0?{}:{artifactRef:l},suspensionStrategy:s.suspensionStrategy,...b===void 0?{}:{materializationSpec:b}});return S=!0,bn(a,d,ee,g)}catch(e){throw S||(i.delete(d),a.delete(d),await fn(r,x)),e}}function Tn(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 En(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}function Dn(e){if(e===void 0)throw Error(`[WorkflowExecutor] startFileExecution called without a workflow runner`);return e}function On(e){if(e===void 0)throw Error(`[WorkflowExecutor] path-backed execution requires a resolved materializationSpec`);return e}async function kn(e,t,n={}){let{bus:r,activeExecutions:i,executionTasks:a}=e,{artifactRef:o,parentSessionId:s,triggerPayload:c,scopeOverride:l}=n,u=n.triggerMode??`immediate`,d=Tt(`wfx`),f=tn(c),p=n.input===void 0?{}:n.input,m=n.config??{},h=l??{type:`global`},g=await e.resolveExecutionWorkspaceRoot(s),_=Dn(e.workflowRunner),v=d,y=On(await vn(e,{executionId:d,workflowId:v,source:{kind:`path`,path:t},workspaceRoot:g},n.materializationSpec)),b=await En(r,s,t,g),x={id:d,workflowId:v,coordinatorSessionId:b,status:`running`,inputs:p,config:m,startedAt:Date.now(),triggerPayload:f,...o===void 0?{}:{artifactRef:o},scope:h},S=!1;try{let s=e.buildRunContext({executionId:d,workflowId:v,coordinatorSessionId:b,source:{kind:`path`,path:y.sourcePath},inputs:p,config:m,scope:h,triggerPayload:f??{},triggerMode:u,...o===void 0?{}:{artifactRef:o},materializationSpec:y});await mn(r,x,s,void 0,n.executionLinks?.(d)),Tn(i,x,t,h,s);let c=dn(r,{executionId:d,workflowId:v,coordinatorSessionId:b,startedAt:x.startedAt,...o===void 0?{}:{artifactRef:o}}),l=Yt(e.buildRunnerTaskDeps(_),{executionId:d,workflowId:v,filePath:t,coordinatorSessionId:b,sanitizedTriggerPayload:f??{},triggerMode:u,boundInputs:p,boundConfig:m,...o===void 0?{}:{artifactRef:o},scope:h,materializationSpec:y});return S=!0,bn(a,d,l,c)}catch(e){throw S||(i.delete(d),a.delete(d),await fn(r,b)),e}}function An(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 jn(e,t){let n=process.platform===`win32`?`win32`:process.platform===`darwin`?`darwin`:`linux`;return{repoPath:e??process.cwd(),makaioHome:t??process.env.MAKAIO_HOME??`${xe.homedir()}/.makaio`,os:n,arch:process.arch}}function Mn(){return{context:jn(),env:{}}}function Nn(e){return{...e,path:[...e.path]}}function Pn(e){if(e===`station`||e===`delegate-agent`||e===`delegate-role`||e===`gate`)return e}function Fn(e,t){let n=Pn(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 In=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=Mn(),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=Tt(`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=Nn(e),i=Fn(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(E.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(E.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(E.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 Ln(e){return{kind:`workflow-execution`,id:e,displayName:`Workflow Engine`}}function Rn(e,t,n){return{inputs:n.inputs,config:n.config??{},trigger:n.triggerPayload,scope:n.scope,env:n.env,execution:{id:t.id,workflowId:t.workflowId,scope:t.scope},workflow:{id:e.id,name:e.name,scope:e.scope}}}function zn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Bn(e){if(e!=null){if(zn(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 Vn(e){if(e!==void 0){if(zn(e))return e;throw Error(`Artifact create expression must return an object.`)}}async function Hn(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:Ln(i)})).artifact;return{current:c,schemaVersion:n.schemaVersion,statusPath:t.statusPath,zodSchema:t.schema}}async function Un(e){let{definition:t,execution:n,runContext:r,zodSchema:i,bus:a}=e,o=t.artifact;if(o===void 0)return;let s=Rn(t,n,r),c=r.artifactRef??(o.resolve===void 0?void 0:Bn(A(o.resolve,s))),l=c===void 0&&o.create!==void 0?Vn(A(o.create,s)):void 0,u=await Hn({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 Wn=new WeakMap;function Gn(e,t){let n=(Wn.get(e)??Promise.resolve()).catch(()=>void 0).then(t);return Wn.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 qn(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]:qn(a,i,n)}}function Jn(e,t,n){return qn(e,t.startsWith(`/`)?t.slice(1).split(`/`):t.split(`.`),n)}function Yn(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 Xn(e,t){if(typeof t==`function`)return{nextData:await t(Object.freeze({...e})),operationLabel:`functional`,changedPaths:[]};let n=Kn(e,t),r=Yn(e,n,t.operation);return{nextData:n,operationLabel:t.operation,changedPaths:r}}function Zn(e){let{executionId:t,frameId:n,bindingState:r,bus:i}=e,a=Object.freeze({...r.current.data}),o=async e=>Gn(r,async()=>{let a=r.current,{nextData:o,operationLabel:s,changedPaths:c}=await Xn(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:Ln(t)}});r.current=l.artifact;let u=l.artifact.revision;return i.emit(de.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 Qn(e,t){return{async get(){return(await t.request(E.state.get,{executionId:e})).value},async update(n){let r=await t.request(E.state.get,{executionId:e}),i=structuredClone(r.value),a=await n(i),o=a===void 0?i:a,s=it(r.value,o);return(await t.request(E.state.patch,{executionId:e,expectedSequence:r.sequence,patch:s,nextValue:o})).value}}}function $n(e,t,n){let r=e.providerContext?.state===`resolved`?e.providerContext:void 0,i=e.providerConfigId??r?.providerConfigId;return{durationMs:t,...n===void 0?{}:{...n.inputTokens===void 0?{}:{inputTokens:n.inputTokens},...n.cachedInputTokens===void 0?{}:{cachedInputTokens:n.cachedInputTokens},...n.outputTokens===void 0?{}:{outputTokens:n.outputTokens},toolCallCount:n.toolCallCount},binding:{adapterName:e.adapterName,...i===void 0?{}:{providerConfigId:i},...r===void 0?{}:{providerDefinitionId:r.definitionId},...e.model===void 0?{}:{model:e.model},...r===void 0?{}:{auth:{mode:r.auth.mode,owner:r.auth.method.owner,methodId:r.auth.method.methodId}}}}}async function er(e,t,n){if(t.signal.aborted)return{status:`cancelled`};let r=await t.bus.requestOptional(E.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 tr({...e,task:i,resolvedConfig:a},t)}async function tr(e,t){if(t.signal.aborted)return{status:`cancelled`};let n=performance.now(),r=await t.bus.requestOptional(S.spawn,{parentSessionId:t.execution.coordinatorSessionId??t.executionId,depth:1,config:cr(e.task,e.resolvedConfig,e.outputSchema)});if(!r.handled)return{status:`failed`,error:e.unavailableRuntimeError};let i=await ir(e,t,r.data.subagentId,{attempts:5}),a=await lr(e,t,r.data.subagentId);if(a===`aborted`)return{status:`cancelled`};if(i||await ir(e,t,r.data.subagentId,{attempts:1}),!a.handled)return await L(e,t,r.data.subagentId,`Workflow execution '${t.executionId}' could not await ${e.cancellationLabel} '${e.nodeId}'`),{status:`failed`,error:e.unavailableAwaitError};if(t.signal.aborted||a.data.status===`cancelled`)return{status:`cancelled`};if(a.data.status===`completed`){let r=a.data.result??null;try{return{status:`completed`,output:await nr({...e,toolObservations:a.data.toolObservations,usage:a.data.usage},t,r,rr(n))}}catch(e){if(t.signal.aborted)return{status:`cancelled`};throw e}}return(a.data.status===`timeout`||a.data.status===`waiting_input`)&&await L(e,t,r.data.subagentId,`Workflow execution '${t.executionId}' abandoned non-terminal ${e.cancellationLabel} '${e.nodeId}'`),{status:`failed`,error:`${e.nodeLabel} '${e.nodeId}' subagent ${a.data.status}: ${a.data.error??`no result`}`}}async function nr(e,t,n,r=0){if(e.resultFinalizerId===void 0)return n;if(e.frameId===void 0||e.delegateNodeType===void 0)throw Error(`Delegate result finalizer '${e.resultFinalizerId}' requires frame and delegate node identity`);let i={finalizerId:e.resultFinalizerId,executionId:t.executionId,workflowId:t.workflowId,frameId:e.frameId,nodeId:e.nodeId,nodeType:e.delegateNodeType,rawResult:n,toolObservations:[...e.toolObservations??[]],...e.resolvedConfig===void 0?{}:{economics:$n(e.resolvedConfig,r,e.usage)}},a=await t.bus.requestOptional(E.finalizeDelegateResult,i,{signal:t.signal});if(a.handled)return a.data.output;let{subjects:o}=pe(e.resultFinalizerId),{finalizerId:s,...c}=i;return(await t.bus.request(o.finalize,c,{signal:t.signal})).output}function rr(e){let t=performance.now()-e;return!Number.isFinite(t)||t<=0?0:Math.min(2**53-1,Math.round(t))}async function ir(e,t,n,r){if(e.frameId===void 0)return!0;try{let i=await ar(t,n,r.attempts);return i===void 0?!1:(await t.bus.emit(E.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 ar(e,t,n){for(let r=0;r<n;r+=1){if(e.signal?.aborted)return;let i=await or(e,t);if(i===void 0||!i.handled)return;if(i.data.childSessionId!==void 0)return i.data.childSessionId;if(r<n-1&&!await sr(e.signal,20))return}}async function or(e,t){try{return await e.bus.requestOptional(S.getStatus,{subagentId:t},{timeout:25,signal:e.signal})}catch{return}}function sr(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 cr(e,t,n){return{task:e,adapterName:t.adapterName,...t.providerConfigId===void 0?{}:{providerConfigId:t.providerConfigId},...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.adapterConfig===void 0?{}:{adapterConfig:t.adapterConfig},...t.tools===void 0?{}:{tools:t.tools},...t.disallowedTools===void 0?{}:{disallowedTools:t.disallowedTools},...t.allowedDirectories===void 0?{}:{allowedDirectories:t.allowedDirectories},...t.completion===void 0?{}:{completion:t.completion},...n===void 0?{}:{responseSchema:n}}}async function lr(e,t,n){if(t.signal.aborted)return await L(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 L(e,t,n),`aborted`;let i,a=new Promise(e=>{i=()=>e(`aborted`),t.signal.addEventListener(`abort`,i,{once:!0})});try{let i=await Promise.race([r,a]);return i===`aborted`&&await L(e,t,n),i}catch(r){throw await L(e,t,n,`Workflow execution '${t.executionId}' failed awaiting ${e.cancellationLabel} '${e.nodeId}'`),r}finally{i!==void 0&&t.signal.removeEventListener(`abort`,i)}}async function L(e,t,n,r){try{await t.bus.requestOptional(S.kill,{subagentId:n,reason:r??`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 ur(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=An(n.frames),a=t.runtimeHandlers.get(e.id);if(a===void 0)return dr(e,t,n,r);let o=t.artifactBinding!==void 0&&r!==void 0?Zn({executionId:t.executionId,frameId:r,bindingState:t.artifactBinding,bus:t.bus}):void 0,s=t.definition.state===void 0?void 0:Qn(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=ue[`execution.progress`].parse({executionId:t.executionId,workflowId:t.workflowId,frameId:r,nodeId:e.id,progress:n,emittedAt:Date.now()});try{await t.bus.emit(E.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 dr(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 er({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)}function fr(e,t){return t===void 0?e:{...e,tools:[...t],disallowedTools:void 0}}function pr(e,t){let n=fr({...t,...e.completion===void 0?{}:{completion:e.completion}},e.allowedTools);return hr(n)?{...n,contextMode:`fresh`}:n}function mr(e,t){return fr({...t,completion:e.completion??t.completion??`tool`},e.allowedTools)}function hr(e){return e.completion===`turn`&&[e.harnessId,e.contextMode,e.adapterConfig,e.tools,e.disallowedTools,e.allowedDirectories].every(e=>e===void 0)}async function gr(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=await t.bus.requestOptional(E.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=vr(e,n);if(a.status===`failed`)return a;let o=e.outputSchema===void 0?void 0:{schema:e.outputSchema},s=mr(e,i.data);return tr({nodeId:e.id,nodeLabel:`Delegate-agent node`,task:a.task,resolvedConfig:s,...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},...e.resultFinalizerId===void 0?{}:{resultFinalizerId:e.resultFinalizerId},delegateNodeType:`delegate-agent`},t)}async function _r(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=await t.bus.requestOptional(E.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=pr(e,i.data);return tr({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},...e.resultFinalizerId===void 0?{}:{resultFinalizerId:e.resultFinalizerId},delegateNodeType:`delegate-role`},t)}function vr(e,t){try{let n=I(t);return{status:`completed`,task:yr(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 yr(e){if(typeof e==`string`)return e;if(e===void 0)return``;try{return JSON.stringify(e,null,2)??``}catch{return String(e)}}function br(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 xr(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 Sr(e,t,n){return xr(e.body,t,n)}function Cr(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 wr=new Set([`completed`,`skipped`,`waiting`]);function R(e,t,n){let r=e?.byNodeId.get(t)??[],i=n.statuses??wr;return r.find(e=>e.parentFrameId===n.parentFrameId&&e.branchKey===n.branchKey&&e.iteration===n.iteration&&i.has(e.status))}function z(e,t,n){let r={...e.frames,[t]:n};return{...e,frames:r,previousSteps:An(r),output:n.status===`completed`?n.output:e.output}}function Tr(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 Er=new Set([`completed`,`running`]);function Dr(e,t){return e.status===`running`&&t.pauseSignal?.aborted===!0&&!t.outerSignal.aborted}async function Or(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:jr({},o)};let c=new AbortController,l=new AbortController,u=t.suspensionStrategy!==`wait-in-process`,d=o===`fail-fast`?Tr(c.signal,l.signal):u?l.signal:void 0,f=d===void 0?t.signal:Tr(t.signal,d),p=f===t.signal?t:t.withSignal(f),m=s.map(([s,c])=>kr(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:jr(Mr(s,e),o)}:t}let h=await Ar(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:jr(Mr(s,h.outcomes),o)}}async function kr(e,t,n,r,i,a,o,s,c){if(r.signal.aborted)return{status:`cancelled`};let l=R(r.resumeFrames,n.id,{parentFrameId:o,branchKey:e,statuses:Er});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 Dr(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=xr(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 Dr(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 Ar(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 jr(e,t){return{mode:t,branches:e}}function Mr(e,t){let n={};for(let r=0;r<e.length;r++){let[i]=e[r],a=t[r];n[i]=Nr(a)}return n}function Nr(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 Pr=new tt.default({allErrors:!0,strict:!1});function B(e,t){if(t===void 0)return{status:`ok`};try{return{status:`ok`,validator:Pr.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:Fr(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 Fr(e){return e.length===0?`schema validation failed`:e.map(e=>`${e.instancePath.length>0?e.instancePath:`/`} ${e.message??`is invalid`}`).join(`; `)}function U(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}const Ir={action:`approve`,source:`timeout`};function Lr(e){return e===void 0?{}:{reason:e}}async function Rr(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=U();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 zr(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,Ir);return s.valid?(await W(e,{...r,status:`resumed`,resumeData:Ir,resolvedAt:a},o),await G(e,t.id,n,{action:`approve`,source:`timeout`}),{status:`completed`,output:{resumeData:Ir}}):(await W(e,{...r,status:`timed-out`,resolvedAt:a},o),await G(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 W(e,{...r,status:`timed-out`,resolvedAt:a},o),await G(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 W(e,{...r,status:`cancelled`,resolvedAt:Date.now()},o),await G(e,t.id,n,{source:`cancelled`}),{status:`cancelled`};let s=Date.now();await W(e,{...r,status:a.action===`reject`?`rejected`:`resumed`,resumeData:a.resumeData,...Lr(a.reason),resolvedAt:s},o);try{await e.bus.emit(E.gate.resumed,{executionId:e.executionId,frameId:n,nodeId:t.id,resumeData:a.resumeData}),await G(e,t.id,n,{action:a.action,source:`user`,...Lr(a.reason)})}catch(e){console.error(`[GateNode] gate.resumed emit failed for '${t.id}':`,e)}return{status:`completed`,output:{resumeData:a.resumeData}}}async function Br(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=e.resumeSchema??{};if(t.suspensionStrategy!==`wait-in-process`){let n=await Wr(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}:Vr(t,e,n,r,i,a.validator)}async function Vr(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 W(e,s,{required:c}),await e.updateFrame(r,{status:`waiting`},{requireFrameStorage:c}),c)return await Hr(e,t,r,i,o,s.createdAt),{status:`paused`,pausedAtGateId:t.id,pausedAtFrameId:r};let l={value:!0},d=U(),f=e.bus.on(E.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 u)n.setResult({accepted:!1});else throw e}return}if(!l.value){n.setResult({accepted:!1});return}if(!V(a,f).valid){n.setResult({accepted:!1});return}l.value=!1,n.setResult({accepted:!0}),d.resolve({action:c,resumeData:f,reason:p})});await Hr(e,t,r,i,o,s.createdAt);let p=await Rr(d,l,e.signal,t.timeoutMs);return f(),zr(e,t,r,s,a,p)}async function Hr(e,t,n,r,i,a){try{await e.bus.emit(E.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 Ur(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 Wr(e,t,n){let r=await Ur(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(E.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 G(e,t.id,n,{action:r.status===`rejected`?`reject`:`approve`,source:`user`,...Lr(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}:zr(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 W(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 G(e,t,n,r){try{await e.bus.emit(E.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 K(e){return{status:`fulfilled`,...e===void 0?{}:{value:e}}}const Gr=new Set([`completed`,`running`]);function Kr(e,t){return e.status===`running`&&t.pauseSignal?.aborted===!0&&!t.outerSignal.aborted}async function qr(e,t,n,r,i,a){if(t.signal.aborted)return{status:`cancelled`};let o=br(e.id,`iterate`,e.collection,n);if(!Array.isArray(o))return o;let s=o;if(s.length===0)return{status:`completed`,output:Zr([])};let c=await Jr(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:Zr(c)}:{status:`paused`,pausedAtGateId:l.pausedAtGateId,pausedAtFrameId:l.pausedAtFrameId}}async function Jr(e,t,n,r,i,a,o,s){let c=new AbortController,l=n.suspensionStrategy!==`wait-in-process`,u=l?Tr(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)=>Xr(e,n,t,d,r,i,a,o,f));return Promise.all(l?n.map(e=>Yr(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(Xr(e[s],s,t,d,r,i,a,o,f));let h=await Promise.all(l?m.map(e=>Yr(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 Yr(e,t){return e.then(e=>(e.status===`paused`&&t.abort(),e))}async function Xr(e,t,n,r,i,a,o,s,c){if(r.signal.aborted)return{status:`cancelled`};let l={...i,item:e,index:t},u=R(r.resumeFrames,n.id,{parentFrameId:o,iteration:t,statuses:Gr});if(u?.status===`completed`)return K(u.output);let d=u??r.createFrame({nodeId:n.id,nodeType:`iterate`,path:s,parentFrameId:o,iteration:t});if(r.signal.aborted)return Kr(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=Sr(n,d.frameId,r);return await Z(d,r,e),K(e)}case`skipped`:return await Z(d,r),K();case`cancelled`:return Kr(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 Zr(e){return{items:e}}const Qr=new Set([`completed`,`running`]);async function $r(e,t,n,r,i,a){if(t.signal.aborted)return{status:`cancelled`};let o=br(e.id,`iterate-chain`,e.collection,n);if(!Array.isArray(o))return o;let s=o;if(s.length===0)return{status:`completed`,output:ti([])};let c=[],l;for(let o=0;o<s.length;o++){if(t.signal.aborted)return{status:`cancelled`};let u=s[o],d=await ei(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:ti(c)}}async function ei(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=R(i.resumeFrames,r.id,{parentFrameId:s,iteration:t,statuses:Qr});if(u?.status===`completed`)return K(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=Sr(r,d.frameId,i);return await Z(d,i,e),K(e)}case`skipped`:return await Z(d,i),K();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 ti(e){return{items:e}}async function ni(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 ri={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 ii(e,t,n,r,i,a){try{await e.bus.emit(E.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(E.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 ai(e){let{node:t,ctx:n,parentFrameId:r,validator:i,pending:a,deferred:o}=e;return n.bus.on(E.gate.respond,async e=>{let{executionId:s,gateId:c,frameId:l,action:d,resumeData:f,reason:p}=e.payload;if(s!==n.executionId||c!==t.id||l!==void 0&&l!==r){try{await e.next()}catch(t){if(t instanceof u)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 oi(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=U(),u=ai({node:e,ctx:t,parentFrameId:n,validator:s.validator,pending:c,deferred:l});await ii(t,e,n,r.schema,r.prompt??``,r.createdAt);try{let s=await ni(l,c,t.signal,r.timeoutMs);return s.status===`timed-out`?li(t,e,n,r,i,a,o,!1):s.status===`resolved`?si(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 si(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(E.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 ci(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 ii(t,e,r,l,c,u.createdAt),{status:`paused`,pausedAtGateId:e.id,pausedAtFrameId:r}):oi(e,t,r,u,i,a,o)}async function li(e,t,n,r,i,a,o,s=!0){let c=Date.now();if(r.autoAction===`approve`){let l=H(t.id,r.schema,ri);return l.valid?(await q(e,{...r,status:`resumed`,resumeData:ri,resolvedAt:c},s),await J(e,t.id,n,{action:`approve`,source:`timeout`}),{status:`completed`,output:Y(`escalate`,a,i,o,ri)}):(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 ui(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 di(e,t,n,r,i,a){let o=await ui(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(E.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?li(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 fi=new Set([`completed`,`running`]);async function pi(e,t,n,r,i,a,o){let s=R(n.resumeFrames,e.id,{parentFrameId:a,iteration:t,statuses:fi});if(s?.status===`completed`)return{terminal:!1,output:s.output??null,replayed:!0,gateExpressionCtx:hi(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 gi(e,c,n,r,i);if(l!==void 0)return{terminal:!0,outcome:l};let u=xr(e.body,c.frameId,n)??null;return await Z(c,n,u),{terminal:!1,output:u,replayed:!1,gateExpressionCtx:hi(e,n,r,c.frameId)}}function mi(e,t,n,r){return R(n.resumeFrames,e.id,{parentFrameId:r,iteration:t,statuses:fi})!==void 0}function hi(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=z(i,n.id,{status:`completed`,...e.output===void 0?{}:{output:e.output}}))}return i}async function gi(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 _i(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 vi(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 pi(e,c,t,n,r,i,a);if(l.terminal)return l.outcome;if(s.push(l.output),l.replayed){if(c++,mi(e,c,t,i))continue;if(e.gate.escalation!==void 0&&t.suspensionStrategy!==`wait-in-process`){let n=await di(t,e,i,{kind:`escalate`,reason:`resumed_from_gate`},c,s);if(n!==void 0)return n}continue}let u=_i(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)}:ci(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 yi(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 bi(e,t){return!!A(e,I(t))}async function xi(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 ur(e,t,n,i);case`delegate-agent`:return gr(e,t,n,i);case`delegate-role`:return _r(e,t,n,i);case`parallel`:return Or(e,t,n,r,i??``,a,e.mode??`all-settled`);case`gate`:return Br(e,t,n,i??``);case`iterate`:return qr(e,t,n,r,i??``,a);case`iterate-chain`:return $r(e,t,n,r,i??``,a);case`loop`:return vi(e,t,n,r,i??``,a);default:return{status:`failed`,error:`Unknown node type: ${String(e.type)}`}}}const Si=new Set([`completed`,`skipped`,`waiting`,`running`]);function Ci(e){return e.type===`parallel`||e.type===`iterate`||e.type===`iterate-chain`||e.type===`loop`}function wi(e,t,n){return R(e.resumeFrames,t.id,{parentFrameId:n,...Ci(t)?{statuses:Si}:{}})}function Ti(e,t,n){if(n?.status===`completed`)return z(e,t.id,{status:`completed`,...n.output===void 0?{}:{output:n.output}});if(n?.status===`skipped`)return z(e,t.id,{status:`skipped`})}async function Ei(e,t,n,r,i,a,o){try{return{result:bi(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 Di(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 xi(e,t,n,Oi,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:z(n,e.id,{status:`completed`,output:s.output})};case`skipped`:return await yi(o,t),{updatedCtx:z(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 Oi(e,t,n,r,i=[]){let a=n;for(let n of e.nodes){if(t.signal.aborted)return{status:`cancelled`};let e=wi(t,n,r),o=Ti(a,n,e);if(o!==void 0){a=o;continue}if(n.when!==void 0){let e=await Ei(n.when,`when`,n,t,a,i,r);if(`status`in e)return e;if(!e.result){await yi(t.createFrame({nodeId:n.id,nodeType:n.type,path:i,parentFrameId:r}),t),a=z(a,n.id,{status:`skipped`});continue}}if(n.skip!==void 0){let e=await Ei(n.skip,`skip`,n,t,a,i,r);if(`status`in e)return e;if(e.result){await yi(t.createFrame({nodeId:n.id,nodeType:n.type,path:i,parentFrameId:r}),t),a=z(a,n.id,{status:`skipped`});continue}}let s=e?.status===`waiting`&&n.type===`gate`||(e?.status===`running`||e?.status===`waiting`)&&Ci(n)?e:void 0,{updatedCtx:c,outcome:l}=await Di(n,t,a,i,r,s);if(a=c,l!==void 0)return l}return{status:`completed`}}function ki(e,t){let n=new Set;if(me(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(`, `)}`)}const Ai=new Set;async function ji(e,t,n){if((await e.requestOptional(N.getRunContext,{executionId:t.executionId})).handled){await Mi(e,t.executionId,n);return}await e.request(E.bootstrapAuthorityState,{executionId:t.executionId,terminalAuthority:`authority`,definition:n})}async function Mi(e,t,n){return await Ni(e,t,n)!==void 0}async function Ni(e,t,n){let r=await e.request(N.getRunContext,{executionId:t});if(r.runContext===null)return;if(r.runContext.executionId!==t)throw Error(`Authority bootstrap identity mismatch for '${t}'`);let i=r.runContext.definitionSnapshot;if(i===void 0){await e.request(N.setRunContext,{runContext:{...r.runContext,terminalAuthority:`authority`}});return}if(!Pi(i,n))throw Error(`Authority bootstrap definition mismatch for '${t}'`);let a=i;return await e.request(N.setRunContext,{runContext:{...r.runContext,terminalAuthority:`authority`,definitionSnapshot:a},initialState:wt(a)}),a}function Pi(e,t){return i(JSON.parse(JSON.stringify(e)),JSON.parse(JSON.stringify(t)))}function Fi(e,t){return e.on(E.bootstrapAuthorityState,async n=>{if(!rt(n,n.payload.executionId))throw Error(`authority state bootstrap is execution-bound`);let r=await Ni(e,n.payload.executionId,n.payload.definition);if(r!==void 0){t?.(n.payload.executionId,r);for(let t of Ai)await t({bus:e,executionId:n.payload.executionId,definition:r,transport:n.transport})}n.setResult({persisted:r!==void 0})})}export{Ve as $,nt as A,Ke as B,Ft as C,ft as D,Ct as E,ke as F,je as G,Je as H,Oe as I,Ie as J,Ae as K,Fe as L,N as M,Ee as N,it as O,Te as P,He as Q,Pe as R,Mt as S,At as T,De as U,Ye as V,M as W,Me as X,Ne as Y,Ue as Z,Qt as _,U as a,Ce as at,F as b,Un as c,E as ct,un as d,Be as et,Cn as f,rn as g,ln as h,Oi as i,Re as it,et as j,rt as k,In as l,wn as m,Fi as n,We as nt,H as o,Se as ot,kn as p,Le as q,ki as r,ze as rt,Cr as s,ue as st,ji as t,Ge as tt,jn as u,Kt as v,Tt as w,It as x,Bt as y,qe as z};
@@ -1 +0,0 @@
1
- import{n as e}from"./capability-j3NekkIu.mjs";import"./worker-node-CjuQb9hl.mjs";import{z as t}from"zod";import{createBusNamespace as n}from"@makaio/framework/core";const r=`autoLaunch`;function ee(t,n){t.emit(e.register,{capabilityId:r,provider:n})}const i=`server`;function te(t,n){return t.emit(e.register,{capabilityId:i,provider:n})}function ne(t,n){return t.emit(e.unregister,{capabilityId:i,providerId:n})}const a=t.object({id:t.number(),state:t.enum([`error`,`failure`,`pending`,`success`]),description:t.string().nullable(),targetUrl:t.string().url().nullable(),context:t.string(),createdAt:t.string().datetime(),updatedAt:t.string().datetime(),creator:t.string().nullable()}),o=t.object({id:t.number(),author:t.string(),body:t.string(),path:t.string().nullable(),line:t.number().nullable(),diffHunk:t.string().nullish(),createdAt:t.string(),updatedAt:t.string(),inReplyToId:t.number().nullable(),threadId:t.string().nullish(),isResolved:t.boolean().nullish()}),re=t.object({provider:t.string(),owner:t.string(),repo:t.string(),url:t.string(),defaultBranch:t.string().optional()}),s=t.object({id:t.string(),number:t.number(),title:t.string(),state:t.enum([`open`,`closed`,`merged`]),draft:t.boolean(),author:t.string(),branch:t.string(),baseBranch:t.string(),url:t.string(),createdAt:t.string(),updatedAt:t.string(),mergedAt:t.string().nullable(),additions:t.number().optional(),deletions:t.number().optional(),changedFiles:t.number().optional(),commentCount:t.number().optional(),reviewCount:t.number().optional(),head:t.object({ref:t.string(),sha:t.string()}).nullish()}),c=t.object({id:t.number(),author:t.string(),state:t.enum([`APPROVED`,`CHANGES_REQUESTED`,`COMMENTED`,`PENDING`,`DISMISSED`]),body:t.string().nullable(),submittedAt:t.string().nullable()}),ie=s.extend({body:t.string().nullable(),reviews:t.array(c),labels:t.array(t.string()),assignees:t.array(t.string()),requestedReviewers:t.array(t.string()),mergeable:t.boolean().nullable(),mergeableState:t.string().optional()}),ae=t.object({id:t.number(),name:t.string(),status:t.enum([`queued`,`in_progress`,`completed`]),conclusion:t.enum([`success`,`failure`,`neutral`,`cancelled`,`skipped`,`timed_out`,`action_required`]).nullable(),startedAt:t.string().nullable(),completedAt:t.string().nullable(),url:t.string(),workflowName:t.string().optional(),jobName:t.string().optional()}),oe=t.object({ref:t.string(),sha:t.string()}).nullish(),l=t.object({id:t.string(),number:t.number(),title:t.string(),state:t.enum([`open`,`closed`,`merged`]),draft:t.boolean(),author:t.string(),branch:t.string(),baseBranch:t.string(),url:t.string(),createdAt:t.string(),updatedAt:t.string(),mergedAt:t.string().nullable(),head:oe}),u=l.extend({additions:t.number().optional(),deletions:t.number().optional(),changedFiles:t.number().optional(),commentCount:t.number().optional(),reviewCount:t.number().optional()}),d={"repository.get":{request:t.object({repoPath:t.string()}),response:t.object({repository:t.object({provider:t.string(),owner:t.string(),repo:t.string(),url:t.string(),defaultBranch:t.string().optional()}).nullable()})},"pr.list":{request:t.object({repoPath:t.string(),branch:t.string()}),response:t.object({pullRequests:t.array(u)})},"pr.get":{request:t.object({repoPath:t.string(),prNumber:t.number()}),response:t.object({pullRequest:u.extend({body:t.string().nullable(),reviews:t.array(t.object({id:t.number(),author:t.string(),state:t.enum([`APPROVED`,`CHANGES_REQUESTED`,`COMMENTED`,`PENDING`,`DISMISSED`]),body:t.string().nullable(),submittedAt:t.string().nullable()})),labels:t.array(t.string()),assignees:t.array(t.string()),requestedReviewers:t.array(t.string()),mergeable:t.boolean().nullable(),mergeableState:t.string().optional()}).nullable()})},"pr.listForFile":{request:t.object({repoPath:t.string(),filePath:t.string()}),response:t.object({pullRequests:t.array(l)})},"checks.get":{request:t.object({repoPath:t.string(),commitSha:t.string()}),response:t.object({checks:t.array(t.object({id:t.number(),name:t.string(),status:t.enum([`queued`,`in_progress`,`completed`]),conclusion:t.enum([`success`,`failure`,`neutral`,`cancelled`,`skipped`,`timed_out`,`action_required`]).nullable(),startedAt:t.string().nullable(),completedAt:t.string().nullable(),url:t.string(),workflowName:t.string().optional(),jobName:t.string().optional()}))})},"statuses.get":{request:t.object({repoPath:t.string(),commitSha:t.string()}),response:t.object({statuses:t.array(a)})},"comments.list":{request:t.object({repoPath:t.string(),prNumber:t.number()}),response:t.object({comments:t.array(o)})},"comments.reply":{request:t.object({repoPath:t.string(),prNumber:t.number(),commentId:t.number(),body:t.string()}),response:t.object({comment:o})},"comments.create":{request:t.object({repoPath:t.string(),prNumber:t.number(),path:t.string(),line:t.number(),commitId:t.string(),body:t.string(),side:t.enum([`LEFT`,`RIGHT`]).optional()}),response:t.object({comment:o})},"comments.resolveThread":{request:t.object({repoPath:t.string(),prNumber:t.number(),threadId:t.string()}),response:t.object({success:t.boolean()})},"capability.write":{request:t.object({repoPath:t.string()}),response:t.object({canWrite:t.boolean(),level:t.enum([`none`,`read`,`triage`,`write`,`maintain`,`admin`])})}},f=n(`vcs`,d),se=f.subjects,p=n(`vcs:events`,{"comment.created":t.object({repoPath:t.string(),prNumber:t.number(),commentId:t.number()}),"thread.resolved":t.object({repoPath:t.string(),prNumber:t.number(),threadId:t.string()})}),ce=p.subjects,le=`vcs`;function ue(t,n){return t.emit(e.register,{capabilityId:`vcs`,provider:n})}function de(t,n){return t.emit(e.unregister,{capabilityId:`vcs`,providerId:n})}const m=t.enum([`open`,`addressed`,`verified`,`dismissed`,`deferred`]),h=t.enum([`critical`,`major`,`minor`,`nitpick`]),g=t.enum([`inline`,`review-body`,`issue-comment`,`cli-output`,`agent`]),_=t.object({file:t.string(),oldCode:t.string(),newCode:t.string()}),v=t.object({repository:t.string(),prNumber:t.number().optional(),branch:t.string().optional(),headSha:t.string().optional()}),y=t.object({id:t.string(),target:v,sourceId:t.string(),reviewer:t.string(),origin:g,threadId:t.string().nullable(),severity:h,file:t.string().nullable(),startLine:t.number().nullable(),endLine:t.number().nullable(),message:t.string(),agentPrompt:t.string().nullable(),suggestedChanges:t.array(_),status:m,addressedBy:t.string().nullable(),addressedAt:t.number().nullable(),verifiedAt:t.number().nullable(),dismissedReason:t.string().nullable(),createdAt:t.number(),updatedAt:t.number(),rawCommentId:t.number().nullable()}),b=t.object({sourceId:t.string(),remaining:t.number(),limit:t.number(),resetsAt:t.number(),lastUpdatedAt:t.number()}),fe=t.object({id:t.union([t.number(),t.string()]),author:t.string(),body:t.string(),url:t.string().nullable(),createdAt:t.string().nullable(),updatedAt:t.string().nullable()}),x={"source.registered":t.object({sourceId:t.string(),reviewer:t.string(),displayName:t.string()}),"source.list":{request:t.object({}),response:t.object({sources:t.array(t.object({sourceId:t.string(),reviewer:t.string(),displayName:t.string(),capabilities:t.object({canTrigger:t.boolean(),canFetch:t.boolean(),isPush:t.boolean()}),processorKey:t.string().nullable(),shadowedProcessors:t.array(t.string()).optional()})),rateLimits:t.array(b)})},start:{request:t.object({target:v,repoPath:t.string(),sourceId:t.string().optional()}),response:t.object({triggered:t.boolean(),estimatedDelayMs:t.number().optional(),rateLimit:b.nullable()})},started:t.object({target:v,sourceId:t.string()}),"findings.fetch":{request:t.object({target:v,repoPath:t.string()}),response:t.object({findings:t.array(y),created:t.number(),updated:t.number()})},"findings.list":{request:t.object({target:v,status:m.optional()}),response:t.object({findings:t.array(y)})},"findings.arrived":t.object({target:v,sourceId:t.string().min(1),reviewer:t.string().min(1),created:t.number().int().nonnegative(),updated:t.number().int().nonnegative()}),"findings.submit":{request:t.object({finding:y.omit({createdAt:!0,updatedAt:!0,verifiedAt:!0,addressedAt:!0,addressedBy:!0}).extend({createdAt:t.number().optional(),updatedAt:t.number().optional()})}),response:t.object({finding:y})},"finding.updateStatus":{request:t.object({findingId:t.string(),target:v,status:m,reason:t.string().optional(),addressedBy:t.string().optional()}),response:t.object({success:t.boolean(),finding:y})},"finding.statusChanged":t.object({finding:y,previousStatus:m}),"source.rateLimitChanged":t.object({rateLimit:b})},pe=n(`review`,x),me=pe.subjects,S=`review-source`,C=`reviewer-processor`;function he(t,n){return t.emit(e.register,{capabilityId:S,provider:n})}function ge(t,n){return t.emit(e.unregister,{capabilityId:S,providerId:n})}function _e(t,n){return t.emit(e.register,{capabilityId:C,provider:n})}function ve(t,n){return t.emit(e.unregister,{capabilityId:C,providerId:n})}const w=t.object({image:t.string(),prompt:t.string().optional()}),T=t.object({description:t.string(),confidence:t.number().min(0).max(1).optional()}),E={analyze:{request:w,response:T}},D=n(`vision`,E),ye=D.subjects,O=t.object({text:t.string(),language:t.string(),confidence:t.number().optional()}),k=t.enum([`idle`,`recording`,`transcribing`,`synthesizing`,`error`]),A=t.object({runtime:t.enum([`server`,`client`]),providerId:t.string(),providerName:t.string()}),j=t.object({stt:A,tts:A}),M={"session.start":{request:t.object({sessionId:t.string()}),response:t.discriminatedUnion(`audioTransport`,[t.object({audioTransport:t.literal(`none`),strategy:j}),t.object({audioTransport:t.literal(`ws`),audioWsUrl:t.string().url(),bindToken:t.string(),strategy:j})])},"session.stop":{request:t.object({sessionId:t.string()}),response:t.object({})},transcription:O.extend({sessionId:t.string(),messageId:t.string().optional()}),"synthesis.start":t.object({sessionId:t.string(),messageId:t.string().optional()}),"synthesis.end":t.object({sessionId:t.string(),messageId:t.string().optional()}),status:t.object({sessionId:t.string(),state:k})},be=t.object({stt:t.string(),tts:t.string()}),N=n(`voice`,M),xe=N.subjects,P=t.enum([`priority`,`status`,`type`,`size`,`review`,`automation`,`custom`]),F=t.object({name:t.string(),semantic:P.nullable()}),Se=t.object({id:t.number().int().nonnegative(),name:t.string(),workflowName:t.string(),conclusion:t.string(),failedStep:t.string().nullable(),detailsUrl:t.string().url().nullable(),completedAt:t.string().datetime().nullable(),source:t.enum([`check-run`,`commit-status`])}),I=t.object({status:t.enum([`pending`,`passing`,`failing`,`mixed`]),total:t.number().int().nonnegative(),passed:t.number().int().nonnegative(),failed:t.number().int().nonnegative(),pending:t.number().int().nonnegative(),skipped:t.number().int().nonnegative(),failedChecks:t.array(Se),summary:t.string()}),L=t.object({reviewer:t.string(),state:t.enum([`APPROVED`,`CHANGES_REQUESTED`,`COMMENTED`,`PENDING`,`DISMISSED`]),submittedAt:t.string().datetime().nullable()}),R=t.object({status:t.enum([`pending`,`approved`,`changes-requested`]),approvals:t.number().int().nonnegative(),changesRequested:t.number().int().nonnegative(),commented:t.number().int().nonnegative(),reviewers:t.array(L),summary:t.string()}),z=t.object({total:t.number().int().nonnegative(),open:t.number().int().nonnegative(),addressed:t.number().int().nonnegative(),verified:t.number().int().nonnegative(),dismissed:t.number().int().nonnegative(),openBySeverity:t.object({critical:t.number().int().nonnegative(),major:t.number().int().nonnegative(),minor:t.number().int().nonnegative(),nitpick:t.number().int().nonnegative()}),summary:t.string()}),B=t.object({status:t.enum([`ready`,`blocked`,`needs-attention`]),blockers:t.array(t.string()),warnings:t.array(t.string())}),V=t.object({repository:t.string(),number:t.number().int().positive(),title:t.string(),branch:t.string(),baseBranch:t.string(),author:t.string(),url:t.string().url(),state:t.enum([`open`,`closed`,`merged`]),draft:t.boolean(),mergeable:t.boolean().nullable(),checks:I,reviews:R,findings:z,labels:t.array(F),readiness:B,syncedAt:t.number().int().nonnegative(),headSha:t.string()}),H=v.extend({prNumber:t.number().int().positive()}),U={get:{request:t.object({repoPath:t.string(),prNumber:t.number().int().positive()}),response:t.object({pr:V})},list:{request:t.object({repoPath:t.string(),branch:t.string().optional()}),response:t.object({prs:t.array(V)})},refresh:{request:t.object({repoPath:t.string(),prNumber:t.number().int().positive()}),response:t.object({pr:V})},stateChanged:t.object({target:H,pr:V}),conflicted:t.object({target:H}),"checks.changed":t.object({target:H,checks:I}),"reviews.changed":t.object({target:H,reviews:R}),"labels.changed":t.object({target:H,labels:t.array(F)})},W=n(`vcs:pr`,U),Ce=W.subjects,G=t.enum([`commit`,`checkout`,`merge`,`rebase`]),K=t.object({oldHash:t.string().min(1),newHash:t.string().min(1)}),q=t.object({repoPath:t.string().min(1),squash:t.boolean(),targetBranch:t.string().min(1).optional(),currentHead:t.string().min(1).optional(),timestamp:t.string()}),J=t.object({repoPath:t.string().min(1),command:t.string().min(1),rewritten:t.array(K),branch:t.string().min(1).optional(),timestamp:t.string()}),Y=t.enum([`covered`,`not-installed`,`hook-missing`,`hook-not-executable`,`state-missing`,`state-mismatch`,`unsupported-operation`,`provider-unavailable`]),X=t.object({repoPath:t.string().min(1),operation:G,worktree:t.string().optional()}),Z=t.object({covered:t.boolean(),reason:Y,coveredOperations:t.array(G)}),Q={coverage:{request:X,response:Z},merge:q,rewrite:J},we=n(`gitHook`,Q),Te=we.subjects,$=`git-hook-events`;function Ee(t,n){return t.emit(e.register,{capabilityId:$,provider:n})}function De(t,n){return t.emit(e.unregister,{capabilityId:$,providerId:n})}export{fe as $,A,C as B,B as C,N as D,U as E,D as F,ve as G,he as H,ye as I,g as J,pe as K,w as L,be as M,M as N,xe as O,k as P,y as Q,T as R,H as S,ee as St,R as T,_e as U,S as V,ge as W,m as X,h as Y,v as Z,I as _,a as _t,Te as a,de as at,P as b,i as bt,Z as c,f as ct,J as d,ae as dt,x as et,K as f,ie as ft,Se as g,o as gt,Ce as h,re as ht,we as i,ue as it,j,O as k,G as l,se as lt,W as m,c as mt,Ee as n,_ as nt,Y as o,ce as ot,Q as p,s as pt,me as q,De as r,le as rt,X as s,p as st,$ as t,b as tt,q as u,d as ut,z as v,te as vt,L as w,V as x,r as xt,F as y,ne as yt,E as z};
@@ -1,2 +0,0 @@
1
- import { a as WorkerNodeSubjects, c as WorkerNodeDispatchRequestSchema, i as WorkerNodeNamespace, l as WorkerNodeDispatchResponseSchema, n as SuspensionStrategySchema, o as WorkerBootstrapClaimRequest, r as WORKER_BOOTSTRAP_IDENTITY_ID, s as WorkerBootstrapClaimResponse, t as SuspensionStrategy, u as WorkerNodeSchemas } from "../../index-DfUpqwBa2.mjs";
2
- export { SuspensionStrategy, SuspensionStrategySchema, WORKER_BOOTSTRAP_IDENTITY_ID, WorkerBootstrapClaimRequest, WorkerBootstrapClaimResponse, WorkerNodeDispatchRequestSchema, WorkerNodeDispatchResponseSchema, WorkerNodeNamespace, WorkerNodeSchemas, WorkerNodeSubjects };
@@ -1 +0,0 @@
1
- import{M as e}from"../../worker-node-CjuQb9hl.mjs";import{a as t,i as n,n as r,o as i,r as a,t as o}from"../../worker-node-Dtf9ilsR.mjs";export{e as SuspensionStrategySchema,o as WORKER_BOOTSTRAP_IDENTITY_ID,n as WorkerNodeDispatchRequestSchema,t as WorkerNodeDispatchResponseSchema,r as WorkerNodeNamespace,i as WorkerNodeSchemas,a as WorkerNodeSubjects};
@@ -1,7 +0,0 @@
1
- import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as ee,O as te,P as ne,Q as re,R as ie,S as m,U as ae,V as oe,W as se,X as ce,Y as le,Z as ue,_ as de,a as fe,at as pe,b as me,c as he,ct as h,et as ge,f as _e,h as ve,i as ye,it as be,j as xe,k as g,l as Se,m as Ce,n as we,nt as Te,o as Ee,ot as De,p as Oe,q as ke,r as Ae,rt as je,st as Me,tt as Ne,u as Pe,v as Fe,w as Ie,x as Le,y as _,z as Re}from"./authority-state-bootstrap-CLYus369.mjs";import{assertWorkflowTriggerPayload as ze,compileWorkflowTriggerBindingFilter as Be}from"./workflow-engine/workflow-trigger-binding-consumer.mjs";import{SerialLane as Ve}from"@makaio/framework/utils";import{ArtifactSubjects as He,AutomationTriggerSubjects as Ue,CRON_AUTOMATION_TRIGGER_KIND as We,EXECUTION_LIST_DEFAULT_LIMIT as Ge,EXECUTION_LIST_MAX_LIMIT as v,EXECUTION_LIST_MIN_LIMIT as y,EXTERNAL_EXECUTION_ID_PREFIX as b,ExecutionsByArtifactRefsQuerySchema as Ke,JsonPatchOperationSchema as qe,JsonValueSchema as Je,SessionSubjects as Ye,WORKFLOW_CANCELLED_REASON as x,WorkLogFrameEntrySchema as Xe,WorkerNodeSubjects as Ze,WorkflowAutomationTriggerBindingSchema as Qe,WorkflowError as S,WorkflowErrorCode as $e,WorkflowNamespace as et,WorkflowRunContextSchema as tt,WorkflowRunResultSchema as nt,WorkflowStepTypeSchema as rt,WorkflowSubjects as C,createWorkflowCancelSubject as it,createWorkflowDelegateResultFinalizerNamespace as at,createWorkflowFinalizerNamespace as ot,dep as st,extensionToken as ct,serializeArtifactRef as lt,walkWorkflowDefinition as ut}from"@makaio/framework/contracts";import{BaseService as dt}from"@makaio/framework/service-base";import{defineDialectSchema as ft,executeTransaction as w,getDatabaseDialect as pt,registerDrizzleHandlers as mt,resolveSchema as T,serializeDatabaseOperation as E}from"@makaio/framework/storage/drizzle";import{and as D,asc as O,count as k,desc as A,eq as j,getTableColumns as ht,gte as gt,isNotNull as _t,isNull as M,lt as vt,lte as yt,notInArray as bt,or as xt,sql as N,sum as P}from"drizzle-orm";import{SessionToken as St}from"@makaio/framework/services";import{AutomationTriggerBindingRuntimeToken as Ct}from"@makaio/framework/services/automation-trigger";const wt=ne.postgres,Tt=se.postgres,Et=l.postgres,Dt=d.postgres,Ot=ce.postgres,kt=ie.postgres,At=u.postgres,jt=be.postgres,Mt=ge.postgres,Nt=re.postgres,Pt=Te.postgres,Ft=n.postgres,It=c.postgres,Lt=De.postgres,F=ft({workflowDefinitions:ee,workflowExecutions:ae,workflowExecutionFrames:o,workflowGateInstances:s,workflowStepSpans:le,workflowExecutionLinks:f,workflowRunContexts:ke,worklogSummaries:je,worklogFrameEntries:e,worklogArtifactWrites:ue,worklogGateEvents:Ne,workflowExecutionState:Re,workflowExecutionStateEvents:oe,workflowFinalizations:pe},{workflowDefinitions:wt,workflowExecutions:Tt,workflowExecutionFrames:Et,workflowGateInstances:Dt,workflowStepSpans:Ot,workflowExecutionLinks:kt,workflowRunContexts:At,worklogSummaries:jt,worklogFrameEntries:Mt,worklogArtifactWrites:Nt,worklogGateEvents:Pt,workflowExecutionState:Ft,workflowExecutionStateEvents:It,workflowFinalizations:Lt});function I(e){return e.type===`global`?{scopeType:`global`,scopeKind:``,scopeId:``}:e.type===`external`?{scopeType:`external`,scopeKind:e.kind,scopeId:e.id}:{scopeType:e.type,scopeKind:``,scopeId:e.id}}function L(e){switch(e.scopeType){case`global`:return{type:`global`};case`external`:if(!e.scopeKind||!e.scopeId)throw Error(`Invalid external workflow scope row: scopeKind and scopeId are required`);return{type:`external`,kind:e.scopeKind,id:e.scopeId};case`workspace`:case`session`:if(!e.scopeId)throw Error(`Invalid ${e.scopeType} workflow scope row: scopeId is required`);return{type:e.scopeType,id:e.scopeId};default:{let t=e.scopeType;throw Error(`Unknown scope type: ${String(t)}`)}}}function Rt(e,t){let{scopeType:n,scopeKind:r,scopeId:i}=I(t);return[j(e.scopeType,n),j(e.scopeKind,r),j(e.scopeId,i)]}function R(e){return{id:e.id,name:e.name,description:e.description??void 0,root:e.root,inputSchema:e.inputSchema??void 0,configSchema:e.configSchema??void 0,outputSchema:e.outputSchema??void 0,state:e.state??void 0,artifact:e.artifact??void 0,triggers:e.triggers??void 0,scope:L(e),canvasLayout:e.canvasLayout??void 0,source:e.source??void 0,executableSource:e.executableSource??void 0,requirements:e.requirements??void 0,successFinalizerId:e.successFinalizerId??void 0}}function zt(e,t){let n=I(e.scope);return{id:e.id,name:e.name??e.id,root:e.root,description:e.description??null,inputSchema:e.inputSchema??null,configSchema:e.configSchema??null,outputSchema:e.outputSchema??null,state:e.state??null,artifact:e.artifact??null,triggers:e.triggers??null,canvasLayout:e.canvasLayout??null,source:e.source??null,executableSource:e.executableSource??null,requirements:e.requirements??null,successFinalizerId:e.successFinalizerId??null,createdAt:t,updatedAt:t,...n}}function Bt(e,t){let{workflowDefinitions:n}=T(t,F),r=ht(n),i=e.on(p.get,async e=>{let r=await t.select().from(n).where(j(n.id,e.payload.id)).limit(1);e.setResult({workflow:r[0]?R(r[0]):null})}),a=e.on(p.set,async i=>{let a=i.payload.workflow,o=Date.now(),s=zt(a,o),c=await E(t,async()=>{let e=await t.insert(n).values(s).onConflictDoNothing({target:n.id}).returning();if(e.length>0)return{kind:`created`,row:e[0]};let[i]=await t.update(n).set({name:s.name,root:s.root,updatedAt:o,createdAt:N`COALESCE(${r.createdAt}, ${o})`,description:s.description===null?N`${r.description}`:s.description,inputSchema:s.inputSchema===null?N`${r.inputSchema}`:s.inputSchema,configSchema:s.configSchema===null?N`${r.configSchema}`:s.configSchema,outputSchema:s.outputSchema===null?N`${r.outputSchema}`:s.outputSchema,state:s.state,artifact:s.artifact===null?N`${r.artifact}`:s.artifact,triggers:s.triggers===null?N`${r.triggers}`:s.triggers,canvasLayout:s.canvasLayout===null?N`${r.canvasLayout}`:s.canvasLayout,source:s.source===null?N`${r.source}`:s.source,executableSource:s.executableSource,requirements:s.requirements,successFinalizerId:s.successFinalizerId,...I(a.scope)}).where(j(n.id,a.id)).returning();return i?{kind:`updated`,row:i}:void 0});c&&await e.emit(c.kind===`created`?h.definition.created:h.definition.updated,R(c.row)),i.setResult({id:a.id})}),o=e.on(p.delete,async r=>{let i=(await E(t,()=>t.delete(n).where(j(n.id,r.payload.id)).returning())).length>0;i&&await e.emit(h.definition.deleted,{id:r.payload.id}),r.setResult({deleted:i})}),s=e.on(p.list,async e=>{let r=e.payload,i=r.scope?Rt(n,r.scope):[],a=i.length>0?await t.select().from(n).where(D(...i)):await t.select().from(n);e.setResult({workflows:a.map(R)})});return()=>{i(),a(),o(),s()}}function Vt(e){return{frameId:e.frameId,nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,parentFrameId:e.parentFrameId??void 0,status:e.status,attempt:e.attempt,iteration:e.iteration??void 0,branchKey:e.branchKey??void 0,...e.outputPresent?{output:e.output}:{},error:e.error??void 0,startedAt:e.startedAt??void 0,completedAt:e.completedAt??void 0}}function Ht(e,t){return{frameId:t.frameId,executionId:e,nodeId:t.nodeId,nodeType:t.nodeType,path:t.path,parentFrameId:t.parentFrameId??null,status:t.status,attempt:t.attempt,iteration:t.iteration??null,branchKey:t.branchKey??null,output:t.output===void 0?null:t.output,outputPresent:t.output!==void 0,error:t.error??null,startedAt:t.startedAt??null,completedAt:t.completedAt??null}}function Ut(e,t){let{workflowExecutionFrames:n}=T(t,F),r=e.on(p.setFrame,async e=>{let{executionId:r,frame:i}=e.payload;if(!g(e,r))throw Error(`Unauthorized: caller is not permitted to write frames for execution: ${r}`);let a=Ht(r,i);await E(t,()=>t.insert(n).values(a).onConflictDoUpdate({target:n.frameId,set:a})),e.setResult({frameId:i.frameId})}),i=e.on(p.getFrame,async e=>{let r=await t.select().from(n).where(j(n.frameId,e.payload.frameId)).limit(1);e.setResult({frame:r[0]?Vt(r[0]):null})}),a=e.on(p.listFrames,async e=>{if(!g(e,e.payload.executionId))throw Error(`Unauthorized: caller is not permitted to list frames for execution: ${e.payload.executionId}`);let r=await t.select().from(n).where(j(n.executionId,e.payload.executionId)).orderBy(O(n.startedAt),O(n.frameId));e.setResult({frames:r.map(Vt)})});return()=>{r(),i(),a()}}function Wt(e){return`${e.executionId}:${e.nodeId}:${e.frameId}`}function z(e){return{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,schema:e.schema,prompt:e.prompt??void 0,status:e.status,autoAction:e.autoAction,timeoutMs:e.timeoutMs??null,...e.resumeDataPresent?{resumeData:e.resumeData}:{},...e.reason===null?{}:{reason:e.reason},createdAt:e.createdAt,resolvedAt:e.resolvedAt??void 0}}function B(e){return{id:Wt(e),executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,schema:e.schema,prompt:e.prompt??null,status:e.status,autoAction:e.autoAction,timeoutMs:e.timeoutMs,resumeData:e.resumeData===void 0?null:e.resumeData,reason:e.reason??null,resumeDataPresent:e.resumeData!==void 0,createdAt:e.createdAt,resolvedAt:e.resolvedAt??null}}function Gt(e,t,n,r){if(e===void 0&&t===void 0)throw Error(`Either executionId or status is required to list gate instances.`);let i=n??Ge;if(!Number.isInteger(i)||i<y||i>v)throw Error(`Gate instance list limit must be an integer between ${y} and ${v}.`);return{resolvedLimit:i,predicates:[...e===void 0?[]:[j(r.executionId,e)],...t===void 0?[]:[j(r.status,t)]]}}function Kt(e,t){let{workflowExecutions:n,workflowGateInstances:r}=T(t,F),i=e.on(p.setGateInstance,async e=>{let n=e.payload.gate;if(!g(e,n.executionId))throw Error(`Unauthorized: caller is not permitted to write gates for execution: ${n.executionId}`);let i=B(n);await E(t,()=>t.insert(r).values(i).onConflictDoUpdate({target:r.id,set:i})),e.setResult({id:i.id})}),a=e.on(p.resolveWaitingGateInstance,async e=>{let n=e.payload.gate,i=B(n),a=await E(t,()=>t.update(r).set(i).where(D(j(r.id,i.id),j(r.status,`waiting`))).returning({id:r.id}));e.setResult({accepted:a.length===1})}),o=e.on(p.getGateInstance,async e=>{let{executionId:n,nodeId:i,frameId:a}=e.payload;if(!g(e,n))throw Error(`Unauthorized: caller is not permitted to read gates for execution: ${n}`);let o=[j(r.executionId,n),j(r.nodeId,i)];a!==void 0&&o.push(j(r.frameId,a));let s=await t.select().from(r).where(D(...o)).limit(1);e.setResult({gate:s[0]?z(s[0]):null})}),s=e.on(p.listGateInstances,async e=>{let{executionId:n,status:i,limit:a}=e.payload,{resolvedLimit:o,predicates:s}=Gt(n,i,a,r),c=await t.select().from(r).where(D(...s)).orderBy(A(r.createdAt),A(r.id)).limit(o);e.setResult({gates:c.map(z)})}),c=e.on(p.listPausedGateTimeouts,async e=>{let i=await t.select({gate:r}).from(r).innerJoin(n,j(r.executionId,n.id)).where(D(j(r.status,`waiting`),j(n.status,`paused`),_t(r.timeoutMs)));e.setResult({gates:i.map(e=>z(e.gate))})});return()=>{i(),a(),o(),s(),c()}}function qt(e){return{executionId:e.executionId,frameId:e.frameId,stepId:e.stepId,stepType:e.stepType,status:e.status,startedAt:e.startedAt??void 0,completedAt:e.completedAt??void 0,durationMs:e.durationMs??void 0,inputTokens:e.inputTokens??void 0,outputTokens:e.outputTokens??void 0,estimatedCost:e.estimatedCost??void 0,toolCallCount:e.toolCallCount??void 0,input:e.input??void 0,output:e.output??void 0}}function Jt(e){return{sourceExecutionId:e.sourceExecutionId,targetExecutionId:e.targetExecutionId,linkType:e.linkType,metadata:e.metadata??void 0}}function Yt(e,t){let{workflowStepSpans:n,workflowExecutionLinks:r}=T(t,F),i=e.on(p.setSpan,async e=>{let{span:r}=e.payload;if(!g(e,r.executionId))throw Error(`Unauthorized: caller is not permitted to write spans for execution: ${r.executionId}`);await E(t,()=>t.insert(n).values(r).onConflictDoUpdate({target:[n.executionId,n.frameId],set:r})),e.setResult({id:`${r.executionId}:${r.frameId}`})}),a=e.on(p.listSpans,async e=>{let r=await t.select().from(n).where(j(n.executionId,e.payload.executionId)).orderBy(O(n.startedAt),O(n.stepId),O(n.frameId));e.setResult({spans:r.map(qt)})}),o=e.on(p.setExecutionLink,async e=>{let{link:n}=e.payload;await E(t,()=>t.insert(r).values(n).onConflictDoUpdate({target:[r.sourceExecutionId,r.targetExecutionId],set:n})),e.setResult({id:`${n.sourceExecutionId}:${n.targetExecutionId}`})}),s=e.on(p.listExecutionLinks,async e=>{let{sourceExecutionId:n,targetExecutionId:i}=e.payload;if(n===void 0&&i===void 0)throw Error(`Either sourceExecutionId or targetExecutionId is required to list execution links.`);let a=[...n===void 0?[]:[j(r.sourceExecutionId,n)],...i===void 0?[]:[j(r.targetExecutionId,i)]],o=t.select().from(r).where(D(...a));e.setResult({links:(await o).map(Jt)})});return()=>{i(),a(),o(),s()}}function V(e,t){return t===null?pt(e)===`postgres`?N`'null'::jsonb`:N`'null'`:t}function Xt(e){switch(e.kind){case`path`:return{sourceKind:`path`,sourcePath:e.path,sourceFilename:null,sourceCode:null};case`source`:return{sourceKind:`source`,sourcePath:null,sourceFilename:e.filename,sourceCode:e.source};case`definition`:return{sourceKind:`definition`,sourcePath:null,sourceFilename:null,sourceCode:null}}}function Zt(e){switch(e.sourceKind){case`path`:if(!e.sourcePath)throw Error(`Invalid run context row: sourcePath required for kind=path`);return{kind:`path`,path:e.sourcePath};case`source`:if(!e.sourceFilename)throw Error(`Invalid run context row: sourceFilename required for kind=source`);return{kind:`source`,filename:e.sourceFilename,source:e.sourceCode??``};case`definition`:return{kind:`definition`,workflowId:e.workflowId};default:throw Error(`Unknown run context source kind: ${String(e.sourceKind)}`)}}function Qt(e){return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,source:Zt(e),definitionSnapshot:e.definitionSnapshot??void 0,workerManifest:e.workerManifest,inputs:e.inputs,config:e.config??{},triggerPayload:e.triggerPayload,triggerMode:e.triggerMode,...e.artifactRef===null?{}:{artifactRef:e.artifactRef},scope:L(e),...e.dispatchMetadata===null?{}:{dispatchMetadata:e.dispatchMetadata},cancelSubject:e.cancelSubject,env:e.env,createdAt:e.createdAt,suspensionStrategy:e.suspensionStrategy??`wait-in-process`,...e.terminalAuthority===null?{}:{terminalAuthority:e.terminalAuthority},...e.materializationSpec===null?{}:{materializationSpec:e.materializationSpec}}}function $t(e){let t=Xt(e.source),n=I(e.scope);return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,...t,definitionSnapshot:e.definitionSnapshot??null,workerManifest:e.workerManifest,inputs:e.inputs,config:e.config??{},triggerPayload:e.triggerPayload,triggerMode:e.triggerMode??`immediate`,artifactRef:e.artifactRef??null,dispatchMetadata:e.dispatchMetadata??null,...n,cancelSubject:e.cancelSubject,env:e.env,createdAt:e.createdAt,suspensionStrategy:e.suspensionStrategy,terminalAuthority:e.terminalAuthority??null,materializationSpec:e.materializationSpec??null}}async function en(e,t,n){let r=$t(t);await e.insert(n).values(r).onConflictDoUpdate({target:n.executionId,set:r})}function tn(e,t){let{workflowRunContexts:n,workflowExecutionState:r,workflowExecutionStateEvents:i}=T(t,F),a=e.on(p.setRunContext,async e=>{let a=e.payload.runContext,o=e.payload.initialState;await w(t,async e=>{if(await en(e,a,n),o===void 0)return;let s=Date.now(),c=V(t,o);await e.insert(r).values({executionId:a.executionId,sequence:0,value:c,updatedAt:s}).onConflictDoNothing(),await e.insert(i).values({executionId:a.executionId,sequence:0,patch:[],value:c,createdAt:s}).onConflictDoNothing()}),e.setResult({executionId:a.executionId})}),o=e.on(p.getRunContext,async e=>{let{executionId:r}=e.payload,i=await t.select().from(n).where(j(n.executionId,r)),a=i[0]?Qt(i[0]):null;e.setResult({runContext:a})});return()=>{a(),o()}}async function nn(e,t,n){let{workflowExecutionState:r,workflowExecutionStateEvents:i}=T(e,F),a=Date.now(),o=V(e,n);await w(e,async e=>{await e.insert(r).values({executionId:t,sequence:0,value:o,updatedAt:a}).onConflictDoNothing(),await e.insert(i).values({executionId:t,sequence:0,patch:[],value:o,createdAt:a}).onConflictDoNothing()})}async function rn(e,t){let{workflowExecutionState:n}=T(e,F),r=(await e.select().from(n).where(j(n.executionId,t)).limit(1))[0];return r?{executionId:r.executionId,sequence:r.sequence,value:r.value}:null}async function an(e,t){let{workflowExecutionState:n,workflowExecutionStateEvents:r}=T(e,F),i=Date.now(),a=V(e,t.nextValue);return w(e,async e=>{let o=(await e.select().from(n).where(j(n.executionId,t.executionId)).limit(1))[0];if(!o)throw Error(`no workflow state for execution ${t.executionId}`);if(t.expectedSequence===void 0)throw Error(`expectedSequence is required to patch workflow state`);let s=o.sequence+1,c=te(o.value,t.nextValue);if((await e.update(n).set({sequence:s,value:a,updatedAt:i}).where(D(j(n.executionId,t.executionId),j(n.sequence,t.expectedSequence))).returning()).length===0)throw Error(`state sequence conflict: expected ${String(t.expectedSequence)}, got ${String(o.sequence)}`);return await e.insert(r).values({executionId:t.executionId,sequence:s,patch:c,value:a,createdAt:i}),{executionId:t.executionId,sequence:s,patch:c,value:t.nextValue}})}function on(e,t){let n=e.on(p.initializeState,async e=>{let{executionId:n,initialValue:r}=e.payload;await nn(t,n,r),e.setResult({})}),r=e.on(p.getState,async e=>{let{executionId:n}=e.payload,r=await rn(t,n);e.setResult({state:r})}),i=e.on(p.patchState,async e=>{let{executionId:n,expectedSequence:r,nextValue:i}=e.payload,a=await an(t,{executionId:n,expectedSequence:r,nextValue:i});e.setResult(a)});return()=>{n(),r(),i()}}function sn(e){return{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName??void 0,status:e.status,startedAt:e.startedAt,completedAt:e.completedAt??void 0,durationMs:e.durationMs??void 0,totalInputTokens:e.totalInputTokens??void 0,totalOutputTokens:e.totalOutputTokens??void 0,totalEstimatedCost:e.totalEstimatedCost??void 0,error:e.error??void 0,failedNodeId:e.failedNodeId??void 0}}async function cn(e,t){let{worklogSummaries:n}=T(e,F);await e.insert(n).values(t).onConflictDoNothing()}async function ln(e,t){let{worklogSummaries:n}=T(e,F);await e.insert(n).values(t).onConflictDoUpdate({target:n.executionId,set:un(t),setWhere:bt(n.status,[`completed`,`failed`,`cancelled`])})}function un(e){return{workflowId:e.workflowId,workflowName:e.workflowName,status:e.status,startedAt:e.startedAt,completedAt:e.completedAt,durationMs:e.durationMs,error:e.error,failedNodeId:e.failedNodeId}}async function H(e,t){let{worklogSummaries:n}=T(e,F),r=await e.select().from(n).where(j(n.executionId,t)).limit(1);return r[0]?sn(r[0]):null}async function dn(e,t={}){let{worklogSummaries:n}=T(e,F),{workflowId:r,status:i,limit:a=50,offset:o=0}=t,s=[...r===void 0?[]:[j(n.workflowId,r)],...i===void 0?[]:[j(n.status,i)]],c=s.length>0?D(...s):void 0,[l,u]=await Promise.all([e.select().from(n).where(c).orderBy(A(n.startedAt)).limit(a).offset(o),e.select({count:k()}).from(n).where(c)]);return{items:l.map(sn),total:u[0]?.count??0}}async function fn(e,t){let{worklogFrameEntries:n}=T(e,F);await e.insert(n).values(t).onConflictDoNothing()}async function pn(e,t){let{worklogFrameEntries:n}=T(e,F);await e.insert(n).values(t).onConflictDoUpdate({target:n.frameId,set:t,setWhere:bt(n.status,[`completed`,`failed`,`skipped`,`cancelled`])})}async function U(e,t){let{worklogFrameEntries:n}=T(e,F);return(await e.select().from(n).where(j(n.frameId,t)).limit(1))[0]??null}async function mn(e,t){let n=await U(e,t);return n===null?null:Xe.parse({executionId:n.executionId,frameId:n.frameId,nodeId:n.nodeId,nodeType:n.nodeType,path:n.path,status:n.status,attempt:n.attempt,iteration:n.iteration??void 0,branchKey:n.branchKey??void 0,startedAt:n.startedAt??void 0,completedAt:n.completedAt??void 0,durationMs:n.durationMs??void 0,inputTokens:n.inputTokens??void 0,outputTokens:n.outputTokens??void 0,estimatedCost:n.estimatedCost??void 0,error:n.error??void 0})}async function hn(e,t){let{worklogArtifactWrites:n}=T(e,F);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}function gn(e,t,n,r,i){return`${e}:${t}:${n}:${r}:${i}`}async function W(e,t){let{worklogGateEvents:n}=T(e,F);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}async function _n(e,t){let{worklogGateEvents:n}=T(e,F);return(await e.select().from(n).where(j(n.id,t)).limit(1))[0]??null}function G(e,t,n){return`${e}:${t}:${n}`}async function vn(e,t,n){let[r]=await e.update(t).set({totalInputTokens:t.totalInputTokens}).where(j(t.executionId,n)).returning();return r}async function yn(e,t,n){let[r]=await e.select({totalInputTokens:P(t.inputTokens),totalOutputTokens:P(t.outputTokens),totalEstimatedCost:P(t.estimatedCost),measuredInputTokens:k(t.inputTokens),measuredOutputTokens:k(t.outputTokens),measuredCosts:k(t.estimatedCost)}).from(t).where(j(t.executionId,n));return{totalInputTokens:Number(r?.totalInputTokens??0),totalOutputTokens:Number(r?.totalOutputTokens??0),totalEstimatedCost:Number(r?.totalEstimatedCost??0),hasMeasurements:Number(r?.measuredInputTokens??0)>0||Number(r?.measuredOutputTokens??0)>0||Number(r?.measuredCosts??0)>0}}function bn(e){return e.hasMeasurements}async function xn(e,t,n,r){await e.update(t).set({totalInputTokens:r.totalInputTokens,totalOutputTokens:r.totalOutputTokens,totalEstimatedCost:r.totalEstimatedCost}).where(j(t.executionId,n))}async function Sn(e,t,n,r){let i=N`coalesce((select sum(${n.inputTokens}) from ${n} where ${n.executionId} = ${r}), 0)`,a=N`coalesce((select sum(${n.outputTokens}) from ${n} where ${n.executionId} = ${r}), 0)`,o=N`coalesce((select sum(${n.estimatedCost}) from ${n} where ${n.executionId} = ${r}), 0)`,s=N`exists(
2
- select 1 from ${n}
3
- where ${n.executionId} = ${r}
4
- and (${n.inputTokens} is not null
5
- or ${n.outputTokens} is not null
6
- or ${n.estimatedCost} is not null)
7
- )`;await e.update(t).set({totalInputTokens:i,totalOutputTokens:a,totalEstimatedCost:o}).where(D(j(t.executionId,r),s))}async function Cn(e,t){let{worklogSummaries:n,worklogFrameEntries:r}=T(e,F);if(pt(e)===`sqlite`){await Sn(e,n,r,t);return}await w(e,async e=>{if(await vn(e,n,t)===void 0)return;let i=await yn(e,r,t);bn(i)&&await xn(e,n,t,i)})}async function wn(e,t={}){let{worklogSummaries:n}=T(e,F),{workflowId:r,since:i,until:a}=t,o=[...r===void 0?[]:[j(n.workflowId,r)],...i===void 0?[]:[gt(n.startedAt,i)],...a===void 0?[]:[yt(n.startedAt,a)]],s=o.length>0?D(...o):void 0,[c,l]=await Promise.all([e.select({status:n.status,count:k()}).from(n).where(s).groupBy(n.status),e.select({totalDurationMs:P(n.durationMs),totalInputTokens:P(n.totalInputTokens),totalOutputTokens:P(n.totalOutputTokens),totalEstimatedCost:P(n.totalEstimatedCost)}).from(n).where(s)]),u={pending:0,running:0,paused:0,finalizing:0,completed:0,failed:0,cancelled:0},d=0;for(let e of c)u[e.status]=e.count,d+=e.count;let f=l[0];return{total:d,byStatus:u,totalDurationMs:Number(f?.totalDurationMs??0),totalInputTokens:Number(f?.totalInputTokens??0),totalOutputTokens:Number(f?.totalOutputTokens??0),totalEstimatedCost:Number(f?.totalEstimatedCost??0)}}async function Tn(e,t,n,r,i){let a=await U(t,n);if(a===null||i===void 0)return null;let o=await e.requestOptional(He.resolve,{ref:{refClass:`artifact`,kind:r.kind,id:r.id,revision:i}}).catch(()=>void 0);if(o===void 0||!o.handled||o.data.artifact===null)return null;let{kind:s,schemaVersion:c,scope:l}=o.data.artifact;return{nodeId:a.nodeId,artifact:{kind:s,schemaVersion:c,scope:l}}}async function K(e,t){try{await t()}catch(t){console.error(`[WorklogProjection] Write failed (${e}):`,t)}}async function q(e,t){try{await e.emit(h.worklog.changed,{executionId:t})}catch(e){console.error(`[WorklogProjection] worklog.changed emit failed for ${t}:`,e)}}const En=new Set([`completed`,`failed`,`cancelled`]);function Dn(e){return En.has(e)}async function On(e,t){return await cn(e,{executionId:t.executionId,workflowId:t.workflowId,workflowName:null,status:`running`,startedAt:t.startedAt??Date.now(),completedAt:null,durationMs:null,totalInputTokens:null,totalOutputTokens:null,totalEstimatedCost:null,error:null,failedNodeId:null}),!0}async function kn(e,t){let n=t.completedAt??Date.now(),r=await H(e,t.executionId);return r!==null&&Dn(r.status)?!1:(await ln(e,{executionId:t.executionId,workflowId:r?.workflowId??t.executionId,workflowName:r?.workflowName??null,status:`completed`,startedAt:r?.startedAt??n-t.totalDuration,completedAt:n,durationMs:t.totalDuration,totalInputTokens:r?.totalInputTokens??null,totalOutputTokens:r?.totalOutputTokens??null,totalEstimatedCost:r?.totalEstimatedCost??null,error:null,failedNodeId:null}),!0)}async function An(e,t,n,r,i,a){let o=await H(e,t);if(o!==null&&Dn(o.status))return!1;let s=o?.startedAt??a;return await ln(e,{executionId:t,workflowId:o?.workflowId??t,workflowName:o?.workflowName??null,status:n,startedAt:s,completedAt:a,durationMs:a-s,totalInputTokens:o?.totalInputTokens??null,totalOutputTokens:o?.totalOutputTokens??null,totalEstimatedCost:o?.totalEstimatedCost??null,error:r,failedNodeId:i}),!0}function jn(e,t){return[e.on(h.execution.started,async n=>{let{executionId:r}=n.payload;await K(`execution.started[${r}]`,async()=>{await E(t,()=>On(t,n.payload))&&await q(e,r)})}),e.on(h.execution.completed,async n=>{let{executionId:r}=n.payload;await K(`execution.completed[${r}]`,async()=>{await E(t,()=>kn(t,n.payload))&&await q(e,r)})}),e.on(h.execution.failed,async n=>{let{executionId:r,error:i,failedStepId:a}=n.payload,o=n.payload.completedAt??Date.now();await K(`execution.failed[${r}]`,async()=>{await E(t,()=>An(t,r,`failed`,i,a??null,o))&&await q(e,r)})}),e.on(h.execution.cancelled,async n=>{let{executionId:r}=n.payload,i=n.payload.completedAt??Date.now();await K(`execution.cancelled[${r}]`,async()=>{await E(t,()=>An(t,r,`cancelled`,null,null,i))&&await q(e,r)})})]}const Mn=new Set([`completed`,`failed`,`skipped`,`cancelled`]);function Nn(e){return Mn.has(e)}function Pn(e,t,n){return e===null?{nodeId:t,nodeType:`station`,path:[],attempt:0,iteration:null,branchKey:null,startedAt:n,inputTokens:null,outputTokens:null,estimatedCost:null}:{nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,attempt:e.attempt,iteration:e.iteration,branchKey:e.branchKey,startedAt:e.startedAt,inputTokens:e.inputTokens,outputTokens:e.outputTokens,estimatedCost:e.estimatedCost}}async function Fn(e,t,n,r,i,a,o){let s=o??Date.now(),c=await U(t,r);c!==null&&Nn(c.status)||(await pn(t,{frameId:r,executionId:n,...Pn(c,i,a===void 0?null:s-a),status:`completed`,completedAt:s,durationMs:a??null,error:null}),await Cn(t,n),await q(e,n))}async function In(e,t,n,r,i,a,o,s){let c=s??Date.now(),l=await U(t,r);l!==null&&Nn(l.status)||(await pn(t,{frameId:r,executionId:n,...Pn(l,i,o===void 0?null:c-o),status:`failed`,completedAt:c,durationMs:o??null,error:a}),await q(e,n))}function Ln(e,t){return[e.on(h.frame.started,async n=>{let{executionId:r,frameId:i,nodeId:a,nodeType:o,path:s,startedAt:c}=n.payload;await K(`frame.started[${i}]`,async()=>{await fn(t,{frameId:i,executionId:r,nodeId:a,nodeType:o,path:s,status:`running`,attempt:0,iteration:null,branchKey:null,startedAt:c??Date.now(),completedAt:null,durationMs:null,inputTokens:null,outputTokens:null,estimatedCost:null,error:null}),await q(e,r)})}),e.on(h.frame.completed,async n=>{let{executionId:r,frameId:i,nodeId:a,duration:o,completedAt:s}=n.payload;await K(`frame.completed[${i}]`,()=>Fn(e,t,r,i,a,o,s))}),e.on(h.frame.failed,async n=>{let{executionId:r,frameId:i,nodeId:a,error:o,duration:s,completedAt:c}=n.payload;await K(`frame.failed[${i}]`,()=>In(e,t,r,i,a,o,s,c))})]}const Rn={user:`rejected`,timeout:`timed-out`,cancelled:`cancelled`};function zn(e,t){return[e.on(h.gate.suspended,async n=>{let{executionId:r,frameId:i,nodeId:a,prompt:o}=n.payload;await K(`gate.suspended[${i}]`,async()=>{await W(t,{id:G(r,a,i),executionId:r,nodeId:a,frameId:i,status:`waiting`,prompt:o??null,openedAt:Date.now(),resolvedAt:null,resumeData:null}),await q(e,r)})}),e.on(h.gate.resumed,async n=>{let{executionId:r,frameId:i,nodeId:a,resumeData:o}=n.payload;await K(`gate.resumed[${i}]`,async()=>{let n=G(r,a,i),s=await _n(t,n),c=Date.now();await W(t,{id:n,executionId:r,nodeId:a,frameId:i,status:`resumed`,prompt:s?.prompt??null,openedAt:s?.openedAt??c,resolvedAt:c,resumeData:o}),await q(e,r)})}),e.on(h.gate.resolved,async n=>Bn(n.payload,e,t)),e.on(h.artifact.updated,async n=>{let{executionId:r,frameId:i,artifactRef:a,revision:o}=n.payload;await K(`artifact.updated[${r}:${i}]`,async()=>{let n=await Tn(e,t,i,a,o);if(n===null)return;let s=Date.now();await hn(t,{id:gn(r,i,a.kind,a.id,s),executionId:r,frameId:i,nodeId:n.nodeId,artifact:n.artifact,revision:o??null,writtenAt:s}),await q(e,r)})})]}async function Bn(e,t,n){let{executionId:r,frameId:i,stepId:a,source:o}=e;o===`user`&&e.action===`approve`||await K(`gate.resolved[${i}]`,async()=>{let s=G(r,a,i),c=await _n(n,s),l=Date.now();await W(n,{id:s,executionId:r,nodeId:a,frameId:i,status:o!==`cancelled`&&e.action===`approve`?`resumed`:Rn[o],prompt:c?.prompt??null,openedAt:c?.openedAt??l,resolvedAt:l,resumeData:c?.resumeData??null}),await q(t,r)})}function Vn(e,t){let n=[...jn(e,t),...Ln(e,t),...zn(e,t),e.on(h.worklog.get,async e=>{let{executionId:n}=e.payload,r=await H(t,n);e.setResult({summary:r})}),e.on(h.worklog.frame.get,async e=>{let{frameId:n}=e.payload,r=await mn(t,n);e.setResult({frame:r})}),e.on(h.worklog.list,async e=>{let{workflowId:n,status:r,limit:i,offset:a}=e.payload,o=await dn(t,{workflowId:n,status:r,limit:i,offset:a});e.setResult(o)}),e.on(h.worklog.stats,async e=>{let{workflowId:n,since:r,until:i}=e.payload,a=await wn(t,{workflowId:n,since:r,until:i});e.setResult({stats:a})})];return()=>{for(let e of n)e()}}function J(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>J(e,t[n]));if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return!1;let n=e,r=t,i=Object.keys(n).sort(),a=Object.keys(r).sort();return i.length===a.length&&i.every((e,t)=>e===a[t]&&J(n[e],r[e]))}function Hn(e){return{executionId:e.executionId,frameId:e.frameId,nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,status:e.status,attempt:e.attempt,iteration:e.iteration??null,branchKey:e.branchKey??null,startedAt:e.startedAt??null,completedAt:e.completedAt??null,durationMs:e.durationMs??null,inputTokens:e.inputTokens??null,outputTokens:e.outputTokens??null,estimatedCost:e.estimatedCost??null,error:e.error??null}}function Un(e,t){let n=e.frame;if(n!==void 0){let r=e.status===`failed`?e.error??null:null;if(n.executionId!==e.executionId)throw Error(`settleExternalExecution requires frame.executionId to match executionId`);if(n.status!==e.status)throw Error(`settleExternalExecution requires frame.status to match status`);if(n.completedAt!==t)throw Error(`settleExternalExecution requires frame.completedAt to match completedAt`);if(n.durationMs!==t-n.startedAt)throw Error(`settleExternalExecution requires frame.durationMs to match its timestamps`);if((n.error??null)!==r)throw Error(`settleExternalExecution requires frame.error to match terminal error metadata`)}return JSON.stringify({version:1,status:e.status,completedAt:t,error:e.status===`failed`?e.error??null:null,reason:e.status===`cancelled`?e.reason??null:null,frame:n===void 0?null:{executionId:n.executionId,frameId:n.frameId,nodeId:n.nodeId,nodeType:n.nodeType,path:n.path,status:n.status,attempt:n.attempt,iteration:n.iteration??null,branchKey:n.branchKey??null,startedAt:n.startedAt,completedAt:n.completedAt,durationMs:n.durationMs,error:n.status===`failed`?n.error??null:null}})}function Wn(e,t,n){if(e!==t)throw Error(`settleExternalExecution: execution "${n}" conflicts with an existing terminal settlement fingerprint`)}async function Gn(e,t,n,r,i){let a=Un(r,i);if(n.externalSettlementFingerprint!==null){Wn(n.externalSettlementFingerprint,a,r.executionId);return}if(r.frame!==void 0)throw Error(`settleExternalExecution: frame presence conflicts with the legacy frame-less settlement for execution "${r.executionId}"`);let o=r.status===`failed`?r.error??null:null,s=r.status===`cancelled`?r.reason??null:null;if((await e.update(t).set({externalSettlementFingerprint:a}).where(D(j(t.id,r.executionId),M(t.externalSettlementFingerprint),j(t.status,r.status),j(t.completedAt,i),o===null?M(t.error):j(t.error,o),s===null?M(t.reason):j(t.reason,s))).returning({fingerprint:t.externalSettlementFingerprint})).length>0)return;let[c]=await e.select().from(t).where(j(t.id,r.executionId)).limit(1);if(c===void 0)throw Error(`settleExternalExecution: execution "${r.executionId}" disappeared`);if(qn(c,r,i),c.externalSettlementFingerprint===null)throw Error(`settleExternalExecution: failed to adopt terminal settlement fingerprint for execution "${r.executionId}"`);Wn(c.externalSettlementFingerprint,a,r.executionId)}function Kn(e,t){if(e.executionId!==t.executionId||e.nodeId!==t.nodeId||e.nodeType!==t.nodeType||!J(e.path,t.path)||e.attempt!==t.attempt||e.iteration!==(t.iteration??null)||e.branchKey!==(t.branchKey??null)||e.startedAt!==t.startedAt)throw Error(`settleExternalExecution: frame "${t.frameId}" conflicts with its registered metadata`)}function qn(e,t,n){let r=t.status===`failed`?t.error??null:null,i=t.status===`cancelled`?t.reason??null:null;if(e.status!==t.status||e.completedAt!==n||e.error!==r||e.reason!==i)throw e.status===t.status?Error(`settleExternalExecution: execution "${t.executionId}" conflicts with an existing terminal settlement`):Error(`settleExternalExecution: execution "${t.executionId}" cannot transition from status "${e.status}"`)}async function Jn(e,t,n){let r=await e.select().from(t).where(j(t.executionId,n.executionId)),i=r.find(e=>e.frameId===n.frame.frameId);if(i!==void 0)return i;if(r.length>0)throw Error(`settleExternalExecution: frame "${n.frame.frameId}" conflicts with the registered frame identity`);let[a]=await e.select().from(t).where(j(t.frameId,n.frame.frameId)).limit(1);if(a!==void 0)throw Error(`settleExternalExecution: frame "${n.frame.frameId}" belongs to another execution`)}function Yn(e,t,n,r){let i=Math.min(e.startedAt,r);return{executionId:e.id,workflowId:e.workflowId,workflowName:t?.workflowName??null,status:n.status,startedAt:i,completedAt:r,durationMs:r-i,totalInputTokens:t?.totalInputTokens??null,totalOutputTokens:t?.totalOutputTokens??null,totalEstimatedCost:t?.totalEstimatedCost??null,error:n.status===`failed`?n.error??null:null,failedNodeId:n.status===`failed`?n.frame?.nodeId??t?.failedNodeId??null:null}}function Xn(e,t){return Hn({...e,inputTokens:e.inputTokens??t?.inputTokens??void 0,outputTokens:e.outputTokens??t?.outputTokens??void 0,estimatedCost:e.estimatedCost??t?.estimatedCost??void 0})}function Zn(e,t){if(e.externalRegistrationFrameId!==(t.externalRegistrationFrameId??null))throw Error(`setExternalExecutionStart: frame metadata conflicts for execution "${t.id}"`);if(!(e.id===t.id&&e.workflowId===t.workflowId&&e.coordinatorSessionId===t.coordinatorSessionId&&e.startedAt===t.startedAt&&e.scopeType===t.scopeType&&e.scopeKind===t.scopeKind&&e.scopeId===t.scopeId&&e.artifactKind===t.artifactKind&&e.artifactId===t.artifactId&&J(e.inputs,t.inputs)&&J(e.triggerPayload,t.triggerPayload)))throw Error(`setExternalExecutionStart: registration conflicts for execution "${t.id}"`)}function Qn(e,t){if(e.workflowId!==t.workflowId||e.startedAt!==t.startedAt||e.executionId!==t.executionId)throw Error(`setExternalExecutionStart: WorkLog summary conflicts for execution "${t.executionId}"`)}function $n(e,t){if(e.executionId!==t.executionId||e.frameId!==t.frameId||e.nodeId!==t.nodeId||e.nodeType!==t.nodeType||!J(e.path,t.path)||e.attempt!==t.attempt||e.iteration!==(t.iteration??null)||e.branchKey!==(t.branchKey??null)||e.startedAt!==t.startedAt)throw Error(`setExternalExecutionStart: WorkLog frame conflicts for frame "${t.frameId}"`)}async function er(e,t,n,r){if(!t.id.startsWith(b))throw Error(`setExternalExecutionStart: execution "${t.id}" is not an external execution ID`);if(n!==void 0&&n.executionId!==t.id)throw Error(`setExternalExecutionStart requires frame.executionId to match execution.id`);let{workflowExecutions:i,worklogSummaries:a,worklogFrameEntries:o}=T(e,F),s={...r(t),externalRegistrationFrameId:n?.frameId??null},c={executionId:t.id,workflowId:t.workflowId,workflowName:null,status:`running`,startedAt:t.startedAt,completedAt:null,durationMs:null,totalInputTokens:null,totalOutputTokens:null,totalEstimatedCost:null,error:null,failedNodeId:null};await w(e,async e=>{let r=(await e.insert(i).values(s).onConflictDoNothing().returning({id:i.id})).length===0;if(r){let[n]=await e.select().from(i).where(j(i.id,t.id)).limit(1);if(n===void 0)throw Error(`setExternalExecutionStart: execution "${t.id}" disappeared`);Zn(n,s)}let[l]=await e.select().from(a).where(j(a.executionId,t.id)).limit(1);if(l===void 0?await e.insert(a).values(c):Qn(l,c),n!==void 0){let[i]=await e.select().from(o).where(j(o.frameId,n.frameId)).limit(1);if(i===void 0){if(r)throw Error(`setExternalExecutionStart: frame metadata conflicts for execution "${t.id}"`);await e.insert(o).values(Hn(n))}else $n(i,n)}})}async function tr(e,t,n,r,i){if(r.frame!==void 0){let n=await Jn(e,t,r);return n!==void 0&&Kn(n,r.frame),{frame:r.frame,existing:n}}if(n.externalRegistrationFrameId===null)return;let[a]=await e.select().from(t).where(j(t.frameId,n.externalRegistrationFrameId)).limit(1);if(a===void 0||a.executionId!==n.id)throw Error(`settleExternalExecution: registered frame "${n.externalRegistrationFrameId}" is unavailable for execution "${n.id}"`);if(a.startedAt===null)throw Error(`settleExternalExecution: registered frame "${a.frameId}" has no start timestamp`);if(i<a.startedAt)throw Error(`settleExternalExecution: completedAt must not precede the registered frame start timestamp`);let o=rt.parse(a.nodeType);return{frame:{executionId:a.executionId,frameId:a.frameId,nodeId:a.nodeId,nodeType:o,path:a.path,status:r.status,attempt:a.attempt,...a.iteration===null?{}:{iteration:a.iteration},...a.branchKey===null?{}:{branchKey:a.branchKey},startedAt:a.startedAt,completedAt:i,durationMs:i-a.startedAt,...r.status===`failed`&&r.error!==void 0?{error:r.error}:{}},existing:a}}async function nr(e,t,n,r,i){let{worklogSummaries:a,worklogFrameEntries:o}=t,s=await vn(e,a,n.id),c=await tr(e,o,n,r,i),l=c===void 0?r:{...r,frame:c.frame};if(c!==void 0){let t=Xn(c.frame,c.existing);await e.insert(o).values(t).onConflictDoUpdate({target:o.frameId,set:t})}let u=await yn(e,o,n.id),d=bn(u),f={totalInputTokens:u.totalInputTokens,totalOutputTokens:u.totalOutputTokens,totalEstimatedCost:u.totalEstimatedCost},p={...Yn(n,s,l,i),...d?f:{}};await e.insert(a).values(p).onConflictDoUpdate({target:a.executionId,set:un(p)}),d&&await xn(e,a,n.id,u)}async function rr(e,t){if(!t.executionId.startsWith(b))throw Error(`settleExternalExecution: execution "${t.executionId}" is engine-owned and must use the engine finalizer`);if(t.frame!==void 0&&t.frame.executionId!==t.executionId)throw Error(`settleExternalExecution requires frame.executionId to match executionId`);let{workflowExecutions:n,worklogSummaries:r,worklogFrameEntries:i}=T(e,F);return w(e,async e=>{let[a]=await e.select().from(n).where(j(n.id,t.executionId)).limit(1);if(a===void 0)throw Error(`settleExternalExecution: execution "${t.executionId}" was not registered`);let o=t.completedAt??a.completedAt??Date.now();if(a.status===`running`){let r=Un(t,o);if((await e.update(n).set({status:t.status,completedAt:o,error:t.status===`failed`?t.error??null:null,reason:t.status===`cancelled`?t.reason??null:null,externalSettlementFingerprint:r}).where(D(j(n.id,t.executionId),j(n.status,`running`),M(n.externalSettlementFingerprint))).returning({id:n.id})).length===0){let[r]=await e.select().from(n).where(j(n.id,t.executionId)).limit(1);if(r===void 0)throw Error(`settleExternalExecution: execution "${t.executionId}" disappeared`);t.completedAt===void 0&&r.completedAt!==null&&(o=r.completedAt),qn(r,t,o),await Gn(e,n,r,t,o)}}else qn(a,t,o),await Gn(e,n,a,t,o);return await nr(e,{worklogSummaries:r,worklogFrameEntries:i},a,t,o),!0})}function ir(e,t,n){let r=e.on(p.setExternalExecutionStart,async r=>{let i=r.payload.execution,a=r.payload.frame;await er(t,i,a,n),await q(e,i.id),r.setResult({executionId:i.id,...a===void 0?{}:{frameId:a.frameId}})}),i=e.on(p.settleExternalExecution,async n=>{let r=await rr(t,n.payload);await q(e,n.payload.executionId),n.setResult({success:r})});return()=>{r(),i()}}function Y(e){return{executionId:e.executionId,workflowId:e.workflowId,finalizerId:e.finalizerId,transitionKey:e.transitionKey,claimToken:e.claimToken,intent:e.intent,claimedAt:e.claimedAt}}function ar(e,t){return e.state===`claimed`&&e.executionId===t.executionId&&e.workflowId===t.workflowId&&e.finalizerId===t.finalizerId&&e.transitionKey===t.transitionKey&&e.claimToken===t.claimToken&&e.intent.status===t.intent.status&&e.intent.completedAt===t.intent.completedAt&&e.intent.error===t.intent.error&&e.intent.reason===t.intent.reason}function or(e,t){if(e.executionId!==t.executionId||e.workflowId!==t.workflowId||e.finalizerId!==t.finalizerId||e.transitionKey!==t.transitionKey||e.claimToken!==t.claimToken)throw Error(`workflow finalization publication claim does not match durable transition ${t.executionId}`)}async function sr(e,t){let{workflowExecutions:n,workflowFinalizations:r}=T(e,F);return w(e,async e=>{let i=await e.select().from(r).where(j(r.executionId,t.executionId)).limit(1);return i[0]?ar(i[0],t):(await e.update(n).set({status:`finalizing`}).where(D(j(n.id,t.executionId),j(n.workflowId,t.workflowId),j(n.status,`running`))).returning({id:n.id})).length===0?!1:(await e.insert(r).values({...t,state:`claimed`}),!0)})}function cr(e){return{status:e.status,completedAt:e.completedAt,error:e.status===`failed`?e.error??`Workflow finalization failed`:null,reason:e.status===`cancelled`?e.reason??null:null}}async function lr(e,t,n,r){let{workflowExecutions:i,workflowFinalizations:a}=T(e,F);return w(e,async e=>{let o=(await e.select().from(a).where(j(a.executionId,t)).limit(1))[0];return!o||o.claimToken!==n||o.state===`failed`?!1:o.state===`acknowledged`?!0:(await e.update(i).set(cr(o.intent)).where(D(j(i.id,t),j(i.status,`finalizing`))).returning({id:i.id})).length===0?!1:(await e.update(a).set({state:`acknowledged`,settledAt:r}).where(D(j(a.executionId,t),j(a.claimToken,n),j(a.state,`claimed`))),!0)})}async function ur(e,t,n,r,i){let{workflowExecutions:a,workflowFinalizations:o}=T(e,F);return w(e,async e=>{let s=(await e.select().from(o).where(j(o.executionId,t)).limit(1))[0];return!s||s.claimToken!==n||s.state===`acknowledged`?!1:s.state===`failed`?!0:(await e.update(a).set({status:`failed`,error:r,reason:null,completedAt:i}).where(D(j(a.id,t),j(a.status,`finalizing`))).returning({id:a.id})).length===0?!1:(await e.update(o).set({state:`failed`,failure:r,settledAt:i}).where(D(j(o.executionId,t),j(o.claimToken,n),j(o.state,`claimed`))),!0)})}async function dr(e,t,n){let{workflowExecutions:r,workflowFinalizations:i}=T(t,F),a=(await t.select().from(i).where(j(i.executionId,n.executionId)).limit(1))[0];if(!a||(or(a,n),a.state===`claimed`||a.publishedAt!==null))return;let o=(await t.select({startedAt:r.startedAt,status:r.status,error:r.error,reason:r.reason,completedAt:r.completedAt}).from(r).where(j(r.id,a.executionId)).limit(1))[0];if(!(!o||o.completedAt==null)){if(o.status===`completed`)await e.emit(h.execution.completed,{executionId:a.executionId,workflowId:a.workflowId,totalDuration:o.completedAt-o.startedAt,completedAt:o.completedAt,transitionKey:a.transitionKey});else if(o.status===`failed`)await e.emit(h.execution.failed,{executionId:a.executionId,workflowId:a.workflowId,error:o.error??`Workflow finalization failed`,completedAt:o.completedAt,transitionKey:a.transitionKey});else if(o.status===`cancelled`)await e.emit(h.execution.cancelled,{executionId:a.executionId,workflowId:a.workflowId,reason:o.reason??void 0,completedAt:o.completedAt,transitionKey:a.transitionKey});else return;await E(t,()=>t.update(i).set({publishedAt:Date.now()}).where(D(j(i.executionId,a.executionId),M(i.publishedAt))))}}function fr(e,t){let n=new Map;return async r=>{let i=(n.get(r.executionId)??Promise.resolve()).catch(()=>void 0).then(()=>dr(e,t,r));n.set(r.executionId,i);try{await i}finally{n.get(r.executionId)===i&&n.delete(r.executionId)}}}function pr(e,t){let n=fr(e,t),r=e.on(p.claimFinalization,async e=>{e.setResult({claimed:await sr(t,e.payload.claim)})}),i=e.on(p.listClaimedFinalizations,async e=>{let{workflowFinalizations:n}=T(t,F),r=await t.select().from(n).where(D(j(n.finalizerId,e.payload.finalizerId),j(n.state,`claimed`)));e.setResult({claims:r.map(Y)})}),a=e.on(p.listUnpublishedFinalizations,async e=>{let{workflowFinalizations:n}=T(t,F),r=await t.select().from(n).where(D(xt(j(n.state,`acknowledged`),j(n.state,`failed`)),j(n.finalizerId,e.payload.finalizerId),M(n.publishedAt)));e.setResult({claims:r.map(Y)})}),o=e.on(p.publishFinalization,async e=>{await n(e.payload.claim),e.setResult({})}),s=e.on(p.acknowledgeFinalization,async e=>{let{executionId:r,claimToken:i,settledAt:a}=e.payload,o=await lr(t,r,i,a);if(e.setResult({acknowledged:o}),!o)return;let{workflowFinalizations:s}=T(t,F),c=await t.select().from(s).where(j(s.executionId,r)).limit(1);c[0]&&await n(Y(c[0]))}),c=e.on(p.failFinalization,async e=>{let{executionId:r,claimToken:i,error:a,settledAt:o}=e.payload,s=await ur(t,r,i,a,o);if(e.setResult({failed:s}),!s)return;let{workflowFinalizations:c}=T(t,F),l=await t.select().from(c).where(j(c.executionId,r)).limit(1);l[0]&&await n(Y(l[0]))});return()=>{r(),i(),a(),o(),s(),c()}}function mr(e){return{id:e.id,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId??void 0,status:e.status,inputs:e.inputs,config:{},error:e.error??void 0,reason:e.reason??void 0,startedAt:e.startedAt,completedAt:e.completedAt??void 0,triggerPayload:e.triggerPayload??void 0,...e.artifactKind!==null&&e.artifactId!==null?{artifactRef:{kind:e.artifactKind,id:e.artifactId}}:{},scope:L(e)}}function X(e){let t=I(e.scope);return{id:e.id,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId??null,status:e.status,inputs:e.inputs,error:e.error??null,reason:e.reason??null,startedAt:e.startedAt,completedAt:e.completedAt??null,triggerPayload:e.triggerPayload??null,artifactKind:e.artifactRef?.kind??null,artifactId:e.artifactRef?.id??null,...t}}function hr(e,t,n,r,i,a){let o=[...e?[j(a.workflowId,e)]:[],...n?[j(a.status,n)]:[],...i===void 0?[]:[j(a.artifactKind,i.kind),j(a.artifactId,i.id)]];if(t&&o.push(...Rt(a,t)),r){let e=xt(vt(a.startedAt,r.startedAt),D(j(a.startedAt,r.startedAt),vt(a.id,r.id)));e&&o.push(e)}return o}async function gr(e,t,n,r,i){if(n.executionId!==t.id)throw Error(`setExecutionStart requires execution.id to match runContext.executionId`);for(let e of i??[])if(e.targetExecutionId!==t.id)throw Error(`setExecutionStart requires executionLinks.targetExecutionId to match execution.id`);let{workflowExecutions:a,workflowRunContexts:o,workflowExecutionState:s,workflowExecutionStateEvents:c,workflowExecutionLinks:l}=T(e,F),u=X(t);await w(e,async d=>{await d.insert(a).values(u).onConflictDoUpdate({target:a.id,set:u});let f=(n.dispatchMetadata===void 0?await d.select({dispatchMetadata:o.dispatchMetadata}).from(o).where(j(o.executionId,n.executionId)).limit(1):[])[0]?.dispatchMetadata;if(await en(d,n.dispatchMetadata===void 0&&f!=null?{...n,dispatchMetadata:f}:n,o),r!==void 0){let n=Date.now(),i=V(e,r);await d.insert(s).values({executionId:t.id,sequence:0,value:i,updatedAt:n}).onConflictDoNothing(),await d.insert(c).values({executionId:t.id,sequence:0,patch:[],value:i,createdAt:n}).onConflictDoNothing()}for(let e of i??[])await d.insert(l).values(e).onConflictDoUpdate({target:[l.sourceExecutionId,l.targetExecutionId],set:e})})}async function _r(e,t,n){if(n.executionId!==t.id)throw Error(`restorePausedGateResumeState requires execution.id to match gate.executionId`);if(t.status!==`paused`||n.status!==`waiting`)throw Error(`restorePausedGateResumeState requires a paused execution and waiting gate`);let{workflowExecutions:r,workflowGateInstances:i}=T(e,F),a=X(t),o=B(n);await w(e,async e=>{await e.insert(r).values(a).onConflictDoUpdate({target:r.id,set:a}),await e.insert(i).values(o).onConflictDoUpdate({target:i.id,set:o})})}async function vr(e,t,n,r){let{workflowExecutions:i,workflowGateInstances:a}=T(e,F);return w(e,async e=>{if((await e.select().from(i).where(j(i.id,t)).limit(1))[0]?.status!==`paused`)return{cancelled:!1,gates:[]};let o=(await e.select().from(a).where(D(j(a.executionId,t),j(a.status,`waiting`)))).map(e=>({...z(e),status:`cancelled`,resolvedAt:n}));await e.update(i).set({status:`cancelled`,completedAt:n,reason:r??null}).where(j(i.id,t));for(let t of o){let n=B(t);await e.update(a).set(n).where(j(a.id,n.id))}return{cancelled:!0,gates:o}})}async function yr(e,t,n,r,i,a){let{workflowExecutions:o}=T(e,F);return w(e,async e=>{if((await e.select({id:o.id}).from(o).where(j(o.id,t)).limit(1))[0]===void 0)return!1;let s={};return n!==void 0&&(s.status=n),r!==void 0&&(s.error=r),i!==void 0&&(s.reason=i),a!==void 0&&(s.completedAt=a),Object.keys(s).length>0&&await e.update(o).set(s).where(j(o.id,t)),!0})}function br(e,t){let{workflowExecutions:n}=T(t,F),r=e.on(p.getExecution,async e=>{let{executionId:r}=e.payload;if(!g(e,r))throw Error(`Unauthorized execution read: ${r}`);let i=await t.select().from(n).where(j(n.id,r));e.setResult({execution:i[0]?mr(i[0]):null})}),i=e.on(p.setExecution,async e=>{let r=e.payload.execution,i=X(r);await E(t,()=>t.insert(n).values(i).onConflictDoUpdate({target:n.id,set:i})),e.setResult({id:r.id})}),a=e.on(p.setExecutionStart,async e=>{let n=e.payload.execution,r=e.payload.runContext;await gr(t,n,r,e.payload.initialState,e.payload.executionLinks),e.setResult({id:n.id,executionId:n.id})}),o=e.on(p.restorePausedGateResumeState,async e=>{let n=e.payload.execution,r=e.payload.gate;await _r(t,n,r),e.setResult({executionId:n.id,gateId:r.nodeId})}),s=e.on(p.updateExecution,async e=>{let{executionId:n,status:r,error:i,reason:a,completedAt:o}=e.payload,s=await yr(t,n,r,i,a,o);e.setResult({success:s})}),c=e.on(p.pauseRunningExecution,async e=>{let{workflowExecutions:n}=T(t,F),r=await E(t,()=>t.update(n).set({status:`paused`}).where(D(j(n.id,e.payload.executionId),j(n.status,`running`))).returning({id:n.id}));e.setResult({paused:r.length===1})}),l=e.on(p.cancelPausedExecution,async e=>{let{executionId:n,completedAt:r,reason:i}=e.payload;e.setResult(await vr(t,n,r,i))});return()=>{r(),i(),a(),o(),s(),c(),l()}}function xr(e,t){let{workflowExecutions:n}=T(t,F),r=e.on(p.listExecutions,async e=>{let{workflowId:r,scope:i,status:a,limit:o,cursor:s,artifactRef:c}=e.payload;if(r===void 0&&i===void 0&&c===void 0)throw Error(`Either workflowId, scope, or artifactRef is required to list executions.`);let l=hr(r,i,a,s,c,n),u=o??Ge;if(!Number.isInteger(u)||u<y||u>v)throw Error(`Execution list limit must be an integer between ${y} and ${v}.`);let d=await t.select().from(n).where(D(...l)).orderBy(A(n.startedAt),A(n.id)).limit(u);e.setResult({executions:d.map(mr)})}),i=e.on(p.listExecutionsByArtifactRefs,async e=>{let r=Ke.safeParse(e.payload);if(!r.success)throw Error(`Invalid listExecutionsByArtifactRefs query: ${r.error.message}`);let{refs:i,limitPerRef:a}=r.data,o={};for(let e of i){let r=await t.select().from(n).where(D(j(n.artifactKind,e.kind),j(n.artifactId,e.id))).orderBy(A(n.startedAt),A(n.id)).limit(a);r.length>0&&(o[lt(e)]=r.map(mr))}e.setResult({executionsByRef:o})});return()=>{r(),i()}}function Sr(e,t){let n=Bt(e,t),r=br(e,t),i=xr(e,t),a=Ut(e,t),o=Kt(e,t),s=Yt(e,t),c=tn(e,t),l=on(e,t),u=Vn(e,t),d=ir(e,t,X),f=pr(e,t);return()=>{n(),r(),i(),a(),o(),s(),c(),l(),u(),d(),f()}}function Cr(e){return e.startsWith(b)}function wr(e){let t={};return e.artifactRef!==void 0&&(t.artifactRef=e.artifactRef),e.triggerPayload!==void 0&&(t.triggerPayload=e.triggerPayload),t}function Tr(e){if(e.status===`failed`){if(e.error===void 0)throw Error(`status 'failed' requires a non-empty 'error' message`);return{error:e.error}}if(e.status===`cancelled`){if(e.reason===void 0)throw Error(`status 'cancelled' requires a non-empty 'reason' string`);return{reason:e.reason}}return{}}async function Er(e,t){let{runContext:n}=await e.request(p.getRunContext,{executionId:t});if(n===null)throw Error(`Run context not found for execution: ${t}`);if(n.definitionSnapshot!==void 0)return n.definitionSnapshot;let{workflow:r}=await e.request(p.get,{id:n.workflowId});return r??void 0}function Dr(e){return[e.on(h.getDefinition,async t=>{let n=await e.request(p.get,{id:t.payload.id});t.setResult(n)}),e.on(h.setDefinition,async t=>{let n=await e.request(p.set,{workflow:t.payload.workflow});t.setResult(n)}),e.on(h.deleteDefinition,async t=>{let n=await e.request(p.delete,{id:t.payload.id});t.setResult(n)}),e.on(h.listDefinitions,async t=>{let n=await e.request(p.list,t.payload);t.setResult(n)}),e.on(h.getExecution,async t=>{let n=await e.request(p.getExecution,{executionId:t.payload.executionId});t.setResult(n)}),e.on(h.listExecutions,async t=>{let n=await e.request(p.listExecutions,t.payload);t.setResult(n)}),e.on(h.listExecutionsByArtifactRefs,async t=>{let n=await e.request(p.listExecutionsByArtifactRefs,t.payload);t.setResult(n)}),e.on(h.listSpans,async t=>{let n=await e.request(p.listSpans,{executionId:t.payload.executionId});t.setResult(n)}),e.on(h.listFrames,async t=>{let n=await e.request(p.listFrames,{executionId:t.payload.executionId});t.setResult(n)}),e.on(h.listGateInstances,async t=>{let n=await e.request(p.listGateInstances,t.payload);t.setResult(n)}),e.on(h.setExecutionLink,async t=>{let n=await e.request(p.setExecutionLink,{link:t.payload.link});t.setResult(n)}),e.on(h.listExecutionLinks,async t=>{let n=await e.request(p.listExecutionLinks,t.payload);t.setResult(n)}),e.on(h.getRunContext,async t=>{let{executionId:n}=t.payload;if(!g(t,n))throw Error(`Unauthorized: caller is not permitted to read run context for execution: ${n}`);let{runContext:r}=await e.request(p.getRunContext,{executionId:n});if(!r)throw Error(`Run context not found for execution: ${n}`);t.setResult(r)}),...Or(e)]}function Or(e){return[e.on(h.registerExternalExecution,async t=>{let n=Me.registerExternalExecution.request.parse(t.payload),{name:r,scope:i,input:a}=n;if(n.executionId!==void 0&&!t.origin.local)throw Error(`registerExternalExecution: caller-supplied executionId is restricted to local callers`);let o=n.executionId??Ie(`wfx-ext`);if(!Cr(o))throw Error(`registerExternalExecution: executionId must use the wfx-ext- prefix`);let s=n.startedAt??Date.now(),c={id:o,workflowId:r,status:`running`,inputs:a===void 0?{}:a,startedAt:s,scope:i??{type:`global`},...wr(n)},l=kr(o,s,n.frame),u=await e.request(p.setExternalExecutionStart,{execution:c,...l===void 0?{}:{frame:l}});t.setResult(u)}),e.on(h.completeExternalExecution,async t=>{let n=Me.completeExternalExecution.request.parse(t.payload),{executionId:r,status:i}=n;if(!g(t,r))throw Error(`Unauthorized: caller is not permitted to settle execution: ${r}`);if(!Cr(r))throw Error(`completeExternalExecution: execution "${r}" is engine-owned and must be completed through the engine finalizer, not this API`);let a=Ar(n),o=await e.request(p.settleExternalExecution,{executionId:r,status:i,...Tr(n),...n.completedAt===void 0?{}:{completedAt:n.completedAt},...a===void 0?{}:{frame:a}});t.setResult({success:o.success})})]}function kr(e,t,n){if(n===void 0)return;let r=n.frameId??`${e}:${n.nodeId}`;return{executionId:e,frameId:r,nodeId:n.nodeId,nodeType:n.nodeType,path:n.path??[r],status:`running`,attempt:n.attempt,...n.iteration===void 0?{}:{iteration:n.iteration},...n.branchKey===void 0?{}:{branchKey:n.branchKey},startedAt:n.startedAt??t}}function Ar(e){if(e.frame===void 0)return;if(e.completedAt===void 0)throw Error(`completedAt is required when frame metadata is supplied`);let t=e.completedAt-e.frame.startedAt;if(t<0)throw Error(`completedAt must not precede frame.startedAt`);if(e.frame.durationMs!==void 0&&e.frame.durationMs!==t)throw Error(`frame.durationMs must equal completedAt - frame.startedAt`);return{executionId:e.executionId,frameId:e.frame.frameId,nodeId:e.frame.nodeId,nodeType:e.frame.nodeType,path:e.frame.path,status:e.status,attempt:e.frame.attempt,...e.frame.iteration===void 0?{}:{iteration:e.frame.iteration},...e.frame.branchKey===void 0?{}:{branchKey:e.frame.branchKey},startedAt:e.frame.startedAt,completedAt:e.completedAt,durationMs:t,...e.status===`failed`&&e.error!==void 0?{error:e.error}:{}}}function jr(e){return[e.on(h.state.get,async t=>{let{executionId:n}=t.payload;if(!g(t,n))throw Error(`Unauthorized: caller is not permitted to read state for execution: ${n}`);let{state:r}=await e.request(p.getState,{executionId:n});if(r===null)throw Error(`no workflow state for execution ${n}`);t.setResult(r)}),e.on(h.state.patch,async t=>{let{executionId:n,expectedSequence:r,patch:i,nextValue:o}=t.payload;if(!g(t,n))throw Error(`Unauthorized: caller is not permitted to patch state for execution: ${n}`);if(r===void 0)throw Error(`expectedSequence is required to patch workflow state`);let s=await Er(e,n);s!==void 0&&a(s,o,`next`),qe.array().parse(i);let c=await e.request(p.patchState,{executionId:n,expectedSequence:r,nextValue:o});e.emit(h.state.updated,{executionId:c.executionId,sequence:c.sequence,patch:c.patch,value:c.value,updatedAt:Date.now()}).catch(()=>{}),t.setResult({executionId:c.executionId,sequence:c.sequence,value:c.value})})]}async function Mr(e,t){let{runContext:n}=await e.bus.request(p.getRunContext,{executionId:t});if(n===null)throw new S($e.RUN_CONTEXT_NOT_FOUND,`Run context not found for workflow execution '${t}'.`);return n}function Nr(e,t){return t===void 0?{mode:e}:{mode:e,reason:t}}async function Pr(e,t){let n=await Mr(e,t.executionId),r=t.input===void 0?n.inputs:t.input,i=t.config??n.config??{},a=t.triggerPayload??n.triggerPayload,o=t.artifactRef??n.artifactRef,s=t.scopeOverride??n.scope,c={input:r,config:i,parentSessionId:t.parentSessionId,triggerPayload:a,artifactRef:o,scopeOverride:s,executionLinks:e=>[{sourceExecutionId:t.executionId,targetExecutionId:e,linkType:`rerun-of`,metadata:Nr(t.mode,t.reason)}]};return t.mode===`snapshot`?await Rr(e,n,c):Ir(n)?await zr(e,n,c):await _e(e,n.workflowId,c)}function Fr(e,t){return Ir(e)?t.id:e.workflowId}function Ir(e){return e.source.kind!==`definition`&&e.workflowId===e.executionId}function Lr(e){let t=e.definitionSnapshot;if(t===void 0)throw new S($e.SNAPSHOT_UNAVAILABLE,`Workflow execution '${e.executionId}' does not have a definition snapshot.`);return t}async function Rr(e,t,n){let r=Lr(t);return Ce(e,Fr(t,r),{workflow:r,executionSource:t.source,definitionSnapshot:r,input:n.input,config:n.config,parentSessionId:n.parentSessionId,triggerPayload:n.triggerPayload,artifactRef:n.artifactRef,scopeOverride:n.scopeOverride,executionLinks:n.executionLinks,...t.materializationSpec===void 0?{}:{materializationSpec:t.materializationSpec}})}async function zr(e,t,n){if(t.definitionSnapshot===void 0&&t.source.kind===`path`){let{materializationSpec:r}=t;if(r===void 0)throw Error(`Invalid persisted path-backed run context: materializationSpec is required`);return Oe(e,t.source.path,{...n,materializationSpec:r})}let r=Lr(t);return Ce(e,r.id,{workflow:r,executionSource:t.source,input:n.input,config:n.config,parentSessionId:n.parentSessionId,triggerPayload:n.triggerPayload,artifactRef:n.artifactRef,scopeOverride:n.scopeOverride,executionLinks:n.executionLinks,...t.materializationSpec===void 0?{}:{materializationSpec:t.materializationSpec}})}var Br=class{bus;resumePausedExecution;handles=new Map;constructor(e,t){this.bus=e,this.resumePausedExecution=t}dispose(){for(let e of this.handles.values())clearTimeout(e);this.handles.clear()}clear(e,t,n){let r=this.makeKey(e,t,n),i=this.handles.get(r);i!==void 0&&(clearTimeout(i),this.handles.delete(r))}schedule(e){e.timeoutMs!==null&&(this.clear(e.executionId,e.nodeId,e.frameId),this.scheduleNextWakeup({...e,timeoutMs:e.timeoutMs}))}scheduleNextWakeup(e){let t=this.makeKey(e.executionId,e.nodeId,e.frameId),n=Math.max(0,e.openedAt+e.timeoutMs-Date.now()),r=setTimeout(()=>{if(this.handles.delete(t),Date.now()<e.openedAt+e.timeoutMs){this.scheduleNextWakeup(e);return}this.handleExpiredWakeup(e)},Math.min(n,2147483647));this.handles.set(t,r)}scheduleNextWakeupAfterDelay(e,t){let n=this.makeKey(e.executionId,e.nodeId,e.frameId),r=setTimeout(()=>{this.handles.delete(n),this.handleExpiredWakeup(e)},t);this.handles.set(n,r)}async handleExpiredWakeup(e){try{await this.resumeTimedOutPausedGate(e)===`retry`&&this.scheduleNextWakeupAfterDelay(e,25)}catch(t){this.scheduleFailedWakeupRetry(e,t)}}scheduleFailedWakeupRetry(e,t){let n=(e.failedWakeupAttempts??0)+1;if(n>4){console.error(`[WorkflowExecutor] Giving up on timed-out gate '${e.nodeId}' after 4 failed wakeup retries:`,t);return}let r=Math.min(250*2**(n-1),2e3);console.error(`[WorkflowExecutor] Failed to resume timed-out gate '${e.nodeId}', retrying in ${r} ms:`,t),this.scheduleNextWakeupAfterDelay({...e,failedWakeupAttempts:n},r)}makeKey(e,t,n){return`${e}:${t}:${n}`}async resumeTimedOutPausedGate(e){this.clear(e.executionId,e.nodeId,e.frameId);let{gate:t}=await this.bus.request(p.getGateInstance,{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId});if(t===null||t.status!==`waiting`)return`settled`;let{execution:n}=await this.bus.request(p.getExecution,{executionId:e.executionId});return n?.status===`running`?`retry`:n?.status===`paused`?(await this.resumePausedExecution(e.executionId),`resumed`):`settled`}};function Vr(e){if(e!==void 0)return Hr(e)?e:{}}function Hr(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ur(e){if(e!==void 0)return Je.parse(e)}function Wr(e,t){return tt.parse({executionId:e.executionId,workflowId:e.workflowId,source:e.source,...e.definitionSnapshot===void 0?{}:{definitionSnapshot:e.definitionSnapshot},workerManifest:{contributionRefs:[]},inputs:e.inputs,config:e.config,scope:e.scope,triggerPayload:e.triggerPayload,triggerMode:e.triggerMode??`immediate`,...e.artifactRef===void 0?{}:{artifactRef:e.artifactRef},coordinatorSessionId:e.coordinatorSessionId,cancelSubject:`workflow.${e.executionId}.cancel`,env:t.platformDefaults.env??{},createdAt:Date.now(),suspensionStrategy:e.suspensionStrategy??`wait-in-process`,...e.materializationSpec===void 0?{}:{materializationSpec:e.materializationSpec}})}function Gr(e){return e?.status===`paused`}function Kr(e){return e?.status===`waiting`}async function qr(e,t,n,r,i,a,o){t.delete(i.id),n.delete(i.id),r.delete(i.id);try{await e.request(p.restorePausedGateResumeState,{execution:i,gate:a})}catch(e){console.error(`[WorkflowExecutor] Failed to restore paused gate '${o}' after resume launch failure:`,e)}}async function Jr(e,t){if(t.suspensionStrategy===`wait-in-process`)return;let{frames:n}=await e.request(p.listFrames,{executionId:t.executionId});if(n.length===0)throw Error(`[WorkflowExecutor] Missing resume frames for paused execution: ${t.executionId}`)}function Yr(e){return{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,timeoutMs:e.timeoutMs,openedAt:e.createdAt}}async function Xr(e,t){if(t.frameId!==void 0){let{gate:n}=await e.request(p.getGateInstance,t);return Kr(n)?n:null}let{gates:n}=await e.request(p.listGateInstances,{executionId:t.executionId}),r=n.filter(e=>e.nodeId===t.nodeId&&e.status===`waiting`);return r.length===1?r[0]:null}function Zr(e,n){return e.origin.local?{executionAttemptId:n.executionAttemptId,executionId:n.executionId}:t(e)}async function Qr(e,t,n){let[{execution:r},{runContext:i}]=await Promise.all([e.request(p.getExecution,{executionId:t}),e.request(p.getRunContext,{executionId:t})]);if(!r)throw Error(`Outcome execution not found: ${t}`);if(r.id!==t||r.workflowId!==n.workflowId)throw Error(`Outcome workflow identity mismatch for execution '${t}'`);if(!i)throw Error(`Outcome run context not found: ${t}`);if(i.executionId!==t||i.workflowId!==n.workflowId)throw Error(`Outcome run context identity mismatch for execution '${t}'`);if(i.terminalAuthority===`worker`)throw Error(`Outcome submission requires authority terminal ownership for execution '${t}'`)}async function $r(e,t,n){if(n.pausedAtGateId===void 0||n.pausedAtFrameId===void 0)throw Error(`Paused outcome for '${t}' is missing gate identity`);let{paused:r}=await e.request(p.pauseRunningExecution,{executionId:t});if(!r){let{execution:n}=await e.request(p.getExecution,{executionId:t});if(n?.status!==`paused`)throw Error(`Failed to park execution '${t}': status is '${n?.status??`missing`}'`);return}await e.emit(h.execution.paused,{executionId:t,workflowId:n.workflowId,pausedAtGateId:n.pausedAtGateId,pausedAtFrameId:n.pausedAtFrameId})}function ei(e,t){return e.on(Ze.control.outcome.submit,async n=>{let r=Zr(n,n.payload);if(r===null)throw Error(`Outcome submission requires an authenticated workflow-execution-attempt peer`);let{result:i}=n.payload;if(!n.origin.local){if(n.payload.executionId!==r.executionId)throw Error(`Outcome payload executionId '${n.payload.executionId}' does not match authenticated peer claim '${r.executionId}'`);if(n.payload.executionAttemptId!==r.executionAttemptId)throw Error(`Outcome payload executionAttemptId '${n.payload.executionAttemptId}' does not match authenticated peer identity '${r.executionAttemptId}'`)}if(i.executionId!==r.executionId)throw Error(`Nested result.executionId '${i.executionId}' does not match trusted identity '${r.executionId}'`);let a=nt.parse(i);await Qr(e,r.executionId,a);let o=a.status===`paused`,s=await t.authority.commitOutcome(r.executionAttemptId,r.executionId,a),c=ti(s.kind);(s.kind===`accepted`||s.kind===`duplicate`)&&(o?await $r(e,r.executionId,a):await t.acceptTerminalResult(r.executionId,s.outcome),t.authority.settleOutcome(r.executionAttemptId,s)),n.setResult({decision:c})})}function ti(e){return e}function ni(e){return e.on(h.finalizeDelegateResult,async t=>{let n=t.payload;ri(t,n.executionId);let{execution:r}=await e.request(p.getExecution,{executionId:n.executionId});if(r===null||r.workflowId!==n.workflowId)throw Error(`delegate result finalization execution does not own the requested workflow`);let{runContext:i}=await e.request(p.getRunContext,{executionId:n.executionId});if(i===null||i.executionId!==n.executionId||i.workflowId!==n.workflowId)throw Error(`delegate result finalization run context does not own the requested workflow execution`);if(i.definitionSnapshot===void 0)throw Error(`delegate result finalization requires an Authority-owned definition snapshot`);ii(i.definitionSnapshot,n.nodeId,n.nodeType,n.finalizerId);let{subjects:a}=at(n.finalizerId),o=await e.request(a.finalize,{executionId:n.executionId,workflowId:n.workflowId,frameId:n.frameId,nodeId:n.nodeId,nodeType:n.nodeType,rawResult:n.rawResult,toolObservations:n.toolObservations,...n.economics===void 0?{}:{economics:n.economics}});t.setResult(o)})}function ri(e,t){if(!g(e,t))throw Error(`delegate result finalization requires its authenticated workflow-execution-attempt peer`)}function ii(e,t,n,r){let i=!1;if(ut(e.root,{enter(e){if(!(e.type!==`delegate-agent`&&e.type!==`delegate-role`||e.id!==t||e.type!==n))return e.resultFinalizerId===r&&(i=!0),!1}}),!i)throw Error(`delegate result finalizer is not selected by the requested durable delegate node`)}var ai=class extends dt{static storage={drizzle:Sr};config;activeExecutions=new Map;executionTasks=new Map;shellAbortControllers=new Map;activeRunnerSteps=new Map;gateTimeoutScheduler;resumeDispatches=new Set;workflowAbortControllers=new Map;successFinalizers=new Map;durableLifecycleTransitions=new Map;lifecyclePublications=new Map;publishingLifecycleExecutions=new Set;workflowRunner;executionAttemptAuthority;materializationSpecResolvers=new Set;constructor(e,t,n,r){super(e),this.config={...i,...t},this.workflowRunner=n,this.executionAttemptAuthority=r,this.gateTimeoutScheduler=new Br(e,e=>this.resumePausedExecution(e))}registerWorkflowMaterializationSpecResolver(e){return this.materializationSpecResolvers.add(e),()=>this.materializationSpecResolvers.delete(e)}async registerSuccessFinalizer(e){if(!this.initialized)throw Error(`[WorkflowExecutor] Initialize the executor before registering success finalizers`);if(this.successFinalizers.has(e))throw Error(`[WorkflowExecutor] Success finalizer already registered: ${e}`);let{namespace:t,subjects:n}=ot(e);this.bus.registerNamespace(t);let i={finalizerId:e,finalizeSubject:n.finalize};this.successFinalizers.set(e,i);try{await r(this.buildFinalizerDeps())}catch(t){throw this.successFinalizers.get(e)===i&&this.successFinalizers.delete(e),t}let a=!1;return()=>{a||(a=!0,this.successFinalizers.get(e)===i&&this.successFinalizers.delete(e))}}async acceptAuthorityRunnerResult(e,t){if(t.status===`paused`)throw Error(`authority runner result must be terminal`);if(t.executionId!==e)throw Error(`authority runner result execution identity mismatch`);let{execution:n}=await this.bus.request(p.getExecution,{executionId:e});if(!n)throw Error(`Authority runner execution not found: ${e}`);if(n.workflowId!==t.workflowId)throw Error(`authority runner result workflow identity mismatch`);let r;if(n.status===`finalizing`){let{workflow:n}=await this.loadAuthorityRunnerContext(e,t.workflowId);r=await this.registerAuthorityResultFinalizer(n)}let i=await this.resolveAuthorityRunnerReplay(n,t).finally(()=>r?.());if(i!==void 0)return{accepted:!0,status:i};if(n.status!==`running`)throw Error(`Authority runner execution is ${n.status}`);let{runContext:a,workflow:o}=await this.loadAuthorityRunnerContext(e,t.workflowId),s=await this.registerAuthorityResultFinalizer(o),c=this.activeExecutions.get(e),l=!1;if(!c)this.activeExecutions.set(e,{execution:n,workflow:o,runContext:a,runtimeHandlers:new Map,runtimeLoopGates:new Map}),l=!0;else if(c.execution.workflowId!==t.workflowId)throw Error(`authority runner active execution identity mismatch`);try{await Fe({activeExecutions:this.activeExecutions,buildFinalizerDeps:()=>this.buildFinalizerDeps()},t)}finally{l&&this.activeExecutions.delete(e),s?.()}let u=await this.bus.request(p.getExecution,{executionId:e});if(!u.execution||!m(u.execution.status,t.status))throw Error(`Authority runner result did not settle compatibly with ${t.status}`);return{accepted:!0,status:u.execution.status}}async resolveAuthorityRunnerReplay(e,t){if(e.status===`finalizing`){if(t.status!==`completed`)throw Error(`authority runner result conflicts with terminal execution`);await r(this.buildFinalizerDeps());let n=await this.bus.request(p.getExecution,{executionId:e.id});if(!n.execution)throw Error(`Authority runner success finalization execution is missing`);if(!m(n.execution.status,t.status))throw Error(`authority runner result conflicts with terminal execution`);return n.execution.status}if(!(e.status!==`completed`&&e.status!==`failed`&&e.status!==`cancelled`)){if(!m(e.status,t.status))throw Error(`authority runner result conflicts with terminal execution`);return e.status}}async loadAuthorityRunnerContext(e,t){let{runContext:n}=await this.bus.request(p.getRunContext,{executionId:e});if(!n)throw Error(`Authority runner run context not found: ${e}`);if(n.executionId!==e||n.workflowId!==t)throw Error(`authority runner run context identity mismatch`);if(n.terminalAuthority!==`authority`)throw Error(`authority runner result requires terminalAuthority=authority`);let r=n.definitionSnapshot??(await this.bus.request(p.get,{id:n.workflowId})).workflow;if(!r||r.id!==t)throw Error(`authority runner workflow definition is unavailable or mismatched`);return{runContext:n,workflow:r}}registerAuthorityResultFinalizer(e){return!e.successFinalizerId||this.successFinalizers.has(e.successFinalizerId)?Promise.resolve(void 0):this.registerSuccessFinalizer(e.successFinalizerId)}async onInit(){this.registerExecutionHandlers(),this.addCleanup(we(this.bus,(e,t)=>{let n=this.activeExecutions.get(e);n!==void 0&&(n.workflow=t)})),this.addCleanup(ni(this.bus)),this.executionAttemptAuthority!==void 0&&this.addCleanup(ei(this.bus,{bus:this.bus,authority:this.executionAttemptAuthority,acceptTerminalResult:(e,t)=>this.acceptAuthorityRunnerResult(e,t)}));for(let e of Dr(this.bus))this.addCleanup(e);for(let e of jr(this.bus))this.addCleanup(e);await this.rehydratePausedGateTimeouts()}async onDestroy(){let e=this.buildFinalizerDeps();await Promise.allSettled([...this.activeExecutions.keys()].map(async t=>{await _(e,t,`Workflow engine shutdown`)&&(this.workflowAbortControllers.get(t)?.abort(),this.workflowAbortControllers.delete(t))}));for(let e of this.workflowAbortControllers.values())e.abort();this.workflowAbortControllers.clear(),await Promise.allSettled(this.executionTasks.values()),await Promise.allSettled(this.durableLifecycleTransitions.values()),await Promise.allSettled(this.lifecyclePublications.values());for(let e of this.shellAbortControllers.values())e.abort();this.shellAbortControllers.clear();for(let e of this.activeRunnerSteps.values())e.hardKillTimer&&clearTimeout(e.hardKillTimer);this.activeRunnerSteps.clear(),this.gateTimeoutScheduler.dispose(),await this.workflowRunner?.dispose?.(),this.activeExecutions.clear()}buildFinalizerDeps(){return{bus:this.bus,activeExecutions:this.activeExecutions,shellAbortControllers:this.shellAbortControllers,activeRunnerSteps:this.activeRunnerSteps,cancelTimeoutMs:this.config.cancelTimeoutMs,successFinalizers:this.successFinalizers,resolveSuccessFinalizerId:e=>this.activeExecutions.get(e)?.workflow.successFinalizerId,durableLifecycleTransitions:this.durableLifecycleTransitions,lifecyclePublications:this.lifecyclePublications,publishingLifecycleExecutions:this.publishingLifecycleExecutions}}buildRunnerTaskDeps(e){return{workflowRunner:e,workflowAbortControllers:this.workflowAbortControllers,executionTasks:this.executionTasks,activeExecutions:this.activeExecutions,buildFinalizerDeps:()=>this.buildFinalizerDeps(),config:this.config}}async resolveExecutionWorkspaceRoot(e){if(!e)return this.config.platformDefaults.cwd;let{session:t}=await this.bus.request(Ye.get,{sessionId:e});if(t===null)throw Error(`[WorkflowExecutor] Parent session not found: ${e}`);return t.targetWorkingDirectory??this.config.platformDefaults.cwd}resolveEphemeralPlatformFields(){return Pe(this.config.platformDefaults.cwd,this.config.makaioHome)}buildStartDeps(){return{bus:this.bus,config:this.config,activeExecutions:this.activeExecutions,executionTasks:this.executionTasks,workflowRunner:this.workflowRunner,buildRunContext:e=>Wr(e,this.config),buildRunnerTaskDeps:e=>this.buildRunnerTaskDeps(e),buildFinalizerDeps:()=>this.buildFinalizerDeps(),resolveExecutionWorkspaceRoot:e=>this.resolveExecutionWorkspaceRoot(e),runExecution:e=>this.runExecution(e),executionAttemptAuthority:this.executionAttemptAuthority,materializationSpecResolvers:this.materializationSpecResolvers}}registerExecutionHandlers(){this.registerHandler(h.acceptAuthorityRunnerResult,async e=>{if(!e.origin.local)throw Error(`authority runner result acceptance is local-authority only`);let{executionId:t,result:n}=e.payload;e.setResult(await this.acceptAuthorityRunnerResult(t,n))}),this.registerHandler(h.start,async e=>{let{workflowId:t,input:n,config:r,parentSessionId:i,triggerPayload:a,artifactRef:o,scope:s}=e.payload;try{let c=await _e(this.buildStartDeps(),t,{input:Ur(n),config:Vr(r)??{},parentSessionId:i,triggerPayload:a,artifactRef:o,scopeOverride:s});e.setResult({executionId:c})}catch(e){if(e instanceof S)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow: ${t}`)}}),this.registerHandler(h.rerun,async e=>{let{executionId:t,mode:n,input:r,config:i,parentSessionId:a,triggerPayload:o,artifactRef:s,scope:c,reason:l}=e.payload;try{let u=await Pr(this.buildStartDeps(),{executionId:t,mode:n,input:Ur(r),config:Vr(i),parentSessionId:a,triggerPayload:o,artifactRef:s,scopeOverride:c,reason:l});e.setResult({executionId:u})}catch(e){if(e instanceof S)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to rerun workflow: ${t}`)}}),this.registerHandler(h.runFile,async e=>{if(this.workflowRunner===void 0)throw Error(`workflow.runFile requires a workflow runner — configure a ThinWorkflowPiscinaRunner or equivalent.`);let{filePath:t,materializationSpec:n,triggerPayload:r,triggerMode:i,scope:a}=e.payload;try{let o=await Oe(this.buildStartDeps(),t,{...n===void 0?{}:{materializationSpec:n},triggerPayload:r,triggerMode:i,scopeOverride:a});e.setResult({executionId:o})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow file: ${t}`)}}),this.registerHandler(h.cancel,async e=>{let{executionId:t,reason:n}=e.payload;await this.bus.emit(it(`workflow.${t}.cancel`),{executionId:t,reason:n}).catch(e=>{console.error(`[WorkflowExecutor] Failed to emit workflow cancel for ${t}:`,e)});let r=this.workflowAbortControllers.get(t);if(r){r.abort(n??x);let i=await _(this.buildFinalizerDeps(),t,n);e.setResult({cancelled:i});return}let i=await _(this.buildFinalizerDeps(),t,n);e.setResult({cancelled:i})}),this.registerGateTimeoutHandlers(),this.addCleanup(this.bus.on(h.gate.respond,async e=>{let{executionId:t,gateId:n,frameId:r,action:i,resumeData:a,reason:o}=e.payload,s=await this.respondToPausedGate({executionId:t,gateId:n,frameId:r,action:i,resumeData:a,reason:o});e.setResult({accepted:s})},{priority:-100}))}registerGateTimeoutHandlers(){this.addCleanup(this.bus.on(h.gate.suspended,e=>{this.gateTimeoutScheduler.schedule(e.payload)})),this.addCleanup(this.bus.on(h.gate.resolved,e=>{this.gateTimeoutScheduler.clear(e.payload.executionId,e.payload.stepId,e.payload.frameId)}))}async rehydratePausedGateTimeouts(){let{gates:e}=await this.bus.request(p.listPausedGateTimeouts,{});for(let t of e)this.gateTimeoutScheduler.schedule(Yr(t))}async runExecution(e){let t=this.activeExecutions.get(e);if(!t)return;let n=new AbortController;this.workflowAbortControllers.set(e,n);try{let r;try{let i=await he({definition:t.workflow,execution:t.execution,runContext:t.runContext,bus:this.bus}),a=new Se(e,t.workflow.id,t.workflow,t.execution,t.runtimeHandlers,this.bus,n.signal,void 0,i,{context:this.resolveEphemeralPlatformFields(),env:t.runContext.env},{runtimeLoopGates:t.runtimeLoopGates});Ae(t.workflow,t.runtimeLoopGates);let o=a.buildExpressionContext();r=await ye(t.workflow.root,a,o)}catch(r){if(n.signal.aborted||t.execution.status===`cancelled`){await _(this.buildFinalizerDeps(),e,x);return}let i=r instanceof Error?r.message:String(r);await me(this.buildFinalizerDeps(),t.execution,e,i);return}let i=this.buildFinalizerDeps();r.status===`cancelled`||n.signal.aborted||t.execution.status===`cancelled`?await _(i,e,x):r.status===`failed`?await me(i,t.execution,e,r.error):r.status===`paused`?(t.execution.status=`paused`,await this.bus.request(p.setExecution,{execution:t.execution}),this.activeExecutions.delete(e)):await Le(i,t.execution,e,t.execution.startedAt)}finally{this.workflowAbortControllers.delete(e)}}async respondToPausedGate(e){let{executionId:t,gateId:n,frameId:r,resumeData:i,reason:a}=e,{execution:o}=await this.bus.request(p.getExecution,{executionId:t});if(!Gr(o))return!1;let s=await Xr(this.bus,{executionId:t,nodeId:n,frameId:r});if(s===null||!Ee(n,s.schema,i).valid)return!1;let{runContext:c}=await this.bus.request(p.getRunContext,{executionId:t});if(c===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${t}`);await Jr(this.bus,c);let{accepted:l}=await this.bus.request(p.resolveWaitingGateInstance,{gate:{...s,status:e.action===`reject`?`rejected`:`resumed`,resumeData:i,...a===void 0?{}:{reason:a},resolvedAt:Date.now()}});if(!l)return!1;try{await this.resumePausedExecution(o.id)}catch(e){throw await qr(this.bus,this.activeExecutions,this.executionTasks,this.workflowAbortControllers,o,s,n),e}return this.gateTimeoutScheduler.clear(t,n,s.frameId),!0}async resumePausedExecution(e){if(!this.resumeDispatches.has(e)){this.resumeDispatches.add(e);try{await this.dispatchPausedExecutionResume(e)||this.resumeDispatches.delete(e)}catch(t){throw this.resumeDispatches.delete(e),t}}}async dispatchPausedExecutionResume(e){let{runContext:t}=await this.bus.request(p.getRunContext,{executionId:e});if(t===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${e}`);let n=t.definitionSnapshot??(await this.bus.request(p.get,{id:t.workflowId})).workflow??(()=>{throw Error(`[WorkflowExecutor] Workflow definition not found for paused execution: ${e}`)})(),{execution:r}=await this.bus.request(p.getExecution,{executionId:e});if(r===null)throw Error(`[WorkflowExecutor] Execution not found for paused execution: ${e}`);if(r.status!==`paused`)return!1;await Jr(this.bus,t),await this.bus.request(p.setExecution,{execution:{...r,status:`running`}}),this.activeExecutions.set(e,{execution:{...r,status:`running`},workflow:n,runContext:t,runtimeHandlers:new Map,runtimeLoopGates:new Map});let i=de(t,n,{resume:!0}),a=ve(this.buildStartDeps(),i).finally(()=>{this.resumeDispatches.delete(e)});return this.executionTasks.set(e,a),!0}};const Z=`[WorkflowTriggerReconciler]`;function oi(e){return e.map(si)}function si(e){let t=Qe.parse(e);return{binding:t,matches:Be(t),subscription:void 0}}function ci(e,t,n){let r=e.triggers??[];try{return n===void 0?oi(r):r.map(e=>n.has(e.kind)?si(e):void 0)}catch(i){if(t){console.error(`${Z} keeping last-good triggers for workflow "${e.id}": its trigger bindings are invalid`,i);return}return r.map((t,r)=>{if(!(n!==void 0&&!n.has(t.kind)))try{return si(t)}catch(t){console.error(`${Z} leaving invalid trigger ${r} of workflow "${e.id}" inactive`,t);return}})}}function Q(e,t){return e.scope.type!==`global`||t.kind!==We}async function li(e,t,n,r){if(r!==void 0)for(let[i,a]of Array.from(r)){let o=e.triggers?.[i];if(o!==void 0&&n!==void 0&&!n.has(o.kind))continue;let s=t[i];s!==void 0&&Q(e,s.binding)||(r.delete(i),await $(a.subscription))}}async function $(e){if(e!==void 0)try{await e.detach()}catch(t){console.error(`${Z} detach failed for '${e.bindingKey}':`,t)}}var ui=class{bus;resolveRuntime;consumers=new Map;cleanupFns=[];initialized=!1;initialization;lane=new Ve;pendingChanges=[];constructor(e,t){this.bus=e,this.resolveRuntime=t}async init(){if(this.initialized)return;if(this.initialization!==void 0)return this.initialization;let e=this.initialize();return this.initialization=e,e.then(()=>this.clearInitialization(e),()=>this.clearInitialization(e)),e}clearInitialization(e){this.initialization===e&&(this.initialization=void 0)}async initialize(){try{let e=({payload:e})=>{this.onSignal(`refresh of workflow "${e.id}"`,()=>this.refreshDefinition(e.id))};this.cleanupFns.push(this.bus.on(C.definition.created,e),this.bus.on(C.definition.updated,e),this.bus.on(C.definition.deleted,e),this.bus.on(Ue.changed,e=>{this.scheduleRegistryReconcile(e.payload)})),await this.reconcileStored(`keep-last-good`),this.initialized=!0}catch(e){throw await this.teardown(),e}}async destroy(){await this.teardown(),this.initialized=!1}activeConsumerCount(){let e=0;for(let t of this.consumers.values())e+=t.size;return e}onSignal(e,t){t().catch(t=>{console.error(`${Z} ${e} failed:`,t)})}scheduleRegistryReconcile(e){let t=this.pendingChanges.length>0;this.pendingChanges.push(e),!t&&queueMicrotask(()=>{if(this.pendingChanges.length===0)return;let e=this.pendingChanges.splice(0),t=new Set(e.flatMap(({kinds:e})=>e)),n=e.map(({owner:e,revision:t})=>`${e}@${t}`).join(`, `);this.onSignal(`reconciliation after trigger registry changes (${n})`,()=>this.reconcileStored(`drop-unavailable`,t))})}async reconcileStored(e,t){await this.lane.run(async()=>{let{workflows:n}=await this.bus.request(p.list,{}),r=new Set(n.map(e=>e.id));for(let r of n){let n=r.triggers??[];t!==void 0&&!n.some(e=>t.has(e.kind))||await this.applyDefinitionWithinLane(r,e,t)}for(let e of Array.from(this.consumers.keys()))r.has(e)||await this.forgetWorkflowWithinLane(e)})}async refreshDefinition(e){await this.lane.run(async()=>{let{workflow:t}=await this.bus.request(p.get,{id:e});if(t===null){await this.forgetWorkflowWithinLane(e);return}await this.applyDefinitionWithinLane(t,`keep-last-good`)})}async applyDefinitionWithinLane(e,t,n){let r=ci(e,(this.consumers.get(e.id)?.size??0)>0,n);if(r===void 0)return;let i=this.consumers.get(e.id);if(await li(e,r,n,i),i?.size===0&&this.consumers.delete(e.id),!r.some(t=>t!==void 0&&Q(e,t.binding)&&(n===void 0||n.has(t.binding.kind))))return;let a=this.resolveRuntime();if(a===void 0){r.length>0&&console.warn(`${Z} no automation trigger binding runtime is available; declarative triggers of workflow "${e.id}" stay inactive`);return}let o=this.consumers.get(e.id);o===void 0&&(o=new Map,this.consumers.set(e.id,o));for(let[i,s]of r.entries())s!==void 0&&Q(e,s.binding)&&(n!==void 0&&!n.has(s.binding.kind)||await this.refreshConsumerWithinLane(a,e.id,i,s,o,t));o.size===0&&this.consumers.delete(e.id)}async refreshConsumerWithinLane(e,t,n,r,i,a){let o=i.get(n),s=this.createListener(t,n,r);try{let t=o?.subscription?.bindingKey,a=e.prepareBinding(r.binding);if(a===void 0)throw Error(`Automation trigger kind '${r.binding.kind}' is not registered`);if(!a.workflowCompatible)throw Error(`Automation trigger kind '${r.binding.kind}' does not emit an object-root payload`);(t===void 0||t!==a.bindingKey)&&i.set(n,r),r.subscription=await a.subscribe(s),i.set(n,r),await $(o?.subscription);return}catch(e){if(o===void 0?i.delete(n):i.set(n,o),a===`keep-last-good`){console.error(`${Z} keeping last-good trigger ${n} of workflow "${t}": binding '${r.binding.kind}' could not be activated`,e);return}console.warn(`${Z} dropping trigger ${n} of workflow "${t}": binding '${r.binding.kind}' is no longer available`,e),i.delete(n),await $(o?.subscription)}}async forgetWorkflowWithinLane(e){let t=this.consumers.get(e);if(t!==void 0){this.consumers.delete(e);for(let e of t.values())await $(e.subscription)}}createListener(e,t,n){let r=`trigger ${t} ('${n.binding.kind}') of workflow "${e}"`;return async i=>{if(this.consumers.get(e)?.get(t)!==n)return;let a;try{a=n.matches(i.payload)}catch(e){console.error(`${Z} filter evaluation failed for ${r}:`,e);return}if(a)try{await this.bus.request(C.start,{workflowId:e,triggerPayload:ze(i.payload)})}catch(t){console.error(`${Z} failed to start workflow "${e}" from ${r}:`,t)}}}async teardown(){this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.pendingChanges.length=0,await this.lane.run(async()=>{for(let e of Array.from(this.consumers.keys()))await this.forgetWorkflowWithinLane(e)})}},di=class{repository;waiters=new Map;constructor(e){this.repository=e}async createAttempt(e){let t=crypto.randomUUID(),n=await this.repository.createAttempt({executionAttemptId:t,executionId:e});return this.installWaiter(t),n}async beginProvisioning(e){return this.repository.beginProvisioning(e)}async getProviderOperation(e){return this.repository.getProviderOperation(e)}async renewProviderOperationClaim(e){return this.repository.renewProviderOperationClaim(e)}async takeOverProviderOperation(e){return this.repository.takeOverProviderOperation(e)}async handoffProviderOperation(e){return this.repository.handoffProviderOperation(e)}async recordProviderOperationUncertainty(e){return this.repository.recordProviderOperationUncertainty(e)}async recordAllocation(e){return this.repository.recordAllocation(e)}async recordProvisioningAbsent(e){let t=await this.repository.recordProvisioningAbsent(e);return t.kind===`recorded`&&this.rejectWaiterWith(e.claim.executionAttemptId,()=>Error(`Attempt '${e.claim.executionAttemptId}' provisioning produced no allocation: ${e.evidence.source} reported '${e.evidence.summary}'`)),t}async recordProvisionerIncarnationLost(e){let t=await this.repository.recordProvisionerIncarnationLost(e);if(t.kind===`recorded`){let{evidence:t,provisionerIncarnationId:n}=e.proof;this.rejectWaiterWith(e.claim.executionAttemptId,()=>Error(`Attempt '${e.claim.executionAttemptId}' lost the provisioner incarnation '${n}' its allocation was bound to: ${t.source} reported '${t.summary}'`))}return t}async recordAllocationTerminated(e){return this.repository.recordAllocationTerminated(e)}async getActiveAttempt(e,t){return this.repository.getActiveAttempt(e,t)}async commitOutcome(e,t,n){let r=await this.repository.commitOutcome({executionAttemptId:e,executionId:t,result:n});return(r.kind===`conflict`||r.kind===`fenced`)&&this.settleWaiterInternal(e,r),r}waitForOutcome(e){return this.waiters.get(e)?.promise}settleOutcome(e,t){this.settleWaiterInternal(e,t)}discardWaiter(e){this.waiters.delete(e)}rejectAndDiscardWaiter(e,t){this.rejectWaiterWith(e,()=>t)}rejectWaiterWith(e,t){let n=this.waiters.get(e);n!==void 0&&(n.promise.catch(()=>void 0),n.reject(t()),this.waiters.delete(e))}get supportsRecovery(){return this.repository.recovery!==void 0}async getAttemptWithAllocation(e){return this.requireRecovery(`getAttemptWithAllocation`).getAttemptWithAllocation(e)}async recordDiscoveredAllocation(e){return this.requireRecovery(`recordDiscoveredAllocation`).recordDiscoveredAllocation(e)}async evolveAllocationRef(e){let t=this.requireRecovery(`evolveAllocationRef`);if(e.currentRef.providerId!==e.nextRef.providerId)throw Error(`Provider identity mismatch in allocation ref evolution: currentRef.providerId '${e.currentRef.providerId}' !== nextRef.providerId '${e.nextRef.providerId}'. Provider identity must not change during correlation.`);return t.evolveAllocationRef(e)}async getRecoverableAttempts(e){return this.requireRecovery(`getRecoverableAttempts`).getRecoverableAttempts(e)}async recordInfrastructureFailure(e){let t=await this.repository.recordInfrastructureFailure(e);return t.kind===`recorded`&&this.rejectWaiterWith(e.claim.executionAttemptId,()=>Error(`Attempt '${e.claim.executionAttemptId}' suffered infrastructure failure: the provider allocation terminated without an acknowledged outcome`)),t}async abandonPendingAttempt(e,t){let n=await this.repository.abandonPendingAttempt(e,t);return(n.kind===`abandoned`||n.kind===`already-abandoned`)&&this.waiters.delete(e),n}requireRecovery(e){let{recovery:t}=this.repository;if(t===void 0)throw Error(`Recovery operation '${e}' requires a repository that exposes recovery operations. The injected repository does not support recovery.`);return t}installWaiter(e){this.waiters.set(e,fe())}settleWaiterInternal(e,t){let n=this.waiters.get(e);if(n){switch(t.kind){case`accepted`:case`duplicate`:n.resolve(t.outcome);break;case`conflict`:n.reject(Error(`Outcome conflict for attempt '${e}': a different outcome was already committed`));break;case`fenced`:n.reject(Error(`Attempt '${e}' has been fenced: it is no longer the active attempt for this execution`));break}this.waiters.delete(e)}}},fi=class extends dt{workflowExecutor;triggerReconcilerInstance;attemptAuthority;workspaceRootResolvers=new Set;constructor(e,t){super(e),this.attemptAuthority=t?.executionAttemptAuthority??(t?.executionAttemptRepository?new di(t.executionAttemptRepository):void 0),this.workflowExecutor=new ai(e,t?.executorConfig,t?.workflowRunner,this.attemptAuthority);for(let e of t?.workflowMaterializationSpecResolvers??[])this.workflowExecutor.registerWorkflowMaterializationSpecResolver(e);let n=t?.automationTriggerBindingRuntime;this.triggerReconcilerInstance=new ui(e,()=>n?.())}get executor(){return this.workflowExecutor}get executionAttemptAuthority(){return this.attemptAuthority}registerSuccessFinalizer(e){return this.workflowExecutor.registerSuccessFinalizer(e)}acceptAuthorityRunnerResult(e,t){return this.workflowExecutor.acceptAuthorityRunnerResult(e,t)}get triggerReconciler(){return this.triggerReconcilerInstance}registerWorkflowMaterializationSpecResolver(e){return this.workflowExecutor.registerWorkflowMaterializationSpecResolver(e)}registerWorkspaceRootResolver(e){return this.workspaceRootResolvers.add(e),()=>{this.workspaceRootResolvers.delete(e)}}async resolveWorkspaceRoot(e){for(let t of this.workspaceRootResolvers){let n=await t(e);if(n!==void 0)return n}}async onInit(){this.addCleanup(()=>this.destroyOwnedServices()),await this.workflowExecutor.init(),await this.triggerReconcilerInstance.init()}async destroyOwnedServices(){let e=[];for(let t of[()=>this.triggerReconcilerInstance.destroy(),()=>this.workflowExecutor.destroy()])try{await t()}catch(t){e.push(t)}if(e.length===1)throw e[0];if(e.length>1)throw AggregateError(e,`Workflow engine service teardown failed`)}};const pi=ct(`makaio.workflow-engine`);function mi(e){return{name:pi.name,displayName:`Workflow Engine`,version:`0.1.0`,dependencies:[st(St.name),st(Ct.name,void 0,!0)],critical:!0,namespaces:[et,xe],storage:{registerHandlers:mt(Sr)},create:t=>new fi(t.bus,{...e,automationTriggerBindingRuntime:()=>t.getService(Ct)})}}const hi=mi();export{di as a,Sr as c,an as d,fi as i,rn as l,mi as n,ui as o,hi as r,ai as s,pi as t,nn as u};
@@ -1 +0,0 @@
1
- import{n as e}from"./json-value-BBZ6uGwc.mjs";import{n as t}from"./capability-j3NekkIu.mjs";import{z as n}from"zod";const r=n.enum([`wait-in-process`,`exit-and-redispatch`,`exit-and-resume`]),i=`worker-node`,a=`makaio.runtime-node.piscina-local`,o=1,s=n.object({version:n.literal(1),providerId:n.string().min(1),providerData:e}).strict(),c={source:128,code:64,summary:512,observedAt:64},l=n.object({source:n.string().min(1).max(c.source),summary:n.string().min(1).max(c.summary),observedAt:n.iso.datetime({offset:!0}).max(c.observedAt),code:n.string().min(1).max(c.code).optional()}).strict(),u=`exhaustive-search-unavailable`,d=`no-allocation-observed`,f=`ambiguous-allocation-match`,p=`pre-request-rejection`,m=[`unknown`,`provisioning`,`ready`,`running`,`suspended`,`terminal`,`absent`],h=n.enum(m),g=n.object({state:h,allocationRef:s,evidence:e.optional()}),_=[`local-directory`,`workspace-snapshot`],v=n.enum(_),y=n.string().min(1).refine(e=>!e.startsWith(`/`)&&!/^[A-Za-z]:[/\\]/.test(e),{message:`sourcePath must be relative (no leading / or drive letter)`}),b=n.object({kind:n.literal(`local-directory`),workspaceId:n.string().min(1),rootDigest:n.string().min(1),sourcePath:y}).strict(),x=n.object({kind:n.literal(`workspace-snapshot`),snapshotId:n.string().min(1),digest:n.string().min(1),sourcePath:y}).strict(),S=n.discriminatedUnion(`kind`,[b,x]),C=/^sha(?:256|384|512)-[A-Za-z0-9+/]+=*$/,w=n.object({packageName:n.string().min(1),version:n.string().min(1),entrypoint:n.string().min(1).refine(e=>!e.includes(`node_modules`)&&!e.startsWith(`/`)&&!/^[A-Za-z]:[/\\]/.test(e),{message:`entrypoint must be package-relative (no node_modules, no absolute path)`}),integrity:n.string().min(1).refine(e=>C.test(e),{message:`integrity must be a valid SRI hash (sha256-..., sha384-..., or sha512-...)`})}).strict(),T=n.object({maxRuntimeMs:n.number().int().positive().optional(),persistentStorage:n.boolean(),customCapabilities:n.array(n.string().min(1)).default([]),suspensionStrategy:r.default(`wait-in-process`),supportsRecovery:n.boolean().default(!1),materializationModes:n.array(v).min(1).default([`local-directory`])}),E=n.object({maxRuntimeMs:n.number().int().positive().optional(),persistentStorage:n.boolean().optional(),customCapabilities:n.array(n.string().min(1)).default([]),recoverableAllocation:n.boolean().optional(),materializationModes:n.array(v).optional()}),D=[`provisioner-process-bound`,`provider-managed`],O=n.enum(D),k=[`found`,`confirmed-absent`,`unknown`],A=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`found`),allocationRef:s}).strict(),n.object({kind:n.literal(`confirmed-absent`),evidence:l}).strict(),n.object({kind:n.literal(`unknown`),evidence:l}).strict()]),j=n.enum([`accepted`,`duplicate`,`conflict`,`fenced`]);var M=class extends Error{constructor(e){super(e),this.name=`ProviderAllocationRefError`}};function N(e,t){let n=s.shape.providerId.parse(e);return{build:e=>{let r=t.parse(e);return{version:1,providerId:n,providerData:s.shape.providerData.parse(r)}},parse:e=>{if(e.version!==1)throw new M(`Unsupported allocation ref version ${String(e.version)}, expected 1`);if(e.providerId!==n)throw new M(`Allocation ref provider '${e.providerId}' does not match this provider '${n}'`);let r=t.safeParse(e.providerData);if(!r.success)throw new M(`Invalid provider data in allocation ref: ${r.error.message}`);return r.data}}}function P(e,t){if(e.length<=t)return e;let n=e.slice(0,t-1),r=n.charCodeAt(n.length-1);return`${r>=55296&&r<=56319?n.slice(0,-1):n}…`}function F(e,t,n){let r=c.summary;return l.parse({source:e,summary:P(n,r),observedAt:new Date().toISOString(),...t===void 0?{}:{code:t}})}function I(e,n){return e.emit(t.register,{capabilityId:i,provider:n})}function L(e,n){return e.emit(t.unregister,{capabilityId:i,providerId:n})}export{E as A,c as C,S as D,w as E,r as M,O,A as S,i as T,j as _,N as a,k as b,g as c,l as d,u as f,d as g,v as h,M as i,x as j,T as k,h as l,_ as m,L as n,m as o,b as p,F as r,f as s,I as t,a as u,p as v,D as w,s as x,o as y};
@@ -1 +0,0 @@
1
- import{n as e}from"./json-value-BBZ6uGwc.mjs";import{A as t,_ as n,x as r}from"./worker-node-CjuQb9hl.mjs";import{G as i,H as a,V as o}from"./workflow-C4mck_NW.mjs";import{z as s}from"zod";import{createBusNamespace as c}from"@makaio/framework/core";const l=s.object({executionAttemptId:s.string().min(1),executionId:s.string().min(1),environment:s.string().min(1),metadata:e.optional()}),u=s.object({executionAttemptId:s.string().min(1),config:i,manifest:o.optional(),requirements:t.optional(),metadata:e.optional()}),d=s.object({executionAttemptId:s.string().min(1),allocationRef:r}).strict(),f={dispatch:{request:u,response:d},"control.attempt-ready":s.object({executionAttemptId:s.string().min(1),executionId:s.string().min(1),adapters:s.array(s.string().min(1)).default([])}).strict(),"control.outcome.submit":{request:s.object({executionAttemptId:s.string().min(1),executionId:s.string().min(1),result:a}).strict().superRefine((e,t)=>{e.result.executionId!==e.executionId&&t.addIssue({code:s.ZodIssueCode.custom,path:[`result`,`executionId`],message:`result.executionId must match executionId`})}),response:s.object({decision:n}).strict()},"control.bootstrap.claim":{request:s.object({executionId:s.string().min(1),executionAttemptId:s.string().min(1)}).strict(),response:s.object({busUrl:s.string().min(1),busAuthSecret:s.string().min(1)}).strict()},"lifecycle.provisioning":l,"lifecycle.booting":l,"lifecycle.ready":l.extend({adapters:s.array(s.string().min(1)).default([])}),"lifecycle.busy":l,"lifecycle.completed":l,"lifecycle.failed":l.extend({error:s.string().min(1)}),"lifecycle.terminated":l.extend({reason:s.string().optional()}),"lifecycle.paused":l.extend({pausedAtGateId:s.string().min(1),pausedAtFrameId:s.string().min(1)})},p=`worker-bootstrap`,m=c(`worker-node`,f),h=m.subjects;export{d as a,u as i,m as n,f as o,h as r,p as t};