@makaio/framework 1.0.0-dev-1788258714339 → 1.0.0-dev-1788721567504

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 (115) hide show
  1. package/dist/.makaio-build.json +2 -2
  2. package/dist/attempt-record-codec-BORASgzn.mjs +1 -0
  3. package/dist/authority-state-bootstrap-eitx6Ukn.mjs +1 -0
  4. package/dist/bus/index.d.mts +19 -19
  5. package/dist/bus/index.mjs +1 -1
  6. package/dist/capabilities-DEvmD9VJ.mjs +1 -0
  7. package/dist/{context-resolution-CW4OtPrS.d.mts → context-resolution-CoKFKIqz.d.mts} +5 -5
  8. package/dist/contracts/adapter/index.d.mts +1 -1
  9. package/dist/contracts/artifact/index.d.mts +2 -2
  10. package/dist/contracts/canonical-model/index.d.mts +1 -1
  11. package/dist/contracts/capabilities/index.d.mts +2 -2
  12. package/dist/contracts/capabilities/index.mjs +1 -1
  13. package/dist/contracts/client/index.d.mts +1 -1
  14. package/dist/contracts/extension/index.d.mts +3 -3
  15. package/dist/contracts/harness/index.d.mts +1 -1
  16. package/dist/contracts/index.d.mts +618 -124
  17. package/dist/contracts/index.mjs +1 -1
  18. package/dist/contracts/materialization/index.d.mts +3 -3
  19. package/dist/contracts/session/index.d.mts +2 -2
  20. package/dist/contracts/shared/index.d.mts +1 -1
  21. package/dist/contracts/variant/index.d.mts +1 -1
  22. package/dist/contracts/worker/index.d.mts +2 -0
  23. package/dist/contracts/worker/index.mjs +1 -0
  24. package/dist/contracts/workflow/index.d.mts +2 -2
  25. package/dist/contracts/workflow/index.mjs +1 -1
  26. package/dist/{execution-attempt-repository-BJ2W6wwx.d.mts → execution-attempt-repository-CRdrgou3.d.mts} +869 -58
  27. package/dist/{index-jxPncqWZ2.d.mts → index--Ws52sWV2.d.mts} +4 -4
  28. package/dist/{index-OG402CBI.d.mts → index-37_b--BH.d.mts} +85 -85
  29. package/dist/{index-B-3I98nw.d.mts → index-AdcDBUnc.d.mts} +95 -95
  30. package/dist/{index-CMekqu_D.d.mts → index-BJdkVFX9.d.mts} +327 -63
  31. package/dist/{index-4KJ6IDE7.d.mts → index-BKIxdzIw.d.mts} +5 -5
  32. package/dist/{index-CPi0UpRh.d.mts → index-B_8bA2JW.d.mts} +1 -1
  33. package/dist/{index-CmwAJ8-5.d.mts → index-CFI6FxC7.d.mts} +1 -1
  34. package/dist/{index-BqlCDBfc.d.mts → index-CVcG4Q3X.d.mts} +5 -5
  35. package/dist/{index-DXqG0r3o.d.mts → index-CxwqnZpT.d.mts} +62 -62
  36. package/dist/{index-BkbnC65b.d.mts → index-CyWGSxrs.d.mts} +291 -291
  37. package/dist/{index-B9V3T4EQ.d.mts → index-D037TVsm.d.mts} +4 -4
  38. package/dist/{index-C146Eq_J.d.mts → index-D1wTWSLR.d.mts} +327 -327
  39. package/dist/{index-DWkFkvRn2.d.mts → index-D8D-yibS2.d.mts} +3 -3
  40. package/dist/{index-Bqk0pJBQ2.d.mts → index-DBD_oFEt2.d.mts} +1 -1
  41. package/dist/{index-DJ2KgJDJ2.d.mts → index-DV38-klA2.d.mts} +59 -83
  42. package/dist/{index-C3lu_fy5.d.mts → index-I5a37JCm.d.mts} +76 -76
  43. package/dist/{namespace-l-HG1rLF.d.mts → namespace-Bo94cenp.d.mts} +136 -136
  44. package/dist/{namespace-DknCutQZ.d.mts → namespace-CPm9dhi2.d.mts} +2 -2
  45. package/dist/{namespace-BNp7n_gu.d.mts → namespace-CsnrP8AD.d.mts} +3 -3
  46. package/dist/{namespace-BGRHcrmp.d.mts → namespace-CstawJgN.d.mts} +2 -2
  47. package/dist/{namespace-C06lJSuj.d.mts → namespace-K23m4b0n.d.mts} +6 -6
  48. package/dist/{package-BNFTUFLB.d.mts → package-DkZmsdCd.d.mts} +107 -30
  49. package/dist/package-UemD2NWn.mjs +7 -0
  50. package/dist/package.json +1 -1
  51. package/dist/runtime-node/index.d.mts +2 -2
  52. package/dist/runtime-node/index.mjs +24 -24
  53. package/dist/runtime-node/makaio-config.d.mts +2 -2
  54. package/dist/runtime-node/makaio-config.mjs +1 -1
  55. package/dist/runtime-node/workflow-execution-bus-access.mjs +1 -1
  56. package/dist/runtime-node/workflow-worker/index.d.mts +2 -2
  57. package/dist/runtime-node/workflow-worker/index.mjs +1 -1
  58. package/dist/runtime-node/workflow-worker/worker-entry.d.mts +49 -9
  59. package/dist/runtime-node/workflow-worker/worker-entry.mjs +1 -1
  60. package/dist/runtime-registration-client-BTtFpt_k.mjs +1 -0
  61. package/dist/{schemas-OWvBn7AH.d.mts → schemas-BCXvEWyF.d.mts} +4 -4
  62. package/dist/{schemas-Dd0po67F.d.mts → schemas-CJKHYluy.d.mts} +16 -16
  63. package/dist/{schemas-C1mxTfd7.d.mts → schemas-CenET9Cq.d.mts} +1 -1
  64. package/dist/{schemas-D7ScxLrf.d.mts → schemas-DTJtS14K.d.mts} +136 -136
  65. package/dist/services/adapter-runtime/index.d.mts +3 -3
  66. package/dist/services/adapter-runtime/namespace.d.mts +1 -1
  67. package/dist/services/adapter-runtime/schemas.d.mts +1 -1
  68. package/dist/services/adapter-subsystem/index.d.mts +2 -2
  69. package/dist/services/adapter-subsystem/namespace.d.mts +1 -1
  70. package/dist/services/agent-runtime/index.d.mts +2 -2
  71. package/dist/services/agent-runtime/namespace.d.mts +1 -1
  72. package/dist/services/agent-runtime/schemas.d.mts +1 -1
  73. package/dist/services/filesystem/namespace.d.mts +6 -6
  74. package/dist/services/filesystem/schemas.d.mts +3 -3
  75. package/dist/services/harness/index.d.mts +3 -3
  76. package/dist/services/index.d.mts +93 -93
  77. package/dist/services/provider-context/index.d.mts +1 -1
  78. package/dist/services/session/index.d.mts +2 -2
  79. package/dist/services/session/messages/namespace.d.mts +1 -1
  80. package/dist/services/settings/namespace.d.mts +12 -12
  81. package/dist/services/settings/storage/extension-configs/namespace.d.mts +3 -3
  82. package/dist/services/subagent-template/index.d.mts +2 -2
  83. package/dist/services/subagent-template/namespace.d.mts +1 -1
  84. package/dist/services/subagent-template/schemas.d.mts +1 -1
  85. package/dist/{transition-DXmCUq6w.d.mts → transition-DxsrTsn4.d.mts} +1 -1
  86. package/dist/{types-DcxBYlPA.d.mts → types-Czdm5op1.d.mts} +306 -306
  87. package/dist/ui-components/index.d.mts +4 -4
  88. package/dist/{view-builder-k82f5KFd.d.mts → view-builder-D-Wz_l_B.d.mts} +1 -1
  89. package/dist/worker-CLsRbzpk.mjs +1 -0
  90. package/dist/worker-DlRdLf2d.mjs +1 -0
  91. package/dist/workflow-BomH9DBB.mjs +1 -0
  92. package/dist/workflow-engine/execution-attempt-repository.d.mts +2 -2
  93. package/dist/workflow-engine/execution-attempt-repository.mjs +1 -1
  94. package/dist/workflow-engine/index.d.mts +352 -62
  95. package/dist/workflow-engine/index.mjs +1 -1
  96. package/dist/workflow-engine/package.d.mts +1 -1
  97. package/dist/workflow-engine/package.mjs +1 -1
  98. package/dist/workflow-engine/testing/index.d.mts +83 -10
  99. package/dist/workflow-engine/testing/index.mjs +1 -1
  100. package/dist/workflow-engine/testing/sqlite.d.mts +3 -2
  101. package/dist/workflow-engine/testing/sqlite.mjs +107 -39
  102. package/dist/workflow-engine/workflow-orchestrator.mjs +1 -1
  103. package/dist/workflow-worker-DjUfKshi.mjs +1 -0
  104. package/package.json +4 -4
  105. package/dist/attempt-record-codec-BYfYkj4M.mjs +0 -1
  106. package/dist/authority-state-bootstrap-CLYus369.mjs +0 -1
  107. package/dist/await-trigger-Bkg2BQfg.mjs +0 -1
  108. package/dist/capabilities-BUwuA7XX.mjs +0 -1
  109. package/dist/contracts/worker-node/index.d.mts +0 -2
  110. package/dist/contracts/worker-node/index.mjs +0 -1
  111. package/dist/package-B01gmu75.mjs +0 -7
  112. package/dist/worker-node-CjuQb9hl.mjs +0 -1
  113. package/dist/worker-node-Dtf9ilsR.mjs +0 -1
  114. package/dist/workflow-C4mck_NW.mjs +0 -1
  115. package/dist/workflow-worker-aNbdgqml.mjs +0 -1
@@ -1,5 +1,5 @@
1
1
  import { l as ProviderOperationOwnershipRecord, o as ProviderOperationClaimDecision, s as ProviderOperationMutationDecision } from "./provider-operation-DbdyFwNm.mjs";
2
- import { A as RecoverableAttemptRecord, C as ProvisioningClaimDecision, D as RecordProviderOperationUncertaintyInput, E as RecordInfrastructureFailureInput, M as TakeOverProviderOperationInput, O as RecordProvisionerIncarnationLostInput, S as ProvisioningAbsenceDecision, T as RecordAllocationTerminatedInput, a as BeginProvisioningInput, b as PendingAttemptAbandonmentDecision, f as ExecutionAttemptOutcomeDecision, h as ExecutionAttemptRepository, i as AllocationTerminationDecision, j as RenewProviderOperationClaimInput, k as RecordProvisioningAbsentInput, n as AllocationRefEvolution, o as DiscoveredAllocationDecision, p as ExecutionAttemptRecord, r as AllocationRefEvolutionDecision, t as AllocationRecordingDecision, v as HandoffProviderOperationInput, w as RecordAllocationInput, x as ProvisionerIncarnationLossDecision, y as InfrastructureFailureDecision } from "./execution-attempt-repository-BJ2W6wwx.mjs";
2
+ import { B as RecordProvisioningAbsentInput, D as MarkRuntimeReadyInput, E as InfrastructureFailureDecision, F as RecordAllocationInput, G as RuntimeRegistrationDecision, H as RegisterRuntimeInput, I as RecordAllocationTerminatedInput, K as TakeOverProviderOperationInput, L as RecordInfrastructureFailureInput, M as ProvisionerIncarnationLossDecision, N as ProvisioningAbsenceDecision, O as OperationAdmissionDecision, P as ProvisioningClaimDecision, R as RecordProviderOperationUncertaintyInput, T as HandoffProviderOperationInput, U as RenewProviderOperationClaimInput, V as RecoverableAttemptRecord, W as RuntimeReadinessDecision, a as AllocationRefEvolutionDecision, d as DiscoveredAllocationDecision, i as AllocationRefEvolution, j as PendingAttemptAbandonmentDecision, k as OperationCompletionDecision, l as BeginProvisioningInput, n as AdmitOperationInput, o as AllocationTerminationDecision, p as DurableOutcome, r as AllocationRecordingDecision, s as AttemptControlState, u as CompleteOperationInput, v as ExecutionAttemptOutcomeDecision, w as ExecutionOwnerId, x as ExecutionAttemptRepository, y as ExecutionAttemptRecord, z as RecordProvisionerIncarnationLostInput } from "./execution-attempt-repository-CRdrgou3.mjs";
3
3
  import { IMakaioBus } from "@makaio/framework/bus";
4
4
  import * as _$_makaio_contracts0 from "@makaio/framework/contracts";
5
5
  import { IWorkflowRunner, LoopGateHandler, MakaioNodeExtension, StationHandler, StepRunnerBusAuth, StepRunnerPlatformDefaults, WorkerMaterializationSpec, WorkflowDefinition, WorkflowExecution, WorkflowRunContext, WorkflowRunResult } from "@makaio/framework/contracts";
@@ -90,7 +90,7 @@ interface WorkflowMaterializationSpecResolver {
90
90
  * Owns:
91
91
  * - attempt ID generation (`crypto.randomUUID()`);
92
92
  * - current-process waiters so runners can `await` a committed outcome;
93
- * - idempotent workflow-state convergence for both `accepted` and `duplicate`.
93
+ * - idempotent owner-state convergence for both `accepted` and `duplicate`.
94
94
  *
95
95
  * Delegates:
96
96
  * - durable attempt creation, provider-operation ownership, allocation
@@ -111,8 +111,9 @@ interface WorkflowMaterializationSpecResolver {
111
111
  *
112
112
  * This service is stateless across process restarts. In-process waiters
113
113
  * are lost on crash; the host recovery coordinator owns recovery decisions.
114
+ * @typeParam TOutcome - Owner-specific outcome type committed per attempt.
114
115
  */
115
- declare class ExecutionAttemptAuthority {
116
+ declare class ExecutionAttemptAuthority<TOutcome> {
116
117
  private readonly repository;
117
118
  /**
118
119
  * In-process waiters keyed by `executionAttemptId`.
@@ -125,16 +126,16 @@ declare class ExecutionAttemptAuthority {
125
126
  /**
126
127
  * @param repository - Injected durable attempt persistence port.
127
128
  */
128
- constructor(repository: ExecutionAttemptRepository);
129
+ constructor(repository: ExecutionAttemptRepository<TOutcome>);
129
130
  /**
130
131
  * Create a new execution attempt with an Authority-generated ID.
131
132
  *
132
133
  * Persists the attempt through the repository and installs an in-process
133
134
  * waiter for the committed outcome. Must be called before dispatch.
134
- * @param executionId - Workflow execution identifier.
135
+ * @param executionId - Owner identifier the attempt belongs to.
135
136
  * @returns The persisted attempt record.
136
137
  */
137
- createAttempt(executionId: string): Promise<ExecutionAttemptRecord>;
138
+ createAttempt(executionId: ExecutionOwnerId): Promise<ExecutionAttemptRecord>;
138
139
  /**
139
140
  * Claim durable ownership of provider provisioning for an active attempt.
140
141
  *
@@ -168,7 +169,7 @@ declare class ExecutionAttemptAuthority {
168
169
  *
169
170
  * The attempt keeps its durable state and stays remediable, so the local
170
171
  * waiter is left untouched: handoff transfers control, it does not answer
171
- * the workflow.
172
+ * the owner.
172
173
  * @param input - Claim being released and optional bounded release evidence.
173
174
  * @returns The durable mutation decision.
174
175
  */
@@ -218,15 +219,91 @@ declare class ExecutionAttemptAuthority {
218
219
  * @returns The durable termination decision.
219
220
  */
220
221
  recordAllocationTerminated(input: RecordAllocationTerminatedInput): Promise<AllocationTerminationDecision>;
222
+ /**
223
+ * Register a runtime incarnation as an attempt's endpoint.
224
+ *
225
+ * Delegates directly to the repository, which allocates the generation. No
226
+ * waiter changes: registering an endpoint says nothing about the attempt's
227
+ * canonical answer, and a refusal is a statement about the runtime rather
228
+ * than about the outcome anybody is waiting for.
229
+ * @param input - Attempt identity, owning execution, and the runtime incarnation.
230
+ * @returns The durable registration decision.
231
+ */
232
+ registerRuntime(input: RegisterRuntimeInput): Promise<RuntimeRegistrationDecision>;
233
+ /**
234
+ * Admit one operation through an attempt's start gate.
235
+ *
236
+ * Delegates directly to the repository, which mints the operation identifier
237
+ * and enforces the at-most-one guard.
238
+ * @param input - Attempt identity, owning execution, kind, idempotency key, and fence.
239
+ * @returns The durable admission decision.
240
+ */
241
+ admitOperation(input: AdmitOperationInput): Promise<OperationAdmissionDecision>;
242
+ /**
243
+ * Release the attempt's active operation.
244
+ *
245
+ * Delegates directly to the repository. A completed operation is not a
246
+ * canonical answer, so the waiter stays pending: what settles an attempt is
247
+ * a committed outcome or a terminal transition, never a freed slot.
248
+ * @param input - Attempt identity, the operation being completed, and its fence.
249
+ * @returns The durable completion decision.
250
+ */
251
+ completeOperation(input: CompleteOperationInput): Promise<OperationCompletionDecision>;
252
+ /**
253
+ * Record that a registered runtime proved itself ready.
254
+ *
255
+ * Delegates directly to the repository.
256
+ * @param input - Attempt identity, the generation the proof belongs to, and when it was observed.
257
+ * @returns The durable readiness decision.
258
+ */
259
+ markRuntimeReady(input: MarkRuntimeReadyInput): Promise<RuntimeReadinessDecision>;
260
+ /**
261
+ * Read an attempt's runtime and operation control state.
262
+ *
263
+ * Delegates directly to the repository. Unfenced and regardless of status,
264
+ * because a process recovering its view of an attempt needs exactly the
265
+ * superseded and settled ones too.
266
+ * @param executionAttemptId - Attempt whose control state to read.
267
+ * @returns The control state, or `null` when no such attempt exists.
268
+ */
269
+ getAttemptControlState(executionAttemptId: string): Promise<AttemptControlState | null>;
221
270
  /**
222
271
  * Retrieve the active attempt for a given execution.
223
272
  *
224
273
  * Delegates directly to the repository.
225
- * @param executionId - Workflow execution identifier.
274
+ * @param executionId - Owner identifier the attempt belongs to.
226
275
  * @param executionAttemptId - Attempt identifier to look up.
227
276
  * @returns The attempt record if active, or `null`.
228
277
  */
229
- getActiveAttempt(executionId: string, executionAttemptId: string): Promise<ExecutionAttemptRecord | null>;
278
+ getActiveAttempt(executionId: ExecutionOwnerId, executionAttemptId: string): Promise<ExecutionAttemptRecord | null>;
279
+ /**
280
+ * Render a submission as the durable fact a commit of it would write.
281
+ *
282
+ * Delegates to the repository, which owns the codec and therefore the
283
+ * durable form. An owner boundary calls this once, before its own
284
+ * validation, so it inspects the value the attempt will actually hold
285
+ * rather than the copy the submitter offered — and then hands the same
286
+ * rendering to {@link commitOutcome}, which is what makes the committed
287
+ * outcome necessarily the validated one.
288
+ * @param outcome - Outcome a caller is about to submit.
289
+ * @returns The text a commit would persist and the outcome that text yields.
290
+ * @throws When the codec rejects the outcome or its own durable text.
291
+ */
292
+ canonicalizeOutcome(outcome: TOutcome): DurableOutcome<TOutcome>;
293
+ /**
294
+ * Read a committed durable text back as the outcome it holds.
295
+ *
296
+ * Delegates to the repository, which owns the codec and therefore the
297
+ * durable form. An owner boundary uses it to obtain a copy of the committed
298
+ * outcome that no earlier step of its own can have touched: the value it
299
+ * handed to its validation and to convergence has been in other hands since,
300
+ * and a mutable outcome one of them changed must not be what a waiter
301
+ * observes. The text it decodes is the one the attempt stored.
302
+ * @param text - Durable text an attempt committed.
303
+ * @returns The outcome that text holds, held by nobody else.
304
+ * @throws When the text is not JSON, or not JSON the codec accepts.
305
+ */
306
+ decodeOutcome(text: string): TOutcome;
230
307
  /**
231
308
  * Commit a terminal outcome for an attempt.
232
309
  *
@@ -234,32 +311,32 @@ declare class ExecutionAttemptAuthority {
234
311
  * `fenced` decisions, the in-process waiter is rejected immediately because
235
312
  * no convergence step follows. For `accepted` and `duplicate` decisions, the
236
313
  * waiter is NOT settled here — the caller must invoke {@link settleOutcome}
237
- * after workflow-state convergence succeeds.
314
+ * after owner-state convergence succeeds.
238
315
  * @param executionAttemptId - The attempt submitting the outcome.
239
- * @param executionId - Workflow execution identifier.
240
- * @param result - Terminal workflow result to commit.
316
+ * @param executionId - Owner identifier the attempt belongs to.
317
+ * @param result - The rendering to commit, from {@link canonicalizeOutcome}.
241
318
  * @returns The durable decision with the canonical outcome when applicable.
242
319
  */
243
- commitOutcome(executionAttemptId: string, executionId: string, result: WorkflowRunResult): Promise<ExecutionAttemptOutcomeDecision>;
320
+ commitOutcome(executionAttemptId: string, executionId: ExecutionOwnerId, result: DurableOutcome<TOutcome>): Promise<ExecutionAttemptOutcomeDecision<TOutcome>>;
244
321
  /**
245
322
  * Obtain the in-process promise for a committed outcome.
246
323
  *
247
324
  * Returns `undefined` when no waiter exists for the given attempt
248
325
  * (e.g. after a process restart or for attempts created by other hosts).
249
326
  * @param executionAttemptId - The attempt to wait for.
250
- * @returns Promise that resolves with the canonical workflow result, or `undefined`.
327
+ * @returns Promise that resolves with the canonical outcome, or `undefined`.
251
328
  */
252
- waitForOutcome(executionAttemptId: string): Promise<WorkflowRunResult> | undefined;
329
+ waitForOutcome(executionAttemptId: string): Promise<TOutcome> | undefined;
253
330
  /**
254
- * Settle the in-process waiter after workflow-state convergence succeeds.
331
+ * Settle the in-process waiter after owner-state convergence succeeds.
255
332
  *
256
- * Called by the outcome-submission handler only after the durable workflow
333
+ * Called by the outcome-submission handler only after the durable owner
257
334
  * transition has completed. This ensures runners observe the committed
258
- * outcome only when canonical workflow state is consistent.
335
+ * outcome only when canonical owner state is consistent.
259
336
  * @param executionAttemptId - The attempt whose waiter to settle.
260
337
  * @param decision - The durable outcome decision (must be accepted or duplicate).
261
338
  */
262
- settleOutcome(executionAttemptId: string, decision: ExecutionAttemptOutcomeDecision): void;
339
+ settleOutcome(executionAttemptId: string, decision: ExecutionAttemptOutcomeDecision<TOutcome>): void;
263
340
  /**
264
341
  * Remove an in-process waiter without settling it.
265
342
  *
@@ -332,10 +409,10 @@ declare class ExecutionAttemptAuthority {
332
409
  *
333
410
  * Delegates to the repository's `getRecoverableAttempts` operation.
334
411
  * Throws when the repository does not support recovery.
335
- * @param executionId - Workflow execution identifier.
412
+ * @param executionId - Owner identifier the attempts belong to.
336
413
  * @returns Allocated, non-settled attempts eligible for recovery, oldest first.
337
414
  */
338
- getRecoverableAttempts(executionId: string): Promise<readonly RecoverableAttemptRecord[]>;
415
+ getRecoverableAttempts(executionId: ExecutionOwnerId): Promise<readonly RecoverableAttemptRecord[]>;
339
416
  /**
340
417
  * Record a confirmed infrastructure failure for an allocated attempt.
341
418
  *
@@ -352,10 +429,10 @@ declare class ExecutionAttemptAuthority {
352
429
  * The repository refuses to use this transition for allocated attempts so a
353
430
  * dispatcher cannot silently strand live infrastructure.
354
431
  * @param executionAttemptId - Attempt whose pre-allocation dispatch ended.
355
- * @param executionId - Workflow execution identifier.
432
+ * @param executionId - Owner identifier the attempt belongs to.
356
433
  * @returns The durable abandonment decision.
357
434
  */
358
- abandonPendingAttempt(executionAttemptId: string, executionId: string): Promise<PendingAttemptAbandonmentDecision>;
435
+ abandonPendingAttempt(executionAttemptId: string, executionId: ExecutionOwnerId): Promise<PendingAttemptAbandonmentDecision>;
359
436
  /**
360
437
  * Obtain the repository's recovery operations, or refuse the call.
361
438
  * @param operation - The recovery operation being attempted.
@@ -419,9 +496,9 @@ declare class WorkflowExecutor extends BaseService {
419
496
  * @param bus - The message bus for communication
420
497
  * @param config - Optional partial configuration (merged with defaults)
421
498
  * @param workflowRunner - Optional workflow-level runner for isolated execution
422
- * @param executionAttemptAuthority - Optional Authority for WorkerNode dispatch runners
499
+ * @param executionAttemptAuthority - Optional Authority for Worker dispatch runners
423
500
  */
424
- constructor(bus: IMakaioBus, config?: Partial<ExecutorConfig>, workflowRunner?: IWorkflowRunner, executionAttemptAuthority?: ExecutionAttemptAuthority);
501
+ constructor(bus: IMakaioBus, config?: Partial<ExecutorConfig>, workflowRunner?: IWorkflowRunner, executionAttemptAuthority?: ExecutionAttemptAuthority<WorkflowRunResult>);
425
502
  /**
426
503
  * Register a host resolver used to freeze workspace materialization before a
427
504
  * path-backed execution is persisted.
@@ -826,14 +903,14 @@ interface WorkflowEngineServiceOptions {
826
903
  /**
827
904
  * Injected execution attempt persistence port.
828
905
  *
829
- * Required when the workflow runner uses WorkerNode dispatch mode. The
906
+ * Required when the workflow runner uses Worker dispatch mode. The
830
907
  * consuming host application provides the concrete implementation that owns
831
908
  * durable attempt records and accept/duplicate/conflict/fence decisions.
832
909
  *
833
910
  * When omitted, the workflow engine operates without attempt tracking
834
911
  * (framework-only, in-process, and Piscina modes).
835
912
  */
836
- executionAttemptRepository?: ExecutionAttemptRepository;
913
+ executionAttemptRepository?: ExecutionAttemptRepository<WorkflowRunResult>;
837
914
  /**
838
915
  * Pre-built execution attempt Authority.
839
916
  *
@@ -845,7 +922,7 @@ interface WorkflowEngineServiceOptions {
845
922
  * construction. When both are provided, the pre-built Authority is used
846
923
  * and the repository is ignored.
847
924
  */
848
- executionAttemptAuthority?: ExecutionAttemptAuthority;
925
+ executionAttemptAuthority?: ExecutionAttemptAuthority<WorkflowRunResult>;
849
926
  /** Host-owned resolvers that create portable specs for path-backed starts. */
850
927
  workflowMaterializationSpecResolvers?: readonly WorkflowMaterializationSpecResolver[];
851
928
  /**
@@ -887,11 +964,11 @@ declare class WorkflowEngineService extends BaseService {
887
964
  * Execution attempt Authority owned by this package service.
888
965
  *
889
966
  * Present only when an {@link ExecutionAttemptRepository} was injected at
890
- * construction time (WorkerNode dispatch mode). Returns `undefined` for
967
+ * construction time (Worker dispatch mode). Returns `undefined` for
891
968
  * framework-only, in-process, and Piscina modes.
892
969
  * @returns Authority instance, or `undefined` when no repository is injected.
893
970
  */
894
- get executionAttemptAuthority(): ExecutionAttemptAuthority | undefined;
971
+ get executionAttemptAuthority(): ExecutionAttemptAuthority<WorkflowRunResult> | undefined;
895
972
  /**
896
973
  * Register a named workflow success finalizer with the owned executor.
897
974
  *
@@ -0,0 +1,7 @@
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-eitx6Ukn.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,ExecutionAttemptSchemas as Ke,ExecutionAttemptSubjects as x,ExecutionsByArtifactRefsQuerySchema as qe,JsonPatchOperationSchema as Je,JsonValueSchema as Ye,SessionSubjects as Xe,WORKFLOW_CANCELLED_REASON as Ze,WorkLogFrameEntrySchema as Qe,WorkerSubjects as $e,WorkflowAutomationTriggerBindingSchema as et,WorkflowError as S,WorkflowErrorCode as tt,WorkflowNamespace as nt,WorkflowRunContextSchema as rt,WorkflowRunResultSchema as it,WorkflowStepTypeSchema as at,WorkflowSubjects as C,createWorkflowCancelSubject as ot,createWorkflowDelegateResultFinalizerNamespace as st,createWorkflowFinalizerNamespace as ct,dep as lt,extensionToken as ut,serializeArtifactRef as dt,walkWorkflowDefinition as ft}from"@makaio/framework/contracts";import{BaseService as pt}from"@makaio/framework/service-base";import{defineDialectSchema as mt,executeTransaction as w,getDatabaseDialect as ht,registerDrizzleHandlers as gt,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 _t,gte as vt,isNotNull as yt,isNull as M,lt as bt,lte as xt,notInArray as St,or as Ct,sql as N,sum as P}from"drizzle-orm";import{SessionToken as wt}from"@makaio/framework/services";import{AutomationTriggerBindingRuntimeToken as Tt}from"@makaio/framework/services/automation-trigger";const Et=ne.postgres,Dt=se.postgres,Ot=l.postgres,kt=d.postgres,At=ce.postgres,jt=ie.postgres,Mt=u.postgres,Nt=be.postgres,Pt=ge.postgres,Ft=re.postgres,It=Te.postgres,Lt=n.postgres,Rt=c.postgres,zt=De.postgres,F=mt({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:Et,workflowExecutions:Dt,workflowExecutionFrames:Ot,workflowGateInstances:kt,workflowStepSpans:At,workflowExecutionLinks:jt,workflowRunContexts:Mt,worklogSummaries:Nt,worklogFrameEntries:Pt,worklogArtifactWrites:Ft,worklogGateEvents:It,workflowExecutionState:Lt,workflowExecutionStateEvents:Rt,workflowFinalizations:zt});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 Bt(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 Vt(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 Ht(e,t){let{workflowDefinitions:n}=T(t,F),r=_t(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=Vt(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?Bt(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 Ut(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 Wt(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 Gt(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=Wt(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]?Ut(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(Ut)})});return()=>{r(),i(),a()}}function Kt(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:Kt(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 qt(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 Jt(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}=qt(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`),yt(r.timeoutMs)));e.setResult({gates:i.map(e=>z(e.gate))})});return()=>{i(),a(),o(),s(),c()}}function Yt(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 Xt(e){return{sourceExecutionId:e.sourceExecutionId,targetExecutionId:e.targetExecutionId,linkType:e.linkType,metadata:e.metadata??void 0}}function Zt(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(Yt)})}),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(Xt)})});return()=>{i(),a(),o(),s()}}function V(e,t){return t===null?ht(e)===`postgres`?N`'null'::jsonb`:N`'null'`:t}function Qt(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 $t(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 en(e){return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,source:$t(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 tn(e){let t=Qt(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 nn(e,t,n){let r=tn(t);await e.insert(n).values(r).onConflictDoUpdate({target:n.executionId,set:r})}function rn(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 nn(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]?en(i[0]):null;e.setResult({runContext:a})});return()=>{a(),o()}}async function an(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 on(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 sn(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 cn(e,t){let n=e.on(p.initializeState,async e=>{let{executionId:n,initialValue:r}=e.payload;await an(t,n,r),e.setResult({})}),r=e.on(p.getState,async e=>{let{executionId:n}=e.payload,r=await on(t,n);e.setResult({state:r})}),i=e.on(p.patchState,async e=>{let{executionId:n,expectedSequence:r,nextValue:i}=e.payload,a=await sn(t,{executionId:n,expectedSequence:r,nextValue:i});e.setResult(a)});return()=>{n(),r(),i()}}function ln(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 un(e,t){let{worklogSummaries:n}=T(e,F);await e.insert(n).values(t).onConflictDoNothing()}async function dn(e,t){let{worklogSummaries:n}=T(e,F);await e.insert(n).values(t).onConflictDoUpdate({target:n.executionId,set:fn(t),setWhere:St(n.status,[`completed`,`failed`,`cancelled`])})}function fn(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]?ln(r[0]):null}async function pn(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(ln),total:u[0]?.count??0}}async function mn(e,t){let{worklogFrameEntries:n}=T(e,F);await e.insert(n).values(t).onConflictDoNothing()}async function hn(e,t){let{worklogFrameEntries:n}=T(e,F);await e.insert(n).values(t).onConflictDoUpdate({target:n.frameId,set:t,setWhere:St(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 gn(e,t){let n=await U(e,t);return n===null?null:Qe.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 _n(e,t){let{worklogArtifactWrites:n}=T(e,F);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}function vn(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 yn(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 bn(e,t,n){let[r]=await e.update(t).set({totalInputTokens:t.totalInputTokens}).where(j(t.executionId,n)).returning();return r}async function xn(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 Sn(e){return e.hasMeasurements}async function Cn(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 wn(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 Tn(e,t){let{worklogSummaries:n,worklogFrameEntries:r}=T(e,F);if(ht(e)===`sqlite`){await wn(e,n,r,t);return}await w(e,async e=>{if(await bn(e,n,t)===void 0)return;let i=await xn(e,r,t);Sn(i)&&await Cn(e,n,t,i)})}async function En(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?[]:[vt(n.startedAt,i)],...a===void 0?[]:[xt(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 Dn(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 On=new Set([`completed`,`failed`,`cancelled`]);function kn(e){return On.has(e)}async function An(e,t){return await un(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 jn(e,t){let n=t.completedAt??Date.now(),r=await H(e,t.executionId);return r!==null&&kn(r.status)?!1:(await dn(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 Mn(e,t,n,r,i,a){let o=await H(e,t);if(o!==null&&kn(o.status))return!1;let s=o?.startedAt??a;return await dn(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 Nn(e,t){return[e.on(h.execution.started,async n=>{let{executionId:r}=n.payload;await K(`execution.started[${r}]`,async()=>{await E(t,()=>An(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,()=>jn(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,()=>Mn(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,()=>Mn(t,r,`cancelled`,null,null,i))&&await q(e,r)})})]}const Pn=new Set([`completed`,`failed`,`skipped`,`cancelled`]);function Fn(e){return Pn.has(e)}function In(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 Ln(e,t,n,r,i,a,o){let s=o??Date.now(),c=await U(t,r);c!==null&&Fn(c.status)||(await hn(t,{frameId:r,executionId:n,...In(c,i,a===void 0?null:s-a),status:`completed`,completedAt:s,durationMs:a??null,error:null}),await Tn(t,n),await q(e,n))}async function Rn(e,t,n,r,i,a,o,s){let c=s??Date.now(),l=await U(t,r);l!==null&&Fn(l.status)||(await hn(t,{frameId:r,executionId:n,...In(l,i,o===void 0?null:c-o),status:`failed`,completedAt:c,durationMs:o??null,error:a}),await q(e,n))}function zn(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 mn(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}]`,()=>Ln(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}]`,()=>Rn(e,t,r,i,a,o,s,c))})]}const Bn={user:`rejected`,timeout:`timed-out`,cancelled:`cancelled`};function Vn(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 yn(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=>Hn(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 Dn(e,t,i,a,o);if(n===null)return;let s=Date.now();await _n(t,{id:vn(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 Hn(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 yn(n,s),l=Date.now();await W(n,{id:s,executionId:r,nodeId:a,frameId:i,status:o!==`cancelled`&&e.action===`approve`?`resumed`:Bn[o],prompt:c?.prompt??null,openedAt:c?.openedAt??l,resolvedAt:l,resumeData:c?.resumeData??null}),await q(t,r)})}function Un(e,t){let n=[...Nn(e,t),...zn(e,t),...Vn(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 gn(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 pn(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 En(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 Wn(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 Gn(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 Kn(e,t,n){if(e!==t)throw Error(`settleExternalExecution: execution "${n}" conflicts with an existing terminal settlement fingerprint`)}async function qn(e,t,n,r,i){let a=Gn(r,i);if(n.externalSettlementFingerprint!==null){Kn(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(Y(c,r,i),c.externalSettlementFingerprint===null)throw Error(`settleExternalExecution: failed to adopt terminal settlement fingerprint for execution "${r.executionId}"`);Kn(c.externalSettlementFingerprint,a,r.executionId)}function Jn(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 Y(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 Yn(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 Xn(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 Zn(e,t){return Wn({...e,inputTokens:e.inputTokens??t?.inputTokens??void 0,outputTokens:e.outputTokens??t?.outputTokens??void 0,estimatedCost:e.estimatedCost??t?.estimatedCost??void 0})}function Qn(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 $n(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 er(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 tr(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`);Qn(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):$n(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(Wn(n))}else er(i,n)}})}async function nr(e,t,n,r,i){if(r.frame!==void 0){let n=await Yn(e,t,r);return n!==void 0&&Jn(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=at.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 rr(e,t,n,r,i){let{worklogSummaries:a,worklogFrameEntries:o}=t,s=await bn(e,a,n.id),c=await nr(e,o,n,r,i),l=c===void 0?r:{...r,frame:c.frame};if(c!==void 0){let t=Zn(c.frame,c.existing);await e.insert(o).values(t).onConflictDoUpdate({target:o.frameId,set:t})}let u=await xn(e,o,n.id),d=Sn(u),f={totalInputTokens:u.totalInputTokens,totalOutputTokens:u.totalOutputTokens,totalEstimatedCost:u.totalEstimatedCost},p={...Xn(n,s,l,i),...d?f:{}};await e.insert(a).values(p).onConflictDoUpdate({target:a.executionId,set:fn(p)}),d&&await Cn(e,a,n.id,u)}async function ir(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=Gn(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),Y(r,t,o),await qn(e,n,r,t,o)}}else Y(a,t,o),await qn(e,n,a,t,o);return await rr(e,{worklogSummaries:r,worklogFrameEntries:i},a,t,o),!0})}function ar(e,t,n){let r=e.on(p.setExternalExecutionStart,async r=>{let i=r.payload.execution,a=r.payload.frame;await tr(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 ir(t,n.payload);await q(e,n.payload.executionId),n.setResult({success:r})});return()=>{r(),i()}}function X(e){return{executionId:e.executionId,workflowId:e.workflowId,finalizerId:e.finalizerId,transitionKey:e.transitionKey,claimToken:e.claimToken,intent:e.intent,claimedAt:e.claimedAt}}function or(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 sr(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 cr(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]?or(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 lr(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 ur(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(lr(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 dr(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 fr(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||(sr(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 pr(e,t){let n=new Map;return async r=>{let i=(n.get(r.executionId)??Promise.resolve()).catch(()=>void 0).then(()=>fr(e,t,r));n.set(r.executionId,i);try{await i}finally{n.get(r.executionId)===i&&n.delete(r.executionId)}}}function mr(e,t){let n=pr(e,t),r=e.on(p.claimFinalization,async e=>{e.setResult({claimed:await cr(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(X)})}),a=e.on(p.listUnpublishedFinalizations,async e=>{let{workflowFinalizations:n}=T(t,F),r=await t.select().from(n).where(D(Ct(j(n.state,`acknowledged`),j(n.state,`failed`)),j(n.finalizerId,e.payload.finalizerId),M(n.publishedAt)));e.setResult({claims:r.map(X)})}),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 ur(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(X(c[0]))}),c=e.on(p.failFinalization,async e=>{let{executionId:r,claimToken:i,error:a,settledAt:o}=e.payload,s=await dr(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(X(l[0]))});return()=>{r(),i(),a(),o(),s(),c()}}function hr(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 Z(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 gr(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(...Bt(a,t)),r){let e=Ct(bt(a.startedAt,r.startedAt),D(j(a.startedAt,r.startedAt),bt(a.id,r.id)));e&&o.push(e)}return o}async function _r(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=Z(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 nn(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 vr(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=Z(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 yr(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 br(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 xr(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]?hr(i[0]):null})}),i=e.on(p.setExecution,async e=>{let r=e.payload.execution,i=Z(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 _r(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 vr(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 br(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 yr(t,n,r,i))});return()=>{r(),i(),a(),o(),s(),c(),l()}}function Sr(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=gr(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(hr)})}),i=e.on(p.listExecutionsByArtifactRefs,async e=>{let r=qe.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[dt(e)]=r.map(hr))}e.setResult({executionsByRef:o})});return()=>{r(),i()}}function Cr(e,t){let n=Ht(e,t),r=xr(e,t),i=Sr(e,t),a=Gt(e,t),o=Jt(e,t),s=Zt(e,t),c=rn(e,t),l=cn(e,t),u=Un(e,t),d=ar(e,t,Z),f=mr(e,t);return()=>{n(),r(),i(),a(),o(),s(),c(),l(),u(),d(),f()}}function wr(e){return e.startsWith(b)}function Tr(e){let t={};return e.artifactRef!==void 0&&(t.artifactRef=e.artifactRef),e.triggerPayload!==void 0&&(t.triggerPayload=e.triggerPayload),t}function Er(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 Dr(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 Or(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)}),...kr(e)]}function kr(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(!wr(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`},...Tr(n)},l=Ar(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(!wr(r))throw Error(`completeExternalExecution: execution "${r}" is engine-owned and must be completed through the engine finalizer, not this API`);let a=jr(n),o=await e.request(p.settleExternalExecution,{executionId:r,status:i,...Er(n),...n.completedAt===void 0?{}:{completedAt:n.completedAt},...a===void 0?{}:{frame:a}});t.setResult({success:o.success})})]}function Ar(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 jr(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 Mr(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 Dr(e,n);s!==void 0&&a(s,o,`next`),Je.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 Nr(e,t){let{runContext:n}=await e.bus.request(p.getRunContext,{executionId:t});if(n===null)throw new S(tt.RUN_CONTEXT_NOT_FOUND,`Run context not found for workflow execution '${t}'.`);return n}function Pr(e,t){return t===void 0?{mode:e}:{mode:e,reason:t}}async function Fr(e,t){let n=await Nr(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:Pr(t.mode,t.reason)}]};return t.mode===`snapshot`?await zr(e,n,c):Lr(n)?await Br(e,n,c):await _e(e,n.workflowId,c)}function Ir(e,t){return Lr(e)?t.id:e.workflowId}function Lr(e){return e.source.kind!==`definition`&&e.workflowId===e.executionId}function Rr(e){let t=e.definitionSnapshot;if(t===void 0)throw new S(tt.SNAPSHOT_UNAVAILABLE,`Workflow execution '${e.executionId}' does not have a definition snapshot.`);return t}async function zr(e,t,n){let r=Rr(t);return Ce(e,Ir(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 Br(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=Rr(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 Vr=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 Hr(e){if(e!==void 0)return Ur(e)?e:{}}function Ur(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Wr(e){if(e!==void 0)return Ye.parse(e)}function Gr(e,t){return rt.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 Kr(e){return e?.status===`paused`}function qr(e){return e?.status===`waiting`}async function Jr(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 Yr(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 Xr(e){return{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,timeoutMs:e.timeoutMs,openedAt:e.createdAt}}async function Zr(e,t){if(t.frameId!==void 0){let{gate:n}=await e.request(p.getGateInstance,t);return qr(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}async function Qr(e,t){let n=e.authority.canonicalizeOutcome(t.outcome);await e.validation?.validate(t.executionId,n.outcome);let r=await e.authority.commitOutcome(t.executionAttemptId,t.executionId,n);return(r.kind===`accepted`||r.kind===`duplicate`)&&(await e.convergence.converge({executionId:t.executionId,executionAttemptId:t.executionAttemptId,outcome:r.outcome,decision:r.kind}),e.authority.settleOutcome(t.executionAttemptId,{kind:r.kind,outcome:e.authority.decodeOutcome(r.text),text:r.text})),r.kind}function $r(e,n){return e.origin.local?{executionAttemptId:n.executionAttemptId,executionId:n.executionId}:t(e)}async function ei(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 ti(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})}var ni=class{bus;acceptTerminalResult;constructor(e,t){this.bus=e,this.acceptTerminalResult=t}async converge(e){if(e.outcome.status===`paused`){await ti(this.bus,e.executionId,e.outcome);return}await this.acceptTerminalResult(e.executionId,e.outcome)}},ri=class{bus;constructor(e){this.bus=e}validate(e,t){return ei(this.bus,e,t)}};function ii(e,t){let n=new ni(e,t.acceptTerminalResult),r=new ri(e);return e.on($e.control.outcome.submit,async e=>{let i=$r(e,e.payload);if(i===null)throw Error(`Outcome submission requires an authenticated workflow-execution-attempt peer`);let{result:a}=e.payload;if(!e.origin.local){if(e.payload.executionId!==i.executionId)throw Error(`Outcome payload executionId '${e.payload.executionId}' does not match authenticated peer claim '${i.executionId}'`);if(e.payload.executionAttemptId!==i.executionAttemptId)throw Error(`Outcome payload executionAttemptId '${e.payload.executionAttemptId}' does not match authenticated peer identity '${i.executionAttemptId}'`)}if(a.executionId!==i.executionId)throw Error(`Nested result.executionId '${a.executionId}' does not match trusted identity '${i.executionId}'`);let o=it.parse(a),s=await Qr({authority:t.authority,convergence:n,validation:r},{executionId:i.executionId,executionAttemptId:i.executionAttemptId,outcome:o});e.setResult({decision:ai(s)})})}function ai(e){return e}const oi=1e4;function si(e,n){let r=n.probeDeliveryTimeoutMs??1e4;return e.on(x.runtime.register,async e=>{let i=t(e);if(i===null)throw Error(`Runtime registration requires an authenticated workflow-execution-attempt peer`);let{executionAttemptId:a,runtimeIncarnationId:o}=Ke[`runtime.register`].request.parse(e.payload);if(a!==i.executionAttemptId)throw Error(`Registration payload executionAttemptId '${a}' does not match authenticated peer identity '${i.executionAttemptId}'`);let s=await n.authority.registerRuntime({executionAttemptId:a,executionId:i.executionId,runtimeIncarnationId:o});if(s.kind===`duplicate`&&s.runtimeReadyAt!==null){await ci(n,a,s.runtimeGeneration),e.setResult({decision:`duplicate`,runtimeGeneration:s.runtimeGeneration});return}if(s.kind!==`registered`&&s.kind!==`duplicate`){e.setResult(di(s.kind));return}let c=s.runtimeGeneration;if(await li(n,r,{executionAttemptId:a,executionId:i.executionId,runtimeIncarnationId:o,runtimeGeneration:c})===null){e.setResult(di(`probe-failed`));return}await ci(n,a,c),e.setResult({decision:`ready`,runtimeGeneration:c})})}async function ci(e,t,n){let r=await e.authority.getAttemptControlState(t);r===null||r.runtimeGeneration!==n||r.runtimeReadyAt===null||await e.bus.emit(x.runtime.ready,{executionAttemptId:t,runtimeGeneration:n,acceptedAt:r.runtimeReadyAt})}async function li(e,t,n){let{executionAttemptId:r,executionId:i,runtimeIncarnationId:a,runtimeGeneration:o}=n,s=await e.authority.admitOperation({executionAttemptId:r,executionId:i,operationKind:`runtime-probe`,admissionKey:`probe:${a}`,runtimeGeneration:o});if(s.kind!==`admitted`&&s.kind!==`duplicate`)return null;let c=s.operationId,l=()=>ui(e,{executionAttemptId:r,operationId:c,runtimeGeneration:o}),u;try{u=(await e.bus.request(x.operation.deliver,{executionAttemptId:r,runtimeIncarnationId:a,operationId:c,operationKind:`runtime-probe`,runtimeGeneration:o},{timeout:t})).receipt}catch{return await l(),null}if(u!==`completed`&&u!==`duplicate`)return await l(),null;let d=await e.authority.completeOperation({executionAttemptId:r,operationId:c,runtimeGeneration:o});if(d.kind!==`completed`&&d.kind!==`duplicate`)return null;let f=await e.authority.markRuntimeReady({executionAttemptId:r,executionId:i,runtimeGeneration:o,readyAt:new Date().toISOString()});return f.kind!==`ready`&&f.kind!==`duplicate`?null:{kind:f.kind,acceptedAt:f.acceptedAt}}async function ui(e,t){try{await e.authority.completeOperation(t)}catch{}}function di(e){return{decision:`refused`,runtimeGeneration:0,refusalReason:e}}function fi(e,n){return e.on(x.operation.admit,async e=>{let r=t(e);if(r===null)throw Error(`Operation admission requires an authenticated workflow-execution-attempt peer`);let{executionAttemptId:i,operationKind:a,admissionKey:o,runtimeGeneration:s}=Ke[`operation.admit`].request.parse(e.payload);if(i!==r.executionAttemptId)throw Error(`Admission payload executionAttemptId '${i}' does not match authenticated peer identity '${r.executionAttemptId}'`);if(a===`runtime-probe`)throw Error(`Operation admission does not accept 'runtime-probe' (executionAttemptId='${i}'): the bounded probe is admitted only by runtime registration`);let c=await n.authority.admitOperation({executionAttemptId:i,executionId:r.executionId,operationKind:a,admissionKey:o,runtimeGeneration:s});if(c.kind===`admitted`||c.kind===`duplicate`){await n.bus.emit(x.operation.admitted,{executionAttemptId:i,operationId:c.operationId,operationKind:a,runtimeGeneration:c.runtimeGeneration,admittedAt:c.admittedAt}),e.setResult({decision:c.kind,operationId:c.operationId});return}e.setResult({decision:`refused`,refusalReason:c.kind})})}function pi(e){return e.on(h.finalizeDelegateResult,async t=>{let n=t.payload;mi(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`);hi(i.definitionSnapshot,n.nodeId,n.nodeType,n.finalizerId);let{subjects:a}=st(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 mi(e,t){if(!g(e,t))throw Error(`delegate result finalization requires its authenticated workflow-execution-attempt peer`)}function hi(e,t,n,r){let i=!1;if(ft(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 gi=class extends pt{static storage={drizzle:Cr};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 Vr(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}=ct(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(pi(this.bus)),this.executionAttemptAuthority!==void 0&&(this.addCleanup(ii(this.bus,{bus:this.bus,authority:this.executionAttemptAuthority,acceptTerminalResult:(e,t)=>this.acceptAuthorityRunnerResult(e,t)})),this.addCleanup(si(this.bus,{bus:this.bus,authority:this.executionAttemptAuthority})),this.addCleanup(fi(this.bus,{bus:this.bus,authority:this.executionAttemptAuthority})));for(let e of Or(this.bus))this.addCleanup(e);for(let e of Mr(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(Xe.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=>Gr(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:Wr(n),config:Hr(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 Fr(this.buildStartDeps(),{executionId:t,mode:n,input:Wr(r),config:Hr(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(ot(`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??Ze);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(Xr(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,Ze);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,Ze):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(!Kr(o))return!1;let s=await Zr(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 Yr(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 Jr(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 Yr(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 Q=`[WorkflowTriggerReconciler]`;function _i(e){return e.map(vi)}function vi(e){let t=et.parse(e);return{binding:t,matches:Be(t),subscription:void 0}}function yi(e,t,n){let r=e.triggers??[];try{return n===void 0?_i(r):r.map(e=>n.has(e.kind)?vi(e):void 0)}catch(i){if(t){console.error(`${Q} 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 vi(t)}catch(t){console.error(`${Q} leaving invalid trigger ${r} of workflow "${e.id}" inactive`,t);return}})}}function bi(e,t){return e.scope.type!==`global`||t.kind!==We}async function xi(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&&bi(e,s.binding)||(r.delete(i),await $(a.subscription))}}async function $(e){if(e!==void 0)try{await e.detach()}catch(t){console.error(`${Q} detach failed for '${e.bindingKey}':`,t)}}var Si=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(`${Q} ${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=yi(e,(this.consumers.get(e.id)?.size??0)>0,n);if(r===void 0)return;let i=this.consumers.get(e.id);if(await xi(e,r,n,i),i?.size===0&&this.consumers.delete(e.id),!r.some(t=>t!==void 0&&bi(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(`${Q} 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&&bi(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(`${Q} keeping last-good trigger ${n} of workflow "${t}": binding '${r.binding.kind}' could not be activated`,e);return}console.warn(`${Q} 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(`${Q} 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(`${Q} 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)})}},Ci=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 registerRuntime(e){return this.repository.registerRuntime(e)}async admitOperation(e){return this.repository.admitOperation(e)}async completeOperation(e){return this.repository.completeOperation(e)}async markRuntimeReady(e){return this.repository.markRuntimeReady(e)}async getAttemptControlState(e){return this.repository.getAttemptControlState(e)}async getActiveAttempt(e,t){return this.repository.getActiveAttempt(e,t)}canonicalizeOutcome(e){return this.repository.canonicalizeOutcome(e)}decodeOutcome(e){return this.repository.decodeOutcome(e)}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)}}},wi=class extends pt{workflowExecutor;triggerReconcilerInstance;attemptAuthority;workspaceRootResolvers=new Set;constructor(e,t){super(e),this.attemptAuthority=t?.executionAttemptAuthority??(t?.executionAttemptRepository?new Ci(t.executionAttemptRepository):void 0),this.workflowExecutor=new gi(e,t?.executorConfig,t?.workflowRunner,this.attemptAuthority);for(let e of t?.workflowMaterializationSpecResolvers??[])this.workflowExecutor.registerWorkflowMaterializationSpecResolver(e);let n=t?.automationTriggerBindingRuntime;this.triggerReconcilerInstance=new Si(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 Ti=ut(`makaio.workflow-engine`);function Ei(e){return{name:Ti.name,displayName:`Workflow Engine`,version:`0.1.0`,dependencies:[lt(wt.name),lt(Tt.name,void 0,!0)],critical:!0,namespaces:[nt,xe],storage:{registerHandlers:gt(Cr)},create:t=>new wi(t.bus,{...e,automationTriggerBindingRuntime:()=>t.getService(Tt)})}}const Di=Ei();export{Ci as a,fi as c,Qr as d,Cr as f,sn as h,wi as i,oi as l,an as m,Ei as n,Si as o,on as p,Di as r,gi as s,Ti as t,si as u};
package/dist/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "@makaio/framework",
3
- "version": "1.0.0-dev-1788258714339",
3
+ "version": "1.0.0-dev-1788721567504",
4
4
  "type": "module"
5
5
  }
@@ -4,7 +4,7 @@ import { a as CODE_EXECUTION_DEFAULT_MAX_PROGRAM_FILES, c as CODE_EXECUTION_DEFA
4
4
  import { t as PiscinaCodeExecutionProvider } from "../index-Dg11JxKZ.mjs";
5
5
  import { a as FilesystemDescriptorDiscovery, n as ExplicitDescriptorDiscovery, o as FilesystemDescriptorDiscoveryOptions, r as ExtensionDiscovery, s as MergedDescriptorDiscovery, t as DiscoveredExtension } from "../extension-discovery-Dhu3WplO.mjs";
6
6
  import { a as isMakaioExtensionLike, c as resolveConventionEntrypoint, i as isCliContributionLike, n as LoadExtensionsOptions, o as isWithinDirectory, r as entrypointStem, s as loadExtensions, t as DescriptorSourcePackageGroup } from "../load-extensions-BQoXaHhR.mjs";
7
- import { At as createHonoRouteGraph, B as ThinWorkflowPiscinaRunnerOptions, Ct as resolveFrameworkSpecifier, Dt as HttpRouteContribution, E as OutcomeDeliveryError, Et as HttpContributionPhase, Ft as activateAdapterRuntimeIdentity, G as MakaioRuntime, H as BootCoordinatorSetupContext, It as prepareAdapterRuntime, J as UpstreamTelemetryBootOptions, K as ServerTransportProvider, L as ThinWorkflowPiscinaRunner, Mt as ActivatedAdapterRuntimeIdentity, Nt as PrepareAdapterRuntimeInput, Ot as HonoRouteGraph, Pt as PreparedAdapterRuntime, R as IWorkflowRunner, S as InProcessWorkflowRunnerOptions, St as NoopFrameworkModuleResolver, Tt as createHttpRouteGraphBuilder, U as BootMakaioRuntimeOptions, V as WorkflowRunResult, W as CoreBootOptions, Y as WorkflowRunnerBootOptions, _ as IsolatedWorkflowRuntimeContext, _t as selectFrameworkCorePackages, a as HeadlessWorkerBootstrapCredentials, b as createIsolatedWorkflowRuntime, bt as FrameworkModuleResolver, c as HeadlessWorkerExecutor, ct as WorkflowWorkerEntryMode, d as HeadlessWorkflowWorkerDeps, dt as DatabaseBootOptions, f as HeadlessWorkflowWorkerResult, ft as InitializeNodeDatabaseOptions, g as IsolatedWorkflowRuntime, gt as normalizeNodeHostCapabilities, h as CreateIsolatedWorkflowRuntimeOptions, ht as HostCapabilityDeclaration, i as HeadlessWorkerBootstrap, jt as ActivateAdapterRuntimeIdentityInput, kt as HonoRouteGraphOptions, l as HeadlessWorkerMaterializer, lt as WorkflowWorkerEntryResolverOptions, m as runHeadlessWorkflowWorker, mt as initializeNodeDatabase, o as HeadlessWorkerBusConnector, pt as InitializeNodeDatabaseResult, q as TransportReadyInfo, s as HeadlessWorkerContributionLoader, u as HeadlessWorkerPostCommitObserver, ut as resolveWorkflowWorkerEntry, v as WorkflowRuntimeAuthorityConnector, vt as ShutdownStep, wt as HttpRouteGraphBuilder, x as InProcessWorkflowRunner, xt as NodeFrameworkModuleResolver, y as WorkflowRuntimeContributionLoader, yt as BridgeBrowserOptions } from "../index-CMekqu_D.mjs";
7
+ import { $ as ThinWorkflowPiscinaRunner, A as runHeadlessWorkflowWorker, At as initializeNodeDatabase, Bt as HttpRouteGraphBuilder, C as HeadlessWorkerContributionLoader, D as HeadlessWorkflowWorkerDeps, Dt as DatabaseBootOptions, E as HeadlessWorkerPostCommitObserver, Et as resolveWorkflowWorkerEntry, F as WorkflowRuntimeContributionLoader, Ft as BridgeBrowserOptions, Gt as HonoRouteGraphOptions, H as OutcomeDeliveryError, Ht as HttpContributionPhase, I as createIsolatedWorkflowRuntime, It as FrameworkModuleResolver, Jt as ActivatedAdapterRuntimeIdentity, Kt as createHonoRouteGraph, L as InProcessWorkflowRunner, Lt as NodeFrameworkModuleResolver, M as IsolatedWorkflowRuntime, Mt as normalizeNodeHostCapabilities, N as IsolatedWorkflowRuntimeContext, Nt as selectFrameworkCorePackages, O as HeadlessWorkflowWorkerResult, Ot as InitializeNodeDatabaseOptions, P as WorkflowRuntimeAuthorityConnector, Pt as ShutdownStep, Qt as prepareAdapterRuntime, R as InProcessWorkflowRunnerOptions, Rt as NoopFrameworkModuleResolver, S as HeadlessWorkerBusConnector, T as HeadlessWorkerMaterializer, Tt as WorkflowWorkerEntryResolverOptions, Ut as HttpRouteContribution, Vt as createHttpRouteGraphBuilder, Wt as HonoRouteGraph, Xt as PreparedAdapterRuntime, Yt as PrepareAdapterRuntimeInput, Zt as activateAdapterRuntimeIdentity, a as OperationAdmissionRefusedError, at as BootMakaioRuntimeOptions, b as HeadlessWorkerBootstrap, c as OperationDeliveryHandler, ct as ServerTransportProvider, d as RegisterWorkerRuntimeOptions, dt as WorkflowRunnerBootOptions, et as IWorkflowRunner, f as RuntimeRegistrationRefusedError, g as registerWorkerRuntime, h as registerAndAdmitWorkflowRun, i as DeliverableOperationKind, it as BootCoordinatorSetupContext, j as CreateIsolatedWorkflowRuntimeOptions, jt as HostCapabilityDeclaration, kt as InitializeNodeDatabaseResult, l as OperationDeliveryHandlers, lt as TransportReadyInfo, m as installOperationDeliveryEndpoint, n as AdmitWorkflowRunOperationOptions, nt as ThinWorkflowPiscinaRunnerOptions, o as OperationDeliveryEndpoint, ot as CoreBootOptions, p as admitWorkflowRunOperation, qt as ActivateAdapterRuntimeIdentityInput, r as AdmittedWorkflowRun, rt as WorkflowRunResult, s as OperationDeliveryEndpointIdentity, st as MakaioRuntime, t as ALLOCATION_VISIBILITY_DEADLINE_MS, u as RegisterAndAdmitWorkflowRunOptions, ut as UpstreamTelemetryBootOptions, w as HeadlessWorkerExecutor, wt as WorkflowWorkerEntryMode, x as HeadlessWorkerBootstrapCredentials, zt as resolveFrameworkSpecifier } from "../index-BJdkVFX9.mjs";
8
8
  import { ConfiguredRuntimeOptions, LoadMakaioConfigOptions, LoadedMakaioConfig, MAKAIO_CONFIG_FILE_ENV, MAKAIO_HOME_ENV, MakaioConfig, ParseMakaioConfigOptions, ParsedMakaioConfig, WorkflowRunnerConfig, buildConfiguredRuntimeOptions, createMakaioConfigDiscovery, defineMakaioConfig, loadMakaioConfig, parseMakaioConfig, resolveMakaioConfigPath, resolveMakaioHome, shouldIncludeExtension } from "./makaio-config.mjs";
9
9
  import { z } from "zod";
10
10
  import { IConfigStorage } from "@makaio/framework/core";
@@ -673,4 +673,4 @@ declare function findWorkspaceRoot(startDir: string): string;
673
673
  */
674
674
  declare function findWorkspaceRootInfo(startDir: string): WorkspaceRootInfo;
675
675
  //#endregion
676
- export { type ActivateAdapterRuntimeIdentityInput, type ActivatedAdapterRuntimeIdentity, type AttachedUpstreamTelemetry, type BootCoordinatorSetupContext, type BootMakaioRuntimeOptions, type BridgeBrowserOptions, type BundledMigrationsProbes, type BusServerTransportOptions, BusServerTransportProvider, CODE_EXECUTION_DEFAULT_IDLE_TIMEOUT_MS, CODE_EXECUTION_DEFAULT_MAX_ARGUMENT_BYTES, CODE_EXECUTION_DEFAULT_MAX_CONCURRENCY, CODE_EXECUTION_DEFAULT_MAX_INVOCATIONS_PER_WORKER, CODE_EXECUTION_DEFAULT_MAX_PROGRAM_FILES, CODE_EXECUTION_DEFAULT_MAX_QUEUED_INVOCATIONS, CODE_EXECUTION_DEFAULT_MAX_RESULT_BYTES, CODE_EXECUTION_DEFAULT_MAX_SOURCE_BYTES, type ConfiguredRuntimeOptions, type CoreBootOptions, type CreateIsolatedWorkflowRuntimeOptions, type CredentialProvider, type DatabaseBootOptions, type DescriptorSourcePackageGroup, type DiscoveredExtension, ExplicitDescriptorDiscovery, type ExtensionDiscovery, FileConfigStorage, FileRegistryCache, FilesystemDescriptorDiscovery, type FilesystemDescriptorDiscoveryOptions, type FrameworkModuleResolver, type HeadlessWorkerBootstrap, type HeadlessWorkerBootstrapCredentials, type HeadlessWorkerBusConnector, type HeadlessWorkerContributionLoader, type HeadlessWorkerExecutor, type HeadlessWorkerMaterializer, type HeadlessWorkerPostCommitObserver, type HeadlessWorkflowWorkerDeps, type HeadlessWorkflowWorkerResult, type HonoRouteGraph, type HonoRouteGraphOptions, type HttpContributionPhase, type HttpRouteContribution, type HttpRouteGraphBuilder, type IWorkflowRunner, InProcessWorkflowRunner, type InProcessWorkflowRunnerOptions, type InitializeNodeDatabaseOptions, type InitializeNodeDatabaseResult, type IsolatedWorkflowRuntime, type IsolatedWorkflowRuntimeContext, type LoadExtensionsOptions, type LoadMakaioConfigOptions, type LoadedMakaioConfig, MAKAIO_CONFIG_FILE_ENV, MAKAIO_HOME_ENV, MAKAIO_UPSTREAM_SECRET_ENV, MAKAIO_UPSTREAM_URL_ENV, type MachineKeyStatus, type MachineKeyValidation, type MakaioConfig, type MakaioRuntime, MergedDescriptorDiscovery, type NodeClientBinaryStrategyDependencyOptions, NodeCredentialProvider, NodeFrameworkModuleResolver, type NodeRuntimeOptions, NoopFrameworkModuleResolver, OutcomeDeliveryError, type ParseMakaioConfigOptions, type ParsedMakaioConfig, type PersistedMachineIdentity, PiscinaCodeExecutionProvider, type PiscinaCodeExecutionProviderOptions, type PrepareAdapterRuntimeInput, type PreparedAdapterRuntime, type ResolveUpstreamTelemetryBootOptionsFromEnvOptions, RuntimeSubjects, type ServerTransportProvider, StoredCredentialProvider, ThinWorkflowPiscinaRunner, type ThinWorkflowPiscinaRunnerOptions, type TransportReadyInfo, type UpstreamTelemetryBootOptions, type UpstreamTelemetryEnv, type UpstreamTelemetryTransportConfig, type WorkflowRunResult, type WorkflowRunnerBootOptions, type WorkflowRunnerConfig, type WorkflowRuntimeAuthorityConnector, type WorkflowRuntimeContributionLoader, type WorkflowWorkerEntryMode, type WorkflowWorkerEntryResolverOptions, type WorkspaceRootInfo, WorkspaceRootNotFoundError, activateAdapterRuntimeIdentity, attachUpstreamTelemetry, bootMakaioRuntime, bootMakaioRuntimeCore, bridgeExtensionBrowserEntries, buildConfiguredRuntimeOptions, buildExtensionBrowserRollupInputName, buildExtensionBrowserRuntimeEntrypoint, buildNodeRuntimeOptions, createHonoRouteGraph, createHttpRouteGraphBuilder, createIsolatedWorkflowRuntime, createMakaioConfigDiscovery, createNodeClientBinaryStrategyDependencies, createUpstreamTelemetryTransport, defineMakaioConfig, entrypointStem, findWorkspaceRoot, findWorkspaceRootInfo, getRuntimeDatabase, initializeNodeDatabase, isCliContributionLike, isMakaioExtensionLike, isMissingOptionalRuntimePackage, isWithinDirectory, loadExtensions, loadMakaioConfig, loadOrCreateMachineIdentity, machineKeysExist, normalizeNodeHostCapabilities, parseMakaioConfig, prepareAdapterRuntime, readFrameworkVersion, registerAdapterNameResolver, registerRuntimeHandlers, resolveBundledMigrationsDir, resolveConventionEntrypoint, resolveFrameworkSpecifier, resolveListeningPort, resolveMakaioConfigPath, resolveMakaioHome, resolveStaticModelRegistryPath, resolveUpstreamTelemetryBootOptionsFromEnv, resolveWorkflowWorkerEntry, runHeadlessWorkflowWorker, runMigrations, runRuntimeHandlerCleanups, selectFrameworkCorePackages, shouldIncludeExtension, tryImport, validateMachineKeys, waitForServerListening };
676
+ export { ALLOCATION_VISIBILITY_DEADLINE_MS, type ActivateAdapterRuntimeIdentityInput, type ActivatedAdapterRuntimeIdentity, type AdmitWorkflowRunOperationOptions, type AdmittedWorkflowRun, type AttachedUpstreamTelemetry, type BootCoordinatorSetupContext, type BootMakaioRuntimeOptions, type BridgeBrowserOptions, type BundledMigrationsProbes, type BusServerTransportOptions, BusServerTransportProvider, CODE_EXECUTION_DEFAULT_IDLE_TIMEOUT_MS, CODE_EXECUTION_DEFAULT_MAX_ARGUMENT_BYTES, CODE_EXECUTION_DEFAULT_MAX_CONCURRENCY, CODE_EXECUTION_DEFAULT_MAX_INVOCATIONS_PER_WORKER, CODE_EXECUTION_DEFAULT_MAX_PROGRAM_FILES, CODE_EXECUTION_DEFAULT_MAX_QUEUED_INVOCATIONS, CODE_EXECUTION_DEFAULT_MAX_RESULT_BYTES, CODE_EXECUTION_DEFAULT_MAX_SOURCE_BYTES, type ConfiguredRuntimeOptions, type CoreBootOptions, type CreateIsolatedWorkflowRuntimeOptions, type CredentialProvider, type DatabaseBootOptions, type DeliverableOperationKind, type DescriptorSourcePackageGroup, type DiscoveredExtension, ExplicitDescriptorDiscovery, type ExtensionDiscovery, FileConfigStorage, FileRegistryCache, FilesystemDescriptorDiscovery, type FilesystemDescriptorDiscoveryOptions, type FrameworkModuleResolver, type HeadlessWorkerBootstrap, type HeadlessWorkerBootstrapCredentials, type HeadlessWorkerBusConnector, type HeadlessWorkerContributionLoader, type HeadlessWorkerExecutor, type HeadlessWorkerMaterializer, type HeadlessWorkerPostCommitObserver, type HeadlessWorkflowWorkerDeps, type HeadlessWorkflowWorkerResult, type HonoRouteGraph, type HonoRouteGraphOptions, type HttpContributionPhase, type HttpRouteContribution, type HttpRouteGraphBuilder, type IWorkflowRunner, InProcessWorkflowRunner, type InProcessWorkflowRunnerOptions, type InitializeNodeDatabaseOptions, type InitializeNodeDatabaseResult, type IsolatedWorkflowRuntime, type IsolatedWorkflowRuntimeContext, type LoadExtensionsOptions, type LoadMakaioConfigOptions, type LoadedMakaioConfig, MAKAIO_CONFIG_FILE_ENV, MAKAIO_HOME_ENV, MAKAIO_UPSTREAM_SECRET_ENV, MAKAIO_UPSTREAM_URL_ENV, type MachineKeyStatus, type MachineKeyValidation, type MakaioConfig, type MakaioRuntime, MergedDescriptorDiscovery, type NodeClientBinaryStrategyDependencyOptions, NodeCredentialProvider, NodeFrameworkModuleResolver, type NodeRuntimeOptions, NoopFrameworkModuleResolver, OperationAdmissionRefusedError, type OperationDeliveryEndpoint, type OperationDeliveryEndpointIdentity, type OperationDeliveryHandler, type OperationDeliveryHandlers, OutcomeDeliveryError, type ParseMakaioConfigOptions, type ParsedMakaioConfig, type PersistedMachineIdentity, PiscinaCodeExecutionProvider, type PiscinaCodeExecutionProviderOptions, type PrepareAdapterRuntimeInput, type PreparedAdapterRuntime, type RegisterAndAdmitWorkflowRunOptions, type RegisterWorkerRuntimeOptions, type ResolveUpstreamTelemetryBootOptionsFromEnvOptions, RuntimeRegistrationRefusedError, RuntimeSubjects, type ServerTransportProvider, StoredCredentialProvider, ThinWorkflowPiscinaRunner, type ThinWorkflowPiscinaRunnerOptions, type TransportReadyInfo, type UpstreamTelemetryBootOptions, type UpstreamTelemetryEnv, type UpstreamTelemetryTransportConfig, type WorkflowRunResult, type WorkflowRunnerBootOptions, type WorkflowRunnerConfig, type WorkflowRuntimeAuthorityConnector, type WorkflowRuntimeContributionLoader, type WorkflowWorkerEntryMode, type WorkflowWorkerEntryResolverOptions, type WorkspaceRootInfo, WorkspaceRootNotFoundError, activateAdapterRuntimeIdentity, admitWorkflowRunOperation, attachUpstreamTelemetry, bootMakaioRuntime, bootMakaioRuntimeCore, bridgeExtensionBrowserEntries, buildConfiguredRuntimeOptions, buildExtensionBrowserRollupInputName, buildExtensionBrowserRuntimeEntrypoint, buildNodeRuntimeOptions, createHonoRouteGraph, createHttpRouteGraphBuilder, createIsolatedWorkflowRuntime, createMakaioConfigDiscovery, createNodeClientBinaryStrategyDependencies, createUpstreamTelemetryTransport, defineMakaioConfig, entrypointStem, findWorkspaceRoot, findWorkspaceRootInfo, getRuntimeDatabase, initializeNodeDatabase, installOperationDeliveryEndpoint, isCliContributionLike, isMakaioExtensionLike, isMissingOptionalRuntimePackage, isWithinDirectory, loadExtensions, loadMakaioConfig, loadOrCreateMachineIdentity, machineKeysExist, normalizeNodeHostCapabilities, parseMakaioConfig, prepareAdapterRuntime, readFrameworkVersion, registerAdapterNameResolver, registerAndAdmitWorkflowRun, registerRuntimeHandlers, registerWorkerRuntime, resolveBundledMigrationsDir, resolveConventionEntrypoint, resolveFrameworkSpecifier, resolveListeningPort, resolveMakaioConfigPath, resolveMakaioHome, resolveStaticModelRegistryPath, resolveUpstreamTelemetryBootOptionsFromEnv, resolveWorkflowWorkerEntry, runHeadlessWorkflowWorker, runMigrations, runRuntimeHandlerCleanups, selectFrameworkCorePackages, shouldIncludeExtension, tryImport, validateMachineKeys, waitForServerListening };