@dudousxd/nestjs-durable-core 0.56.0 → 0.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/queue.ts","../src/admission.ts","../src/ambient-ctx.ts","../src/control-flow-signal.ts","../src/errors.ts","../src/workflow-ref.ts","../src/durable-workflow.ts","../src/duration.ts","../src/backoff.ts","../src/step-logger.ts","../src/protocol.ts","../src/checkpoints.ts","../src/entities.ts","../src/event-accumulators.ts","../src/events.ts","../src/tenant-group.ts","../src/remote-workflow-executor.ts","../src/run-waiting.ts","../src/singleton-gate.ts","../src/transport-pool.ts","../src/completion.ts","../src/step-name-symbol.ts","../src/workflow-ctx.ts","../src/engine.ts","../src/interfaces.ts","../src/codec-state-store.ts","../src/metrics.ts","../src/scheduler.ts","../src/search-attributes.ts","../src/search-attributes-schema.ts","../src/tokens.ts","../src/testing/in-memory-state-store.ts","../src/testing/in-memory-transport.ts"],"sourcesContent":["/**\n * Flow control for dispatched steps. A queue caps how much work `ctx.step(step, input, { queue })`\n * admits at once — a concurrency limit and/or a fixed-window rate limit. When a call can't be\n * admitted it doesn't dispatch: the run re-suspends with a near-future wake time, and the timer\n * poller re-tries admission later — so flow control is durable (survives crashes) without holding\n * the run in memory.\n *\n * Accounting is per engine instance (the DBOS `workerConcurrency` tier): correct for the common\n * single-orchestrator deployment. Global, cross-instance limits would need a durable counter in the\n * store — a deliberate follow-up, not built here.\n *\n * Beyond raw caps, the controller can admit contended slots by PRIORITY and by per-KEY FAIRNESS\n * (round-robin), so a single noisy key/tenant can't monopolize the concurrency budget. This is the\n * DISPATCH/admission layer — it never touches workflow replay (engine positional logic). Default\n * behaviour is unchanged FIFO when neither priority nor fairness is configured/passed.\n *\n * Design (vs Temporal/Inngest/DBOS): Temporal task queues are FIFO with separate priority levels;\n * Inngest concurrency keys + throttle give per-key fairness; DBOS queues are FIFO with a\n * `workerConcurrency` cap. We fold both knobs into the same in-process admission gate: an optional\n * per-call `priority` (higher first) and an optional queue-level `fairness: 'key'` (round-robin by\n * the per-call `key`). Because blocked calls re-suspend durably and retry independently (there is no\n * resident FIFO list to reorder), the controller remembers the set of WAITERS that asked-and-were-\n * blocked, and on a later retry only admits the one that is rightful-next under the policy.\n */\nexport interface QueueConfig {\n /** Queue name, referenced by `ctx.step(step, input, { queue: name })`. */\n name: string;\n /** Max steps in flight at once for this queue (this instance). Omit for unlimited. */\n concurrency?: number;\n /** Fixed-window rate limit: at most `limit` admissions per `periodMs`. Omit for unlimited. */\n rateLimit?: { limit: number; periodMs: number };\n /** Delay (ms) before a concurrency-blocked call re-checks for a free slot. Default 1000. */\n retryMs?: number;\n /**\n * Fairness policy for a contended concurrency slot. `'key'` round-robins across distinct per-call\n * keys (the least-recently-served key wins the next slot), so one key can't monopolize the budget.\n * Omit (or `'fifo'`) for plain first-come ordering. Priority always wins over fairness; fairness\n * only breaks ties within the same priority.\n */\n fairness?: 'fifo' | 'key';\n /**\n * Arrival-order tiebreak among otherwise-equal waiters (same priority, same fairness rank).\n * `'fifo'` (default) admits the earliest arrival; `'lifo'` admits the most recent (a stack). Orthogonal\n * to `priority` and `fairness` — those still win first; this only breaks their ties.\n */\n order?: 'fifo' | 'lifo';\n}\n\n/**\n * Per-call admission hints. All optional — omitting them keeps the legacy FIFO behaviour.\n * - `priority`: higher is admitted first (default 0).\n * - `key`: the fairness bucket (e.g. a tenant id) for `fairness: 'key'`.\n * - `waiterId`: a stable id for THIS call across its retries (the engine passes the stepId), so the\n * controller can track it as one waiter instead of counting each retry as a new contender.\n */\nexport interface AdmissionItem {\n priority?: number | undefined;\n key?: string | undefined;\n waiterId?: string | undefined;\n}\n\n/** Admission decision: either admitted, or blocked until `retryAt` (epoch ms). */\nexport type Admission = { ok: true } | { ok: false; retryAt: number };\n\n/** A call that asked for a slot and was blocked — remembered so the controller can order admission. */\ninterface Waiter {\n priority: number;\n key?: string | undefined;\n /** Monotonic registration order — FIFO tiebreak within equal priority/fairness. */\n seq: number;\n}\n\n/** In-process admission controller for one {@link QueueConfig}. */\nexport class QueueController {\n private inFlight = 0;\n private windowStart = 0;\n private windowCount = 0;\n /** Registered waiters by id (only used when priority/fairness ordering is in play). */\n private readonly waiters = new Map<string, Waiter>();\n /** Monotonic counter stamping each newly-seen waiter for a stable FIFO tiebreak. */\n private waiterSeq = 0;\n /** Per-key \"last served\" order for round-robin fairness — higher = more recently served. */\n private readonly keyServed = new Map<string, number>();\n private servedTick = 0;\n\n constructor(\n readonly config: QueueConfig,\n private readonly clock: () => number,\n ) {}\n\n /** Whether this controller does any priority/fairness ordering (else it's a plain FIFO gate). */\n private get ordered(): boolean {\n return this.config.fairness === 'key' || this.config.order === 'lifo';\n }\n\n /**\n * Try to admit one unit of work. On `ok`, the caller has taken a concurrency slot and must call\n * {@link release} when the step settles. On block, `retryAt` is when admission may next succeed.\n *\n * `item` carries optional priority/fairness hints; omitting it is the legacy FIFO path. When\n * ordering is configured (or a priority is given), a blocked call REGISTERS as a waiter and is only\n * admitted on a later retry once it is the rightful next under (priority desc, fairness, FIFO).\n */\n tryAdmit(item?: AdmissionItem): Admission {\n const now = this.clock();\n const rl = this.config.rateLimit;\n // Rate limit is a hard global window — checked first and unaffected by priority/fairness.\n if (rl) {\n if (now - this.windowStart >= rl.periodMs) {\n this.windowStart = now;\n this.windowCount = 0;\n }\n if (this.windowCount >= rl.limit)\n return { ok: false, retryAt: this.windowStart + rl.periodMs };\n }\n\n const usingOrder = this.ordered || item?.priority != null || item?.waiterId != null;\n const waiterId = item?.waiterId;\n\n // Concurrency gate.\n const full = this.config.concurrency != null && this.inFlight >= this.config.concurrency;\n if (full) {\n // No slot at all → block (and register as a waiter so a later retry can be ordered).\n if (usingOrder && waiterId != null) this.register(waiterId, item);\n return { ok: false, retryAt: now + (this.config.retryMs ?? 1000) };\n }\n\n // A slot is free. Without ordering, admit immediately (legacy FIFO). With ordering, only admit if\n // THIS call is the rightful next among all registered waiters — otherwise keep it waiting so the\n // freed slot can go to a higher-priority / under-served key on its retry.\n if (usingOrder && this.waiters.size > 0) {\n if (waiterId != null) this.register(waiterId, item);\n if (!this.isNext(waiterId, item)) {\n return { ok: false, retryAt: now + (this.config.retryMs ?? 1000) };\n }\n }\n\n // Admit: consume the slot, the rate-window tick, and clear this waiter.\n if (rl) this.windowCount += 1;\n this.inFlight += 1;\n if (waiterId != null) this.waiters.delete(waiterId);\n if (item?.key != null) this.keyServed.set(item.key, ++this.servedTick);\n return { ok: true };\n }\n\n /** Release a concurrency slot taken by a successful {@link tryAdmit}. */\n release(): void {\n if (this.inFlight > 0) this.inFlight -= 1;\n }\n\n /** Track (or refresh) a blocked call as a waiter; its FIFO seq is stamped only on first sight. */\n private register(waiterId: string, item?: AdmissionItem): void {\n const existing = this.waiters.get(waiterId);\n if (existing) {\n existing.priority = item?.priority ?? 0;\n existing.key = item?.key;\n return;\n }\n this.waiters.set(waiterId, {\n priority: item?.priority ?? 0,\n key: item?.key,\n seq: this.waiterSeq++,\n });\n }\n\n /**\n * Is the calling item the best candidate among all registered waiters? Ordering, best first:\n * 1. higher `priority`;\n * 2. fairness: with `fairness: 'key'`, the least-recently-served key wins (round-robin);\n * 3. earliest registration (FIFO) — stable tiebreak.\n * A bare item (no waiterId) is compared on its hints directly.\n */\n private isNext(waiterId: string | undefined, item?: AdmissionItem): boolean {\n const self: Waiter =\n (waiterId != null ? this.waiters.get(waiterId) : undefined) ??\n ({ priority: item?.priority ?? 0, key: item?.key, seq: Number.POSITIVE_INFINITY } as Waiter);\n let best = self;\n for (const w of this.waiters.values()) {\n if (this.better(w, best)) best = w;\n }\n return best === self;\n }\n\n /** Strict \"a should be admitted before b\" comparison under the active policy. */\n private better(a: Waiter, b: Waiter): boolean {\n if (a.priority !== b.priority) return a.priority > b.priority;\n if (this.config.fairness === 'key') {\n const sa = this.servedOf(a.key);\n const sb = this.servedOf(b.key);\n if (sa !== sb) return sa < sb; // least-recently-served key first\n }\n return this.config.order === 'lifo' ? a.seq > b.seq : a.seq < b.seq; // arrival tiebreak\n }\n\n /** Last-served tick for a key (0 = never served, so an unseen key is admitted before a busy one). */\n private servedOf(key?: string): number {\n if (key == null) return 0;\n return this.keyServed.get(key) ?? 0;\n }\n}\n","import { type Admission, type AdmissionItem, type QueueConfig, QueueController } from './queue';\n\n/**\n * Pluggable backend for the step flow-control gate (`ctx.step(step, input, { queue })`). The\n * engine asks it whether a queued call may be admitted now (concurrency / rate / ordering) and tells\n * it when an admitted slot is released.\n *\n * The default {@link InMemoryAdmissionBackend} keeps per-instance counts — correct for a single\n * orchestrator. Swap in a store/Redis-backed backend to make the caps and ordering GLOBAL across\n * engine replicas (so `concurrency: 5` means 5 in-flight across the whole fleet, not 5 per pod).\n *\n * `tryAdmit`/`release` are async so a global backend can do its atomic round-trip; the in-memory one\n * resolves synchronously. An UNREGISTERED queue name is treated as ungated (admits immediately) — the\n * engine only tracks/releases a slot for a registered queue.\n */\nexport interface AdmissionBackend {\n /** Register (or replace) a queue's config. Called from `engine.registerQueue`. */\n register(config: QueueConfig): void;\n /** Whether `queue` is registered (gated). The engine only tracks/releases a slot for a gated queue. */\n handles(queue: string): boolean;\n /** May a call on `queue` take a slot now? On `ok`, the caller holds a slot until {@link release}. */\n tryAdmit(queue: string, item: AdmissionItem): Promise<Admission>;\n /**\n * Release the slot granted by {@link tryAdmit} for `queue`. `slotId` is the admitted item's\n * `waiterId` (the engine's stepId), so a lease-based backend can drop the exact slot; an in-process\n * counter ignores it.\n */\n release(queue: string, slotId: string): Promise<void>;\n /**\n * Optional: subscribe to \"a slot just freed on `queue`\" events (e.g. a fleet-wide pub/sub). The\n * engine uses it to wake its admission-blocked runs early instead of waiting for their retry tick.\n * A backend without it falls back to retry-tick polling. Fired best-effort across the fleet.\n */\n onFreed?(handler: (queue: string) => void): void;\n}\n\n/**\n * Default admission backend: one in-process {@link QueueController} per registered queue. Caps and\n * waiter ordering are per engine instance (see {@link QueueConfig}). Preserves the exact pre-backend\n * behaviour — the engine used to hold these controllers directly.\n */\nexport class InMemoryAdmissionBackend implements AdmissionBackend {\n private readonly controllers = new Map<string, QueueController>();\n\n constructor(private readonly clock: () => number) {}\n\n register(config: QueueConfig): void {\n this.controllers.set(config.name, new QueueController(config, this.clock));\n }\n\n handles(queue: string): boolean {\n return this.controllers.has(queue);\n }\n\n async tryAdmit(queue: string, item: AdmissionItem): Promise<Admission> {\n const controller = this.controllers.get(queue);\n // Unregistered queue → ungated (mirrors the old `this.queues.get(queue)` truthiness check).\n if (!controller) return { ok: true };\n return controller.tryAdmit(item);\n }\n\n async release(queue: string, _slotId: string): Promise<void> {\n this.controllers.get(queue)?.release();\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { WorkflowCtx } from './interfaces';\n\n/**\n * The ambient workflow context: an `AsyncLocalStorage` the engine (and the thin worker runtime)\n * installs around every execution of a workflow body, so code running ON the body's async path can\n * discover the live {@link WorkflowCtx} without threading it through — the mechanism behind the\n * class-first `MyWorkflow.start()` / `MyWorkflow.execute()` statics (see `durable-workflow.ts`).\n *\n * One storage per PROCESS, not per copy of this package: stashed on `globalThis` under a\n * `Symbol.for` key, so a dependency tree carrying duplicate copies of core still shares the same\n * ambient context (the same duplicate-copy trap the DI tokens guard against — see `tokens.ts`).\n */\nconst STORAGE_KEY = Symbol.for('nestjs-durable:ambient-workflow-ctx');\n\ntype GlobalWithStorage = typeof globalThis & {\n [STORAGE_KEY]?: AsyncLocalStorage<WorkflowCtx>;\n};\n\nconst globalRef = globalThis as GlobalWithStorage;\nif (!globalRef[STORAGE_KEY]) {\n globalRef[STORAGE_KEY] = new AsyncLocalStorage<WorkflowCtx>();\n}\nconst storage: AsyncLocalStorage<WorkflowCtx> = globalRef[STORAGE_KEY];\n\n/**\n * Run `fn` with `ctx` as the ambient workflow context. Engine-internal: wraps every execution of a\n * workflow body (first run and every replay), so ambient reads inside the body see the SAME ctx the\n * body received.\n */\nexport function runInWorkflowCtx<T>(ctx: WorkflowCtx, fn: () => T): T {\n return storage.run(ctx, fn);\n}\n\n/**\n * The {@link WorkflowCtx} of the workflow body currently executing on this async path — or\n * `undefined` outside one. Note a `@Step` HANDLER runs on a worker, off the body's path: it has no\n * ambient workflow context (by design — a handler is not the workflow body).\n */\nexport function currentWorkflowCtx(): WorkflowCtx | undefined {\n return storage.getStore();\n}\n","/**\n * Cross-package, cross-runtime marker for engine CONTROL-FLOW signals — {@link WorkflowSuspended}\n * and {@link ContinueAsNew} (this package), plus the thin worker's {@link\n * import('@dudousxd/durable-worker').Suspend} (`@dudousxd/durable-worker`, the BullMQ\n * route-by-handler runtime). These are thrown by `WorkflowCtx`/`WorkflowContext` ops to unwind the\n * current turn — never real failures — so a workflow's `catch` block MUST rethrow them untouched.\n * Running a failure/cleanup path on a control-flow signal corrupts the run: it emits extra\n * `recordStep` commands into history that a subsequent replay didn't produce the first time,\n * surfacing as a `NonDeterminismError`/`NondeterminismError` on resume.\n *\n * `Symbol.for` (the GLOBAL registry), NOT a plain `Symbol()` — so a duplicate copy of this module\n * (pnpm peer-dependency multiplexing, a dual ESM/CJS load, or the SEPARATE `@dudousxd/durable-worker`\n * package declaring the same `Symbol.for` key locally) still collapses onto the SAME symbol. Same\n * rationale as `DURABLE_STEP_NAME` in `./step-name-symbol.ts`.\n *\n * Deliberately checked as a stamped property, NOT `instanceof` — `instanceof` only recognizes a\n * signal thrown by the SAME class the checking code imported, which fails across the in-process\n * engine (`@dudousxd/nestjs-durable-core`'s `WorkflowSuspended`/`ContinueAsNew`) and the thin worker\n * (`@dudousxd/durable-worker`'s `Suspend`) — two different classes for what is, from a workflow\n * author's catch block, the same \"this isn't a real error, let it through\" event.\n *\n * NOT designed to survive a serialization boundary (e.g. JSON over the wire) — these signals are\n * always thrown and caught in-process within a single replay turn, never (de)serialized, so a\n * stamped-but-not-cloneable property is sufficient.\n */\nexport const CONTROL_FLOW_SIGNAL = Symbol.for('aviary:durable:control-flow');\n\n/**\n * True for any engine control-flow signal (currently: {@link WorkflowSuspended}, {@link\n * ContinueAsNew}, and the thin worker's `Suspend`) — regardless of which runtime or module instance\n * threw it. Workflow `catch` blocks MUST rethrow these untouched; running a failure/cleanup path on\n * one corrupts the run's history (extra commands recorded during what replay will later see as a\n * suspend, not a failure) and the resumed replay dies with a non-determinism error.\n *\n * Deliberately NOT control-flow (do not add to this predicate):\n * - `Cancelled` (worker) / a cancelled run — a TERMINAL outcome the consumer may legitimately want\n * to observe and react to (e.g. release a lock), not a mid-turn unwind to rethrow untouched.\n * - `StepFailed` (worker) / an awaited step rejection reaching the engine — a REAL failure a\n * workflow's `catch` is meant to compensate for; misclassifying it as control-flow would swallow\n * genuine errors instead of protecting them.\n *\n * @example\n * ```ts\n * try {\n * await ctx.step('chargeCard', input);\n * } catch (error) {\n * if (isWorkflowControlFlowSignal(error)) throw error; // suspend/continue-as-new: rethrow as-is\n * await ctx.step('refund', input); // a REAL failure — safe to run cleanup here\n * throw error;\n * }\n * ```\n */\nexport function isWorkflowControlFlowSignal(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as { [CONTROL_FLOW_SIGNAL]?: unknown })[CONTROL_FLOW_SIGNAL] === true\n );\n}\n","import { CONTROL_FLOW_SIGNAL, type isWorkflowControlFlowSignal } from './control-flow-signal';\n\n/**\n * Thrown inside a step to signal an unrecoverable failure: the engine will NOT retry it,\n * regardless of the step's `retries` setting, and fails the run immediately. Use it for\n * business errors that retrying cannot fix (e.g. a declined card, invalid input).\n */\nexport class FatalError extends Error {\n readonly code?: string | undefined;\n constructor(message: string, code?: string) {\n super(message);\n this.name = 'FatalError';\n this.code = code;\n }\n}\n\n/**\n * Thrown by `start` when a singleton workflow's wait queue is full: the count of in-flight + gated\n * runs sharing the key already equals `limit + maxQueueDepth`, so admitting another would let the\n * same-key backlog grow unbounded. Back-pressure — the caller should retry later or shed load. Only\n * raised when {@link SingletonConfig.maxQueueDepth} is set (omit it for the old unbounded behavior).\n */\nexport class SingletonQueueFullError extends Error {\n readonly workflow: string;\n readonly key: string;\n readonly maxQueueDepth: number;\n constructor(workflow: string, key: string, maxQueueDepth: number) {\n super(\n `singleton queue for ${workflow} key \"${key}\" is full (maxQueueDepth=${maxQueueDepth}); retry later`,\n );\n this.name = 'SingletonQueueFullError';\n this.workflow = workflow;\n this.key = key;\n this.maxQueueDepth = maxQueueDepth;\n }\n}\n\n/**\n * Internal control signal thrown to suspend a run (e.g. on a durable sleep). Not an error the\n * user should throw or catch; the engine uses it to stop execution and persist `wakeAt`.\n */\nexport class SignalTimeoutError extends Error {\n readonly token: string;\n readonly timeoutMs: number;\n constructor(token: string, timeoutMs: number) {\n super(`timed out after ${timeoutMs}ms waiting for signal \"${token}\"`);\n this.name = 'SignalTimeoutError';\n this.token = token;\n this.timeoutMs = timeoutMs;\n }\n}\n\n/**\n * Thrown when a remote step produces no result and no heartbeat within its `timeoutMs` window —\n * i.e. the worker is presumed dead. Subject to the step's `retries` (it's retryable), so the engine\n * re-dispatches before giving up.\n */\nexport class RemoteStepTimeout extends Error {\n readonly stepId: string;\n readonly timeoutMs: number;\n constructor(stepId: string, timeoutMs: number) {\n super(`remote step ${stepId} produced no result/heartbeat within ${timeoutMs}ms`);\n this.name = 'RemoteStepTimeout';\n this.stepId = stepId;\n this.timeoutMs = timeoutMs;\n }\n}\n\n/**\n * Thrown by a remote {@link WorkflowExecutor} (e.g. {@link RemoteWorkflowExecutor}) when an `advance`\n * does not produce its decision within the configured `timeoutMs` — i.e. the worker is presumed gone\n * (the decision was dropped by a stall/redelivery or an instance restart spanning the in-memory waiter\n * map). Crucially this is NOT a run failure: the work may have actually completed and only the decision\n * was lost. The engine treats it as RECOVERABLE — it releases the run lease and leaves the run\n * `running` so `recoverIncomplete` re-drives it deterministically (replaying completed steps from\n * history). Distinct from a real executor error, which still fails the run.\n *\n * OPT-IN: only thrown when the executor was constructed with a `timeoutMs`. Absent a timeout, the\n * engine awaits the decision with its prior (unbounded) behavior — so existing users see no change.\n *\n * Known hazard: a timeout that fires while a worker is LEGITIMATELY still executing a not-yet-\n * checkpointed step will re-drive and re-run that in-flight step → DUPLICATE side effects. Therefore\n * the timeout is only safe when set GENEROUSLY (longer than the longest legitimate single turn). The\n * robust fix — a liveness/heartbeat-rearmed deadline so only a genuinely-dead worker re-drives — is the\n * documented follow-up (see the Track A diagnosis doc, \"Part B\").\n */\nexport class RemoteWorkflowTimeout extends Error {\n readonly taskId: string;\n readonly timeoutMs: number;\n constructor(taskId: string, timeoutMs: number) {\n super(\n `remote workflow task ${taskId} produced no decision within ${timeoutMs}ms — presumed dropped; re-driving via recovery`,\n );\n this.name = 'RemoteWorkflowTimeout';\n this.taskId = taskId;\n this.timeoutMs = timeoutMs;\n }\n}\n\n/**\n * Thrown on resume when the workflow code no longer matches the recorded history: the step at a\n * logical position has a different name/kind than the checkpoint saved there. This means the\n * workflow definition changed (a step was added/removed/reordered) under an in-flight run without a\n * new `@Workflow` version — continuing would replay the wrong checkpoint into the wrong step and\n * silently corrupt the run, so the engine fails loudly instead. Register a new workflow version for\n * breaking changes (old runs finish on the version they started on).\n */\nexport class NonDeterminismError extends Error {\n readonly runId: string;\n readonly seq: number;\n constructor(runId: string, seq: number, expected: string, recorded: string) {\n super(\n `non-determinism at ${runId}#${seq}: code expects \"${expected}\" but history recorded ` +\n `\"${recorded}\". The workflow changed under an in-flight run — register a new @Workflow version.`,\n );\n this.name = 'NonDeterminismError';\n this.runId = runId;\n this.seq = seq;\n }\n}\n\n/**\n * Thrown by `ctx.all` when one or more parallel child workflows fail. Carries the per-item failures\n * (input index, child run id, error message) and presents an aggregate message summarizing the count\n * and the failing ids — the wait-all/fail-fast counterpart to a single child's FatalError. Mirrors\n * the Python SDK's `GatherFailed`.\n */\nexport class GatherError extends Error {\n readonly failures: { index: number; id: string; error: string }[];\n constructor(failures: { index: number; id: string; error: string }[], total?: number) {\n const ids = failures.map((f) => f.id).join(', ');\n const denom = total ?? failures.length;\n super(`ctx.all: ${failures.length} of ${denom} child(ren) failed: ${ids}`);\n this.name = 'GatherError';\n this.failures = failures;\n }\n}\n\nexport class WorkflowSuspended extends Error {\n /** Epoch ms to auto-resume (durable sleep), or undefined when waiting on an external signal. */\n readonly wakeAt?: number | undefined;\n /** Marks this as a control-flow signal — see {@link isWorkflowControlFlowSignal}. */\n readonly [CONTROL_FLOW_SIGNAL] = true;\n constructor(wakeAt?: number) {\n super('workflow suspended');\n this.name = 'WorkflowSuspended';\n this.wakeAt = wakeAt;\n }\n}\n\n/**\n * Thrown by `ctx.continueAsNew(input)` to end the current run and hand off to a fresh execution of\n * the same workflow with a clean history — for long-running / looping workflows that would otherwise\n * accumulate unbounded checkpoints. The engine completes this run and starts the next one.\n */\nexport class ContinueAsNew extends Error {\n /** Marks this as a control-flow signal — see {@link isWorkflowControlFlowSignal}. */\n readonly [CONTROL_FLOW_SIGNAL] = true;\n constructor(readonly input: unknown) {\n super('workflow continued as new');\n this.name = 'ContinueAsNew';\n }\n}\n","/**\n * A **workflow reference** is how one workflow names another to call it: either a registered workflow\n * **name** (a string — the only option across runtimes, e.g. a Python workflow) or, for a same-runtime\n * TypeScript workflow, its **class**. The class carries the input/output types through the call, so\n * `ctx.child(ShippingWorkflow, input)` type-checks the input and returns a typed result — while a\n * string stays available for the cross-runtime case.\n */\n\n/**\n * The symbol the `@Workflow` decorator stamps a workflow's registered name onto, so a class ref can\n * be resolved back to its name. A global-registry symbol (`Symbol.for`) so it survives duplicate\n * copies of this package in a dependency tree.\n */\nexport const WORKFLOW_NAME_KEY: unique symbol = Symbol.for('nestjs-durable:workflow-name');\n\n/** Structural shape of a `@Workflow` class — its `run(ctx, input)` carries the input/output types. */\nexport type WorkflowClass<TInput = unknown, TOutput = unknown> = abstract new (\n ...args: never[]\n) => {\n run(ctx: never, input: TInput): Promise<TOutput> | TOutput;\n};\n\n/** A workflow reference: a registered name (cross-runtime) or a workflow class (typed, same-runtime). */\nexport type WorkflowRef<TInput = unknown, TOutput = unknown> =\n | string\n | WorkflowClass<TInput, TOutput>;\n\n/** The input type a workflow class's `run` accepts. */\nexport type WorkflowInputOf<C> = C extends abstract new (\n ...args: never[]\n) => {\n run(ctx: never, input: infer I): unknown;\n}\n ? I\n : unknown;\n\n/** The output type a workflow class's `run` resolves to (Promise unwrapped). */\nexport type WorkflowOutputOf<C> = C extends abstract new (\n ...args: never[]\n) => {\n run(ctx: never, input: never): infer R;\n}\n ? Awaited<R>\n : unknown;\n\n/**\n * Resolve a {@link WorkflowRef} to its registered workflow name: a string is returned as-is; a\n * `@Workflow` class is resolved via the name the decorator stamped on it. Throws if a class was\n * never decorated (so it carries no registered name).\n */\nexport function workflowName(ref: WorkflowRef): string {\n if (typeof ref === 'string') return ref;\n const name = (ref as { [WORKFLOW_NAME_KEY]?: string })[WORKFLOW_NAME_KEY];\n if (!name) {\n throw new Error(\n `workflow class ${ref.name} has no registered name — is it decorated with @Workflow({ name })?`,\n );\n }\n return name;\n}\n","import { currentWorkflowCtx } from './ambient-ctx';\nimport type { StartOptions } from './engine';\nimport { FatalError } from './errors';\nimport type { RunResult } from './interfaces';\nimport {\n type WorkflowClass,\n type WorkflowInputOf,\n type WorkflowOutputOf,\n workflowName,\n} from './workflow-ref';\n\n/**\n * What the class-first statics need from whoever registered the workflow class: the engine, or a\n * store-less start facade (a tenant's `DurableStartClient`). `waitForRun` is optional — a facade\n * without a store cannot wait, so `execute` outside a workflow throws a clear error there.\n */\nexport interface WorkflowStartClient {\n start(workflow: string, input: unknown, runId: string, opts?: StartOptions): Promise<RunResult>;\n waitForRun?(\n runId: string,\n opts?: { timeoutMs?: number; until?: 'settled' | 'terminal' },\n ): Promise<RunResult>;\n}\n\n/**\n * Per-process class → start-client bindings, written by the registrar at boot. On `globalThis`\n * under a `Symbol.for` key for the same duplicate-copy reason as the ambient context: every copy of\n * core in the tree must read the same map. A WeakMap so a torn-down module doesn't pin its classes.\n */\nconst BINDINGS_KEY = Symbol.for('nestjs-durable:workflow-class-bindings');\n\ntype GlobalWithBindings = typeof globalThis & {\n // biome-ignore lint/complexity/noBannedTypes: keyed by class constructors\n [BINDINGS_KEY]?: WeakMap<Function, WorkflowStartClient>;\n};\n\nconst globalRef = globalThis as GlobalWithBindings;\nif (!globalRef[BINDINGS_KEY]) {\n globalRef[BINDINGS_KEY] = new WeakMap();\n}\nconst bindings = globalRef[BINDINGS_KEY];\n\n/**\n * Bind a `@Workflow` class to the client that can start it — called by the registrar for every\n * discovered workflow at boot. This is what lets `MyWorkflow.start()` resolve THE engine that\n * registered it, with no global engine singleton (two engines in one process each bind their own\n * classes).\n */\n// biome-ignore lint/complexity/noBannedTypes: keyed by class constructors\nexport function bindWorkflowClass(ctor: Function, client: WorkflowStartClient): void {\n bindings.set(ctor, client);\n}\n\nfunction clientOf(ctor: WorkflowClass): WorkflowStartClient {\n const client = bindings.get(ctor);\n if (!client) {\n throw new Error(\n `${workflowName(ctor)} is not bound to a durable engine — the class-first statics only work after the module that registers this workflow has booted (or, in a store-less tenant worker, use the injected WorkflowService/engine facade instead).`,\n );\n }\n return client;\n}\n\n/**\n * Optional base class giving a `@Workflow` a **class-first API** — start it from anywhere without\n * injecting the engine or `WorkflowService`:\n *\n * ```ts\n * @Workflow({ name: 'checkout', version: '1' })\n * export class CheckoutWorkflow extends DurableWorkflow {\n * async run(ctx: WorkflowCtx, order: Order) { ... }\n * }\n *\n * const { runId } = await CheckoutWorkflow.start(order); // fire-and-forget, typed input\n * const result = await CheckoutWorkflow.execute(order); // run-and-await, typed output\n * ```\n *\n * Each method means the same thing everywhere; only the mechanism adapts to where you call it:\n *\n * - {@link DurableWorkflow.start | `start`} — **fire-and-forget**. Outside a workflow it is exactly\n * `engine.start` (enqueue, return `{ runId, status }` immediately). Inside a workflow body it\n * becomes `ctx.startChild` — checkpointed, replay-safe, parent-linked — same contract.\n * - {@link DurableWorkflow.execute | `execute`} — **run-and-await the typed output**. Inside a\n * workflow it is `ctx.child` (the parent suspends with zero compute and resumes with the result).\n * Outside it starts the run and waits until it settles terminally, resolving the output or\n * throwing `FatalError` when the run failed/cancelled/dead.\n *\n * Inside-ness is detected via the ambient workflow context the engine installs around every body\n * execution (see `ambient-ctx.ts`). A `@Step` handler runs on a worker, off the body's path — the\n * statics there start a TOP-LEVEL run, which is correct: a handler is not the workflow body.\n */\nexport class DurableWorkflow {\n /**\n * Fire-and-forget start — `engine.start` outside a workflow, `ctx.startChild` (parent-linked)\n * inside one. `opts.id` pins the run id (outside) / child id (inside) for idempotent starts.\n */\n static async start<C extends WorkflowClass>(\n this: C,\n input: WorkflowInputOf<C>,\n opts?: { id?: string } & StartOptions,\n ): Promise<RunResult> {\n // biome-ignore lint/complexity/noThisInStatic: the polymorphic `this` IS the subclass being started — the class name would break every subclass\n // biome-ignore lint/complexity/noUselessThisAlias: aliased ONCE on purpose so the noThisInStatic suppression lives in one place, not on every `this` use below\n const cls = this;\n const ctx = currentWorkflowCtx();\n if (ctx) {\n const runId = await ctx.startChild(cls, input, opts?.id);\n return { runId, status: 'pending' };\n }\n const runId = opts?.id ?? globalThis.crypto.randomUUID();\n return clientOf(cls).start(workflowName(cls), input, runId, opts);\n }\n\n /**\n * Run-and-await the typed output — `ctx.child` inside a workflow (suspends the parent, zero\n * compute); outside, starts the run and waits until it settles terminally. Throws `FatalError`\n * when the run does not complete. `opts.timeoutMs` bounds the OUTSIDE wait only (inside, a\n * suspended parent costs nothing — bound the child itself with `executionTimeout` instead).\n */\n static async execute<C extends WorkflowClass>(\n this: C,\n input: WorkflowInputOf<C>,\n opts?: { id?: string; timeoutMs?: number } & StartOptions,\n ): Promise<WorkflowOutputOf<C>> {\n // biome-ignore lint/complexity/noThisInStatic: the polymorphic `this` IS the subclass being run — the class name would break every subclass\n // biome-ignore lint/complexity/noUselessThisAlias: aliased ONCE on purpose so the noThisInStatic suppression lives in one place, not on every `this` use below\n const cls = this;\n const ctx = currentWorkflowCtx();\n if (ctx) return ctx.child(cls, input, opts?.id);\n const client = clientOf(cls);\n if (!client.waitForRun) {\n throw new FatalError(\n `${workflowName(cls)}.execute() outside a workflow needs a store-backed engine to await the result — this class is bound to a store-less start facade (tenant worker). Use ${workflowName(cls)}.start() and observe the run instead.`,\n 'execute_unsupported',\n );\n }\n const runId = opts?.id ?? globalThis.crypto.randomUUID();\n await client.start(workflowName(cls), input, runId, opts);\n const settled = await client.waitForRun(runId, {\n ...(opts?.timeoutMs != null ? { timeoutMs: opts.timeoutMs } : {}),\n until: 'terminal',\n });\n if (settled.status === 'completed') return settled.output as WorkflowOutputOf<C>;\n const detail = settled.error ? `: ${settled.error.message}` : '';\n throw new FatalError(\n `${workflowName(cls)} run ${runId} settled ${settled.status}${detail}`,\n settled.error?.code ?? 'execute_failed',\n );\n }\n}\n","const UNIT_MS: Record<string, number> = {\n ms: 1,\n s: 1_000,\n sec: 1_000,\n second: 1_000,\n seconds: 1_000,\n m: 60_000,\n min: 60_000,\n minute: 60_000,\n minutes: 60_000,\n h: 3_600_000,\n hr: 3_600_000,\n hour: 3_600_000,\n hours: 3_600_000,\n d: 86_400_000,\n day: 86_400_000,\n days: 86_400_000,\n w: 604_800_000,\n week: 604_800_000,\n weeks: 604_800_000,\n};\n\n/**\n * Parse a human duration to milliseconds. Accepts a number (already ms) or a string like\n * `'500ms'`, `'30s'`, `'15m'`, `'2h'`, `'7d'`, `'7 days'`.\n */\nexport function parseDuration(duration: string | number): number {\n if (typeof duration === 'number') return duration;\n const match = duration.trim().match(/^(\\d+(?:\\.\\d+)?)\\s*([a-z]+)$/i);\n if (!match) throw new Error(`invalid duration: ${duration}`);\n const value = Number(match[1]);\n const unit = (match[2] ?? '').toLowerCase();\n const factor = UNIT_MS[unit];\n if (factor === undefined) throw new Error(`unknown duration unit: ${unit}`);\n return value * factor;\n}\n","import type { StepOptions } from './interfaces';\n\n/** Delay in ms before the next retry attempt, per a step's `StepOptions` backoff config. Shared by\n * the local-step retry loop and the durable remote-step retry, so they stay consistent. */\nexport function backoffDelay(attempt: number, options?: StepOptions): number {\n const base = options?.backoffMs ?? 0;\n if (base <= 0) return 0;\n const raw = options?.backoff === 'exp' ? base * 2 ** (attempt - 1) : base;\n const capped = options?.backoffMaxMs ? Math.min(raw, options.backoffMaxMs) : raw;\n return options?.jitter ? Math.round(capped * (0.5 + Math.random() * 0.5)) : capped;\n}\n","import type { StepEvent, StepLogger, SubProcessHandle } from './interfaces';\n\n/** Attach the elapsed `durationMs` (from `start`) to `data`, unless the caller already set one. */\nfunction withDuration(start: number, now: () => number, data?: unknown): Record<string, unknown> {\n if (data && typeof data === 'object' && 'durationMs' in data) {\n return data as Record<string, unknown>;\n }\n const base = data && typeof data === 'object' ? (data as Record<string, unknown>) : {};\n return { ...base, durationMs: now() - start };\n}\n\n/**\n * A {@link StepLogger} that appends to `events`, stamping each line with `now()`. Shared by the\n * local-step path (`ctx.step`) and the remote-worker path (`runStepHandler`) so a step records\n * the same {@link StepEvent} shape wherever it runs — the TypeScript twin of the Python SDK's\n * `StepContext`.\n */\nexport function createStepLogger(events: StepEvent[], now: () => number): StepLogger {\n // The sub-process a `subProcess(...)` body is currently inside; debug/info/warn/error emitted while\n // inside get tagged with its id, so the dashboard groups that log trail under the sub-process.\n let currentSub: { id: string } | undefined;\n const push = (level: StepEvent['level'], message: string, data?: unknown) =>\n events.push({\n at: now(),\n level,\n message,\n ...(currentSub ? { subId: currentSub.id } : {}),\n ...(data === undefined ? {} : { data }),\n });\n const subEvent: StepLogger['subEvent'] = (e) =>\n events.push({\n at: now(),\n level: e.status === 'failed' ? 'error' : e.status === 'skipped' ? 'warn' : 'info',\n message: e.message ?? e.phase ?? e.name,\n subId: e.id,\n name: e.name,\n ...(e.group === undefined ? {} : { group: e.group }),\n ...(e.phase === undefined ? {} : { phase: e.phase }),\n ...(e.status === undefined ? {} : { status: e.status }),\n ...(e.data === undefined ? {} : { data: e.data }),\n });\n const subProcess: StepLogger['subProcess'] = async (name, body, opts) => {\n const id = opts?.id ?? globalThis.crypto.randomUUID();\n const group = opts?.group;\n const start = now();\n const prevSub = currentSub;\n currentSub = { id };\n let terminal = false;\n const emit = (status: 'ok' | 'failed' | 'skipped', message?: string, data?: unknown) => {\n if (terminal) return;\n terminal = true;\n subEvent({ id, name, group, status, message, data: withDuration(start, now, data) });\n };\n const handle: SubProcessHandle = {\n phase: (phase, data) => {\n if (!terminal) subEvent({ id, name, group, phase, data });\n return handle;\n },\n skip: (reason, data) => emit('skipped', reason, data),\n fail: (reason, data) => emit('failed', reason, data),\n };\n try {\n const result = await body(handle);\n emit('ok'); // no-op if the body already called skip()/fail()\n return result;\n } catch (err) {\n emit('failed', err instanceof Error ? err.message : String(err));\n throw err;\n } finally {\n currentSub = prevSub;\n }\n };\n return {\n debug: (m, d) => push('debug', m, d),\n info: (m, d) => push('info', m, d),\n warn: (m, d) => push('warn', m, d),\n error: (m, d) => push('error', m, d),\n sub: (name, status, message, data) =>\n events.push({\n at: now(),\n level: status === 'failed' ? 'error' : status === 'skipped' ? 'warn' : 'info',\n message: message ?? name,\n name,\n status,\n ...(data === undefined ? {} : { data }),\n }),\n subEvent,\n subProcess,\n };\n}\n","import type { RemoteTask, StepEvent, StepLogger, StepResult } from './interfaces';\nimport { createStepLogger } from './step-logger';\n\n/** Canonical step id — the stable identity of a step within a run, used for dedupe and\n * correlation. The format is part of the cross-language wire contract (Python builds the same). */\nexport function stepId(runId: string, seq: number): string {\n return `${runId}:${seq}`;\n}\n\n/** Deterministic signal token a breakpoint suspends on — derived from its logical position. Shared\n * so `ctx.breakpoint` (which records it) and `engine.continue` (which signals it) agree. */\nexport const breakpointToken = (runId: string, seq: number): string => `bp:${runId}:${seq}`;\n\n/** A remote-worker step body. The optional `log` records sub-process outcomes and debug/error\n * lines that ride back on the result — the TypeScript twin of the Python SDK's `StepContext`. */\nexport type StepHandler = (input: unknown, log: StepLogger) => Promise<unknown> | unknown;\n\n/**\n * Run `handler` for `task` and produce the wire-format {@link StepResult}. Pure (no transport,\n * no I/O beyond the handler), so every transport — and any language port — can share the exact\n * same completed / failed / no-handler contract instead of re-deriving it.\n */\nexport async function runStepHandler(\n task: RemoteTask,\n handler: StepHandler | undefined,\n): Promise<StepResult> {\n // Stamp the worker's pickup time so the engine can report queue-wait (startedAt − enqueuedAt).\n // This is the one place every transport funnels through, so timing comes for free everywhere.\n const base = { runId: task.runId, seq: task.seq, stepId: task.stepId, startedAt: Date.now() };\n if (!handler) {\n return {\n ...base,\n status: 'failed',\n error: { message: `no handler for ${task.name}`, retryable: false },\n };\n }\n const events: StepEvent[] = [];\n const withEvents = (result: StepResult): StepResult =>\n events.length > 0 ? { ...result, events } : result;\n try {\n const output = await handler(task.input, createStepLogger(events, Date.now));\n return withEvents({ ...base, status: 'completed', output });\n } catch (err) {\n // Carry `code`/`retryable` off the thrown error if present, so the engine's durable retry can\n // honour a worker's \"don't retry this\" verdict (e.g. a declined card).\n const e = err as { message?: string; code?: string; retryable?: boolean };\n return withEvents({\n ...base,\n status: 'failed',\n error: {\n message: err instanceof Error ? err.message : String(err),\n ...(typeof e?.code === 'string' ? { code: e.code } : {}),\n ...(typeof e?.retryable === 'boolean' ? { retryable: e.retryable } : {}),\n },\n });\n }\n}\n","import type { StepCheckpoint, StepError, StepEvent, StepKind } from './interfaces';\nimport { stepId } from './protocol';\n\n/** Drop an empty events array to `undefined` (the repeated `events?.length ? events : undefined`). */\nfunction nonEmptyEvents(events: StepEvent[] | undefined): StepEvent[] | undefined {\n return events && events.length > 0 ? events : undefined;\n}\n\n/**\n * Build a *phased* step checkpoint — one with distinct enqueue/run/finish timestamps (a local step\n * that is running/completed/failed, or a pending remote/sleep step). Computes the deterministic\n * `stepId` and normalizes empty event arrays, so the engine's running/completed/failed/pending\n * checkpoint literals are constructed in exactly one place instead of ~8.\n *\n * For instantaneous checkpoints (sleep timers, markers, delivered signals) use {@link instantCheckpoint}.\n */\nexport function stepCheckpoint(p: {\n runId: string;\n seq: number;\n name: string;\n kind: StepKind;\n status: StepCheckpoint['status'];\n attempts: number;\n enqueuedAt: Date;\n startedAt: Date;\n finishedAt: Date;\n input?: unknown;\n output?: unknown;\n error?: StepError | undefined;\n events?: StepEvent[] | undefined;\n workerGroup?: string | undefined;\n wakeAt?: number | undefined;\n parallelGroup?: string | undefined;\n}): StepCheckpoint {\n return {\n runId: p.runId,\n seq: p.seq,\n name: p.name,\n kind: p.kind,\n stepId: stepId(p.runId, p.seq),\n status: p.status,\n input: p.input,\n output: p.output,\n error: p.error,\n events: nonEmptyEvents(p.events),\n attempts: p.attempts,\n workerGroup: p.workerGroup,\n wakeAt: p.wakeAt,\n parallelGroup: p.parallelGroup,\n enqueuedAt: p.enqueuedAt,\n startedAt: p.startedAt,\n finishedAt: p.finishedAt,\n };\n}\n\n/**\n * Build an *instantaneous* checkpoint — one with no distinct enqueue/run/finish phases (a durable\n * sleep timer, a breakpoint marker, a delivered signal, a published `setEvent` value, a `patched`\n * marker). All three timestamps collapse to now and `attempts` is 1. Collapses what was five\n * near-identical 10-field `saveCheckpoint({...})` literals into one builder.\n */\nexport function instantCheckpoint(p: {\n runId: string;\n seq: number;\n name: string;\n kind: StepKind;\n status?: StepCheckpoint['status'];\n output?: unknown;\n wakeAt?: number;\n parallelGroup?: string | undefined;\n}): StepCheckpoint {\n const at = new Date();\n return {\n runId: p.runId,\n seq: p.seq,\n name: p.name,\n kind: p.kind,\n stepId: stepId(p.runId, p.seq),\n status: p.status ?? 'completed',\n output: p.output,\n wakeAt: p.wakeAt,\n parallelGroup: p.parallelGroup,\n attempts: 1,\n enqueuedAt: at,\n startedAt: at,\n finishedAt: at,\n };\n}\n","import { FatalError } from './errors';\nimport type { InternalWorkflowCtx } from './workflow-ctx';\n\n/** One operation on a durable entity: mutate `state` in place and/or return a result. */\nexport type EntityHandler<S = unknown> = (state: S, arg: unknown) => unknown | Promise<unknown>;\n\n/** A durable keyed entity (a virtual object): per-key serialized handlers over durable state. */\nexport interface EntityConfig<S = unknown> {\n /** Build the initial state for a fresh key. */\n initialState: () => S;\n /** Operation handlers, keyed by op name. Each runs serially per key, exactly once. */\n handlers: Record<string, EntityHandler<S>>;\n}\n\n/** The slice of the engine the entity subsystem needs (so it stays a standalone module). */\nexport interface EntityHost {\n register(\n name: string,\n version: string,\n fn: (ctx: InternalWorkflowCtx, input: unknown) => Promise<unknown>,\n ): void;\n signalWithStart(\n workflow: string,\n input: unknown,\n runId: string,\n signal: { token: string; payload?: unknown },\n ): Promise<{ runId: string }>;\n getEvent<T>(runId: string, key: string): Promise<T | undefined>;\n signal(token: string, payload: unknown): Promise<unknown>;\n}\n\nconst ENTITY_WORKFLOW = '__entity';\nconst entityRunId = (name: string, key: string): string => `entity:${name}:${key}`;\n\n/**\n * Durable keyed **entities** (virtual objects): a keyed actor whose handlers run **serialized per\n * key** over **durable state**, exactly once. Each key is one long-lived run (`entity:<name>:<key>`)\n * processing ops in order. Drive it with `signal` (fire) or `ctx.callEntity` (call + await result),\n * read state with `getState`. Registers its built-in runner on construction.\n */\nexport class Entities {\n private readonly configs = new Map<string, EntityConfig>();\n\n constructor(private readonly host: EntityHost) {\n host.register(ENTITY_WORKFLOW, '1', (ctx, input) => this.run(ctx, input));\n }\n\n register<S>(name: string, config: EntityConfig<S>): void {\n this.configs.set(name, config as EntityConfig);\n }\n\n /** Deliver an op to an entity's runner, starting it on first contact. `reply` (a signal token)\n * receives the handler's result, for `ctx.callEntity`. */\n dispatch(\n name: string,\n key: string,\n op: string,\n arg: unknown,\n reply?: string,\n ): Promise<{ runId: string }> {\n const runId = entityRunId(name, key);\n return this.host.signalWithStart(ENTITY_WORKFLOW, { name, key }, runId, {\n token: runId,\n payload: { op, arg, reply },\n });\n }\n\n async signal(name: string, key: string, op: string, arg?: unknown): Promise<void> {\n await this.dispatch(name, key, op, arg);\n }\n\n getState<S = unknown>(name: string, key: string): Promise<S | undefined> {\n return this.host.getEvent<S>(entityRunId(name, key), 'state');\n }\n\n /** The built-in runner: one long-lived run per key, processing ops serially over state. */\n private async run(ctx: InternalWorkflowCtx, input: unknown): Promise<unknown> {\n const { name, key } = input as { name: string; key: string };\n const config = this.configs.get(name);\n if (!config) throw new FatalError(`entity \"${name}\" is not registered`);\n const token = entityRunId(name, key);\n let state = config.initialState();\n for (let i = 0; ; i += 1) {\n const msg = (await ctx.waitForSignal(token)) as { op: string; arg: unknown; reply?: string };\n // Run the handler and snapshot the (possibly mutated) state in ONE checkpoint, so replay\n // restores the state from the checkpoint instead of re-running the handler. `ctx.step` is now\n // ALWAYS dispatched (see WorkflowCtx.step) — this in-process capture uses the internal\n // `localStep` primitive instead (same checkpointed-once-then-replayed semantics).\n const out = await ctx.localStep(`op:${i}`, async () => {\n const handler = config.handlers[msg.op];\n if (!handler) throw new FatalError(`entity \"${name}\" has no handler for op \"${msg.op}\"`);\n const result = await handler(state, msg.arg);\n return { result, state };\n });\n state = out.state; // carry state forward (and restore it from the checkpoint on replay)\n await ctx.setEvent('state', state); // publish for getState\n if (msg.reply) {\n await ctx.localStep(`reply:${i}`, async () => {\n await this.host.signal((msg as { reply: string }).reply, out.result);\n });\n }\n }\n }\n}\n","import { SignalTimeoutError } from './errors';\nimport type { WorkflowCtx } from './interfaces';\n\n/** How `onEvent` triggers are coalesced into fewer runs (see `@Workflow({ debounce | batch })`). */\nexport type EventBatchConfig =\n | { mode: 'debounce'; windowMs: number }\n | { mode: 'batch'; maxSize: number; windowMs: number };\n\n/** The slice of the engine the accumulators need (so they stay a standalone module). */\nexport interface AccumulatorHost {\n register(\n name: string,\n version: string,\n fn: (ctx: WorkflowCtx, input: unknown) => Promise<unknown>,\n ): void;\n signalWithStart(\n workflow: string,\n input: unknown,\n runId: string,\n signal: { token: string; payload?: unknown },\n ): Promise<{ runId: string }>;\n}\n\nconst accToken = (target: string): string => `__evtacc__:${target}`;\n\n/**\n * Built-in workflows that coalesce `onEvent` triggers. Each is a long-lived per-target accumulator\n * fed by `signalWithStart`: it collects payloads then starts the target once, and `continueAsNew`s to\n * re-arm for the next burst. Signal buffering keeps the re-arm race-free. Registers its runners on\n * construction.\n */\nexport class EventAccumulators {\n constructor(private readonly host: AccumulatorHost) {\n host.register('__evt_debounce', '1', (ctx, input) => this.debounce(ctx, input));\n host.register('__evt_batch', '1', (ctx, input) => this.batch(ctx, input));\n }\n\n /** Route an `onEvent` payload into its target's debounce/batch accumulator. */\n route(target: string, config: EventBatchConfig, payload: unknown): Promise<{ runId: string }> {\n const [workflow, input] =\n config.mode === 'debounce'\n ? (['__evt_debounce', { target, windowMs: config.windowMs }] as const)\n : ([\n '__evt_batch',\n { target, maxSize: config.maxSize, windowMs: config.windowMs },\n ] as const);\n return this.host.signalWithStart(workflow, input, accToken(target), {\n token: accToken(target),\n payload,\n });\n }\n\n /** Fire the target with the LAST payload once events have been quiet for `windowMs`. */\n private async debounce(ctx: WorkflowCtx, input: unknown): Promise<unknown> {\n const { target, windowMs } = input as { target: string; windowMs: number };\n const token = accToken(target);\n let last = await ctx.waitForSignal(token); // park for the first event of a burst\n for (;;) {\n try {\n last = await ctx.waitForSignal(token, { timeoutMs: windowMs }); // extend on each event\n } catch (e) {\n if (e instanceof SignalTimeoutError) break; // quiet for `windowMs` → fire\n throw e; // WorkflowSuspended / ContinueAsNew etc. must propagate\n }\n }\n await ctx.startChild(target, last);\n return ctx.continueAsNew(input); // re-arm\n }\n\n /** Fire the target with all payloads (`{ events }`) once `maxSize` or `windowMs` from the first. */\n private async batch(ctx: WorkflowCtx, input: unknown): Promise<unknown> {\n const { target, maxSize, windowMs } = input as {\n target: string;\n maxSize: number;\n windowMs: number;\n };\n const token = accToken(target);\n const events: unknown[] = [await ctx.waitForSignal(token)]; // park for the first\n const deadline = (await ctx.now()) + windowMs;\n while (events.length < maxSize) {\n const remaining = deadline - (await ctx.now());\n if (remaining <= 0) break;\n try {\n events.push(await ctx.waitForSignal(token, { timeoutMs: remaining }));\n } catch (e) {\n if (e instanceof SignalTimeoutError) break; // window elapsed → fire what we have\n throw e; // WorkflowSuspended / ContinueAsNew etc. must propagate\n }\n }\n await ctx.startChild(target, { events });\n return ctx.continueAsNew(input); // re-arm\n }\n}\n","// Named events: pub/sub on top of the signal-waiter table. A `ctx.waitForEvent(name, { match })`\n// registers a signal waiter whose token encodes the event name + match criteria (base64 so they\n// never contain the `:` delimiter); `engine.publishEvent(name, payload)` lists the waiters for that\n// name by token prefix, checks each one's match against the payload, and signals the ones that pass.\n// No schema change beyond a `listSignalWaiters(prefix)` store method.\n\nconst enc = (s: string): string => Buffer.from(s, 'utf8').toString('base64');\nconst dec = (s: string): string => Buffer.from(s, 'base64').toString('utf8');\n\n/**\n * How many candidates a buffered-event scan considers (`listBufferedEvents(name, limit)`) before\n * giving up. An event's buffer is keyed by `name` only (see {@link eventMatches}'s match-based\n * consumption), so a hot name with many distinct payloads sitting unclaimed could in principle\n * accumulate an unbounded backlog; this caps the per-scan cost regardless. Shared by the workflow-ctx\n * consumer and the engine's reconcile sweep so both see the same window.\n */\nexport const EVENT_BUFFER_SCAN_LIMIT = 50;\n\n/** The literal prefix EVERY event-waiter token starts with, regardless of `name` — `eventPrefix(name)`\n * always begins with this; exported so a caller that only needs to CLASSIFY a token (not fan out a\n * specific name) doesn't have to re-derive or duplicate the literal (see run-waiting.ts's own copy,\n * kept in sync with this one, and engine.ts's reconcile sweep). */\nexport const EVENT_TOKEN_PREFIX = 'event:';\n\n/** Token prefix for every waiter on `name` — used by `listSignalWaiters` to fan an event out. */\nexport function eventPrefix(name: string): string {\n return `${EVENT_TOKEN_PREFIX}${enc(name)}:`;\n}\n\n/** Whether `token` is an event-waiter token (vs. a plain signal / child / webhook / breakpoint one). */\nexport function isEventToken(token: string): boolean {\n return token.startsWith(EVENT_TOKEN_PREFIX);\n}\n\n/** Build the unique waiter token for one `waitForEvent` call (name + match + run position). */\nexport function eventToken(\n name: string,\n match: Record<string, unknown> | undefined,\n runId: string,\n seq: number,\n): string {\n return `${eventPrefix(name)}${enc(JSON.stringify(match ?? {}))}:${runId}#${seq}`;\n}\n\n/** The event name embedded in an event waiter token (the 2nd `:`-segment is the base64 name), so a\n * dashboard can show \"waiting on event `<name>`\" instead of the opaque token. */\nexport function eventNameOf(token: string): string {\n try {\n return dec(token.split(':')[1] ?? '');\n } catch {\n return token;\n }\n}\n\n/** The match criteria embedded in an event waiter token (the 3rd `:`-segment is the base64 match). */\nexport function eventMatchOf(token: string): Record<string, unknown> {\n try {\n return JSON.parse(dec(token.split(':')[2] ?? '')) as Record<string, unknown>;\n } catch {\n return {};\n }\n}\n\n/** Whether `payload` satisfies a waiter's `match`: every match key deep-equals the payload's value. */\nexport function eventMatches(payload: unknown, match: Record<string, unknown>): boolean {\n const keys = Object.keys(match);\n if (keys.length === 0) return true; // no criteria → matches any payload of this name\n if (!payload || typeof payload !== 'object') return false;\n const p = payload as Record<string, unknown>;\n return keys.every((k) => JSON.stringify(p[k]) === JSON.stringify(match[k]));\n}\n","/**\n * Compute the worker group a tenant's run dispatches to. Mirrors the transport's\n * default-is-bare rule (unset/empty/`'default'` ⇒ bare): a\n * `tenant` of `undefined`, `''`, or `'default'` is the bare `baseGroup`, so a single-tenant\n * deployment (or the `'default'` tenant of a multi-tenant one) stays byte-identical to today.\n * Any other tenant suffixes the group as `<baseGroup>@<tenant>`, so an operator control plane\n * (namespace: undefined) can route each tenant's run to its own worker pool.\n */\nexport function tenantGroup(baseGroup: string, tenant: string | undefined): string {\n return tenant !== undefined && tenant !== '' && tenant !== 'default'\n ? `${baseGroup}@${tenant}`\n : baseGroup;\n}\n\n/**\n * Sanitize a handler/workflow name for use as a BullMQ queue token: BullMQ forbids `:` in queue\n * names (it uses the colon internally as a key separator), so every `:` is replaced with `-`. `.`\n * is legal in a BullMQ queue name and is left as-is — step/workflow names commonly use it as a\n * namespacing separator (e.g. `payments.charge-card`).\n */\nexport function sanitizeQueueToken(name: string): string {\n return name.replace(/:/g, '-');\n}\n","import type {\n HistoryEvent,\n Transport,\n WorkflowExecutor,\n WorkflowRun,\n WorkflowTask,\n} from './interfaces';\nimport { sanitizeQueueToken, tenantGroup } from './tenant-group';\n\n/**\n * A {@link WorkflowExecutor} backed by a {@link Transport}: it advances a remote workflow by\n * DISPATCHING a {@link WorkflowTask} over the broker under the ENGINE-SUPPLIED `taskId`, WITHOUT\n * awaiting the decision. Pass one to `engine.registerRemote(name, version, { group, executor })` so a\n * workflow authored in another SDK (e.g. the Python `durable-worker`) is driven over Redis/BullMQ.\n *\n * Routes by NAME, not a hand-declared group: the dispatched task's routing token is\n * `tenantGroup(sanitizeQueueToken(name), partition)` — the same formula a {@link import('./interfaces').StepDef}\n * uses — so `partition` is an optional isolation suffix, not a separate identity. Omit it to route by\n * the bare (sanitized) `name`.\n *\n * Multi-instance safe by construction: the executor holds NO in-memory state correlating a dispatched\n * turn to its decision. The engine records the `taskId` on the run as the awaited marker AND releases\n * the run's lease BEFORE calling `dispatch`, so the worker's {@link import('./interfaces').WorkflowDecision},\n * delivered over the transport's `onDecision` and applied DURABLY (by run id) on whatever engine\n * instance consumes it — even one that did not dispatch the turn — can never arrive ahead of its marker\n * or contend with a still-held lease and be dropped. A point-to-point broker can therefore hand the\n * decision to any instance without it being dropped (the bug this design fixes).\n *\n * Recovery-safe: if the engine crashes (or a decision is genuinely lost because the worker died), the\n * suspended turn's heartbeat-rearmed window (`remoteAdvanceSilenceMs`) lapses and the timer poller\n * re-dispatches a fresh task with the same history — the worker's replay is deterministic, so it\n * returns the same decision; a late decision for the old `taskId` no longer matches the run's\n * currently-awaited turn and is dropped.\n */\nexport class RemoteWorkflowExecutor implements WorkflowExecutor {\n constructor(\n private readonly transport: Transport,\n private readonly name: string,\n private readonly partition?: string | undefined,\n // Accepted for source compatibility; liveness now lives on the engine's suspended-turn window\n // (`remoteAdvanceSilenceMs`) + recovery re-drive, not an in-memory per-turn timeout.\n _opts: { timeoutMs?: number } = {},\n ) {}\n\n /**\n * Enqueue one workflow turn under the engine-supplied `taskId`. Does NOT await the decision — the\n * engine has already suspended the run on `taskId` and applies the decision durably via `onDecision`.\n */\n async dispatch(\n run: WorkflowRun,\n history: HistoryEvent[],\n taskId: string,\n pendingSignals?: WorkflowTask['pendingSignals'],\n ): Promise<void> {\n if (!this.transport.dispatchWorkflowTask) {\n throw new Error('transport does not support workflow tasks (dispatchWorkflowTask)');\n }\n const task: WorkflowTask = {\n taskId,\n runId: run.id,\n workflow: run.workflow,\n workflowVersion: run.workflowVersion,\n input: run.input,\n history,\n ...(pendingSignals ? { pendingSignals } : {}),\n group: tenantGroup(sanitizeQueueToken(this.name), this.partition),\n priority: run.priority,\n attempt: 1,\n };\n await this.transport.dispatchWorkflowTask(task);\n }\n}\n","import { EVENT_TOKEN_PREFIX, eventNameOf } from './events';\nimport type { RunWaiting, SignalWaiter, WorkflowRun } from './interfaces';\n\n// Waiter-token prefixes the engine stamps (see `workflow-ctx.ts`): a webhook mints `wh:<runId>:<seq>`,\n// an awaited child parks on `child:<id>`, a `ctx.breakpoint` mints `bp:<runId>:<seq>` (see\n// `breakpointToken` in `protocol.ts`), a named event on `event:<b64 name>:…`. A plain\n// `ctx.waitForSignal(name)` uses `name` verbatim as the token, so an unrecognised token IS the signal\n// name.\nconst WEBHOOK_PREFIX = 'wh:';\nconst CHILD_PREFIX = 'child:';\nconst BREAKPOINT_PREFIX = 'bp:';\nconst EVENT_PREFIX = EVENT_TOKEN_PREFIX;\n\n/**\n * Resolve WHAT a suspended run is parked on from the token of the {@link SignalWaiter} it registered.\n * The token prefix carries the kind — no extra store lookup and no new persisted field. Used by the\n * store-backed run gateway to stamp {@link RunWaiting} onto each listed run so the dashboard can name\n * the wait in a row without fetching that run's timeline.\n *\n * `ctx.breakpoint` reuses the signal-waiter machinery (`engine.continue` resumes it via `signal()`\n * like any other), so without this case it would fall through to the generic `signal` branch with the\n * raw `bp:<runId>:<seq>` token as its display name — a real bug. Named `'breakpoint'` here instead;\n * the token carries no separate label to recover cheaply (see {@link RunWaiting.name}).\n */\nexport function classifyWaiterToken(token: string): RunWaiting {\n if (token.startsWith(WEBHOOK_PREFIX)) return { on: 'webhook', name: token };\n if (token.startsWith(BREAKPOINT_PREFIX)) return { on: 'breakpoint', name: 'breakpoint' };\n if (token.startsWith(CHILD_PREFIX))\n return { on: 'child', name: token.slice(CHILD_PREFIX.length) };\n if (token.startsWith(EVENT_PREFIX)) return { on: 'signal', name: eventNameOf(token) };\n return { on: 'signal', name: token };\n}\n\n/**\n * Resolve a suspended run's {@link RunWaiting} from the pending signal waiters (indexed by `runId`).\n * Event-only by design (see {@link RunWaiting}): a `waitForSignal`/`waitForEvent`/webhook/awaited-child\n * suspend registers a waiter and gets named here; every other suspend (a bare `ctx.sleep`, an in-flight\n * remote step, a reconcile-parked orphan) returns `undefined`, so the client layers its own display\n * state (no-worker, singleton, running) on top — none of which can be told apart from `wakeAt` alone.\n */\nexport function resolveRunWaiting(\n run: WorkflowRun,\n waiterByRun: ReadonlyMap<string, SignalWaiter>,\n): RunWaiting | undefined {\n if (run.status !== 'suspended') return undefined;\n const waiter = waiterByRun.get(run.id);\n return waiter ? classifyWaiterToken(waiter.token) : undefined;\n}\n\n/** Index signal waiters by `runId`, keeping the first seen per run (a run parks on one waiter at a\n * time in the sequential case; the earliest is the one it's blocked on). */\nexport function indexWaitersByRun(waiters: readonly SignalWaiter[]): Map<string, SignalWaiter> {\n const byRun = new Map<string, SignalWaiter>();\n for (const w of waiters) if (!byRun.has(w.runId)) byRun.set(w.runId, w);\n return byRun;\n}\n","import type { SingletonConfig } from './engine';\nimport { SingletonQueueFullError } from './errors';\nimport type { StateStore, WorkflowRun } from './interfaces';\n\nconst SINGLETON_RETRY_MS = 1000;\n/**\n * Max jitter (ms, each direction) added to {@link SINGLETON_RETRY_MS} so a queue of N gated runs\n * doesn't wake in lockstep and stampede the admission scan. Each retry picks an independent offset\n * in `[-SINGLETON_RETRY_JITTER_MS, +SINGLETON_RETRY_JITTER_MS]`.\n */\nconst SINGLETON_RETRY_JITTER_MS = 250;\n\nexport interface SingletonGateDeps {\n store: Pick<StateStore, 'listRuns' | 'updateRun'>;\n clock: () => number;\n /** Hand a gated run to the run dispatcher (fire-and-forget, like the engine's other dispatches). */\n dispatch: (runId: string) => void;\n /** Resolve a settled run's singleton config from the engine's workflow registry. */\n configFor: (run: WorkflowRun) => SingletonConfig | undefined;\n}\n\n/**\n * Per-key serialization for singleton workflows — start-time back-pressure, FIFO race-free\n * admission, and notify-on-release wakeups. Extracted from {@link WorkflowEngine} so the whole\n * singleton feature lives in one place instead of being smeared across `start`, `execute`, both run\n * loops, and `cancel`.\n */\nexport class SingletonGate {\n constructor(private readonly deps: SingletonGateDeps) {}\n\n /** The tag a singleton run carries, so the gate can find others sharing its key. */\n tag(cfg: SingletonConfig, input: unknown): string {\n return `singleton:${cfg.key(input)}`;\n }\n\n /** Next wake time for a gated run: the base retry delay jittered to avoid a wakeup stampede. */\n retryWakeAt(): number {\n return (\n this.deps.clock() +\n SINGLETON_RETRY_MS +\n Math.floor((Math.random() * 2 - 1) * SINGLETON_RETRY_JITTER_MS)\n );\n }\n\n /**\n * Reject a start that would grow the same-key backlog past `limit + maxQueueDepth` (counting\n * `pending`/`running`/`suspended` runs sharing the key in one scan). No-op when no `maxQueueDepth`\n * is configured.\n */\n async assertCapacity(workflow: string, cfg: SingletonConfig, input: unknown): Promise<void> {\n if (cfg.maxQueueDepth == null) return;\n const cap = (cfg.limit ?? 1) + cfg.maxQueueDepth;\n const queued = await this.deps.store.listRuns({\n tag: this.tag(cfg, input),\n workflow,\n statuses: ['pending', 'running', 'suspended', 'cancelling'],\n });\n if (queued.length >= cap) {\n throw new SingletonQueueFullError(workflow, cfg.key(input), cfg.maxQueueDepth);\n }\n }\n\n /**\n * Whether `run` may run now under its key: it's among the `limit` oldest in-flight (running or\n * suspended) runs sharing the key, by `(createdAt, id)` order. A consistent store gives every\n * instance the same ordering, so admission is race-free + FIFO.\n */\n async admit(run: WorkflowRun, cfg: SingletonConfig): Promise<boolean> {\n // ONE scan for both in-flight statuses; the total `(createdAt, id)` sort makes admission order\n // independent of the store's row order, preserving the FIFO + race-free-across-instances contract.\n const inflight = (\n await this.deps.store.listRuns({\n tag: this.tag(cfg, run.input),\n workflow: run.workflow,\n statuses: ['running', 'suspended', 'cancelling'],\n })\n ).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id));\n const idx = inflight.findIndex((r) => r.id === run.id);\n return idx >= 0 && idx < (cfg.limit ?? 1);\n }\n\n /**\n * Notify-on-release: a singleton run settled (freeing a slot), so dispatch the oldest gated\n * (`suspended` + same tag) waiters now instead of waiting for their ~1s retry timer. Each re-checks\n * admission in the executor and runs only if it actually wins a slot, so FIFO/race-free guarantees\n * hold; the durable timer remains the cross-instance/crash fallback.\n */\n async wakeNext(settled: WorkflowRun): Promise<void> {\n const cfg = this.deps.configFor(settled);\n if (!cfg) return;\n const tag = settled.tags?.find((t) => t.startsWith('singleton:'));\n if (!tag) return;\n const gated = (\n await this.deps.store.listRuns({ tag, workflow: settled.workflow, statuses: ['suspended'] })\n ).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id));\n for (const next of gated.slice(0, cfg.limit ?? 1)) {\n // Clear the durable retry timer as we hand the run over, so the timer poller can't also pick it\n // up and double-dispatch. Only for runs that carry a wakeAt; dispatch after the clear commits.\n if (next.wakeAt != null) {\n await this.deps.store\n .updateRun(next.id, { wakeAt: undefined, updatedAt: new Date() })\n .catch(() => undefined);\n }\n this.deps.dispatch(next.id);\n }\n }\n}\n","import type {\n GroupHealth,\n Heartbeat,\n NamedTransport,\n RemoteTask,\n StartRunMessage,\n StepResult,\n Transport,\n WorkflowDecision,\n WorkflowStepEvent,\n} from './interfaces';\n\n/**\n * An ordered pool of named transports. The engine dispatches on the first and fails over to the\n * next on a dispatch error; a step can pin one by id. Pure transport plumbing — no run lifecycle —\n * so it lives apart from the engine.\n */\nexport class TransportPool {\n constructor(private readonly transports: NamedTransport[]) {}\n\n get size(): number {\n return this.transports.length;\n }\n\n /**\n * The primary (first) transport — the one `dispatch` prefers when no `preferId` is pinned. A\n * {@link RemoteWorkflowExecutor} built by `engine.remote()` rides it (it needs a single\n * `dispatchWorkflowTask`/`onDecision` Transport, not the whole failover pool). Throws if the pool\n * is empty — there is nothing to dispatch a remote workflow over.\n */\n get primary(): Transport {\n const first = this.transports[0];\n if (!first) {\n throw new Error(\n 'no transport configured — engine.remote() needs a transport (or transports)',\n );\n }\n return first.transport;\n }\n\n /** Register the engine's result/heartbeat/step-event handlers on EVERY transport — a result can come\n * back on whichever one delivered the task, so failover stays symmetric. `onStepEvent` is wired only\n * on transports that carry streamed workflow step lifecycle (BullMQ); others simply skip it. */\n bind(\n onResult: (result: StepResult) => Promise<void>,\n onHeartbeat: (beat: Heartbeat) => Promise<void>,\n onStepEvent?: (event: WorkflowStepEvent) => Promise<void>,\n onDecision?: (decision: WorkflowDecision) => Promise<void>,\n ): void {\n for (const { transport } of this.transports) {\n transport.onResult(onResult);\n transport.onHeartbeat(onHeartbeat);\n if (onStepEvent && transport.onStepEvent) {\n transport.onStepEvent(onStepEvent);\n }\n // A workflow-turn decision can come back on whichever transport carried the task — and on\n // whichever ENGINE INSTANCE consumes it (point-to-point), which may NOT be the dispatcher. The\n // engine applies it durably by run id, so binding it here (like onResult) is multi-instance safe.\n if (onDecision && transport.onDecision) {\n transport.onDecision(onDecision);\n }\n }\n }\n\n /**\n * Dispatch `task` over the pool: try the preferred (or first) transport, fail over to the next on\n * a dispatch error, and stamp the task with the id of the transport that accepted it (so a worker\n * replies on the matching one). Throws if every transport fails.\n */\n async dispatch(task: Omit<RemoteTask, 'transport'>, preferId?: string): Promise<void> {\n let lastErr: unknown;\n for (const { id, transport } of this.ordered(preferId)) {\n try {\n await transport.dispatch({ ...task, transport: id });\n return;\n } catch (err) {\n lastErr = err;\n }\n }\n throw lastErr ?? new Error('no transport accepted the dispatch');\n }\n\n /** Worker-health for `group`, merged across every transport that can report it (a group's queue\n * and its workers may live on any pinned transport). Undefined when no transport implements\n * `groupHealth` (e.g. a pure in-process transport — nothing to introspect). */\n async groupHealth(group: string): Promise<GroupHealth | undefined> {\n const reports: GroupHealth[] = [];\n for (const { transport } of this.transports) {\n if (transport.groupHealth) reports.push(await transport.groupHealth(group));\n }\n if (reports.length === 0) return undefined;\n return {\n group,\n depth: reports.reduce((sum, r) => sum + r.depth, 0),\n liveWorkers: reports.flatMap((r) => r.liveWorkers),\n };\n }\n\n /**\n * Register a control-plane `start-run` consumer on every transport that carries the channel. Only\n * control-plane-side transports implement {@link Transport.onStartRun}; a transport without it is\n * skipped, so a plain worker/in-process pool is a no-op. Mirrors {@link bind}'s per-transport wiring.\n */\n onStartRun(handler: (msg: StartRunMessage) => Promise<void>): void {\n for (const { transport } of this.transports) {\n transport.onStartRun?.(handler);\n }\n }\n\n /** Distinct worker groups with a live heartbeat, merged across every transport that can report it. */\n async listWorkerGroups(): Promise<string[]> {\n const groups = new Set<string>();\n for (const { transport } of this.transports) {\n if (transport.listWorkerGroups) {\n for (const g of await transport.listWorkerGroups()) groups.add(g);\n }\n }\n return [...groups];\n }\n\n /**\n * The first transport (in pool order) reporting a LIVE heartbeat for `group` — the one a\n * convention-routed remote workflow must dispatch on. In a mixed pool (e.g. a tenant-scoped\n * control plane pairing its namespaced transport with a bare-prefix one for operator-convention\n * tenant workers), each transport sees a DIFFERENT keyspace: dispatching on `primary` while the\n * live worker heartbeats on another transport parks the task on a queue nobody consumes. Returns\n * `undefined` when no transport reports the group (mirrors the merged `listWorkerGroups` miss).\n */\n async transportWithLiveGroup(group: string): Promise<Transport | undefined> {\n for (const { transport } of this.transports) {\n if (!transport.listWorkerGroups) continue;\n if ((await transport.listWorkerGroups()).includes(group)) return transport;\n }\n return undefined;\n }\n\n /** Pinned `preferId` first, then the rest (failover order). */\n private ordered(preferId?: string): NamedTransport[] {\n if (!preferId) return this.transports;\n const pref = this.transports.filter((t) => t.id === preferId);\n if (pref.length === 0) throw new Error(`transport \"${preferId}\" is not registered`);\n return [...pref, ...this.transports.filter((t) => t.id !== preferId)];\n }\n}\n","import { FatalError } from './errors';\n\n/**\n * The payload an external `ctx.task` / child run delivers back on its completion signal: either a\n * value or a failure. One typed envelope so `task` and `child` share the same unwrap (instead of\n * sniffing ad-hoc `__error` keys).\n */\nexport type Completion<T> = { ok: true; value: T } | { ok: false; error: string };\n\n/** Read a `Completion` from a signal payload: return the value, or throw a FatalError if it failed. */\nexport function unwrapCompletion<T>(payload: unknown, label: string): T {\n const c = payload as Completion<T> | null;\n if (c && typeof c === 'object' && 'ok' in c && c.ok === false) {\n throw new FatalError(`${label} failed: ${c.error}`);\n }\n return (c as { value: T } | null)?.value as T;\n}\n","/**\n * Cross-package step-name stamp. The `@Step` decorator (`@dudousxd/nestjs-durable`) writes a\n * method's derived routing name under this key; core's `ctx.step` reads it (via {@link stepNameOf})\n * to route a method-reference call to the same handler a worker registers by name.\n *\n * `Symbol.for` (the GLOBAL registry), NOT a plain `Symbol()` — so a duplicate copy of this module\n * (pnpm peer-dependency multiplexing, or a dual ESM/CJS load) still reads the SAME key. A plain\n * `Symbol()` would mint a distinct token per copy, so a decorator running against one core instance\n * could stamp a name core's `ctx.step` (a different instance) can never read back. Mirrors the\n * `STATE_STORE` token fix in `./tokens.ts`.\n */\nexport const DURABLE_STEP_NAME = Symbol.for('durable.step.name');\n\n/**\n * Cross-package step-DISPATCH-POLICY stamp. `@Step({ retries, backoff, backoffMs, backoffMaxMs,\n * jitter, timeoutMs })` (`@dudousxd/nestjs-durable`) writes the def-level durable-retry/liveness\n * policy under this key; core's `ctx.step` reads it (via {@link stepConfigOf}) and merges it with any\n * per-call {@link StepDispatchOpts} override to build the dispatched {@link StepDef}. Same\n * `Symbol.for` rationale as {@link DURABLE_STEP_NAME} — a duplicate copy of this module (pnpm\n * peer-dependency multiplexing, dual ESM/CJS) must still read back the SAME key.\n */\nexport const DURABLE_STEP_CONFIG = Symbol.for('durable.step.config');\n\n/**\n * The def-level durable-dispatch policy a `@Step(...)` can stamp on a method: retry/backoff and the\n * remote-liveness `timeoutMs` — the dispatch-relevant subset of the engine's `StepOptions`. Read off\n * a handler reference via {@link stepConfigOf}; a per-call {@link StepDispatchOpts} passed to\n * `ctx.step(ref, input, opts)` overrides these field-by-field.\n */\nexport interface StepConfig {\n /** Max attempts before the step (and run) fails. */\n retries?: number | undefined;\n /** How the delay between retries grows: `fixed` (constant) or `exp` (doubles each attempt). */\n backoff?: 'fixed' | 'exp' | undefined;\n /** Base delay in ms between retries. Omit (or 0) to retry with no delay. */\n backoffMs?: number | undefined;\n /** Upper bound on the (exponential) backoff delay. */\n backoffMaxMs?: number | undefined;\n /** Add random jitter (50–100% of the computed delay) to avoid thundering-herd retries. */\n jitter?: boolean | undefined;\n /** Liveness window for the dispatched step: no result/heartbeat within this many ms presumes the\n * worker dead and fails the dispatch with a `RemoteStepTimeout` (retryable — re-dispatches per\n * `retries`). Omit to wait indefinitely. */\n timeoutMs?: number | undefined;\n}\n\nfunction isStepConfig(value: unknown): value is StepConfig {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * A method carrying its `@Step`-stamped routing name (and, optionally, its dispatch policy).\n * `ctx.step(ref, input)` reads the name via {@link stepNameOf} — the reference itself is never\n * invoked directly by the caller's process (the worker serving that name re-resolves the real\n * handler from DI), so an unbound `this` on `ref` is irrelevant; `ref` is purely a typed,\n * refactor-safe handle onto the stamped name (and policy).\n */\nexport type StepRef<TInput = unknown, TOutput = unknown> = ((\n input: TInput,\n) => Promise<TOutput> | TOutput) & {\n [DURABLE_STEP_NAME]?: string | undefined;\n [DURABLE_STEP_CONFIG]?: StepConfig | undefined;\n};\n\n/** Read the `@Step`-stamped routing name off a function ref. `undefined` for anything unstamped\n * (including a plain string — {@link stepNameOf} only reads function refs; a caller passing a\n * string already has the routing name and dispatches it directly). */\nexport function stepNameOf(ref: unknown): string | undefined {\n if (typeof ref !== 'function') return undefined;\n const stamped = (ref as { [DURABLE_STEP_NAME]?: unknown })[DURABLE_STEP_NAME];\n return typeof stamped === 'string' ? stamped : undefined;\n}\n\n/** Read the `@Step`-stamped dispatch policy off a function ref. `undefined` for anything unstamped\n * (including a plain string — a cross-runtime string-name call has no def-level policy to read; pass\n * it via {@link StepDispatchOpts} instead). */\nexport function stepConfigOf(ref: unknown): StepConfig | undefined {\n if (typeof ref !== 'function') return undefined;\n const stamped = (ref as { [DURABLE_STEP_CONFIG]?: unknown })[DURABLE_STEP_CONFIG];\n return isStepConfig(stamped) ? stamped : undefined;\n}\n","import { backoffDelay } from './backoff';\nimport { instantCheckpoint } from './checkpoints';\nimport { unwrapCompletion } from './completion';\nimport { parseDuration } from './duration';\nimport {\n ContinueAsNew,\n FatalError,\n GatherError,\n NonDeterminismError,\n SignalTimeoutError,\n WorkflowSuspended,\n} from './errors';\nimport { EVENT_BUFFER_SCAN_LIMIT, eventMatches, eventToken } from './events';\nimport type {\n ChildCallOptions,\n DurableWebhook,\n SearchAttributes,\n SearchAttributesSchema,\n StateStore,\n StepCheckpoint,\n StepDef,\n StepDispatchOpts,\n StepError,\n StepEvent,\n StepInvocation,\n StepKind,\n StepLogger,\n StepOptions,\n StepUndo,\n WorkflowCtx,\n} from './interfaces';\nimport { breakpointToken } from './protocol';\nimport { createStepLogger } from './step-logger';\nimport { type StepConfig, type StepRef, stepConfigOf, stepNameOf } from './step-name-symbol';\nimport { type WorkflowRef, workflowName } from './workflow-ref';\n\n/** Normalize the `ctx.child`/`ctx.startChild` 3rd arg: a bare string is shorthand for `{ childId }`. */\nfunction normalizeChildOptions(options?: string | ChildCallOptions): ChildCallOptions {\n return typeof options === 'string' ? { childId: options } : (options ?? {});\n}\n\n/** Render a Standard Schema issue `path` (a mix of raw keys and `{ key }` segments) as a dotted\n * string, for a `searchAttributes` validation error — `['amount']` → `'amount'`, `[]`/`undefined` →\n * `'(root)'` (the merged object itself failed, not one of its keys). */\nfunction formatIssuePath(\n path: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }> | undefined,\n): string {\n if (!path || path.length === 0) return '(root)';\n return path\n .map((segment) => String(typeof segment === 'object' ? segment.key : segment))\n .join('.');\n}\n\n/**\n * Merge a `@Step`-declared {@link StepConfig} with a per-call {@link StepDispatchOpts} override into\n * the dispatch-relevant `StepOptions` subset of a {@link StepDef} (`retries`/`backoff`/`backoffMs`/\n * `backoffMaxMs`/`jitter`/`timeoutMs`), `opts` winning field-by-field. Omits every field neither side\n * set — required under `exactOptionalPropertyTypes` (an explicit `undefined` value is a type error).\n */\nfunction resolveStepPolicy(\n config: StepConfig | undefined,\n opts: StepDispatchOpts | undefined,\n): StepOptions {\n const policy: StepOptions = {};\n const retries = opts?.retries ?? config?.retries;\n if (retries !== undefined) policy.retries = retries;\n const backoff = opts?.backoff ?? config?.backoff;\n if (backoff !== undefined) policy.backoff = backoff;\n const backoffMs = opts?.backoffMs ?? config?.backoffMs;\n if (backoffMs !== undefined) policy.backoffMs = backoffMs;\n const backoffMaxMs = opts?.backoffMaxMs ?? config?.backoffMaxMs;\n if (backoffMaxMs !== undefined) policy.backoffMaxMs = backoffMaxMs;\n const jitter = opts?.jitter ?? config?.jitter;\n if (jitter !== undefined) policy.jitter = jitter;\n const timeoutMs = opts?.timeoutMs ?? config?.timeoutMs;\n if (timeoutMs !== undefined) policy.timeoutMs = timeoutMs;\n return policy;\n}\n\n/**\n * A saga undo registered by a completed step, kept with its step name for visibility on failure.\n * Two shapes, pushed onto the SAME `compensations` stack so the engine unwinds them together in one\n * strict reverse-completion order, regardless of which kind each one is:\n * - `fn`: a LOCAL undo (`ctx.localStep`'s `compensate` closure) — run in-process.\n * - `dispatch`: a DISPATCHED undo (`ctx.step`'s `compensate` ref/string) — an ordinary `@Step` def\n * the engine dispatches to a worker at unwind time, called with the `StepUndo` envelope (`args`).\n */\nexport type Compensation =\n | { name: string; fn: () => Promise<void> }\n | {\n name: string;\n dispatch: {\n def: StepDef<StepUndo<unknown, unknown>, unknown>;\n args: StepUndo<unknown, unknown>;\n };\n };\n\n/** A finished local step the host should checkpoint and announce (completed or failed). */\nexport interface StepRecord {\n runId: string;\n seq: number;\n name: string;\n kind: StepKind;\n input?: unknown;\n events?: StepEvent[] | undefined;\n attempts: number;\n enqueuedAt: Date;\n startedAt: Date;\n workerGroup?: string | undefined;\n}\n\n/**\n * The narrow surface {@link createWorkflowCtx} needs from the engine — the seam between the\n * authoring API (this module) and the orchestrator (the engine owns lifecycle: emitting events,\n * suspending/resuming runs, dispatching remote steps).\n */\nexport interface CtxHost {\n readonly store: StateStore;\n /**\n * Per-execution checkpoint snapshot, loaded ONCE at execution start (the completed prefix this\n * replay walks). Lets each primitive read the prefix from memory instead of a per-call DB SELECT\n * (the O(N²) replay-reads fix). A seq ABSENT from the map is NOT cached — the primitive falls back\n * to the live store, so the checkpoint this resume is waking on (signal/timer/child, written after\n * the snapshot) is always read fresh. New checkpoints written during this execution are inserted\n * into the map so any later same-execution read sees them. Undefined ⇒ always hit the store.\n */\n readonly replay?: Map<number, StepCheckpoint> | undefined;\n clock(): number;\n webhookUrl?: ((token: string) => string) | undefined;\n /** Mark a local step's body as started — emits `step.started` and (optionally) a `running` checkpoint. */\n startStep(step: StepRecord): Promise<void>;\n completeStep(step: StepRecord & { output: unknown }): Promise<void>;\n failStep(step: StepRecord & { error: StepError }): Promise<void>;\n callRemote<TInput, TOutput>(\n runId: string,\n seq: number,\n step: StepDef<TInput, TOutput>,\n input: TInput,\n queue?: string,\n transport?: string,\n admission?: { priority?: number | undefined; fairnessKey?: string | undefined },\n ): Promise<TOutput>;\n /** Start a child run once, deferred so it can't reentrantly resume a still-running parent. */\n startChild(workflow: string, input: unknown, id: string, priority?: number): void;\n /**\n * Best-effort cancel of a child run — deferred for the SAME reason as `startChild` (so ctx code\n * can't reentrantly mutate engine state while the parent's own step is still executing\n * synchronously). Plain cancel, no saga undo; used by `ctx.all`'s `failFast` mode to stop the\n * surviving siblings once one has failed. Cancelling an already-terminal/cancelled run is a no-op\n * (`engine.cancel`'s own idempotency guard), so a replay that re-issues the same calls is safe.\n * Optional: hosts that never construct a `ctx.all` failFast call (e.g. test fakes) can omit it.\n */\n cancelChild?(childId: string): void;\n /** Shallow-merge `attrs` into the run's `searchAttributes` (see {@link WorkflowCtx.upsertSearchAttributes}). */\n upsertSearchAttributes(runId: string, attrs: SearchAttributes): Promise<void>;\n /** Deliver an op to a durable entity (deferred), optionally with a `reply` token for the result. */\n signalEntity?(name: string, key: string, op: string, arg: unknown, reply?: string): void;\n /** Run a local step body through the registered step interceptors (identity if none). */\n interceptStep?<T>(invocation: StepInvocation, body: () => Promise<T>): Promise<T>;\n}\n\n/** The per-run logical position counter. `rewind()` gives a position back (see `ctx.patched`). */\nclass Position {\n private seq = -1;\n next(): number {\n this.seq += 1;\n return this.seq;\n }\n rewind(): void {\n this.seq -= 1;\n }\n}\n\n/**\n * Back-compat alias of {@link WorkflowCtx}. `localStep` — the checkpointed in-process step primitive\n * used for saga compensation — is now part of the public {@link WorkflowCtx}, so this type adds\n * nothing; it is kept only so internal consumers (the durable-entity runner) keep compiling.\n */\nexport type InternalWorkflowCtx = WorkflowCtx;\n\n/**\n * Build the {@link WorkflowCtx} handed to a workflow body. Every primitive is a closure over the\n * position counter (the per-run logical position) and the saga `compensations` stack, so `task`/\n * `child` compose `step`/`waitForSignal` directly. All durability goes through {@link CtxHost}, so\n * the workflow body stays deterministic.\n */\nexport function createWorkflowCtx(\n host: CtxHost,\n runId: string,\n compensations: Compensation[],\n workflow = '',\n searchAttributesSchema?: SearchAttributesSchema,\n): InternalWorkflowCtx {\n const { store, replay } = host;\n const pos = new Position();\n\n // Read the checkpoint at `seq`: from the per-execution snapshot when present (no DB round-trip),\n // otherwise from the live store. Absence in the snapshot means \"written after the snapshot\" (the\n // signal/timer/child this resume wakes on, or nothing yet) — those MUST hit the store. Identical\n // behaviour to a raw `store.getCheckpoint`, just memoized for the completed prefix.\n const readCheckpoint = (seq: number): Promise<StepCheckpoint | null> | StepCheckpoint => {\n const hit = replay?.get(seq);\n if (hit !== undefined) return hit;\n return store.getCheckpoint(runId, seq);\n };\n\n // Persist a checkpoint AND reflect it in the snapshot, so a later same-execution read of this seq\n // (e.g. a re-read within the same call) sees it instead of falling back to the store.\n const writeCheckpoint = async (cp: StepCheckpoint): Promise<void> => {\n await store.saveCheckpoint(cp);\n replay?.set(cp.seq, cp);\n };\n\n // The in-process local-step runner: checkpointed, replayed, retried. No longer publicly exposed as\n // `ctx.step` (that name is now the ALWAYS-dispatched form below) — this backs the library's own\n // internal primitives that need a checkpointed in-process body: `ctx.task`'s dispatch step and the\n // deterministic capture helpers `ctx.now`/`ctx.sideEffect`.\n const localStep = async <T>(\n name: string,\n fn: (log: StepLogger) => Promise<T>,\n options?: StepOptions,\n ): Promise<T> => {\n const current = pos.next();\n const existing = await readCheckpoint(current);\n if (existing && existing.name !== name) {\n throw new NonDeterminismError(runId, current, name, existing.name);\n }\n if (existing && existing.status === 'completed') {\n // Register the compensation on replay too, so a saga undoes ALL completed steps — even\n // those done in an earlier (since-suspended) pass — not just the ones run this pass.\n if (options?.compensate) compensations.push({ name, fn: options.compensate });\n return existing.output as T;\n }\n const maxAttempts = Math.max(1, options?.retries ?? 1);\n const startedAt = new Date();\n // Announce the body has begun (and, when enabled, checkpoint it `running`) so the step is\n // visible in flight — not only once it settles. Skipped on replay: a completed step returns\n // above before reaching here, so this fires once, when the body actually first runs.\n await host.startStep({\n runId,\n seq: current,\n name,\n kind: 'local',\n attempts: 1,\n enqueuedAt: startedAt,\n startedAt,\n });\n for (let attempt = 1; ; attempt += 1) {\n // Events are scoped per attempt — a retry starts a clean log, so the checkpoint reflects\n // only the attempt that actually completed (or the final failing one).\n const events: StepEvent[] = [];\n try {\n const invocation: StepInvocation = {\n runId,\n workflow,\n stepName: name,\n seq: current,\n attempt,\n };\n const body = () => fn(createStepLogger(events, host.clock));\n const output = host.interceptStep\n ? await host.interceptStep(invocation, body)\n : await body();\n await host.completeStep({\n runId,\n seq: current,\n name,\n kind: 'local',\n output,\n events,\n attempts: attempt,\n enqueuedAt: startedAt,\n startedAt,\n });\n if (options?.compensate) compensations.push({ name, fn: options.compensate });\n return output;\n } catch (err) {\n if (err instanceof FatalError || attempt >= maxAttempts) {\n await host.failStep({\n runId,\n seq: current,\n name,\n kind: 'local',\n error: {\n message: err instanceof Error ? err.message : String(err),\n stack: err instanceof Error ? err.stack : undefined,\n },\n events,\n attempts: attempt,\n enqueuedAt: startedAt,\n startedAt,\n });\n throw err;\n }\n // Wait out the backoff before the next attempt (no-op when backoffMs is unset).\n const wait = backoffDelay(attempt, options);\n if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));\n }\n }\n };\n\n // Exactly-once DB step: run the body and write the step checkpoint in ONE store transaction, so the\n // business write commits atomically with the \"done\" marker (a plain step checkpoints AFTER the body,\n // so a crash in between re-runs it). Replay returns the recorded output without re-running.\n const transaction = async <T>(name: string, fn: (tx: unknown) => Promise<T>): Promise<T> => {\n if (!store.transaction) {\n throw new Error(\n 'ctx.transaction needs a store that supports transactions (the SQL adapters do). Use ctx.step for non-transactional work.',\n );\n }\n const current = pos.next();\n const existing = await readCheckpoint(current);\n if (existing && existing.name !== name) {\n throw new NonDeterminismError(runId, current, name, existing.name);\n }\n if (existing && existing.status === 'completed') return existing.output as T;\n return store.transaction(async (tx) => {\n const output = await fn(tx.raw);\n const cp = instantCheckpoint({ runId, seq: current, name, kind: 'local', output });\n await tx.saveCheckpoint(cp);\n // Reflect the committed checkpoint in the snapshot, keeping the writeback invariant uniform.\n replay?.set(current, cp);\n return output;\n });\n };\n\n // Shared by sleep / sleepUntil: record a durable timer at this position and suspend until `wakeAt`\n // (epoch ms). The wakeAt is computed by the caller — but only used on the first run; on replay the\n // recorded checkpoint's wakeAt wins, so a clock change can't shift an already-scheduled timer.\n const suspendUntil = async (wakeAt: () => number): Promise<void> => {\n const current = pos.next();\n const now = host.clock();\n const existing = await readCheckpoint(current);\n if (existing) {\n // Timer already recorded: resume if due, otherwise re-suspend cheaply.\n if (now >= (existing.wakeAt ?? 0)) return;\n throw new WorkflowSuspended(existing.wakeAt ?? now);\n }\n const at = wakeAt();\n await writeCheckpoint(\n instantCheckpoint({ runId, seq: current, name: 'sleep', kind: 'sleep', wakeAt: at }),\n );\n throw new WorkflowSuspended(at);\n };\n\n const sleep = (duration: string | number): Promise<void> =>\n suspendUntil(() => host.clock() + parseDuration(duration));\n\n const sleepUntil = (when: Date | number): Promise<void> =>\n suspendUntil(() => (typeof when === 'number' ? when : when.getTime()));\n\n // End this run and hand off to a fresh execution (clean history) with the new input. Terminal —\n // it always throws, so any code after it in the workflow is unreachable.\n const continueAsNew = (input?: unknown): Promise<never> => {\n throw new ContinueAsNew(input);\n };\n\n // NOTE (determinism): a bounded wait consumes TWO logical positions (deadline + wait), an\n // unbounded one consumes ONE. So adding or removing `{ timeoutMs }` on an existing `waitForSignal`\n // shifts the seq of every later step — treat it as a workflow-version change for in-flight runs.\n // Consume a buffered signal (one delivered before this run was waiting), recording it as the\n // signal checkpoint at `seq` so it resumes immediately instead of suspending. Replay-safe: the\n // checkpoint makes the consumption deterministic.\n const consumeBuffered = async <T>(token: string, seq: number): Promise<{ value: T } | null> => {\n const buffered = await store.takeBufferedSignal(token);\n if (!buffered) return null;\n await writeCheckpoint(\n instantCheckpoint({\n runId,\n seq,\n name: `signal:${token}`,\n kind: 'signal',\n output: buffered.payload,\n }),\n );\n return { value: buffered.payload as T };\n };\n\n // Consume a buffered EVENT matching `match` (one published with no live waiter — see\n // engine.publishEvent's buffering), recording it as the resolving `signal:<token>` checkpoint at\n // `seq` so replay is deterministic — the event analog of `consumeBuffered` above, but match-aware:\n // an event's buffer is keyed by NAME only (many waiters can share a name with different `match`\n // criteria), so consumption scans the oldest candidates and evaluates each one's match HERE — the\n // match predicate belongs to the WAITER, never the store (see events.ts / interfaces.ts). A hit\n // atomically claims that one row via `removeBufferedEvent`'s boolean return, which arbitrates a\n // concurrent claim (notably engine.publishEvent's own late re-check reaching the same row first —\n // see the wiring in engine.ts); losing that race tries the NEXT oldest candidate instead of giving\n // up, so a later non-matching buffered event never blocks an earlier matching one behind it.\n const consumeBufferedEvent = async <T>(\n name: string,\n match: Record<string, unknown> | undefined,\n token: string,\n seq: number,\n ): Promise<{ value: T } | null> => {\n const candidates = await store.listBufferedEvents(name, EVENT_BUFFER_SCAN_LIMIT);\n for (const candidate of candidates) {\n if (!eventMatches(candidate.payload, match ?? {})) continue;\n if (!(await store.removeBufferedEvent(candidate.id))) continue; // raced away — try the next\n // Resolved it ourselves — remove OUR OWN waiter row via the exact match (not\n // `takeSignalWaiter(token)`; harmless here since an event token is unique per call, but exact\n // removal keeps this symmetric with the signal-side precedent in `waitForSignal` above).\n await store.removeSignalWaiter({ token, runId, seq });\n await writeCheckpoint(\n instantCheckpoint({\n runId,\n seq,\n name: `signal:${token}`,\n kind: 'signal',\n output: candidate.payload,\n }),\n );\n return { value: candidate.payload as T };\n }\n return null;\n };\n\n // Durably stamp the deadline for a BOUNDED wait, ONCE: the first run computes `clock() + timeoutMs`\n // and records it as a timer checkpoint at `deadlineSeq`; every later replay reads the SAME recorded\n // `wakeAt` back instead of recomputing it — so a slow replay (or a clock that moved between the\n // original run and the replay) can never shift an already-scheduled deadline. `label` only affects\n // the checkpoint's `name` (cosmetic, for the dashboard timeline) — the shared mechanic behind every\n // bounded-wait primitive (`waitForSignal`, `waitForEvent`, `DurableWebhook.wait`).\n const stampDeadline = async (\n deadlineSeq: number,\n label: string,\n timeoutMs: number,\n ): Promise<number> => {\n const recorded = await readCheckpoint(deadlineSeq);\n const deadline = recorded?.wakeAt ?? host.clock() + timeoutMs;\n if (!recorded) {\n await writeCheckpoint(\n instantCheckpoint({\n runId,\n seq: deadlineSeq,\n name: `timeout:${label}`,\n kind: 'sleep',\n wakeAt: deadline,\n }),\n );\n }\n return deadline;\n };\n\n const waitForSignal = async <T>(token: string, opts?: { timeoutMs?: number }): Promise<T> => {\n if (opts?.timeoutMs == null) {\n const current = pos.next();\n const existing = await readCheckpoint(current);\n if (existing && existing.status === 'completed') return existing.output as T;\n const buffered = await consumeBuffered<T>(token, current);\n if (buffered) return buffered.value;\n // Register, THEN check the buffer again before suspending — closes the lost-wake window\n // between the check above and this registration: a signal delivered in that sliver found no\n // waiter (we hadn't registered yet) and no buffer either by the time IT checked, so it buffered\n // the payload; without this re-check we'd suspend with the payload sitting unpaired forever.\n // (Registering UNCONDITIONALLY before even the first check — instead of only on a miss like\n // here — reopens a worse window: a token an entity loop reuses across iterations would expose\n // a \"this turn is about to self-resolve from the buffer\" waiter row to a concurrent signal for\n // the NEXT iteration's payload, which can steal it via engine.signal's plain takeSignalWaiter\n // and misdeliver. Checking first, so we only ever register when we're sure no buffer already\n // existed, avoids that.) See the interleaving proof at engine.signal for the mirror-image\n // take→buffer→re-take on the signaling side that this pairs with.\n await store.putSignalWaiter({ token, runId, seq: current });\n const lateBuffered = await consumeBuffered<T>(token, current);\n if (lateBuffered) {\n // Resolved it ourselves — remove OUR OWN row via the exact match, not\n // `takeSignalWaiter(token)`, which deletes ANY row for this token and could steal a\n // different run's waiter that has since claimed the same token.\n await store.removeSignalWaiter({ token, runId, seq: current });\n return lateBuffered.value;\n }\n throw new WorkflowSuspended();\n }\n const timeoutMs = opts.timeoutMs;\n const deadlineSeq = pos.next();\n const waitSeq = pos.next();\n // The run also gets a run-level wakeAt (via WorkflowSuspended) so the timer poller resumes it at\n // the deadline.\n const deadline = await stampDeadline(deadlineSeq, token, timeoutMs);\n const waited = await readCheckpoint(waitSeq);\n if (waited && waited.status === 'completed') return waited.output as T;\n const buffered = await consumeBuffered<T>(token, waitSeq);\n if (buffered) return buffered.value;\n if (host.clock() >= deadline) {\n // A PRIOR replay of this same call may have already registered the waiter (below) before this\n // one found the deadline past — clean up that exact row (own token/runId/seq only; a plain\n // `takeSignalWaiter(token)` could otherwise steal a different run's waiter on the same token).\n // A no-op if nothing was ever registered.\n await store.removeSignalWaiter({ token, runId, seq: waitSeq }).catch(() => undefined);\n throw new SignalTimeoutError(token, timeoutMs);\n }\n // Same reorder as the unbounded arm above: check, THEN register, THEN re-check before suspending.\n await store.putSignalWaiter({ token, runId, seq: waitSeq });\n const lateBuffered = await consumeBuffered<T>(token, waitSeq);\n if (lateBuffered) {\n await store.removeSignalWaiter({ token, runId, seq: waitSeq });\n return lateBuffered.value;\n }\n throw new WorkflowSuspended(deadline);\n };\n\n // Wait for a named event delivered by engine.publishEvent(name, payload). Like waitForSignal, but\n // name-based pub/sub with optional `match` filtering — the token embeds name + match (see events.ts),\n // so a publish fans out to the runs whose match the payload satisfies.\n //\n // Buffering (reliable events — mirrors signalWithStart's reliability contract for signals, see the\n // \"Semantics\" doc on engine.publishEvent): a publish that finds no live waiter buffers ONE copy, and\n // this call's post-registration scan is what consumes it. UNLIKE waitForSignal, this registers its\n // waiter FIRST and scans the buffer only ONCE after — no separate \"check before registering\" pass.\n // That's deliberate, not an oversight: waitForSignal's own token is a caller-chosen string an entity\n // loop can legitimately REUSE across iterations, so registering before checking would expose a\n // \"this turn is about to self-resolve\" waiter row to a concurrent signal for the NEXT iteration's\n // token, which could steal it via engine.signal's plain takeSignalWaiter. An event token embeds this\n // call's OWN `runId#seq` (see eventToken in events.ts) — nothing else, ever, mints the same token —\n // so that hazard cannot arise here, and a single check-after-register closes the lost-wake window\n // symmetrically with engine.publishEvent's own buffer-then-recheck (see its wiring in engine.ts).\n const waitForEvent = async <T>(\n name: string,\n opts?: { match?: Record<string, unknown>; timeoutMs?: number },\n ): Promise<T> => {\n if (opts?.timeoutMs == null) {\n const current = pos.next();\n const token = eventToken(name, opts?.match, runId, current);\n const existing = await readCheckpoint(current);\n if (existing && existing.status === 'completed') return existing.output as T;\n await store.putSignalWaiter({ token, runId, seq: current });\n const bufferedHit = await consumeBufferedEvent<T>(name, opts?.match, token, current);\n if (bufferedHit) return bufferedHit.value;\n throw new WorkflowSuspended();\n }\n const timeoutMs = opts.timeoutMs;\n const deadlineSeq = pos.next();\n const waitSeq = pos.next();\n const token = eventToken(name, opts.match, runId, waitSeq);\n const deadline = await stampDeadline(deadlineSeq, `event:${name}`, timeoutMs);\n const waited = await readCheckpoint(waitSeq);\n if (waited && waited.status === 'completed') return waited.output as T;\n if (host.clock() >= deadline) {\n // Exact removal (see waitForSignal above) — takeSignalWaiter(token) deletes ANY row for this\n // token and could steal a different run's waiter registered on it after ours timed out.\n await store.removeSignalWaiter({ token, runId, seq: waitSeq }).catch(() => undefined);\n throw new SignalTimeoutError(`event:${name}`, timeoutMs);\n }\n await store.putSignalWaiter({ token, runId, seq: waitSeq });\n const bufferedHit = await consumeBufferedEvent<T>(name, opts.match, token, waitSeq);\n if (bufferedHit) return bufferedHit.value;\n throw new WorkflowSuspended(deadline);\n };\n\n // An external task = a checkpointed dispatch + a wait for its async-completion `Completion`\n // (delivered by engine.completeTask/failTask). The whole \"fire at a foreign system, suspend,\n // resume when it reports back\" pattern as one call.\n const task = async <T>(\n name: string,\n dispatch: () => Promise<void>,\n options?: StepOptions,\n ): Promise<T> => {\n await localStep(`task:dispatch:${name}`, dispatch, options);\n return unwrapCompletion<T>(await waitForSignal(`task:${runId}:${name}`), `task \"${name}\"`);\n };\n\n // Child workflow (await result): start it once, then suspend on a `child:<id>` waiter the child\n // signals on its terminal state (see engine.notifyParent).\n const child = async <T>(\n workflow: WorkflowRef,\n input: unknown,\n options?: string | ChildCallOptions,\n ): Promise<T> => {\n const { childId, priority } = normalizeChildOptions(options);\n const current = pos.next();\n const id = childId ?? `${runId}.child.${current}`;\n const existing = await readCheckpoint(current);\n if (existing && existing.status === 'completed') {\n return unwrapCompletion<T>(existing.output, `child \"${id}\"`);\n }\n await store.putSignalWaiter({ token: `child:${id}`, runId, seq: current });\n if (!(await store.getRun(id))) host.startChild(workflowName(workflow), input, id, priority);\n // Make the awaited child visible in the parent's timeline WHILE it runs: a `running` placeholder\n // at this seq with the same `signal:child:<id>` name the signal resolution later overwrites as\n // `completed`. So the dashboard shows the child node (and can inline-expand it) live, instead of\n // it appearing only when it finishes. Written once (skipped on replay, where `existing` is set);\n // `running` is ignored by replay history, so it never short-circuits determinism.\n if (!existing) {\n await writeCheckpoint(\n instantCheckpoint({\n runId,\n seq: current,\n name: `signal:child:${id}`,\n kind: 'signal',\n status: 'running',\n }),\n );\n }\n throw new WorkflowSuspended();\n };\n\n // Parallel child workflows (wait-all): dispatch N children CONCURRENTLY and wait for ALL their\n // outputs. Reserves a contiguous position block in list order FIRST (the determinism anchor), then\n // dispatches every not-yet-completed item and suspends once; on each child completion the parent\n // resumes and replays — completed items short-circuit, remaining ones re-register and re-suspend.\n // When all resolve, outputs are returned in INPUT order (waitAll), or a GatherError is thrown\n // carrying the per-item failures. Parity with the Python SDK's `gather_children`.\n const all = async <T = unknown>(\n workflow: WorkflowRef,\n inputs: unknown[],\n opts?: { mode?: 'waitAll' | 'failFast' },\n ): Promise<T[]> => {\n // Empty: reserve no positions and produce no side effects (degenerate identity).\n if (inputs.length === 0) return [];\n const mode = opts?.mode ?? 'waitAll';\n const name = workflowName(workflow);\n // Reserve the whole block in list order BEFORE any dispatch — replay re-derives identical seqs.\n const positions = inputs.map(() => pos.next());\n const group = `all:${positions[0]}`;\n const id = (i: number) => `${runId}.all.${positions[0]}.${i}`;\n const existing = await Promise.all(positions.map((seq) => readCheckpoint(seq)));\n\n // failFast: bail the moment any already-completed item is a failed Completion.\n if (mode === 'failFast') {\n for (let i = 0; i < inputs.length; i += 1) {\n const cp = existing[i];\n const c =\n cp?.status === 'completed' ? (cp.output as { ok?: boolean; error?: string }) : null;\n if (c && c.ok === false) {\n // Cancel every sibling that hasn't completed yet — plain cancel, no saga undo. Best-effort:\n // a sibling mid-step only observes the cancellation at its NEXT checkpoint (it isn't\n // force-killed mid-synchronous-execution), so a fast-enough sibling can still slip through\n // and complete before it notices. `cancelChild` is deferred (like `startChild`), and\n // cancelling an already-terminal/cancelled run is a no-op, so replaying this branch after a\n // resume (which re-executes this loop and re-issues the same cancels) is safe.\n for (let j = 0; j < inputs.length; j += 1) {\n if (j !== i && existing[j]?.status !== 'completed') host.cancelChild?.(id(j));\n }\n throw new GatherError(\n [{ index: i, id: id(i), error: c.error ?? 'unknown' }],\n inputs.length,\n );\n }\n }\n }\n\n // Dispatch every item not yet completed in history; write its running placeholder once.\n let pending = false;\n for (let i = 0; i < inputs.length; i += 1) {\n const cp = existing[i];\n if (cp?.status === 'completed') continue;\n pending = true;\n const seq = positions[i] as number;\n const childId = id(i);\n // Carry the fan `group` onto the waiter too: the child's terminal `signal:child:` checkpoint is\n // (re)written by engine.signal when the child notifies the parent, OVERWRITING the running\n // placeholder below at the same seq — so without this the resolved checkpoint would lose the\n // group and the dashboard would render the resolved fan as a sequential chain.\n await store.putSignalWaiter({ token: `child:${childId}`, runId, seq, parallelGroup: group });\n if (!(await store.getRun(childId))) host.startChild(name, inputs[i], childId);\n if (!cp) {\n await writeCheckpoint(\n instantCheckpoint({\n runId,\n seq,\n name: `signal:child:${childId}`,\n kind: 'signal',\n status: 'running',\n parallelGroup: group,\n }),\n );\n }\n }\n // Any item still outstanding → suspend once; the resume replays this whole block.\n if (pending) throw new WorkflowSuspended();\n\n // All resolved: build outputs in INPUT order, aggregating any failures.\n const outputs: T[] = [];\n const failures: { index: number; id: string; error: string }[] = [];\n for (let i = 0; i < inputs.length; i += 1) {\n const c = existing[i]?.output as { ok?: boolean; value?: T; error?: string } | null;\n if (c && typeof c === 'object' && 'ok' in c && c.ok === false) {\n failures.push({ index: i, id: id(i), error: c.error ?? 'unknown' });\n outputs.push(undefined as T);\n } else {\n outputs.push((c as { value?: T } | null)?.value as T);\n }\n }\n if (failures.length > 0) throw new GatherError(failures, inputs.length);\n return outputs;\n };\n\n // Child workflow (fire-and-forget): dispatch it once and return its id WITHOUT suspending. The\n // start is checkpointed at this position so replay returns the same id without re-dispatching, and\n // is idempotent by id, so `child(..., sameId)` later joins the same run rather than starting a new\n // one (start + join scatter-gather).\n const startChild = async (\n workflow: WorkflowRef,\n input: unknown,\n options?: string | ChildCallOptions,\n ): Promise<string> => {\n const { childId, priority } = normalizeChildOptions(options);\n const current = pos.next();\n const id = childId ?? `${runId}.child.${current}`;\n const existing = await readCheckpoint(current);\n if (existing && existing.status === 'completed') return existing.output as string;\n if (!(await store.getRun(id))) host.startChild(workflowName(workflow), input, id, priority);\n await writeCheckpoint(\n instantCheckpoint({ runId, seq: current, name: `spawn:${id}`, kind: 'local', output: id }),\n );\n return id;\n };\n\n // Call a durable entity op and await its result: register a reply waiter at this position, dispatch\n // the op with the reply token, and suspend until the entity signals the result back (checkpointed,\n // so replay returns it without re-dispatching).\n const callEntity = async <R>(\n name: string,\n key: string,\n op: string,\n arg?: unknown,\n ): Promise<R> => {\n const current = pos.next();\n const existing = await readCheckpoint(current);\n if (existing && existing.status === 'completed') return existing.output as R;\n const reply = `entityreply:${runId}:${current}`;\n await store.putSignalWaiter({ token: reply, runId, seq: current });\n host.signalEntity?.(name, key, op, arg, reply);\n throw new WorkflowSuspended();\n };\n\n // Send a durable entity op without awaiting a result — dispatched once (checkpointed, replay-safe).\n const signalEntity = async (\n name: string,\n key: string,\n op: string,\n arg?: unknown,\n ): Promise<void> => {\n const current = pos.next();\n const existing = await readCheckpoint(current);\n if (existing && existing.status === 'completed') return;\n host.signalEntity?.(name, key, op, arg);\n await writeCheckpoint(\n instantCheckpoint({ runId, seq: current, name: `entitysig:${name}:${key}`, kind: 'local' }),\n );\n };\n\n // A breakpoint = a visible `pending` checkpoint + a signal waiter the dashboard resumes via\n // `engine.continue`. Reuses the signal machinery, so resume overwrites the pending checkpoint\n // with a completed one and the run replays past it.\n const breakpoint = async (label?: string): Promise<void> => {\n const current = pos.next();\n const existing = await readCheckpoint(current);\n if (existing && existing.status === 'completed') return;\n if (!existing) {\n await writeCheckpoint(\n instantCheckpoint({\n runId,\n seq: current,\n name: label ? `breakpoint:${label}` : 'breakpoint',\n kind: 'signal',\n status: 'pending',\n }),\n );\n await store.putSignalWaiter({ token: breakpointToken(runId, current), runId, seq: current });\n }\n throw new WorkflowSuspended();\n };\n\n // Guard an in-place change: a fresh run records a `patch:<id>` marker here and takes the new\n // branch; a run recorded under the OLD code finds a real step at this position instead, so we\n // rewind the logical position (the marker is transparent to it) and return false — its replay\n // reads that old step next and follows the old branch. No position shift → no corruption.\n const patched = async (id: string): Promise<boolean> => {\n const marker = `patch:${id}`;\n const current = pos.next();\n const existing = await readCheckpoint(current);\n if (existing) {\n if (existing.name === marker) return true;\n if (existing.name.startsWith('patch:')) {\n throw new NonDeterminismError(runId, current, marker, existing.name);\n }\n pos.rewind(); // not a marker: an old run's step lives here — give the position back to it\n return false;\n }\n await writeCheckpoint(\n instantCheckpoint({ runId, seq: current, name: marker, kind: 'local', output: true }),\n );\n return true;\n };\n\n // An update point: suspend on a run-scoped `update:<runId>:<name>` token that engine.update\n // delivers to (after its validator passes). Reuses the signal machinery; run-scoped like task/child.\n const onUpdate = <T>(name: string, opts?: { timeoutMs?: number }): Promise<T> =>\n waitForSignal<T>(`update:${runId}:${name}`, opts);\n\n // A queryable named value: a checkpoint whose `name` is `event:<key>`, so the latest value for a\n // key is just the highest-seq such checkpoint (read by engine.getEvent). Replay-idempotent.\n const setEvent = async (key: string, value: unknown): Promise<void> => {\n const current = pos.next();\n const name = `event:${key}`;\n const existing = await readCheckpoint(current);\n if (existing && existing.name !== name) {\n throw new NonDeterminismError(runId, current, name, existing.name);\n }\n if (existing && existing.status === 'completed') return; // replay: already published\n await writeCheckpoint(\n instantCheckpoint({ runId, seq: current, name, kind: 'local', output: value }),\n );\n };\n\n // A durable webhook reserves a logical position NOW to mint a stable token, so the url can be\n // handed to a third party before `wait()` suspends. `wait()` then parks on that same position\n // until the callback lands as engine.signal(token, body) — single position, replay-safe. The\n // deadline (when `wait({ timeoutMs })` is used) is a SEPARATE, later position — reserved lazily by\n // `wait()` itself, not at mint time, since the mint site has no `opts` to know a timeout was\n // requested. That's fine: `wait()` runs in the same deterministic order on every replay, so the\n // deadline seq it claims is stable too.\n const webhook = <T>(): DurableWebhook<T> => {\n const current = pos.next();\n const token = `wh:${runId}:${current}`;\n const wait = async (opts?: { timeoutMs?: number }): Promise<T> => {\n // A bounded wait claims its deadline position UNCONDITIONALLY, before the completed-replay\n // early return: the same `wait({ timeoutMs })` call re-runs on every replay, so the position\n // walk must be identical whether the callback has landed yet or not. (Claiming it lazily after\n // the early return would shift every later primitive by one on the post-callback replay and\n // trip the NonDeterminism guard on the stamped `timeout:*` checkpoint.)\n const timeoutMs = opts?.timeoutMs;\n const deadlineSeq = timeoutMs == null ? -1 : pos.next();\n const existing = await readCheckpoint(current);\n if (existing && existing.status === 'completed') return existing.output as T;\n if (timeoutMs == null) {\n await store.putSignalWaiter({ token, runId, seq: current });\n throw new WorkflowSuspended();\n }\n const deadline = await stampDeadline(deadlineSeq, token, timeoutMs);\n if (host.clock() >= deadline) {\n await store.takeSignalWaiter(token).catch(() => undefined);\n throw new SignalTimeoutError(token, timeoutMs);\n }\n await store.putSignalWaiter({ token, runId, seq: current });\n throw new WorkflowSuspended(deadline);\n };\n return { token, url: host.webhookUrl?.(token), wait };\n };\n\n // Deterministic capture: run `fn` once, checkpoint its output, and replay the SAME value verbatim\n // afterwards (fn is NOT re-run on replay). The general primitive for any non-deterministic value the\n // author controls the generator for — `ctx.sideEffect(() => uuidv7())`, `() => Math.random()`, a\n // config/env read. A raw `Date.now()`/`Math.random()` in a workflow body differs across replays and\n // corrupts the run; this captures it deterministically.\n const sideEffect = <T>(fn: () => T | Promise<T>): Promise<T> =>\n localStep('sideEffect', async () => fn());\n // `now` is the one ubiquitous convenience (a single obvious implementation, epoch ms like\n // `Date.now()`); everything else uses `sideEffect` so the author picks the generator.\n const now = () => localStep('now', async () => host.clock());\n\n // Merge into this run's searchAttributes exactly once: a checkpoint at this position marks it done,\n // so a replay SKIPS the write (mirrors `transaction` / the instant primitives) instead of re-merging\n // on every turn. Nondeterminism-guarded by the recorded marker name.\n const upsertSearchAttributes = async (attrs: SearchAttributes): Promise<void> => {\n const current = pos.next();\n const existing = await readCheckpoint(current);\n if (existing) {\n if (existing.name !== 'searchAttributes') {\n throw new NonDeterminismError(runId, current, 'searchAttributes', existing.name);\n }\n // Replayed: the write already happened on a prior turn — skip it, and (deliberately) skip\n // re-validating too. Validation only ever needs to run once, at the position it's recorded;\n // re-running it on replay would be redundant at best and, for a schema whose rules change\n // between deploys, a source of a replay throwing on history a live run already accepted.\n return;\n }\n if (searchAttributesSchema) {\n // The schema describes the whole run's search-attribute shape (optional keys included), so\n // validate the MERGED result — this call's `attrs` shallow-merged onto what's already on the\n // run — not `attrs` alone. Mirrors the merge `host.upsertSearchAttributes` itself performs;\n // read here is best-effort (not transactional with the host's own read+write), same as that\n // merge already is.\n const run = await store.getRun(runId);\n const merged = { ...(run?.searchAttributes ?? {}), ...attrs };\n const result = searchAttributesSchema['~standard'].validate(merged);\n if (result instanceof Promise) {\n throw new Error(\n `workflow \"${workflow}\": ctx.upsertSearchAttributes schema validation must be synchronous (the searchAttributes schema's \\`~standard.validate\\` returned a Promise) — replay-determinism requires a sync validator; drop any async refinement from the schema passed to @Workflow({ searchAttributes }).`,\n );\n }\n if (result.issues) {\n const offendingKeys = [\n ...new Set(result.issues.map((issue) => formatIssuePath(issue.path))),\n ];\n const details = result.issues\n .map((issue) => `${formatIssuePath(issue.path)}: ${issue.message}`)\n .join('; ');\n throw new Error(\n `workflow \"${workflow}\": ctx.upsertSearchAttributes rejected by its searchAttributes schema — ` +\n `offending key(s) ${offendingKeys.join(', ')} — ${details}`,\n );\n }\n }\n await host.upsertSearchAttributes(runId, attrs);\n await writeCheckpoint(\n instantCheckpoint({\n runId,\n seq: current,\n name: 'searchAttributes',\n kind: 'local',\n output: attrs,\n }),\n );\n };\n\n // Resolve a `ctx.step(..., { compensate })` ref/string into the undo's own dispatchable StepDef —\n // same routing-name resolution as the step it's attached to (see `step` below), but its dispatch\n // policy comes ONLY from its own `@Step`-stamped config (stepConfigOf), never the compensated\n // call's per-call `opts`: the undo is a separately-declared handler with its own retry/backoff, not\n // an extension of the step it undoes. The string form (cross-runtime, unchecked) has no stamped\n // config, so it dispatches with engine defaults. Takes `unknown` (like `stepNameOf`/`stepConfigOf`\n // themselves) rather than a `StepRef<StepUndo<TInput, TOutput>, ...>` — the caller's TInput/TOutput\n // are call-site type parameters with no runtime shape to check here; the compile-time contract is\n // already enforced by `WorkflowCtx.step`'s overload signature (interfaces.ts) that typed `opts`.\n function resolveCompensateDef(compensate: unknown): StepDef<StepUndo<unknown, unknown>, unknown> {\n const name = typeof compensate === 'string' ? compensate : stepNameOf(compensate);\n if (name === undefined) {\n throw new Error(\n 'ctx.step: compensate handler is not a @Step reference (no stamped step name) — pass a @Step-decorated method or a step name string',\n );\n }\n const config = typeof compensate === 'string' ? undefined : stepConfigOf(compensate);\n return { name, ...resolveStepPolicy(config, undefined) };\n }\n\n // ONE durable step primitive: always dispatched, always engine-scheduled — no local/remote\n // placement choice for the workflow author (see `WorkflowCtx.step`). Resolve the routing name off\n // a `@Step`-stamped handler reference, or take it literally for the cross-runtime string form; the\n // reference itself is NEVER invoked here — only its stamped name (and dispatch policy) is read (the\n // serving worker re-resolves the real handler from DI), so an unbound `this` on `handlerOrName` is\n // irrelevant. The effective durable-retry/liveness policy is `{ ...stepConfigOf(handlerOrName),\n // ...opts }` — the `@Step`-declared def-level policy, with a per-call `opts` field winning wherever\n // it's set. The string form has no stamped config, so it uses `opts` only. Carrying this policy onto\n // the `StepDef` re-enables `callRemote`'s durable retry/backoff and liveness-timeout branches (see\n // `engine.ts`), which were otherwise orphaned.\n function step<TInput, TOutput>(\n handlerOrName: StepRef<TInput, TOutput> | string,\n input: TInput,\n opts?: StepDispatchOpts & { compensate?: StepRef<StepUndo<TInput, TOutput>, unknown> | string },\n ): Promise<TOutput> {\n const name = typeof handlerOrName === 'string' ? handlerOrName : stepNameOf(handlerOrName);\n if (name === undefined) {\n throw new Error(\n 'ctx.step: handler is not a @Step reference (no stamped step name) — pass a @Step-decorated method or a step name string',\n );\n }\n const config = typeof handlerOrName === 'string' ? undefined : stepConfigOf(handlerOrName);\n const def: StepDef<TInput, TOutput> = { name, ...resolveStepPolicy(config, opts) };\n return host\n .callRemote(runId, pos.next(), def, input, opts?.queue, opts?.transport, {\n priority: opts?.priority,\n fairnessKey: opts?.fairnessKey,\n })\n .then((output) => {\n // `callRemote` resolves ONLY once this step is durably complete — the replay-completed branch\n // (a checkpointed output) or the in-memory `timeoutMs` liveness path once the live result\n // lands (engine.ts). Register the compensation HERE, after that resolution, so a saga only\n // ever undoes steps that actually finished. Mirrors `localStep`'s rebuild-on-replay: the\n // workflow body re-passes `compensate` on every replay of a completed call, and `input`/\n // `output` come straight from this call (the checkpointed ones on replay) — no store-schema\n // change needed to carry the undo's args.\n if (opts?.compensate) {\n compensations.push({\n name,\n dispatch: { def: resolveCompensateDef(opts.compensate), args: { input, output } },\n });\n }\n return output;\n });\n }\n\n return {\n runId,\n step,\n localStep,\n upsertSearchAttributes,\n transaction,\n callEntity,\n signalEntity,\n sleep,\n sleepUntil,\n continueAsNew,\n waitForSignal,\n waitForEvent,\n task,\n child,\n all,\n startChild,\n breakpoint,\n webhook,\n setEvent,\n onUpdate,\n patched,\n now,\n sideEffect,\n };\n}\n","import { type AdmissionBackend, InMemoryAdmissionBackend } from './admission';\nimport { runInWorkflowCtx } from './ambient-ctx';\nimport { backoffDelay } from './backoff';\nimport { instantCheckpoint, stepCheckpoint } from './checkpoints';\nimport { type Completion } from './completion';\nimport { parseDuration } from './duration';\nimport { Entities, type EntityConfig } from './entities';\nimport {\n ContinueAsNew,\n FatalError,\n NonDeterminismError,\n RemoteStepTimeout,\n RemoteWorkflowTimeout,\n SignalTimeoutError,\n WorkflowSuspended,\n} from './errors';\nimport { EventAccumulators, type EventBatchConfig } from './event-accumulators';\nimport {\n EVENT_BUFFER_SCAN_LIMIT,\n eventMatchOf,\n eventMatches,\n eventNameOf,\n eventPrefix,\n isEventToken,\n} from './events';\nimport type {\n ControlPlane,\n EngineEvent,\n EngineListener,\n GroupHealth,\n NamedTransport,\n RemoteTask,\n RunDispatcher,\n RunQuery,\n RunResult,\n RunStatus,\n SearchAttributes,\n SearchAttributesSchema,\n SignalWaiter,\n StateStore,\n StepCheckpoint,\n StepDef,\n StepError,\n StepEvent,\n StepInterceptor,\n StepInvocation,\n StepKind,\n StepResult,\n StepUndo,\n Transport,\n UpdateResult,\n UpdateValidator,\n WorkflowCommand,\n WorkflowCtx,\n WorkflowDecision,\n WorkflowExecutor,\n WorkflowRun,\n WorkflowStepEvent,\n} from './interfaces';\nimport type { HistoryEvent } from './interfaces';\nimport { breakpointToken, stepId } from './protocol';\nimport type { QueueConfig } from './queue';\nimport { RemoteWorkflowExecutor } from './remote-workflow-executor';\nimport { indexWaitersByRun } from './run-waiting';\nimport { SingletonGate } from './singleton-gate';\nimport { sanitizeQueueToken, tenantGroup } from './tenant-group';\nimport { TransportPool } from './transport-pool';\nimport {\n type Compensation,\n type CtxHost,\n type InternalWorkflowCtx,\n type StepRecord,\n createWorkflowCtx,\n} from './workflow-ctx';\nimport {\n type WorkflowClass,\n type WorkflowInputOf,\n type WorkflowRef,\n workflowName,\n} from './workflow-ref';\n\n// The engine ALWAYS runs a body with the InternalWorkflowCtx `createWorkflowCtx` produces (it carries\n// the internal `localStep` the entity runner + capture helpers need). Public authors type their body\n// with the narrower `WorkflowCtx`; contravariance keeps those assignable to this param, so the internal\n// type never leaks into the public authoring surface while `EntityHost.register` still lines up.\ntype WorkflowFn = (ctx: InternalWorkflowCtx, input: unknown) => Promise<unknown>;\n\n/** Options for {@link WorkflowEngine.start}. */\nexport interface StartOptions {\n /** Run-scoped tags, merged with the workflow's static `@Workflow({ tags })` onto the run. */\n tags?: string[] | undefined;\n /** Typed, queryable run data stamped on the run (e.g. `{ amount: 200, tier: 'pro' }`). */\n searchAttributes?: SearchAttributes | undefined;\n /**\n * Dispatch priority for a remote run — stamped on the run and carried onto every {@link WorkflowTask}\n * the engine dispatches to advance it. Higher wins; absent = unprioritised. See {@link WorkflowRun.priority}.\n */\n priority?: number | undefined;\n /**\n * Override the namespace stamped on the run. Defaults to the engine's own `namespace`. Set by the\n * control plane when it starts a run on behalf of a tenant (a {@link StartRunMessage}'s `tenant`\n * maps here), so one DB-less-tenant-facing engine can create runs across many namespaces.\n */\n namespace?: string | undefined;\n}\n\n/**\n * Serialize runs of a workflow that share a key — a durable, FIFO mutex (e.g. one pipeline per base).\n * Excess runs are admitted in creation order, `limit` at a time; the rest wait (suspended) and retry\n * admission on a timer until a slot frees. Race-free on a consistent store (admission order is the\n * same `(createdAt, id)` view for every instance).\n */\nexport interface SingletonConfig {\n /** Derive the serialization key from the workflow input. */\n key: (input: unknown) => string;\n /** Max concurrent runs sharing the key. Default 1 (a mutex). */\n limit?: number;\n /**\n * Max GATED (waiting-for-admission) runs allowed to queue behind the `limit` in-flight ones. When\n * set, `start` rejects with {@link SingletonQueueFullError} once in-flight + gated reaches\n * `limit + maxQueueDepth` — back-pressure against an unbounded same-key backlog. Omit for the\n * default unbounded queue. Counts `pending`/`running`/`suspended` runs sharing the key.\n */\n maxQueueDepth?: number;\n}\n\n/** Union of a workflow's static tags and a run's start-time tags, de-duplicated, or undefined if none. */\nfunction mergeTags(staticTags?: string[], runTags?: string[]): string[] | undefined {\n if (!staticTags?.length && !runTags?.length) return undefined;\n return [...new Set([...(staticTags ?? []), ...(runTags ?? [])])];\n}\n\n/** A breakpoint checkpoint's `name` is `breakpoint` (or `breakpoint:<label>`). This name — not the\n * reused `signal` kind — is the explicit marker the dashboard and `continue()` detect it by. */\nconst BREAKPOINT = 'breakpoint';\nconst isBreakpoint = (cp: { status: string; name: string }): boolean =>\n cp.status === 'pending' && cp.name.startsWith(BREAKPOINT);\n\ninterface RegisteredWorkflow {\n name: string;\n version: string;\n fn: WorkflowFn;\n /** Static `@Workflow({ tags })` — merged with per-run tags onto each run at start. */\n tags?: string[] | undefined;\n /** Per-key serialization (a durable mutex). See {@link SingletonConfig}. */\n singleton?: SingletonConfig | undefined;\n /** Max wall-clock lifetime (ms) before a run is cancelled by `sweepTimeouts`. */\n executionTimeoutMs?: number | undefined;\n /** Validate the input at start; throw to reject before a run is created. Validator-agnostic. */\n validateInput?: ((input: unknown) => void | Promise<void>) | undefined;\n /** Typed/validated `searchAttributes` shape. When set, `ctx.upsertSearchAttributes` validates the\n * merged result against it (see `createWorkflowCtx`). See `WorkflowMeta.searchAttributes`. */\n searchAttributesSchema?: SearchAttributesSchema | undefined;\n /** Event names that start a fresh run of this workflow when published. See `publishEvent`. */\n onEvent?: string[] | undefined;\n /** Coalesce `onEvent` triggers: debounce (fire once it's quiet) or batch (fire on size/window). */\n eventBatch?: EventBatchConfig | undefined;\n /** Set for a workflow advanced by DISPATCH instead of an inline `fn`: a cross-SDK (e.g. Python)\n * body via {@link WorkflowEngine.registerRemote}, OR a group-served TS body via\n * `register(..., { group, executor })`. The engine hands the run's history to `executor` (which\n * dispatches a workflow task to `group`) rather than running `fn` in-process. See\n * {@link WorkflowExecutor}. */\n remote?: { group: string; executor: WorkflowExecutor };\n /** True when `fn` is a real in-process body (`register`), false/absent for a body-less remote whose\n * `fn` is the throwing stub (`registerRemote` / a synthesized remote child). Gates\n * {@link WorkflowEngine.workflowBody} so an in-app worker only ever gets a runnable body. */\n hasBody?: boolean | undefined;\n}\n\nconst versionKey = (name: string, version: string): string => `${name}@${version}`;\n\n/** The id for the next continuation of a run: `r` → `r~1` → `r~2` … (stable, traceable lineage). */\nfunction nextContinuationId(runId: string): string {\n const m = runId.match(/^(.*)~(\\d+)$/);\n return m ? `${m[1]}~${Number(m[2]) + 1}` : `${runId}~1`;\n}\n\n/** True when version `a` is newer than `b` (numeric when both parse as numbers, else natural sort). */\nfunction isNewerVersion(a: string, b: string): boolean {\n const na = Number(a);\n const nb = Number(b);\n if (!Number.isNaN(na) && !Number.isNaN(nb)) return na > nb;\n return a.localeCompare(b, undefined, { numeric: true }) > 0;\n}\n\n/** What a remote worker hands back: the output plus when it actually began (for queue-wait timing). */\ninterface RemoteResolution {\n output: unknown;\n startedAt?: number | undefined;\n events?: StepEvent[] | undefined;\n}\n\ninterface PendingRemote {\n resolve: (result: RemoteResolution) => void;\n reject: (error: Error) => void;\n}\n\n/** A terminal/suspended transition handed to {@link WorkflowEngine.settleRun}. */\ntype RunOutcome =\n | { kind: 'completed'; output: unknown }\n | { kind: 'failed'; error: StepError }\n | { kind: 'suspended'; wakeAt?: number | undefined };\n\n/**\n * What {@link WorkflowEngine.unwindCompensations} returns when the run must keep waiting on a\n * dispatched compensation — `wakeAt` set while backing off a durable retry (the due-timer poller\n * re-drives it once elapsed), absent while freshly dispatched/in flight (only the worker's result,\n * via `completeRemoteResult`, re-drives it). `undefined` (no `UnwindPending`) means every\n * compensation resolved. Deliberately NOT a `RunResult`: the two callers persist \"still unwinding\"\n * differently (a plain `suspended` run for the failure path; `cancelling` held as-is for the cancel\n * path — see `compensateAndCancel`), so the settling is left to them.\n */\ninterface UnwindPending {\n wakeAt?: number | undefined;\n}\n\nexport interface WorkflowEngineDeps {\n store: StateStore;\n /** A single task transport. Shorthand for a one-entry `transports` pool (id `default`). */\n transport?: Transport | undefined;\n /**\n * An ordered pool of named transports. The engine dispatches on the first and fails over to the\n * next on a dispatch error; a step pins one via `ctx.step(step, input, { transport: id })`. Use\n * this instead of `transport` for failover / multi-broker setups.\n */\n transports?: NamedTransport[] | undefined;\n /**\n * Cross-instance broadcast pub/sub for lifecycle events + cancellation (see {@link ControlPlane}).\n * Separate from the task `transport`; omit for a single-instance / local-only setup. A transport\n * that can also broadcast may be passed here as well.\n */\n controlPlane?: ControlPlane | undefined;\n /** Epoch-ms clock; injectable for tests. Defaults to `Date.now`. */\n clock?: (() => number) | undefined;\n /**\n * Flow-control admission backend for `ctx.step(step, input, { queue })`. Defaults to an in-process\n * {@link InMemoryAdmissionBackend} (per-instance caps). Inject a store/Redis-backed backend to make\n * concurrency / rate-limit / ordering GLOBAL across engine replicas.\n */\n admission?: AdmissionBackend | undefined;\n /** Unique id for this engine instance, used for recovery leases. Defaults to a random id. */\n instanceId?: string | undefined;\n /**\n * Worker-pool partition for this engine. Stamped on every run it creates; the poll paths\n * (`runPending`/`recoverIncomplete`/`resumeDueTimers`/`sweepTimeouts`) only act on runs in this\n * namespace. Set distinct values to safely share ONE state store across non-interchangeable pools\n * (e.g. local dev vs a cluster). **Omit it to make this engine an OPERATOR** — an unset namespace\n * drives/recovers/resumes runs of EVERY namespace (the poll filters no-op, the resume/decision\n * guards fall through) and leaves the transport on its bare prefix. This is the hosted control\n * plane: \"ver tudo = ausência de namespace\".\n */\n namespace?: string | undefined;\n /** Recovery lease duration in ms — how long this instance owns a run it picked up. Default 30s. */\n leaseMs?: number | undefined;\n /**\n * Cap how many times crash-recovery may pick up the same still-`running` run before giving up and\n * moving it to the `dead` dead-letter state (a poison pill that crashes the process every boot).\n * Omit for unlimited (the default — recovery always retries).\n */\n maxRecoveryAttempts?: number | undefined;\n /**\n * Opt-in liveness deadline (ms) for a remote workflow `advance`. If the worker neither returns a\n * decision NOR sends a run-scoped {@link Heartbeat} within this window, the engine presumes it dead:\n * it rejects the advance with {@link RemoteWorkflowTimeout}, releases the lease, and lets recovery\n * re-drive (replaying completed steps from history). Each beat REARMS the window, so a worker still\n * legitimately replaying a long turn (it keeps beating) is never re-driven — closing the duplicate-\n * side-effect hazard a fixed {@link RemoteWorkflowExecutor} `timeoutMs` cannot avoid. Omit (default)\n * for the prior unbounded await — byte-identical behavior when unset. If a `RemoteWorkflowExecutor` is\n * ALSO constructed with its own `timeoutMs`, the shorter of the two deadlines wins; prefer setting only\n * one (this rearmed window for heartbeat-aware workers, or the fixed `timeoutMs` otherwise).\n */\n remoteAdvanceSilenceMs?: number | undefined;\n /**\n * Fallback re-drive window (ms) for a run that SUSPENDS with no natural timer — i.e. it's waiting on\n * an EVENT to wake it (a child's completion, a signal, a remote step with no `timeoutMs`) rather than\n * a `ctx.sleep`. Those events re-drive the run directly; but if the wake is LOST (the delivering pod\n * crashed / rolled mid-handoff), the run would otherwise sit `suspended` forever with `wakeAt: null` —\n * invisible to both the timer poller (no `wakeAt`) and crash-recovery (no lease). This stamps a\n * fallback `wakeAt` so {@link resumeDueTimers} re-drives it after the window; the re-drive is an\n * idempotent replay (a still-pending dependency re-suspends via the checkpoint guard, a settled one\n * advances), so it's a safe self-heal, not a retry that can double-dispatch. The primary event path\n * still wins first for a healthy run (it re-drives long before this fires), so this only ever fires\n * for a genuinely-orphaned run. Default 5min; set `0` to disable (the prior wake-forever behavior).\n */\n reconcileMs?: number | undefined;\n /**\n * Retention for a BUFFERED event that no `waitForEvent` ever claims (see\n * {@link WorkflowEngine.publishEvent}'s buffering — a publish matching no live waiter keeps ONE\n * copy around for a later matching wait). Default `undefined`: keep it until consumed, same as\n * {@link StateStore.bufferSignal}'s buffered signals — no silent expiry. Set a duration (ms) to\n * have the {@link resumeDueTimers} reconcile pass prune rows past `publishedAt + eventBufferTtlMs`\n * as it encounters them. Scoped to event NAMES the current reconcile tick's registered waiters\n * reference (the sweep has no reason to otherwise enumerate every buffered name) — a name with a\n * stale buffered event but zero waiters ever registered against it is not visited by this pass; that\n * is an accepted gap given `listBufferedEvents` is name-scoped by design (see interfaces.ts), not a\n * bug to route around here.\n */\n eventBufferTtlMs?: number | undefined;\n /**\n * Opt-in self-heal window (ms) for a remote step with NO `timeoutMs` whose dispatched job was LOST —\n * the worker crashed mid-step leaving no result, or the transport dropped the job (a Redis\n * flush/eviction, or BullMQ moving a stalled job to `failed` and removing it). The `pending`\n * checkpoint then has no result to resume on, and — BY DESIGN (see {@link reconcileMs}) — the\n * reconcile re-drive re-suspends a still-pending step rather than re-dispatching, so a slow-but-live\n * worker is never double-run. That safety means a genuinely-lost dispatch would otherwise hang\n * forever. When set, a reconcile re-drive that finds a remote step still `pending` PAST this window\n * re-dispatches it (bumping `attempts`, bounded by {@link remoteRedispatchMax}). Off by default:\n * re-dispatch can double-run a step whose original job is merely slow, so the window MUST exceed the\n * longest such step and the step MUST be idempotent. Prefer a per-step `timeoutMs` (tighter,\n * heartbeat-aware) where you can; this is the store-driven net for no-timeout steps that must\n * survive a lost dispatch. {@link WorkflowEngine.redispatchPending} is the manual counterpart.\n */\n remoteRedispatchMs?: number | undefined;\n /**\n * Max times {@link remoteRedispatchMs} re-dispatches one lost remote step before giving up and\n * failing it as a {@link RemoteStepError} (`code: 'remote_step_lost'`), so the run fails / dead-letters\n * instead of re-dispatching forever. Default 10. Ignored when `remoteRedispatchMs` is unset.\n */\n remoteRedispatchMax?: number | undefined;\n /**\n * Build the public callback URL for a `ctx.webhook()` token (e.g.\n * ``(t) => `https://api.example.com/durable/webhooks/${t}` ``). Populates\n * {@link DurableWebhook.url}. Omit if you build URLs yourself from the token.\n */\n webhookUrl?: ((token: string) => string) | undefined;\n /**\n * Provide the current W3C `traceparent` to stamp on each dispatched {@link RemoteTask}, so a\n * worker (including the Python SDK) continues the distributed trace. Keep core OTel-free: supply\n * `otelTraceparent` from `@dudousxd/nestjs-durable-otel`, or your own context reader. Omit to send none.\n */\n traceparent?: (() => string | undefined) | undefined;\n /**\n * Provide an opaque context carrier (tenant / user / correlation ids) to attach to each dispatched\n * {@link RemoteTask} as its `context`, so a worker (including the Python SDK) re-exposes it to the\n * step handler — cross-process propagation alongside the {@link traceparent}. Keep core dependency-free:\n * supply this from `@dudousxd/nestjs-context` or your own request-scoped reader. The engine never\n * inspects the returned object's shape. Omit to send none.\n *\n * Re-evaluated at each (re)dispatch — including a retry or a resume that the engine drives AFTER a\n * crash/scale-down, which runs OUTSIDE the originating request scope. On such a path this provider\n * may return empty or stale values (the request-scoped tenant/user is gone). Treat the carrier as\n * best-effort correlation/propagation metadata only — do NOT treat it as an authorization boundary.\n */\n context?: (() => Record<string, unknown> | undefined) | undefined;\n /**\n * Re-hydrate the originating context around a LOCAL step body, so a `@DurableStep` reader sees the\n * tenant / user / correlation ids that were live when the run was started — even on a path the\n * engine drives outside the originating request scope (a resume after crash/scale-down, a timer).\n * Given the carrier produced by {@link context} (may be empty/undefined) and the step body `fn`, it\n * runs `fn` with that context ambiently established (e.g. inside `@dudousxd/nestjs-context`'s ALS)\n * and returns its result. Keep core dependency-free: supply this from the nestjs wiring (which owns\n * nestjs-context) or your own ALS bridge. The handler signature is unchanged — re-hydration is\n * ambient. Default: passthrough (`(_, fn) => fn()`), so behavior is byte-identical when unset.\n */\n rehydrate?: (<T>(carrier: Record<string, unknown> | undefined, fn: () => T) => T) | undefined;\n /**\n * Attempts for each saga compensation when the run fails (a transient undo — e.g. a refund API\n * hiccup — gets another try). Default 1 (no retry). Compensations must be idempotent.\n */\n compensationRetries?: number | undefined;\n /**\n * Persist a `running` checkpoint when a local step's body begins, so an in-flight step shows up\n * in the dashboard (and a fresh page load / REST query) the moment it starts — not only once it\n * completes. The `step.started` lifecycle event is emitted either way (the live SSE view always\n * sees the start); this flag only controls the extra checkpoint write. Default `true`. Set\n * `false` on hot paths with many short local steps to halve their checkpoint writes — you keep\n * the live event but lose reload-survivable in-flight visibility.\n */\n trackStepStart?: boolean | undefined;\n /**\n * Where a freshly-`start`ed run executes (see {@link RunDispatcher}). Defaults to in-process: the\n * run executes on this instance asynchronously (a microtask), so `start` returns without blocking.\n * Pass a no-op dispatcher on a caller that must NOT run workflows (e.g. an API/dashboard pod), and\n * run `runPending` on a worker pod to pick those up; or a broker-backed one for a worker pool.\n */\n runDispatcher?: RunDispatcher | undefined;\n}\n\n/** Thrown by {@link WorkflowEngine.resume} when the run belongs to a different namespace. */\nclass NamespaceMismatch extends Error {\n constructor() {\n super('namespace-mismatch');\n }\n}\n\n/**\n * The orchestrator. Owns workflow state and replays runs deterministically: each step's\n * result is checkpointed, so on resume a completed step returns its saved output instead of\n * re-executing. Remote steps are dispatched over the Transport; their results checkpoint the\n * same way local steps do.\n */\nexport class WorkflowEngine {\n private readonly store: StateStore;\n /** Ordered transport pool (dispatch + failover). Empty = no remote steps. */\n private readonly pool: TransportPool;\n private readonly controlPlane?: ControlPlane | undefined;\n private readonly clock: () => number;\n private readonly instanceId: string;\n private readonly namespace: string | undefined;\n private readonly leaseMs: number;\n private readonly maxRecoveryAttempts?: number | undefined;\n private readonly remoteAdvanceSilenceMs?: number | undefined;\n private readonly reconcileMs: number | undefined;\n private readonly eventBufferTtlMs: number | undefined;\n private readonly remoteRedispatchMs: number | undefined;\n private readonly remoteRedispatchMax: number;\n private readonly webhookUrl?: ((token: string) => string) | undefined;\n private readonly traceparent?: (() => string | undefined) | undefined;\n private readonly context?: (() => Record<string, unknown> | undefined) | undefined;\n /** Establish the originating context ambiently around a local step body (see {@link WorkflowEngineDeps.rehydrate}). Default passthrough. */\n private readonly rehydrate: <T>(carrier: Record<string, unknown> | undefined, fn: () => T) => T;\n private readonly compensationRetries: number;\n /** Persist a `running` checkpoint at the start of a local step body (see {@link WorkflowEngineDeps.trackStepStart}). */\n private readonly trackStepStart: boolean;\n /** Where a freshly-started run executes — in-process by default (see {@link RunDispatcher}). */\n private readonly runDispatcher: RunDispatcher;\n\n /** Per-key serialization for singleton workflows (admission, back-pressure, notify-on-release). */\n private readonly singletons: SingletonGate;\n /** Every registered workflow, keyed by `name@version` — so old versions stay runnable. */\n private readonly workflows = new Map<string, RegisteredWorkflow>();\n /** The newest registered version per workflow name — used to `start` new runs. */\n private readonly latest = new Map<string, RegisteredWorkflow>();\n /** Event name → workflow names started when that event is published (see `onEvent`). */\n private readonly eventTriggers = new Map<string, Set<string>>();\n /** Durable-entity subsystem (registers the `__entity` runner; see `registerEntity`). */\n private readonly entities: Entities;\n /** Event debounce/batch accumulators (register the `__evt_*` runners; see `accumulators.route`). */\n private readonly accumulators: EventAccumulators;\n /** In-flight remote steps awaiting a worker result, keyed by stepId. */\n private readonly pending = new Map<string, PendingRemote>();\n /** \"Reset the liveness timer\" callbacks keyed by the beat's target — a stepId (in-flight remote step)\n * or a runId (in-flight remote workflow turn) — invoked when a matching heartbeat arrives. The two id\n * shapes don't collide in practice: a stepId is `${runId}:${seq}`, a run key is the bare runId. */\n private readonly heartbeatResets = new Map<string, () => void>();\n private readonly listeners = new Set<EngineListener>();\n /** Step interceptors (onion middleware around real local-step execution), first = outermost. */\n private readonly interceptors: StepInterceptor[] = [];\n /** Callbacks notified (on any instance) when a run is cancelled — for cooperative cancellation. */\n private readonly cancelListeners = new Set<(runId: string) => void>();\n /** Callbacks notified when a run is enqueued elsewhere — for low-latency cross-pod dispatch. */\n private readonly enqueuedListeners = new Set<(runId: string) => void>();\n /** Notified when a run is dead-lettered (moved to `dead`) — a hook for a DLQ handler. */\n private readonly deadListeners = new Set<(run: WorkflowRun) => void>();\n /** Validators gating `engine.update`, keyed by `<workflow>:<updateName>`. */\n private readonly updateValidators = new Map<string, UpdateValidator>();\n /** Runs being cancelled WITH saga compensation — see `cancel({ compensate: true })`. */\n private readonly cancelRequested = new Set<string>();\n /** Flow-control admission backend for remote steps (see {@link registerQueue}). */\n private readonly admission: AdmissionBackend;\n /** Runs on THIS instance blocked on admission, by queue — woken early on a freed-slot signal. */\n private readonly queueWaiters = new Map<string, Set<string>>();\n /** Which queue a dispatched step took a slot from, by stepId — so the result can release it. */\n private readonly stepQueue = new Map<string, string>();\n /** Executions currently in flight, so a graceful shutdown can wait for them to settle. */\n private readonly inflight = new Set<Promise<RunResult>>();\n private draining = false;\n\n constructor(deps: WorkflowEngineDeps) {\n this.store = deps.store;\n this.pool = new TransportPool(\n deps.transports ?? (deps.transport ? [{ id: 'default', transport: deps.transport }] : []),\n );\n this.controlPlane = deps.controlPlane;\n this.clock = deps.clock ?? Date.now;\n this.admission = deps.admission ?? new InMemoryAdmissionBackend(this.clock);\n // Wake this instance's admission-blocked runs the moment a slot frees anywhere in the fleet,\n // instead of waiting for their retry tick. Best-effort (the retry tick remains the guarantee).\n this.admission.onFreed?.((queue) => this.wakeQueueWaiters(queue));\n this.instanceId = deps.instanceId ?? globalThis.crypto.randomUUID();\n this.namespace = deps.namespace;\n // The engine's namespace deliberately does NOT touch the transport(s). The two tenancy axes are\n // orthogonal and encode differently ON PURPOSE (the cross-SDK canonical wire convention):\n // - `namespace` scopes the STORE (which runs this engine drives/recovers) and stamps every run\n // it starts; per-run routing then suffixes GROUP tokens (`<name>@<tenant>`, see tenantGroup)\n // on the transport's own prefix — the same convention every worker SDK (Python, the TS\n // tenant role) speaks natively.\n // - Whole-DEPLOYMENT isolation on a shared broker is the transport's `prefix`/`namespace`\n // constructor options — explicit, never inferred from the engine.\n // (An earlier design auto-folded a scoped engine's namespace into the transport prefix,\n // producing a keyspace no tenant worker could see — the tenant ended up encoded twice, once in\n // the prefix and once in the group suffix, and cross-runtime discovery silently failed.)\n this.leaseMs = deps.leaseMs ?? 30_000;\n this.maxRecoveryAttempts = deps.maxRecoveryAttempts;\n this.remoteAdvanceSilenceMs = deps.remoteAdvanceSilenceMs;\n // Default 5min; an explicit 0 disables the fallback (opt back into wake-forever-on-lost-event).\n this.reconcileMs = deps.reconcileMs === undefined ? 300_000 : deps.reconcileMs || undefined;\n // Opt-in: unset (or 0) keeps buffered events around forever, same as buffered signals.\n this.eventBufferTtlMs = deps.eventBufferTtlMs || undefined;\n // Opt-in: unset (or 0) leaves the by-design \"re-suspend a lost dispatch, never re-dispatch\" behavior.\n this.remoteRedispatchMs = deps.remoteRedispatchMs || undefined;\n this.remoteRedispatchMax = Math.max(1, deps.remoteRedispatchMax ?? 10);\n this.webhookUrl = deps.webhookUrl;\n this.traceparent = deps.traceparent;\n this.context = deps.context;\n // Default passthrough: with no bridge supplied, a local step body runs exactly as before.\n this.rehydrate = deps.rehydrate ?? ((_carrier, fn) => fn());\n this.compensationRetries = Math.max(1, deps.compensationRetries ?? 1);\n this.trackStepStart = deps.trackStepStart ?? true;\n // Default: execute the run on this instance, asynchronously, so `start` never blocks on the body.\n // A failed pickup is swallowed here (the run stays `pending` for a `runPending` poll to retry);\n // run failures themselves are handled inside `execute` and surfaced as the run's `failed` state.\n this.runDispatcher = deps.runDispatcher ?? {\n dispatch: (runId) => queueMicrotask(() => void this.runOne(runId).catch(() => {})),\n };\n this.singletons = new SingletonGate({\n store: this.store,\n clock: this.clock,\n dispatch: (runId) => {\n this.runDispatcher.dispatch(runId);\n },\n configFor: (run) =>\n (\n this.workflows.get(versionKey(run.workflow, run.workflowVersion)) ??\n this.latest.get(run.workflow)\n )?.singleton,\n });\n this.pool.bind(\n async (result) => {\n // In-memory path (a `timeoutMs` step awaiting on THIS instance): resolve its pending promise.\n const waiter = this.pending.get(result.stepId);\n if (waiter) {\n this.pending.delete(result.stepId);\n if (result.status === 'completed') {\n waiter.resolve({\n output: result.output,\n startedAt: result.startedAt,\n events: result.events,\n });\n } else {\n waiter.reject(new RemoteStepError(result.error));\n }\n return;\n }\n // Durable path: no in-memory waiter (the step suspended the run, possibly on another\n // instance) → complete the checkpoint and resume the run here.\n await this.completeRemoteResult(result);\n },\n // A heartbeat resets the liveness window for whatever it targets: an in-flight long STEP (keyed\n // by stepId, see callRemote) or — when stepId is absent — the in-flight workflow TURN (keyed by\n // runId). For an INLINE-advance turn the reset is an in-memory callback; for a DISPATCH-suspend\n // turn there is no in-memory waiter, so a run-scoped beat rearms the suspended turn's durable\n // re-drive deadline (`wakeAt`) instead, keeping a live worker's turn from being re-dispatched.\n async (beat) => {\n const reset = this.heartbeatResets.get(beat.stepId ?? beat.runId);\n if (reset) {\n reset();\n return;\n }\n if (beat.stepId === undefined) await this.rearmDecisionDeadline(beat.runId);\n },\n // A remote workflow worker streams each local step's lifecycle (running → completed/failed) so\n // it's checkpointed live, not all-at-once when the long turn ends.\n async (event) => {\n await this.persistStepEvent(event);\n },\n // A workflow-turn DECISION delivered over the broker — applied durably (by run id) on whatever\n // instance consumes it, NOT correlated to an in-memory promise on the dispatcher. This is the\n // multi-instance fix: a point-to-point broker may hand the decision to a non-dispatching instance.\n async (decision) => {\n await this.completeRemoteDecision(decision);\n },\n );\n // Control-plane start-run: a DB-less tenant worker publishes a StartRunMessage and this\n // (control-plane) engine turns it into a durable run stamped with the tenant's namespace. Guarded\n // by the transport's `onStartRun` capability (like the other optional transport hooks) — a pool\n // whose transport can't carry the channel simply never registers, so a worker-only engine no-ops.\n this.pool.onStartRun(async (message) => {\n await this.start(\n message.workflow,\n message.input,\n message.runId ?? globalThis.crypto.randomUUID(),\n {\n namespace: message.tenant,\n tags: message.tags,\n searchAttributes: message.searchAttributes,\n },\n );\n });\n // Control plane: re-broadcast lifecycle events from OTHER instances to this instance's\n // subscribers (cross-pod live-tail), and act on cancellations issued elsewhere. A broker may\n // echo our own publish back — ignore those (we already handled them locally) to avoid duplicates.\n this.controlPlane?.onControl((msg) => {\n if (msg.from === this.instanceId) return;\n if (msg.kind === 'event') {\n // `at` may be a string after JSON transit (Redis) — normalize back to a Date.\n this.deliver({ ...msg.event, at: new Date(msg.event.at) });\n } else if (msg.kind === 'cancel') {\n this.notifyCancelled(msg.runId);\n } else if (msg.kind === 'enqueued') {\n // A run was enqueued on another instance — let worker subscribers pick it up immediately\n // instead of waiting for the next poll. (Self-broadcasts are already filtered above.)\n for (const fn of this.enqueuedListeners) {\n try {\n fn(msg.runId);\n } catch {\n /* an enqueue listener must not break the engine */\n }\n }\n }\n });\n this.accumulators = new EventAccumulators(this);\n this.entities = new Entities(this);\n }\n\n /**\n * Register a **durable entity** (a virtual object): a keyed actor whose `handlers` run **serialized\n * per key** over **durable state**, exactly once. Drive it with `signalEntity` (fire) /\n * `ctx.callEntity` (call + await result) and read its state with `getEntityState`. See {@link Entities}.\n */\n registerEntity<S>(name: string, config: EntityConfig<S>): void {\n this.entities.register(name, config);\n }\n\n /** Send an operation to an entity (fire-and-forget). Ordered + exactly-once per key. */\n signalEntity(name: string, key: string, op: string, arg?: unknown): Promise<void> {\n return this.entities.signal(name, key, op, arg);\n }\n\n /** Read an entity's current durable state (published after each op), or undefined if it has none yet. */\n getEntityState<S = unknown>(name: string, key: string): Promise<S | undefined> {\n return this.entities.getState<S>(name, key);\n }\n\n /**\n * Be notified when a run is enqueued on ANOTHER instance (via the control plane), so a worker can\n * pick it up at once — e.g. `engine.onEnqueued((runId) => engine.runOne(runId))`. Returns an\n * unsubscribe function. Only wire this on instances that should execute runs (workers).\n */\n onEnqueued(listener: (runId: string) => void): () => void {\n this.enqueuedListeners.add(listener);\n return () => this.enqueuedListeners.delete(listener);\n }\n\n /** Fire cooperative-cancellation listeners for `runId` (a worker bridge aborts in-flight work). */\n private notifyCancelled(runId: string): void {\n for (const fn of this.cancelListeners) {\n try {\n fn(runId);\n } catch {\n /* a cancel listener must not break the engine */\n }\n }\n }\n\n /**\n * Register a workflow version. Register multiple versions of the same name to keep in-flight\n * runs working across a breaking change: old runs resume on the version they started on, new\n * runs start on the newest registered version.\n *\n * GROUP-SERVED (uniform dispatch, opt-in): pass `{ group, executor }` to have the engine DISPATCH\n * this workflow's turns to a worker `group` (via `executor.advance`) instead of running `fn`\n * inline — exactly as {@link registerRemote} does for a cross-SDK (e.g. Python) body, EXCEPT the\n * body is a TS `fn` the engine retains so an IN-APP worker on `group` can fetch it by name\n * ({@link workflowBody}) and run it. This is \"one app, both roles\": the same process owns the\n * engine AND consumes its own group. Recovery, timers, singleton, cancel and dead-lettering stay\n * engine concerns, identical to a remote run. OMIT `group`/`executor` (the default) to keep the\n * inline fast path — `fn` runs in-process and the run pays zero dispatch round-trips. The first\n * step toward routing every run through a group with no local/remote flag (Phase 3).\n */\n register(\n name: string,\n version: string,\n fn: WorkflowFn,\n opts?: {\n tags?: string[] | undefined;\n singleton?: SingletonConfig | undefined;\n executionTimeout?: string | number | undefined;\n validateInput?: ((input: unknown) => void | Promise<void>) | undefined;\n /** Typed/validated `searchAttributes` shape — see `RegisteredWorkflow.searchAttributesSchema`. */\n searchAttributesSchema?: SearchAttributesSchema | undefined;\n onEvent?: string[] | undefined;\n eventBatch?: EventBatchConfig | undefined;\n /** Worker group to DISPATCH this workflow's turns to (uniform dispatch). Requires `executor`.\n * Omit for the default inline fast path. See the method doc. */\n group?: string | undefined;\n /** Advances a turn by dispatching a {@link WorkflowTask} to `group`. Requires `group`. For an\n * in-app worker, pair a transport-backed {@link RemoteWorkflowExecutor} (group consumed by a\n * worker that calls {@link workflowBody}) so the retained `fn` runs through the transport hop. */\n executor?: WorkflowExecutor | undefined;\n },\n ): void {\n // Group-served is all-or-nothing: a `group` with no `executor` (or vice-versa) is a wiring bug —\n // fail loudly at registration rather than silently falling back to the inline path at dispatch.\n if ((opts?.group == null) !== (opts?.executor == null)) {\n throw new Error(\n `workflow ${name}@${version}: register({ group, executor }) needs BOTH group and executor (or neither)`,\n );\n }\n const registered: RegisteredWorkflow = {\n name,\n version,\n fn,\n tags: opts?.tags,\n singleton: opts?.singleton,\n executionTimeoutMs:\n opts?.executionTimeout != null ? parseDuration(opts.executionTimeout) : undefined,\n validateInput: opts?.validateInput,\n searchAttributesSchema: opts?.searchAttributesSchema,\n onEvent: opts?.onEvent,\n eventBatch: opts?.eventBatch,\n // A real, retained in-process body — so `workflowBody` can hand it to an in-app worker, and so\n // it is NOT confused with the throwing stub `registerRemote` installs for a body-less remote.\n hasBody: true,\n };\n // When group-served, route DISPATCH through the executor (the same `remote` branch a Python\n // workflow takes); `fn` above stays usable for the in-app worker. Omitted = inline fast path.\n if (opts?.group != null && opts?.executor != null) {\n registered.remote = { group: opts.group, executor: opts.executor };\n }\n this.workflows.set(versionKey(name, version), registered);\n const current = this.latest.get(name);\n if (!current || isNewerVersion(version, current.version)) this.latest.set(name, registered);\n for (const event of opts?.onEvent ?? []) {\n const subscribers = this.eventTriggers.get(event) ?? new Set<string>();\n subscribers.add(name);\n this.eventTriggers.set(event, subscribers);\n }\n }\n\n /**\n * The retained in-process body for `name@version`, for an IN-APP worker that consumes this engine's\n * own group to SERVE a group-served `register(..., { group, executor })` workflow (uniform dispatch):\n * the worker fetches the body by name when it picks up the dispatched {@link WorkflowTask}, replays\n * it, and returns the {@link WorkflowDecision}. `undefined` for an unregistered name or a body-less\n * remote (a `registerRemote` / synthesized child carries only a throwing stub, never handed out).\n */\n workflowBody(name: string, version: string): WorkflowFn | undefined {\n const reg = this.workflows.get(versionKey(name, version));\n return reg?.hasBody ? reg.fn : undefined;\n }\n\n /**\n * Register a workflow whose body runs in another SDK (e.g. Python). The engine owns the run exactly\n * as for a TS workflow — it persists checkpoints, recovers, runs timers — but advances it by handing\n * the run's history to `executor` (which dispatches a {@link WorkflowTask} to the worker) and applying\n * the {@link WorkflowDecision} the worker's replay returns. The worker never touches the store.\n */\n registerRemote(\n name: string,\n version: string,\n opts: {\n group: string;\n executor: WorkflowExecutor;\n tags?: string[];\n singleton?: SingletonConfig;\n executionTimeout?: string | number;\n validateInput?: (input: unknown) => void | Promise<void>;\n },\n ): void {\n const registered: RegisteredWorkflow = {\n name,\n version,\n // A remote workflow has no in-process body; execute() branches on `remote` before this is read.\n fn: () => {\n throw new Error(`workflow ${name} is remote — it has no in-process body`);\n },\n tags: opts.tags,\n singleton: opts.singleton,\n executionTimeoutMs:\n opts.executionTimeout != null ? parseDuration(opts.executionTimeout) : undefined,\n validateInput: opts.validateInput,\n remote: { group: opts.group, executor: opts.executor },\n };\n this.workflows.set(versionKey(name, version), registered);\n const current = this.latest.get(name);\n if (!current || isNewerVersion(version, current.version)) this.latest.set(name, registered);\n }\n\n /**\n * The convenience form of {@link registerRemote}: register a workflow whose body runs on a worker\n * `group` (e.g. the Python `durable-worker`, or a separate TS worker), without hand-building a\n * {@link RemoteWorkflowExecutor}. It wires the standard broker executor — a `RemoteWorkflowExecutor`\n * over the engine's own transport, dispatching to `opts.group` — for you, so you write\n * `engine.remote('processing', { group: 'processing' })` instead of\n * `engine.registerRemote('processing', '1', { group: 'processing', executor: new RemoteWorkflowExecutor(transport, 'processing') })`.\n *\n * Defaults the version to `'1'`. All the other {@link registerRemote} options\n * (`tags` / `singleton` / `executionTimeout` / `validateInput`) pass straight through. Reach for the\n * low-level {@link registerRemote} when you need a custom {@link WorkflowExecutor} (a different\n * transport, a fixed `timeoutMs`, a polyglot stub) — `remote()` is the standard wiring on the rails.\n */\n remote(\n name: string,\n opts: {\n /** Worker group this workflow's turns are dispatched to (also the executor's target group). */\n group: string;\n /** Workflow version. Defaults to `'1'`. */\n version?: string;\n tags?: string[];\n singleton?: SingletonConfig;\n executionTimeout?: string | number;\n validateInput?: (input: unknown) => void | Promise<void>;\n },\n ): void {\n const { group, version, ...rest } = opts;\n const executor = new RemoteWorkflowExecutor(this.pool.primary, group);\n this.registerRemote(name, version ?? '1', { group, executor, ...rest });\n }\n\n /**\n * Register a flow-control queue referenced by `ctx.step(step, input, { queue })`. Caps concurrent\n * in-flight steps and/or the admission rate; blocked calls re-suspend and retry, so the limit is\n * durable. Per engine instance (see {@link QueueConfig}). Registering the same name replaces it.\n */\n registerQueue(config: QueueConfig): void {\n this.admission.register(config);\n }\n\n /** Subscribe to lifecycle events. Returns an unsubscribe function. */\n subscribe(listener: EngineListener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /**\n * Register a {@link StepInterceptor} — onion middleware run around the real execution of every\n * local `ctx.step` (timing, logging, tracing, error enrichment, context propagation). First\n * registered is outermost; interceptors fire only when a step executes, never on replay. Returns\n * an unsubscribe function.\n */\n use(interceptor: StepInterceptor): () => void {\n this.interceptors.push(interceptor);\n return () => {\n const i = this.interceptors.indexOf(interceptor);\n if (i >= 0) this.interceptors.splice(i, 1);\n };\n }\n\n /**\n * Fold the registered interceptors around a local step body (identity when there are none), then\n * run the whole thing inside the re-hydrated originating context. The carrier is read at execution\n * time from {@link context} — the SAME reader stamped on dispatched remote tasks — so a local step\n * sees the live tenant / user / trace ids ambiently (via the {@link rehydrate} bridge). Default\n * `rehydrate` is a passthrough, so this is byte-identical to a bare body call when unwired.\n */\n private interceptStep<T>(invocation: StepInvocation, body: () => Promise<T>): Promise<T> {\n const carrier = this.context?.();\n const run = (): Promise<T> => {\n if (this.interceptors.length === 0) return body();\n const chain = this.interceptors.reduceRight<() => Promise<unknown>>(\n (next, interceptor) => () => interceptor(invocation, next),\n body as () => Promise<unknown>,\n );\n return chain() as Promise<T>;\n };\n return this.rehydrate(carrier, run);\n }\n\n /**\n * Be notified when a run is cancelled — on ANY instance, via the transport control plane. A\n * worker bridge can use this for cooperative cancellation: abort the in-flight work for `runId`\n * instead of finishing it just to have the result discarded. Returns an unsubscribe function.\n */\n onCancel(listener: (runId: string) => void): () => void {\n this.cancelListeners.add(listener);\n return () => this.cancelListeners.delete(listener);\n }\n\n /**\n * Be notified when a run is **dead-lettered** — moved to `dead` after exceeding\n * `maxRecoveryAttempts`. The listener receives the dead run (status `dead`, with its error), so a\n * DLQ handler can do something other than just leaving it parked: alert, push to a real queue, or\n * start a dead-letter workflow (e.g. `engine.onDead((run) => engine.start('pipeline-dlq', run, ...))`).\n * Returns an unsubscribe function.\n */\n onDead(listener: (run: WorkflowRun) => void): () => void {\n this.deadListeners.add(listener);\n return () => this.deadListeners.delete(listener);\n }\n\n private notifyDead(run: WorkflowRun): void {\n for (const fn of this.deadListeners) {\n try {\n fn(run);\n } catch {\n /* a dead-letter handler must not break recovery */\n }\n }\n }\n\n /** Emit a locally-produced lifecycle event: deliver to subscribers AND broadcast it on the\n * control plane so other instances (e.g. a dashboard pod) can live-tail this run. */\n private emit(event: Omit<EngineEvent, 'at'>): void {\n const full: EngineEvent = { ...event, at: new Date() };\n this.deliver(full);\n if (this.controlPlane) {\n void this.controlPlane\n .publishControl({ kind: 'event', event: full, from: this.instanceId })\n .catch(() => {\n // control-plane delivery is best-effort observability; never break execution\n });\n }\n }\n\n /** Deliver an event to local subscribers only (no re-broadcast) — used for both locally-produced\n * events and ones received from the control plane, so an event shows up once on every instance. */\n private deliver(event: EngineEvent): void {\n for (const listener of this.listeners) {\n try {\n listener(event);\n } catch {\n // a misbehaving subscriber must never break workflow execution\n }\n }\n }\n\n async start<C extends WorkflowClass>(\n workflow: C,\n input: WorkflowInputOf<C>,\n runId: string,\n opts?: StartOptions,\n ): Promise<RunResult>;\n async start<TInput>(\n workflow: string,\n input: TInput,\n runId: string,\n opts?: StartOptions,\n ): Promise<RunResult>;\n async start(\n workflow: WorkflowRef,\n input: unknown,\n runId: string,\n opts?: StartOptions,\n ): Promise<RunResult> {\n const name = workflowName(workflow);\n let registered = this.latest.get(name);\n if (!registered) {\n // An unregistered run inherits remote routing from its spawning ancestor (see\n // {@link findInheritedRegistration}): the child of a remote workflow can be started without a\n // redundant `registerRemote` for its name. The child run doesn't exist yet, but its parent\n // already wrote the `child:<runId>` waiter BEFORE calling start (the remote `startChild` command\n // and `ctx.child`/`ctx.all` all put the waiter first), so the ancestor is discoverable now.\n const ancestor = await this.findRemoteAncestor(runId);\n if (ancestor) registered = this.synthesizeRemoteChild(name, ancestor.version, ancestor);\n }\n if (!registered) {\n // Convention routing: if the transport reports a live group of the same name, synthesize a\n // remote registration on the fly. Version '1' is the convention default (same as engine.remote()).\n const conventionRun: WorkflowRun = {\n id: runId,\n workflow: name,\n workflowVersion: '1',\n status: 'pending',\n // Stamp the namespace the REAL run will carry (below) so convention routing resolves the same\n // tenant-suffixed group the run will dispatch to — an operator starting a tenant's run via the\n // `onStartRun` wire (opts.namespace = tenant) must find the live `<workflow>@<tenant>` group,\n // not the bare group. Without this the start-run entry path can't reach a suffixed-only worker.\n namespace: opts?.namespace ?? this.namespace,\n input,\n createdAt: new Date(),\n updatedAt: new Date(),\n };\n registered = await this.resolveRemoteByConvention(conventionRun);\n }\n if (!registered) throw new Error(`workflow ${name} is not registered`);\n // Validate the input up front — a bad payload is rejected before any run is created.\n await registered.validateInput?.(input);\n // Idempotent by run id: a redelivered trigger (at-least-once queues) or a scheduler re-tick for\n // the same id is a no-op, returning the existing run's state instead of starting a duplicate.\n const prior = await this.store.getRun(runId);\n if (prior) {\n return { runId, status: prior.status, output: prior.output, error: prior.error };\n }\n const now = new Date();\n // A singleton workflow stamps a `singleton:<key>` tag so the admission gate (in execute) can find\n // the other in-flight runs sharing the key via a tag+status query.\n const tags = mergeTags(\n registered.tags,\n registered.singleton\n ? [...(opts?.tags ?? []), this.singletons.tag(registered.singleton, input)]\n : opts?.tags,\n );\n // Singleton back-pressure: reject a start that would grow the same-key backlog past\n // `limit + maxQueueDepth` (no-op when no maxQueueDepth is configured).\n if (registered.singleton) {\n await this.singletons.assertCapacity(name, registered.singleton, input);\n }\n const run: WorkflowRun = {\n id: runId,\n workflow: name,\n workflowVersion: registered.version,\n status: 'pending',\n namespace: opts?.namespace ?? this.namespace,\n input,\n tags,\n searchAttributes: opts?.searchAttributes,\n priority: opts?.priority,\n createdAt: now,\n updatedAt: now,\n };\n await this.store.createRun(run);\n // The run is durably enqueued; a dispatcher (in-process by default) executes it — `start` does\n // NOT run the body inline. Await the terminal/suspended state with `waitForRun(runId)` if needed.\n await this.runDispatcher.dispatch(runId);\n // Nudge worker instances to pick it up now instead of on their next poll (no-op without a control\n // plane; self-receipt is filtered, so it only helps OTHER pods — e.g. an API pod's enqueue).\n if (this.controlPlane) {\n void this.controlPlane\n .publishControl({ kind: 'enqueued', runId, from: this.instanceId })\n .catch(() => undefined);\n }\n return { runId, status: 'pending' };\n }\n\n /** Read a run's current persisted state (or null if unknown). A thin pass-through to the store. */\n getRun(runId: string): Promise<WorkflowRun | null> {\n return this.store.getRun(runId);\n }\n\n async resume(runId: string): Promise<RunResult> {\n const run = await this.store.getRun(runId);\n if (!run) throw new Error(`run ${runId} not found`);\n // A definitively-finished run must not be re-executed (e.g. a worker result landing after the\n // run was cancelled, or a duplicate resume) — that would replay the body and clobber the\n // terminal state. `failed` is intentionally NOT terminal here: retry resumes a failed run.\n if (run.status === 'cancelled' || run.status === 'completed' || run.status === 'dead') {\n return { runId, status: run.status, output: run.output, error: run.error };\n }\n // Namespace guard: release the lock and bail when this run belongs to a different worker pool.\n // Piggybacked on the existing store.getRun above — no extra async step on the happy path.\n // An undefined namespace (a store adapter that doesn't persist the field yet) is treated as\n // \"belongs to everyone\" for back-compat: don't skip it. Likewise, this ENGINE having an\n // undefined namespace means it's an operator control plane — it belongs to every namespace too,\n // so the guard never applies to it.\n if (\n this.namespace !== undefined &&\n run.namespace !== undefined &&\n run.namespace !== this.namespace\n ) {\n await this.store.releaseRunLock(runId);\n throw new NamespaceMismatch();\n }\n // Pin to the version the run STARTED on — replay is positional, so running a changed\n // workflow body against old checkpoints would corrupt the run. The direct lookup is synchronous\n // (`??` short-circuits): a registered run never awaits here, so its resume timing is unchanged —\n // only an UNREGISTERED run pays the inheritance walk (see {@link findInheritedRegistration}).\n const registered =\n this.workflows.get(versionKey(run.workflow, run.workflowVersion)) ??\n (await this.findInheritedRegistration(run)) ??\n (await this.resolveRemoteByConvention(run));\n if (!registered) {\n throw new Error(\n `workflow ${run.workflow}@${run.workflowVersion} is not registered — keep the prior version deployed so in-flight runs can drain (skew protection)`,\n );\n }\n return this.track(this.execute(run, registered.fn));\n }\n\n /**\n * The registration for an UNREGISTERED run, INHERITED from its nearest REMOTE ancestor — or\n * `undefined` if it has none (the skew-protection error case in {@link resume}). Callers check the\n * flat registry FIRST (so an explicit `registerRemote(name, …)` ALWAYS wins, and a registered run\n * never reaches here); this resolves only the new case: a child spawned by a remote workflow (e.g. a\n * Python `gather_children` / `start_child` fan-out) of a name the host never `registerRemote`-ed. It\n * is driven as a remote run on the ancestor's group + the SAME executor instance, so the host needs\n * no redundant registration per child name.\n *\n * RECOMPUTED per resume rather than memoized into `this.workflows`: a synthesized child is not a real\n * registration and must not leak into `latest`, `knownGroups`, or `sweepTimeouts` (which iterate the\n * registry); recomputing also stays correct if the ancestor's remote registration is re-pointed at a\n * new executor across a deploy. Only unregistered runs pay it, so registered workflows pay nothing.\n */\n private async findInheritedRegistration(\n run: WorkflowRun,\n ): Promise<RegisteredWorkflow | undefined> {\n const ancestor = await this.findRemoteAncestor(run.id);\n if (!ancestor) return undefined;\n return this.synthesizeRemoteChild(run.workflow, run.workflowVersion, ancestor);\n }\n\n /**\n * A throwaway {@link RegisteredWorkflow} that routes `name@version` as a remote run on the ancestor's\n * group via the ancestor's SAME executor instance. The executor is group-scoped (it dispatches a\n * {@link WorkflowTask} carrying `run.workflow`, and the worker picks the body by name), so reusing it\n * is correct AND required — a second executor on the same group would race the worker for results.\n * Only `remote` is inherited; the child gets none of the ancestor's singleton/timeout/validator, so\n * its identity stays its own.\n */\n private synthesizeRemoteChild(\n name: string,\n version: string,\n ancestor: RegisteredWorkflow,\n ): RegisteredWorkflow {\n // `ancestor` always carries `remote` (findRemoteAncestor / start only pass a remote registration);\n // the guard narrows the optional type without an unsafe cast and documents the invariant.\n const remote = ancestor.remote;\n if (!remote) throw new Error(`workflow ${ancestor.name} is not a remote workflow`);\n return {\n name,\n version,\n fn: () => {\n throw new Error(`workflow ${name} is remote — it has no in-process body`);\n },\n remote,\n };\n }\n\n /**\n * Attempt to route an unregistered workflow to the live worker group of the same name: if the\n * transport reports a live heartbeat for group `run.workflow`, synthesize a throwaway\n * {@link RegisteredWorkflow} that dispatches to that group over the primary transport. Returns\n * `undefined` when the group is not live. Always attempted — there is no opt-in flag; an explicit\n * `register`/`registerRemote` still takes precedence (this only runs when nothing is registered).\n *\n * Recomputed per call (never memoized into `this.workflows`) so it stays correct if group\n * liveness changes between calls, exactly as {@link synthesizeRemoteChild} does.\n */\n private async resolveRemoteByConvention(\n run: WorkflowRun,\n ): Promise<RegisteredWorkflow | undefined> {\n // Workers register/heartbeat their liveGroups under the SANITIZED token (`sanitizeQueueToken`),\n // so the membership check must sanitize too — else a `:`-named workflow's live worker is under\n // `orders-fulfill` while this computes `orders:fulfill` and never matches.\n const group = tenantGroup(sanitizeQueueToken(run.workflow), run.namespace);\n // Resolve the TRANSPORT the group is live on, not just membership in the merged list: in a\n // mixed pool (a tenant-scoped control plane pairing its namespaced transport with a bare-prefix\n // one for operator-convention tenant workers), each transport scans a different keyspace —\n // dispatching on `primary` while the worker heartbeats on another transport would park the turn\n // on a queue nobody consumes.\n const liveTransport = await this.pool.transportWithLiveGroup(group);\n if (!liveTransport) return undefined;\n // Feed the workflow NAME + namespace-as-partition through, rather than the pre-combined\n // `group` string above — the executor computes the identical token itself (name+partition is\n // the new routing primitive; `group` here still exists only for the liveGroups membership check).\n const executor = new RemoteWorkflowExecutor(liveTransport, run.workflow, run.namespace);\n return {\n name: run.workflow,\n version: run.workflowVersion,\n fn: () => {\n throw new Error(`remote workflow ${run.workflow} has no local body`);\n },\n hasBody: false,\n remote: { group, executor },\n };\n }\n\n /**\n * Walk the parent chain of `childRunId` to the nearest ancestor registered as REMOTE, returning its\n * registration (or `undefined` if there is none). The parent of an awaited child is found via its\n * live `child:<childId>` signal waiter — present for as long as the parent is suspended awaiting the\n * child, i.e. throughout the child's executable lifetime (start, every resume, crash recovery, cancel\n * cascade), which is exactly when we resolve. A registered-but-LOCAL parent stops the walk (an\n * unregistered child of a TS workflow is a genuine misconfiguration → skew error); only an\n * unregistered parent keeps walking, so a child of an inherited child still reaches the remote root.\n * `visited` guards against a pathological cyclic id graph.\n */\n private async findRemoteAncestor(\n childRunId: string,\n visited = new Set<string>(),\n ): Promise<RegisteredWorkflow | undefined> {\n if (visited.has(childRunId)) return undefined;\n visited.add(childRunId);\n const parentRunId = await this.findParentRunId(childRunId);\n if (!parentRunId) return undefined;\n const parent = await this.store.getRun(parentRunId);\n if (!parent) return undefined;\n const parentReg = this.workflows.get(versionKey(parent.workflow, parent.workflowVersion));\n if (parentReg?.remote) return parentReg;\n if (parentReg) return undefined;\n return this.findRemoteAncestor(parent.id, visited);\n }\n\n /**\n * The run that spawned `childRunId`, via its live `child:<childRunId>` signal waiter — every awaited\n * child (`ctx.child`, `ctx.all`, a remote `start_child`) suspends its parent on exactly this waiter,\n * and the waiter is written BEFORE the child is started. Only reached for an UNREGISTERED child, so\n * registered runs never pay the scan; returns `undefined` once the parent has settled the child (the\n * waiter is consumed), but by then the child is terminal and no longer resolved.\n */\n private async findParentRunId(childRunId: string): Promise<string | undefined> {\n const token = `child:${childRunId}`;\n for (const waiter of await this.store.listSignalWaiters('child:')) {\n if (waiter.token === token) return waiter.runId;\n }\n return undefined;\n }\n\n /** Track an in-flight execution so {@link drain} can wait for it. */\n private track(p: Promise<RunResult>): Promise<RunResult> {\n this.inflight.add(p);\n void p.finally(() => this.inflight.delete(p));\n return p;\n }\n\n /**\n * Graceful shutdown: stop picking up new runs (recovery/timer become no-ops) and wait for\n * in-flight executions to settle, up to `timeoutMs`. Call from your app's shutdown hook so a\n * deploy hands off cleanly instead of leaving runs to the lease timeout.\n */\n async drain(timeoutMs = 10_000): Promise<void> {\n this.draining = true;\n if (this.inflight.size === 0) return;\n const timer = new Promise<void>((resolve) => {\n const t = setTimeout(resolve, timeoutMs);\n (t as { unref?: () => void }).unref?.();\n });\n await Promise.race([Promise.allSettled([...this.inflight]), timer]);\n }\n\n /**\n * Cancel in-flight runs that have outlived their workflow's `executionTimeout`. Call it from the\n * timer poller alongside {@link resumeDueTimers}. A timed-out run is moved to `cancelled` with an\n * `execution_timeout` error (terminal, so a late step result can't resurrect it).\n */\n async sweepTimeouts(now: number = this.clock()): Promise<void> {\n for (const reg of new Set(this.latest.values())) {\n if (reg.executionTimeoutMs == null) continue;\n const deadline = now - reg.executionTimeoutMs;\n const inflight = [\n ...(await this.store.listRuns({\n workflow: reg.name,\n status: 'running',\n namespace: this.namespace,\n })),\n ...(await this.store.listRuns({\n workflow: reg.name,\n status: 'suspended',\n namespace: this.namespace,\n })),\n ];\n for (const run of inflight) {\n if (run.createdAt.getTime() > deadline) continue;\n const error = { message: 'execution timeout', code: 'execution_timeout' };\n await this.store.updateRun(run.id, { status: 'cancelled', error, updatedAt: new Date() });\n this.emit({\n type: 'run.failed',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n error,\n });\n }\n }\n }\n\n /**\n * Resume every run left incomplete by a crash or deploy. Called on boot. Completed steps\n * replay from their checkpoints, so only the work that had not finished runs again.\n */\n async recoverIncomplete(nowMs: number = this.clock()): Promise<RunResult[]> {\n if (this.draining) return [];\n const results: RunResult[] = [];\n for (const run of await this.store.listIncompleteRuns(this.namespace)) {\n // A live worker renews its lease, so an acquirable lease means the run is genuinely orphaned\n // (its worker crashed). Skip the ones still owned.\n const acquired = await this.store.tryLockRun(\n run.id,\n this.instanceId,\n nowMs + this.leaseMs,\n nowMs,\n );\n if (!acquired) continue;\n // Count the attempt / dead-letter a poison pill past maxRecoveryAttempts.\n const settled = await this.countRecovery(run);\n if (settled) {\n results.push(settled);\n continue;\n }\n // Re-enqueue rather than resume inline: recovery must NOT block (boot, or a poll tick) on a\n // long workflow step. A dispatcher/worker re-runs it, replaying its checkpoints.\n await this.store.releaseRunLock(run.id);\n // A `cancelling` run keeps its status (resetting to `pending` would lose the persisted cancel\n // intent and resurrect the run): the re-driven turn re-derives it from the status and finishes\n // the cancel. Every other run re-enqueues as `pending` for a clean (re)start.\n if (run.status !== 'cancelling') {\n await this.store.updateRun(run.id, { status: 'pending', updatedAt: new Date() });\n }\n await this.runDispatcher.dispatch(run.id);\n results.push({\n runId: run.id,\n status: run.status === 'cancelling' ? 'cancelling' : 'pending',\n });\n }\n return results;\n }\n\n /**\n * Per-recovery bookkeeping (called once the lease is held): count the attempt, or — past\n * `maxRecoveryAttempts` — move a poison pill to the `dead` dead-letter state. Returns a terminal\n * result to skip the resume, or `undefined` to proceed.\n */\n private async countRecovery(run: WorkflowRun): Promise<RunResult | undefined> {\n const attempts = (run.recoveryAttempts ?? 0) + 1;\n if (this.maxRecoveryAttempts != null && attempts > this.maxRecoveryAttempts) {\n const error = {\n message: `run exceeded maxRecoveryAttempts (${this.maxRecoveryAttempts}) — moved to dead-letter`,\n code: 'max_recovery_attempts',\n };\n await this.store.updateRun(run.id, { status: 'dead', error, updatedAt: new Date() });\n await this.store.releaseRunLock(run.id);\n this.emit({\n type: 'run.failed',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n error,\n });\n this.notifyDead({ ...run, status: 'dead', error, recoveryAttempts: attempts });\n return { runId: run.id, status: 'dead', error };\n }\n // Count BEFORE resuming, so a crash mid-resume still advances the counter.\n await this.store.updateRun(run.id, { recoveryAttempts: attempts, updatedAt: new Date() });\n return undefined;\n }\n\n /**\n * Resume every suspended run whose durable timer is due. Call periodically (a poller) and on\n * boot. A run still not due re-suspends cheaply without running new work.\n *\n * Piggy-backs the signal/event-waiter reconcile safety net (see {@link reconcileSignalWaiter}): a\n * crash between the waiter/buffer pairing ops on EITHER side (this run's own `putSignalWaiter` →\n * `takeBufferedSignal`/`listBufferedEvents`, or the other side's `takeSignalWaiter`/fan-out →\n * `bufferSignal`/`bufferEvent` → re-check — see `signal`'s interleaving proof, which `publishEvent`\n * mirrors for events) can leave both rows stranded with nothing left to pair them: the waiter's turn\n * already suspended, the other side that buffered it already returned. Event-wait suspends already\n * carry a `reconcileMs` fallback `wakeAt` (see {@link reconcileWakeAt}) precisely so they show up\n * HERE — that's what makes this due-timer pass the natural place for the sweep (and, for events, also\n * where an `eventBufferTtlMs` prune piggy-backs — see {@link reconcileBufferedEvent}). One bulk waiter\n * scan, filtered to just this tick's batch, keeps it cheap regardless of store size.\n */\n async resumeDueTimers(nowMs: number = this.clock()): Promise<RunResult[]> {\n const due = await this.store.listDueTimers(nowMs, this.namespace);\n if (due.length === 0) return [];\n const waiterByRun = indexWaitersByRun(await this.store.listSignalWaiters(''));\n return this.resumeLeased(due, nowMs, (run) =>\n this.reconcileSignalWaiter(run, waiterByRun.get(run.id)),\n );\n }\n\n /**\n * The reconcile safety net's per-run check (see {@link resumeDueTimers}): if this suspended run has\n * a registered signal OR event waiter and a matching payload is already buffered, pair and deliver\n * them directly instead of falling through to a full replay. Child/breakpoint waiter tokens are\n * never buffered (a child/breakpoint notifies via `signal` only once its counterpart is already\n * registered) — `takeBufferedSignal` on those is a guaranteed miss, so this only ever does real work\n * for a plain signal or an event waiter (classified via {@link isEventToken}).\n *\n * Also opportunistically prunes expired buffered EVENTS for this waiter's name when\n * {@link eventBufferTtlMs} is set (see its doc — scoped to names a registered waiter references in\n * this tick's batch, piggy-backing the SAME scan rather than a separate pass), even on a miss.\n *\n * Returns `undefined` (not settled — `resumeLeased` proceeds with its normal `resume`) when there's\n * no waiter or no buffered hit. Deliberately never returns `null`: a delivered signal always resumes\n * via {@link deliverSignal}, and even a `NamespaceMismatch` there is reported as a real (non-nullish)\n * result — returning `null` would read as \"not settled\" to `resumeLeased`'s `??` fallback and\n * trigger a second, redundant `resume` call on the same run.\n */\n private async reconcileSignalWaiter(\n run: WorkflowRun,\n waiter: SignalWaiter | undefined,\n ): Promise<RunResult | undefined> {\n if (!waiter) return undefined;\n if (isEventToken(waiter.token)) return this.reconcileBufferedEvent(run, waiter);\n const buffered = await this.store.takeBufferedSignal(waiter.token);\n if (!buffered) return undefined;\n await this.store.removeSignalWaiter(waiter);\n const settled = await this.deliverSignal(waiter, buffered.payload);\n return settled ?? { runId: run.id, status: run.status };\n }\n\n /**\n * The EVENT half of {@link reconcileSignalWaiter}: scan this waiter's name for a matching buffered\n * event (same list+evaluate+claim shape as `waitForEvent`'s own consumption — the match predicate\n * belongs to the waiter, never the store), pruning any expired candidates it encounters along the\n * way when {@link eventBufferTtlMs} is configured. A pruned-but-non-matching candidate does not stop\n * the scan; only a MATCHING hit (or exhausting the scan window) does.\n */\n private async reconcileBufferedEvent(\n run: WorkflowRun,\n waiter: SignalWaiter,\n ): Promise<RunResult | undefined> {\n const name = eventNameOf(waiter.token);\n const match = eventMatchOf(waiter.token);\n const candidates = await this.store.listBufferedEvents(name, EVENT_BUFFER_SCAN_LIMIT);\n const nowMs = this.clock();\n for (const candidate of candidates) {\n if (this.eventBufferTtlMs != null && nowMs - candidate.publishedAt > this.eventBufferTtlMs) {\n await this.store.removeBufferedEvent(candidate.id); // expired — prune regardless of match\n continue;\n }\n if (!eventMatches(candidate.payload, match)) continue;\n if (!(await this.store.removeBufferedEvent(candidate.id))) continue; // raced away — try the next\n await this.store.removeSignalWaiter(waiter);\n const settled = await this.deliverSignal(waiter, candidate.payload);\n return settled ?? { runId: run.id, status: run.status };\n }\n return undefined;\n }\n\n /**\n * Lease and execute one run by id — the worker side of dispatch. Acquires the recovery lease (so\n * exactly one instance runs it), then resumes the body. Returns the result, or null if another\n * instance holds the lease or the engine is draining. The default in-process dispatcher calls this;\n * a broker-backed worker calls it per consumed run id.\n */\n async runOne(runId: string): Promise<RunResult | null> {\n if (this.draining) return null;\n const nowMs = this.clock();\n const acquired = await this.store.tryLockRun(\n runId,\n this.instanceId,\n nowMs + this.leaseMs,\n nowMs,\n );\n if (!acquired) return null;\n // resume() checks the namespace and throws NamespaceMismatch when it doesn't match — no extra\n // await before the call, so the microtask ordering (critical for cancel-safety) is unchanged.\n return this.resume(runId).catch((err) => {\n if (err instanceof NamespaceMismatch) return null;\n throw err;\n });\n }\n\n /**\n * Re-enqueue a run for a worker to (re-)execute — the dispatch-model **retry**. Sets it back to\n * `pending`, clears any stale lease, and dispatches; a worker resumes it (replaying its checkpoints,\n * re-attempting the failed step). Returns the enqueued state immediately — never runs the body\n * inline — or null if the run is unknown. The dashboard \"retry\" goes through here so it can't block\n * the HTTP request on workflow execution.\n */\n async requeue(runId: string): Promise<RunResult | null> {\n const run = await this.store.getRun(runId);\n if (!run) return null;\n await this.store.releaseRunLock(runId);\n await this.store.updateRun(runId, { status: 'pending', updatedAt: new Date() });\n await this.runDispatcher.dispatch(runId);\n return { runId, status: 'pending' };\n }\n\n /**\n * Explicitly re-dispatch every remote step of `runId` stuck `pending` — the OPERATOR escape hatch for\n * a run whose dispatched step job was LOST (worker crashed with no result, or a transport that dropped\n * the job). No automatic recovery re-drives these: a reconcile re-drive re-suspends a still-pending\n * step by design (unless `remoteRedispatchMs` is set), `recoverIncomplete` only reclaims LEASED runs,\n * and `requeue` just replays back to the pending guard. This re-enqueues the same `stepId` so the\n * (idempotent) step re-runs and its result resumes the run. Safe to call on a healthy run — it re-runs\n * only in-flight `pending` remote steps, which are idempotent by the durable contract. Returns the\n * run's current status (with the count re-dispatched), or null if the run is unknown.\n */\n async redispatchPending(runId: string): Promise<(RunResult & { redispatched: number }) | null> {\n const run = await this.store.getRun(runId);\n if (!run) return null;\n const pending = (await this.store.listCheckpoints(runId)).filter(\n (cp) => cp.kind === 'remote' && cp.status === 'pending',\n );\n let redispatched = 0;\n for (const cp of pending) {\n if (!cp.stepId) continue;\n const reAttempt = cp.attempts + 1;\n const reEnqueuedAt = new Date();\n await this.store.saveCheckpoint({\n ...cp,\n attempts: reAttempt,\n enqueuedAt: reEnqueuedAt,\n startedAt: reEnqueuedAt,\n finishedAt: reEnqueuedAt,\n });\n await this.dispatchRemoteTask({\n runId,\n seq: cp.seq,\n name: cp.name,\n stepId: cp.stepId,\n group: cp.workerGroup ?? sanitizeQueueToken(cp.name),\n input: cp.input,\n attempt: reAttempt,\n });\n redispatched += 1;\n }\n return { runId, status: run.status, redispatched };\n }\n\n /**\n * **Fix-and-replay**: re-run a run (typically a `dead`/`failed` one) with a corrected `input`, as a\n * fresh run with clean history. It's a NEW run — `newRunId` defaults to `<runId>~retry~<uuid>` — so\n * the original stays inspectable. Returns the new run's id, or null if `runId` is unknown.\n */\n async retryWithInput(\n runId: string,\n input: unknown,\n newRunId?: string,\n ): Promise<{ runId: string } | null> {\n const run = await this.store.getRun(runId);\n if (!run) return null;\n const id = newRunId ?? `${runId}~retry~${globalThis.crypto.randomUUID().slice(0, 8)}`;\n // Inherit the original run's namespace so a retry of a tenant's run stays that tenant's — on an\n // operator (this.namespace === undefined) an unstamped retry would fall to 'default' and route to\n // the bare worker group, orphaning it if only the tenant-suffixed worker is live.\n await this.start(run.workflow, input, id, { tags: run.tags, namespace: run.namespace });\n return { runId: id };\n }\n\n /**\n * Pick up and execute every `pending` run — the poll-based side of dispatch for a worker pod with\n * no broker. Runs enqueued by other pods (or by a caller using a no-op dispatcher) sit `pending`\n * in the store until polled; leasing ensures exactly one pod runs each. Call periodically alongside\n * {@link resumeDueTimers}.\n */\n async runPending(nowMs: number = this.clock()): Promise<RunResult[]> {\n // Oldest-first (FIFO), capped per call so a backlog drains over several polls without one sweep\n // fetching unboundedly. A run not picked up this tick is picked up the next.\n return this.resumeLeased(await this.store.listPendingRuns(100, this.namespace), nowMs);\n }\n\n /**\n * Resolve once `runId` reaches a settled state — terminal (completed/failed/cancelled/dead) or\n * suspended (handed off to a timer/signal/event). The async counterpart to dispatch: pair it with\n * `start` when a call site needs the outcome — `await start(...); const r = await waitForRun(id)`.\n */\n waitForRun(\n runId: string,\n opts?: { timeoutMs?: number; until?: 'settled' | 'terminal' },\n ): Promise<RunResult> {\n // `cancelling` is NON-terminal (the saga undo is still running), so a `waitForRun` after a\n // compensating cancel keeps waiting until the run reaches the terminal `cancelled`.\n //\n // A run in the DISPATCH-AND-SUSPEND liveness state — `suspended` while still awaiting a dispatched\n // workflow TURN's decision (`awaitingDecisionTaskId` set) — is mid-turn, NOT settled: that\n // `suspended` is the engine's re-drive marker, not a body-emitted sleep/signal suspend. Resolving on\n // it would hand back a half-applied turn (e.g. a sleep whose `wakeAt` the decision hasn't written\n // yet). Wait until the decision lands and clears the marker (a real suspend) or the run goes terminal.\n //\n // `until: 'terminal'` skips settling on a real suspend too — it resolves only on\n // completed/failed/cancelled/dead (the wait behind `MyWorkflow.execute()` outside a workflow).\n const TERMINAL: ReadonlySet<string> = new Set(['completed', 'failed', 'cancelled', 'dead']);\n const isSettled = (run: WorkflowRun): boolean =>\n opts?.until === 'terminal'\n ? TERMINAL.has(run.status)\n : run.status !== 'pending' &&\n run.status !== 'running' &&\n run.status !== 'cancelling' &&\n !(run.status === 'suspended' && run.awaitingDecisionTaskId !== undefined);\n const toResult = (run: WorkflowRun): RunResult => ({\n runId,\n status: run.status,\n output: run.output,\n error: run.error,\n });\n return new Promise<RunResult>((resolve, reject) => {\n let done = false;\n let off: () => void = () => {};\n const timer =\n opts?.timeoutMs != null\n ? setTimeout(() => {\n if (done) return;\n done = true;\n if (poller) clearInterval(poller);\n off();\n reject(new Error(`waitForRun(${runId}) timed out after ${opts.timeoutMs}ms`));\n }, opts.timeoutMs)\n : undefined;\n const finish = (run: WorkflowRun): void => {\n if (done) return;\n done = true;\n if (timer) clearTimeout(timer);\n if (poller) clearInterval(poller);\n off();\n resolve(toResult(run));\n };\n const check = (): void => {\n void this.store.getRun(runId).then((run) => {\n if (run && isSettled(run)) finish(run);\n });\n };\n // Terminal mode also polls: cancelled/dead transitions have no `run.*` lifecycle event to\n // react to (and a resume may happen on ANOTHER instance), so events alone can miss them.\n const poller =\n opts?.until === 'terminal'\n ? (() => {\n const interval = setInterval(check, 250);\n interval.unref?.();\n return interval;\n })()\n : undefined;\n // React only to this run's settling events (not its every step event), and subscribe BEFORE the\n // initial read so a run that settles in between isn't missed.\n off = this.subscribe((ev) => {\n if (\n ev.runId === runId &&\n (ev.type === 'run.completed' || ev.type === 'run.failed' || ev.type === 'run.suspended')\n ) {\n check();\n }\n });\n check();\n });\n }\n\n /**\n * Resume each run only if this instance can acquire its recovery lease — so when several\n * replicas recover or poll at once, each run is picked up by exactly one of them.\n */\n private async resumeLeased(\n runs: WorkflowRun[],\n nowMs: number = this.clock(),\n onLocked?: (run: WorkflowRun) => Promise<RunResult | undefined>,\n ): Promise<RunResult[]> {\n if (this.draining) return []; // shutting down — don't pick up new runs\n const results: RunResult[] = [];\n for (const run of runs) {\n const acquired = await this.store.tryLockRun(\n run.id,\n this.instanceId,\n nowMs + this.leaseMs,\n nowMs,\n );\n if (!acquired) continue;\n // A per-run hook (recovery counting / dead-lettering) may settle the run terminally instead.\n const settled = onLocked ? await onLocked(run) : undefined;\n results.push(settled ?? (await this.resume(run.id)));\n }\n return results;\n }\n\n /**\n * Deliver an external signal to the run waiting on `token` and resume it with `payload`.\n * Returns the run result, or null if no run is waiting for that token.\n */\n /**\n * Publish a named event. It does two things, and returns how many runs it touched (the sum):\n * 1. **Resumes** every in-flight run waiting on it via `ctx.waitForEvent(name, { match })` whose\n * match the payload satisfies (fan-out, vs `signal`'s point-to-point token).\n * 2. **Starts** a fresh run of every workflow registered with `onEvent: [name]`, passing the\n * payload as input. Idempotent by `evt:<id>:<workflow>` — pass `opts.id` to dedupe redeliveries\n * of the same logical event (default: a fresh uuid, so each publish triggers once).\n *\n * Semantics (deliberate — mirrors `signalWithStart`'s reliability contract, so document it exactly):\n * a publish that resumes ≥1 live waiter, OR routes into an `eventBatch` accumulator / starts ≥1\n * subscriber, behaves exactly as above and is NOT buffered — fan-out stays live-only, same as\n * today. A publish that touches NEITHER — no live waiter matched, no subscriber exists/started —\n * buffers ONE copy (via {@link StateStore.bufferEvent}) unless `opts.buffer === false`, so it isn't\n * silently dropped just because nobody happened to be listening yet. That buffered copy is consumed\n * by the FIRST future `ctx.waitForEvent(name, { match })` whose match accepts its payload —\n * point-to-point on redelivery, by design (only one waiter ever gets it, even though the LIVE path\n * above is fan-out) — never by a second, later-registered onEvent subscriber (subscriber starts stay\n * live-only; `opts.id` dedupe applies to those only, unchanged). Right after buffering, this re-checks\n * `listSignalWaiters` ONCE — sandwich parity with `signal`'s own take → buffer → re-check — so a\n * waiter that registers in the sliver between the initial miss and the buffer write is still paired\n * instead of leaving both rows stranded (see `signal`'s interleaving proof; `waitForEvent`'s own\n * post-registration buffer scan is the mirror-image half of this same race).\n */\n async publishEvent(\n name: string,\n payload: unknown,\n opts?: { id?: string; buffer?: boolean },\n ): Promise<number> {\n let touched = 0;\n const waiters = await this.store.listSignalWaiters(eventPrefix(name));\n for (const w of waiters) {\n if (eventMatches(payload, eventMatchOf(w.token))) {\n await this.signal(w.token, payload);\n touched += 1;\n }\n }\n const subscribers = this.eventTriggers.get(name);\n if (subscribers?.size) {\n const eventId = opts?.id ?? globalThis.crypto.randomUUID();\n for (const workflow of subscribers) {\n // A subscriber that rejects the payload (validateInput) must not block the others or the\n // waiters — its run simply never starts, mirroring fire-and-forget dead-letter routing.\n try {\n const batch = this.latest.get(workflow)?.eventBatch;\n if (batch) {\n // Coalesce: route the event into a per-workflow accumulator (one long-lived run that\n // debounces/batches and then starts the target with the collected payload(s)).\n await this.accumulators.route(workflow, batch, payload);\n } else {\n await this.start(workflow, payload, `evt:${eventId}:${workflow}`);\n }\n touched += 1;\n } catch {\n // skip this subscriber\n }\n }\n }\n // Nobody received it live (no waiter matched, no subscriber exists/started) — buffer ONE copy\n // unless the caller opted out. `touched > 0` covers BOTH the waiter fan-out and the subscriber\n // loop above, matching the \"no one received it\" condition the semantics doc promises.\n if (touched > 0 || opts?.buffer === false) return touched;\n const bufferedId = globalThis.crypto.randomUUID();\n await this.store.bufferEvent({ name, payload, id: bufferedId, publishedAt: this.clock() });\n // Re-check: a waiter may have registered in the window between the miss above and this buffer\n // write (see the interleaving proof at `signal` — this is the events-side mirror of it). Only the\n // FIRST late-registered matching waiter is considered: only one buffered copy exists, so once a\n // claim attempt below either succeeds or finds the buffer already gone, there is nothing left for\n // any other candidate regardless.\n const lateWaiters = await this.store.listSignalWaiters(eventPrefix(name));\n const lateWaiter = lateWaiters.find((w) => eventMatches(payload, eventMatchOf(w.token)));\n if (!lateWaiter) return touched;\n if (!(await this.store.removeBufferedEvent(bufferedId))) return touched; // claimed elsewhere already\n // `takeSignalWaiter` is safe here even though it deletes ANY row for the token: an event token\n // embeds this ONE `waitForEvent` call's own `runId#seq` (see eventToken in events.ts), so no other\n // registration could ever share it.\n const waiter = await this.store.takeSignalWaiter(lateWaiter.token);\n if (waiter) {\n const settled = await this.deliverSignal(waiter, payload);\n if (settled) touched += 1;\n }\n // If `waiter` is null, that exact registration resolved itself some other way in the interim (most\n // likely its own timeout deadline landing in this same sliver) — the buffered copy is already\n // spent (claimed above), so — mirroring `signal`'s own reclaim precedent — drop it rather than\n // resuming a run a second time or re-buffering for a THIRD, unrelated waiter to pick up later.\n return touched;\n }\n\n /**\n * Deliver a signal to an already-known waiter: write its resolving `signal:<token>` checkpoint and\n * resume the run. Shared by {@link signal}'s direct hit, its post-buffer re-check reclaim, and the\n * due-timer reconcile sweep ({@link reconcileSignalWaiter}) — all three resolve a waiter the exact\n * same way.\n */\n private async deliverSignal(waiter: SignalWaiter, payload: unknown): Promise<RunResult | null> {\n await this.store.saveCheckpoint(\n instantCheckpoint({\n runId: waiter.runId,\n seq: waiter.seq,\n name: `signal:${waiter.token}`,\n kind: 'signal',\n output: payload,\n // Carry the awaiting command's fan group (set when a `ctx.gather_children`/`ctx.all` fan-out\n // registered this waiter) onto the resolving `signal:child:<id>` checkpoint, so the dashboard\n // groups the child fan-out vertically instead of rendering it as a sequential chain. Undefined\n // for an ordinary (non-fan) signal/child await.\n parallelGroup: waiter.parallelGroup,\n }),\n );\n return this.resume(waiter.runId).catch((err) => {\n if (err instanceof NamespaceMismatch) return null;\n throw err;\n });\n }\n\n /**\n * Deliver an external signal to the run waiting on `token`, resume it with `payload`, and return\n * the run result — or null if no run is (or ends up) waiting for it.\n *\n * Race with the waiter side (`waitForSignal`'s check → `putSignalWaiter` → re-check, same shape in\n * the remote `waitSignal` command): a waiter can register in the sliver between this method's\n * initial `takeSignalWaiter` miss and its `bufferSignal` write, and the naive old flow (buffer and\n * return) would then leave BOTH a buffered payload and a registered waiter sitting in the store with\n * nothing left to pair them — a lost wake, forever suspended.\n *\n * The interleaving proof: the waiter side does check → put → re-check, this side does take → buffer\n * → re-check. Whichever side's SECOND look runs last is guaranteed to observe the other side's\n * write, because it always follows that write in real time:\n * - If the waiter's `put` lands before this method's first `take`, the take just finds it directly\n * (the pre-existing, non-racy path).\n * - If the waiter's `put` lands after this method's `bufferSignal`, our re-check below either sees\n * it (if `put` also lands before the re-check) or the waiter's OWN post-put re-check sees our\n * buffer (if `put` lands after our re-check but the waiter hasn't re-checked yet either — its\n * re-check strictly follows its own put).\n * - If the waiter's `put` lands between this method's `take` and its re-`take`, the re-check below\n * catches it.\n * Either way, the destructive `take*` ops (on the waiter row, on the buffer) arbitrate: whichever\n * side actually removes the row is the one that delivers, so a signal is never delivered twice.\n */\n async signal(token: string, payload: unknown): Promise<RunResult | null> {\n const waiter = await this.store.takeSignalWaiter(token);\n if (waiter) return this.deliverSignal(waiter, payload);\n // No one was waiting yet — buffer it so the next `waitForSignal(token)` consumes it instead of\n // dropping it (reliable signals; the basis of `signalWithStart`).\n await this.store.bufferSignal(token, payload);\n // Re-check: a waiter may have registered in the window between the miss above and this buffer\n // write (see the interleaving proof above).\n const lateWaiter = await this.store.takeSignalWaiter(token);\n if (!lateWaiter) return null;\n const reclaimed = await this.store.takeBufferedSignal(token);\n if (!reclaimed) {\n // The waiter side won the race to consume the buffer itself (its own checkpoint+resume already\n // delivered the payload) in the sliver between our takeSignalWaiter and takeBufferedSignal just\n // above. We've already (destructively) taken `lateWaiter` off the store, but there is nothing\n // left to deliver — drop it deliberately rather than resuming the run a second time.\n return null;\n }\n return this.deliverSignal(lateWaiter, reclaimed.payload);\n }\n\n /**\n * Ensure a run exists for `runId`, then deliver a signal to it — atomically race-free thanks to\n * signal buffering: if the run is new (or busy / not yet waiting), the signal is buffered and\n * consumed when it reaches `waitForSignal(token)`. The canonical **durable-entity / accumulator**\n * pattern: one long-lived run per key (the `runId`) that loops on `waitForSignal`, fed events by\n * many `signalWithStart` calls. `start` is idempotent by `runId`, so concurrent callers converge on\n * one run. (Use a per-run `token`, e.g. derived from `runId`, so the signal targets this entity.)\n */\n async signalWithStart(\n workflow: WorkflowRef,\n input: unknown,\n runId: string,\n signal: { token: string; payload?: unknown },\n opts?: StartOptions,\n ): Promise<{ runId: string }> {\n // `start` is overloaded per ref kind (class | string); a `WorkflowRef` union fits neither\n // overload, so resolve to the string overload (the engine handles both at runtime).\n await this.start(workflow as string, input, runId, opts); // idempotent: no-op if run exists\n await this.signal(signal.token, signal.payload);\n return { runId };\n }\n\n /**\n * Report the result of a `ctx.task(name, …)` back to its run (async completion). The external\n * worker that the task dispatched to calls this when done; the run resumes with `result`. Returns\n * null if no run is waiting on the task (e.g. a duplicate/late delivery) — a safe no-op.\n */\n async completeTask(runId: string, name: string, result: unknown): Promise<RunResult | null> {\n return this.signal(`task:${runId}:${name}`, {\n ok: true,\n value: result,\n } satisfies Completion<unknown>);\n }\n\n /** Report that a `ctx.task` failed — the run resumes and throws a FatalError at the task. */\n async failTask(runId: string, name: string, error: string): Promise<RunResult | null> {\n return this.signal(`task:${runId}:${name}`, { ok: false, error } satisfies Completion<never>);\n }\n\n /**\n * Notify a parent that's waiting on `runId` as a child of its terminal outcome (the `ctx.child`\n * rendezvous). A no-op when no parent is waiting, so `execute()` can call it on every run without\n * knowing about the child feature.\n */\n private notifyParent(runId: string, completion: Completion<unknown>): void {\n void this.signal(`child:${runId}`, completion).catch(() => undefined);\n }\n\n /**\n * Deferred child start shared by the in-process ctx host and the remote `startChild` command.\n * Deferred (microtask) so a fast child can't reentrantly resume a still-suspending parent. A start\n * that THROWS (unregistered/unroutable workflow, input validation, singleton back-pressure, store\n * failure) must NOT be swallowed: the parent is already suspended on `child:<childId>` (the waiter\n * is put BEFORE start on every path), so a silent drop parks it in suspended-forever, invisibly\n * re-attempting on every recovery wake — a misconfigured remote child looks exactly like a healthy\n * long wait. Instead the failure is delivered to that waiter like a failed child (notifyParent):\n * the parent resumes and fails loudly with the cause. For a fire-and-forget `ctx.startChild`\n * (spawn — no waiter) the completion is buffered; a later join by the same id consumes it and\n * correctly observes the failed start.\n */\n private startChildDeferred(\n workflow: string,\n input: unknown,\n childId: string,\n opts?: StartOptions,\n ): void {\n queueMicrotask(\n () =>\n void this.start(workflow, input, childId, opts).catch((err) => {\n const message = err instanceof Error ? err.message : String(err);\n this.notifyParent(childId, {\n ok: false,\n error: `child workflow \"${workflow}\" failed to start: ${message}`,\n });\n }),\n );\n }\n\n /**\n * Cancel a run (e.g. from the dashboard). Returns null if the run does not exist. Pass\n * `{ compensate: true }` to undo the saga first: the suspended run is resumed so its completed\n * steps' compensations run in reverse (visible as `compensate:<step>` events), then it's marked\n * cancelled. Without it, cancellation is immediate (no undo).\n */\n async cancel(runId: string, opts?: { compensate?: boolean }): Promise<RunResult | null> {\n const run = await this.store.getRun(runId);\n if (!run) return null;\n // Already finished — nothing to cancel (and don't clobber a completed/dead run). This also stops\n // the child cascade below from looping on already-cancelled runs.\n if (run.status === 'completed' || run.status === 'cancelled' || run.status === 'dead') {\n return { runId, status: run.status, output: run.output, error: run.error };\n }\n // Already compensating (status persisted as `cancelling`): idempotent — don't re-queue the resume,\n // and crucially don't fall through to the instant-cancel path below (which would mark `cancelled`\n // and SKIP the in-flight saga undo). A repeat cancel just echoes the in-progress status.\n if (run.status === 'cancelling') {\n return { runId, status: 'cancelling' };\n }\n // Compensating cancel: resume the run with a cancellation pending — replay re-registers the saga,\n // and at the suspension point execute() runs the undo and marks it cancelled. Run that resume in\n // the BACKGROUND so the caller (e.g. an HTTP request) never blocks on replaying the workflow +\n // compensations. `execute` holds the run's lease, so this can't double-run one a live worker owns\n // (its lease acquire fails and it no-ops); the broadcast tells that worker to abort cooperatively.\n if (opts?.compensate && (run.status === 'suspended' || run.status === 'running')) {\n this.cancelRequested.add(runId);\n // Persist `cancelling` so the dashboard/API show \"compensation in progress\" instead of a\n // misleading `running`/`suspended` while the background undo runs. NON-TERMINAL: the admission\n // gate still counts it and recovery re-drives it on crash (runExecution re-derives the cancel\n // intent from this status), so the cancel is durable; it flips to `cancelled` when the resumed\n // replay finishes compensating.\n await this.store.updateRun(runId, { status: 'cancelling', updatedAt: new Date() });\n run.status = 'cancelling';\n if (this.controlPlane) {\n void this.controlPlane\n .publishControl({ kind: 'cancel', runId, from: this.instanceId })\n .catch(() => undefined);\n }\n queueMicrotask(() => {\n void this.resume(runId)\n .then(() => this.notifyCancelled(runId))\n .catch(() => undefined);\n });\n await this.cancelChildren(runId, opts);\n return { runId, status: 'cancelling' };\n }\n const error = { message: 'cancelled' };\n await this.store.updateRun(runId, { status: 'cancelled', error, updatedAt: new Date() });\n this.emit({\n type: 'run.failed',\n runId,\n workflow: run.workflow,\n namespace: run.namespace,\n error,\n });\n await this.cancelChildren(runId, opts);\n // Notify local cancel listeners now (a worker on this pod), and broadcast so the instance/worker\n // actually running this run learns of it and can abort cooperatively (the store already records\n // `cancelled`, but a busy worker won't re-read it).\n this.notifyCancelled(runId);\n if (this.controlPlane) {\n void this.controlPlane\n .publishControl({ kind: 'cancel', runId, from: this.instanceId })\n .catch(() => undefined);\n }\n // A cancelled singleton run frees its slot — wake the next gated waiter now (notify-on-release).\n void this.singletons.wakeNext(run).catch(() => undefined);\n return { runId, status: 'cancelled', error };\n }\n\n /**\n * Bulk-cancel every run matching a filter — e.g. cancel all `order` runs tagged `vip`, or every run\n * whose `tier` search attribute is `free`. The filter is a {@link RunQuery} (workflow / status / tag\n * / search-attribute predicates), so it reuses the same matching the dashboard list uses. Each match\n * is run through {@link cancel}, so the same plumbing applies per run: child cascade, the optional\n * saga `compensate`, local cancel listeners, and the control-plane broadcast that tells the owning\n * worker to abort. Returns one {@link RunResult} per matched run (already-finished matches report\n * their terminal status — `cancel` is a no-op on them, never clobbering a completed/dead run).\n */\n async cancelWhere(\n filter: Omit<RunQuery, 'limit' | 'offset'>,\n opts?: { compensate?: boolean },\n ): Promise<RunResult[]> {\n const runs = await this.store.listRuns(filter);\n const results: RunResult[] = [];\n for (const run of runs) {\n const r = await this.cancel(run.id, opts);\n if (r) results.push(r);\n }\n return results;\n }\n\n /**\n * Hard-delete a run and its entire subtree. Unlike {@link cancel} (which marks a run `cancelled`\n * but keeps it as history), delete REMOVES the run and all its rows (checkpoints, signal waiters,\n * search-attribute rows) — it vanishes from {@link getRun} and {@link listRuns}. Use it to purge a\n * finished run whose data is being deleted (e.g. a pipeline run whose result rows are cleared).\n *\n * Cascades depth-first via {@link getRunChildren} so children are gone before the parent (no\n * orphaned child runs). Prefer {@link cancel} first for a live run — deleting one mid-flight orphans\n * its worker (its next checkpoint write fails). Returns the number of runs deleted (0 if absent).\n */\n async deleteRun(runId: string): Promise<number> {\n const run = await this.store.getRun(runId);\n if (!run) return 0;\n // Collect children BEFORE deleting this run's checkpoints (getRunChildren reads them).\n let deleted = 0;\n for (const childId of await this.getRunChildren(runId)) {\n deleted += await this.deleteRun(childId);\n }\n await this.store.deleteRun(runId);\n return deleted + 1;\n }\n\n /**\n * Cascade cancellation to a run's children — both awaited (`ctx.child`, found via its live\n * `child:<id>` waiter) and fire-and-forget (`ctx.startChild`, found via its `spawn:<id>`\n * checkpoint). Recursive, so a whole subtree is cancelled; the terminal guard in `cancel` stops it\n * at finished / already-cancelled runs (no loops, no re-cancel).\n */\n private async cancelChildren(\n parentRunId: string,\n opts?: { compensate?: boolean },\n ): Promise<void> {\n for (const id of await this.getRunChildren(parentRunId)) {\n await this.cancel(id, opts).catch(() => undefined);\n }\n }\n\n /**\n * The ids of the runs a run spawned — both awaited (`ctx.child`) and fire-and-forget\n * (`ctx.startChild`, found via its `spawn:<id>` checkpoint). The canonical parent→children edge,\n * used for both cancellation cascades and the dashboard run-tree.\n *\n * An awaited child is discovered two ways, because the live `child:<id>` waiter only exists WHILE\n * the parent is suspended on it: the waiter resolves and is consumed the moment the child settles,\n * so a completed parent (or a completed awaited child) would otherwise drop out of the tree. The\n * `signal:child:<id>` checkpoint (the placeholder written when the parent first awaits the child,\n * overwritten as completed/failed when it settles) persists across completion, so we read both and\n * dedupe — the edge stays stable for a finished run, not just a live one.\n */\n async getRunChildren(parentRunId: string): Promise<string[]> {\n const childIds = new Set<string>();\n for (const w of await this.store.listSignalWaiters('child:')) {\n if (w.runId === parentRunId) childIds.add(w.token.slice('child:'.length));\n }\n // Targeted read: only the `signal:child:` / `spawn:` checkpoints, not the whole history. Falls\n // back to a full listCheckpoints + in-JS prefix scan for a custom store that omits the method.\n const prefixes = ['signal:child:', 'spawn:'];\n const childCheckpoints = this.store.listCheckpointsByNamePrefix\n ? await this.store.listCheckpointsByNamePrefix(parentRunId, prefixes)\n : (await this.store.listCheckpoints(parentRunId)).filter((cp) =>\n prefixes.some((p) => cp.name.startsWith(p)),\n );\n for (const cp of childCheckpoints) {\n if (cp.name.startsWith('signal:child:')) childIds.add(cp.name.slice('signal:child:'.length));\n if (cp.name.startsWith('spawn:') && typeof cp.output === 'string') childIds.add(cp.output);\n }\n return [...childIds];\n }\n\n /** The worker groups this engine dispatches to: every registered remote workflow's group, plus any\n * `extra` the caller declares. Local-step groups (a group consumed by in-process `@DurableStep`\n * workers, e.g. `pipeline`) aren't derivable from registrations — pass them via `extra` so a group\n * with backlog and ZERO workers is still reported (the alert case has no heartbeat to discover). */\n knownGroups(extra: string[] = []): string[] {\n const groups = new Set<string>(extra);\n for (const def of this.workflows.values()) {\n if (def.remote?.group) groups.add(def.remote.group);\n }\n return [...groups];\n }\n\n /** Per-group worker health (queue backlog + live worker heartbeats). Covers {@link knownGroups}\n * (so a registered group with backlog and ZERO workers still reports — the alert case) UNION the\n * groups discovered from live heartbeats (so a local-step group like `pipeline`, not derivable\n * from registrations, shows once its workers beat). Empty when no transport can introspect health\n * (only the BullMQ transport implements `groupHealth`). */\n async workerHealth(extra: string[] = []): Promise<GroupHealth[]> {\n const groups = new Set([...this.knownGroups(extra), ...(await this.pool.listWorkerGroups())]);\n // Classify each group workflow-vs-step from the registry (authoritative — no name heuristic): a\n // group whose base token is a registered workflow serves a `@Workflow` body; anything else (an\n // in-process `@Step`, a remote `handle_*` step) is a step. A LOCAL workflow's queue token is\n // `sanitizeQueueToken(name)`; a REMOTE one (e.g. Python) routes to its `remote.group`, which can\n // differ from the name — so seed the workflow-token set with BOTH.\n const workflowTokens = new Set<string>();\n for (const def of this.workflows.values()) {\n workflowTokens.add(sanitizeQueueToken(def.name));\n if (def.remote?.group) workflowTokens.add(def.remote.group);\n }\n const out: GroupHealth[] = [];\n for (const group of groups) {\n const health = await this.pool.groupHealth(group);\n if (!health) continue;\n const at = group.lastIndexOf('@');\n const baseToken = at === -1 ? group : group.slice(0, at);\n out.push({ ...health, kind: workflowTokens.has(baseToken) ? 'workflow' : 'step' });\n }\n return out;\n }\n\n /**\n * Persist a streamed local-step lifecycle event from a remote workflow worker (see\n * {@link WorkflowStepEvent}). A Python `@workflow` runs its `ctx.step`s inline over one turn that\n * can last minutes; the worker streams each step's start/finish so the engine checkpoints it LIVE —\n * a step shows `running` the moment its body begins, then resolves to `completed`/`failed` with its\n * real wall-clock window and sub-process events — instead of every step appearing at once when the\n * turn ends. The turn's final `recordStep` command re-persists the same (runId, seq) checkpoint\n * idempotently, so this is purely additive observability and never changes the run's outcome.\n */\n private async persistStepEvent(event: WorkflowStepEvent): Promise<void> {\n const startedAt = new Date(event.startedAt);\n if (event.phase === 'running') {\n await this.store.saveCheckpoint(\n stepCheckpoint({\n runId: event.runId,\n seq: event.seq,\n name: event.name,\n kind: 'local',\n status: 'running',\n events: event.events,\n attempts: 1,\n enqueuedAt: startedAt,\n startedAt,\n finishedAt: startedAt, // placeholder until the step settles\n parallelGroup: event.parallelGroup,\n }),\n );\n this.emit({\n type: 'step.started',\n runId: event.runId,\n seq: event.seq,\n name: event.name,\n kind: 'local',\n });\n return;\n }\n const failed = event.phase === 'failed';\n await this.store.saveCheckpoint(\n stepCheckpoint({\n runId: event.runId,\n seq: event.seq,\n name: event.name,\n kind: 'local',\n status: failed ? 'failed' : 'completed',\n output: failed ? undefined : event.output,\n error: failed ? event.error : undefined,\n events: event.events,\n attempts: 1,\n enqueuedAt: startedAt,\n startedAt,\n finishedAt: event.finishedAt != null ? new Date(event.finishedAt) : new Date(),\n parallelGroup: event.parallelGroup,\n }),\n );\n this.emit({\n type: failed ? 'step.failed' : 'step.completed',\n runId: event.runId,\n seq: event.seq,\n name: event.name,\n kind: 'local',\n output: failed ? undefined : event.output,\n error: failed ? event.error : undefined,\n });\n }\n\n /**\n * Announce a local step's body has begun and (when `trackStepStart`) checkpoint it as `running`,\n * so it's visible in flight rather than appearing only on completion. The checkpoint is a\n * placeholder overwritten by {@link completeStep}/{@link failStep}; it never short-circuits replay\n * (only `completed` does), so a crash mid-body just re-runs the step. The `step.started` event\n * fires regardless — the live SSE view sees the start even with persistence off.\n */\n private async startStep(step: StepRecord): Promise<void> {\n if (this.trackStepStart) {\n await this.store.saveCheckpoint(\n stepCheckpoint({\n runId: step.runId,\n seq: step.seq,\n name: step.name,\n kind: step.kind,\n status: 'running',\n input: step.input,\n events: step.events,\n attempts: step.attempts,\n workerGroup: step.workerGroup,\n enqueuedAt: step.enqueuedAt,\n startedAt: step.startedAt,\n finishedAt: step.startedAt, // placeholder until the body settles\n }),\n );\n }\n this.emit({\n type: 'step.started',\n runId: step.runId,\n seq: step.seq,\n name: step.name,\n kind: step.kind,\n });\n }\n\n /** Checkpoint a finished step and announce it — the two things that must always happen together. */\n private async completeStep(step: StepRecord & { output: unknown }): Promise<void> {\n await this.store.saveCheckpoint(\n stepCheckpoint({\n runId: step.runId,\n seq: step.seq,\n name: step.name,\n kind: step.kind,\n status: 'completed',\n input: step.input,\n output: step.output,\n events: step.events,\n attempts: step.attempts,\n workerGroup: step.workerGroup,\n enqueuedAt: step.enqueuedAt,\n startedAt: step.startedAt,\n finishedAt: new Date(),\n }),\n );\n this.emit({\n type: 'step.completed',\n runId: step.runId,\n seq: step.seq,\n name: step.name,\n kind: step.kind,\n output: step.output,\n queueMs: step.startedAt.getTime() - step.enqueuedAt.getTime(),\n durationMs: Date.now() - step.startedAt.getTime(),\n });\n }\n\n /** Checkpoint a step that failed terminally, so the failure point is visible (not just the run). */\n private async failStep(step: StepRecord & { error: StepError }): Promise<void> {\n await this.store.saveCheckpoint(\n stepCheckpoint({\n runId: step.runId,\n seq: step.seq,\n name: step.name,\n kind: step.kind,\n status: 'failed',\n input: step.input,\n error: step.error,\n events: step.events,\n attempts: step.attempts,\n workerGroup: step.workerGroup,\n enqueuedAt: step.enqueuedAt,\n startedAt: step.startedAt,\n finishedAt: new Date(),\n }),\n );\n this.emit({\n type: 'step.failed',\n runId: step.runId,\n seq: step.seq,\n name: step.name,\n kind: step.kind,\n error: step.error,\n queueMs: step.startedAt.getTime() - step.enqueuedAt.getTime(),\n durationMs: Date.now() - step.startedAt.getTime(),\n });\n }\n\n private async execute(run: WorkflowRun, fn: WorkflowFn): Promise<RunResult> {\n // Synchronous fast path (`??` short-circuits) for registered runs — no extra await, so execution\n // timing for the common case is unchanged; only an unregistered (inherited-remote) run awaits.\n const registered =\n this.workflows.get(versionKey(run.workflow, run.workflowVersion)) ??\n (await this.findInheritedRegistration(run)) ??\n (await this.resolveRemoteByConvention(run));\n // Hold the lease for the WHOLE execution — whatever path got us here (leased sweep, a signal, a\n // remote result, a dashboard action). The leased sweeps already own it; the event-driven paths\n // don't, so acquire it here. If another instance owns it, don't double-run. While we run, renew\n // the lease periodically so a long run keeps it (a crashed worker's lease still expires and is\n // reclaimed by periodic recovery).\n const lockNow = this.clock();\n if (run.lockedBy !== this.instanceId || (run.lockedUntil ?? 0) <= lockNow) {\n if (\n !(await this.store.tryLockRun(run.id, this.instanceId, lockNow + this.leaseMs, lockNow))\n ) {\n return { runId: run.id, status: run.status };\n }\n }\n const renew = setInterval(\n () => {\n void this.store\n .renewRunLock(run.id, this.instanceId, this.clock() + this.leaseMs)\n .catch(() => undefined);\n },\n Math.max(50, Math.floor(this.leaseMs / 2)),\n );\n renew.unref?.();\n try {\n // A remote (e.g. Python) workflow is advanced by dispatching workflow tasks, not by running an\n // in-process body — but everything around it (lease, recovery, timers, the resume that lands us\n // here on a step result) is identical, so it branches here under the same lease.\n const result = registered?.remote\n ? await this.runRemoteExecution(run, registered)\n : await this.runExecution(run, fn, registered);\n // Notify-on-release: a singleton run that just reached a terminal state freed a slot — wake the\n // next gated waiter(s) now instead of waiting for the ~1s retry timer. Fire-and-forget so it\n // never blocks the settling run; the durable timer is still the cross-instance/crash fallback.\n if (\n registered?.singleton &&\n (result.status === 'completed' ||\n result.status === 'failed' ||\n result.status === 'cancelled' ||\n result.status === 'dead')\n ) {\n void this.singletons.wakeNext(run).catch(() => undefined);\n }\n return result;\n } finally {\n clearInterval(renew);\n }\n }\n\n /**\n * Advance a remote (cross-SDK) workflow one turn: hand its history to the executor (which dispatches\n * a workflow task to the worker and awaits its replay) and apply the decision. Mirrors\n * {@link runExecution}'s settle/suspend; the lease is held by {@link execute}. The result that lands\n * us back here (a remote step finished, a timer fired) goes through `resume` like any TS workflow.\n */\n /**\n * Apply a terminal/suspended transition once: persist the new run status, emit the matching\n * lifecycle event, and (on completion/failure) wake a waiting parent. Both the TS and remote\n * executors funnel their completed/failed/suspended outcomes through here so a status update can\n * never drift from its event or `notifyParent` call. Does NOT touch the run lock — each executor\n * keeps its own lease handling (the TS executor's `finally`, the remote path's caller).\n */\n private async settleRun(run: WorkflowRun, outcome: RunOutcome): Promise<RunResult> {\n const updatedAt = new Date();\n if (outcome.kind === 'completed') {\n // Clear any error from an earlier failed-then-retried attempt — a completed run is a success.\n await this.store.updateRun(run.id, {\n status: 'completed',\n output: outcome.output,\n error: undefined,\n updatedAt,\n });\n this.emit({\n type: 'run.completed',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n output: outcome.output,\n });\n void this.notifyParent(run.id, { ok: true, value: outcome.output });\n return { runId: run.id, status: 'completed', output: outcome.output };\n }\n if (outcome.kind === 'failed') {\n await this.store.updateRun(run.id, { status: 'failed', error: outcome.error, updatedAt });\n this.emit({\n type: 'run.failed',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n error: outcome.error,\n });\n void this.notifyParent(run.id, { ok: false, error: outcome.error.message });\n return { runId: run.id, status: 'failed', error: outcome.error };\n }\n // This outcome was computed by a turn that started from a possibly-stale run snapshot. If the run\n // was cancelled WHILE that turn was still executing (e.g. `ctx.all`'s failFast cancelling a\n // sibling mid-turn — plain `cancel()` writes `cancelled` directly, without waiting for the target's\n // in-flight turn to notice), this now-stale \"suspended\" outcome must not resurrect it: re-check the\n // CURRENT persisted status right before writing and echo it instead of clobbering a real cancel.\n const latest = await this.store.getRun(run.id);\n if (latest?.status === 'cancelled') {\n return { runId: run.id, status: 'cancelled', error: latest.error };\n }\n await this.store.updateRun(run.id, {\n status: 'suspended',\n wakeAt: this.reconcileWakeAt(outcome.wakeAt),\n updatedAt,\n });\n this.emit({\n type: 'run.suspended',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n });\n return { runId: run.id, status: 'suspended' };\n }\n\n /**\n * A wakeAt to persist on a suspend: the natural timer if the turn produced one (a `ctx.sleep`, a\n * remote-step deadline), else the {@link reconcileMs} fallback so an event-waiting run (child/signal/\n * timeout-less remote step) can't be orphaned forever if its wake is lost. `undefined` only when the\n * fallback is disabled (`reconcileMs: 0`). See {@link WorkflowEngineDeps.reconcileMs}.\n */\n private reconcileWakeAt(wakeAt: number | undefined): number | undefined {\n if (wakeAt != null) return wakeAt;\n return this.reconcileMs != null ? this.clock() + this.reconcileMs : undefined;\n }\n\n private async runRemoteExecution(\n run: WorkflowRun,\n registered: RegisteredWorkflow,\n ): Promise<RunResult> {\n // Compensating cancel in flight for a remote workflow: its steps execute in the worker, so there\n // are no TS-side compensations to replay here — finalize to cancelled. Re-broadcast so a live worker\n // mid-turn aborts cooperatively; on recovery (the broadcast was lost to a crash) this still settles\n // the run deterministically instead of resurrecting it by re-advancing.\n if (run.status === 'cancelling') {\n const error = { message: 'cancelled' };\n await this.store.updateRun(run.id, { status: 'cancelled', error, updatedAt: new Date() });\n this.emit({\n type: 'run.failed',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n error,\n });\n this.notifyCancelled(run.id);\n if (this.controlPlane) {\n void this.controlPlane\n .publishControl({ kind: 'cancel', runId: run.id, from: this.instanceId })\n .catch(() => undefined);\n }\n await this.store.releaseRunLock(run.id);\n return { runId: run.id, status: 'cancelled', error };\n }\n const remote = registered.remote as NonNullable<RegisteredWorkflow['remote']>;\n if (run.status === 'pending') {\n await this.store.updateRun(run.id, { status: 'running', updatedAt: new Date() });\n run.status = 'running';\n this.emit({\n type: 'run.started',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n });\n }\n if (registered.singleton && !(await this.singletons.admit(run, registered.singleton))) {\n const wakeAt = this.singletons.retryWakeAt();\n await this.store.updateRun(run.id, { status: 'suspended', wakeAt, updatedAt: new Date() });\n this.emit({\n type: 'run.suspended',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n });\n await this.store.releaseRunLock(run.id);\n return { runId: run.id, status: 'suspended' };\n }\n\n const history = await this.remoteHistory(run.id);\n\n // DISPATCH-AND-SUSPEND (broker-backed executors): SUSPEND-then-ENQUEUE. The engine generates the\n // turn's `taskId`, records it on the run as the awaited marker, and RELEASES the lease — all BEFORE\n // enqueuing the turn — so a fast worker's decision (delivered over `onDecision`, applied durably by\n // `completeRemoteDecision` on WHATEVER instance consumes it) can NEVER arrive ahead of its marker,\n // nor contend with a still-held lease, and be dropped. (The original dispatch-then-mark order lost a\n // sub-millisecond cached-replay decision that round-tripped the in-cluster broker before the marker\n // write to the remote store committed — the multi-instance decision-drop's deeper race.) Liveness is\n // the suspended turn's heartbeat-rearmed window (`remoteAdvanceSilenceMs` → `wakeAt`): if no\n // decision/heartbeat lands before it lapses (including a dispatch that throws below), the timer\n // poller re-drives by re-marking + re-enqueuing a fresh turn.\n if (remote.executor.dispatch) {\n const taskId = `${run.id}:wf:${globalThis.crypto.randomUUID().slice(0, 8)}`;\n const silenceMs = this.remoteAdvanceSilenceMs;\n const wakeAt = silenceMs != null ? this.clock() + silenceMs : undefined;\n // MARK FIRST: record the awaited turn before it is enqueued. No resurrection risk — unlike the old\n // mark-AFTER-dispatch order, nothing rewrites `status` past this point, so a parent-cancel that\n // writes a terminal status during the enqueue below simply wins (its decision is later dropped by\n // `completeRemoteDecision`'s terminal-status check).\n await this.store.updateRun(run.id, {\n status: 'suspended',\n awaitingDecisionTaskId: taskId,\n wakeAt,\n updatedAt: new Date(),\n });\n this.emit({\n type: 'run.suspended',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n });\n // RELEASE BEFORE ENQUEUE: the decision must be able to BOTH match the marker AND acquire the lease\n // the instant it arrives — even a few ms after the enqueue. Holding the lease through the enqueue\n // would drop a fast decision at lock contention. Idempotent vs. `execute`'s own finally release.\n await this.store.releaseRunLock(run.id);\n // THEN enqueue. A failed/lost dispatch leaves the run suspended-awaiting with `wakeAt` set, so the\n // timer poller re-drives it — no lost run.\n await remote.executor.dispatch(run, history, taskId);\n return { runId: run.id, status: 'suspended' };\n }\n\n // INLINE advance (in-process group-served executors): the decision is produced in-process, so await\n // it under the lease. Single-instance by nature; the dispatch path above is the multi-instance one.\n const advanceExecutor = remote.executor.advance;\n if (!advanceExecutor) {\n throw new Error(\n `workflow ${run.workflow}@${run.workflowVersion}: executor implements neither advance nor dispatch`,\n );\n }\n let decision: WorkflowDecision;\n try {\n // When `remoteAdvanceSilenceMs` is configured, wrap the advance in a heartbeat-rearmed deadline\n // keyed by `run.id`: a worker replaying this turn beats (a run-scoped Heartbeat) to keep it alive,\n // and only a genuinely-silent worker trips RemoteWorkflowTimeout → recovery re-drive. Unset = the\n // prior unbounded await. INVARIANT: `advance()` is created and passed to awaitWithLivenessDeadline\n // SYNCHRONOUSLY (no await between), so the `heartbeatResets` entry is registered before the event\n // loop can deliver any beat — an early beat is never lost. If the executor ALSO carries its own\n // `timeoutMs`, the shorter of the two deadlines wins (both raise the same RemoteWorkflowTimeout,\n // handled identically by the catch below).\n const silenceMs = this.remoteAdvanceSilenceMs;\n const advance = advanceExecutor.call(remote.executor, run, history);\n decision =\n silenceMs != null\n ? await this.awaitWithLivenessDeadline(\n run.id,\n advance,\n silenceMs,\n () => new RemoteWorkflowTimeout(run.id, silenceMs),\n )\n : await advance;\n } catch (err) {\n // A RemoteWorkflowTimeout is NOT a failure: the advance only timed out (the decision was likely\n // dropped, while the work may have actually completed). Failing the run here would be wrong — and\n // would notify the parent of a false failure. Instead RELEASE the lease and leave the run in its\n // current `running` state so `recoverIncomplete` re-acquires the now-free lease and re-drives it;\n // the re-driven turn replays completed steps from history and, if the work was done, returns the same\n // `completed` decision → settles → notifies the parent. Opt-in: only reachable when the executor\n // was constructed with a `timeoutMs` (absent = prior unbounded await, unchanged).\n //\n // FIXED-TIMEOUT HAZARD: a bare RemoteWorkflowExecutor `timeoutMs` that fires while a worker is\n // LEGITIMATELY still executing a not-yet-checkpointed step re-drives → DUPLICATE side effects, so\n // that knob is only safe set GENEROUSLY (> the longest legitimate single turn). The robust fix is\n // the heartbeat-rearmed deadline above (`remoteAdvanceSilenceMs`): the worker beats while it works,\n // so only a genuinely-silent (dead) worker trips the timeout — no re-drive of a live turn.\n //\n // Lease lifecycle: `execute` clears its renew interval in its `finally` once this returns, so the\n // lease (released just below) stays free. `releaseRunLock` is idempotent, and `renewRunLock` is a\n // no-op once `lockedBy` is cleared, so a renew tick racing the release cannot re-acquire it.\n if (err instanceof RemoteWorkflowTimeout) {\n await this.store.releaseRunLock(run.id);\n // The suspended path returned early above; run is always `running` here — left for recovery to re-drive.\n return { runId: run.id, status: 'running' as const };\n }\n const error = {\n message: err instanceof Error ? err.message : String(err),\n stack: err instanceof Error ? err.stack : undefined,\n };\n // terminal failure: lease expires naturally — no recovery re-drive will race it\n await this.store.updateRun(run.id, { status: 'failed', error, updatedAt: new Date() });\n this.emit({\n type: 'run.failed',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n error,\n });\n return { runId: run.id, status: 'failed', error };\n }\n\n return this.applyDecision(run, decision);\n }\n\n /**\n * Apply a remote workflow turn's {@link WorkflowDecision}: persist the local steps it ran, then\n * settle (completed/failed/cancelled) or dispatch its blocking ops and suspend (continue). Shared by\n * the INLINE-advance path ({@link runRemoteExecution}, under the held lease) and the durable\n * DISPATCH path ({@link completeRemoteDecision}, which holds the lease itself). Idempotent transitions\n * — the caller has already ensured this is the decision for the currently-awaited turn.\n */\n private async applyDecision(run: WorkflowRun, decision: WorkflowDecision): Promise<RunResult> {\n if (decision.status === 'completed') {\n // Persist the local steps THIS turn ran before marking the run done. A workflow that runs\n // straight to completion in a single turn (every step inline, never suspending — e.g. a Python\n // @workflow whose body is a sequence of ctx.step calls) emits ALL its recordStep commands on\n // this terminal turn; without applying them the run shows `completed` with zero recorded steps.\n // Only this turn's NEW steps are present (prior turns' steps replay as `found`, emitting no\n // command), so there's no duplication.\n await this.applyCommands(run, decision.commands);\n return this.settleRun(run, { kind: 'completed', output: decision.output });\n }\n if (decision.status === 'failed') {\n // Same as completed: persist the steps this turn ran — including the failed one (the worker\n // records a failed-step command before raising) — so the dashboard shows WHERE it failed.\n await this.applyCommands(run, decision.commands);\n return this.settleRun(run, {\n kind: 'failed',\n error: decision.error ?? { message: 'workflow failed' },\n });\n }\n\n if (decision.status === 'cancelled') {\n // The worker bailed at an op boundary because the run was cancelled mid-turn — `cancel` already\n // set status=cancelled, cascaded to children and emitted the lifecycle event. Persist the steps\n // that DID run this turn (partial progress / where it stopped) and reassert `cancelled`\n // (idempotent with `cancel`'s write; preserves the existing error). The point is to NOT resurrect\n // the run to `suspended` or flip it to `failed` — both of which a normal turn result would do.\n await this.applyCommands(run, decision.commands);\n await this.store.updateRun(run.id, { status: 'cancelled', updatedAt: new Date() });\n return { runId: run.id, status: 'cancelled' };\n }\n\n // continue: persist any local steps the replay ran, dispatch the blocking ops, then suspend. When\n // those resolve (a result lands, a timer fires) `resume` brings us back for the next turn.\n //\n // Guard: re-read the run BEFORE writing `suspended` — a parent-cancel cascade may have written\n // `cancelled` to the store WHILE the executor was replaying this turn (the advance() awaited above\n // runs outside the store transaction). Overwriting `cancelled` → `suspended` would let recovery\n // re-drive the run forever. If the store already shows a terminal/cancelled state, bail without\n // touching it — identical to the guard in `completeRemoteResult` for remote step results.\n const fresh = await this.store.getRun(run.id);\n if (\n fresh &&\n (fresh.status === 'cancelled' || fresh.status === 'completed' || fresh.status === 'dead')\n ) {\n return { runId: run.id, status: fresh.status, output: fresh.output, error: fresh.error };\n }\n const wakeAt = await this.applyCommands(run, decision.commands);\n return this.settleRun(run, { kind: 'suspended', wakeAt });\n }\n\n /** The run's resolved durable ops as replay inputs: completed/failed steps + elapsed timers. */\n private async remoteHistory(runId: string): Promise<HistoryEvent[]> {\n const checkpoints = await this.store.listCheckpoints(runId);\n const kindOf: Record<StepKind, HistoryEvent['kind']> = {\n remote: 'call',\n local: 'step',\n sleep: 'timer',\n signal: 'signal',\n };\n const events: HistoryEvent[] = [];\n for (const cp of checkpoints) {\n if (cp.status === 'completed' || cp.status === 'failed') {\n // A child run resolves THROUGH the signal machinery (a `child:<id>` waiter notified on the\n // child's terminal state), so its checkpoint is kind `signal` with a `signal:child:` name and\n // a Completion payload. Surface it as a `child` event with the value/error unwrapped.\n if (cp.kind === 'signal' && cp.name.startsWith('signal:child:')) {\n const completion = cp.output as Completion<unknown> | undefined;\n events.push({\n seq: cp.seq,\n kind: 'child',\n output: completion?.ok ? completion.value : undefined,\n error:\n completion && completion.ok === false ? { message: completion.error } : undefined,\n });\n continue;\n }\n events.push({\n seq: cp.seq,\n kind: kindOf[cp.kind] ?? 'step',\n // A signal checkpoint's name is the internal `signal:<token>`, not the workflow-level signal\n // name the replay used — omit it so the replay matches on seq + kind (its determinism anchor).\n name: cp.kind === 'signal' ? undefined : cp.name,\n output: cp.status === 'completed' ? cp.output : undefined,\n error: cp.status === 'failed' ? cp.error : undefined,\n });\n } else if (cp.kind === 'sleep' && cp.wakeAt != null && cp.wakeAt <= this.clock()) {\n // a still-`pending` sleep whose deadline has passed reads as a resolved timer on replay.\n events.push({ seq: cp.seq, kind: 'timer', name: cp.name });\n }\n }\n return events.sort((a, b) => a.seq - b.seq);\n }\n\n /** Apply a turn's commands: persist recorded local steps, dispatch remote calls, schedule timers.\n * Returns the earliest timer deadline to suspend on (or undefined — suspended on a result). */\n private async applyCommands(\n run: WorkflowRun,\n commands: WorkflowCommand[],\n ): Promise<number | undefined> {\n let wakeAt: number | undefined;\n for (const cmd of commands) {\n const at = new Date();\n const id = stepId(run.id, cmd.seq);\n if (cmd.kind === 'recordStep') {\n // Prefer the step's real wall-clock window + sub-process events (carried by the command, and\n // already streamed live via persistStepEvent) so the checkpoint shows a true duration and its\n // p-process trail — not a 0ms placeholder. Fall back to apply-time for older workers.\n const startedAt = cmd.startedAt != null ? new Date(cmd.startedAt) : at;\n const finishedAt = cmd.finishedAt != null ? new Date(cmd.finishedAt) : at;\n await this.store.saveCheckpoint(\n stepCheckpoint({\n runId: run.id,\n seq: cmd.seq,\n name: cmd.name,\n kind: 'local',\n status: cmd.error ? 'failed' : 'completed',\n output: cmd.output,\n error: cmd.error,\n events: cmd.events,\n attempts: 1,\n enqueuedAt: startedAt,\n startedAt,\n finishedAt,\n // Carry the worker's `parallelGroup` (a Python `ctx.gather` tags every step in the fan with\n // the same group) onto the checkpoint, so the dashboard can render the steps as one parallel\n // group instead of a sequential list. Additive: undefined for ordinary sequential steps.\n parallelGroup: cmd.parallelGroup,\n }),\n );\n this.emit({\n type: cmd.error ? 'step.failed' : 'step.completed',\n runId: run.id,\n seq: cmd.seq,\n name: cmd.name,\n kind: 'local',\n output: cmd.output,\n error: cmd.error,\n });\n } else if (cmd.kind === 'call') {\n // Idempotency (load-bearing for `ctx.gather_calls`): a fan-out re-emits its still-pending\n // `call` commands on every PARTIAL resume (a sibling settled, but not all). Without this guard\n // each re-emit would re-persist + re-dispatch an already-in-flight (or already-completed) step,\n // double-dispatching the worker and resetting attempts. So if a checkpoint for (run.id, seq)\n // already exists — pending OR terminal — skip the save + dispatch entirely; its result lands\n // independently via completeRemoteResult (keyed by seq, so concurrent calls never clobber).\n // Mirrors the `startChild` `getRun(childId)` guard below.\n if (await this.store.getCheckpoint(run.id, cmd.seq)) continue;\n await this.store.saveCheckpoint(\n stepCheckpoint({\n runId: run.id,\n seq: cmd.seq,\n name: cmd.name,\n kind: 'remote',\n status: 'pending',\n input: cmd.input,\n attempts: 1,\n // `cmd.group` is the routing declaration the worker's replay emitted (cross-SDK, or a\n // group-served TS body) — treated as an isolation partition on top of the step's own\n // name, mirroring the StepDef formula below (identical expression everywhere).\n workerGroup: tenantGroup(sanitizeQueueToken(cmd.name), cmd.group),\n enqueuedAt: at,\n startedAt: at,\n finishedAt: at,\n // A `ctx.gather_calls([...])` fan-out stamps every dispatched `call` in the fan with the\n // same group, so the dashboard renders the dispatched steps as one parallel fan (parity\n // with the gathered `recordStep`/`startChild` tags). Undefined for a lone sequential `ctx.step`.\n parallelGroup: cmd.parallelGroup,\n }),\n );\n await this.pool.dispatch(\n {\n runId: run.id,\n seq: cmd.seq,\n name: cmd.name,\n stepId: id,\n group: tenantGroup(sanitizeQueueToken(cmd.name), cmd.group),\n input: cmd.input,\n traceparent: this.traceparent?.(),\n context: this.context?.(),\n attempt: 1,\n },\n undefined,\n );\n this.emit({\n type: 'step.started',\n runId: run.id,\n seq: cmd.seq,\n name: cmd.name,\n kind: 'remote',\n });\n } else if (cmd.kind === 'sleep') {\n const deadline = this.clock() + cmd.ms;\n await this.store.saveCheckpoint(\n stepCheckpoint({\n runId: run.id,\n seq: cmd.seq,\n name: `sleep:${cmd.seq}`,\n kind: 'sleep',\n status: 'pending',\n attempts: 1,\n wakeAt: deadline,\n enqueuedAt: at,\n startedAt: at,\n finishedAt: at,\n }),\n );\n wakeAt = wakeAt == null ? deadline : Math.min(wakeAt, deadline);\n } else if (cmd.kind === 'waitSignal') {\n // Park on a signal: register a waiter at this seq so engine.signal(token) lands the resolving\n // `signal` checkpoint here and resumes the run. The token is the signal name, so an external\n // engine.signal(name, payload) delivers it. If the signal was already delivered (buffered\n // before the workflow reached this point — e.g. signalWithStart), resolve it now and re-drive\n // on a macrotask, AFTER this turn suspends and frees the run lock (a re-entrant resume bails).\n //\n // NOTE: `WorkflowCommand` has no `waitEvent` kind — a polyglot (remote-executor) workflow has\n // no way to issue `ctx.waitForEvent(name, { match })` today; only in-process TS workflows\n // (`workflow-ctx.ts`) can. So buffered EVENTS (`bufferEvent`/`listBufferedEvents`/\n // `removeBufferedEvent`) are reachable only from `engine.publishEvent` and the in-process\n // `waitForEvent`/reconcile paths — never from this remote command loop. Extending the\n // polyglot protocol with an event-wait command is future work, not something to invent here.\n const deliverBuffered = async (payload: unknown): Promise<void> => {\n await this.store.saveCheckpoint(\n instantCheckpoint({\n runId: run.id,\n seq: cmd.seq,\n name: `signal:${cmd.signal}`,\n kind: 'signal',\n output: payload,\n }),\n );\n setTimeout(() => void this.resume(run.id).catch(() => undefined), 0);\n };\n const buffered = await this.store.takeBufferedSignal(cmd.signal);\n if (buffered) {\n await deliverBuffered(buffered.payload);\n } else {\n // Same reorder as the in-process ctx.waitForSignal (see there for why registering\n // UNCONDITIONALLY before even the first check is unsafe — it would expose a \"this turn is\n // about to self-resolve\" waiter row to a concurrent signal for a token a polyglot entity\n // loop reuses, which could steal it and misdeliver): check first, and only on a miss\n // register, then re-check once more before suspending — closing the lost-wake window where\n // a signal races in between the miss above and the registration below (see the interleaving\n // proof at engine.signal).\n await this.store.putSignalWaiter({ token: cmd.signal, runId: run.id, seq: cmd.seq });\n const lateBuffered = await this.store.takeBufferedSignal(cmd.signal);\n if (lateBuffered) {\n // Resolved it ourselves — remove OUR OWN row via the exact match (not\n // takeSignalWaiter(cmd.signal), which deletes ANY row for this token and could steal a\n // different run's waiter that has since claimed the same token).\n await this.store.removeSignalWaiter({ token: cmd.signal, runId: run.id, seq: cmd.seq });\n await deliverBuffered(lateBuffered.payload);\n }\n }\n } else if (cmd.kind === 'startChild') {\n // Start a child run and await it (the worker's ctx.start_child suspends until the child's\n // result is in history). Mirror the in-process `ctx.child`: register a `child:<id>` waiter at\n // this seq — the child notifies it on its terminal state (engine.notifyParent) — then start the\n // child once, deferred so a fast child can't reentrantly resume this still-suspending parent,\n // and id-idempotent so replay/recovery never double-starts it.\n const childId = `${run.id}.child.${cmd.seq}`;\n await this.store.putSignalWaiter({\n token: `child:${childId}`,\n runId: run.id,\n seq: cmd.seq,\n // A `ctx.gather_children`/`ctx.all` fan-out stamps every `startChild` in the fan with the same\n // group. Thread it onto the waiter so the child's terminal `signal:child:<id>` checkpoint\n // (written by engine.signal when the child notifies the parent) carries the group and the\n // dashboard renders the fan as one parallel group. Undefined for a lone (non-fan) child.\n parallelGroup: cmd.parallelGroup,\n });\n if (!(await this.store.getRun(childId))) {\n // Inherit the parent run's namespace (see ctxHostFor.startChild) so a remote workflow's\n // child stays on the parent's tenant/partition regardless of which engine executes it.\n this.startChildDeferred(cmd.workflow, cmd.input, childId, { namespace: run.namespace });\n }\n } else {\n throw new Error(\n `remote workflow command '${(cmd as { kind: string }).kind}' is not supported yet`,\n );\n }\n }\n return wakeAt;\n }\n\n /**\n * Undo the registered saga compensations in reverse and settle the run `cancelled`. Shared by EVERY\n * exit path of a run with a compensating cancel in flight — whether the resumed replay returned,\n * suspended, hit continue-as-new, or threw — so a cancel is never lost just because the body didn't\n * stop at a suspension point.\n *\n * A dispatched compensation still in flight (or backing off a retry) needs the run to keep waiting:\n * unlike the failure path (which is fine going `suspended` — a resumable state no different from an\n * ordinary in-flight `ctx.step`), THIS run must stay `cancelling` — `engine.cancel`'s idempotent\n * re-check, `waitForRun`'s non-terminal treatment, and crash recovery (`recoverIncomplete` only\n * re-drives `running`/`cancelling` runs — a `cancelling` one with a free lease, whatever it's\n * internally waiting on) all key off that status. So on a pending unwind this returns WITHOUT\n * touching `status` (already `cancelling`, untouched since `engine.cancel` set it) — the in-memory\n * cancel flag stays too, re-derived from the status on any later re-drive regardless.\n */\n private async compensateAndCancel(\n run: WorkflowRun,\n compensations: Compensation[],\n replay?: Map<number, StepCheckpoint>,\n ): Promise<RunResult> {\n const pending = await this.unwindCompensations(run, compensations, replay);\n if (pending) return { runId: run.id, status: 'cancelling' };\n this.cancelRequested.delete(run.id);\n const error = { message: 'cancelled' };\n await this.store.updateRun(run.id, { status: 'cancelled', error, updatedAt: new Date() });\n this.emit({\n type: 'run.failed',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n error,\n });\n return { runId: run.id, status: 'cancelled', error };\n }\n\n /** The run body, lease held + renewed by {@link execute}. */\n private async runExecution(\n run: WorkflowRun,\n fn: WorkflowFn,\n registered: RegisteredWorkflow | undefined,\n ): Promise<RunResult> {\n // A run persisted as `cancelling` is a compensating cancel in flight — possibly re-driven by\n // recovery after a crash that lost the in-memory cancel flag. Re-derive the intent from the status\n // so the replay below reaches the WorkflowSuspended + cancelRequested branch and compensates →\n // cancelled (this is what makes a compensating cancel durable across a crash).\n if (run.status === 'cancelling') this.cancelRequested.add(run.id);\n // First execution of an enqueued run: mark it running and announce the start, BEFORE the singleton\n // gate — `singletons.admit` only counts `running`/`suspended` runs, so a still-`pending` run could\n // never be admitted. A resumed run is already past `pending`, so this fires exactly once.\n if (run.status === 'pending') {\n await this.store.updateRun(run.id, { status: 'running', updatedAt: new Date() });\n run.status = 'running';\n this.emit({\n type: 'run.started',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n });\n }\n // Singleton admission gate: if this run shares its key with `limit` older in-flight runs, wait\n // (suspend on a short timer) until a slot frees instead of running now. Re-checked on each resume.\n // A `cancelling` run skips the gate — it is tearing down, not competing for a slot, and suspending\n // it here would clobber the `cancelling` status.\n if (\n run.status !== 'cancelling' &&\n registered?.singleton &&\n !(await this.singletons.admit(run, registered.singleton))\n ) {\n const wakeAt = this.singletons.retryWakeAt();\n await this.store.updateRun(run.id, { status: 'suspended', wakeAt, updatedAt: new Date() });\n this.emit({\n type: 'run.suspended',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n });\n await this.store.releaseRunLock(run.id);\n return { runId: run.id, status: 'suspended' };\n }\n // Saga compensations registered by completed steps; run in reverse if the run later fails.\n const compensations: Compensation[] = [];\n // Load this run's checkpoints ONCE and key them by seq, so replaying the completed prefix reads\n // from memory instead of one `getCheckpoint` SELECT per primitive (the O(N²) replay-reads fix).\n // Read once at execution start: a checkpoint written AFTER this snapshot (the signal/timer/child\n // this resume wakes on, or one written later in this same execution) is absent from the map, and\n // the ctx falls back to the live store for any absent seq — so replay semantics are unchanged.\n const snapshot = await this.store.listCheckpoints(run.id);\n const replay = new Map<number, StepCheckpoint>();\n for (const cp of snapshot) replay.set(cp.seq, cp);\n const ctx = createWorkflowCtx(\n this.ctxHostFor(replay, run.namespace),\n run.id,\n compensations,\n run.workflow,\n registered?.searchAttributesSchema,\n );\n try {\n // The ambient-context wrap is what lets class-first statics (`MyWorkflow.execute()`) find\n // this ctx from anywhere on the body's async path — first run and every replay alike.\n const output = await runInWorkflowCtx(ctx, () => fn(ctx, run.input));\n // A compensating cancel may have been requested while this turn ran (or re-derived from a\n // `cancelling` status on recovery): undo + settle cancelled rather than completing, so the cancel\n // is never lost when the body returns without first hitting a suspension point.\n if (this.cancelRequested.has(run.id)) {\n return this.compensateAndCancel(run, compensations, replay);\n }\n return this.settleRun(run, { kind: 'completed', output });\n } catch (err) {\n if (err instanceof ContinueAsNew) {\n // A cancel in flight wins over continue-as-new: undo + cancel instead of spawning the next run.\n if (this.cancelRequested.has(run.id)) {\n return this.compensateAndCancel(run, compensations, replay);\n }\n // Hand off to a fresh execution with a clean history: complete this run, then start the next\n // (`<id>~N`) with the new input. Deferred + idempotent by the continuation id, so a crash\n // mid-handoff re-derives the same next run instead of forking.\n await this.store.updateRun(run.id, {\n status: 'completed',\n output: undefined,\n error: undefined,\n updatedAt: new Date(),\n });\n this.emit({\n type: 'run.completed',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n });\n void this.notifyParent(run.id, { ok: true, value: undefined });\n const nextId = nextContinuationId(run.id);\n queueMicrotask(\n () => void this.start(run.workflow, err.input, nextId).catch(() => undefined),\n );\n return { runId: run.id, status: 'completed' };\n }\n if (err instanceof WorkflowSuspended) {\n // A compensating cancel resumed this run to reach here: undo + cancel instead of re-suspending.\n if (this.cancelRequested.has(run.id)) {\n return this.compensateAndCancel(run, compensations, replay);\n }\n return this.settleRun(run, { kind: 'suspended', wakeAt: err.wakeAt });\n }\n // A cancel in flight that surfaced as a thrown error still settles cancelled (not failed) — the\n // saga undo runs either way; this just keeps the terminal status faithful to the cancel request.\n if (this.cancelRequested.has(run.id)) {\n return this.compensateAndCancel(run, compensations, replay);\n }\n const error = {\n message: err instanceof Error ? err.message : String(err),\n stack: err instanceof Error ? err.stack : undefined,\n };\n // Saga: undo completed steps in reverse — local ones in-process, dispatched ones as durable\n // remote-step dispatches (see `unwindCompensations`) — each made VISIBLE as a `compensate:<step>`\n // step event/checkpoint so a stranded undo is never silently swallowed; a failing one is still\n // skipped so it can't mask the original failure or strand the rest (compensations should be\n // idempotent). A dispatched undo still in flight (or backing off a retry) SUSPENDS the run\n // exactly like an ordinary `ctx.step` dispatch — the next re-drive (the worker's result landing,\n // or the retry backoff elapsing) resumes `unwindCompensations` right where it left off.\n const pending = await this.unwindCompensations(run, compensations, replay);\n if (pending) return this.settleRun(run, { kind: 'suspended', wakeAt: pending.wakeAt });\n return this.settleRun(run, { kind: 'failed', error });\n } finally {\n // Release the recovery lease once the run reaches a terminal/suspended state, so the\n // next instance (or the timer poller) can pick it up promptly.\n await this.store.releaseRunLock(run.id);\n }\n }\n\n /**\n * Undo every registered saga compensation in strict reverse order — the shared unwind both the\n * run-failure path (`runExecution`'s catch) and the compensating-cancel path\n * (`compensateAndCancel`) drive. Every entry, LOCAL or DISPATCHED, gets a NEGATIVE checkpoint seq\n * `-(k + 1)` for its position `k` (0, 1, 2… walking the stack in reverse) — reserved space that can\n * never collide with a body position (those start at 0), so a saga's undo trail composes onto the\n * run's ordinary checkpoint history with no store-schema change, and shows up in run detail exactly\n * like any other step. Deterministic because `compensations` is rebuilt identically on every replay\n * (see `workflow-ctx.ts`), so the same comp always lands on the same negative seq across a crash +\n * re-drive — the crash-safety this whole scheme rests on.\n *\n * A LOCAL entry runs in-process (`runCompensation`), which checkpoints its own outcome — completed,\n * or failed once `compensationRetries` are exhausted — so a crash mid-unwind SKIPS an\n * already-resolved one on the next pass instead of re-running it (and re-spending its retry budget)\n * from attempt 1. A DISPATCHED entry is an ordinary remote-step dispatch under the hood\n * (`dispatchCompensation`): when it needs the run to WAIT — freshly dispatched, still in flight, or\n * backing off a durable retry — this function returns that wait signal immediately (skipping every\n * comp after it in this pass); the CALLER decides how to represent \"still unwinding\" (see\n * `compensateAndCancel`'s doc comment for why that differs between the two callers). Either way, the\n * run resumes later exactly like any other dispatched step: `completeRemoteResult` completes the\n * negative-seq checkpoint and re-drives, the body replays and deterministically re-throws the same\n * exit it took before (the original failure, or the suspension `compensateAndCancel` resumed from),\n * this function runs again, the now-resolved comp is skipped, and the unwind continues from there.\n *\n * Returns `undefined` once every compensation has resolved — the caller then finalizes the run\n * (`failed` with the ORIGINAL body error, never masked by a comp outcome; or `cancelled`).\n */\n private async unwindCompensations(\n run: WorkflowRun,\n compensations: Compensation[],\n replay?: Map<number, StepCheckpoint>,\n ): Promise<UnwindPending | undefined> {\n for (let i = compensations.length - 1; i >= 0; i -= 1) {\n const comp = compensations[i];\n if (!comp) continue;\n const seq = -(compensations.length - i);\n if ('fn' in comp) {\n const existing = replay?.get(seq) ?? (await this.store.getCheckpoint(run.id, seq));\n if (existing) continue; // already resolved (completed or exhausted-failed) in an earlier pass\n await this.runCompensation(run, comp, seq, replay);\n continue;\n }\n const pending = await this.dispatchCompensation(run, comp, seq, replay);\n if (pending) return pending;\n }\n return undefined;\n }\n\n /**\n * Run one LOCAL saga compensation, retried up to `compensationRetries`, emitting a\n * `compensate:<step>` step event for its outcome so a stranded undo is visible. Never throws — a\n * permanently-failing compensation is skipped so it can't mask the original failure. Checkpoints\n * its outcome at `seq` (a negative unwind position reserved by {@link unwindCompensations}) so a\n * crash mid-unwind skips an already-resolved undo on a later pass instead of re-running it (and\n * re-spending its retry budget) from attempt 1 — the checkpoint is durability/visibility only; the\n * runtime retry-in-process-back-to-back semantics of `comp.fn()` are unchanged.\n */\n private async runCompensation(\n run: WorkflowRun,\n comp: Extract<Compensation, { fn: () => Promise<void> }>,\n seq: number,\n replay?: Map<number, StepCheckpoint>,\n ): Promise<void> {\n const name = `compensate:${comp.name}`;\n const enqueuedAt = new Date();\n for (let attempt = 1; attempt <= this.compensationRetries; attempt += 1) {\n const startedAt = new Date();\n try {\n await comp.fn();\n this.emit({\n type: 'step.completed',\n runId: run.id,\n workflow: run.workflow,\n name,\n kind: 'local',\n durationMs: Date.now() - startedAt.getTime(),\n });\n const cp = stepCheckpoint({\n runId: run.id,\n seq,\n name,\n kind: 'local',\n status: 'completed',\n attempts: attempt,\n enqueuedAt,\n startedAt,\n finishedAt: new Date(),\n });\n await this.store.saveCheckpoint(cp);\n replay?.set(seq, cp);\n return;\n } catch (err) {\n if (attempt >= this.compensationRetries) {\n const error = { message: err instanceof Error ? err.message : String(err) };\n this.emit({\n type: 'step.failed',\n runId: run.id,\n workflow: run.workflow,\n name,\n kind: 'local',\n error,\n durationMs: Date.now() - startedAt.getTime(),\n });\n const cp = stepCheckpoint({\n runId: run.id,\n seq,\n name,\n kind: 'local',\n status: 'failed',\n attempts: attempt,\n error,\n enqueuedAt,\n startedAt,\n finishedAt: new Date(),\n });\n await this.store.saveCheckpoint(cp);\n replay?.set(seq, cp);\n }\n }\n }\n }\n\n /**\n * Resolve (or advance) ONE dispatched saga compensation at its reserved negative `seq` — the undo\n * handler is an ordinary remote `@Step`, so this mirrors `callRemote`'s pending/failed/absent\n * branches (engine.ts's `callRemote`), minus the queue/admission and in-memory-`timeoutMs` paths\n * (V1: dispatch direct by name, always durable). Returns the wait signal when the run must pause for\n * this compensation (freshly dispatched, still in flight, or backing off before a durable retry);\n * `undefined` once it's resolved — completed (crash-safe skip), or retries exhausted/non-retryable\n * (already visible: `completeRemoteResult` emitted `step.failed` for `compensate:<name>` when that\n * checkpoint landed — never re-emitted here, and never allowed to block the rest of the unwind or\n * mask the run's original failure).\n */\n private async dispatchCompensation(\n run: WorkflowRun,\n comp: Extract<Compensation, { dispatch: unknown }>,\n seq: number,\n replay?: Map<number, StepCheckpoint>,\n ): Promise<UnwindPending | undefined> {\n const { def, args } = comp.dispatch;\n const name = `compensate:${comp.name}`;\n const existing = replay?.get(seq) ?? (await this.store.getCheckpoint(run.id, seq));\n if (existing?.status === 'completed') return undefined;\n if (existing?.status === 'pending') return {}; // dispatched, awaiting the worker's result\n if (existing?.status === 'failed') {\n const maxAttempts = Math.max(1, def.retries ?? 1);\n const retryable = existing.error?.retryable !== false;\n if (!retryable || existing.attempts >= maxAttempts) return undefined;\n if (existing.wakeAt == null) {\n const wakeAt = this.clock() + backoffDelay(existing.attempts, def);\n const withWakeAt = { ...existing, wakeAt };\n await this.store.saveCheckpoint(withWakeAt);\n replay?.set(seq, withWakeAt);\n return { wakeAt };\n }\n if (this.clock() < existing.wakeAt) return { wakeAt: existing.wakeAt };\n await this.dispatchCompensationAttempt(\n run,\n seq,\n name,\n def,\n args,\n existing.attempts + 1,\n replay,\n );\n return {};\n }\n // Absent: first dispatch.\n await this.dispatchCompensationAttempt(run, seq, name, def, args, 1, replay);\n return {};\n }\n\n /**\n * Dispatch (or re-dispatch, on a durable retry) one compensation's undo handler — mirrors\n * `callRemote`'s dispatch block (persist the `pending` checkpoint BEFORE handing off to the\n * transport, so a fast result always finds it to complete). Two DIFFERENT names are in play: the\n * checkpoint's `name` is `compensate:<originalStepName>` (what makes this undo show up on the run's\n * timeline, and what `completeRemoteResult` emits `step.completed`/`step.failed` under); the WIRE\n * task's `name` is the undo handler's OWN routing name (`def.name`) — a worker dispatches to the\n * `@Step` it registered, not to this saga-visibility label.\n */\n private async dispatchCompensationAttempt(\n run: WorkflowRun,\n seq: number,\n name: string,\n def: StepDef<StepUndo<unknown, unknown>, unknown>,\n args: StepUndo<unknown, unknown>,\n attempt: number,\n replay?: Map<number, StepCheckpoint>,\n ): Promise<void> {\n if (this.pool.size === 0) throw new Error('remote steps require a Transport');\n const group = tenantGroup(sanitizeQueueToken(def.name), def.partition);\n const enqueuedAt = new Date();\n const cp = stepCheckpoint({\n runId: run.id,\n seq,\n name,\n kind: 'remote',\n status: 'pending',\n input: args,\n attempts: attempt,\n workerGroup: group,\n enqueuedAt,\n startedAt: enqueuedAt,\n finishedAt: enqueuedAt,\n });\n await this.store.saveCheckpoint(cp);\n replay?.set(seq, cp);\n await this.pool.dispatch({\n runId: run.id,\n seq,\n name: def.name,\n stepId: cp.stepId,\n group,\n input: args,\n traceparent: this.traceparent?.(),\n context: this.context?.(),\n attempt,\n });\n this.emit({ type: 'step.started', runId: run.id, seq, name, kind: 'remote' });\n }\n\n /** The seam handed to {@link createWorkflowCtx}: the authoring API reaches durability + lifecycle\n * (checkpointing, dispatch, child start) through this, so the ctx primitives live in their own\n * module and the engine stays the orchestrator. */\n private ctxHostFor(replay?: Map<number, StepCheckpoint>, parentNamespace?: string): CtxHost {\n return {\n store: this.store,\n replay,\n clock: this.clock,\n webhookUrl: this.webhookUrl,\n startStep: (s) => this.startStep(s),\n completeStep: (s) => this.completeStep(s),\n failStep: (s) => this.failStep(s),\n callRemote: (runId, seq, step, input, queue, transport, admission) =>\n this.callRemote(runId, seq, step, input, queue, transport, replay, admission),\n // Defer so a fast child can't reentrantly resume a still-running parent. Stamp the child with\n // the PARENT run's namespace (not this engine's) so a child belongs to the tenant/partition of\n // the run it was spawned from — even when an operator (namespace: undefined, drives every\n // namespace) is the one executing the parent. Otherwise an operator recovery-resuming a\n // `davi-local` pipeline would stamp its `processing` child `default` and it would leak off the\n // tenant's worker pool onto the shared/dev workers.\n startChild: (workflow, input, id, priority) => {\n this.startChildDeferred(workflow, input, id, { priority, namespace: parentNamespace });\n },\n // Deferred for the same reentrancy reason as `startChild` above. `cancel()` is already\n // idempotent on a terminal/cancelled run (returns its existing status without side effects), so\n // no extra guard is needed here for the failFast replay case (re-issuing the same cancel calls).\n cancelChild: (childId) => {\n queueMicrotask(() => void this.cancel(childId).catch(() => undefined));\n },\n // Shallow-merge into the run's searchAttributes (the ctx primitive makes this exactly-once).\n upsertSearchAttributes: async (runId, attrs) => {\n const run = await this.store.getRun(runId);\n await this.store.updateRun(runId, {\n searchAttributes: { ...(run?.searchAttributes ?? {}), ...attrs },\n updatedAt: new Date(),\n });\n },\n signalEntity: (name, key, op, arg, reply) => {\n queueMicrotask(\n () => void this.entities.dispatch(name, key, op, arg, reply).catch(() => undefined),\n );\n },\n interceptStep: (invocation, body) => this.interceptStep(invocation, body),\n };\n }\n\n /**\n * Resume a run paused at a {@link WorkflowCtx.breakpoint} (e.g. the dashboard \"continue\" button).\n * Finds the run's pending breakpoint checkpoint and signals it. Returns null if the run isn't\n * paused at a breakpoint.\n */\n async continue(runId: string): Promise<RunResult | null> {\n const checkpoints = await this.store.listCheckpoints(runId);\n const bp = checkpoints.find(isBreakpoint);\n if (!bp) return null;\n return this.signal(breakpointToken(runId, bp.seq), undefined);\n }\n\n /**\n * Read the latest value a run published for `key` via {@link WorkflowCtx.setEvent} — a\n * side-effect-free query of a live (or finished) run's state. Returns `undefined` if the run\n * never published that key. The suspend-model counterpart of a Temporal query.\n */\n async getEvent<TValue = unknown>(runId: string, key: string): Promise<TValue | undefined> {\n const name = `event:${key}`;\n // Targeted read: the highest-seq checkpoint for this name is the most recent value (a re-published\n // key overwrites at a higher seq), matching the old \"last in seq order wins\" scan. Falls back to a\n // full listCheckpoints scan (last match in seq-ascending order wins) for a store that omits it.\n if (this.store.getLatestCheckpointByName) {\n const latest = await this.store.getLatestCheckpointByName(runId, name);\n return latest?.output as TValue | undefined;\n }\n // listCheckpoints is ordered by seq ascending, so the last match is the most recent value.\n let latest: TValue | undefined;\n for (const cp of await this.store.listCheckpoints(runId))\n if (cp.name === name) latest = cp.output as TValue;\n return latest;\n }\n\n /**\n * Register a validator gating `engine.update(runId, name, …)` for runs of `workflow`. The\n * validator runs BEFORE the update is delivered, so a rejection leaves the run untouched. One\n * validator per (workflow, update name); registering again replaces it.\n */\n registerUpdateValidator<TArg>(\n workflow: string,\n name: string,\n validate: UpdateValidator<TArg>,\n ): void {\n this.updateValidators.set(`${workflow}:${name}`, validate as UpdateValidator);\n }\n\n /**\n * Deliver a validated update to the run waiting at `ctx.onUpdate(name)`. Runs the registered\n * validator (if any) first: on rejection returns `{ accepted: false, reason }` without disturbing\n * the run; otherwise delivers `arg` and resumes, returning `{ accepted: true, run }` (`run` is null\n * if nothing was waiting — a too-early or duplicate update).\n */\n async update(runId: string, name: string, arg: unknown): Promise<UpdateResult> {\n const run = await this.store.getRun(runId);\n if (!run) return { accepted: false, reason: `run ${runId} not found` };\n const validate = this.updateValidators.get(`${run.workflow}:${name}`);\n if (validate) {\n try {\n const reason = await validate(arg);\n if (typeof reason === 'string' && reason.length > 0) return { accepted: false, reason };\n } catch (err) {\n return { accepted: false, reason: err instanceof Error ? err.message : String(err) };\n }\n }\n const result = await this.signal(`update:${runId}:${name}`, arg);\n return { accepted: true, run: result };\n }\n\n private async callRemote<TInput, TOutput>(\n runId: string,\n seq: number,\n step: StepDef<TInput, TOutput>,\n input: TInput,\n queue?: string,\n transport?: string,\n replay?: Map<number, StepCheckpoint>,\n admission?: { priority?: number | undefined; fairnessKey?: string | undefined },\n ): Promise<TOutput> {\n // Read the prefix from the per-execution snapshot (avoids the O(N²) replay SELECTs); a seq absent\n // from the snapshot — not yet dispatched, or written after the snapshot — falls back to the store.\n const existing = replay?.get(seq) ?? (await this.store.getCheckpoint(runId, seq));\n if (existing && existing.name !== step.name) {\n throw new NonDeterminismError(runId, seq, step.name, existing.name);\n }\n if (existing?.status === 'completed') return existing.output as TOutput;\n if (this.pool.size === 0) throw new Error('remote steps require a Transport');\n // A step with a liveness `timeoutMs` keeps the in-memory await + heartbeat path (re-dispatch a\n // presumed-dead worker). Without one, the call SUSPENDS DURABLY: dispatch, persist a `pending`\n // checkpoint, and let the result resume the run on whichever instance receives it — so a worker\n // pod can scale down or crash mid-step without losing the run or re-running completed work.\n if (step.timeoutMs) return this.callRemoteInMemory(runId, seq, step, input, transport);\n if (existing?.status === 'pending') {\n // Dispatched; normally we just keep waiting for the result to resume the run. But a LOST dispatch\n // (worker crashed with no result, or the transport dropped the job) would hang here forever — a\n // reconcile re-drive replays straight back to this guard. Opt-in self-heal: once the step has been\n // pending longer than `remoteRedispatchMs`, re-dispatch the same stepId (the idempotent step\n // re-runs, its result resumes the run), bounded by `remoteRedispatchMax` so a never-settling step\n // fails instead of looping. Unset (default) keeps the by-design \"re-suspend, never re-dispatch\".\n if (this.remoteRedispatchMs == null) throw new WorkflowSuspended();\n // Stamp a redispatch deadline (clock-space, persisted) the first time we see this pending step,\n // stable across replays and crashes — mirrors the failed-retry backoff below. The run's wakeAt\n // becomes this deadline, so a reconcile re-drive lands exactly when it's due to re-dispatch.\n if (existing.wakeAt == null) {\n const wakeAt = this.clock() + this.remoteRedispatchMs;\n await this.store.saveCheckpoint({ ...existing, wakeAt });\n throw new WorkflowSuspended(wakeAt);\n }\n if (this.clock() < existing.wakeAt) throw new WorkflowSuspended(existing.wakeAt);\n // Past the deadline with no result — the dispatch is presumed lost. Re-dispatch (bounded by\n // `remoteRedispatchMax` so a step that never settles fails the run instead of looping forever).\n if (existing.attempts >= this.remoteRedispatchMax) {\n throw new RemoteStepError({\n message: `remote step \"${step.name}\" lost — no result after ${existing.attempts} re-dispatch(es)`,\n code: 'remote_step_lost',\n });\n }\n const reAttempt = existing.attempts + 1;\n const nextDeadline = this.clock() + this.remoteRedispatchMs;\n const reEnqueuedAt = new Date();\n await this.store.saveCheckpoint({\n ...existing,\n attempts: reAttempt,\n wakeAt: nextDeadline,\n enqueuedAt: reEnqueuedAt,\n startedAt: reEnqueuedAt,\n finishedAt: reEnqueuedAt,\n });\n await this.dispatchRemoteTask({\n runId,\n seq,\n name: step.name,\n stepId: existing.stepId ?? stepId(runId, seq),\n group: existing.workerGroup ?? tenantGroup(sanitizeQueueToken(step.name), step.partition),\n input: existing.input,\n priority: admission?.priority,\n attempt: reAttempt,\n transport,\n });\n throw new WorkflowSuspended(nextDeadline);\n }\n\n // Durable retry: a failed attempt re-dispatches up to `retries`, spacing attempts by `backoff` —\n // unless the worker marked the error non-retryable (a deterministic verdict like a declined card).\n // The retry deadline is stamped on the failed checkpoint as `wakeAt` (clock-space, persisted) the\n // first time we see it, so it's stable across replays and survives a crash.\n let attempt = 1;\n if (existing?.status === 'failed') {\n const maxAttempts = Math.max(1, step.retries ?? 1);\n const retryable = existing.error?.retryable !== false;\n if (!retryable || existing.attempts >= maxAttempts) throw new RemoteStepError(existing.error);\n if (existing.wakeAt == null) {\n const wakeAt = this.clock() + backoffDelay(existing.attempts, step);\n await this.store.saveCheckpoint({ ...existing, wakeAt });\n throw new WorkflowSuspended(wakeAt);\n }\n if (this.clock() < existing.wakeAt) throw new WorkflowSuspended(existing.wakeAt);\n attempt = existing.attempts + 1;\n }\n\n const id = stepId(runId, seq);\n // Flow control: a queued call that can't be admitted (concurrency/rate) does NOT dispatch — the\n // run re-suspends with the queue's retry time and the timer poller re-tries admission later, so\n // the limit is durable. The admitted slot is released when the result lands (completeRemoteResult).\n if (queue && this.admission.handles(queue)) {\n // Admission carries the per-call priority + fairness key (default the runId so each run is its\n // own fairness bucket), and the stepId as a STABLE waiter id so the backend tracks one waiter\n // across this call's durable retries. Ordering lives in the backend (in-process by default, or\n // global) — this is the dispatch/admission layer, not the positional replay path.\n const decision = await this.admission.tryAdmit(queue, {\n priority: admission?.priority,\n key: admission?.fairnessKey ?? runId,\n waiterId: id,\n });\n if (!decision.ok) {\n // Remember this run as blocked on `queue` so a freed-slot signal can wake it early.\n const waiters = this.queueWaiters.get(queue) ?? new Set<string>();\n waiters.add(runId);\n this.queueWaiters.set(queue, waiters);\n throw new WorkflowSuspended(decision.retryAt);\n }\n this.queueWaiters.get(queue)?.delete(runId);\n this.stepQueue.set(id, queue);\n }\n\n const enqueuedAt = new Date();\n // Persist the pending checkpoint BEFORE dispatching, so a fast result always finds it to complete.\n await this.store.saveCheckpoint({\n runId,\n seq,\n name: step.name,\n kind: 'remote',\n stepId: id,\n status: 'pending',\n input,\n attempts: attempt,\n workerGroup: tenantGroup(sanitizeQueueToken(step.name), step.partition),\n enqueuedAt,\n startedAt: enqueuedAt, // placeholders until the worker result lands\n finishedAt: enqueuedAt,\n });\n await this.dispatchRemoteTask({\n runId,\n seq,\n name: step.name,\n stepId: id,\n group: tenantGroup(sanitizeQueueToken(step.name), step.partition),\n input,\n priority: admission?.priority,\n attempt,\n transport,\n });\n this.emit({ type: 'step.started', runId, seq, name: step.name, kind: 'remote' });\n throw new WorkflowSuspended();\n }\n\n /** Enqueue a remote step task to its worker group via the transport pool. Shared by the initial\n * dispatch, the opt-in self-heal re-dispatch (see `remoteRedispatchMs`), and the explicit\n * {@link redispatchPending}. Carries the current trace/context so a re-dispatch is traceable. */\n private dispatchRemoteTask(task: {\n runId: string;\n seq: number;\n name: string;\n stepId: string;\n group: string;\n input: unknown;\n attempt: number;\n priority?: number | undefined;\n transport?: string | undefined;\n }): Promise<void> {\n return this.pool.dispatch(\n {\n runId: task.runId,\n seq: task.seq,\n name: task.name,\n stepId: task.stepId,\n group: task.group,\n input: task.input,\n traceparent: this.traceparent?.(),\n context: this.context?.(),\n priority: task.priority,\n attempt: task.attempt,\n },\n task.transport,\n );\n }\n\n /**\n * Complete a durable remote step from its worker result and resume the run — runs on whichever\n * instance receives the result (the dispatching one may be gone), so the run is crash/scale-safe.\n * A no-op if the checkpoint isn't `pending` (a duplicate or late delivery).\n */\n private async completeRemoteResult(result: StepResult): Promise<void> {\n const cp = await this.store.getCheckpoint(result.runId, result.seq);\n if (!cp || cp.status !== 'pending') return;\n // A result settling this step frees its flow-control slot (no-op if it wasn't queued). Done\n // before the cancelled-run early-return below, so a cancellation can't leak the slot. Released\n // fire-and-forget: the slot/notify is best-effort (a global backend self-heals via lease), and\n // not awaiting keeps it off the result-processing critical path (no ordering shift).\n void this.releaseQueueSlot(cp.stepId).catch(() => undefined);\n // Drop a late result for a run that was cancelled/finished meanwhile — don't complete the step\n // or resume (the run is already terminal). This is the engine side of cooperative cancellation.\n const run = await this.store.getRun(result.runId);\n if (run && (run.status === 'cancelled' || run.status === 'completed')) return;\n const finishedAt = new Date();\n const startedAt = result.startedAt ? new Date(result.startedAt) : cp.startedAt;\n await this.store.saveCheckpoint({\n ...cp,\n status: result.status,\n output: result.status === 'completed' ? result.output : cp.output,\n error: result.error,\n events: result.events ?? cp.events,\n startedAt,\n finishedAt,\n });\n this.emit({\n type: result.status === 'completed' ? 'step.completed' : 'step.failed',\n runId: result.runId,\n seq: result.seq,\n name: cp.name,\n kind: cp.kind,\n output: result.output,\n error: result.error,\n queueMs: startedAt.getTime() - cp.enqueuedAt.getTime(),\n durationMs: finishedAt.getTime() - startedAt.getTime(),\n });\n await this.resume(result.runId).catch((err) => {\n if (err instanceof NamespaceMismatch) return null;\n throw err;\n });\n }\n\n /**\n * Apply a remote workflow-turn {@link WorkflowDecision} durably — runs on WHATEVER instance receives\n * it over the broker (the dispatching one may be gone, or a point-to-point broker handed it to a\n * non-dispatcher). The durable, multi-instance-safe twin of {@link completeRemoteResult} for the\n * workflow TURN: look the run up by `decision.runId`, verify the decision matches the run's\n * CURRENTLY-awaited turn (`awaitingDecisionTaskId`) — so a stale / duplicate / foreign / re-driven\n * decision is dropped (applied AT MOST ONCE) — lease it, clear the marker, and apply the decision.\n */\n private async completeRemoteDecision(decision: WorkflowDecision): Promise<void> {\n // Cheap pre-checks before contending for the lease: only the run currently awaiting THIS taskId\n // (and not already terminal) is a candidate. A re-driven turn has a different taskId, so a late\n // decision for the prior turn is dropped here.\n const run = await this.store.getRun(decision.runId);\n if (!run || run.awaitingDecisionTaskId !== decision.taskId) return;\n if (run.status === 'cancelled' || run.status === 'completed' || run.status === 'dead') return;\n if (\n this.namespace !== undefined &&\n run.namespace !== undefined &&\n run.namespace !== this.namespace\n ) {\n return;\n }\n const nowMs = this.clock();\n // Lease so exactly one instance applies it — serialized with a concurrent timer re-drive of the\n // same run. If the lease is held (a re-drive in flight), drop: the re-driven turn produces a fresh\n // decision. The common single-decision path is uncontended, so this acquires immediately.\n if (\n !(await this.store.tryLockRun(decision.runId, this.instanceId, nowMs + this.leaseMs, nowMs))\n ) {\n return;\n }\n const renew = setInterval(\n () => {\n void this.store\n .renewRunLock(decision.runId, this.instanceId, this.clock() + this.leaseMs)\n .catch(() => undefined);\n },\n Math.max(50, Math.floor(this.leaseMs / 2)),\n );\n renew.unref?.();\n try {\n // Re-read under the lease and re-check the marker — it may have changed (a re-drive applied\n // first, or another decision raced in) between the unlocked pre-check and acquiring the lease.\n const fresh = await this.store.getRun(decision.runId);\n if (!fresh || fresh.awaitingDecisionTaskId !== decision.taskId) return;\n if (fresh.status === 'cancelled' || fresh.status === 'completed' || fresh.status === 'dead') {\n return;\n }\n // Clear the awaited-turn marker and the re-drive deadline: this turn is now being applied exactly\n // once. `applyDecision` resets `wakeAt` itself when it suspends on the turn's blocking ops.\n await this.store.updateRun(decision.runId, {\n awaitingDecisionTaskId: undefined,\n wakeAt: undefined,\n updatedAt: new Date(),\n });\n fresh.awaitingDecisionTaskId = undefined;\n await this.applyDecision(fresh, decision);\n } finally {\n clearInterval(renew);\n await this.store.releaseRunLock(decision.runId);\n }\n }\n\n /**\n * A run-scoped heartbeat for a run suspended awaiting a workflow-turn decision (the dispatch path):\n * push its durable re-drive deadline (`wakeAt`) forward so a still-working worker's turn is not\n * re-dispatched. The durable counterpart of an inline turn's in-memory `heartbeatResets` rearm.\n */\n private async rearmDecisionDeadline(runId: string): Promise<void> {\n const silenceMs = this.remoteAdvanceSilenceMs;\n if (silenceMs == null) return;\n const run = await this.store.getRun(runId);\n if (!run || run.status !== 'suspended' || run.awaitingDecisionTaskId === undefined) return;\n await this.store.updateRun(runId, { wakeAt: this.clock() + silenceMs, updatedAt: new Date() });\n }\n\n /**\n * A slot freed on `queue` (a fleet-wide signal): resume this instance's runs blocked on it so they\n * re-contend now instead of at their retry tick. Snapshot-and-clear — a run still blocked after the\n * retry re-registers itself, and one that's gone (cancelled/admitted) is dropped. Best-effort.\n */\n private wakeQueueWaiters(queue: string): void {\n const waiters = this.queueWaiters.get(queue);\n if (!waiters || waiters.size === 0) return;\n const runIds = [...waiters];\n waiters.clear();\n for (const runId of runIds) void this.resume(runId).catch(() => undefined);\n }\n\n /** Release the flow-control slot a dispatched step held (if any), by its stepId. */\n private async releaseQueueSlot(id: string): Promise<void> {\n const queue = this.stepQueue.get(id);\n if (queue === undefined) return;\n this.stepQueue.delete(id);\n await this.admission.release(queue, id);\n }\n\n /** In-memory await path for a remote step with a liveness `timeoutMs` (re-dispatch on timeout). */\n private async callRemoteInMemory<TInput, TOutput>(\n runId: string,\n seq: number,\n step: StepDef<TInput, TOutput>,\n input: TInput,\n transport?: string,\n ): Promise<TOutput> {\n if (this.pool.size === 0) throw new Error('remote steps require a Transport');\n // A bare `@Step()` (no `input`/`output` schemas attached) skips validation.\n const validInput = step.input ? step.input.parse(input) : input;\n const id = stepId(runId, seq);\n const enqueuedAt = new Date();\n this.emit({ type: 'step.started', runId, seq, name: step.name, kind: 'remote' });\n // Retry policy differs from an in-process step on purpose: the internal in-process primitives\n // (`ctx.task`'s dispatch, `ctx.now`/`ctx.sideEffect`) retry any non-fatal throw (the work is in-process),\n // but a dispatched `ctx.step` only re-dispatches on a liveness TIMEOUT (presumed-dead worker). A\n // worker that *reported* an error returned a deterministic verdict, so we surface it to the\n // workflow instead of hammering the worker. Timeout retries need a window to detect death, so\n // they're gated on `timeoutMs` being set.\n const maxAttempts = step.timeoutMs ? Math.max(1, step.retries ?? 1) : 1;\n\n for (let attempt = 1; ; attempt += 1) {\n const resultPromise = new Promise<RemoteResolution>((resolve, reject) => {\n this.pending.set(id, { resolve, reject });\n });\n await this.pool.dispatch(\n {\n runId,\n seq,\n name: step.name,\n stepId: id,\n group: tenantGroup(sanitizeQueueToken(step.name), step.partition),\n input: validInput,\n traceparent: this.traceparent?.(),\n context: this.context?.(),\n attempt,\n },\n transport,\n );\n try {\n const resolution = step.timeoutMs\n ? await this.awaitWithHeartbeat(id, resultPromise, step.timeoutMs)\n : await resultPromise;\n const output = step.output\n ? (step.output.parse(resolution.output) as TOutput)\n : (resolution.output as TOutput);\n // The worker reports when it actually picked the task up; fall back to dispatch time if a\n // transport doesn't carry it (queue-wait then reads as zero rather than going negative).\n const startedAt = resolution.startedAt ? new Date(resolution.startedAt) : enqueuedAt;\n await this.completeStep({\n runId,\n seq,\n name: step.name,\n kind: 'remote',\n input: validInput,\n output,\n events: resolution.events,\n attempts: attempt,\n workerGroup: tenantGroup(sanitizeQueueToken(step.name), step.partition),\n enqueuedAt,\n startedAt,\n });\n return output;\n } catch (err) {\n this.pending.delete(id);\n if (err instanceof RemoteStepTimeout && attempt < maxAttempts) continue;\n throw err;\n }\n }\n }\n\n /**\n * Await `resultPromise`, but reject with `onTimeout()` if neither it settles nor a heartbeat for `id`\n * arrives within `timeoutMs`. Each heartbeat (delivered via `transport.onHeartbeat`, looked up in\n * `heartbeatResets` by `id`) REARMS the window, so a worker that keeps beating stays alive past\n * `timeoutMs`. Shared by the remote-STEP liveness (keyed by stepId) and the remote-WORKFLOW advance\n * liveness (keyed by runId); the caller supplies the timeout error and any extra cleanup via `onTimeout`.\n */\n private awaitWithLivenessDeadline<T>(\n id: string,\n resultPromise: Promise<T>,\n timeoutMs: number,\n onTimeout: () => Error,\n ): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout>;\n const cleanup = () => {\n clearTimeout(timer);\n this.heartbeatResets.delete(id);\n };\n const arm = () => {\n timer = setTimeout(() => {\n cleanup();\n reject(onTimeout());\n }, timeoutMs);\n (timer as { unref?: () => void }).unref?.();\n };\n this.heartbeatResets.set(id, () => {\n clearTimeout(timer);\n arm();\n });\n arm();\n resultPromise.then(\n (value) => {\n cleanup();\n resolve(value);\n },\n (err) => {\n cleanup();\n reject(err);\n },\n );\n });\n }\n\n /** Remote-STEP liveness: await a worker result, timing out (with the step's pending-map cleanup) to\n * `RemoteStepTimeout` if it neither lands nor beats within `timeoutMs`. See {@link awaitWithLivenessDeadline}. */\n private awaitWithHeartbeat(\n id: string,\n resultPromise: Promise<RemoteResolution>,\n timeoutMs: number,\n ): Promise<RemoteResolution> {\n return this.awaitWithLivenessDeadline(id, resultPromise, timeoutMs, () => {\n this.pending.delete(id);\n return new RemoteStepTimeout(id, timeoutMs);\n });\n }\n}\n\n/** Raised inside the workflow when a remote worker reports a step failure. */\nexport class RemoteStepError extends Error {\n readonly stepError?: StepError | undefined;\n constructor(stepError?: StepError) {\n super(stepError?.message ?? 'remote step failed');\n this.name = 'RemoteStepError';\n this.stepError = stepError;\n }\n}\n","import type { z } from 'zod';\nimport type { StandardSchemaV1 } from './standard-schema';\nimport type { StepRef } from './step-name-symbol';\nimport type { WorkflowClass, WorkflowInputOf, WorkflowOutputOf } from './workflow-ref';\n\n/**\n * Core type contracts for nestjs-durable.\n *\n * These are intentionally framework-agnostic: `@dudousxd/nestjs-durable-core` knows only\n * these interfaces, never a concrete transport, store or ORM. Adapters implement them.\n */\n\n// ---------------------------------------------------------------------------\n// Runs & checkpoints — the durable state owned by the orchestrator\n// ---------------------------------------------------------------------------\n\nexport type RunStatus =\n /** Created + enqueued by `start`, not yet picked up — a worker will lease and execute it. */\n | 'pending'\n | 'running'\n | 'suspended'\n /**\n * Compensating cancel in progress: `cancel(runId, { compensate: true })` has been requested and the\n * saga undo is running in the background. NON-TERMINAL — the run is still in-flight (counted by the\n * admission gate, re-driven by recovery if the engine crashes mid-compensation), and flips to\n * `cancelled` once compensation completes. A non-compensating cancel skips this and goes straight to\n * `cancelled`.\n */\n | 'cancelling'\n | 'completed'\n | 'failed'\n | 'cancelled'\n /** Dead-letter: recovery gave up after `maxRecoveryAttempts` (a poison pill). Terminal; inspect it. */\n | 'dead';\n\n/** One execution of a workflow. The unit of durability and the unit shown in the dashboard. */\nexport interface WorkflowRun {\n id: string;\n /** Registered workflow name, e.g. `checkout`. */\n workflow: string;\n /** Code version at start; old runs must resume on the version they began on. */\n workflowVersion: string;\n status: RunStatus;\n /** Serialized workflow input (the args the run was started with). */\n input: unknown;\n /** Serialized workflow output, once `completed`. */\n output?: unknown;\n /** Structured error, once `failed`. */\n error?: StepError | undefined;\n /** When `suspended` on a durable sleep: epoch ms at which the run becomes due to resume. */\n wakeAt?: number | undefined;\n /** Recovery lease owner (engine instance id) while a run is being resumed. */\n lockedBy?: string | undefined;\n /** Recovery lease expiry (epoch ms); another instance may take over once it passes. */\n lockedUntil?: number | undefined;\n /** How many times crash-recovery has picked this run up — caps poison pills (see maxRecoveryAttempts). */\n recoveryAttempts?: number | undefined;\n /** Searchable labels: the workflow's static `@Workflow({ tags })` merged with the run's start-time tags. */\n tags?: string[] | undefined;\n /** Typed, queryable run data (e.g. `{ amount: 200, tier: 'pro' }`) — see {@link RunQuery.attributes}. */\n searchAttributes?: SearchAttributes | undefined;\n /**\n * The worker-pool partition this run belongs to. Stamped at creation from the creating engine's\n * `namespace` (default `'default'`). A worker only picks up / recovers / resumes-timers-for /\n * times-out runs in its own namespace. `undefined` on a run created before this field existed; the\n * store persists it as `'default'`. Read paths (dashboard, `getRun`) are NOT namespace-scoped.\n */\n namespace?: string | undefined;\n /**\n * Dispatch priority for a REMOTE run (one advanced by a {@link WorkflowExecutor} over a broker):\n * carried onto each {@link WorkflowTask} so an urgent child workflow can jump ahead of enqueued\n * lower-priority ones at the worker. Higher wins; absent = unprioritised. Best-effort ordering, not\n * durable state required for correctness — a transport without priority support ignores it.\n */\n priority?: number | undefined;\n /**\n * REMOTE workflow turn awaiting a decision: the `taskId` of the turn the engine dispatched to a\n * workflow worker and then SUSPENDED on. Set by the dispatch-and-suspend path; matched by\n * {@link WorkflowEngine.completeRemoteDecision} so ONLY the decision for the currently-awaited turn\n * is applied (a stale/duplicate/foreign decision is dropped), then cleared the moment it is applied.\n * This is what makes a workflow-turn decision multi-instance safe: any engine instance that receives\n * the decision looks the run up by `decision.runId` and applies it durably, instead of resolving an\n * in-memory promise that only the dispatching instance held. Absent on non-remote / not-awaiting runs.\n */\n awaitingDecisionTaskId?: string | undefined;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * WHAT an event-parked suspended run is waiting on, resolved for display — the engine keeps one\n * generic `suspended` status (it's what drives recovery/timers/queries), but to a human \"waiting on\n * signal `approve`\" reads very differently from \"waiting on webhook `stripe-cb`\". Computed by the\n * store-backed gateway from the run's signal waiters (`listSignalWaiters`, ONE bulk scan), so the\n * dashboard can NAME the wait in a list row without fetching each run's timeline. `on` is derived from\n * the waiter token's prefix (see `classifyWaiterToken`): `wh:<runId>:<seq>` ⇒ `webhook`, `child:<id>`\n * ⇒ `child`, `bp:<runId>:<seq>` ⇒ `breakpoint` (a `ctx.breakpoint` DOES register a signal waiter —\n * same machinery, `engine.continue` resumes it — so it's classified here, not left to fall through to\n * the generic `signal` case with the raw token as its ugly display name), `event:<name>:…` ⇒ `signal`\n * (name decoded), anything else ⇒ `signal` (the token IS the signal name).\n *\n * Deliberately EVENT-only (no timer/step): `wakeAt` alone can't tell a real `ctx.sleep` from the\n * reconcile-fallback `wakeAt` an event/step suspend now carries, and the store exposes no cheap bulk\n * checkpoint scan to disambiguate — so the client shows a non-event suspend with a live worker as\n * `running` (it flips off \"no worker\" the moment a worker returns) rather than guessing \"sleeping\".\n * The detail view (which has the timeline) still distinguishes sleep vs in-flight step precisely.\n */\nexport interface RunWaiting {\n on: 'signal' | 'webhook' | 'child' | 'breakpoint';\n /**\n * The token/name the run is parked on — the signal name, webhook token, or awaited child id. For a\n * breakpoint this is always the literal `'breakpoint'`: the real label (if any) lives on the pending\n * `breakpoint`/`breakpoint:<label>` checkpoint, which the detail view's timeline already shows —\n * naming it here would need an extra per-run checkpoint read, defeating the bulk waiter scan.\n */\n name: string;\n}\n\nexport type StepKind = 'local' | 'remote' | 'sleep' | 'signal';\n\n/**\n * The recorded result of a single step at a deterministic logical position (`seq`).\n * On replay, a `completed` checkpoint means the step is NOT re-executed — its `output` is\n * returned. A non-terminal checkpoint (`pending`/`running`) does not short-circuit: the step is\n * re-awaited (remote) or re-run (local).\n */\nexport interface StepCheckpoint {\n runId: string;\n /** Deterministic logical position of the step within the run. */\n seq: number;\n /** Registered step name (matches the remote handler name for remote steps). */\n name: string;\n kind: StepKind;\n /** Stable id passed to remote workers so they can dedupe a re-delivered task. */\n stepId: string;\n /**\n * `pending` = a remote step dispatched and awaiting its worker result (the run is durably\n * suspended, not held in memory); it becomes `completed`/`failed` when the result arrives.\n * `running` = a local step whose body is executing in-process right now (see `trackStepStart`);\n * it's overwritten by `completed`/`failed` when the body settles, and on a crash mid-body it\n * simply re-runs on replay (only `completed` short-circuits).\n */\n status: 'pending' | 'running' | 'completed' | 'failed';\n /** What the step was called with — the `ctx.step` (dispatched) args for a remote step (a local step has none). */\n input?: unknown;\n output?: unknown;\n error?: StepError | undefined;\n attempts: number;\n /** For remote steps: which worker group ran it. */\n workerGroup?: string | undefined;\n /** Structured events/logs the step emitted (sub-step outcomes, debug/error lines). */\n events?: StepEvent[] | undefined;\n /** For sleep steps: epoch ms the sleep elapses at. */\n wakeAt?: number | undefined;\n /**\n * Set on the running placeholder checkpoints of the children dispatched by one `ctx.all` call —\n * a shared tag (`all:<firstSeq>`) grouping the N siblings so the dashboard can render them as one\n * parallel fan-out. Optional and additive: absent on every non-`all` checkpoint. Mirrors the\n * Python SDK's `parallelGroup`.\n */\n parallelGroup?: string | undefined;\n /**\n * When the step entered the system: for a remote step, when the engine dispatched it to the\n * transport; for a local step, when it began. Queue-wait time = `startedAt − enqueuedAt`.\n */\n enqueuedAt: Date;\n /** When processing actually began: worker pickup for a remote step, execution start for a local one. */\n startedAt: Date;\n finishedAt: Date;\n}\n\n/**\n * A structured event a step (or its worker) emits while running — a log line and/or a sub-step\n * outcome. The dashboard renders these under the step, so you can see what happened inside a step\n * that the workflow treats as one unit (e.g. which of N parallel sub-processes ok/failed/skipped).\n */\nexport interface StepEvent {\n /** Epoch ms. */\n at: number;\n level: 'debug' | 'info' | 'warn' | 'error';\n message: string;\n /** Stable run identity for a sub-process. Distinct invocations of the same `name` carry distinct\n * ids, so their phases and log trails never collapse into one. Absent on events emitted by the\n * legacy `sub()` path, which keys by `name` instead. */\n subId?: string;\n /** For a sub-step/sub-process within the step: its name. */\n name?: string;\n /** Open, consumer-defined grouping label for a sub-process (e.g. a handler/lane). The dashboard\n * groups rows by it. The library never interprets it. */\n group?: string;\n /** For a sub-step: its terminal outcome (closed enum — drives colour + aggregation). */\n status?: 'ok' | 'failed' | 'skipped';\n /** Open, consumer-defined intermediate phase label for a sub-process transition. Carries no\n * terminal `status`; the library timestamps and orders it but never interprets it. */\n phase?: string;\n /** For a log line emitted *inside* a sub-process: that owning sub-process's name, so the dashboard\n * can group a step's log trail under each sub-process instead of one flat list. Set on logs (no\n * `status`); a worker stamps it from the sub-process it's running.\n * @deprecated Superseded by `subId` for run-distinct grouping; kept so existing workers/runs render. */\n process?: string;\n /** Optional structured payload. `data.durationMs` (number) overrides the derived duration. */\n data?: unknown;\n}\n\n/**\n * Handed to a local step's body (`ctx.step(name, (log) => …)`) so it can record what happened\n * inside the step — debug/info/warn/error lines and per-sub-process outcomes. The events are\n * checkpointed with the step and rendered under it in the dashboard. The remote/cross-language\n * counterpart is the worker attaching the same `StepEvent[]` to its `StepResult` (see the Python\n * SDK's `StepContext`), so observability is symmetric regardless of where the step ran.\n */\nexport interface StepLogger {\n debug(message: string, data?: unknown): void;\n info(message: string, data?: unknown): void;\n warn(message: string, data?: unknown): void;\n error(message: string, data?: unknown): void;\n /** Record a sub-step / sub-process outcome (e.g. one of N parallel p-processes). */\n sub(name: string, status: 'ok' | 'failed' | 'skipped', message?: string, data?: unknown): void;\n /** Record a sub-process event. Typically pass `phase` for an intermediate transition (carrying no\n * terminal status), or `status` for the terminal outcome — the type permits either; the engine\n * interprets which is set. `id` is the run identity (distinct per invocation); `group` is an\n * open grouping label. */\n subEvent(e: {\n id: string;\n name: string;\n group?: string | undefined;\n phase?: string | undefined;\n status?: 'ok' | 'failed' | 'skipped' | undefined;\n message?: string | undefined;\n data?: unknown;\n }): void;\n /**\n * Ergonomic sub-process lifecycle: run `body`, timing it, and record a terminal `ok` with the\n * measured `durationMs` on success — or `failed` (with the error message) if it throws, then\n * re-throw. `sp.phase(label)` records an intermediate transition; `sp.skip(reason)` a terminal\n * `skipped`. Logs emitted inside `body` are tagged to this sub-process so the dashboard groups\n * them under it. Returns whatever `body` returns. The TS twin of the Python SDK's `sub_process`.\n *\n * ```ts\n * const rows = await log.subProcess('fetch-data', async () => readEverything());\n * await log.subProcess('export-file', () => upload(rows));\n * ```\n */\n subProcess<T>(\n name: string,\n body: (sp: SubProcessHandle) => Promise<T> | T,\n opts?: { group?: string; id?: string },\n ): Promise<T>;\n}\n\n/** The handle a {@link StepLogger.subProcess} body receives to mark phases / a non-`ok` outcome. */\nexport interface SubProcessHandle {\n /** Record an intermediate phase transition (a consumer-defined label, no terminal status). */\n phase(phase: string, data?: unknown): SubProcessHandle;\n /** Record a terminal `skipped` outcome (e.g. nothing to do / validation failed). */\n skip(reason?: string, data?: unknown): void;\n /** Record a terminal `failed` outcome explicitly (the wrapper also does this if the body throws). */\n fail(reason?: string, data?: unknown): void;\n}\n\nexport interface StepError {\n message: string;\n /** Optional machine-readable code, e.g. `declined`, `timeout`. */\n code?: string | undefined;\n /** Whether the engine should treat this as retryable. */\n retryable?: boolean | undefined;\n stack?: string | undefined;\n}\n\n// ---------------------------------------------------------------------------\n// StateStore — where runs and checkpoints live (Postgres / MySQL / SQLite via ORM adapters)\n// ---------------------------------------------------------------------------\n\nexport interface StateStore {\n /**\n * Provision the tables/collections this store needs, idempotently. Called on boot when the\n * module's `autoSchema` is on. Optional: stores that need no setup (in-memory) omit it.\n */\n ensureSchema?(): Promise<void>;\n\n createRun(run: WorkflowRun): Promise<void>;\n updateRun(runId: string, patch: Partial<WorkflowRun>): Promise<void>;\n getRun(runId: string): Promise<WorkflowRun | null>;\n\n /**\n * Hard-delete a run and all of its rows — the run plus its checkpoints, signal waiters, and\n * normalized search-attribute rows. Unlike a cancelled run (which stays as terminal history), a\n * deleted run is GONE: it no longer appears in {@link getRun} or {@link listRuns}. This removes\n * exactly the one run — the engine's {@link WorkflowEngine.deleteRun} handles the child cascade.\n * No-op if the run doesn't exist. (Token-keyed buffered signals are transient and left alone.)\n */\n deleteRun(runId: string): Promise<void>;\n\n /**\n * Hard-delete up to `limit` terminal runs that fall OUTSIDE `policy` (oldest / over the count cap\n * first), cascading to their child rows exactly like {@link deleteRun}. Returns how many runs were\n * deleted — call again while it returns `limit` to drain a large backlog in bounded batches.\n *\n * Optional: only adapters that implement a bulk prune provide it; the retention poller no-ops with a\n * warning when the configured store omits it. See {@link RetentionPolicy} for the keep/prune rule.\n */\n pruneTerminalRuns?(policy: RetentionPolicy, nowMs: number, limit: number): Promise<number>;\n\n getCheckpoint(runId: string, seq: number): Promise<StepCheckpoint | null>;\n /**\n * Persist a checkpoint and advance the run atomically. Durable semantics depend on this\n * being a single transaction; stores without transactions cannot give the strong guarantee.\n */\n saveCheckpoint(checkpoint: StepCheckpoint): Promise<void>;\n\n /** Used by recovery on boot to find runs to resume (crashed, left `running`). */\n listIncompleteRuns(namespace?: string): Promise<WorkflowRun[]>;\n\n /** The oldest `pending` runs awaiting dispatch (FIFO, by `createdAt`), capped at `limit`. */\n listPendingRuns(limit: number, namespace?: string): Promise<WorkflowRun[]>;\n\n /** Suspended runs whose durable timer is due (`wakeAt <= nowMs`), ready to resume. */\n listDueTimers(nowMs: number, namespace?: string): Promise<WorkflowRun[]>;\n\n /**\n * Atomically acquire the recovery lease on a run for `owner` until `leaseUntilMs`, but only if\n * it is currently unlocked or its lease has expired (`<= nowMs`). Returns whether it was\n * acquired — so concurrent engine instances never recover the same run twice.\n */\n tryLockRun(runId: string, owner: string, leaseUntilMs: number, nowMs: number): Promise<boolean>;\n\n /** Release a run's recovery lease so another instance can pick it up (e.g. once it suspends). */\n releaseRunLock(runId: string): Promise<void>;\n\n /**\n * Extend a run's lease to `leaseUntilMs`, but ONLY if `owner` still holds it — so a live worker\n * heartbeating its long run keeps the lease, while a dead worker's lease still expires and gets\n * reclaimed. Returns false if the lease was lost (taken over or released).\n */\n renewRunLock(runId: string, owner: string, leaseUntilMs: number): Promise<boolean>;\n\n /** Record that a run is suspended waiting for an external signal `token`. */\n putSignalWaiter(waiter: SignalWaiter): Promise<void>;\n /** Atomically take (and remove) the run waiting on `token`, if any. */\n takeSignalWaiter(token: string): Promise<SignalWaiter | null>;\n /** List waiters whose `token` starts with `prefix` — used to fan out an event to its subscribers. */\n listSignalWaiters(prefix: string): Promise<SignalWaiter[]>;\n\n /**\n * Delete the EXACT waiter row — `token` AND `runId` AND `seq` must all match — no-op if absent.\n * Unlike {@link takeSignalWaiter}, which deletes ANY row for `token` (fine when the caller just won\n * the race to consume it), this is for a caller removing its OWN registration after resolving the\n * wait some other way (a buffered hit, a timeout): blind `takeSignalWaiter(token)` there could steal\n * a DIFFERENT run's waiter that has since claimed the same token (`token` is the store's primary key,\n * so a later `putSignalWaiter` for the same token replaces the row). The exact-match variant only\n * ever removes the row this caller itself put there.\n */\n removeSignalWaiter(waiter: SignalWaiter): Promise<void>;\n\n /**\n * Buffer a signal whose waiter hasn't arrived yet, so the next `waitForSignal(token)` consumes it\n * instead of it being lost (FIFO per token). Makes signals reliable regardless of timing and\n * powers `signalWithStart`.\n */\n bufferSignal(token: string, payload: unknown): Promise<void>;\n /** Take the oldest buffered signal for `token` (FIFO), or null if none is buffered. */\n takeBufferedSignal(token: string): Promise<{ payload: unknown } | null>;\n\n /**\n * Buffer a published event that matched NO live waiter, so a LATER `ctx.waitForEvent(name, { match })`\n * still consumes it instead of it being silently dropped — the events analog of {@link bufferSignal}'s\n * reliability contract for signals, but MATCH-based rather than token-based: an event's buffer is keyed\n * by `name` alone (many waiters can share a name with different `match` criteria), so consumption is\n * list ({@link listBufferedEvents}) + evaluate the WAITER's own match predicate + claim\n * ({@link removeBufferedEvent}) — never a blind take, because the store has no way to know which\n * candidate a given waiter wants. `input.id` is minted by the caller (engine.publishEvent) so\n * {@link removeBufferedEvent} can later target this exact row.\n */\n bufferEvent(input: {\n name: string;\n payload: unknown;\n id: string;\n publishedAt: number;\n }): Promise<void>;\n /**\n * Buffered events for `name`, OLDEST (`publishedAt`) first, capped at `limit`. A waiter scans these,\n * evaluates its own `eventMatches(payload, match)` locally, and claims the one it wants via\n * {@link removeBufferedEvent} — the match predicate belongs to the WAITER, never the store.\n */\n listBufferedEvents(\n name: string,\n limit: number,\n ): Promise<Array<{ id: string; payload: unknown; publishedAt: number }>>;\n /**\n * Atomically delete the buffered event `id`. Returns `true` iff a row was actually deleted, `false`\n * if it was already gone (claimed by a concurrent waiter, reclaimed by `engine.publishEvent`'s own\n * late re-check, or pruned as expired) — the arbiter under concurrency: whichever caller's delete\n * returns `true` is the one that gets to deliver the payload; every other caller backs off.\n */\n removeBufferedEvent(id: string): Promise<boolean>;\n\n /**\n * Run `work` in a SINGLE store transaction — giving it the store-native transaction handle (`raw`)\n * for the caller's own DB writes plus a `saveCheckpoint` that commits IN THE SAME transaction, so a\n * business write and the step's \"done\" checkpoint are atomic (exactly-once). Optional — only the SQL\n * adapters implement it; `ctx.transaction` errors on a store without it.\n */\n transaction?<T>(work: (tx: StoreTransaction) => Promise<T>): Promise<T>;\n\n // Dashboard queries\n listRuns(query: RunQuery): Promise<WorkflowRun[]>;\n listCheckpoints(runId: string): Promise<StepCheckpoint[]>;\n\n /**\n * The LATEST checkpoint for `runId` whose `name` equals `name` exactly (highest `seq` wins), or\n * `undefined` if none. A targeted read that avoids fetching + deserializing every checkpoint just to\n * keep one match — the store does the filter (`WHERE name = … ORDER BY seq DESC LIMIT 1`). Preserves\n * the \"last in seq order wins\" semantics the engine relies on for `getEvent` (a re-published key\n * overwrites the prior value at a higher seq, so the highest-seq match is the current value).\n *\n * Optional: a store that omits it still works — the engine falls back to {@link listCheckpoints}\n * plus an in-JS filter that produces the identical result.\n */\n getLatestCheckpointByName?(runId: string, name: string): Promise<StepCheckpoint | undefined>;\n\n /**\n * All checkpoints for `runId` whose `name` starts with ANY of `prefixes`, ordered by `seq` ascending\n * (same order as {@link listCheckpoints}). A targeted read that avoids scanning every checkpoint just\n * to keep the prefix matches — the store does the filter (`WHERE name LIKE 'prefix%' …`). Used by the\n * run-tree to find a parent's child edges (`signal:child:` / `spawn:` checkpoints) without loading the\n * whole history. An empty `prefixes` array matches nothing.\n *\n * Optional: a store that omits it still works — the engine falls back to {@link listCheckpoints}\n * plus an in-JS prefix scan that produces the identical result.\n */\n listCheckpointsByNamePrefix?(runId: string, prefixes: string[]): Promise<StepCheckpoint[]>;\n}\n\n/** The terminal run statuses — a run in one of these is finished and will never change on its own.\n * Only these are eligible for retention pruning (a {@link RetentionPolicy} targeting a non-terminal\n * status would race the engine and delete live work). */\nexport const TERMINAL_RUN_STATUSES: readonly RunStatus[] = [\n 'completed',\n 'failed',\n 'cancelled',\n 'dead',\n];\n\n/**\n * One retention rule for hard-pruning terminal run history. Within `statuses` (terminal only), a run\n * is KEPT only if it satisfies EVERY bound you set, and pruned the moment it violates any:\n * - `maxAge` — prune runs whose `updatedAt` (≈ the time they reached terminal) is older than\n * `now - maxAge`. A number is milliseconds; a string is an `ms`-style duration parsed by\n * {@link parseDuration} (`'7d'`, `'2w'`, `'90m'` — note `'m'` is MINUTES; use `'30d'` for a month).\n * - `maxCount` — keep only the `maxCount` most-recent (by `updatedAt`) runs in the status set; prune\n * everything past that.\n *\n * Set one or both (both = the most-restrictive wins: capped at `maxCount` rows AND nothing older than\n * `maxAge`). Statuses not named by any policy are never pruned.\n */\nexport interface RetentionPolicy {\n statuses: RunStatus[];\n maxAge?: number | string;\n maxCount?: number;\n}\n\n/** Typed, queryable per-run data — exact values for `eq`/`ne`, numbers/strings for range ops. */\nexport type SearchAttributes = Record<string, string | number | boolean>;\n\n/**\n * A Standard Schema (https://standardschema.dev — implemented by zod 3.24+, valibot, arktype, …)\n * whose validated OUTPUT is search-attribute-shaped: flat `string`/`number`/`boolean` values only.\n * Declared via `@Workflow({ searchAttributes })`, this makes `ctx.upsertSearchAttributes` reject any\n * write whose merged result doesn't conform. The `Output extends SearchAttributes` bound is enforced\n * structurally at the declaration site — a schema whose inferred output has a nested object/array\n * value (e.g. `z.object({ meta: z.object({ ... }) })`) fails to satisfy this type, so it's a\n * compile-time error to declare it as a `searchAttributes` schema, not a runtime surprise.\n *\n * @example\n * ```ts\n * import { z } from 'zod';\n *\n * const orderAttrs = z.object({\n * tier: z.enum(['free', 'pro']),\n * amount: z.number(),\n * rushOrder: z.boolean().optional(),\n * });\n *\n * @Workflow({ name: 'checkout', searchAttributes: orderAttrs })\n * class CheckoutWorkflow {\n * async run(ctx: WorkflowCtx<InferSearchAttributes<typeof orderAttrs>>, input: CheckoutInput) {\n * await ctx.upsertSearchAttributes({ tier: input.tier, amount: input.total });\n * }\n * }\n * ```\n */\nexport type SearchAttributesSchema<A extends SearchAttributes = SearchAttributes> =\n StandardSchemaV1<unknown, A>;\n\n/** Infer the validated OUTPUT shape of a {@link SearchAttributesSchema} — the typed attributes a\n * workflow declares via `@Workflow({ searchAttributes })`. Feed it straight into `WorkflowCtx<A>`:\n * `WorkflowCtx<InferSearchAttributes<typeof mySchema>>`. */\nexport type InferSearchAttributes<S extends StandardSchemaV1<unknown, SearchAttributes>> =\n StandardSchemaV1.InferOutput<S>;\n\nexport type AttributeOp = 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte';\n\n/** One predicate over a run's {@link SearchAttributes}; a {@link RunQuery} ANDs them all. */\nexport interface AttributeFilter {\n key: string;\n op: AttributeOp;\n value: string | number | boolean;\n}\n\nexport interface RunQuery {\n workflow?: string | undefined;\n status?: RunStatus | undefined;\n /**\n * Match any of these statuses (a `status IN (...)` filter). ORed together, and ANDed with the other\n * predicates. Use this instead of issuing one {@link listRuns} call per status — e.g. the singleton\n * admission gate counts `running` + `suspended` in-flight runs in a single scan. If both `status` and\n * `statuses` are set, both must hold (the single `status` further narrows the set). Empty array =\n * matches nothing.\n */\n statuses?: RunStatus[] | undefined;\n /** Only runs carrying this tag (exact match against {@link WorkflowRun.tags}). */\n tag?: string | undefined;\n /**\n * Typed/range predicates over {@link WorkflowRun.searchAttributes}, ANDed together (e.g. `amount`\n * >= 200 and `tier` = 'pro'). Applied in-process after the coarse filters, so pair with\n * `workflow`/`status`/`tag` to bound the scan on large stores.\n */\n attributes?: AttributeFilter[] | undefined;\n /** Restrict to runs in this namespace (exact match), ANDed with the other predicates. */\n namespace?: string | undefined;\n limit?: number | undefined;\n offset?: number | undefined;\n}\n\n/** The transaction handle `StateStore.transaction` hands to its work callback. */\nexport interface StoreTransaction {\n /** The store-native transaction handle (TypeORM `EntityManager`, Prisma tx client, MikroORM `EntityManager`,\n * Drizzle tx) — do your business DB writes on THIS so they commit atomically with the checkpoint. */\n readonly raw: unknown;\n /** Persist the step checkpoint inside this transaction. */\n saveCheckpoint(checkpoint: StepCheckpoint): Promise<void>;\n}\n\n/** Binds an external signal `token` to the suspended run/step position waiting for it. */\nexport interface SignalWaiter {\n token: string;\n runId: string;\n seq: number;\n /**\n * The parallel-fan group this waiter belongs to, carried from the awaiting command so the resolving\n * `signal:<token>` checkpoint (notably `signal:child:<id>` for an awaited child run) can be tagged\n * with it. A worker's `ctx.gather_children`/`ctx.all` fan-out stamps every `startChild` with the same\n * group; without threading it through the waiter, the child-await checkpoint comes out untagged and the\n * dashboard renders the fan as a sequential chain instead of one parallel group. Undefined for an\n * ordinary (non-fan) signal/child await.\n */\n parallelGroup?: string | undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Transport — how a remote task travels to a worker and the result returns\n// ---------------------------------------------------------------------------\n\n/**\n * A DB-less tenant worker → control plane request to start a run. Published by a worker that has\n * no direct DB access (the hosted-control-plane tenant model) onto the\n * `<effectivePrefix>-start-run` queue; the control plane consumes it and turns it into a durable\n * run (P4 of the tenants plan).\n *\n * The `tenant` identifies the namespace that owns the run (maps to the engine's `namespace`); it\n * is separate from the wire-level key prefix so a single transport can serve multiple tenants.\n */\nexport interface StartRunMessage {\n tenant: string;\n /** Registered workflow name. */\n workflow: string;\n input: unknown;\n /** Optional caller-supplied run id (idempotency key). The engine generates one if absent. */\n runId?: string | undefined;\n /** Tags to stamp on the run (merged with the workflow's static @Workflow tags). */\n tags?: string[] | undefined;\n /** Typed, queryable run data to stamp on the run (same as {@link StartOptions.searchAttributes}). */\n searchAttributes?: SearchAttributes | undefined;\n}\n\n/**\n * A tenant worker → control plane read/control request over the shared transport. Enqueued on\n * `<effectivePrefix>-run-request`; the control plane's `onRunRequest` consumer answers it, scoped to\n * `tenant`, and publishes a {@link RunReply} on `<effectivePrefix>-run-reply` correlated by `requestId`.\n */\nexport interface RunRequest {\n /** Correlation id minted by the tenant; the matching {@link RunReply} carries it back. */\n requestId: string;\n /** The requesting tenant — the operator scopes the run's namespace to this. */\n tenant: string;\n body: RunRequestKind;\n}\n\n/** The discriminated verb + args of a {@link RunRequest}. Mirrors the tenant-facing `RunGateway`. */\nexport type RunRequestKind =\n | { kind: 'getRunDetail'; runId: string }\n | { kind: 'listRuns'; query: RunQuery }\n // Per-group worker health — the operator answers it scoped to the requester's own groups (see\n // `RunRequestResponder`), so a tenant's Workers panel shows ITS queues, never another tenant's.\n | { kind: 'workerHealth' }\n | { kind: 'cancel'; runId: string; opts?: { compensate?: boolean } }\n | { kind: 'retry'; runId: string }\n | { kind: 'continue'; runId: string }\n | { kind: 'retryWithInput'; runId: string; input: unknown }\n | { kind: 'redispatch'; runId: string }\n // Bulk, not runId-bearing (like `listRuns`/`workerHealth`) — the operator answers it in one shot\n // and filters the result to runs the requester's tenant actually owns (see `RunRequestResponder`).\n | { kind: 'waitingFor'; runIds: string[] };\n\n/** The control plane's answer to a {@link RunRequest}, correlated by `requestId`. */\nexport interface RunReply {\n requestId: string;\n result: RunReplyResult;\n}\n\n/** Success carries the verb's payload (JSON-serialised); failure carries a re-throwable error. */\nexport type RunReplyResult =\n | { ok: true; data: unknown }\n | { ok: false; error: { message: string; code?: string } };\n\n/** A lifecycle event re-published to a single tenant's channel (`<effectivePrefix>-tenant-events-<tenant>`)\n * so a store-less tenant can live-tail ITS OWN runs. Scoped by the run's namespace at publish time. */\nexport interface TenantEvent {\n tenant: string;\n event: EngineEvent;\n}\n\n/** A unit of work dispatched to a remote worker. This is the documented wire payload. */\nexport interface RemoteTask {\n runId: string;\n seq: number;\n /** Handler name the worker registered, e.g. `payments.charge-card`. */\n name: string;\n stepId: string;\n /** Worker group expected to handle this task. */\n group: string;\n input: unknown;\n /** W3C traceparent so the worker can continue the distributed trace. */\n traceparent?: string | undefined;\n /**\n * Opaque context carrier (tenant / user / correlation ids) the worker re-exposes to the step\n * handler, for cross-process propagation alongside the {@link traceparent}. The engine treats it\n * as a pass-through object and never inspects its shape — the producer (e.g. `@dudousxd/nestjs-context`)\n * owns the keys. Absent when no `context` provider is configured.\n */\n context?: Record<string, unknown> | undefined;\n /**\n * Id of the transport this task was dispatched on (when the engine runs a pool — see\n * {@link NamedTransport}). A worker that consumes several transports replies via the matching one,\n * so failover is symmetric without the worker choosing a transport. Absent for a single transport.\n */\n transport?: string | undefined;\n /**\n * Admission priority carried through to the broker (BullMQ job `priority`) so a transport that\n * supports priority ordering lets an urgent task jump ahead of already-enqueued lower-priority\n * ones at the worker. Mirrors the per-call `priority` from `ctx.step(..., { priority })`. Higher\n * wins; absent means default/unprioritised. Transports without priority support ignore it.\n */\n priority?: number | undefined;\n attempt: number;\n}\n\nexport interface StepResult {\n runId: string;\n seq: number;\n stepId: string;\n status: 'completed' | 'failed';\n output?: unknown;\n error?: StepError | undefined;\n /** Epoch ms when the worker began processing — lets the engine report queue-wait time. */\n startedAt?: number | undefined;\n /** Structured events the worker emitted while running the step (sub-step outcomes, logs). */\n events?: StepEvent[] | undefined;\n}\n\nexport interface Heartbeat {\n runId: string;\n seq: number;\n /**\n * The in-flight step this beat keeps alive. ABSENT for a RUN-scoped (workflow-turn) heartbeat: a\n * worker replaying a long workflow turn beats for its `runId` so the engine rearms the run's\n * `advance` deadline (see `WorkflowEngineDeps.remoteAdvanceSilenceMs`). The engine then keys the\n * liveness reset by `runId` instead of `stepId`.\n */\n stepId?: string | undefined;\n group: string;\n}\n\n// ---------------------------------------------------------------------------\n// Polyglot workflows — the workflow-task / commands protocol\n//\n// A workflow authored in a non-TS SDK (e.g. Python) runs coordinator-driven: the engine stays the\n// sole owner of the durable state + recovery/timers and advances the run one TURN at a time by\n// dispatching a {@link WorkflowTask} (the run's history) to a workflow worker, which REPLAYS the\n// function locally and returns a {@link WorkflowDecision} (the commands it produced). The engine\n// applies the decision (persist checkpoints, dispatch steps, schedule timers, settle the run). The\n// worker never touches the store. See docs/plans/2026-06-15-polyglot-workflows-protocol.md.\n// ---------------------------------------------------------------------------\n\n/** engine → workflow worker: advance this run one turn by replaying the function against `history`. */\nexport interface WorkflowTask {\n /** Dedupe id for this turn (a re-delivered task must be idempotent). */\n taskId: string;\n runId: string;\n /** Registered workflow name + the version the run started on — replay must use that version. */\n workflow: string;\n workflowVersion: string;\n input: unknown;\n /** Completed durable ops so far, ordered by seq — what the worker replays its results from. */\n history: HistoryEvent[];\n /** Signals delivered to the run but not yet consumed, so `wait_signal` resolves on replay. */\n pendingSignals?: Array<{ seq: number; signal: string; payload: unknown }>;\n group: string;\n /** Id of the transport this task was dispatched on (pool failover) — see {@link NamedTransport}. */\n transport?: string;\n traceparent?: string;\n /**\n * Admission priority carried to the broker (BullMQ job `priority`) so an urgent child workflow can\n * jump ahead of already-enqueued lower-priority ones at the worker. Higher wins; absent means\n * default/unprioritised. Transports without priority support ignore it.\n */\n priority?: number | undefined;\n attempt: number;\n}\n\n/** One resolved durable op in a run's history — a superset of a completed {@link StepCheckpoint}. */\nexport interface HistoryEvent {\n seq: number;\n kind: 'step' | 'call' | 'timer' | 'signal' | 'child';\n name?: string | undefined;\n /** Resolved value: a step/call output, a child run's output, a signal payload. */\n output?: unknown;\n /** Set when the op resolved to a failure (e.g. a failed remote step the workflow may catch). */\n error?: StepError | undefined;\n}\n\n/** A decision the workflow function produced at a `seq` that was not yet in history. */\nexport type WorkflowCommand =\n /** `ctx.step(handlerOrName, input)` — dispatch a step (by typed handler reference or by name) and\n * await it. A worker's `ctx.gather_calls([...])` fan-out tags every dispatched call with the same\n * `parallelGroup` so the dashboard renders the dispatched steps as one parallel fan (parity with\n * the gathered `recordStep` / `startChild` tags). Undefined for a lone sequential `ctx.step`. */\n | {\n kind: 'call';\n seq: number;\n name: string;\n group: string;\n input: unknown;\n parallelGroup?: string;\n }\n /** `ctx.step(name, body)` — a LOCAL step the worker already ran this turn; the engine persists its\n * result so replay returns it instead of re-running (durability for side-effectful work).\n * `startedAt`/`finishedAt` (epoch ms) carry the step's real wall-clock window so the dashboard\n * shows a true duration instead of 0ms, and `events` carry the sub-process/log trail the step\n * emitted (so each handler's p-processes show under it). All optional for back-compat. */\n | {\n kind: 'recordStep';\n seq: number;\n name: string;\n output?: unknown;\n error?: StepError;\n startedAt?: number;\n finishedAt?: number;\n events?: StepEvent[];\n /** A worker's `ctx.gather([...])` tags every step in the parallel fan with the same group, so the\n * engine carries it onto the checkpoint and the dashboard renders the fan as one group. */\n parallelGroup?: string;\n }\n /** `ctx.sleep(ms)` — a durable timer of `ms` duration. The engine computes the absolute deadline\n * (now + ms) when it applies the command, so the worker never reads the clock (determinism). */\n | { kind: 'sleep'; seq: number; ms: number }\n /** `ctx.wait_signal(name)` — block until a signal `name` is delivered to the run. */\n | { kind: 'waitSignal'; seq: number; signal: string }\n /** `ctx.start_child(workflow, input)` — start a child run with its own lifecycle. A worker's\n * `ctx.all([...])` fan-out tags every dispatched child with the same `parallelGroup` so the\n * dashboard can render the fan as one group (parity with the gathered `recordStep` tag). */\n | {\n kind: 'startChild';\n seq: number;\n workflow: string;\n input: unknown;\n parallelGroup?: string;\n };\n\n/** workflow worker → engine: the result of replaying one turn of a remote workflow. */\nexport interface WorkflowDecision {\n taskId: string;\n runId: string;\n /** `continue` = produced `commands` and is blocked on an await; otherwise the run settles.\n * `cancelled` = the worker bailed at an op boundary because the run was cancelled mid-turn. */\n status: 'continue' | 'completed' | 'failed' | 'cancelled';\n /** New durable ops the replay produced this turn (status === 'continue'), ordered by seq. */\n commands: WorkflowCommand[];\n /** Final workflow output (status === 'completed'). */\n output?: unknown;\n /** Terminal error (status === 'failed'). */\n error?: StepError;\n}\n\n/**\n * workflow worker → engine: a LOCAL step's lifecycle, streamed AS IT HAPPENS (not batched into the\n * turn's final {@link WorkflowDecision}). A Python `@workflow` runs its `ctx.step`s inline over one\n * turn that can last minutes; without this the engine learns of the steps only when the turn ends,\n * so the dashboard shows nothing mid-run. The worker emits `running` when a step's body starts and\n * `completed`/`failed` when it settles; the engine checkpoints each immediately, so a step appears\n * in-flight and then resolves live. The turn's final `recordStep` command re-persists the same\n * checkpoint idempotently (replay history), so this is purely additive observability.\n */\nexport interface WorkflowStepEvent {\n runId: string;\n seq: number;\n name: string;\n phase: 'running' | 'completed' | 'failed';\n /** Epoch ms the step body began (all phases) and settled (`completed`/`failed`). */\n startedAt: number;\n finishedAt?: number;\n /** The replayed result / failure for the settled phases. */\n output?: unknown;\n error?: StepError;\n /** Sub-process + log trail the step emitted so far (the handler's p-processes). */\n events?: StepEvent[];\n /** A worker's `ctx.gather([...])` fan tags every step's lifecycle with the same group so the\n * dashboard renders the live fan-out as one group (parity with the `recordStep` tag). */\n parallelGroup?: string | undefined;\n}\n\n/**\n * Advances a workflow run one turn. The engine has one per workflow: the default {@link InProcess}\n * one runs a registered TS function with the in-process replay machinery; a remote one dispatches a\n * {@link WorkflowTask} to a worker (Python) and awaits its {@link WorkflowDecision}. Either way the\n * engine applies the returned decision — so recovery, timers, singleton and dead-letter stay engine\n * concerns, identical for in-process and remote workflows.\n */\nexport interface WorkflowExecutor {\n /**\n * INLINE replay: advance the turn and RETURN its decision (the in-process executor runs the\n * registered TS function synchronously). The engine awaits this under the run's lease. Provide this\n * OR {@link dispatch} — exactly one. An executor with only `advance` is single-instance by nature\n * (the decision is produced in-process, not delivered over a broker).\n */\n advance?(\n run: WorkflowRun,\n history: HistoryEvent[],\n pendingSignals?: WorkflowTask['pendingSignals'],\n ): Promise<WorkflowDecision>;\n /**\n * DISPATCH-AND-SUSPEND (broker-backed, multi-instance safe): enqueue the turn to a worker under the\n * ENGINE-SUPPLIED `taskId`, WITHOUT awaiting the decision. The engine generates `taskId`, records it\n * on the run as the awaited marker, AND releases the run's lease — all BEFORE calling this — so the\n * worker's {@link WorkflowDecision} (delivered over {@link Transport.onDecision} and applied DURABLY\n * by {@link WorkflowEngine.completeRemoteDecision}, which looks the run up by `decision.runId`) can\n * never arrive ahead of its marker or contend with a still-held lease and be dropped. This method\n * therefore ONLY enqueues — it owns no taskId generation and returns nothing. No in-memory await, so\n * the decision is never lost to a point-to-point broker handing it to a non-dispatching instance.\n * Provide this OR {@link advance} — exactly one.\n */\n dispatch?(\n run: WorkflowRun,\n history: HistoryEvent[],\n taskId: string,\n pendingSignals?: WorkflowTask['pendingSignals'],\n ): Promise<void>;\n}\n\n/**\n * A transport in an ordered pool, identified by `id`. The engine dispatches on the first by default\n * and fails over to the next on a dispatch error; a step can pin one via `ctx.step(…, { transport })`.\n * The chosen `id` is stamped on the {@link RemoteTask} so a worker replies through the matching one.\n */\nexport interface NamedTransport {\n id: string;\n transport: Transport;\n}\n\n/**\n * Decides where a freshly-`start`ed run executes. `start` creates the run as `pending` and hands its\n * id here instead of running the body inline — so the API/caller never blocks on workflow execution.\n * The default in-process dispatcher runs it on this instance (a microtask); a broker-backed one\n * enqueues the id for a worker pool to consume (`engine.runOne(runId)`); a no-op one leaves it\n * `pending` in the store for a worker's `runPending` poll to pick up (DB-only, caller-doesn't-execute).\n */\nexport interface RunDispatcher {\n dispatch(runId: string): void | Promise<void>;\n}\n\nexport interface Transport {\n /** engine → worker */\n dispatch(task: RemoteTask): Promise<void>;\n /** worker → engine: a step finished (ok or error). */\n onResult(handler: (result: StepResult) => Promise<void>): void;\n /** worker → engine: liveness signal for an in-flight long step. */\n onHeartbeat(handler: (beat: Heartbeat) => Promise<void>): void;\n /** Release the transport's resources (broker workers, queues, connections) for a clean shutdown.\n * Optional — an in-process transport has nothing to close. Called on `onApplicationShutdown`\n * after the engine drains, so a deploy hands off instead of leaving the broker to time out. */\n close?(): Promise<void>;\n /** engine → workflow worker: dispatch a {@link WorkflowTask} (the polyglot-workflow path). Optional\n * — only transports that carry workflow tasks (BullMQ) implement it; the {@link RemoteWorkflowExecutor}\n * uses it + {@link onDecision} to advance a remote workflow over the broker. */\n dispatchWorkflowTask?(task: WorkflowTask): Promise<void>;\n /** workflow worker → engine: a replayed turn's {@link WorkflowDecision}. Pair with dispatchWorkflowTask. */\n onDecision?(handler: (decision: WorkflowDecision) => Promise<void>): void;\n /** workflow worker → engine: a LOCAL step's {@link WorkflowStepEvent}, streamed mid-turn so the\n * engine can checkpoint it live. Point-to-point (a single engine instance consumes each event and\n * persists it once — no cross-pod duplicate writes). Optional; only broker transports carry it. */\n dispatchStepEvent?(event: WorkflowStepEvent): Promise<void>;\n /** engine ← workflow worker: consume streamed {@link WorkflowStepEvent}s. Pair with dispatchStepEvent. */\n onStepEvent?(handler: (event: WorkflowStepEvent) => Promise<void>): void;\n /** Worker-health for a group: queue backlog + live worker heartbeats. Optional — only broker\n * transports (BullMQ) that can introspect the task queue and the worker-heartbeat keys implement\n * it. The engine aggregates this across its groups in {@link WorkflowEngine.workerHealth}. */\n groupHealth?(group: string): Promise<GroupHealth>;\n /** Distinct groups that currently have a live worker heartbeat — discovered from the heartbeat\n * keyspace, so a group with workers but no engine-side registration (e.g. a local-step group)\n * still surfaces. Pairs with {@link groupHealth}. */\n listWorkerGroups?(): Promise<string[]>;\n /**\n * DB-less tenant worker → control plane: publish a {@link StartRunMessage} requesting a new run.\n * Optional — only transports that carry the hosted-control-plane protocol (P4) implement this.\n * The message is enqueued on `<effectivePrefix>-start-run`; the control plane's\n * `onStartRun` consumer turns it into a durable run.\n */\n dispatchStartRun?(msg: StartRunMessage): Promise<void>;\n /**\n * control plane ← tenant worker: consume {@link StartRunMessage}s and start runs. Pair with\n * {@link dispatchStartRun}. Optional — only control-plane-side transports implement this.\n */\n onStartRun?(handler: (msg: StartRunMessage) => Promise<void>): void;\n /**\n * Tenant worker → control plane: publish a {@link RunRequest} (read/control) on\n * `<effectivePrefix>-run-request`. Optional — only broker transports carry it.\n */\n dispatchRunRequest?(msg: RunRequest): Promise<void>;\n /** control plane ← tenant worker: consume {@link RunRequest}s. Pair with {@link dispatchRunRequest}. */\n onRunRequest?(handler: (msg: RunRequest) => Promise<void>): void;\n /** control plane → tenant worker: publish a correlated {@link RunReply} on `<effectivePrefix>-run-reply`\n * (pub/sub; every tenant subscribes and filters by `requestId`). */\n publishRunReply?(reply: RunReply): Promise<void>;\n /** tenant worker ← control plane: consume {@link RunReply}s (filter by `requestId` client-side). */\n onRunReply?(handler: (reply: RunReply) => void): void;\n /** control plane → tenant worker: re-publish a lifecycle {@link TenantEvent} on the run's per-tenant\n * channel `<effectivePrefix>-tenant-events-<tenant>`. */\n publishTenantEvent?(evt: TenantEvent): Promise<void>;\n /** tenant worker ← control plane: subscribe to THIS tenant's event channel. Returns an unsubscribe fn. */\n onTenantEvent?(tenant: string, handler: (evt: TenantEvent) => void): () => void;\n}\n\n/** How a worker decides its concurrency, carried in {@link WorkerStatus} so a dashboard can tell a\n * fixed knob from a self-regulating one (and, for the latter, where the controller currently sits). */\nexport interface WorkerConcurrencyStatus {\n /** `fixed` = the configured `concurrency` number, never moves. `adaptive` = the controller tunes it. */\n mode: 'fixed' | 'adaptive';\n /** The concurrency ceiling in effect right now (fixed: the configured value; adaptive: the live limit). */\n limit: number;\n /** Adaptive only — the floor the controller won't go below. */\n min?: number;\n /** Adaptive only — the ceiling the controller won't exceed. */\n max?: number;\n}\n\n/** The adaptive controller's most recent limit change — the \"why did it move\" a dashboard shows so an\n * auto-tuner isn't a black box. Absent until the controller first adjusts (or for a fixed worker). */\nexport interface WorkerAdjust {\n /** Epoch ms of the adjustment. */\n at: number;\n /** Limit before this change. */\n from: number;\n /** Limit after this change. */\n to: number;\n /** Why it moved: `ram_ceiling` (hard brake), `backpressure` (errors/stall), `grow` (had headroom),\n * `shrink` (latency gradient showed queuing), `cpu_ceiling`. */\n reason: 'ram_ceiling' | 'cpu_ceiling' | 'backpressure' | 'grow' | 'shrink';\n}\n\n/** A live snapshot of a worker's execution state, carried in the worker-liveness heartbeat (so it\n * rides the existing TTL'd key — no extra round-trip) and surfaced per worker in the dashboard. Every\n * field beyond {@link concurrency}/{@link inFlight} is best-effort: a field a runtime can't measure is\n * simply omitted. The shape is shared by the TS and Python SDKs so a mixed-language group reports\n * uniformly. */\nexport interface WorkerStatus {\n /** Which SDK is running this worker — `node` (TS) or `python`. */\n runtime?: 'node' | 'python';\n /** The worker's concurrency knob and its live ceiling. */\n concurrency: WorkerConcurrencyStatus;\n /** Tasks executing right now (0..limit). With `limit`, this is the saturation a dashboard charts. */\n inFlight: number;\n /** Resident set size in bytes, if the runtime can read it. */\n rssBytes?: number;\n /** The process memory ceiling in bytes (cgroup `memory.max`, else host total), if known. */\n rssLimitBytes?: number;\n /** RSS as a percent of {@link rssLimitBytes} (0..100) — what the adaptive RAM brake watches. */\n rssPct?: number;\n /** Process CPU utilisation percent over the last control tick (0..100×cores), if measured. */\n cpuPct?: number;\n /** Completed tasks per minute over the recent window — the controller's throughput signal. */\n throughputPerMin?: number;\n /** p95 of recent task durations in ms — the latency a dashboard charts against the limit. */\n p95Ms?: number;\n /** The adaptive controller's last limit change (absent for a fixed worker or before the first move). */\n lastAdjust?: WorkerAdjust;\n}\n\n/** One worker's liveness record — a TTL'd heartbeat a worker refreshes while it's consuming. Its\n * ABSENCE (the key expired) is the signal: a worker that died or stalled stops refreshing. */\nexport interface WorkerHeartbeat {\n /** The worker group this instance serves (e.g. `pipeline`, `processing-workflows`). */\n group: string;\n /** Stable per-process id (host + pid), so N replicas of a group each show as a distinct worker. */\n instanceId: string;\n /** Epoch ms of the worker's most recent heartbeat. */\n lastBeatAt: number;\n /** The worker's live execution snapshot, when its heartbeat carries one (newer SDKs stamp a JSON\n * value; an older SDK's bare-timestamp heartbeat leaves this undefined). */\n status?: WorkerStatus;\n}\n\n/** Per-group worker-health snapshot: how much work is queued vs. how many workers are alive to do it.\n * The actionable alert state is `depth > 0 && liveWorkers.length === 0` — work piling up with no\n * consumer (exactly the failure where a worker is \"alive but not consuming\"). */\nexport interface GroupHealth {\n group: string;\n /** Outstanding jobs in the group's task queue (waiting + active + delayed + prioritized). */\n depth: number;\n /** Workers with a non-expired heartbeat for this group. */\n liveWorkers: WorkerHeartbeat[];\n /**\n * Whether this group serves a `@Workflow` body or a `@Step`/handler — route-by-handler gives each\n * its own queue, so a health list mixes both. Classified by the CONTROL PLANE from its authoritative\n * registry (`workerHealth()`): a group whose base name is a registered workflow is `'workflow'`,\n * everything else (in-process steps, remote `handle_*`) is `'step'`. `undefined` only when no\n * control-plane registry was available to classify (e.g. a transport that reports health with no\n * engine). Lets a dashboard summarise the fleet in domain terms (\"N workflows · M steps\") instead of\n * leaking the raw queue count.\n */\n kind?: 'workflow' | 'step';\n}\n\n/**\n * The **control plane** — a broadcast pub/sub across ALL engine instances (every pod), separate\n * from the {@link Transport}'s point-to-point work queues (`dispatch`/`onResult`). It carries what\n * every instance may need regardless of who runs a given run: lifecycle events (so a dashboard-only\n * pod can live-tail a run executing on a worker pod) and cancellation (so the pod actually running a\n * run learns it was cancelled elsewhere). In-process implementations broadcast locally; a\n * cross-process one (BullMQ) fans out over its broker (Redis pub/sub). Give the engine a\n * `controlPlane` to enable cross-instance events/cancellation; omit it and the engine is local-only.\n * A transport that can broadcast may implement this too and be passed as both.\n */\nexport interface ControlPlane {\n publishControl(msg: ControlMessage): Promise<void>;\n onControl(handler: (msg: ControlMessage) => void): void;\n}\n\n/** A message on the {@link ControlPlane}. `from` is the originating engine's `instanceId`, so a\n * broker that echoes a publish back to its own subscriber (e.g. Redis pub/sub) can be deduped by\n * the originator. */\nexport type ControlMessage = { from?: string } & (\n | { kind: 'event'; event: EngineEvent }\n | { kind: 'cancel'; runId: string }\n // A run was just enqueued — nudge worker instances to pick it up now instead of on the next poll.\n | { kind: 'enqueued'; runId: string }\n);\n\n// ---------------------------------------------------------------------------\n// Authoring — workflows, local steps, and typed remote steps\n// ---------------------------------------------------------------------------\n\nexport type BackoffStrategy = 'fixed' | 'exp';\n\n/**\n * Options for `ctx.child` / `ctx.startChild`. A bare string passed instead is shorthand for\n * `{ childId }`, so the existing `ctx.child(ref, input, 'my-id')` form keeps working.\n */\nexport interface ChildCallOptions {\n /** Deterministic child run id; defaults to one derived from the parent run id + call position. */\n childId?: string | undefined;\n /**\n * Dispatch priority for a REMOTE child workflow — stamped on the child run and carried onto every\n * {@link WorkflowTask} dispatched to advance it, so an urgent child can jump ahead of enqueued\n * lower-priority ones at the worker. Higher wins; absent = unprioritised. Ignored for an in-process\n * (TS class) child, which runs in the engine and never hits a broker queue.\n */\n priority?: number | undefined;\n}\n\nexport interface StepOptions {\n /** Max attempts before the step (and run) fails. */\n retries?: number;\n /** How the delay between retries grows: `fixed` (constant) or `exp` (doubles each attempt). */\n backoff?: BackoffStrategy;\n /** Base delay in ms between retries. Omit (or 0) to retry with no delay. */\n backoffMs?: number;\n /** Upper bound on the (exponential) backoff delay. */\n backoffMaxMs?: number;\n /** Add random jitter (50–100% of the computed delay) to avoid thundering-herd retries. */\n jitter?: boolean;\n /**\n * Liveness window for a dispatched step (`ctx.step`): if the worker produces no result and no\n * heartbeat within this many ms, the engine presumes it dead and fails the dispatch with a\n * `RemoteStepTimeout` (retryable — it re-dispatches per `retries`). Each heartbeat resets the\n * window. Omit to wait indefinitely.\n */\n timeoutMs?: number;\n /**\n * Saga compensation: if this step completes but the run later **fails**, the engine runs the\n * registered `compensate` callbacks in reverse order (undo what was done). Local steps only.\n * Idempotency note: a step is already deduplicated by its deterministic `stepId` (runId:seq) —\n * remote workers can use it as the idempotency key, so there's no separate key option.\n */\n compensate?: () => Promise<void>;\n}\n\n/**\n * The structural carrier a dispatched `ctx.step` call resolves to and hands the engine: `name` is\n * the routing contract (the worker registers a handler under the same name, and routing is BY that\n * name — a worker subscribes per registered handler name, not a hand-declared group). There is no\n * public factory for this anymore — a `ctx.step(ref, input)` call builds one internally from the\n * `@Step`-stamped name (see {@link StepRef}/`stepNameOf`); a `ctx.step(name, input)` call builds one\n * from the literal string. `input`/`output` are optional runtime zod schemas an authoring layer MAY\n * attach (e.g. `@Step({ input, output })`) for validation at the dispatch boundary — a bare `@Step()`\n * carries neither, and the engine skips validation when they're absent.\n */\nexport interface StepDef<TInput = unknown, TOutput = unknown> extends StepOptions {\n name: string;\n /** Optional isolation partition; routing is by `name`. Suffixes the routing token as\n * `<name>@<partition>` (via {@link tenantGroup}) — omit to route by the bare (sanitized) `name`. */\n partition?: string | undefined;\n input?: z.ZodType<TInput> | undefined;\n output?: z.ZodType<TOutput> | undefined;\n}\n\n/**\n * A durable webhook handle minted by {@link WorkflowCtx.webhook}. Hand `url` to a third party,\n * then `await wait()` — the run suspends with zero compute until the external system POSTs the\n * callback (delivered as `engine.signal(token, body)`), and resumes with the body.\n */\nexport interface DurableWebhook<TPayload = unknown> {\n /** Deterministic signal token (`wh:<runId>:<seq>`) the callback delivers on — stable across replay. */\n readonly token: string;\n /**\n * Public callback URL for `token`, built by the engine's `webhookUrl` option. Hand this to the\n * third party. `undefined` when no builder is configured (use {@link DurableWebhook.token} to\n * build your own).\n */\n readonly url?: string | undefined;\n /**\n * Suspend until the callback arrives, then resume with its payload. Waits indefinitely by default —\n * no compute consumed. Pass `{ timeoutMs }` to bound the wait: if the deadline passes first the call\n * throws a `SignalTimeoutError` (catch it in the workflow to branch) — same timeout semantics as\n * {@link WorkflowCtx.waitForSignal}. The deadline is computed once (on the first call) and persisted,\n * so a replay reuses the recorded deadline rather than recomputing it from the current clock.\n */\n wait(opts?: { timeoutMs?: number }): Promise<TPayload>;\n}\n\n/**\n * Options for a dispatched {@link WorkflowCtx.step} call. `retries`/`backoff`/`backoffMs`/\n * `backoffMaxMs`/`jitter`/`timeoutMs` are a PER-CALL override of the `@Step`-declared\n * {@link StepConfig} (see `stepConfigOf`) — the effective policy `ctx.step` builds into the dispatched\n * {@link StepDef} is `{ ...stepConfigOf(ref), ...opts }`, so a call-site value wins field-by-field. The\n * string (cross-runtime) form of `ctx.step` has no stamped `@Step` to read, so it uses these fields\n * as-is.\n */\nexport interface StepDispatchOpts {\n /** Subject the dispatch to a registered flow-control queue (concurrency / rate limit). */\n queue?: string;\n /** Admission priority within `queue`; higher is admitted first when a slot is contended\n * (default 0). No effect without a `queue`. */\n priority?: number;\n /** The fairness bucket for a queue with `fairness: 'key'` (e.g. a tenant id) — the queue\n * round-robins across distinct keys so one key can't monopolize the budget. Defaults to the run\n * id when omitted. No effect without a `queue`. */\n fairnessKey?: string;\n /** Pin the dispatch to a named transport in the pool (else the pool's first, with failover to the\n * rest). See `engine.registerQueue` / the engine's `transports` option. */\n transport?: string;\n /** Max attempts before the step (and run) fails. Overrides the `@Step`-declared value. */\n retries?: number;\n /** How the delay between retries grows: `fixed` (constant) or `exp` (doubles each attempt).\n * Overrides the `@Step`-declared value. */\n backoff?: BackoffStrategy;\n /** Base delay in ms between retries. Omit (or 0) to retry with no delay. Overrides the\n * `@Step`-declared value. */\n backoffMs?: number;\n /** Upper bound on the (exponential) backoff delay. Overrides the `@Step`-declared value. */\n backoffMaxMs?: number;\n /** Add random jitter (50–100% of the computed delay) to avoid thundering-herd retries. Overrides\n * the `@Step`-declared value. */\n jitter?: boolean;\n /** Liveness window for this dispatched step: no result/heartbeat within this many ms presumes the\n * worker dead and fails the dispatch with a `RemoteStepTimeout` (retryable — re-dispatches per\n * `retries`). Omit to wait indefinitely. Overrides the `@Step`-declared value. */\n timeoutMs?: number;\n}\n\n/** What a saga undo handler receives: the compensated step's original input and its result — the\n * ONE argument a compensation `@Step` is called with, so it's self-describing on the wire (a\n * Python worker sees `{ input, output }` with no side-channel lookup needed). */\nexport interface StepUndo<TInput, TOutput> {\n input: TInput;\n output: TOutput;\n}\n\n/**\n * Derive a `ctx.step` compensation handler's expected argument from the ORIGINAL step's method\n * type, so the ref form is compile-checked against the step it undoes:\n *\n * ```ts\n * async cancelBooking(undo: UndoOf<FlightService['book']>) { ... }\n * ```\n *\n * `...rest: never[]` pins this to a single-argument method (the shape every `@Step` handler has —\n * see {@link StepRef}); `Awaited<R>` unwraps a `Promise<TOutput>` return down to `TOutput`.\n */\nexport type UndoOf<H> = H extends (input: infer I, ...rest: never[]) => infer R\n ? StepUndo<I, Awaited<R>>\n : never;\n\n/**\n * The context handed to a workflow function. Every interaction with the outside world goes\n * through it so the engine can checkpoint — the workflow body itself stays deterministic.\n *\n * Generic over `A`, the run's {@link SearchAttributes} shape — narrows {@link upsertSearchAttributes}\n * when a workflow declares a `@Workflow({ searchAttributes })` schema (pass\n * `WorkflowCtx<InferSearchAttributes<typeof mySchema>>` as the `run` method's ctx type). Defaults to\n * the untyped `SearchAttributes`, so every existing `WorkflowCtx` usage is unaffected.\n */\nexport interface WorkflowCtx<A extends SearchAttributes = SearchAttributes> {\n readonly runId: string;\n /**\n * Run a durable step — always dispatched, always engine-scheduled: the ONE step primitive (no\n * local/remote placement choice). Pass the step's method **reference** (a `@Step`-decorated\n * method, typed by its own signature — refactor-safe, autocompleted):\n *\n * ```ts\n * const r = await ctx.step(this.extraction.runExtractionPage, { page, key });\n * ```\n *\n * or its **name** for a cross-runtime handler (no JS reference to import, e.g. a Python `@step`):\n *\n * ```ts\n * const out = await ctx.step<ProcResult>('processing:proc', input);\n * ```\n *\n * Both forms dispatch identically — a step runs on whatever worker serves that name and the run\n * suspends (zero compute) until the result lands, then resumes with it (durable, replay-safe).\n *\n * `opts.compensate` registers a SAGA UNDO for this call, dispatched (durably, in reverse order\n * with every other registered undo) if the run later fails or is cancelled with\n * `{ compensate: true }`. The undo is itself a normal `@Step` — pass its reference (compile-time\n * checked: it must accept `StepUndo<TInput, TOutput>` of THIS call, see {@link UndoOf}) or its\n * name for a cross-runtime undo handler. It runs on whatever worker serves that name, called with\n * the ONE `{ input, output }` envelope — never the original handler re-invoked in-process.\n */\n step<TInput, TOutput>(\n handler: StepRef<TInput, TOutput>,\n input: TInput,\n opts?: StepDispatchOpts & { compensate?: StepRef<StepUndo<TInput, TOutput>, unknown> | string },\n ): Promise<TOutput>;\n step<TOutput = unknown, TInput = unknown>(\n name: string,\n input: TInput,\n opts?: StepDispatchOpts & { compensate?: StepRef<StepUndo<TInput, TOutput>, unknown> | string },\n ): Promise<TOutput>;\n /**\n * **Exactly-once** durable step for DB work: runs `fn` and writes the step's checkpoint in ONE\n * store transaction, so the business write and the \"done\" marker commit atomically — a crash can\n * never leave the write done-but-not-checkpointed (which a plain `ctx.step` would re-run). `fn`\n * receives the store-native transaction handle (`tx` — a TypeORM/MikroORM `EntityManager`, a Prisma\n * tx client, or a Drizzle tx); do your writes on it. Needs a SQL store that supports transactions\n * (the bundled SQL adapters do); throws otherwise.\n */\n transaction<TOutput>(name: string, fn: (tx: unknown) => Promise<TOutput>): Promise<TOutput>;\n /**\n * Call a durable **entity** op and await its result — the entity (`engine.registerEntity`) runs the\n * op serialized per `key` over durable state. e.g. `await ctx.callEntity('cart', userId, 'add', item)`.\n */\n callEntity<TResult = unknown>(\n name: string,\n key: string,\n op: string,\n arg?: unknown,\n ): Promise<TResult>;\n /** Send a durable entity op without awaiting a result (fire-and-forget, dispatched once). */\n signalEntity(name: string, key: string, op: string, arg?: unknown): Promise<void>;\n /**\n * Durable sleep: suspends the run for `duration` (e.g. `'30s'`, `'2h'`, `'7 days'`, or ms as a\n * number) without consuming resources, resuming automatically once the timer is due — even\n * across restarts.\n */\n sleep(duration: string | number): Promise<void>;\n /**\n * Durable sleep until an **absolute** time (a `Date` or epoch ms) — like {@link sleep} but for a\n * fixed deadline (e.g. \"resume at midnight\"). Resumes automatically once the time passes, across\n * restarts. The recorded wake time is fixed on the first run, so it's replay-stable.\n */\n sleepUntil(when: Date | number): Promise<void>;\n /**\n * End this run and **continue as a fresh execution** of the same workflow with `input` and a clean\n * history — for long-running / looping workflows that would otherwise accumulate unbounded\n * checkpoints (and slow replays). The next run gets id `<runId>~N`. Terminal: it always throws, so\n * code after it never runs. Carry forward whatever state the next iteration needs in `input`.\n */\n continueAsNew(input?: unknown): Promise<never>;\n /**\n * Suspend the run until an external `engine.signal(token, payload)` arrives (e.g. a webhook or\n * human approval), then resume with the payload. Waits indefinitely by default — no compute\n * consumed. Pass `{ timeoutMs }` to bound the wait: if the deadline passes first the call throws\n * a `SignalTimeoutError` (catch it in the workflow to branch).\n */\n waitForSignal<TPayload>(token: string, opts?: { timeoutMs?: number }): Promise<TPayload>;\n /**\n * Wait for a named **event** published via `engine.publishEvent(name, payload)`, then resume with\n * the payload. Unlike a signal (point-to-point by token), events are name-based pub/sub: pass an\n * optional `match` (a subset of the payload that must deep-equal) so a publish fans out only to the\n * runs it concerns — e.g. `ctx.waitForEvent('payment.settled', { match: { orderId } })`. `timeoutMs`\n * bounds the wait (throws `SignalTimeoutError`). No compute consumed while waiting.\n */\n waitForEvent<TPayload>(\n name: string,\n opts?: { match?: Record<string, unknown>; timeoutMs?: number },\n ): Promise<TPayload>;\n /**\n * An external task with **async completion**: run `dispatch` once (checkpointed — e.g. send to a\n * queue, kick off a non-durable worker or a foreign service like a Python process), then suspend\n * with zero compute until `engine.completeTask(runId, name, result)` (or `failTask`) reports back,\n * and resume with the result. The durable, first-class counterpart of the hand-rolled\n * \"dispatch over SQS → wait for COMPLETE_PHASE → signal\" pattern. `name` must be unique per run.\n */\n task<TResult>(\n name: string,\n dispatch: () => Promise<void>,\n options?: StepOptions,\n ): Promise<TResult>;\n /**\n * Run another registered workflow as a **tracked child** and await its result: starts it once and\n * suspends — zero compute — until the child reaches a terminal state, then resumes with the child's\n * output (or throws a FatalError if the child failed). `childId` defaults to a deterministic id\n * derived from this run and the call position, so it's stable across replay.\n *\n * Pass the child's **class** (`ctx.child(ShippingWorkflow, input)`) for a typed input + result; pass\n * a **string** name for a cross-runtime child (e.g. a Python workflow) where there's no class.\n */\n child<C extends WorkflowClass>(\n workflow: C,\n input: WorkflowInputOf<C>,\n options?: string | ChildCallOptions,\n ): Promise<WorkflowOutputOf<C>>;\n child<TOutput>(\n workflow: string,\n input: unknown,\n options?: string | ChildCallOptions,\n ): Promise<TOutput>;\n /**\n * Start a child workflow **fire-and-forget**: dispatches it once (checkpointed, replay-safe) and\n * returns its run id immediately — the parent keeps running instead of suspending. Use it to kick\n * off side work (an audit log, a notification) you don't need to wait on, or to fan out: collect\n * the ids, then later `await ctx.child(...)` each with the same id to join (the start is idempotent\n * by id, so the child runs exactly once). Class or string ref, like {@link child}.\n */\n startChild<C extends WorkflowClass>(\n workflow: C,\n input: WorkflowInputOf<C>,\n options?: string | ChildCallOptions,\n ): Promise<string>;\n startChild(\n workflow: string,\n input: unknown,\n options?: string | ChildCallOptions,\n ): Promise<string>;\n /**\n * Run N children of the SAME workflow **in parallel** and wait for ALL of them: dispatches one\n * child per entry in `inputs` (concurrently, each with its own durable lifecycle), suspends — zero\n * compute — until every child reaches a terminal state, then resumes with their outputs in **input\n * order**. Child ids are group-scoped and stable (`<runId>.all.<firstSeq>.<i>`), and the running\n * placeholders share a `parallelGroup` tag so the dashboard renders the fan-out as one group.\n *\n * `mode` (default `waitAll`): `waitAll` waits for all then throws an aggregate {@link GatherError}\n * if any failed; `failFast` throws as soon as a failed child is seen, and requests cancellation of\n * every sibling that hasn't completed yet (best-effort, plain cancel — no saga undo; a sibling\n * mid-step only observes it at its next checkpoint, it isn't force-killed mid-synchronous-execution,\n * so a fast sibling can still slip through and complete). Empty `inputs` returns `[]` with no side\n * effects. The wait-all / fan-out counterpart to {@link child}; parity with the Python SDK's\n * `gather_children`.\n */\n all<C extends WorkflowClass>(\n workflow: C,\n inputs: WorkflowInputOf<C>[],\n opts?: { mode?: 'waitAll' | 'failFast' },\n ): Promise<WorkflowOutputOf<C>[]>;\n all<TOutput = unknown>(\n workflow: string,\n inputs: unknown[],\n opts?: { mode?: 'waitAll' | 'failFast' },\n ): Promise<TOutput[]>;\n /**\n * Pause the run at this point until a human resumes it from the dashboard (or\n * `engine.continue(runId)`). Records a visible `pending` checkpoint so the breakpoint shows up\n * in the timeline, then suspends with zero compute — the durable equivalent of a debugger\n * breakpoint. Gate it on your own config to make breakpoints opt-in per run:\n * `if (cfg.breakAfterExtraction) await ctx.breakpoint('after-extraction')`.\n */\n breakpoint(label?: string): Promise<void>;\n /**\n * Mint a durable webhook: returns a handle with a deterministic `token` and (if the engine has a\n * `webhookUrl` builder) a public `url`. Hand the url to a third party — inside a `ctx.step` — then\n * `await handle.wait()` to suspend with zero compute until they POST the callback (the dashboard\n * turns that POST into `engine.signal(token, body)`). The first-class, replay-safe version of\n * \"expose a callback URL and wait for it\".\n */\n webhook<TPayload>(): DurableWebhook<TPayload>;\n /**\n * Publish a named, queryable value from inside the run — the latest value for `key` is readable\n * externally via `engine.getEvent(runId, key)` while the run is still in flight (progress, a\n * partial result, a status). Checkpointed and replay-safe (overwrites the previous value for the\n * same key). The read side has no effect on the run — the durable, suspend-model counterpart of a\n * Temporal query.\n */\n setEvent<TValue>(key: string, value: TValue): Promise<void>;\n /**\n * Expose a named **update point**: suspend until an external `engine.update(runId, name, arg)`\n * delivers `arg`, then resume with it. The update is run-scoped (`name` need only be unique within\n * the run) and gated by any validator registered via `engine.registerUpdateValidator` — a rejected\n * update never reaches here. Pass `{ timeoutMs }` to bound the wait (throws `SignalTimeoutError`).\n * The durable counterpart of a Temporal update handler.\n */\n onUpdate<TArg>(name: string, opts?: { timeoutMs?: number }): Promise<TArg>;\n /**\n * Guard an in-place workflow change without a new version. Wrap the changed code in\n * `if (await ctx.patched('my-change')) { …new… } else { …old… }`: a fresh run records a marker and\n * takes the new branch (`true`); a run already recorded under the old code keeps the old branch\n * (`false`), because its history has a real step where the marker would sit. The marker is\n * position-transparent for old runs (it doesn't shift their recorded steps), so guarding code is\n * replay-safe. Once every old run has drained, remove the guard (keep the new branch).\n */\n patched(id: string): Promise<boolean>;\n /**\n * Deterministic wall-clock, epoch **milliseconds** (like `Date.now()`): records the time on the\n * first run and replays the SAME value afterwards. Use this instead of `Date.now()`/`new Date()`\n * inside a workflow — a raw clock read returns a different value on every replay, which silently\n * corrupts a durable run. Returns a number so it composes in arithmetic (deadlines, elapsed);\n * for an ISO string do `new Date(await ctx.now()).toISOString()`. Every step is dispatched now\n * (see {@link step}), so a trivial timestamp capture gets this lightweight deterministic helper\n * instead of a full `@Step` + worker round-trip.\n */\n now(): Promise<number>;\n /**\n * **Deterministic capture.** Run `fn` once, checkpoint its result, and on replay return the SAME\n * value WITHOUT re-running `fn` — the durable way to bring a non-deterministic value into a workflow\n * where you control the generator: `ctx.sideEffect(() => uuidv7())`, `() => ulid()`,\n * `() => Math.random()`, a config/env read. Prefer a {@link step} for real work with side effects\n * (a DB write, an API call): `fn` here runs only once and MUST be effectively pure (it produces a\n * value; it is not re-executed on replay), like Temporal's `sideEffect`. For a plain timestamp use\n * {@link now}.\n */\n sideEffect<TValue>(fn: () => TValue | Promise<TValue>): Promise<TValue>;\n /**\n * Merge `attrs` into THIS run's {@link WorkflowRun.searchAttributes} — the indexed metadata the\n * dashboard and {@link RunQuery} filter on. Shallow merge: keys you don't pass are kept. Durable +\n * exactly-once — recorded at this position on the first run and SKIPPED on replay, so it does one\n * write, not one per turn. Use this instead of injecting the {@link StateStore} to mutate the run\n * you're executing (`@Inject(state-store)` + `store.updateRun(ctx.runId, …)` becomes\n * `ctx.upsertSearchAttributes(…)`).\n *\n * When the workflow declares a `@Workflow({ searchAttributes })` schema, the MERGED result (this\n * run's existing `searchAttributes` shallow-merged with `attrs`) is validated against it before the\n * write — an invalid merge throws, naming the workflow, the offending key(s), and the schema's\n * issues. Validation runs once, on the same first-run-only position as the write itself (skipped\n * entirely on replay, so it's never a source of nondeterminism); it must be synchronous — a schema\n * whose `validate` returns a `Promise` throws instead of being awaited. No schema declared ⇒\n * unchanged, unvalidated behavior.\n */\n upsertSearchAttributes(attrs: Partial<A>): Promise<void>;\n /**\n * Run a checkpointed step **in-process** — the escape hatch from the always-dispatched {@link step}\n * for work that must run inline in the workflow body. Like `step`, its result is a durable checkpoint\n * (returned, not re-run, on replay); unlike `step`, the body `fn` executes here rather than on a\n * worker, so it can carry an in-memory `compensate` callback for **sagas** — an undo the engine runs\n * in reverse if the run later fails (see [Sagas & compensation](/docs/reliability/sagas)). `fn`\n * receives a {@link StepLogger} for sub-process events. Prefer {@link step} for ordinary work; reach\n * for `localStep` when you need in-process execution or a compensation.\n */\n localStep<TOutput>(\n name: string,\n fn: (log: StepLogger) => Promise<TOutput>,\n options?: StepOptions,\n ): Promise<TOutput>;\n}\n\n/** Result of executing or resuming a workflow run. */\nexport interface RunResult {\n runId: string;\n status: RunStatus;\n output?: unknown;\n error?: StepError | undefined;\n}\n\n/**\n * Validates an incoming `engine.update` before it is delivered to the run. Throw (or return a\n * non-empty string) to reject — the run is left untouched. Return nothing/void to accept. May be\n * async (e.g. a business-rule check against a DB).\n */\n// A validator may return nothing (accept) or a reason string (reject); `void` is the intended\n// \"returned nothing\" case, sync or async.\nexport type UpdateValidator<TArg = unknown> =\n // biome-ignore lint/suspicious/noConfusingVoidType: `void` here means \"returned nothing\" (accept).\n (arg: TArg) => void | string | Promise<void | string>;\n\n/** Outcome of `engine.update`: rejected by the validator, or accepted and delivered. */\nexport type UpdateResult =\n | { accepted: false; reason: string }\n | { accepted: true; run: RunResult | null };\n\nexport type EngineEventType =\n | 'run.started'\n | 'run.completed'\n | 'run.failed'\n | 'run.suspended'\n | 'step.started'\n | 'step.completed'\n | 'step.failed'\n // A single step event (log line / sub-process outcome) emitted WHILE a step is still running, so\n // observers tail a long step's progress live instead of waiting for `step.completed` to deliver\n // the whole `events` array at once. Carries `event`; never persisted (live-tail only).\n | 'step.progress';\n\n/**\n * A lifecycle event emitted by the engine. The observability surfaces (dashboard, OTel, the\n * Telescope integration) all subscribe to these rather than reaching into the store.\n */\nexport interface EngineEvent {\n type: EngineEventType;\n runId: string;\n workflow?: string | undefined;\n /** The run's worker-pool partition (see {@link WorkflowRun.namespace}), stamped on the `run.*`\n * lifecycle events (where the emitting call site already has the run in hand) so a tenant-event\n * re-publisher can scope without a per-event store read. Absent on `step.*` events. */\n namespace?: string | undefined;\n seq?: number | undefined;\n name?: string | undefined;\n kind?: StepKind | undefined;\n output?: unknown;\n error?: StepError | undefined;\n /** Wall-clock duration of the unit that just finished (step or run), when known. */\n durationMs?: number | undefined;\n /** For a remote step: how long it waited in the queue before a worker picked it up. */\n queueMs?: number | undefined;\n /** The live step event carried by a `step.progress` (the single log line / sub-process outcome a\n * running step just emitted). Absent on lifecycle events. */\n event?: StepEvent | undefined;\n at: Date;\n}\n\nexport type EngineListener = (event: EngineEvent) => void;\n\n/** What a {@link StepInterceptor} is told about the local step it is wrapping. */\nexport interface StepInvocation {\n readonly runId: string;\n readonly workflow: string;\n /** The step name passed to `ctx.step(name, ...)` (also `'now'`/`'random'`/`'uuid'` internals). */\n readonly stepName: string;\n /** The step's logical position within the run. */\n readonly seq: number;\n /** 1-based attempt number — increments across `ctx.step` retries. */\n readonly attempt: number;\n}\n\n/**\n * Wraps the **real execution** of a local `ctx.step` (Template/Nest-style onion middleware). Call\n * `next()` to run the step body (or the next interceptor) and return — or transform — its result;\n * throw to fail the step. First-registered runs outermost. Interceptors fire only when a step\n * actually executes, NOT on replay (a replayed step returns its recorded output without running),\n * so they see true execution timing. Register with `engine.use`.\n */\nexport type StepInterceptor = (\n invocation: StepInvocation,\n next: () => Promise<unknown>,\n) => Promise<unknown>;\n","import type { RunQuery, SignalWaiter, StateStore, StepCheckpoint, WorkflowRun } from './interfaces';\n\n/**\n * Transforms a payload value as it crosses the store boundary — e.g. encrypt-at-rest, compress, or\n * redact PII. `decode` must be the exact inverse of `encode`. Both are synchronous (use a local\n * cipher / codec); wrap an async KMS yourself if you need one.\n */\nexport interface PayloadCodec {\n encode(value: unknown): unknown;\n decode(value: unknown): unknown;\n}\n\n/**\n * A `StateStore` decorator that runs run/step **payloads** (input + output) through a\n * {@link PayloadCodec} — encoded on write, decoded on read — so they're never stored in the clear.\n * Adapter-agnostic: wrap any store. Searchable metadata (id, status, workflow, tags, timestamps) and\n * the structured `error` are left untouched so the dashboard, queries, and recovery still work.\n *\n * ```ts\n * const store = new CodecStateStore(new TypeOrmStateStore(ds), aesCodec);\n * ```\n */\nexport class CodecStateStore implements StateStore {\n constructor(\n private readonly inner: StateStore,\n private readonly codec: PayloadCodec,\n ) {}\n\n private enc(v: unknown): unknown {\n return v === undefined ? undefined : this.codec.encode(v);\n }\n private dec(v: unknown): unknown {\n return v === undefined ? undefined : this.codec.decode(v);\n }\n\n private encRun(run: WorkflowRun): WorkflowRun {\n return { ...run, input: this.enc(run.input), output: this.enc(run.output) };\n }\n private decRun<T extends WorkflowRun | null>(run: T): T {\n return (run && { ...run, input: this.dec(run.input), output: this.dec(run.output) }) as T;\n }\n private encCp(cp: StepCheckpoint): StepCheckpoint {\n return { ...cp, input: this.enc(cp.input), output: this.enc(cp.output) };\n }\n private decCp<T extends StepCheckpoint | null>(cp: T): T {\n return (cp && { ...cp, input: this.dec(cp.input), output: this.dec(cp.output) }) as T;\n }\n\n ensureSchema(): Promise<void> {\n return this.inner.ensureSchema?.() ?? Promise.resolve();\n }\n\n createRun(run: WorkflowRun): Promise<void> {\n return this.inner.createRun(this.encRun(run));\n }\n updateRun(runId: string, patch: Partial<WorkflowRun>): Promise<void> {\n const next = { ...patch };\n if ('input' in patch) next.input = this.enc(patch.input);\n if ('output' in patch) next.output = this.enc(patch.output);\n return this.inner.updateRun(runId, next);\n }\n async getRun(runId: string): Promise<WorkflowRun | null> {\n return this.decRun(await this.inner.getRun(runId));\n }\n deleteRun(runId: string): Promise<void> {\n return this.inner.deleteRun(runId);\n }\n async getCheckpoint(runId: string, seq: number): Promise<StepCheckpoint | null> {\n return this.decCp(await this.inner.getCheckpoint(runId, seq));\n }\n saveCheckpoint(checkpoint: StepCheckpoint): Promise<void> {\n return this.inner.saveCheckpoint(this.encCp(checkpoint));\n }\n transaction<T>(\n work: (tx: {\n raw: unknown;\n saveCheckpoint: (cp: StepCheckpoint) => Promise<void>;\n }) => Promise<T>,\n ): Promise<T> {\n if (!this.inner.transaction) {\n throw new Error('the wrapped store does not support transactions');\n }\n // Encode the checkpoint inside the tx, so payloads stay encoded at rest like the normal path.\n return this.inner.transaction((tx) =>\n work({ raw: tx.raw, saveCheckpoint: (cp) => tx.saveCheckpoint(this.encCp(cp)) }),\n );\n }\n async listIncompleteRuns(namespace?: string): Promise<WorkflowRun[]> {\n return (await this.inner.listIncompleteRuns(namespace)).map((r) => this.decRun(r));\n }\n async listPendingRuns(limit: number, namespace?: string): Promise<WorkflowRun[]> {\n return (await this.inner.listPendingRuns(limit, namespace)).map((r) => this.decRun(r));\n }\n async listDueTimers(nowMs: number, namespace?: string): Promise<WorkflowRun[]> {\n return (await this.inner.listDueTimers(nowMs, namespace)).map((r) => this.decRun(r));\n }\n tryLockRun(runId: string, owner: string, leaseUntilMs: number, nowMs: number): Promise<boolean> {\n return this.inner.tryLockRun(runId, owner, leaseUntilMs, nowMs);\n }\n releaseRunLock(runId: string): Promise<void> {\n return this.inner.releaseRunLock(runId);\n }\n renewRunLock(runId: string, owner: string, leaseUntilMs: number): Promise<boolean> {\n return this.inner.renewRunLock(runId, owner, leaseUntilMs);\n }\n putSignalWaiter(waiter: SignalWaiter): Promise<void> {\n return this.inner.putSignalWaiter(waiter);\n }\n takeSignalWaiter(token: string): Promise<SignalWaiter | null> {\n return this.inner.takeSignalWaiter(token);\n }\n listSignalWaiters(prefix: string): Promise<SignalWaiter[]> {\n return this.inner.listSignalWaiters(prefix);\n }\n removeSignalWaiter(waiter: SignalWaiter): Promise<void> {\n return this.inner.removeSignalWaiter(waiter);\n }\n bufferSignal(token: string, payload: unknown): Promise<void> {\n return this.inner.bufferSignal(token, this.enc(payload));\n }\n async takeBufferedSignal(token: string): Promise<{ payload: unknown } | null> {\n const buffered = await this.inner.takeBufferedSignal(token);\n return buffered && { payload: this.dec(buffered.payload) };\n }\n bufferEvent(input: {\n name: string;\n payload: unknown;\n id: string;\n publishedAt: number;\n }): Promise<void> {\n return this.inner.bufferEvent({ ...input, payload: this.enc(input.payload) });\n }\n async listBufferedEvents(\n name: string,\n limit: number,\n ): Promise<Array<{ id: string; payload: unknown; publishedAt: number }>> {\n const events = await this.inner.listBufferedEvents(name, limit);\n return events.map((e) => ({ ...e, payload: this.dec(e.payload) }));\n }\n removeBufferedEvent(id: string): Promise<boolean> {\n return this.inner.removeBufferedEvent(id);\n }\n async listRuns(query: RunQuery): Promise<WorkflowRun[]> {\n return (await this.inner.listRuns(query)).map((r) => this.decRun(r));\n }\n async listCheckpoints(runId: string): Promise<StepCheckpoint[]> {\n return (await this.inner.listCheckpoints(runId)).map((c) => this.decCp(c));\n }\n async getLatestCheckpointByName(\n runId: string,\n name: string,\n ): Promise<StepCheckpoint | undefined> {\n // Forward the targeted read when the inner store implements it; otherwise fall back to the\n // (always-present) listCheckpoints scan so wrapping a legacy custom store keeps working.\n if (this.inner.getLatestCheckpointByName) {\n const cp = await this.inner.getLatestCheckpointByName(runId, name);\n return cp ? this.decCp(cp) : undefined;\n }\n let latest: StepCheckpoint | undefined;\n for (const cp of await this.inner.listCheckpoints(runId)) if (cp.name === name) latest = cp;\n return latest ? this.decCp(latest) : undefined;\n }\n async listCheckpointsByNamePrefix(runId: string, prefixes: string[]): Promise<StepCheckpoint[]> {\n const matches = this.inner.listCheckpointsByNamePrefix\n ? await this.inner.listCheckpointsByNamePrefix(runId, prefixes)\n : (await this.inner.listCheckpoints(runId)).filter((cp) =>\n prefixes.some((p) => cp.name.startsWith(p)),\n );\n return matches.map((c) => this.decCp(c));\n }\n}\n","import type { EngineEvent } from './interfaces';\n\nexport interface MetricsSnapshot {\n runs: { started: number; completed: number; failed: number; suspended: number };\n steps: { started: number; completed: number; failed: number };\n /** Per-workflow run counters, keyed by workflow name. */\n byWorkflow: Record<string, { started: number; completed: number; failed: number }>;\n /** Sum + count of recorded step durations (ms), for an average. */\n stepDuration: { sumMs: number; count: number };\n}\n\nexport interface MetricsCollector {\n snapshot(): MetricsSnapshot;\n /** Prometheus text exposition of the counters — serve this from a `/metrics` endpoint. */\n prometheus(): string;\n /** Unsubscribe from the engine. */\n stop(): void;\n}\n\ntype Subscribable = { subscribe(listener: (event: EngineEvent) => void): () => void };\n\n/**\n * Subscribe to an engine's lifecycle events and accumulate Prometheus-style counters (runs + steps by\n * outcome, per-workflow run counts, step-duration sum/count). Dependency-free — call `.prometheus()`\n * from your metrics endpoint, or `.snapshot()` for the raw numbers. Counters are per process; scrape\n * each instance.\n */\nexport function collectMetrics(engine: Subscribable): MetricsCollector {\n const m: MetricsSnapshot = {\n runs: { started: 0, completed: 0, failed: 0, suspended: 0 },\n steps: { started: 0, completed: 0, failed: 0 },\n byWorkflow: {},\n stepDuration: { sumMs: 0, count: 0 },\n };\n const wf = (name?: string) => {\n const k = name ?? 'unknown';\n let entry = m.byWorkflow[k];\n if (!entry) {\n entry = { started: 0, completed: 0, failed: 0 };\n m.byWorkflow[k] = entry;\n }\n return entry;\n };\n\n const stop = engine.subscribe((e) => {\n switch (e.type) {\n case 'run.started':\n m.runs.started += 1;\n wf(e.workflow).started += 1;\n break;\n case 'run.completed':\n m.runs.completed += 1;\n wf(e.workflow).completed += 1;\n break;\n case 'run.failed':\n m.runs.failed += 1;\n wf(e.workflow).failed += 1;\n break;\n case 'run.suspended':\n m.runs.suspended += 1;\n break;\n case 'step.started':\n m.steps.started += 1;\n break;\n case 'step.completed':\n m.steps.completed += 1;\n if (e.durationMs != null) {\n m.stepDuration.sumMs += e.durationMs;\n m.stepDuration.count += 1;\n }\n break;\n case 'step.failed':\n m.steps.failed += 1;\n break;\n }\n });\n\n return {\n snapshot: () => structuredClone(m),\n stop,\n prometheus: () => {\n const lines: string[] = [];\n lines.push('# TYPE durable_runs_total counter');\n for (const [k, v] of Object.entries(m.runs))\n lines.push(`durable_runs_total{event=\"${k}\"} ${v}`);\n lines.push('# TYPE durable_steps_total counter');\n for (const [k, v] of Object.entries(m.steps))\n lines.push(`durable_steps_total{event=\"${k}\"} ${v}`);\n lines.push('# TYPE durable_runs_by_workflow_total counter');\n for (const [name, v] of Object.entries(m.byWorkflow))\n for (const [event, n] of Object.entries(v))\n lines.push(`durable_runs_by_workflow_total{workflow=\"${name}\",event=\"${event}\"} ${n}`);\n lines.push('# TYPE durable_step_duration_ms_sum counter');\n lines.push(`durable_step_duration_ms_sum ${m.stepDuration.sumMs}`);\n lines.push('# TYPE durable_step_duration_count counter');\n lines.push(`durable_step_duration_count ${m.stepDuration.count}`);\n return `${lines.join('\\n')}\\n`;\n },\n };\n}\n","import { createRequire } from 'node:module';\nimport type { WorkflowEngine } from './engine';\n\n// Resolve the optional `cron-parser` peer dependency in a way that works in BOTH the ESM and CJS\n// builds of this package (dual publish). `createRequire(import.meta.url)` gives a real `require` in\n// ESM output; in the CJS build, tsup's banner shims `import.meta.url` to the file URL, so the same\n// call resolves there too. This keeps the load synchronous (no async leak into the scheduler API).\nconst nodeRequire = createRequire(import.meta.url);\n\nexport interface ScheduledWorkflow {\n /** Stable key identifying this schedule — part of the deterministic run id. */\n key: string;\n workflow: string;\n input?: unknown;\n /** Start one run every `everyMs`. Mutually exclusive with `cron`. */\n everyMs?: number;\n /**\n * A cron expression (5 fields `m h dom mon dow`, or 6 with leading seconds) evaluated in\n * {@link ScheduledWorkflow.timezone}. Mutually exclusive with `everyMs`. Needs the optional peer\n * dependency `cron-parser`.\n */\n cron?: string;\n /** IANA timezone the `cron` fires in (e.g. `America/Sao_Paulo`). Defaults to UTC. */\n timezone?: string;\n /** Temporarily stop firing this schedule (kept registered). Defaults to false. */\n paused?: boolean;\n /**\n * What to do when the previous window's run hasn't finished yet (fixed-interval schedules only):\n * `'allow'` (default) starts the new window anyway; `'skip'` skips it while the prior run is still\n * `running`/`suspended`, so a slow run can't pile up overlapping executions.\n */\n overlap?: 'allow' | 'skip';\n /**\n * Randomly delay the dispatch by up to this many ms BEFORE firing, to spread load when many\n * instances tick on the same boundary (avoids a thundering herd). Opt-in; absent = fire immediately.\n *\n * This is dispatch-path jitter only — it does NOT affect the run id (still the time bucket), so\n * idempotency is unchanged: two instances jittering the same window still start it exactly once.\n * (The engine forbids `Math.random` inside workflow code; the scheduler dispatch path is not\n * workflow code, so jitter here is fine.)\n */\n jitter?: number;\n /**\n * Enqueue windows that were missed while the scheduler was down, instead of silently skipping\n * them. Opt-in; absent = only the current window fires. `maxCatchup` bounds how many PRIOR windows\n * are backfilled (a long outage can't flood the system). Backfilled runs use each missed window's\n * deterministic bucket run id, so `engine.start` idempotency skips any that already ran.\n */\n backfill?: { maxCatchup: number };\n}\n\n/** Injectable dispatch-path effects (kept out of the deterministic run-id logic). Defaults to real\n * `Math.random` + `setTimeout`; overridden in tests so jitter is deterministic and instant. */\nexport interface RunSchedulesOptions {\n random?: () => number;\n sleep?: (ms: number) => Promise<void>;\n}\n\nconst defaultSleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));\n\n/** Deterministic run id for a fixed-interval schedule's current time window. */\nexport function scheduledRunId(key: string, everyMs: number, nowMs: number): string {\n return `sched:${key}:${Math.floor(nowMs / everyMs)}`;\n}\n\ntype CronParser = typeof import('cron-parser');\nlet cronParser: CronParser | undefined;\nfunction loadCronParser(): CronParser {\n if (cronParser) return cronParser;\n try {\n // Lazy + optional: core stays dependency-free; only users who schedule by cron need this.\n cronParser = nodeRequire('cron-parser') as CronParser;\n } catch {\n throw new Error(\n 'cron schedules need the optional peer dependency \"cron-parser\" — install it (e.g. `npm i cron-parser`).',\n );\n }\n return cronParser;\n}\n\n/**\n * Epoch ms of the most recent cron fire at or before `nowMs`, evaluated in `timezone` (default UTC).\n * This is the deterministic \"bucket\" a cron run is keyed on, so polling repeatedly within an\n * interval resolves to the same fire time — and thus the same idempotent run id.\n */\nexport function prevCronFireMs(expr: string, nowMs: number, timezone = 'UTC'): number {\n const parser = loadCronParser();\n // `+1` makes a fire landing exactly on `nowMs` count as \"at or before now\", not the prior one.\n const it = parser.parseExpression(expr, { currentDate: new Date(nowMs + 1), tz: timezone });\n return it.prev().toDate().getTime();\n}\n\n/** The deterministic, idempotent run id for a schedule at `nowMs` — its current fire window. */\nfunction scheduleRunIdAt(s: ScheduledWorkflow, nowMs: number): string {\n if (s.cron != null) return `sched:${s.key}:${prevCronFireMs(s.cron, nowMs, s.timezone)}`;\n if (s.everyMs != null) return scheduledRunId(s.key, s.everyMs, nowMs);\n throw new Error(`schedule \"${s.key}\" needs either \"everyMs\" or \"cron\"`);\n}\n\n/**\n * The run ids this schedule should fire at `nowMs`: the current window, plus — when `backfill` is set\n * — up to `maxCatchup` prior windows that may have been missed. Oldest-first, so a backfill catches\n * up in chronological order. Ids are the same deterministic buckets `scheduleRunIdAt` produces, so\n * `engine.start` idempotency drops any window that already ran.\n */\nfunction scheduleRunIdsAt(s: ScheduledWorkflow, nowMs: number): string[] {\n const current = scheduleRunIdAt(s, nowMs);\n if (!s.backfill || s.backfill.maxCatchup <= 0) return [current];\n\n const ids: string[] = [];\n if (s.everyMs != null) {\n const bucket = Math.floor(nowMs / s.everyMs);\n const oldest = Math.max(0, bucket - s.backfill.maxCatchup);\n for (let b = oldest; b < bucket; b += 1) ids.push(`sched:${s.key}:${b}`);\n } else if (s.cron != null) {\n // Walk back through prior cron fire times (most-recent missed first), then reverse to oldest-first.\n const prior: string[] = [];\n let cursor = prevCronFireMs(s.cron, nowMs, s.timezone);\n for (let i = 0; i < s.backfill.maxCatchup; i += 1) {\n // `cursor` (exclusive) → the fire strictly before it.\n const before = prevCronFireMs(s.cron, cursor - 1, s.timezone);\n prior.push(`sched:${s.key}:${before}`);\n cursor = before;\n }\n ids.push(...prior.reverse());\n }\n ids.push(current);\n return ids;\n}\n\n/**\n * Start each schedule's current-window run. The run id is the time bucket (a fixed-interval index,\n * or the cron fire time) and `engine.start` is idempotent, so firing this on an interval — or\n * racing two instances on the same tick — starts **each window exactly once**. Wire it to a\n * `setInterval`, the durable timer poller, or `@nestjs/schedule`. Returns the run ids for the\n * current windows.\n */\nexport async function runSchedules(\n engine: Pick<WorkflowEngine, 'start' | 'getRun'>,\n schedules: readonly ScheduledWorkflow[],\n nowMs: number,\n opts?: RunSchedulesOptions,\n): Promise<string[]> {\n const random = opts?.random ?? Math.random;\n const sleep = opts?.sleep ?? defaultSleep;\n const ids: string[] = [];\n for (const s of schedules) {\n if (s.paused) continue;\n // overlap:'skip' (fixed-interval): don't start this window while the previous window's run is\n // still in-flight, so a slow run can't pile up. Interval-only — cron windows aren't adjacent ids.\n if (s.overlap === 'skip' && s.everyMs) {\n const prevBucket = Math.floor(nowMs / s.everyMs) - 1;\n if (prevBucket >= 0) {\n const prev = await engine.getRun(`sched:${s.key}:${prevBucket}`);\n if (prev && (prev.status === 'running' || prev.status === 'suspended')) continue;\n }\n }\n // Dispatch-path jitter (not workflow code): spread same-boundary ticks across instances. Applied\n // once per schedule, before firing — the run ids below are unaffected, so idempotency holds.\n if (s.jitter && s.jitter > 0) await sleep(Math.floor(random() * s.jitter));\n for (const runId of scheduleRunIdsAt(s, nowMs)) {\n await engine.start(s.workflow, s.input, runId);\n ids.push(runId);\n }\n }\n return ids;\n}\n","import type { AttributeFilter, AttributeOp, RunQuery, WorkflowRun } from './interfaces';\nimport type { SearchAttributes } from './interfaces';\n\n/** Compare one attribute value against a filter operand. Range ops need both sides comparable. */\nfunction compare(actual: unknown, op: AttributeOp, expected: string | number | boolean): boolean {\n switch (op) {\n case 'eq':\n return actual === expected;\n case 'ne':\n return actual !== expected;\n case 'gt':\n return actual != null && actual > expected;\n case 'gte':\n return actual != null && actual >= expected;\n case 'lt':\n return actual != null && actual < expected;\n case 'lte':\n return actual != null && actual <= expected;\n }\n}\n\n/**\n * Does a run's search attributes satisfy EVERY filter (AND)? A missing key never matches (so `ne`\n * on an absent key is false too — the attribute simply isn't there to compare). Empty/undefined\n * filters match everything. Shared by every store so typed/range queries behave identically across\n * adapters (applied in-process after the coarse workflow/status/tag filters).\n */\nexport function matchesAttributes(\n attributes: SearchAttributes | undefined,\n filters: AttributeFilter[] | undefined,\n): boolean {\n if (!filters?.length) return true;\n if (!attributes) return false;\n return filters.every((f) => f.key in attributes && compare(attributes[f.key], f.op, f.value));\n}\n\n/**\n * Apply a query's attribute predicates then its `offset`/`limit`, in-process — for store adapters\n * that can't express typed/range predicates in SQL. Pass rows already coarse-filtered (workflow /\n * status / tag) and sorted newest-first; this filters by `attributes` and paginates. Only call it\n * when `query.attributes` is set (otherwise let the DB do `LIMIT`/`OFFSET`).\n */\nexport function applyAttributeQuery(rows: WorkflowRun[], query: RunQuery): WorkflowRun[] {\n const filtered = rows.filter((r) => matchesAttributes(r.searchAttributes, query.attributes));\n const offset = query.offset ?? 0;\n const limit = query.limit ?? filtered.length;\n return filtered.slice(offset, offset + limit);\n}\n\n/**\n * One normalized row of the `durable_run_attributes` side-table: a single (key → value) pair of a\n * run's search attributes, split into typed columns so SQL can index/range-scan it. Exactly one of\n * `strValue`/`numValue` is set per row (booleans normalize to a string `\"true\"`/`\"false\"` so `eq`/`ne`\n * still match). NULL for the column that doesn't apply, which keeps `(key, numValue)` /\n * `(key, strValue)` indexes selective.\n */\nexport interface RunAttributeRow {\n runId: string;\n key: string;\n strValue: string | null;\n numValue: number | null;\n}\n\n/**\n * Explode a run's search attributes into normalized side-table rows (one per key). Used by SQL stores\n * to maintain `durable_run_attributes` on every create/update and by the in-memory store's index, so\n * attribute predicates can be pushed DOWN into a join/EXISTS instead of scanned in-process. Numbers go\n * to `numValue`; strings to `strValue`; booleans to `strValue` as `\"true\"`/`\"false\"` (matching how the\n * in-process `compare` treats `eq`/`ne` on booleans). Returns `[]` for a run with no attributes.\n */\nexport function normalizeAttributeRows(\n runId: string,\n attributes: SearchAttributes | undefined,\n): RunAttributeRow[] {\n if (!attributes) return [];\n const out: RunAttributeRow[] = [];\n for (const [key, value] of Object.entries(attributes)) {\n if (typeof value === 'number') {\n out.push({ runId, key, strValue: null, numValue: value });\n } else if (typeof value === 'boolean') {\n out.push({ runId, key, strValue: value ? 'true' : 'false', numValue: null });\n } else {\n out.push({ runId, key, strValue: value, numValue: null });\n }\n }\n return out;\n}\n\n/** SQL comparison operator for an {@link AttributeOp} (used to build pushdown predicates). */\nexport function sqlComparator(op: AttributeOp): string {\n switch (op) {\n case 'eq':\n return '=';\n case 'ne':\n return '<>';\n case 'gt':\n return '>';\n case 'gte':\n return '>=';\n case 'lt':\n return '<';\n case 'lte':\n return '<=';\n }\n}\n\n/**\n * Which side-table column an attribute filter compares against: numeric operands (and range ops on\n * numbers) hit `numValue`; everything else hits `strValue` (booleans are stored as `\"true\"`/`\"false\"`).\n * Keeping this in core means every SQL adapter pushes predicates down identically.\n */\nexport function attributeColumnFor(filter: AttributeFilter): 'numValue' | 'strValue' {\n return typeof filter.value === 'number' ? 'numValue' : 'strValue';\n}\n\n/** The literal a side-table predicate compares against (booleans → `\"true\"`/`\"false\"` strings). */\nexport function attributeOperand(filter: AttributeFilter): string | number {\n if (typeof filter.value === 'boolean') return filter.value ? 'true' : 'false';\n return filter.value;\n}\n","import type { InferSearchAttributes, SearchAttributes, SearchAttributesSchema } from './interfaces';\n\n/**\n * Read a run's `searchAttributes` through a {@link SearchAttributesSchema}, typed to the schema's\n * inferred output. **Safe-parse semantics, deliberately lenient** — unlike\n * `ctx.upsertSearchAttributes` (which is strict: an invalid merge throws), a failed validation here\n * returns `{}` rather than throwing. This is intentional: `run.searchAttributes` may predate the\n * schema (an older deploy wrote it under a looser or absent schema, or a run started before this\n * workflow ever declared one), and a dashboard/read path crashing on old history is worse than it\n * quietly reporting no typed attributes for that run. Write-time enforcement is what keeps NEW writes\n * conformant; this is the read-side counterpart for consuming them.\n *\n * The schema's `validate` must be synchronous (matching the write-side constraint in\n * `ctx.upsertSearchAttributes`) — one returning a `Promise` throws with a clear error rather than\n * being silently awaited or silently treated as a failure.\n *\n * @example\n * ```ts\n * import { z } from 'zod';\n * import { readSearchAttributes } from '@dudousxd/nestjs-durable-core';\n *\n * const orderAttrs = z.object({ tier: z.enum(['free', 'pro']), amount: z.number() });\n *\n * const run = await store.getRun(runId);\n * const attrs = readSearchAttributes(orderAttrs, run ?? {}); // { tier: 'pro', amount: 42 } | {}\n * ```\n */\nexport function readSearchAttributes<S extends SearchAttributesSchema>(\n schema: S,\n // `| null` because ORM store entities (MikroORM/TypeORM/Prisma) type the JSON column as\n // nullable — the entity row is the argument every real consumer passes.\n run: { searchAttributes?: SearchAttributes | null | undefined },\n): InferSearchAttributes<S> {\n const result = schema['~standard'].validate(run.searchAttributes ?? {});\n if (result instanceof Promise) {\n throw new Error(\n \"readSearchAttributes: schema validation must be synchronous (the searchAttributes schema's \" +\n '`~standard.validate` returned a Promise) — async Standard Schema validators are not supported.',\n );\n }\n if (result.issues) {\n // Lenient by design (see doc comment) — old/foreign runs shouldn't crash a read path. The `{}`\n // is cast, not `Partial<InferSearchAttributes<S>>`, to keep the common case (destructuring known\n // keys straight off the result) ergonomic; callers reading untrusted history should still treat\n // every field as possibly absent.\n return {} as InferSearchAttributes<S>;\n }\n return result.value as InferSearchAttributes<S>;\n}\n","/**\n * Dependency-injection tokens. Adapters bind their implementations to these so `core` and\n * `@dudousxd/nestjs-durable` depend only on the interfaces in `./interfaces`.\n *\n * These use `Symbol.for(key)` (the global symbol registry), NOT `Symbol(key)`, so the token is the\n * SAME instance no matter how many times `core` is evaluated in a process. A consumer can hold more\n * than one physical copy of `core` at runtime — pnpm peer-dependency multiplexing installs a\n * separate virtual copy per distinct peer set, and the dual ESM/CJS build can be loaded once as\n * `import` (`index.js`) and once as `require` (`index.cjs`). A plain `Symbol()` would mint a\n * DISTINCT token per copy, so `DurableModule` (provider) and `DashboardService` / a store adapter\n * (injector) could resolve different symbols → Nest can't satisfy the dependency\n * (`STATE_STORE is not available in the DurableApiModule context`). A registered symbol collapses\n * them to one. Mirrors the `CONTEXT_ACCESSOR` token in `@dudousxd/nestjs-durable`'s `tokens.ts`.\n */\n\n/**\n * @deprecated Use {@link STATE_STORE_CANONICAL} (`@dudousxd/nestjs-durable:state-store`). The legacy\n * token stays bound as a back-compat alias and still resolves; it will be removed in a future major.\n */\nexport const STATE_STORE = Symbol.for('nestjs-durable:STATE_STORE');\n/**\n * @deprecated Use {@link TRANSPORT_CANONICAL} (`@dudousxd/nestjs-durable:transport`). The legacy\n * token stays bound as a back-compat alias and still resolves; it will be removed in a future major.\n */\nexport const TRANSPORT = Symbol.for('nestjs-durable:TRANSPORT');\n/**\n * @deprecated Use {@link DURABLE_OPTIONS_CANONICAL} (`@dudousxd/nestjs-durable:options`). The legacy\n * token stays bound as a back-compat alias and still resolves; it will be removed in a future major.\n */\nexport const DURABLE_OPTIONS = Symbol.for('nestjs-durable:DURABLE_OPTIONS');\n\n/**\n * Canonical, cross-lib-discoverable aliases of the durable DI tokens, following the ecosystem\n * capability naming `@dudousxd/nestjs-durable:<name>` (identical to `capability('durable', <name>)`).\n * `DurableModule` binds these alongside the legacy tokens (dual-bind), so an external library can\n * resolve durable's store/transport/options by the canonical name without importing durable\n * internals. Bare `Symbol.for` (same cross-copy-stability rationale as the legacy tokens above)\n * keeps `core` free of any `@dudousxd/nestjs-diagnostics` runtime dependency.\n */\nexport const STATE_STORE_CANONICAL = Symbol.for('@dudousxd/nestjs-durable:state-store');\nexport const TRANSPORT_CANONICAL = Symbol.for('@dudousxd/nestjs-durable:transport');\nexport const DURABLE_OPTIONS_CANONICAL = Symbol.for('@dudousxd/nestjs-durable:options');\n","import type {\n RunQuery,\n SignalWaiter,\n StateStore,\n StepCheckpoint,\n WorkflowRun,\n} from '../interfaces';\nimport type { AttributeFilter } from '../interfaces';\nimport { type RunAttributeRow, normalizeAttributeRows } from '../search-attributes';\n\n/**\n * A non-durable, in-process `StateStore` for tests and local development.\n * The shipped `@dudousxd/nestjs-durable-store` package re-exports an equivalent.\n */\nexport class InMemoryStateStore implements StateStore {\n private readonly runs = new Map<string, WorkflowRun>();\n private readonly checkpoints = new Map<string, StepCheckpoint>();\n private readonly signalWaiters = new Map<string, SignalWaiter>();\n\n /**\n * Normalized search-attribute side-table, the in-memory analog of the SQL stores'\n * `durable_run_attributes`: `key -> (runId -> row)`. Maintained on every create/update so an\n * attribute query can be pushed DOWN to a key-indexed candidate set instead of scanning every run\n * and comparing in-process. Mirrors {@link normalizeAttributeRows} so behavior matches the SQL path.\n */\n private readonly attributeIndex = new Map<string, Map<string, RunAttributeRow>>();\n /** Test/observability hook: how many candidate runs the last attribute query's index produced. */\n lastAttributeCandidates = 0;\n /**\n * Test/observability hook: how many checkpoint rows the LAST checkpoint read materialized (the rows\n * actually returned to the caller). `listCheckpoints` returns all rows for the run; the targeted\n * {@link getLatestCheckpointByName} / {@link listCheckpointsByNamePrefix} return only the matches —\n * so this lets the benchmark contrast \"fetch N, scan in JS\" against \"fetch the k that match\".\n */\n lastCheckpointRowsRead = 0;\n\n private key(runId: string, seq: number): string {\n return `${runId}:${seq}`;\n }\n\n /** Drop then re-add a run's normalized attribute rows so the index tracks its current attributes. */\n private reindexAttributes(runId: string, attributes: WorkflowRun['searchAttributes']): void {\n for (const byRun of this.attributeIndex.values()) byRun.delete(runId);\n for (const row of normalizeAttributeRows(runId, attributes)) {\n let byRun = this.attributeIndex.get(row.key);\n if (!byRun) {\n byRun = new Map();\n this.attributeIndex.set(row.key, byRun);\n }\n byRun.set(runId, row);\n }\n }\n\n async createRun(run: WorkflowRun): Promise<void> {\n // Normalize undefined namespace to 'default', matching the SQL stores' column DEFAULT 'default'\n // (interfaces.ts: \"the store persists it as 'default'\"). This ensures legacy runs (created without\n // a namespace, e.g. in tests that bypass the engine) are reachable via a namespace='default' filter.\n this.runs.set(run.id, { ...run, namespace: run.namespace ?? 'default' });\n this.reindexAttributes(run.id, run.searchAttributes);\n }\n\n async updateRun(runId: string, patch: Partial<WorkflowRun>): Promise<void> {\n const existing = this.runs.get(runId);\n if (!existing) throw new Error(`run ${runId} not found`);\n const next = { ...existing, ...patch };\n this.runs.set(runId, next);\n if ('searchAttributes' in patch) this.reindexAttributes(runId, next.searchAttributes);\n }\n\n async getRun(runId: string): Promise<WorkflowRun | null> {\n const run = this.runs.get(runId);\n return run ? { ...run } : null;\n }\n\n async deleteRun(runId: string): Promise<void> {\n this.runs.delete(runId);\n for (const [key, cp] of this.checkpoints) {\n if (cp.runId === runId) this.checkpoints.delete(key);\n }\n for (const [token, waiter] of this.signalWaiters) {\n if (waiter.runId === runId) this.signalWaiters.delete(token);\n }\n // Drop the run's normalized attribute rows (reindex with no attributes clears them).\n this.reindexAttributes(runId, undefined);\n }\n\n async getCheckpoint(runId: string, seq: number): Promise<StepCheckpoint | null> {\n const cp = this.checkpoints.get(this.key(runId, seq));\n return cp ? { ...cp } : null;\n }\n\n async saveCheckpoint(checkpoint: StepCheckpoint): Promise<void> {\n this.checkpoints.set(this.key(checkpoint.runId, checkpoint.seq), { ...checkpoint });\n }\n\n async listIncompleteRuns(namespace?: string): Promise<WorkflowRun[]> {\n return [...this.runs.values()]\n .filter(\n (r) =>\n (r.status === 'running' || r.status === 'cancelling') &&\n (namespace === undefined || r.namespace === namespace),\n )\n .map((r) => ({ ...r }));\n }\n\n async listPendingRuns(limit: number, namespace?: string): Promise<WorkflowRun[]> {\n return [...this.runs.values()]\n .filter(\n (r) => r.status === 'pending' && (namespace === undefined || r.namespace === namespace),\n )\n .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id))\n .slice(0, limit)\n .map((r) => ({ ...r }));\n }\n\n async listDueTimers(nowMs: number, namespace?: string): Promise<WorkflowRun[]> {\n return [...this.runs.values()]\n .filter(\n (r) =>\n r.status === 'suspended' &&\n r.wakeAt !== undefined &&\n r.wakeAt <= nowMs &&\n (namespace === undefined || r.namespace === namespace),\n )\n .map((r) => ({ ...r }));\n }\n\n async tryLockRun(\n runId: string,\n owner: string,\n leaseUntilMs: number,\n nowMs: number,\n ): Promise<boolean> {\n const run = this.runs.get(runId);\n if (!run) return false;\n if (run.lockedUntil !== undefined && run.lockedUntil > nowMs) return false;\n run.lockedBy = owner;\n run.lockedUntil = leaseUntilMs;\n return true;\n }\n\n async releaseRunLock(runId: string): Promise<void> {\n const run = this.runs.get(runId);\n if (run) {\n run.lockedBy = undefined;\n run.lockedUntil = undefined;\n }\n }\n\n async renewRunLock(runId: string, owner: string, leaseUntilMs: number): Promise<boolean> {\n const run = this.runs.get(runId);\n if (!run || run.lockedBy !== owner) return false;\n run.lockedUntil = leaseUntilMs;\n return true;\n }\n\n async putSignalWaiter(waiter: SignalWaiter): Promise<void> {\n this.signalWaiters.set(waiter.token, { ...waiter });\n }\n\n async takeSignalWaiter(token: string): Promise<SignalWaiter | null> {\n const waiter = this.signalWaiters.get(token);\n if (!waiter) return null;\n this.signalWaiters.delete(token);\n return { ...waiter };\n }\n\n async listSignalWaiters(prefix: string): Promise<SignalWaiter[]> {\n return [...this.signalWaiters.values()]\n .filter((w) => w.token.startsWith(prefix))\n .map((w) => ({ ...w }));\n }\n\n async removeSignalWaiter(waiter: SignalWaiter): Promise<void> {\n // Keyed by token only (one row per token) — only delete if the CURRENT row still matches this\n // exact (runId, seq); a later putSignalWaiter for the same token may have already replaced it\n // with a different run's row, which must be left alone.\n const current = this.signalWaiters.get(waiter.token);\n if (current && current.runId === waiter.runId && current.seq === waiter.seq) {\n this.signalWaiters.delete(waiter.token);\n }\n }\n\n // No real DB transaction (there's no DB) — run the work and save the checkpoint. Exactly-once\n // across a crash needs a SQL store; this keeps `ctx.transaction` usable in tests / local dev.\n async transaction<T>(\n work: (tx: {\n raw: unknown;\n saveCheckpoint: (cp: StepCheckpoint) => Promise<void>;\n }) => Promise<T>,\n ): Promise<T> {\n return work({ raw: this, saveCheckpoint: (cp) => this.saveCheckpoint(cp) });\n }\n\n private readonly bufferedSignals = new Map<string, unknown[]>();\n async bufferSignal(token: string, payload: unknown): Promise<void> {\n const queue = this.bufferedSignals.get(token) ?? [];\n queue.push(payload);\n this.bufferedSignals.set(token, queue);\n }\n async takeBufferedSignal(token: string): Promise<{ payload: unknown } | null> {\n const queue = this.bufferedSignals.get(token);\n if (!queue || queue.length === 0) return null;\n const payload = queue.shift();\n if (queue.length === 0) this.bufferedSignals.delete(token);\n return { payload };\n }\n\n /** `id -> row`, so {@link removeBufferedEvent} can delete an exact row regardless of iteration\n * order — mirrors the SQL stores' PK-by-id delete. */\n private readonly bufferedEvents = new Map<\n string,\n { name: string; payload: unknown; publishedAt: number }\n >();\n async bufferEvent(input: {\n name: string;\n payload: unknown;\n id: string;\n publishedAt: number;\n }): Promise<void> {\n this.bufferedEvents.set(input.id, {\n name: input.name,\n payload: input.payload,\n publishedAt: input.publishedAt,\n });\n }\n async listBufferedEvents(\n name: string,\n limit: number,\n ): Promise<Array<{ id: string; payload: unknown; publishedAt: number }>> {\n return [...this.bufferedEvents.entries()]\n .filter(([, e]) => e.name === name)\n .sort((a, b) => a[1].publishedAt - b[1].publishedAt) // oldest first\n .slice(0, limit)\n .map(([id, e]) => ({ id, payload: e.payload, publishedAt: e.publishedAt }));\n }\n async removeBufferedEvent(id: string): Promise<boolean> {\n return this.bufferedEvents.delete(id);\n }\n\n /**\n * Candidate run ids satisfying ONE attribute predicate, served from {@link attributeIndex} — the\n * pushdown step. Numeric predicates scan only `numValue` rows under the key; string/boolean ones\n * scan `strValue` rows. This is the in-memory analog of the SQL EXISTS on `durable_run_attributes`.\n */\n private candidatesForFilter(f: AttributeFilter): Set<string> {\n const byRun = this.attributeIndex.get(f.key);\n const out = new Set<string>();\n if (!byRun) return out;\n const numeric = typeof f.value === 'number';\n const operand = typeof f.value === 'boolean' ? (f.value ? 'true' : 'false') : f.value;\n for (const row of byRun.values()) {\n const actual = numeric ? row.numValue : row.strValue;\n if (actual == null) continue;\n let ok = false;\n switch (f.op) {\n case 'eq':\n ok = actual === operand;\n break;\n case 'ne':\n ok = actual !== operand;\n break;\n case 'gt':\n ok = actual > operand;\n break;\n case 'gte':\n ok = actual >= operand;\n break;\n case 'lt':\n ok = actual < operand;\n break;\n case 'lte':\n ok = actual <= operand;\n break;\n }\n if (ok) out.add(row.runId);\n }\n return out;\n }\n\n async listRuns(query: RunQuery): Promise<WorkflowRun[]> {\n let runs = [...this.runs.values()];\n if (query.workflow) runs = runs.filter((r) => r.workflow === query.workflow);\n if (query.status) runs = runs.filter((r) => r.status === query.status);\n if (query.statuses) runs = runs.filter((r) => query.statuses?.includes(r.status));\n if (query.tag) runs = runs.filter((r) => r.tags?.includes(query.tag as string));\n if (query.namespace !== undefined) runs = runs.filter((r) => r.namespace === query.namespace);\n if (query.attributes?.length) {\n // Pushdown: intersect per-predicate candidate sets from the key-indexed side-table, so we only\n // ever materialize the runs that already satisfy EVERY attribute filter (no full per-run scan).\n let candidates: Set<string> | null = null;\n for (const f of query.attributes) {\n const next = this.candidatesForFilter(f);\n if (candidates == null) {\n candidates = next;\n } else {\n const prev: Set<string> = candidates;\n candidates = new Set([...prev].filter((id) => next.has(id)));\n }\n if (candidates.size === 0) break;\n }\n const ids = candidates ?? new Set<string>();\n this.lastAttributeCandidates = ids.size;\n runs = runs.filter((r) => ids.has(r.id));\n }\n // Newest first (matches the store adapters' `createdAt DESC`) — recent runs on top in the dashboard.\n runs.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());\n const offset = query.offset ?? 0;\n const limit = query.limit ?? runs.length;\n return runs.slice(offset, offset + limit).map((r) => ({ ...r }));\n }\n\n async listCheckpoints(runId: string): Promise<StepCheckpoint[]> {\n const rows = [...this.checkpoints.values()]\n .filter((cp) => cp.runId === runId)\n .sort((a, b) => a.seq - b.seq)\n .map((cp) => ({ ...cp }));\n this.lastCheckpointRowsRead = rows.length;\n return rows;\n }\n\n async getLatestCheckpointByName(\n runId: string,\n name: string,\n ): Promise<StepCheckpoint | undefined> {\n let latest: StepCheckpoint | undefined;\n for (const cp of this.checkpoints.values()) {\n if (cp.runId !== runId || cp.name !== name) continue;\n if (!latest || cp.seq > latest.seq) latest = cp;\n }\n this.lastCheckpointRowsRead = latest ? 1 : 0;\n return latest ? { ...latest } : undefined;\n }\n\n async listCheckpointsByNamePrefix(runId: string, prefixes: string[]): Promise<StepCheckpoint[]> {\n const rows = [...this.checkpoints.values()]\n .filter((cp) => cp.runId === runId && prefixes.some((p) => cp.name.startsWith(p)))\n .sort((a, b) => a.seq - b.seq)\n .map((cp) => ({ ...cp }));\n this.lastCheckpointRowsRead = rows.length;\n return rows;\n }\n}\n","import type {\n ControlMessage,\n ControlPlane,\n Heartbeat,\n RemoteTask,\n StepResult,\n Transport,\n WorkflowStepEvent,\n} from '../interfaces';\nimport { type StepHandler, runStepHandler } from '../protocol';\n\n/**\n * An in-process `Transport` (and `ControlPlane`) for tests and local development: registered\n * handlers stand in for remote workers, so a whole cross-app workflow runs in a single process,\n * and control messages broadcast locally. Pass the same instance as both `transport` and\n * `controlPlane`.\n */\nexport class InMemoryTransport implements Transport, ControlPlane {\n private readonly handlers = new Map<string, StepHandler>();\n private resultHandler?: (result: StepResult) => Promise<void>;\n private heartbeatHandler?: (beat: Heartbeat) => Promise<void>;\n private stepEventHandler?: (event: WorkflowStepEvent) => Promise<void>;\n private readonly controlHandlers = new Set<(msg: ControlMessage) => void>();\n\n /** Register a fake worker handler for a step name. */\n handle(name: string, fn: StepHandler): void {\n this.handlers.set(name, fn);\n }\n\n async dispatch(task: RemoteTask): Promise<void> {\n if (!this.resultHandler) throw new Error('no result handler registered');\n const result = await runStepHandler(task, this.handlers.get(task.name));\n // Deliver the result ASYNCHRONOUSLY, not inline: a durable `ctx.call` suspends the run right\n // after dispatch, so the result must land AFTER that unwinds (else the resume re-enters\n // mid-suspend). Real brokers are async; this mirrors them.\n setImmediate(() => void this.resultHandler?.(result));\n }\n\n onResult(handler: (result: StepResult) => Promise<void>): void {\n this.resultHandler = handler;\n }\n\n onHeartbeat(handler: (beat: Heartbeat) => Promise<void>): void {\n // In-process step handlers run synchronously (no step liveness to track), but a test can drive a\n // RUN-scoped beat via `emitHeartbeat` to exercise the engine's heartbeat-rearmed advance deadline.\n this.heartbeatHandler = handler;\n }\n\n /** Test hook: deliver a liveness heartbeat to the engine, as a real broker would on its channel. */\n async emitHeartbeat(beat: Heartbeat): Promise<void> {\n await this.heartbeatHandler?.(beat);\n }\n\n /** Workflow step lifecycle: deliver to the engine's handler (async, mirroring a real broker). */\n async dispatchStepEvent(event: WorkflowStepEvent): Promise<void> {\n await this.stepEventHandler?.(event);\n }\n\n onStepEvent(handler: (event: WorkflowStepEvent) => Promise<void>): void {\n this.stepEventHandler = handler;\n }\n\n // Control plane: broadcast to every registered handler (including the publisher's own — the\n // engine dedupes by `from`), mirroring how a real broker echoes a publish to all subscribers.\n async publishControl(msg: ControlMessage): Promise<void> {\n for (const handler of this.controlHandlers) handler(msg);\n }\n\n onControl(handler: (msg: ControlMessage) => void): void {\n this.controlHandlers.add(handler);\n }\n}\n"],"mappings":";;;;AAyEO,IAAMA,kBAAN,MAAMA;EAzEb,OAyEaA;;;;;EACHC,WAAW;EACXC,cAAc;EACdC,cAAc;;EAELC,UAAU,oBAAIC,IAAAA;;EAEvBC,YAAY;;EAEHC,YAAY,oBAAIF,IAAAA;EACzBG,aAAa;EAErB,YACWC,QACQC,OACjB;SAFSD,SAAAA;SACQC,QAAAA;EAChB;;EAGH,IAAYC,UAAmB;AAC7B,WAAO,KAAKF,OAAOG,aAAa,SAAS,KAAKH,OAAOI,UAAU;EACjE;;;;;;;;;EAUAC,SAASC,MAAiC;AACxC,UAAMC,MAAM,KAAKN,MAAK;AACtB,UAAMO,KAAK,KAAKR,OAAOS;AAEvB,QAAID,IAAI;AACN,UAAID,MAAM,KAAKd,eAAee,GAAGE,UAAU;AACzC,aAAKjB,cAAcc;AACnB,aAAKb,cAAc;MACrB;AACA,UAAI,KAAK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AA;EAChC;EAEAC,YAAYN,SAA4D;AACtE,SAAKf,mBAAmBe;EAC1B;;;EAIA,MAAMO,eAAeC,KAAoC;AACvD,eAAWR,WAAW,KAAKd,gBAAiBc,SAAQQ,GAAAA;EACtD;EAEAC,UAAUT,SAA8C;AACtD,SAAKd,gBAAgBwB,IAAIV,OAAAA;EAC3B;AACF;","names":["QueueController","inFlight","windowStart","windowCount","waiters","Map","waiterSeq","keyServed","servedTick","config","clock","ordered","fairness","order","tryAdmit","item","now","rl","rateLimit","periodMs","limit","ok","retryAt","usingOrder","priority","waiterId","full","concurrency","register","retryMs","size","isNext","delete","key","set","release","existing","get","seq","self","undefined","Number","POSITIVE_INFINITY","best","w","values","better","a","b","sa","servedOf","sb","InMemoryAdmissionBackend","controllers","Map","clock","register","config","set","name","QueueController","handles","queue","has","tryAdmit","item","controller","get","ok","release","_slotId","AsyncLocalStorage","STORAGE_KEY","Symbol","for","globalRef","globalThis","AsyncLocalStorage","storage","runInWorkflowCtx","ctx","fn","run","currentWorkflowCtx","getStore","CONTROL_FLOW_SIGNAL","Symbol","for","isWorkflowControlFlowSignal","error","FatalError","Error","code","message","name","SingletonQueueFullError","workflow","key","maxQueueDepth","SignalTimeoutError","token","timeoutMs","RemoteStepTimeout","stepId","RemoteWorkflowTimeout","taskId","NonDeterminismError","runId","seq","expected","recorded","GatherError","failures","total","ids","map","f","id","join","denom","length","WorkflowSuspended","wakeAt","CONTROL_FLOW_SIGNAL","ContinueAsNew","input","WORKFLOW_NAME_KEY","Symbol","for","workflowName","ref","name","Error","BINDINGS_KEY","Symbol","for","globalRef","globalThis","WeakMap","bindings","bindWorkflowClass","ctor","client","set","clientOf","get","Error","workflowName","DurableWorkflow","start","input","opts","cls","ctx","currentWorkflowCtx","runId","startChild","id","status","crypto","randomUUID","execute","child","waitForRun","FatalError","settled","timeoutMs","until","output","detail","error","message","code","UNIT_MS","ms","s","sec","second","seconds","m","min","minute","minutes","h","hr","hour","hours","d","day","days","w","week","weeks","parseDuration","duration","match","trim","Error","value","Number","unit","toLowerCase","factor","undefined","backoffDelay","attempt","options","base","backoffMs","raw","backoff","capped","backoffMaxMs","Math","min","jitter","round","random","withDuration","start","now","data","base","durationMs","createStepLogger","events","currentSub","push","level","message","at","subId","id","undefined","subEvent","e","status","phase","name","group","subProcess","body","opts","globalThis","crypto","randomUUID","prevSub","terminal","emit","handle","skip","reason","fail","result","err","Error","String","debug","m","d","info","warn","error","sub","stepId","runId","seq","breakpointToken","runStepHandler","task","handler","base","startedAt","Date","now","status","error","message","name","retryable","events","withEvents","result","length","output","input","createStepLogger","err","e","Error","String","code","nonEmptyEvents","events","length","undefined","stepCheckpoint","p","runId","seq","name","kind","stepId","status","input","output","error","attempts","workerGroup","wakeAt","parallelGroup","enqueuedAt","startedAt","finishedAt","instantCheckpoint","at","Date","ENTITY_WORKFLOW","entityRunId","name","key","Entities","configs","Map","host","register","ctx","input","run","config","set","dispatch","op","arg","reply","runId","signalWithStart","token","payload","signal","getState","getEvent","get","FatalError","state","initialState","i","msg","waitForSignal","out","localStep","handler","handlers","result","setEvent","accToken","target","EventAccumulators","host","register","ctx","input","debounce","batch","route","config","payload","workflow","mode","windowMs","maxSize","signalWithStart","token","last","waitForSignal","timeoutMs","e","SignalTimeoutError","startChild","continueAsNew","events","deadline","now","length","remaining","push","enc","s","Buffer","from","toString","dec","EVENT_BUFFER_SCAN_LIMIT","EVENT_TOKEN_PREFIX","eventPrefix","name","isEventToken","token","startsWith","eventToken","match","runId","seq","JSON","stringify","eventNameOf","split","eventMatchOf","parse","eventMatches","payload","keys","Object","length","p","every","k","tenantGroup","baseGroup","tenant","undefined","sanitizeQueueToken","name","replace","RemoteWorkflowExecutor","transport","name","partition","_opts","dispatch","run","history","taskId","pendingSignals","dispatchWorkflowTask","Error","task","runId","id","workflow","workflowVersion","input","group","tenantGroup","sanitizeQueueToken","priority","attempt","WEBHOOK_PREFIX","CHILD_PREFIX","BREAKPOINT_PREFIX","EVENT_PREFIX","EVENT_TOKEN_PREFIX","classifyWaiterToken","token","startsWith","on","name","slice","length","eventNameOf","resolveRunWaiting","run","waiterByRun","status","undefined","waiter","get","id","indexWaitersByRun","waiters","byRun","Map","w","has","runId","set","SINGLETON_RETRY_MS","SINGLETON_RETRY_JITTER_MS","SingletonGate","deps","tag","cfg","input","key","retryWakeAt","clock","Math","floor","random","assertCapacity","workflow","maxQueueDepth","cap","limit","queued","store","listRuns","statuses","length","SingletonQueueFullError","admit","run","inflight","sort","a","b","createdAt","getTime","id","localeCompare","idx","findIndex","r","wakeNext","settled","configFor","tags","find","t","startsWith","gated","next","slice","wakeAt","updateRun","undefined","updatedAt","Date","catch","dispatch","TransportPool","transports","size","length","primary","first","Error","transport","bind","onResult","onHeartbeat","onStepEvent","onDecision","dispatch","task","preferId","lastErr","id","ordered","err","groupHealth","group","reports","push","undefined","depth","reduce","sum","r","liveWorkers","flatMap","onStartRun","handler","listWorkerGroups","groups","Set","g","add","transportWithLiveGroup","includes","pref","filter","t","unwrapCompletion","payload","label","c","ok","FatalError","error","value","DURABLE_STEP_NAME","Symbol","for","DURABLE_STEP_CONFIG","isStepConfig","value","stepNameOf","ref","undefined","stamped","stepConfigOf","normalizeChildOptions","options","childId","formatIssuePath","path","length","map","segment","String","key","join","resolveStepPolicy","config","opts","policy","retries","undefined","backoff","backoffMs","backoffMaxMs","jitter","timeoutMs","Position","seq","next","rewind","createWorkflowCtx","host","runId","compensations","workflow","searchAttributesSchema","store","replay","pos","readCheckpoint","hit","get","getCheckpoint","writeCheckpoint","cp","saveCheckpoint","set","localStep","name","fn","current","existing","NonDeterminismError","status","compensate","push","output","maxAttempts","Math","max","startedAt","Date","startStep","kind","attempts","enqueuedAt","attempt","events","invocation","stepName","body","createStepLogger","clock","interceptStep","completeStep","err","FatalError","failStep","error","message","Error","stack","wait","backoffDelay","Promise","resolve","setTimeout","transaction","tx","raw","instantCheckpoint","suspendUntil","wakeAt","now","WorkflowSuspended","at","sleep","duration","parseDuration","sleepUntil","when","getTime","continueAsNew","input","ContinueAsNew","consumeBuffered","token","buffered","takeBufferedSignal","payload","value","consumeBufferedEvent","match","candidates","listBufferedEvents","EVENT_BUFFER_SCAN_LIMIT","candidate","eventMatches","removeBufferedEvent","id","removeSignalWaiter","stampDeadline","deadlineSeq","label","recorded","deadline","waitForSignal","putSignalWaiter","lateBuffered","waitSeq","waited","catch","SignalTimeoutError","waitForEvent","eventToken","bufferedHit","task","dispatch","unwrapCompletion","child","priority","getRun","startChild","workflowName","all","inputs","mode","positions","group","i","c","ok","j","cancelChild","GatherError","index","pending","parallelGroup","outputs","failures","callEntity","op","arg","reply","signalEntity","breakpoint","breakpointToken","patched","marker","startsWith","onUpdate","setEvent","webhook","takeSignalWaiter","url","webhookUrl","sideEffect","upsertSearchAttributes","attrs","run","merged","searchAttributes","result","validate","issues","offendingKeys","Set","issue","details","resolveCompensateDef","stepNameOf","stepConfigOf","step","handlerOrName","def","callRemote","queue","transport","fairnessKey","then","args","mergeTags","staticTags","runTags","length","undefined","Set","BREAKPOINT","isBreakpoint","cp","status","name","startsWith","versionKey","version","nextContinuationId","runId","m","match","Number","isNewerVersion","a","b","na","nb","isNaN","localeCompare","numeric","NamespaceMismatch","Error","WorkflowEngine","store","pool","controlPlane","clock","instanceId","namespace","leaseMs","maxRecoveryAttempts","remoteAdvanceSilenceMs","reconcileMs","eventBufferTtlMs","remoteRedispatchMs","remoteRedispatchMax","webhookUrl","traceparent","context","rehydrate","compensationRetries","trackStepStart","runDispatcher","singletons","workflows","Map","latest","eventTriggers","entities","accumulators","pending","heartbeatResets","listeners","interceptors","cancelListeners","enqueuedListeners","deadListeners","updateValidators","cancelRequested","admission","queueWaiters","stepQueue","inflight","draining","deps","TransportPool","transports","transport","id","Date","now","InMemoryAdmissionBackend","onFreed","queue","wakeQueueWaiters","globalThis","crypto","randomUUID","Math","max","_carrier","fn","dispatch","queueMicrotask","runOne","catch","SingletonGate","configFor","run","get","workflow","workflowVersion","singleton","bind","result","waiter","stepId","delete","resolve","output","startedAt","events","reject","RemoteStepError","error","completeRemoteResult","beat","reset","rearmDecisionDeadline","event","persistStepEvent","decision","completeRemoteDecision","onStartRun","message","start","input","tenant","tags","searchAttributes","onControl","msg","from","kind","deliver","at","notifyCancelled","EventAccumulators","Entities","registerEntity","config","register","signalEntity","key","op","arg","signal","getEntityState","getState","onEnqueued","listener","add","opts","group","executor","registered","executionTimeoutMs","executionTimeout","parseDuration","validateInput","searchAttributesSchema","onEvent","eventBatch","hasBody","remote","set","current","subscribers","workflowBody","reg","registerRemote","rest","RemoteWorkflowExecutor","primary","registerQueue","subscribe","use","interceptor","push","i","indexOf","splice","interceptStep","invocation","body","carrier","chain","reduceRight","next","onCancel","onDead","notifyDead","emit","full","publishControl","workflowName","ancestor","findRemoteAncestor","synthesizeRemoteChild","conventionRun","createdAt","updatedAt","resolveRemoteByConvention","prior","getRun","tag","assertCapacity","priority","createRun","resume","releaseRunLock","findInheritedRegistration","track","execute","tenantGroup","sanitizeQueueToken","liveTransport","transportWithLiveGroup","childRunId","visited","has","parentRunId","findParentRunId","parent","parentReg","token","listSignalWaiters","p","finally","drain","timeoutMs","size","timer","Promise","t","setTimeout","unref","race","allSettled","sweepTimeouts","values","deadline","listRuns","getTime","code","updateRun","type","recoverIncomplete","nowMs","results","listIncompleteRuns","acquired","tryLockRun","settled","countRecovery","attempts","recoveryAttempts","resumeDueTimers","due","listDueTimers","waiterByRun","indexWaitersByRun","resumeLeased","reconcileSignalWaiter","isEventToken","reconcileBufferedEvent","buffered","takeBufferedSignal","removeSignalWaiter","deliverSignal","payload","eventNameOf","eventMatchOf","candidates","listBufferedEvents","EVENT_BUFFER_SCAN_LIMIT","candidate","publishedAt","removeBufferedEvent","eventMatches","err","requeue","redispatchPending","listCheckpoints","filter","redispatched","reAttempt","reEnqueuedAt","saveCheckpoint","enqueuedAt","finishedAt","dispatchRemoteTask","seq","workerGroup","attempt","retryWithInput","newRunId","slice","runPending","listPendingRuns","waitForRun","TERMINAL","isSettled","until","awaitingDecisionTaskId","toResult","done","off","poller","clearInterval","finish","clearTimeout","check","then","interval","setInterval","ev","runs","onLocked","publishEvent","touched","waiters","eventPrefix","w","eventId","batch","route","buffer","bufferedId","bufferEvent","lateWaiters","lateWaiter","find","takeSignalWaiter","instantCheckpoint","parallelGroup","bufferSignal","reclaimed","signalWithStart","completeTask","ok","value","failTask","notifyParent","completion","startChildDeferred","childId","String","cancel","compensate","cancelChildren","wakeNext","cancelWhere","r","deleteRun","deleted","getRunChildren","childIds","prefixes","childCheckpoints","listCheckpointsByNamePrefix","some","knownGroups","extra","groups","def","workerHealth","listWorkerGroups","workflowTokens","out","health","groupHealth","lastIndexOf","baseToken","phase","stepCheckpoint","failed","startStep","step","completeStep","queueMs","durationMs","failStep","lockNow","lockedBy","lockedUntil","renew","renewRunLock","floor","runRemoteExecution","runExecution","settleRun","outcome","wakeAt","reconcileWakeAt","admit","retryWakeAt","history","remoteHistory","taskId","silenceMs","advanceExecutor","advance","call","awaitWithLivenessDeadline","RemoteWorkflowTimeout","stack","applyDecision","applyCommands","commands","fresh","checkpoints","kindOf","local","sleep","sort","cmd","getCheckpoint","ms","min","deliverBuffered","putSignalWaiter","lateBuffered","compensateAndCancel","compensations","replay","unwindCompensations","snapshot","ctx","createWorkflowCtx","ctxHostFor","runInWorkflowCtx","ContinueAsNew","nextId","WorkflowSuspended","comp","existing","runCompensation","dispatchCompensation","args","maxAttempts","retries","retryable","backoffDelay","withWakeAt","dispatchCompensationAttempt","partition","parentNamespace","s","callRemote","startChild","cancelChild","upsertSearchAttributes","attrs","reply","continue","bp","breakpointToken","getEvent","getLatestCheckpointByName","registerUpdateValidator","validate","update","accepted","reason","NonDeterminismError","callRemoteInMemory","nextDeadline","handles","tryAdmit","fairnessKey","waiterId","retryAt","task","releaseQueueSlot","runIds","clear","release","validInput","parse","resultPromise","resolution","awaitWithHeartbeat","RemoteStepTimeout","onTimeout","cleanup","arm","stepError","TERMINAL_RUN_STATUSES","CodecStateStore","inner","codec","enc","v","undefined","encode","dec","decode","encRun","run","input","output","decRun","encCp","cp","decCp","ensureSchema","Promise","resolve","createRun","updateRun","runId","patch","next","getRun","deleteRun","getCheckpoint","seq","saveCheckpoint","checkpoint","transaction","work","Error","tx","raw","listIncompleteRuns","namespace","map","r","listPendingRuns","limit","listDueTimers","nowMs","tryLockRun","owner","leaseUntilMs","releaseRunLock","renewRunLock","putSignalWaiter","waiter","takeSignalWaiter","token","listSignalWaiters","prefix","removeSignalWaiter","bufferSignal","payload","takeBufferedSignal","buffered","bufferEvent","listBufferedEvents","name","events","e","removeBufferedEvent","id","listRuns","query","listCheckpoints","c","getLatestCheckpointByName","latest","listCheckpointsByNamePrefix","prefixes","matches","filter","some","p","startsWith","collectMetrics","engine","m","runs","started","completed","failed","suspended","steps","byWorkflow","stepDuration","sumMs","count","wf","name","k","entry","stop","subscribe","e","type","workflow","durationMs","snapshot","structuredClone","prometheus","lines","push","v","Object","entries","event","n","join","createRequire","nodeRequire","createRequire","url","defaultSleep","ms","Promise","r","setTimeout","scheduledRunId","key","everyMs","nowMs","Math","floor","cronParser","loadCronParser","Error","prevCronFireMs","expr","timezone","parser","it","parseExpression","currentDate","Date","tz","prev","toDate","getTime","scheduleRunIdAt","s","cron","scheduleRunIdsAt","current","backfill","maxCatchup","ids","bucket","oldest","max","b","push","prior","cursor","i","before","reverse","runSchedules","engine","schedules","opts","random","sleep","paused","overlap","prevBucket","getRun","status","jitter","runId","start","workflow","input","compare","actual","op","expected","matchesAttributes","attributes","filters","length","every","f","key","value","applyAttributeQuery","rows","query","filtered","filter","r","searchAttributes","offset","limit","slice","normalizeAttributeRows","runId","out","Object","entries","push","strValue","numValue","sqlComparator","attributeColumnFor","attributeOperand","readSearchAttributes","schema","run","result","validate","searchAttributes","Promise","Error","issues","value","STATE_STORE","Symbol","for","TRANSPORT","DURABLE_OPTIONS","STATE_STORE_CANONICAL","TRANSPORT_CANONICAL","DURABLE_OPTIONS_CANONICAL","InMemoryStateStore","runs","Map","checkpoints","signalWaiters","attributeIndex","lastAttributeCandidates","lastCheckpointRowsRead","key","runId","seq","reindexAttributes","attributes","byRun","values","delete","row","normalizeAttributeRows","get","set","createRun","run","id","namespace","searchAttributes","updateRun","patch","existing","Error","next","getRun","deleteRun","cp","token","waiter","undefined","getCheckpoint","saveCheckpoint","checkpoint","listIncompleteRuns","filter","r","status","map","listPendingRuns","limit","sort","a","b","createdAt","getTime","localeCompare","slice","listDueTimers","nowMs","wakeAt","tryLockRun","owner","leaseUntilMs","lockedUntil","lockedBy","releaseRunLock","renewRunLock","putSignalWaiter","takeSignalWaiter","listSignalWaiters","prefix","w","startsWith","removeSignalWaiter","current","transaction","work","raw","bufferedSignals","bufferSignal","payload","queue","push","takeBufferedSignal","length","shift","bufferedEvents","bufferEvent","input","name","publishedAt","listBufferedEvents","entries","e","removeBufferedEvent","candidatesForFilter","f","out","Set","numeric","value","operand","actual","numValue","strValue","ok","op","add","listRuns","query","workflow","statuses","includes","tag","tags","candidates","prev","has","size","ids","offset","listCheckpoints","rows","getLatestCheckpointByName","latest","listCheckpointsByNamePrefix","prefixes","some","p","InMemoryTransport","handlers","Map","resultHandler","heartbeatHandler","stepEventHandler","controlHandlers","Set","handle","name","fn","set","dispatch","task","Error","result","runStepHandler","get","setImmediate","onResult","handler","onHeartbeat","emitHeartbeat","beat","dispatchStepEvent","event","onStepEvent","publishControl","msg","onControl","add"]}
1
+ {"version":3,"sources":["../src/queue.ts","../src/admission.ts","../src/ambient-ctx.ts","../src/control-flow-signal.ts","../src/errors.ts","../src/workflow-ref.ts","../src/durable-workflow.ts","../src/duration.ts","../src/backoff.ts","../src/step-logger.ts","../src/protocol.ts","../src/checkpoints.ts","../src/entities.ts","../src/event-accumulators.ts","../src/events.ts","../src/tenant-group.ts","../src/remote-workflow-executor.ts","../src/run-waiting.ts","../src/singleton-gate.ts","../src/transport-pool.ts","../src/completion.ts","../src/step-name-symbol.ts","../src/workflow-ctx.ts","../src/engine.ts","../src/interfaces.ts","../src/codec-state-store.ts","../src/metrics.ts","../src/scheduler.ts","../src/search-attributes.ts","../src/search-attributes-schema.ts","../src/tokens.ts","../src/testing/in-memory-state-store.ts","../src/testing/in-memory-transport.ts"],"sourcesContent":["/**\n * Flow control for dispatched steps. A queue caps how much work `ctx.step(step, input, { queue })`\n * admits at once — a concurrency limit and/or a fixed-window rate limit. When a call can't be\n * admitted it doesn't dispatch: the run re-suspends with a near-future wake time, and the timer\n * poller re-tries admission later — so flow control is durable (survives crashes) without holding\n * the run in memory.\n *\n * Accounting is per engine instance (the DBOS `workerConcurrency` tier): correct for the common\n * single-orchestrator deployment. Global, cross-instance limits would need a durable counter in the\n * store — a deliberate follow-up, not built here.\n *\n * Beyond raw caps, the controller can admit contended slots by PRIORITY and by per-KEY FAIRNESS\n * (round-robin), so a single noisy key/tenant can't monopolize the concurrency budget. This is the\n * DISPATCH/admission layer — it never touches workflow replay (engine positional logic). Default\n * behaviour is unchanged FIFO when neither priority nor fairness is configured/passed.\n *\n * Design (vs Temporal/Inngest/DBOS): Temporal task queues are FIFO with separate priority levels;\n * Inngest concurrency keys + throttle give per-key fairness; DBOS queues are FIFO with a\n * `workerConcurrency` cap. We fold both knobs into the same in-process admission gate: an optional\n * per-call `priority` (higher first) and an optional queue-level `fairness: 'key'` (round-robin by\n * the per-call `key`). Because blocked calls re-suspend durably and retry independently (there is no\n * resident FIFO list to reorder), the controller remembers the set of WAITERS that asked-and-were-\n * blocked, and on a later retry only admits the one that is rightful-next under the policy.\n */\nexport interface QueueConfig {\n /** Queue name, referenced by `ctx.step(step, input, { queue: name })`. */\n name: string;\n /** Max steps in flight at once for this queue (this instance). Omit for unlimited. */\n concurrency?: number;\n /** Fixed-window rate limit: at most `limit` admissions per `periodMs`. Omit for unlimited. */\n rateLimit?: { limit: number; periodMs: number };\n /** Delay (ms) before a concurrency-blocked call re-checks for a free slot. Default 1000. */\n retryMs?: number;\n /**\n * Fairness policy for a contended concurrency slot. `'key'` round-robins across distinct per-call\n * keys (the least-recently-served key wins the next slot), so one key can't monopolize the budget.\n * Omit (or `'fifo'`) for plain first-come ordering. Priority always wins over fairness; fairness\n * only breaks ties within the same priority.\n */\n fairness?: 'fifo' | 'key';\n /**\n * Arrival-order tiebreak among otherwise-equal waiters (same priority, same fairness rank).\n * `'fifo'` (default) admits the earliest arrival; `'lifo'` admits the most recent (a stack). Orthogonal\n * to `priority` and `fairness` — those still win first; this only breaks their ties.\n */\n order?: 'fifo' | 'lifo';\n}\n\n/**\n * Per-call admission hints. All optional — omitting them keeps the legacy FIFO behaviour.\n * - `priority`: higher is admitted first (default 0).\n * - `key`: the fairness bucket (e.g. a tenant id) for `fairness: 'key'`.\n * - `waiterId`: a stable id for THIS call across its retries (the engine passes the stepId), so the\n * controller can track it as one waiter instead of counting each retry as a new contender.\n */\nexport interface AdmissionItem {\n priority?: number | undefined;\n key?: string | undefined;\n waiterId?: string | undefined;\n}\n\n/** Admission decision: either admitted, or blocked until `retryAt` (epoch ms). */\nexport type Admission = { ok: true } | { ok: false; retryAt: number };\n\n/** A call that asked for a slot and was blocked — remembered so the controller can order admission. */\ninterface Waiter {\n priority: number;\n key?: string | undefined;\n /** Monotonic registration order — FIFO tiebreak within equal priority/fairness. */\n seq: number;\n}\n\n/** In-process admission controller for one {@link QueueConfig}. */\nexport class QueueController {\n private inFlight = 0;\n private windowStart = 0;\n private windowCount = 0;\n /** Registered waiters by id (only used when priority/fairness ordering is in play). */\n private readonly waiters = new Map<string, Waiter>();\n /** Monotonic counter stamping each newly-seen waiter for a stable FIFO tiebreak. */\n private waiterSeq = 0;\n /** Per-key \"last served\" order for round-robin fairness — higher = more recently served. */\n private readonly keyServed = new Map<string, number>();\n private servedTick = 0;\n\n constructor(\n readonly config: QueueConfig,\n private readonly clock: () => number,\n ) {}\n\n /** Whether this controller does any priority/fairness ordering (else it's a plain FIFO gate). */\n private get ordered(): boolean {\n return this.config.fairness === 'key' || this.config.order === 'lifo';\n }\n\n /**\n * Try to admit one unit of work. On `ok`, the caller has taken a concurrency slot and must call\n * {@link release} when the step settles. On block, `retryAt` is when admission may next succeed.\n *\n * `item` carries optional priority/fairness hints; omitting it is the legacy FIFO path. When\n * ordering is configured (or a priority is given), a blocked call REGISTERS as a waiter and is only\n * admitted on a later retry once it is the rightful next under (priority desc, fairness, FIFO).\n */\n tryAdmit(item?: AdmissionItem): Admission {\n const now = this.clock();\n const rl = this.config.rateLimit;\n // Rate limit is a hard global window — checked first and unaffected by priority/fairness.\n if (rl) {\n if (now - this.windowStart >= rl.periodMs) {\n this.windowStart = now;\n this.windowCount = 0;\n }\n if (this.windowCount >= rl.limit)\n return { ok: false, retryAt: this.windowStart + rl.periodMs };\n }\n\n const usingOrder = this.ordered || item?.priority != null || item?.waiterId != null;\n const waiterId = item?.waiterId;\n\n // Concurrency gate.\n const full = this.config.concurrency != null && this.inFlight >= this.config.concurrency;\n if (full) {\n // No slot at all → block (and register as a waiter so a later retry can be ordered).\n if (usingOrder && waiterId != null) this.register(waiterId, item);\n return { ok: false, retryAt: now + (this.config.retryMs ?? 1000) };\n }\n\n // A slot is free. Without ordering, admit immediately (legacy FIFO). With ordering, only admit if\n // THIS call is the rightful next among all registered waiters — otherwise keep it waiting so the\n // freed slot can go to a higher-priority / under-served key on its retry.\n if (usingOrder && this.waiters.size > 0) {\n if (waiterId != null) this.register(waiterId, item);\n if (!this.isNext(waiterId, item)) {\n return { ok: false, retryAt: now + (this.config.retryMs ?? 1000) };\n }\n }\n\n // Admit: consume the slot, the rate-window tick, and clear this waiter.\n if (rl) this.windowCount += 1;\n this.inFlight += 1;\n if (waiterId != null) this.waiters.delete(waiterId);\n if (item?.key != null) this.keyServed.set(item.key, ++this.servedTick);\n return { ok: true };\n }\n\n /** Release a concurrency slot taken by a successful {@link tryAdmit}. */\n release(): void {\n if (this.inFlight > 0) this.inFlight -= 1;\n }\n\n /** Track (or refresh) a blocked call as a waiter; its FIFO seq is stamped only on first sight. */\n private register(waiterId: string, item?: AdmissionItem): void {\n const existing = this.waiters.get(waiterId);\n if (existing) {\n existing.priority = item?.priority ?? 0;\n existing.key = item?.key;\n return;\n }\n this.waiters.set(waiterId, {\n priority: item?.priority ?? 0,\n key: item?.key,\n seq: this.waiterSeq++,\n });\n }\n\n /**\n * Is the calling item the best candidate among all registered waiters? Ordering, best first:\n * 1. higher `priority`;\n * 2. fairness: with `fairness: 'key'`, the least-recently-served key wins (round-robin);\n * 3. earliest registration (FIFO) — stable tiebreak.\n * A bare item (no waiterId) is compared on its hints directly.\n */\n private isNext(waiterId: string | undefined, item?: AdmissionItem): boolean {\n const self: Waiter =\n (waiterId != null ? this.waiters.get(waiterId) : undefined) ??\n ({ priority: item?.priority ?? 0, key: item?.key, seq: Number.POSITIVE_INFINITY } as Waiter);\n let best = self;\n for (const w of this.waiters.values()) {\n if (this.better(w, best)) best = w;\n }\n return best === self;\n }\n\n /** Strict \"a should be admitted before b\" comparison under the active policy. */\n private better(a: Waiter, b: Waiter): boolean {\n if (a.priority !== b.priority) return a.priority > b.priority;\n if (this.config.fairness === 'key') {\n const sa = this.servedOf(a.key);\n const sb = this.servedOf(b.key);\n if (sa !== sb) return sa < sb; // least-recently-served key first\n }\n return this.config.order === 'lifo' ? a.seq > b.seq : a.seq < b.seq; // arrival tiebreak\n }\n\n /** Last-served tick for a key (0 = never served, so an unseen key is admitted before a busy one). */\n private servedOf(key?: string): number {\n if (key == null) return 0;\n return this.keyServed.get(key) ?? 0;\n }\n}\n","import { type Admission, type AdmissionItem, type QueueConfig, QueueController } from './queue';\n\n/**\n * Pluggable backend for the step flow-control gate (`ctx.step(step, input, { queue })`). The\n * engine asks it whether a queued call may be admitted now (concurrency / rate / ordering) and tells\n * it when an admitted slot is released.\n *\n * The default {@link InMemoryAdmissionBackend} keeps per-instance counts — correct for a single\n * orchestrator. Swap in a store/Redis-backed backend to make the caps and ordering GLOBAL across\n * engine replicas (so `concurrency: 5` means 5 in-flight across the whole fleet, not 5 per pod).\n *\n * `tryAdmit`/`release` are async so a global backend can do its atomic round-trip; the in-memory one\n * resolves synchronously. An UNREGISTERED queue name is treated as ungated (admits immediately) — the\n * engine only tracks/releases a slot for a registered queue.\n */\nexport interface AdmissionBackend {\n /** Register (or replace) a queue's config. Called from `engine.registerQueue`. */\n register(config: QueueConfig): void;\n /** Whether `queue` is registered (gated). The engine only tracks/releases a slot for a gated queue. */\n handles(queue: string): boolean;\n /** May a call on `queue` take a slot now? On `ok`, the caller holds a slot until {@link release}. */\n tryAdmit(queue: string, item: AdmissionItem): Promise<Admission>;\n /**\n * Release the slot granted by {@link tryAdmit} for `queue`. `slotId` is the admitted item's\n * `waiterId` (the engine's stepId), so a lease-based backend can drop the exact slot; an in-process\n * counter ignores it.\n */\n release(queue: string, slotId: string): Promise<void>;\n /**\n * Optional: subscribe to \"a slot just freed on `queue`\" events (e.g. a fleet-wide pub/sub). The\n * engine uses it to wake its admission-blocked runs early instead of waiting for their retry tick.\n * A backend without it falls back to retry-tick polling. Fired best-effort across the fleet.\n */\n onFreed?(handler: (queue: string) => void): void;\n}\n\n/**\n * Default admission backend: one in-process {@link QueueController} per registered queue. Caps and\n * waiter ordering are per engine instance (see {@link QueueConfig}). Preserves the exact pre-backend\n * behaviour — the engine used to hold these controllers directly.\n */\nexport class InMemoryAdmissionBackend implements AdmissionBackend {\n private readonly controllers = new Map<string, QueueController>();\n\n constructor(private readonly clock: () => number) {}\n\n register(config: QueueConfig): void {\n this.controllers.set(config.name, new QueueController(config, this.clock));\n }\n\n handles(queue: string): boolean {\n return this.controllers.has(queue);\n }\n\n async tryAdmit(queue: string, item: AdmissionItem): Promise<Admission> {\n const controller = this.controllers.get(queue);\n // Unregistered queue → ungated (mirrors the old `this.queues.get(queue)` truthiness check).\n if (!controller) return { ok: true };\n return controller.tryAdmit(item);\n }\n\n async release(queue: string, _slotId: string): Promise<void> {\n this.controllers.get(queue)?.release();\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { WorkflowCtx } from './interfaces';\n\n/**\n * The ambient workflow context: an `AsyncLocalStorage` the engine (and the thin worker runtime)\n * installs around every execution of a workflow body, so code running ON the body's async path can\n * discover the live {@link WorkflowCtx} without threading it through — the mechanism behind the\n * class-first `MyWorkflow.start()` / `MyWorkflow.execute()` statics (see `durable-workflow.ts`).\n *\n * One storage per PROCESS, not per copy of this package: stashed on `globalThis` under a\n * `Symbol.for` key, so a dependency tree carrying duplicate copies of core still shares the same\n * ambient context (the same duplicate-copy trap the DI tokens guard against — see `tokens.ts`).\n */\nconst STORAGE_KEY = Symbol.for('nestjs-durable:ambient-workflow-ctx');\n\ntype GlobalWithStorage = typeof globalThis & {\n [STORAGE_KEY]?: AsyncLocalStorage<WorkflowCtx>;\n};\n\nconst globalRef = globalThis as GlobalWithStorage;\nif (!globalRef[STORAGE_KEY]) {\n globalRef[STORAGE_KEY] = new AsyncLocalStorage<WorkflowCtx>();\n}\nconst storage: AsyncLocalStorage<WorkflowCtx> = globalRef[STORAGE_KEY];\n\n/**\n * Run `fn` with `ctx` as the ambient workflow context. Engine-internal: wraps every execution of a\n * workflow body (first run and every replay), so ambient reads inside the body see the SAME ctx the\n * body received.\n */\nexport function runInWorkflowCtx<T>(ctx: WorkflowCtx, fn: () => T): T {\n return storage.run(ctx, fn);\n}\n\n/**\n * The {@link WorkflowCtx} of the workflow body currently executing on this async path — or\n * `undefined` outside one. Note a `@Step` HANDLER runs on a worker, off the body's path: it has no\n * ambient workflow context (by design — a handler is not the workflow body).\n */\nexport function currentWorkflowCtx(): WorkflowCtx | undefined {\n return storage.getStore();\n}\n","/**\n * Cross-package, cross-runtime marker for engine CONTROL-FLOW signals — {@link WorkflowSuspended}\n * and {@link ContinueAsNew} (this package), plus the thin worker's {@link\n * import('@dudousxd/durable-worker').Suspend} (`@dudousxd/durable-worker`, the BullMQ\n * route-by-handler runtime). These are thrown by `WorkflowCtx`/`WorkflowContext` ops to unwind the\n * current turn — never real failures — so a workflow's `catch` block MUST rethrow them untouched.\n * Running a failure/cleanup path on a control-flow signal corrupts the run: it emits extra\n * `recordStep` commands into history that a subsequent replay didn't produce the first time,\n * surfacing as a `NonDeterminismError`/`NondeterminismError` on resume.\n *\n * `Symbol.for` (the GLOBAL registry), NOT a plain `Symbol()` — so a duplicate copy of this module\n * (pnpm peer-dependency multiplexing, a dual ESM/CJS load, or the SEPARATE `@dudousxd/durable-worker`\n * package declaring the same `Symbol.for` key locally) still collapses onto the SAME symbol. Same\n * rationale as `DURABLE_STEP_NAME` in `./step-name-symbol.ts`.\n *\n * Deliberately checked as a stamped property, NOT `instanceof` — `instanceof` only recognizes a\n * signal thrown by the SAME class the checking code imported, which fails across the in-process\n * engine (`@dudousxd/nestjs-durable-core`'s `WorkflowSuspended`/`ContinueAsNew`) and the thin worker\n * (`@dudousxd/durable-worker`'s `Suspend`) — two different classes for what is, from a workflow\n * author's catch block, the same \"this isn't a real error, let it through\" event.\n *\n * NOT designed to survive a serialization boundary (e.g. JSON over the wire) — these signals are\n * always thrown and caught in-process within a single replay turn, never (de)serialized, so a\n * stamped-but-not-cloneable property is sufficient.\n */\nexport const CONTROL_FLOW_SIGNAL = Symbol.for('aviary:durable:control-flow');\n\n/**\n * True for any engine control-flow signal (currently: {@link WorkflowSuspended}, {@link\n * ContinueAsNew}, and the thin worker's `Suspend`) — regardless of which runtime or module instance\n * threw it. Workflow `catch` blocks MUST rethrow these untouched; running a failure/cleanup path on\n * one corrupts the run's history (extra commands recorded during what replay will later see as a\n * suspend, not a failure) and the resumed replay dies with a non-determinism error.\n *\n * Deliberately NOT control-flow (do not add to this predicate):\n * - `Cancelled` (worker) / a cancelled run — a TERMINAL outcome the consumer may legitimately want\n * to observe and react to (e.g. release a lock), not a mid-turn unwind to rethrow untouched.\n * - `StepFailed` (worker) / an awaited step rejection reaching the engine — a REAL failure a\n * workflow's `catch` is meant to compensate for; misclassifying it as control-flow would swallow\n * genuine errors instead of protecting them.\n *\n * @example\n * ```ts\n * try {\n * await ctx.step('chargeCard', input);\n * } catch (error) {\n * if (isWorkflowControlFlowSignal(error)) throw error; // suspend/continue-as-new: rethrow as-is\n * await ctx.step('refund', input); // a REAL failure — safe to run cleanup here\n * throw error;\n * }\n * ```\n */\nexport function isWorkflowControlFlowSignal(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as { [CONTROL_FLOW_SIGNAL]?: unknown })[CONTROL_FLOW_SIGNAL] === true\n );\n}\n","import { CONTROL_FLOW_SIGNAL, type isWorkflowControlFlowSignal } from './control-flow-signal';\n\n/**\n * Thrown inside a step to signal an unrecoverable failure: the engine will NOT retry it,\n * regardless of the step's `retries` setting, and fails the run immediately. Use it for\n * business errors that retrying cannot fix (e.g. a declined card, invalid input).\n */\nexport class FatalError extends Error {\n readonly code?: string | undefined;\n constructor(message: string, code?: string) {\n super(message);\n this.name = 'FatalError';\n this.code = code;\n }\n}\n\n/**\n * Thrown by `start` when a singleton workflow's wait queue is full: the count of in-flight + gated\n * runs sharing the key already equals `limit + maxQueueDepth`, so admitting another would let the\n * same-key backlog grow unbounded. Back-pressure — the caller should retry later or shed load. Only\n * raised when {@link SingletonConfig.maxQueueDepth} is set (omit it for the old unbounded behavior).\n */\nexport class SingletonQueueFullError extends Error {\n readonly workflow: string;\n readonly key: string;\n readonly maxQueueDepth: number;\n constructor(workflow: string, key: string, maxQueueDepth: number) {\n super(\n `singleton queue for ${workflow} key \"${key}\" is full (maxQueueDepth=${maxQueueDepth}); retry later`,\n );\n this.name = 'SingletonQueueFullError';\n this.workflow = workflow;\n this.key = key;\n this.maxQueueDepth = maxQueueDepth;\n }\n}\n\n/**\n * Internal control signal thrown to suspend a run (e.g. on a durable sleep). Not an error the\n * user should throw or catch; the engine uses it to stop execution and persist `wakeAt`.\n */\nexport class SignalTimeoutError extends Error {\n readonly token: string;\n readonly timeoutMs: number;\n constructor(token: string, timeoutMs: number) {\n super(`timed out after ${timeoutMs}ms waiting for signal \"${token}\"`);\n this.name = 'SignalTimeoutError';\n this.token = token;\n this.timeoutMs = timeoutMs;\n }\n}\n\n/**\n * Thrown when a remote step produces no result and no heartbeat within its `timeoutMs` window —\n * i.e. the worker is presumed dead. Subject to the step's `retries` (it's retryable), so the engine\n * re-dispatches before giving up.\n */\nexport class RemoteStepTimeout extends Error {\n readonly stepId: string;\n readonly timeoutMs: number;\n constructor(stepId: string, timeoutMs: number) {\n super(`remote step ${stepId} produced no result/heartbeat within ${timeoutMs}ms`);\n this.name = 'RemoteStepTimeout';\n this.stepId = stepId;\n this.timeoutMs = timeoutMs;\n }\n}\n\n/**\n * Thrown by a remote {@link WorkflowExecutor} (e.g. {@link RemoteWorkflowExecutor}) when an `advance`\n * does not produce its decision within the configured `timeoutMs` — i.e. the worker is presumed gone\n * (the decision was dropped by a stall/redelivery or an instance restart spanning the in-memory waiter\n * map). Crucially this is NOT a run failure: the work may have actually completed and only the decision\n * was lost. The engine treats it as RECOVERABLE — it releases the run lease and leaves the run\n * `running` so `recoverIncomplete` re-drives it deterministically (replaying completed steps from\n * history). Distinct from a real executor error, which still fails the run.\n *\n * OPT-IN: only thrown when the executor was constructed with a `timeoutMs`. Absent a timeout, the\n * engine awaits the decision with its prior (unbounded) behavior — so existing users see no change.\n *\n * Known hazard: a timeout that fires while a worker is LEGITIMATELY still executing a not-yet-\n * checkpointed step will re-drive and re-run that in-flight step → DUPLICATE side effects. Therefore\n * the timeout is only safe when set GENEROUSLY (longer than the longest legitimate single turn). The\n * robust fix — a liveness/heartbeat-rearmed deadline so only a genuinely-dead worker re-drives — is the\n * documented follow-up (see the Track A diagnosis doc, \"Part B\").\n */\nexport class RemoteWorkflowTimeout extends Error {\n readonly taskId: string;\n readonly timeoutMs: number;\n constructor(taskId: string, timeoutMs: number) {\n super(\n `remote workflow task ${taskId} produced no decision within ${timeoutMs}ms — presumed dropped; re-driving via recovery`,\n );\n this.name = 'RemoteWorkflowTimeout';\n this.taskId = taskId;\n this.timeoutMs = timeoutMs;\n }\n}\n\n/**\n * Thrown on resume when the workflow code no longer matches the recorded history: the step at a\n * logical position has a different name/kind than the checkpoint saved there. This means the\n * workflow definition changed (a step was added/removed/reordered) under an in-flight run without a\n * new `@Workflow` version — continuing would replay the wrong checkpoint into the wrong step and\n * silently corrupt the run, so the engine fails loudly instead. Register a new workflow version for\n * breaking changes (old runs finish on the version they started on).\n */\nexport class NonDeterminismError extends Error {\n readonly runId: string;\n readonly seq: number;\n constructor(runId: string, seq: number, expected: string, recorded: string) {\n super(\n `non-determinism at ${runId}#${seq}: code expects \"${expected}\" but history recorded ` +\n `\"${recorded}\". The workflow changed under an in-flight run — register a new @Workflow version.`,\n );\n this.name = 'NonDeterminismError';\n this.runId = runId;\n this.seq = seq;\n }\n}\n\n/**\n * Thrown by `ctx.all` when one or more parallel child workflows fail. Carries the per-item failures\n * (input index, child run id, error message) and presents an aggregate message summarizing the count\n * and the failing ids — the wait-all/fail-fast counterpart to a single child's FatalError. Mirrors\n * the Python SDK's `GatherFailed`.\n */\nexport class GatherError extends Error {\n readonly failures: { index: number; id: string; error: string }[];\n constructor(failures: { index: number; id: string; error: string }[], total?: number) {\n const ids = failures.map((f) => f.id).join(', ');\n const denom = total ?? failures.length;\n super(`ctx.all: ${failures.length} of ${denom} child(ren) failed: ${ids}`);\n this.name = 'GatherError';\n this.failures = failures;\n }\n}\n\nexport class WorkflowSuspended extends Error {\n /** Epoch ms to auto-resume (durable sleep), or undefined when waiting on an external signal. */\n readonly wakeAt?: number | undefined;\n /** Marks this as a control-flow signal — see {@link isWorkflowControlFlowSignal}. */\n readonly [CONTROL_FLOW_SIGNAL] = true;\n constructor(wakeAt?: number) {\n super('workflow suspended');\n this.name = 'WorkflowSuspended';\n this.wakeAt = wakeAt;\n }\n}\n\n/**\n * Thrown by `ctx.continueAsNew(input)` to end the current run and hand off to a fresh execution of\n * the same workflow with a clean history — for long-running / looping workflows that would otherwise\n * accumulate unbounded checkpoints. The engine completes this run and starts the next one.\n */\nexport class ContinueAsNew extends Error {\n /** Marks this as a control-flow signal — see {@link isWorkflowControlFlowSignal}. */\n readonly [CONTROL_FLOW_SIGNAL] = true;\n constructor(readonly input: unknown) {\n super('workflow continued as new');\n this.name = 'ContinueAsNew';\n }\n}\n","/**\n * A **workflow reference** is how one workflow names another to call it: either a registered workflow\n * **name** (a string — the only option across runtimes, e.g. a Python workflow) or, for a same-runtime\n * TypeScript workflow, its **class**. The class carries the input/output types through the call, so\n * `ctx.child(ShippingWorkflow, input)` type-checks the input and returns a typed result — while a\n * string stays available for the cross-runtime case.\n */\n\n/**\n * The symbol the `@Workflow` decorator stamps a workflow's registered name onto, so a class ref can\n * be resolved back to its name. A global-registry symbol (`Symbol.for`) so it survives duplicate\n * copies of this package in a dependency tree.\n */\nexport const WORKFLOW_NAME_KEY: unique symbol = Symbol.for('nestjs-durable:workflow-name');\n\n/** Structural shape of a `@Workflow` class — its `run(ctx, input)` carries the input/output types. */\nexport type WorkflowClass<TInput = unknown, TOutput = unknown> = abstract new (\n ...args: never[]\n) => {\n run(ctx: never, input: TInput): Promise<TOutput> | TOutput;\n};\n\n/** A workflow reference: a registered name (cross-runtime) or a workflow class (typed, same-runtime). */\nexport type WorkflowRef<TInput = unknown, TOutput = unknown> =\n | string\n | WorkflowClass<TInput, TOutput>;\n\n/** The input type a workflow class's `run` accepts. */\nexport type WorkflowInputOf<C> = C extends abstract new (\n ...args: never[]\n) => {\n run(ctx: never, input: infer I): unknown;\n}\n ? I\n : unknown;\n\n/** The output type a workflow class's `run` resolves to (Promise unwrapped). */\nexport type WorkflowOutputOf<C> = C extends abstract new (\n ...args: never[]\n) => {\n run(ctx: never, input: never): infer R;\n}\n ? Awaited<R>\n : unknown;\n\n/**\n * Resolve a {@link WorkflowRef} to its registered workflow name: a string is returned as-is; a\n * `@Workflow` class is resolved via the name the decorator stamped on it. Throws if a class was\n * never decorated (so it carries no registered name).\n */\nexport function workflowName(ref: WorkflowRef): string {\n if (typeof ref === 'string') return ref;\n const name = (ref as { [WORKFLOW_NAME_KEY]?: string })[WORKFLOW_NAME_KEY];\n if (!name) {\n throw new Error(\n `workflow class ${ref.name} has no registered name — is it decorated with @Workflow({ name })?`,\n );\n }\n return name;\n}\n","import { currentWorkflowCtx } from './ambient-ctx';\nimport type { StartOptions } from './engine';\nimport { FatalError } from './errors';\nimport type { RunResult } from './interfaces';\nimport {\n type WorkflowClass,\n type WorkflowInputOf,\n type WorkflowOutputOf,\n workflowName,\n} from './workflow-ref';\n\n/**\n * What the class-first statics need from whoever registered the workflow class: the engine, or a\n * store-less start facade (a tenant's `DurableStartClient`). `waitForRun` is optional — a facade\n * without a store cannot wait, so `execute` outside a workflow throws a clear error there.\n */\nexport interface WorkflowStartClient {\n start(workflow: string, input: unknown, runId: string, opts?: StartOptions): Promise<RunResult>;\n waitForRun?(\n runId: string,\n opts?: { timeoutMs?: number; until?: 'settled' | 'terminal' },\n ): Promise<RunResult>;\n}\n\n/**\n * Per-process class → start-client bindings, written by the registrar at boot. On `globalThis`\n * under a `Symbol.for` key for the same duplicate-copy reason as the ambient context: every copy of\n * core in the tree must read the same map. A WeakMap so a torn-down module doesn't pin its classes.\n */\nconst BINDINGS_KEY = Symbol.for('nestjs-durable:workflow-class-bindings');\n\ntype GlobalWithBindings = typeof globalThis & {\n // biome-ignore lint/complexity/noBannedTypes: keyed by class constructors\n [BINDINGS_KEY]?: WeakMap<Function, WorkflowStartClient>;\n};\n\nconst globalRef = globalThis as GlobalWithBindings;\nif (!globalRef[BINDINGS_KEY]) {\n globalRef[BINDINGS_KEY] = new WeakMap();\n}\nconst bindings = globalRef[BINDINGS_KEY];\n\n/**\n * Bind a `@Workflow` class to the client that can start it — called by the registrar for every\n * discovered workflow at boot. This is what lets `MyWorkflow.start()` resolve THE engine that\n * registered it, with no global engine singleton (two engines in one process each bind their own\n * classes).\n */\n// biome-ignore lint/complexity/noBannedTypes: keyed by class constructors\nexport function bindWorkflowClass(ctor: Function, client: WorkflowStartClient): void {\n bindings.set(ctor, client);\n}\n\nfunction clientOf(ctor: WorkflowClass): WorkflowStartClient {\n const client = bindings.get(ctor);\n if (!client) {\n throw new Error(\n `${workflowName(ctor)} is not bound to a durable engine — the class-first statics only work after the module that registers this workflow has booted (or, in a store-less tenant worker, use the injected WorkflowService/engine facade instead).`,\n );\n }\n return client;\n}\n\n/**\n * Optional base class giving a `@Workflow` a **class-first API** — start it from anywhere without\n * injecting the engine or `WorkflowService`:\n *\n * ```ts\n * @Workflow({ name: 'checkout', version: '1' })\n * export class CheckoutWorkflow extends DurableWorkflow {\n * async run(ctx: WorkflowCtx, order: Order) { ... }\n * }\n *\n * const { runId } = await CheckoutWorkflow.start(order); // fire-and-forget, typed input\n * const result = await CheckoutWorkflow.execute(order); // run-and-await, typed output\n * ```\n *\n * Each method means the same thing everywhere; only the mechanism adapts to where you call it:\n *\n * - {@link DurableWorkflow.start | `start`} — **fire-and-forget**. Outside a workflow it is exactly\n * `engine.start` (enqueue, return `{ runId, status }` immediately). Inside a workflow body it\n * becomes `ctx.startChild` — checkpointed, replay-safe, parent-linked — same contract.\n * - {@link DurableWorkflow.execute | `execute`} — **run-and-await the typed output**. Inside a\n * workflow it is `ctx.child` (the parent suspends with zero compute and resumes with the result).\n * Outside it starts the run and waits until it settles terminally, resolving the output or\n * throwing `FatalError` when the run failed/cancelled/dead.\n *\n * Inside-ness is detected via the ambient workflow context the engine installs around every body\n * execution (see `ambient-ctx.ts`). A `@Step` handler runs on a worker, off the body's path — the\n * statics there start a TOP-LEVEL run, which is correct: a handler is not the workflow body.\n */\nexport class DurableWorkflow {\n /**\n * Fire-and-forget start — `engine.start` outside a workflow, `ctx.startChild` (parent-linked)\n * inside one. `opts.id` pins the run id (outside) / child id (inside) for idempotent starts.\n */\n static async start<C extends WorkflowClass>(\n this: C,\n input: WorkflowInputOf<C>,\n opts?: { id?: string } & StartOptions,\n ): Promise<RunResult> {\n // biome-ignore lint/complexity/noThisInStatic: the polymorphic `this` IS the subclass being started — the class name would break every subclass\n // biome-ignore lint/complexity/noUselessThisAlias: aliased ONCE on purpose so the noThisInStatic suppression lives in one place, not on every `this` use below\n const cls = this;\n const ctx = currentWorkflowCtx();\n if (ctx) {\n const runId = await ctx.startChild(cls, input, opts?.id);\n return { runId, status: 'pending' };\n }\n const runId = opts?.id ?? globalThis.crypto.randomUUID();\n return clientOf(cls).start(workflowName(cls), input, runId, opts);\n }\n\n /**\n * Run-and-await the typed output — `ctx.child` inside a workflow (suspends the parent, zero\n * compute); outside, starts the run and waits until it settles terminally. Throws `FatalError`\n * when the run does not complete. `opts.timeoutMs` bounds the OUTSIDE wait only (inside, a\n * suspended parent costs nothing — bound the child itself with `executionTimeout` instead).\n */\n static async execute<C extends WorkflowClass>(\n this: C,\n input: WorkflowInputOf<C>,\n opts?: { id?: string; timeoutMs?: number } & StartOptions,\n ): Promise<WorkflowOutputOf<C>> {\n // biome-ignore lint/complexity/noThisInStatic: the polymorphic `this` IS the subclass being run — the class name would break every subclass\n // biome-ignore lint/complexity/noUselessThisAlias: aliased ONCE on purpose so the noThisInStatic suppression lives in one place, not on every `this` use below\n const cls = this;\n const ctx = currentWorkflowCtx();\n if (ctx) return ctx.child(cls, input, opts?.id);\n const client = clientOf(cls);\n if (!client.waitForRun) {\n throw new FatalError(\n `${workflowName(cls)}.execute() outside a workflow needs a store-backed engine to await the result — this class is bound to a store-less start facade (tenant worker). Use ${workflowName(cls)}.start() and observe the run instead.`,\n 'execute_unsupported',\n );\n }\n const runId = opts?.id ?? globalThis.crypto.randomUUID();\n await client.start(workflowName(cls), input, runId, opts);\n const settled = await client.waitForRun(runId, {\n ...(opts?.timeoutMs != null ? { timeoutMs: opts.timeoutMs } : {}),\n until: 'terminal',\n });\n if (settled.status === 'completed') return settled.output as WorkflowOutputOf<C>;\n const detail = settled.error ? `: ${settled.error.message}` : '';\n throw new FatalError(\n `${workflowName(cls)} run ${runId} settled ${settled.status}${detail}`,\n settled.error?.code ?? 'execute_failed',\n );\n }\n}\n","const UNIT_MS: Record<string, number> = {\n ms: 1,\n s: 1_000,\n sec: 1_000,\n second: 1_000,\n seconds: 1_000,\n m: 60_000,\n min: 60_000,\n minute: 60_000,\n minutes: 60_000,\n h: 3_600_000,\n hr: 3_600_000,\n hour: 3_600_000,\n hours: 3_600_000,\n d: 86_400_000,\n day: 86_400_000,\n days: 86_400_000,\n w: 604_800_000,\n week: 604_800_000,\n weeks: 604_800_000,\n};\n\n/**\n * Parse a human duration to milliseconds. Accepts a number (already ms) or a string like\n * `'500ms'`, `'30s'`, `'15m'`, `'2h'`, `'7d'`, `'7 days'`.\n */\nexport function parseDuration(duration: string | number): number {\n if (typeof duration === 'number') return duration;\n const match = duration.trim().match(/^(\\d+(?:\\.\\d+)?)\\s*([a-z]+)$/i);\n if (!match) throw new Error(`invalid duration: ${duration}`);\n const value = Number(match[1]);\n const unit = (match[2] ?? '').toLowerCase();\n const factor = UNIT_MS[unit];\n if (factor === undefined) throw new Error(`unknown duration unit: ${unit}`);\n return value * factor;\n}\n","import type { StepOptions } from './interfaces';\n\n/** Delay in ms before the next retry attempt, per a step's `StepOptions` backoff config. Shared by\n * the local-step retry loop and the durable remote-step retry, so they stay consistent. */\nexport function backoffDelay(attempt: number, options?: StepOptions): number {\n const base = options?.backoffMs ?? 0;\n if (base <= 0) return 0;\n const raw = options?.backoff === 'exp' ? base * 2 ** (attempt - 1) : base;\n const capped = options?.backoffMaxMs ? Math.min(raw, options.backoffMaxMs) : raw;\n return options?.jitter ? Math.round(capped * (0.5 + Math.random() * 0.5)) : capped;\n}\n","import type { StepEvent, StepLogger, SubProcessHandle } from './interfaces';\n\n/** Attach the elapsed `durationMs` (from `start`) to `data`, unless the caller already set one. */\nfunction withDuration(start: number, now: () => number, data?: unknown): Record<string, unknown> {\n if (data && typeof data === 'object' && 'durationMs' in data) {\n return data as Record<string, unknown>;\n }\n const base = data && typeof data === 'object' ? (data as Record<string, unknown>) : {};\n return { ...base, durationMs: now() - start };\n}\n\n/**\n * A {@link StepLogger} that appends to `events`, stamping each line with `now()`. Shared by the\n * local-step path (`ctx.step`) and the remote-worker path (`runStepHandler`) so a step records\n * the same {@link StepEvent} shape wherever it runs — the TypeScript twin of the Python SDK's\n * `StepContext`.\n */\nexport function createStepLogger(events: StepEvent[], now: () => number): StepLogger {\n // The sub-process a `subProcess(...)` body is currently inside; debug/info/warn/error emitted while\n // inside get tagged with its id, so the dashboard groups that log trail under the sub-process.\n let currentSub: { id: string } | undefined;\n const push = (level: StepEvent['level'], message: string, data?: unknown) =>\n events.push({\n at: now(),\n level,\n message,\n ...(currentSub ? { subId: currentSub.id } : {}),\n ...(data === undefined ? {} : { data }),\n });\n const subEvent: StepLogger['subEvent'] = (e) =>\n events.push({\n at: now(),\n level: e.status === 'failed' ? 'error' : e.status === 'skipped' ? 'warn' : 'info',\n message: e.message ?? e.phase ?? e.name,\n subId: e.id,\n name: e.name,\n ...(e.group === undefined ? {} : { group: e.group }),\n ...(e.phase === undefined ? {} : { phase: e.phase }),\n ...(e.status === undefined ? {} : { status: e.status }),\n ...(e.data === undefined ? {} : { data: e.data }),\n });\n const subProcess: StepLogger['subProcess'] = async (name, body, opts) => {\n const id = opts?.id ?? globalThis.crypto.randomUUID();\n const group = opts?.group;\n const start = now();\n const prevSub = currentSub;\n currentSub = { id };\n let terminal = false;\n const emit = (status: 'ok' | 'failed' | 'skipped', message?: string, data?: unknown) => {\n if (terminal) return;\n terminal = true;\n subEvent({ id, name, group, status, message, data: withDuration(start, now, data) });\n };\n const handle: SubProcessHandle = {\n phase: (phase, data) => {\n if (!terminal) subEvent({ id, name, group, phase, data });\n return handle;\n },\n skip: (reason, data) => emit('skipped', reason, data),\n fail: (reason, data) => emit('failed', reason, data),\n };\n try {\n const result = await body(handle);\n emit('ok'); // no-op if the body already called skip()/fail()\n return result;\n } catch (err) {\n emit('failed', err instanceof Error ? err.message : String(err));\n throw err;\n } finally {\n currentSub = prevSub;\n }\n };\n return {\n debug: (m, d) => push('debug', m, d),\n info: (m, d) => push('info', m, d),\n warn: (m, d) => push('warn', m, d),\n error: (m, d) => push('error', m, d),\n sub: (name, status, message, data) =>\n events.push({\n at: now(),\n level: status === 'failed' ? 'error' : status === 'skipped' ? 'warn' : 'info',\n message: message ?? name,\n name,\n status,\n ...(data === undefined ? {} : { data }),\n }),\n subEvent,\n subProcess,\n };\n}\n","import type { RemoteTask, StepEvent, StepLogger, StepResult } from './interfaces';\nimport { createStepLogger } from './step-logger';\n\n/** Canonical step id — the stable identity of a step within a run, used for dedupe and\n * correlation. The format is part of the cross-language wire contract (Python builds the same). */\nexport function stepId(runId: string, seq: number): string {\n return `${runId}:${seq}`;\n}\n\n/** Deterministic signal token a breakpoint suspends on — derived from its logical position. Shared\n * so `ctx.breakpoint` (which records it) and `engine.continue` (which signals it) agree. */\nexport const breakpointToken = (runId: string, seq: number): string => `bp:${runId}:${seq}`;\n\n/** A remote-worker step body. The optional `log` records sub-process outcomes and debug/error\n * lines that ride back on the result — the TypeScript twin of the Python SDK's `StepContext`. */\nexport type StepHandler = (input: unknown, log: StepLogger) => Promise<unknown> | unknown;\n\n/**\n * Run `handler` for `task` and produce the wire-format {@link StepResult}. Pure (no transport,\n * no I/O beyond the handler), so every transport — and any language port — can share the exact\n * same completed / failed / no-handler contract instead of re-deriving it.\n */\nexport async function runStepHandler(\n task: RemoteTask,\n handler: StepHandler | undefined,\n): Promise<StepResult> {\n // Stamp the worker's pickup time so the engine can report queue-wait (startedAt − enqueuedAt).\n // This is the one place every transport funnels through, so timing comes for free everywhere.\n const base = { runId: task.runId, seq: task.seq, stepId: task.stepId, startedAt: Date.now() };\n if (!handler) {\n return {\n ...base,\n status: 'failed',\n error: { message: `no handler for ${task.name}`, retryable: false },\n };\n }\n const events: StepEvent[] = [];\n const withEvents = (result: StepResult): StepResult =>\n events.length > 0 ? { ...result, events } : result;\n try {\n const output = await handler(task.input, createStepLogger(events, Date.now));\n return withEvents({ ...base, status: 'completed', output });\n } catch (err) {\n // Carry `code`/`retryable` off the thrown error if present, so the engine's durable retry can\n // honour a worker's \"don't retry this\" verdict (e.g. a declined card).\n const e = err as { message?: string; code?: string; retryable?: boolean };\n return withEvents({\n ...base,\n status: 'failed',\n error: {\n message: err instanceof Error ? err.message : String(err),\n ...(typeof e?.code === 'string' ? { code: e.code } : {}),\n ...(typeof e?.retryable === 'boolean' ? { retryable: e.retryable } : {}),\n },\n });\n }\n}\n","import type { StepCheckpoint, StepError, StepEvent, StepKind } from './interfaces';\nimport { stepId } from './protocol';\n\n/** Drop an empty events array to `undefined` (the repeated `events?.length ? events : undefined`). */\nfunction nonEmptyEvents(events: StepEvent[] | undefined): StepEvent[] | undefined {\n return events && events.length > 0 ? events : undefined;\n}\n\n/**\n * Build a *phased* step checkpoint — one with distinct enqueue/run/finish timestamps (a local step\n * that is running/completed/failed, or a pending remote/sleep step). Computes the deterministic\n * `stepId` and normalizes empty event arrays, so the engine's running/completed/failed/pending\n * checkpoint literals are constructed in exactly one place instead of ~8.\n *\n * For instantaneous checkpoints (sleep timers, markers, delivered signals) use {@link instantCheckpoint}.\n */\nexport function stepCheckpoint(p: {\n runId: string;\n seq: number;\n name: string;\n kind: StepKind;\n status: StepCheckpoint['status'];\n attempts: number;\n enqueuedAt: Date;\n startedAt: Date;\n finishedAt: Date;\n input?: unknown;\n output?: unknown;\n error?: StepError | undefined;\n events?: StepEvent[] | undefined;\n workerGroup?: string | undefined;\n wakeAt?: number | undefined;\n parallelGroup?: string | undefined;\n}): StepCheckpoint {\n return {\n runId: p.runId,\n seq: p.seq,\n name: p.name,\n kind: p.kind,\n stepId: stepId(p.runId, p.seq),\n status: p.status,\n input: p.input,\n output: p.output,\n error: p.error,\n events: nonEmptyEvents(p.events),\n attempts: p.attempts,\n workerGroup: p.workerGroup,\n wakeAt: p.wakeAt,\n parallelGroup: p.parallelGroup,\n enqueuedAt: p.enqueuedAt,\n startedAt: p.startedAt,\n finishedAt: p.finishedAt,\n };\n}\n\n/**\n * Build an *instantaneous* checkpoint — one with no distinct enqueue/run/finish phases (a durable\n * sleep timer, a breakpoint marker, a delivered signal, a published `setEvent` value, a `patched`\n * marker). All three timestamps collapse to now and `attempts` is 1. Collapses what was five\n * near-identical 10-field `saveCheckpoint({...})` literals into one builder.\n */\nexport function instantCheckpoint(p: {\n runId: string;\n seq: number;\n name: string;\n kind: StepKind;\n status?: StepCheckpoint['status'];\n output?: unknown;\n wakeAt?: number;\n parallelGroup?: string | undefined;\n}): StepCheckpoint {\n const at = new Date();\n return {\n runId: p.runId,\n seq: p.seq,\n name: p.name,\n kind: p.kind,\n stepId: stepId(p.runId, p.seq),\n status: p.status ?? 'completed',\n output: p.output,\n wakeAt: p.wakeAt,\n parallelGroup: p.parallelGroup,\n attempts: 1,\n enqueuedAt: at,\n startedAt: at,\n finishedAt: at,\n };\n}\n","import { FatalError } from './errors';\nimport type { InternalWorkflowCtx } from './workflow-ctx';\n\n/** One operation on a durable entity: mutate `state` in place and/or return a result. */\nexport type EntityHandler<S = unknown> = (state: S, arg: unknown) => unknown | Promise<unknown>;\n\n/** A durable keyed entity (a virtual object): per-key serialized handlers over durable state. */\nexport interface EntityConfig<S = unknown> {\n /** Build the initial state for a fresh key. */\n initialState: () => S;\n /** Operation handlers, keyed by op name. Each runs serially per key, exactly once. */\n handlers: Record<string, EntityHandler<S>>;\n}\n\n/** The slice of the engine the entity subsystem needs (so it stays a standalone module). */\nexport interface EntityHost {\n register(\n name: string,\n version: string,\n fn: (ctx: InternalWorkflowCtx, input: unknown) => Promise<unknown>,\n ): void;\n signalWithStart(\n workflow: string,\n input: unknown,\n runId: string,\n signal: { token: string; payload?: unknown },\n ): Promise<{ runId: string }>;\n getEvent<T>(runId: string, key: string): Promise<T | undefined>;\n signal(token: string, payload: unknown): Promise<unknown>;\n}\n\nconst ENTITY_WORKFLOW = '__entity';\nconst entityRunId = (name: string, key: string): string => `entity:${name}:${key}`;\n\n/**\n * Durable keyed **entities** (virtual objects): a keyed actor whose handlers run **serialized per\n * key** over **durable state**, exactly once. Each key is one long-lived run (`entity:<name>:<key>`)\n * processing ops in order. Drive it with `signal` (fire) or `ctx.callEntity` (call + await result),\n * read state with `getState`. Registers its built-in runner on construction.\n */\nexport class Entities {\n private readonly configs = new Map<string, EntityConfig>();\n\n constructor(private readonly host: EntityHost) {\n host.register(ENTITY_WORKFLOW, '1', (ctx, input) => this.run(ctx, input));\n }\n\n register<S>(name: string, config: EntityConfig<S>): void {\n this.configs.set(name, config as EntityConfig);\n }\n\n /** Deliver an op to an entity's runner, starting it on first contact. `reply` (a signal token)\n * receives the handler's result, for `ctx.callEntity`. */\n dispatch(\n name: string,\n key: string,\n op: string,\n arg: unknown,\n reply?: string,\n ): Promise<{ runId: string }> {\n const runId = entityRunId(name, key);\n return this.host.signalWithStart(ENTITY_WORKFLOW, { name, key }, runId, {\n token: runId,\n payload: { op, arg, reply },\n });\n }\n\n async signal(name: string, key: string, op: string, arg?: unknown): Promise<void> {\n await this.dispatch(name, key, op, arg);\n }\n\n getState<S = unknown>(name: string, key: string): Promise<S | undefined> {\n return this.host.getEvent<S>(entityRunId(name, key), 'state');\n }\n\n /** The built-in runner: one long-lived run per key, processing ops serially over state. */\n private async run(ctx: InternalWorkflowCtx, input: unknown): Promise<unknown> {\n const { name, key } = input as { name: string; key: string };\n const config = this.configs.get(name);\n if (!config) throw new FatalError(`entity \"${name}\" is not registered`);\n const token = entityRunId(name, key);\n let state = config.initialState();\n for (let i = 0; ; i += 1) {\n const msg = (await ctx.waitForSignal(token)) as { op: string; arg: unknown; reply?: string };\n // Run the handler and snapshot the (possibly mutated) state in ONE checkpoint, so replay\n // restores the state from the checkpoint instead of re-running the handler. `ctx.step` is now\n // ALWAYS dispatched (see WorkflowCtx.step) — this in-process capture uses the internal\n // `localStep` primitive instead (same checkpointed-once-then-replayed semantics).\n const out = await ctx.localStep(`op:${i}`, async () => {\n const handler = config.handlers[msg.op];\n if (!handler) throw new FatalError(`entity \"${name}\" has no handler for op \"${msg.op}\"`);\n const result = await handler(state, msg.arg);\n return { result, state };\n });\n state = out.state; // carry state forward (and restore it from the checkpoint on replay)\n await ctx.setEvent('state', state); // publish for getState\n if (msg.reply) {\n await ctx.localStep(`reply:${i}`, async () => {\n await this.host.signal((msg as { reply: string }).reply, out.result);\n });\n }\n }\n }\n}\n","import { SignalTimeoutError } from './errors';\nimport type { WorkflowCtx } from './interfaces';\n\n/** How `onEvent` triggers are coalesced into fewer runs (see `@Workflow({ debounce | batch })`). */\nexport type EventBatchConfig =\n | { mode: 'debounce'; windowMs: number }\n | { mode: 'batch'; maxSize: number; windowMs: number };\n\n/** The slice of the engine the accumulators need (so they stay a standalone module). */\nexport interface AccumulatorHost {\n register(\n name: string,\n version: string,\n fn: (ctx: WorkflowCtx, input: unknown) => Promise<unknown>,\n ): void;\n signalWithStart(\n workflow: string,\n input: unknown,\n runId: string,\n signal: { token: string; payload?: unknown },\n ): Promise<{ runId: string }>;\n}\n\nconst accToken = (target: string): string => `__evtacc__:${target}`;\n\n/**\n * Built-in workflows that coalesce `onEvent` triggers. Each is a long-lived per-target accumulator\n * fed by `signalWithStart`: it collects payloads then starts the target once, and `continueAsNew`s to\n * re-arm for the next burst. Signal buffering keeps the re-arm race-free. Registers its runners on\n * construction.\n */\nexport class EventAccumulators {\n constructor(private readonly host: AccumulatorHost) {\n host.register('__evt_debounce', '1', (ctx, input) => this.debounce(ctx, input));\n host.register('__evt_batch', '1', (ctx, input) => this.batch(ctx, input));\n }\n\n /** Route an `onEvent` payload into its target's debounce/batch accumulator. */\n route(target: string, config: EventBatchConfig, payload: unknown): Promise<{ runId: string }> {\n const [workflow, input] =\n config.mode === 'debounce'\n ? (['__evt_debounce', { target, windowMs: config.windowMs }] as const)\n : ([\n '__evt_batch',\n { target, maxSize: config.maxSize, windowMs: config.windowMs },\n ] as const);\n return this.host.signalWithStart(workflow, input, accToken(target), {\n token: accToken(target),\n payload,\n });\n }\n\n /** Fire the target with the LAST payload once events have been quiet for `windowMs`. */\n private async debounce(ctx: WorkflowCtx, input: unknown): Promise<unknown> {\n const { target, windowMs } = input as { target: string; windowMs: number };\n const token = accToken(target);\n let last = await ctx.waitForSignal(token); // park for the first event of a burst\n for (;;) {\n try {\n last = await ctx.waitForSignal(token, { timeoutMs: windowMs }); // extend on each event\n } catch (e) {\n if (e instanceof SignalTimeoutError) break; // quiet for `windowMs` → fire\n throw e; // WorkflowSuspended / ContinueAsNew etc. must propagate\n }\n }\n await ctx.startChild(target, last);\n return ctx.continueAsNew(input); // re-arm\n }\n\n /** Fire the target with all payloads (`{ events }`) once `maxSize` or `windowMs` from the first. */\n private async batch(ctx: WorkflowCtx, input: unknown): Promise<unknown> {\n const { target, maxSize, windowMs } = input as {\n target: string;\n maxSize: number;\n windowMs: number;\n };\n const token = accToken(target);\n const events: unknown[] = [await ctx.waitForSignal(token)]; // park for the first\n const deadline = (await ctx.now()) + windowMs;\n while (events.length < maxSize) {\n const remaining = deadline - (await ctx.now());\n if (remaining <= 0) break;\n try {\n events.push(await ctx.waitForSignal(token, { timeoutMs: remaining }));\n } catch (e) {\n if (e instanceof SignalTimeoutError) break; // window elapsed → fire what we have\n throw e; // WorkflowSuspended / ContinueAsNew etc. must propagate\n }\n }\n await ctx.startChild(target, { events });\n return ctx.continueAsNew(input); // re-arm\n }\n}\n","// Named events: pub/sub on top of the signal-waiter table. A `ctx.waitForEvent(name, { match })`\n// registers a signal waiter whose token encodes the event name + match criteria (base64 so they\n// never contain the `:` delimiter); `engine.publishEvent(name, payload)` lists the waiters for that\n// name by token prefix, checks each one's match against the payload, and signals the ones that pass.\n// No schema change beyond a `listSignalWaiters(prefix)` store method.\n\nconst enc = (s: string): string => Buffer.from(s, 'utf8').toString('base64');\nconst dec = (s: string): string => Buffer.from(s, 'base64').toString('utf8');\n\n/**\n * How many candidates a buffered-event scan considers (`listBufferedEvents(name, limit)`) before\n * giving up. An event's buffer is keyed by `name` only (see {@link eventMatches}'s match-based\n * consumption), so a hot name with many distinct payloads sitting unclaimed could in principle\n * accumulate an unbounded backlog; this caps the per-scan cost regardless. Shared by the workflow-ctx\n * consumer and the engine's reconcile sweep so both see the same window.\n */\nexport const EVENT_BUFFER_SCAN_LIMIT = 50;\n\n/** The literal prefix EVERY event-waiter token starts with, regardless of `name` — `eventPrefix(name)`\n * always begins with this; exported so a caller that only needs to CLASSIFY a token (not fan out a\n * specific name) doesn't have to re-derive or duplicate the literal (see run-waiting.ts's own copy,\n * kept in sync with this one, and engine.ts's reconcile sweep). */\nexport const EVENT_TOKEN_PREFIX = 'event:';\n\n/** Token prefix for every waiter on `name` — used by `listSignalWaiters` to fan an event out. */\nexport function eventPrefix(name: string): string {\n return `${EVENT_TOKEN_PREFIX}${enc(name)}:`;\n}\n\n/** Whether `token` is an event-waiter token (vs. a plain signal / child / webhook / breakpoint one). */\nexport function isEventToken(token: string): boolean {\n return token.startsWith(EVENT_TOKEN_PREFIX);\n}\n\n/** Build the unique waiter token for one `waitForEvent` call (name + match + run position). */\nexport function eventToken(\n name: string,\n match: Record<string, unknown> | undefined,\n runId: string,\n seq: number,\n): string {\n return `${eventPrefix(name)}${enc(JSON.stringify(match ?? {}))}:${runId}#${seq}`;\n}\n\n/** The event name embedded in an event waiter token (the 2nd `:`-segment is the base64 name), so a\n * dashboard can show \"waiting on event `<name>`\" instead of the opaque token. */\nexport function eventNameOf(token: string): string {\n try {\n return dec(token.split(':')[1] ?? '');\n } catch {\n return token;\n }\n}\n\n/** The match criteria embedded in an event waiter token (the 3rd `:`-segment is the base64 match). */\nexport function eventMatchOf(token: string): Record<string, unknown> {\n try {\n return JSON.parse(dec(token.split(':')[2] ?? '')) as Record<string, unknown>;\n } catch {\n return {};\n }\n}\n\n/** Whether `payload` satisfies a waiter's `match`: every match key deep-equals the payload's value. */\nexport function eventMatches(payload: unknown, match: Record<string, unknown>): boolean {\n const keys = Object.keys(match);\n if (keys.length === 0) return true; // no criteria → matches any payload of this name\n if (!payload || typeof payload !== 'object') return false;\n const p = payload as Record<string, unknown>;\n return keys.every((k) => JSON.stringify(p[k]) === JSON.stringify(match[k]));\n}\n","/**\n * Compute the worker group a tenant's run dispatches to. Mirrors the transport's\n * default-is-bare rule (unset/empty/`'default'` ⇒ bare): a\n * `tenant` of `undefined`, `''`, or `'default'` is the bare `baseGroup`, so a single-tenant\n * deployment (or the `'default'` tenant of a multi-tenant one) stays byte-identical to today.\n * Any other tenant suffixes the group as `<baseGroup>@<tenant>`, so an operator control plane\n * (namespace: undefined) can route each tenant's run to its own worker pool.\n */\nexport function tenantGroup(baseGroup: string, tenant: string | undefined): string {\n return tenant !== undefined && tenant !== '' && tenant !== 'default'\n ? `${baseGroup}@${tenant}`\n : baseGroup;\n}\n\n/**\n * Sanitize a handler/workflow name for use as a BullMQ queue token: BullMQ forbids `:` in queue\n * names (it uses the colon internally as a key separator), so every `:` is replaced with `-`. `.`\n * is legal in a BullMQ queue name and is left as-is — step/workflow names commonly use it as a\n * namespacing separator (e.g. `payments.charge-card`).\n */\nexport function sanitizeQueueToken(name: string): string {\n return name.replace(/:/g, '-');\n}\n","import type {\n HistoryEvent,\n Transport,\n WorkflowExecutor,\n WorkflowRun,\n WorkflowTask,\n} from './interfaces';\nimport { sanitizeQueueToken, tenantGroup } from './tenant-group';\n\n/**\n * A {@link WorkflowExecutor} backed by a {@link Transport}: it advances a remote workflow by\n * DISPATCHING a {@link WorkflowTask} over the broker under the ENGINE-SUPPLIED `taskId`, WITHOUT\n * awaiting the decision. Pass one to `engine.registerRemote(name, version, { group, executor })` so a\n * workflow authored in another SDK (e.g. the Python `durable-worker`) is driven over Redis/BullMQ.\n *\n * Routes by NAME, not a hand-declared group: the dispatched task's routing token is\n * `tenantGroup(sanitizeQueueToken(name), partition)` — the same formula a {@link import('./interfaces').StepDef}\n * uses — so `partition` is an optional isolation suffix, not a separate identity. Omit it to route by\n * the bare (sanitized) `name`.\n *\n * Multi-instance safe by construction: the executor holds NO in-memory state correlating a dispatched\n * turn to its decision. The engine records the `taskId` on the run as the awaited marker AND releases\n * the run's lease BEFORE calling `dispatch`, so the worker's {@link import('./interfaces').WorkflowDecision},\n * delivered over the transport's `onDecision` and applied DURABLY (by run id) on whatever engine\n * instance consumes it — even one that did not dispatch the turn — can never arrive ahead of its marker\n * or contend with a still-held lease and be dropped. A point-to-point broker can therefore hand the\n * decision to any instance without it being dropped (the bug this design fixes).\n *\n * Recovery-safe: if the engine crashes (or a decision is genuinely lost because the worker died), the\n * suspended turn's heartbeat-rearmed window (`remoteAdvanceSilenceMs`) lapses and the timer poller\n * re-dispatches a fresh task with the same history — the worker's replay is deterministic, so it\n * returns the same decision; a late decision for the old `taskId` no longer matches the run's\n * currently-awaited turn and is dropped.\n */\nexport class RemoteWorkflowExecutor implements WorkflowExecutor {\n constructor(\n private readonly transport: Transport,\n private readonly name: string,\n private readonly partition?: string | undefined,\n // Accepted for source compatibility; liveness now lives on the engine's suspended-turn window\n // (`remoteAdvanceSilenceMs`) + recovery re-drive, not an in-memory per-turn timeout.\n _opts: { timeoutMs?: number } = {},\n ) {}\n\n /**\n * Enqueue one workflow turn under the engine-supplied `taskId`. Does NOT await the decision — the\n * engine has already suspended the run on `taskId` and applies the decision durably via `onDecision`.\n */\n async dispatch(\n run: WorkflowRun,\n history: HistoryEvent[],\n taskId: string,\n pendingSignals?: WorkflowTask['pendingSignals'],\n ): Promise<void> {\n if (!this.transport.dispatchWorkflowTask) {\n throw new Error('transport does not support workflow tasks (dispatchWorkflowTask)');\n }\n const task: WorkflowTask = {\n taskId,\n runId: run.id,\n workflow: run.workflow,\n workflowVersion: run.workflowVersion,\n input: run.input,\n history,\n ...(pendingSignals ? { pendingSignals } : {}),\n group: tenantGroup(sanitizeQueueToken(this.name), this.partition),\n priority: run.priority,\n attempt: 1,\n };\n await this.transport.dispatchWorkflowTask(task);\n }\n}\n","import { EVENT_TOKEN_PREFIX, eventNameOf } from './events';\nimport type { RunWaiting, SignalWaiter, WorkflowRun } from './interfaces';\n\n// Waiter-token prefixes the engine stamps (see `workflow-ctx.ts`): a webhook mints `wh:<runId>:<seq>`,\n// an awaited child parks on `child:<id>`, a `ctx.breakpoint` mints `bp:<runId>:<seq>` (see\n// `breakpointToken` in `protocol.ts`), a named event on `event:<b64 name>:…`. A plain\n// `ctx.waitForSignal(name)` uses `name` verbatim as the token, so an unrecognised token IS the signal\n// name.\nconst WEBHOOK_PREFIX = 'wh:';\nconst CHILD_PREFIX = 'child:';\nconst BREAKPOINT_PREFIX = 'bp:';\nconst EVENT_PREFIX = EVENT_TOKEN_PREFIX;\n\n/**\n * Resolve WHAT a suspended run is parked on from the token of the {@link SignalWaiter} it registered.\n * The token prefix carries the kind — no extra store lookup and no new persisted field. Used by the\n * store-backed run gateway to stamp {@link RunWaiting} onto each listed run so the dashboard can name\n * the wait in a row without fetching that run's timeline.\n *\n * `ctx.breakpoint` reuses the signal-waiter machinery (`engine.continue` resumes it via `signal()`\n * like any other), so without this case it would fall through to the generic `signal` branch with the\n * raw `bp:<runId>:<seq>` token as its display name — a real bug. Named `'breakpoint'` here instead;\n * the token carries no separate label to recover cheaply (see {@link RunWaiting.name}).\n */\nexport function classifyWaiterToken(token: string): RunWaiting {\n if (token.startsWith(WEBHOOK_PREFIX)) return { on: 'webhook', name: token };\n if (token.startsWith(BREAKPOINT_PREFIX)) return { on: 'breakpoint', name: 'breakpoint' };\n if (token.startsWith(CHILD_PREFIX))\n return { on: 'child', name: token.slice(CHILD_PREFIX.length) };\n if (token.startsWith(EVENT_PREFIX)) return { on: 'signal', name: eventNameOf(token) };\n return { on: 'signal', name: token };\n}\n\n/**\n * Resolve a suspended run's {@link RunWaiting} from the pending signal waiters (indexed by `runId`).\n * Event-only by design (see {@link RunWaiting}): a `waitForSignal`/`waitForEvent`/webhook/awaited-child\n * suspend registers a waiter and gets named here; every other suspend (a bare `ctx.sleep`, an in-flight\n * remote step, a reconcile-parked orphan) returns `undefined`, so the client layers its own display\n * state (no-worker, singleton, running) on top — none of which can be told apart from `wakeAt` alone.\n */\nexport function resolveRunWaiting(\n run: WorkflowRun,\n waiterByRun: ReadonlyMap<string, SignalWaiter>,\n): RunWaiting | undefined {\n if (run.status !== 'suspended') return undefined;\n const waiter = waiterByRun.get(run.id);\n return waiter ? classifyWaiterToken(waiter.token) : undefined;\n}\n\n/** Index signal waiters by `runId`, keeping the first seen per run (a run parks on one waiter at a\n * time in the sequential case; the earliest is the one it's blocked on). */\nexport function indexWaitersByRun(waiters: readonly SignalWaiter[]): Map<string, SignalWaiter> {\n const byRun = new Map<string, SignalWaiter>();\n for (const w of waiters) if (!byRun.has(w.runId)) byRun.set(w.runId, w);\n return byRun;\n}\n","import type { SingletonConfig } from './engine';\nimport { SingletonQueueFullError } from './errors';\nimport type { StateStore, WorkflowRun } from './interfaces';\n\nconst SINGLETON_RETRY_MS = 1000;\n/**\n * Max jitter (ms, each direction) added to {@link SINGLETON_RETRY_MS} so a queue of N gated runs\n * doesn't wake in lockstep and stampede the admission scan. Each retry picks an independent offset\n * in `[-SINGLETON_RETRY_JITTER_MS, +SINGLETON_RETRY_JITTER_MS]`.\n */\nconst SINGLETON_RETRY_JITTER_MS = 250;\n\nexport interface SingletonGateDeps {\n store: Pick<StateStore, 'listRuns' | 'updateRun'>;\n clock: () => number;\n /** Hand a gated run to the run dispatcher (fire-and-forget, like the engine's other dispatches). */\n dispatch: (runId: string) => void;\n /** Resolve a settled run's singleton config from the engine's workflow registry. */\n configFor: (run: WorkflowRun) => SingletonConfig | undefined;\n}\n\n/**\n * Per-key serialization for singleton workflows — start-time back-pressure, FIFO race-free\n * admission, and notify-on-release wakeups. Extracted from {@link WorkflowEngine} so the whole\n * singleton feature lives in one place instead of being smeared across `start`, `execute`, both run\n * loops, and `cancel`.\n */\nexport class SingletonGate {\n constructor(private readonly deps: SingletonGateDeps) {}\n\n /** The tag a singleton run carries, so the gate can find others sharing its key. */\n tag(cfg: SingletonConfig, input: unknown): string {\n return `singleton:${cfg.key(input)}`;\n }\n\n /** Next wake time for a gated run: the base retry delay jittered to avoid a wakeup stampede. */\n retryWakeAt(): number {\n return (\n this.deps.clock() +\n SINGLETON_RETRY_MS +\n Math.floor((Math.random() * 2 - 1) * SINGLETON_RETRY_JITTER_MS)\n );\n }\n\n /**\n * Reject a start that would grow the same-key backlog past `limit + maxQueueDepth` (counting\n * `pending`/`running`/`suspended` runs sharing the key in one scan). No-op when no `maxQueueDepth`\n * is configured.\n */\n async assertCapacity(workflow: string, cfg: SingletonConfig, input: unknown): Promise<void> {\n if (cfg.maxQueueDepth == null) return;\n const cap = (cfg.limit ?? 1) + cfg.maxQueueDepth;\n const queued = await this.deps.store.listRuns({\n tag: this.tag(cfg, input),\n workflow,\n statuses: ['pending', 'running', 'suspended', 'cancelling'],\n });\n if (queued.length >= cap) {\n throw new SingletonQueueFullError(workflow, cfg.key(input), cfg.maxQueueDepth);\n }\n }\n\n /**\n * Whether `run` may run now under its key: it's among the `limit` oldest in-flight (running or\n * suspended) runs sharing the key, by `(createdAt, id)` order. A consistent store gives every\n * instance the same ordering, so admission is race-free + FIFO.\n */\n async admit(run: WorkflowRun, cfg: SingletonConfig): Promise<boolean> {\n // ONE scan for both in-flight statuses; the total `(createdAt, id)` sort makes admission order\n // independent of the store's row order, preserving the FIFO + race-free-across-instances contract.\n const inflight = (\n await this.deps.store.listRuns({\n tag: this.tag(cfg, run.input),\n workflow: run.workflow,\n statuses: ['running', 'suspended', 'cancelling'],\n })\n ).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id));\n const idx = inflight.findIndex((r) => r.id === run.id);\n return idx >= 0 && idx < (cfg.limit ?? 1);\n }\n\n /**\n * Notify-on-release: a singleton run settled (freeing a slot), so dispatch the oldest gated\n * (`suspended` + same tag) waiters now instead of waiting for their ~1s retry timer. Each re-checks\n * admission in the executor and runs only if it actually wins a slot, so FIFO/race-free guarantees\n * hold; the durable timer remains the cross-instance/crash fallback.\n */\n async wakeNext(settled: WorkflowRun): Promise<void> {\n const cfg = this.deps.configFor(settled);\n if (!cfg) return;\n const tag = settled.tags?.find((t) => t.startsWith('singleton:'));\n if (!tag) return;\n const gated = (\n await this.deps.store.listRuns({ tag, workflow: settled.workflow, statuses: ['suspended'] })\n ).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id));\n for (const next of gated.slice(0, cfg.limit ?? 1)) {\n // Clear the durable retry timer as we hand the run over, so the timer poller can't also pick it\n // up and double-dispatch. Only for runs that carry a wakeAt; dispatch after the clear commits.\n if (next.wakeAt != null) {\n await this.deps.store\n .updateRun(next.id, { wakeAt: undefined, updatedAt: new Date() })\n .catch(() => undefined);\n }\n this.deps.dispatch(next.id);\n }\n }\n}\n","import type {\n GroupHealth,\n Heartbeat,\n NamedTransport,\n RemoteTask,\n StartRunMessage,\n StepResult,\n Transport,\n WorkflowDecision,\n WorkflowStepEvent,\n} from './interfaces';\n\n/**\n * An ordered pool of named transports. The engine dispatches on the first and fails over to the\n * next on a dispatch error; a step can pin one by id. Pure transport plumbing — no run lifecycle —\n * so it lives apart from the engine.\n */\nexport class TransportPool {\n constructor(private readonly transports: NamedTransport[]) {}\n\n get size(): number {\n return this.transports.length;\n }\n\n /**\n * The primary (first) transport — the one `dispatch` prefers when no `preferId` is pinned. A\n * {@link RemoteWorkflowExecutor} built by `engine.remote()` rides it (it needs a single\n * `dispatchWorkflowTask`/`onDecision` Transport, not the whole failover pool). Throws if the pool\n * is empty — there is nothing to dispatch a remote workflow over.\n */\n get primary(): Transport {\n const first = this.transports[0];\n if (!first) {\n throw new Error(\n 'no transport configured — engine.remote() needs a transport (or transports)',\n );\n }\n return first.transport;\n }\n\n /** Register the engine's result/heartbeat/step-event handlers on EVERY transport — a result can come\n * back on whichever one delivered the task, so failover stays symmetric. `onStepEvent` is wired only\n * on transports that carry streamed workflow step lifecycle (BullMQ); others simply skip it. */\n bind(\n onResult: (result: StepResult) => Promise<void>,\n onHeartbeat: (beat: Heartbeat) => Promise<void>,\n onStepEvent?: (event: WorkflowStepEvent) => Promise<void>,\n onDecision?: (decision: WorkflowDecision) => Promise<void>,\n ): void {\n for (const { transport } of this.transports) {\n transport.onResult(onResult);\n transport.onHeartbeat(onHeartbeat);\n if (onStepEvent && transport.onStepEvent) {\n transport.onStepEvent(onStepEvent);\n }\n // A workflow-turn decision can come back on whichever transport carried the task — and on\n // whichever ENGINE INSTANCE consumes it (point-to-point), which may NOT be the dispatcher. The\n // engine applies it durably by run id, so binding it here (like onResult) is multi-instance safe.\n if (onDecision && transport.onDecision) {\n transport.onDecision(onDecision);\n }\n }\n }\n\n /**\n * Dispatch `task` over the pool: try the preferred (or first) transport, fail over to the next on\n * a dispatch error, and stamp the task with the id of the transport that accepted it (so a worker\n * replies on the matching one). Throws if every transport fails.\n */\n async dispatch(task: Omit<RemoteTask, 'transport'>, preferId?: string): Promise<void> {\n let lastErr: unknown;\n for (const { id, transport } of this.ordered(preferId)) {\n try {\n await transport.dispatch({ ...task, transport: id });\n return;\n } catch (err) {\n lastErr = err;\n }\n }\n throw lastErr ?? new Error('no transport accepted the dispatch');\n }\n\n /** Worker-health for `group`, merged across every transport that can report it (a group's queue\n * and its workers may live on any pinned transport). Undefined when no transport implements\n * `groupHealth` (e.g. a pure in-process transport — nothing to introspect). */\n async groupHealth(group: string): Promise<GroupHealth | undefined> {\n const reports: GroupHealth[] = [];\n for (const { transport } of this.transports) {\n if (transport.groupHealth) reports.push(await transport.groupHealth(group));\n }\n if (reports.length === 0) return undefined;\n return {\n group,\n depth: reports.reduce((sum, r) => sum + r.depth, 0),\n liveWorkers: reports.flatMap((r) => r.liveWorkers),\n };\n }\n\n /**\n * Register a control-plane `start-run` consumer on every transport that carries the channel. Only\n * control-plane-side transports implement {@link Transport.onStartRun}; a transport without it is\n * skipped, so a plain worker/in-process pool is a no-op. Mirrors {@link bind}'s per-transport wiring.\n */\n onStartRun(handler: (msg: StartRunMessage) => Promise<void>): void {\n for (const { transport } of this.transports) {\n transport.onStartRun?.(handler);\n }\n }\n\n /** Distinct worker groups with a live heartbeat, merged across every transport that can report it. */\n async listWorkerGroups(): Promise<string[]> {\n const groups = new Set<string>();\n for (const { transport } of this.transports) {\n if (transport.listWorkerGroups) {\n for (const g of await transport.listWorkerGroups()) groups.add(g);\n }\n }\n return [...groups];\n }\n\n /**\n * The first transport (in pool order) reporting a LIVE heartbeat for `group` — the one a\n * convention-routed remote workflow must dispatch on. In a mixed pool (e.g. a tenant-scoped\n * control plane pairing its namespaced transport with a bare-prefix one for operator-convention\n * tenant workers), each transport sees a DIFFERENT keyspace: dispatching on `primary` while the\n * live worker heartbeats on another transport parks the task on a queue nobody consumes. Returns\n * `undefined` when no transport reports the group (mirrors the merged `listWorkerGroups` miss).\n */\n async transportWithLiveGroup(group: string): Promise<Transport | undefined> {\n for (const { transport } of this.transports) {\n if (!transport.listWorkerGroups) continue;\n if ((await transport.listWorkerGroups()).includes(group)) return transport;\n }\n return undefined;\n }\n\n /** Pinned `preferId` first, then the rest (failover order). */\n private ordered(preferId?: string): NamedTransport[] {\n if (!preferId) return this.transports;\n const pref = this.transports.filter((t) => t.id === preferId);\n if (pref.length === 0) throw new Error(`transport \"${preferId}\" is not registered`);\n return [...pref, ...this.transports.filter((t) => t.id !== preferId)];\n }\n}\n","import { FatalError } from './errors';\n\n/**\n * The payload an external `ctx.task` / child run delivers back on its completion signal: either a\n * value or a failure. One typed envelope so `task` and `child` share the same unwrap (instead of\n * sniffing ad-hoc `__error` keys).\n */\nexport type Completion<T> = { ok: true; value: T } | { ok: false; error: string };\n\n/** Read a `Completion` from a signal payload: return the value, or throw a FatalError if it failed. */\nexport function unwrapCompletion<T>(payload: unknown, label: string): T {\n const c = payload as Completion<T> | null;\n if (c && typeof c === 'object' && 'ok' in c && c.ok === false) {\n throw new FatalError(`${label} failed: ${c.error}`);\n }\n return (c as { value: T } | null)?.value as T;\n}\n","/**\n * Cross-package step-name stamp. The `@Step` decorator (`@dudousxd/nestjs-durable`) writes a\n * method's derived routing name under this key; core's `ctx.step` reads it (via {@link stepNameOf})\n * to route a method-reference call to the same handler a worker registers by name.\n *\n * `Symbol.for` (the GLOBAL registry), NOT a plain `Symbol()` — so a duplicate copy of this module\n * (pnpm peer-dependency multiplexing, or a dual ESM/CJS load) still reads the SAME key. A plain\n * `Symbol()` would mint a distinct token per copy, so a decorator running against one core instance\n * could stamp a name core's `ctx.step` (a different instance) can never read back. Mirrors the\n * `STATE_STORE` token fix in `./tokens.ts`.\n */\nexport const DURABLE_STEP_NAME = Symbol.for('durable.step.name');\n\n/**\n * Cross-package step-DISPATCH-POLICY stamp. `@Step({ retries, backoff, backoffMs, backoffMaxMs,\n * jitter, timeoutMs })` (`@dudousxd/nestjs-durable`) writes the def-level durable-retry/liveness\n * policy under this key; core's `ctx.step` reads it (via {@link stepConfigOf}) and merges it with any\n * per-call {@link StepDispatchOpts} override to build the dispatched {@link StepDef}. Same\n * `Symbol.for` rationale as {@link DURABLE_STEP_NAME} — a duplicate copy of this module (pnpm\n * peer-dependency multiplexing, dual ESM/CJS) must still read back the SAME key.\n */\nexport const DURABLE_STEP_CONFIG = Symbol.for('durable.step.config');\n\n/**\n * The def-level durable-dispatch policy a `@Step(...)` can stamp on a method: retry/backoff and the\n * remote-liveness `timeoutMs` — the dispatch-relevant subset of the engine's `StepOptions`. Read off\n * a handler reference via {@link stepConfigOf}; a per-call {@link StepDispatchOpts} passed to\n * `ctx.step(ref, input, opts)` overrides these field-by-field.\n */\nexport interface StepConfig {\n /** Max attempts before the step (and run) fails. */\n retries?: number | undefined;\n /** How the delay between retries grows: `fixed` (constant) or `exp` (doubles each attempt). */\n backoff?: 'fixed' | 'exp' | undefined;\n /** Base delay in ms between retries. Omit (or 0) to retry with no delay. */\n backoffMs?: number | undefined;\n /** Upper bound on the (exponential) backoff delay. */\n backoffMaxMs?: number | undefined;\n /** Add random jitter (50–100% of the computed delay) to avoid thundering-herd retries. */\n jitter?: boolean | undefined;\n /** Liveness window for the dispatched step: no result/heartbeat within this many ms presumes the\n * worker dead and fails the dispatch with a `RemoteStepTimeout` (retryable — re-dispatches per\n * `retries`). Omit to wait indefinitely. */\n timeoutMs?: number | undefined;\n}\n\nfunction isStepConfig(value: unknown): value is StepConfig {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * A method carrying its `@Step`-stamped routing name (and, optionally, its dispatch policy).\n * `ctx.step(ref, input)` reads the name via {@link stepNameOf} — the reference itself is never\n * invoked directly by the caller's process (the worker serving that name re-resolves the real\n * handler from DI), so an unbound `this` on `ref` is irrelevant; `ref` is purely a typed,\n * refactor-safe handle onto the stamped name (and policy).\n */\nexport type StepRef<TInput = unknown, TOutput = unknown> = ((\n input: TInput,\n) => Promise<TOutput> | TOutput) & {\n [DURABLE_STEP_NAME]?: string | undefined;\n [DURABLE_STEP_CONFIG]?: StepConfig | undefined;\n};\n\n/** Read the `@Step`-stamped routing name off a function ref. `undefined` for anything unstamped\n * (including a plain string — {@link stepNameOf} only reads function refs; a caller passing a\n * string already has the routing name and dispatches it directly). */\nexport function stepNameOf(ref: unknown): string | undefined {\n if (typeof ref !== 'function') return undefined;\n const stamped = (ref as { [DURABLE_STEP_NAME]?: unknown })[DURABLE_STEP_NAME];\n return typeof stamped === 'string' ? stamped : undefined;\n}\n\n/** Read the `@Step`-stamped dispatch policy off a function ref. `undefined` for anything unstamped\n * (including a plain string — a cross-runtime string-name call has no def-level policy to read; pass\n * it via {@link StepDispatchOpts} instead). */\nexport function stepConfigOf(ref: unknown): StepConfig | undefined {\n if (typeof ref !== 'function') return undefined;\n const stamped = (ref as { [DURABLE_STEP_CONFIG]?: unknown })[DURABLE_STEP_CONFIG];\n return isStepConfig(stamped) ? stamped : undefined;\n}\n","import { backoffDelay } from './backoff';\nimport { instantCheckpoint } from './checkpoints';\nimport { unwrapCompletion } from './completion';\nimport { parseDuration } from './duration';\nimport {\n ContinueAsNew,\n FatalError,\n GatherError,\n NonDeterminismError,\n SignalTimeoutError,\n WorkflowSuspended,\n} from './errors';\nimport { EVENT_BUFFER_SCAN_LIMIT, eventMatches, eventToken } from './events';\nimport type {\n ChildCallOptions,\n DurableWebhook,\n SearchAttributes,\n SearchAttributesSchema,\n StateStore,\n StepCheckpoint,\n StepDef,\n StepDispatchOpts,\n StepError,\n StepEvent,\n StepInvocation,\n StepKind,\n StepLogger,\n StepOptions,\n StepUndo,\n WorkflowCtx,\n} from './interfaces';\nimport { breakpointToken } from './protocol';\nimport { createStepLogger } from './step-logger';\nimport { type StepConfig, type StepRef, stepConfigOf, stepNameOf } from './step-name-symbol';\nimport { type WorkflowRef, workflowName } from './workflow-ref';\n\n/** Normalize the `ctx.child`/`ctx.startChild` 3rd arg: a bare string is shorthand for `{ childId }`. */\nfunction normalizeChildOptions(options?: string | ChildCallOptions): ChildCallOptions {\n return typeof options === 'string' ? { childId: options } : (options ?? {});\n}\n\n/** Render a Standard Schema issue `path` (a mix of raw keys and `{ key }` segments) as a dotted\n * string, for a `searchAttributes` validation error — `['amount']` → `'amount'`, `[]`/`undefined` →\n * `'(root)'` (the merged object itself failed, not one of its keys). */\nfunction formatIssuePath(\n path: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }> | undefined,\n): string {\n if (!path || path.length === 0) return '(root)';\n return path\n .map((segment) => String(typeof segment === 'object' ? segment.key : segment))\n .join('.');\n}\n\n/**\n * Merge a `@Step`-declared {@link StepConfig} with a per-call {@link StepDispatchOpts} override into\n * the dispatch-relevant `StepOptions` subset of a {@link StepDef} (`retries`/`backoff`/`backoffMs`/\n * `backoffMaxMs`/`jitter`/`timeoutMs`), `opts` winning field-by-field. Omits every field neither side\n * set — required under `exactOptionalPropertyTypes` (an explicit `undefined` value is a type error).\n */\nfunction resolveStepPolicy(\n config: StepConfig | undefined,\n opts: StepDispatchOpts | undefined,\n): StepOptions {\n const policy: StepOptions = {};\n const retries = opts?.retries ?? config?.retries;\n if (retries !== undefined) policy.retries = retries;\n const backoff = opts?.backoff ?? config?.backoff;\n if (backoff !== undefined) policy.backoff = backoff;\n const backoffMs = opts?.backoffMs ?? config?.backoffMs;\n if (backoffMs !== undefined) policy.backoffMs = backoffMs;\n const backoffMaxMs = opts?.backoffMaxMs ?? config?.backoffMaxMs;\n if (backoffMaxMs !== undefined) policy.backoffMaxMs = backoffMaxMs;\n const jitter = opts?.jitter ?? config?.jitter;\n if (jitter !== undefined) policy.jitter = jitter;\n const timeoutMs = opts?.timeoutMs ?? config?.timeoutMs;\n if (timeoutMs !== undefined) policy.timeoutMs = timeoutMs;\n return policy;\n}\n\n/**\n * A saga undo registered by a completed step, kept with its step name for visibility on failure.\n * Two shapes, pushed onto the SAME `compensations` stack so the engine unwinds them together in one\n * strict reverse-completion order, regardless of which kind each one is:\n * - `fn`: a LOCAL undo (`ctx.localStep`'s `compensate` closure) — run in-process.\n * - `dispatch`: a DISPATCHED undo (`ctx.step`'s `compensate` ref/string) — an ordinary `@Step` def\n * the engine dispatches to a worker at unwind time, called with the `StepUndo` envelope (`args`).\n */\nexport type Compensation =\n | { name: string; fn: () => Promise<void> }\n | {\n name: string;\n dispatch: {\n def: StepDef<StepUndo<unknown, unknown>, unknown>;\n args: StepUndo<unknown, unknown>;\n };\n };\n\n/** A finished local step the host should checkpoint and announce (completed or failed). */\nexport interface StepRecord {\n runId: string;\n seq: number;\n name: string;\n kind: StepKind;\n input?: unknown;\n events?: StepEvent[] | undefined;\n attempts: number;\n enqueuedAt: Date;\n startedAt: Date;\n workerGroup?: string | undefined;\n}\n\n/**\n * The narrow surface {@link createWorkflowCtx} needs from the engine — the seam between the\n * authoring API (this module) and the orchestrator (the engine owns lifecycle: emitting events,\n * suspending/resuming runs, dispatching remote steps).\n */\nexport interface CtxHost {\n readonly store: StateStore;\n /**\n * Per-execution checkpoint snapshot, loaded ONCE at execution start (the completed prefix this\n * replay walks). Lets each primitive read the prefix from memory instead of a per-call DB SELECT\n * (the O(N²) replay-reads fix). A seq ABSENT from the map is NOT cached — the primitive falls back\n * to the live store, so the checkpoint this resume is waking on (signal/timer/child, written after\n * the snapshot) is always read fresh. New checkpoints written during this execution are inserted\n * into the map so any later same-execution read sees them. Undefined ⇒ always hit the store.\n */\n readonly replay?: Map<number, StepCheckpoint> | undefined;\n clock(): number;\n webhookUrl?: ((token: string) => string) | undefined;\n /** Mark a local step's body as started — emits `step.started` and (optionally) a `running` checkpoint. */\n startStep(step: StepRecord): Promise<void>;\n completeStep(step: StepRecord & { output: unknown }): Promise<void>;\n failStep(step: StepRecord & { error: StepError }): Promise<void>;\n callRemote<TInput, TOutput>(\n runId: string,\n seq: number,\n step: StepDef<TInput, TOutput>,\n input: TInput,\n queue?: string,\n transport?: string,\n admission?: { priority?: number | undefined; fairnessKey?: string | undefined },\n ): Promise<TOutput>;\n /** Start a child run once, deferred so it can't reentrantly resume a still-running parent. */\n startChild(workflow: string, input: unknown, id: string, priority?: number): void;\n /**\n * Best-effort cancel of a child run — deferred for the SAME reason as `startChild` (so ctx code\n * can't reentrantly mutate engine state while the parent's own step is still executing\n * synchronously). Plain cancel, no saga undo; used by `ctx.all`'s `failFast` mode to stop the\n * surviving siblings once one has failed. Cancelling an already-terminal/cancelled run is a no-op\n * (`engine.cancel`'s own idempotency guard), so a replay that re-issues the same calls is safe.\n * Optional: hosts that never construct a `ctx.all` failFast call (e.g. test fakes) can omit it.\n */\n cancelChild?(childId: string): void;\n /** Shallow-merge `attrs` into the run's `searchAttributes` (see {@link WorkflowCtx.upsertSearchAttributes}). */\n upsertSearchAttributes(runId: string, attrs: SearchAttributes): Promise<void>;\n /** Deliver an op to a durable entity (deferred), optionally with a `reply` token for the result. */\n signalEntity?(name: string, key: string, op: string, arg: unknown, reply?: string): void;\n /** Run a local step body through the registered step interceptors (identity if none). */\n interceptStep?<T>(invocation: StepInvocation, body: () => Promise<T>): Promise<T>;\n}\n\n/** The per-run logical position counter. `rewind()` gives a position back (see `ctx.patched`). */\nclass Position {\n private seq = -1;\n next(): number {\n this.seq += 1;\n return this.seq;\n }\n rewind(): void {\n this.seq -= 1;\n }\n}\n\n/**\n * Back-compat alias of {@link WorkflowCtx}. `localStep` — the checkpointed in-process step primitive\n * used for saga compensation — is now part of the public {@link WorkflowCtx}, so this type adds\n * nothing; it is kept only so internal consumers (the durable-entity runner) keep compiling.\n */\nexport type InternalWorkflowCtx = WorkflowCtx;\n\n/**\n * Build the {@link WorkflowCtx} handed to a workflow body. Every primitive is a closure over the\n * position counter (the per-run logical position) and the saga `compensations` stack, so `task`/\n * `child` compose `step`/`waitForSignal` directly. All durability goes through {@link CtxHost}, so\n * the workflow body stays deterministic.\n */\nexport function createWorkflowCtx(\n host: CtxHost,\n runId: string,\n compensations: Compensation[],\n workflow = '',\n searchAttributesSchema?: SearchAttributesSchema,\n): InternalWorkflowCtx {\n const { store, replay } = host;\n const pos = new Position();\n\n // Read the checkpoint at `seq`: from the per-execution snapshot when present (no DB round-trip),\n // otherwise from the live store. Absence in the snapshot means \"written after the snapshot\" (the\n // signal/timer/child this resume wakes on, or nothing yet) — those MUST hit the store. Identical\n // behaviour to a raw `store.getCheckpoint`, just memoized for the completed prefix.\n const readCheckpoint = (seq: number): Promise<StepCheckpoint | null> | StepCheckpoint => {\n const hit = replay?.get(seq);\n if (hit !== undefined) return hit;\n return store.getCheckpoint(runId, seq);\n };\n\n // Persist a checkpoint AND reflect it in the snapshot, so a later same-execution read of this seq\n // (e.g. a re-read within the same call) sees it instead of falling back to the store.\n const writeCheckpoint = async (cp: StepCheckpoint): Promise<void> => {\n await store.saveCheckpoint(cp);\n replay?.set(cp.seq, cp);\n };\n\n // The in-process local-step runner: checkpointed, replayed, retried. No longer publicly exposed as\n // `ctx.step` (that name is now the ALWAYS-dispatched form below) — this backs the library's own\n // internal primitives that need a checkpointed in-process body: `ctx.task`'s dispatch step and the\n // deterministic capture helpers `ctx.now`/`ctx.sideEffect`.\n const localStep = async <T>(\n name: string,\n fn: (log: StepLogger) => Promise<T>,\n options?: StepOptions,\n ): Promise<T> => {\n const current = pos.next();\n const existing = await readCheckpoint(current);\n if (existing && existing.name !== name) {\n throw new NonDeterminismError(runId, current, name, existing.name);\n }\n if (existing && existing.status === 'completed') {\n // Register the compensation on replay too, so a saga undoes ALL completed steps — even\n // those done in an earlier (since-suspended) pass — not just the ones run this pass.\n if (options?.compensate) compensations.push({ name, fn: options.compensate });\n return existing.output as T;\n }\n const maxAttempts = Math.max(1, options?.retries ?? 1);\n const startedAt = new Date();\n // Announce the body has begun (and, when enabled, checkpoint it `running`) so the step is\n // visible in flight — not only once it settles. Skipped on replay: a completed step returns\n // above before reaching here, so this fires once, when the body actually first runs.\n await host.startStep({\n runId,\n seq: current,\n name,\n kind: 'local',\n attempts: 1,\n enqueuedAt: startedAt,\n startedAt,\n });\n for (let attempt = 1; ; attempt += 1) {\n // Events are scoped per attempt — a retry starts a clean log, so the checkpoint reflects\n // only the attempt that actually completed (or the final failing one).\n const events: StepEvent[] = [];\n try {\n const invocation: StepInvocation = {\n runId,\n workflow,\n stepName: name,\n seq: current,\n attempt,\n };\n const body = () => fn(createStepLogger(events, host.clock));\n const output = host.interceptStep\n ? await host.interceptStep(invocation, body)\n : await body();\n await host.completeStep({\n runId,\n seq: current,\n name,\n kind: 'local',\n output,\n events,\n attempts: attempt,\n enqueuedAt: startedAt,\n startedAt,\n });\n if (options?.compensate) compensations.push({ name, fn: options.compensate });\n return output;\n } catch (err) {\n if (err instanceof FatalError || attempt >= maxAttempts) {\n await host.failStep({\n runId,\n seq: current,\n name,\n kind: 'local',\n error: {\n message: err instanceof Error ? err.message : String(err),\n stack: err instanceof Error ? err.stack : undefined,\n },\n events,\n attempts: attempt,\n enqueuedAt: startedAt,\n startedAt,\n });\n throw err;\n }\n // Wait out the backoff before the next attempt (no-op when backoffMs is unset).\n const wait = backoffDelay(attempt, options);\n if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));\n }\n }\n };\n\n // Exactly-once DB step: run the body and write the step checkpoint in ONE store transaction, so the\n // business write commits atomically with the \"done\" marker (a plain step checkpoints AFTER the body,\n // so a crash in between re-runs it). Replay returns the recorded output without re-running.\n const transaction = async <T>(name: string, fn: (tx: unknown) => Promise<T>): Promise<T> => {\n if (!store.transaction) {\n throw new Error(\n 'ctx.transaction needs a store that supports transactions (the SQL adapters do). Use ctx.step for non-transactional work.',\n );\n }\n const current = pos.next();\n const existing = await readCheckpoint(current);\n if (existing && existing.name !== name) {\n throw new NonDeterminismError(runId, current, name, existing.name);\n }\n if (existing && existing.status === 'completed') return existing.output as T;\n return store.transaction(async (tx) => {\n const output = await fn(tx.raw);\n const cp = instantCheckpoint({ runId, seq: current, name, kind: 'local', output });\n await tx.saveCheckpoint(cp);\n // Reflect the committed checkpoint in the snapshot, keeping the writeback invariant uniform.\n replay?.set(current, cp);\n return output;\n });\n };\n\n // Shared by sleep / sleepUntil: record a durable timer at this position and suspend until `wakeAt`\n // (epoch ms). The wakeAt is computed by the caller — but only used on the first run; on replay the\n // recorded checkpoint's wakeAt wins, so a clock change can't shift an already-scheduled timer.\n const suspendUntil = async (wakeAt: () => number): Promise<void> => {\n const current = pos.next();\n const now = host.clock();\n const existing = await readCheckpoint(current);\n if (existing) {\n // Timer already recorded: resume if due, otherwise re-suspend cheaply.\n if (now >= (existing.wakeAt ?? 0)) return;\n throw new WorkflowSuspended(existing.wakeAt ?? now);\n }\n const at = wakeAt();\n await writeCheckpoint(\n instantCheckpoint({ runId, seq: current, name: 'sleep', kind: 'sleep', wakeAt: at }),\n );\n throw new WorkflowSuspended(at);\n };\n\n const sleep = (duration: string | number): Promise<void> =>\n suspendUntil(() => host.clock() + parseDuration(duration));\n\n const sleepUntil = (when: Date | number): Promise<void> =>\n suspendUntil(() => (typeof when === 'number' ? when : when.getTime()));\n\n // End this run and hand off to a fresh execution (clean history) with the new input. Terminal —\n // it always throws, so any code after it in the workflow is unreachable.\n const continueAsNew = (input?: unknown): Promise<never> => {\n throw new ContinueAsNew(input);\n };\n\n // NOTE (determinism): a bounded wait consumes TWO logical positions (deadline + wait), an\n // unbounded one consumes ONE. So adding or removing `{ timeoutMs }` on an existing `waitForSignal`\n // shifts the seq of every later step — treat it as a workflow-version change for in-flight runs.\n // Consume a buffered signal (one delivered before this run was waiting), recording it as the\n // signal checkpoint at `seq` so it resumes immediately instead of suspending. Replay-safe: the\n // checkpoint makes the consumption deterministic.\n const consumeBuffered = async <T>(token: string, seq: number): Promise<{ value: T } | null> => {\n const buffered = await store.takeBufferedSignal(token);\n if (!buffered) return null;\n await writeCheckpoint(\n instantCheckpoint({\n runId,\n seq,\n name: `signal:${token}`,\n kind: 'signal',\n output: buffered.payload,\n }),\n );\n return { value: buffered.payload as T };\n };\n\n // Consume a buffered EVENT matching `match` (one published with no live waiter — see\n // engine.publishEvent's buffering), recording it as the resolving `signal:<token>` checkpoint at\n // `seq` so replay is deterministic — the event analog of `consumeBuffered` above, but match-aware:\n // an event's buffer is keyed by NAME only (many waiters can share a name with different `match`\n // criteria), so consumption scans the oldest candidates and evaluates each one's match HERE — the\n // match predicate belongs to the WAITER, never the store (see events.ts / interfaces.ts). A hit\n // atomically claims that one row via `removeBufferedEvent`'s boolean return, which arbitrates a\n // concurrent claim (notably engine.publishEvent's own late re-check reaching the same row first —\n // see the wiring in engine.ts); losing that race tries the NEXT oldest candidate instead of giving\n // up, so a later non-matching buffered event never blocks an earlier matching one behind it.\n const consumeBufferedEvent = async <T>(\n name: string,\n match: Record<string, unknown> | undefined,\n token: string,\n seq: number,\n ): Promise<{ value: T } | null> => {\n const candidates = await store.listBufferedEvents(name, EVENT_BUFFER_SCAN_LIMIT);\n for (const candidate of candidates) {\n if (!eventMatches(candidate.payload, match ?? {})) continue;\n if (!(await store.removeBufferedEvent(candidate.id))) continue; // raced away — try the next\n // Resolved it ourselves — remove OUR OWN waiter row via the exact match (not\n // `takeSignalWaiter(token)`; harmless here since an event token is unique per call, but exact\n // removal keeps this symmetric with the signal-side precedent in `waitForSignal` above).\n await store.removeSignalWaiter({ token, runId, seq });\n await writeCheckpoint(\n instantCheckpoint({\n runId,\n seq,\n name: `signal:${token}`,\n kind: 'signal',\n output: candidate.payload,\n }),\n );\n return { value: candidate.payload as T };\n }\n return null;\n };\n\n // Durably stamp the deadline for a BOUNDED wait, ONCE: the first run computes `clock() + timeoutMs`\n // and records it as a timer checkpoint at `deadlineSeq`; every later replay reads the SAME recorded\n // `wakeAt` back instead of recomputing it — so a slow replay (or a clock that moved between the\n // original run and the replay) can never shift an already-scheduled deadline. `label` only affects\n // the checkpoint's `name` (cosmetic, for the dashboard timeline) — the shared mechanic behind every\n // bounded-wait primitive (`waitForSignal`, `waitForEvent`, `DurableWebhook.wait`).\n const stampDeadline = async (\n deadlineSeq: number,\n label: string,\n timeoutMs: number,\n ): Promise<number> => {\n const recorded = await readCheckpoint(deadlineSeq);\n const deadline = recorded?.wakeAt ?? host.clock() + timeoutMs;\n if (!recorded) {\n await writeCheckpoint(\n instantCheckpoint({\n runId,\n seq: deadlineSeq,\n name: `timeout:${label}`,\n kind: 'sleep',\n wakeAt: deadline,\n }),\n );\n }\n return deadline;\n };\n\n const waitForSignal = async <T>(token: string, opts?: { timeoutMs?: number }): Promise<T> => {\n if (opts?.timeoutMs == null) {\n const current = pos.next();\n const existing = await readCheckpoint(current);\n if (existing && existing.status === 'completed') return existing.output as T;\n const buffered = await consumeBuffered<T>(token, current);\n if (buffered) return buffered.value;\n // Register, THEN check the buffer again before suspending — closes the lost-wake window\n // between the check above and this registration: a signal delivered in that sliver found no\n // waiter (we hadn't registered yet) and no buffer either by the time IT checked, so it buffered\n // the payload; without this re-check we'd suspend with the payload sitting unpaired forever.\n // (Registering UNCONDITIONALLY before even the first check — instead of only on a miss like\n // here — reopens a worse window: a token an entity loop reuses across iterations would expose\n // a \"this turn is about to self-resolve from the buffer\" waiter row to a concurrent signal for\n // the NEXT iteration's payload, which can steal it via engine.signal's plain takeSignalWaiter\n // and misdeliver. Checking first, so we only ever register when we're sure no buffer already\n // existed, avoids that.) See the interleaving proof at engine.signal for the mirror-image\n // take→buffer→re-take on the signaling side that this pairs with.\n await store.putSignalWaiter({ token, runId, seq: current });\n const lateBuffered = await consumeBuffered<T>(token, current);\n if (lateBuffered) {\n // Resolved it ourselves — remove OUR OWN row via the exact match, not\n // `takeSignalWaiter(token)`, which deletes ANY row for this token and could steal a\n // different run's waiter that has since claimed the same token.\n await store.removeSignalWaiter({ token, runId, seq: current });\n return lateBuffered.value;\n }\n throw new WorkflowSuspended();\n }\n const timeoutMs = opts.timeoutMs;\n const deadlineSeq = pos.next();\n const waitSeq = pos.next();\n // The run also gets a run-level wakeAt (via WorkflowSuspended) so the timer poller resumes it at\n // the deadline.\n const deadline = await stampDeadline(deadlineSeq, token, timeoutMs);\n const waited = await readCheckpoint(waitSeq);\n if (waited && waited.status === 'completed') return waited.output as T;\n const buffered = await consumeBuffered<T>(token, waitSeq);\n if (buffered) return buffered.value;\n if (host.clock() >= deadline) {\n // A PRIOR replay of this same call may have already registered the waiter (below) before this\n // one found the deadline past — clean up that exact row (own token/runId/seq only; a plain\n // `takeSignalWaiter(token)` could otherwise steal a different run's waiter on the same token).\n // A no-op if nothing was ever registered.\n await store.removeSignalWaiter({ token, runId, seq: waitSeq }).catch(() => undefined);\n throw new SignalTimeoutError(token, timeoutMs);\n }\n // Same reorder as the unbounded arm above: check, THEN register, THEN re-check before suspending.\n await store.putSignalWaiter({ token, runId, seq: waitSeq });\n const lateBuffered = await consumeBuffered<T>(token, waitSeq);\n if (lateBuffered) {\n await store.removeSignalWaiter({ token, runId, seq: waitSeq });\n return lateBuffered.value;\n }\n throw new WorkflowSuspended(deadline);\n };\n\n // Wait for a named event delivered by engine.publishEvent(name, payload). Like waitForSignal, but\n // name-based pub/sub with optional `match` filtering — the token embeds name + match (see events.ts),\n // so a publish fans out to the runs whose match the payload satisfies.\n //\n // Buffering (reliable events — mirrors signalWithStart's reliability contract for signals, see the\n // \"Semantics\" doc on engine.publishEvent): a publish that finds no live waiter buffers ONE copy, and\n // this call's post-registration scan is what consumes it. UNLIKE waitForSignal, this registers its\n // waiter FIRST and scans the buffer only ONCE after — no separate \"check before registering\" pass.\n // That's deliberate, not an oversight: waitForSignal's own token is a caller-chosen string an entity\n // loop can legitimately REUSE across iterations, so registering before checking would expose a\n // \"this turn is about to self-resolve\" waiter row to a concurrent signal for the NEXT iteration's\n // token, which could steal it via engine.signal's plain takeSignalWaiter. An event token embeds this\n // call's OWN `runId#seq` (see eventToken in events.ts) — nothing else, ever, mints the same token —\n // so that hazard cannot arise here, and a single check-after-register closes the lost-wake window\n // symmetrically with engine.publishEvent's own buffer-then-recheck (see its wiring in engine.ts).\n const waitForEvent = async <T>(\n name: string,\n opts?: { match?: Record<string, unknown>; timeoutMs?: number },\n ): Promise<T> => {\n if (opts?.timeoutMs == null) {\n const current = pos.next();\n const token = eventToken(name, opts?.match, runId, current);\n const existing = await readCheckpoint(current);\n if (existing && existing.status === 'completed') return existing.output as T;\n await store.putSignalWaiter({ token, runId, seq: current });\n const bufferedHit = await consumeBufferedEvent<T>(name, opts?.match, token, current);\n if (bufferedHit) return bufferedHit.value;\n throw new WorkflowSuspended();\n }\n const timeoutMs = opts.timeoutMs;\n const deadlineSeq = pos.next();\n const waitSeq = pos.next();\n const token = eventToken(name, opts.match, runId, waitSeq);\n const deadline = await stampDeadline(deadlineSeq, `event:${name}`, timeoutMs);\n const waited = await readCheckpoint(waitSeq);\n if (waited && waited.status === 'completed') return waited.output as T;\n if (host.clock() >= deadline) {\n // Exact removal (see waitForSignal above) — takeSignalWaiter(token) deletes ANY row for this\n // token and could steal a different run's waiter registered on it after ours timed out.\n await store.removeSignalWaiter({ token, runId, seq: waitSeq }).catch(() => undefined);\n throw new SignalTimeoutError(`event:${name}`, timeoutMs);\n }\n await store.putSignalWaiter({ token, runId, seq: waitSeq });\n const bufferedHit = await consumeBufferedEvent<T>(name, opts.match, token, waitSeq);\n if (bufferedHit) return bufferedHit.value;\n throw new WorkflowSuspended(deadline);\n };\n\n // An external task = a checkpointed dispatch + a wait for its async-completion `Completion`\n // (delivered by engine.completeTask/failTask). The whole \"fire at a foreign system, suspend,\n // resume when it reports back\" pattern as one call.\n const task = async <T>(\n name: string,\n dispatch: () => Promise<void>,\n options?: StepOptions,\n ): Promise<T> => {\n await localStep(`task:dispatch:${name}`, dispatch, options);\n return unwrapCompletion<T>(await waitForSignal(`task:${runId}:${name}`), `task \"${name}\"`);\n };\n\n // Child workflow (await result): start it once, then suspend on a `child:<id>` waiter the child\n // signals on its terminal state (see engine.notifyParent).\n const child = async <T>(\n workflow: WorkflowRef,\n input: unknown,\n options?: string | ChildCallOptions,\n ): Promise<T> => {\n const { childId, priority } = normalizeChildOptions(options);\n const current = pos.next();\n const id = childId ?? `${runId}.child.${current}`;\n const existing = await readCheckpoint(current);\n if (existing && existing.status === 'completed') {\n return unwrapCompletion<T>(existing.output, `child \"${id}\"`);\n }\n await store.putSignalWaiter({ token: `child:${id}`, runId, seq: current });\n // Lost-wake guard (mirrors the engine's remote `startChild` command path): the child may have\n // ALREADY completed while no waiter was registered — e.g. this run failed on the child's\n // failure, the child was retried to completion, and this run is now being retried — leaving its\n // completion BUFFERED. Consume it here or the re-registered waiter waits forever for a signal\n // that already fired. Resolve exactly as engine.signal would: overwrite the placeholder with\n // the completed signal checkpoint, then unwrap.\n const buffered = await store.takeBufferedSignal(`child:${id}`);\n if (buffered) {\n await store.removeSignalWaiter({ token: `child:${id}`, runId, seq: current });\n await writeCheckpoint(\n instantCheckpoint({\n runId,\n seq: current,\n name: `signal:child:${id}`,\n kind: 'signal',\n output: buffered.payload,\n }),\n );\n return unwrapCompletion<T>(buffered.payload, `child \"${id}\"`);\n }\n if (!(await store.getRun(id))) host.startChild(workflowName(workflow), input, id, priority);\n // Make the awaited child visible in the parent's timeline WHILE it runs: a `running` placeholder\n // at this seq with the same `signal:child:<id>` name the signal resolution later overwrites as\n // `completed`. So the dashboard shows the child node (and can inline-expand it) live, instead of\n // it appearing only when it finishes. Written once (skipped on replay, where `existing` is set);\n // `running` is ignored by replay history, so it never short-circuits determinism.\n if (!existing) {\n await writeCheckpoint(\n instantCheckpoint({\n runId,\n seq: current,\n name: `signal:child:${id}`,\n kind: 'signal',\n status: 'running',\n }),\n );\n }\n throw new WorkflowSuspended();\n };\n\n // Parallel child workflows (wait-all): dispatch N children CONCURRENTLY and wait for ALL their\n // outputs. Reserves a contiguous position block in list order FIRST (the determinism anchor), then\n // dispatches every not-yet-completed item and suspends once; on each child completion the parent\n // resumes and replays — completed items short-circuit, remaining ones re-register and re-suspend.\n // When all resolve, outputs are returned in INPUT order (waitAll), or a GatherError is thrown\n // carrying the per-item failures. Parity with the Python SDK's `gather_children`.\n const all = async <T = unknown>(\n workflow: WorkflowRef,\n inputs: unknown[],\n opts?: { mode?: 'waitAll' | 'failFast' },\n ): Promise<T[]> => {\n // Empty: reserve no positions and produce no side effects (degenerate identity).\n if (inputs.length === 0) return [];\n const mode = opts?.mode ?? 'waitAll';\n const name = workflowName(workflow);\n // Reserve the whole block in list order BEFORE any dispatch — replay re-derives identical seqs.\n const positions = inputs.map(() => pos.next());\n const group = `all:${positions[0]}`;\n const id = (i: number) => `${runId}.all.${positions[0]}.${i}`;\n const existing = await Promise.all(positions.map((seq) => readCheckpoint(seq)));\n\n // failFast: bail the moment any already-completed item is a failed Completion.\n if (mode === 'failFast') {\n for (let i = 0; i < inputs.length; i += 1) {\n const cp = existing[i];\n const c =\n cp?.status === 'completed' ? (cp.output as { ok?: boolean; error?: string }) : null;\n if (c && c.ok === false) {\n // Cancel every sibling that hasn't completed yet — plain cancel, no saga undo. Best-effort:\n // a sibling mid-step only observes the cancellation at its NEXT checkpoint (it isn't\n // force-killed mid-synchronous-execution), so a fast-enough sibling can still slip through\n // and complete before it notices. `cancelChild` is deferred (like `startChild`), and\n // cancelling an already-terminal/cancelled run is a no-op, so replaying this branch after a\n // resume (which re-executes this loop and re-issues the same cancels) is safe.\n for (let j = 0; j < inputs.length; j += 1) {\n if (j !== i && existing[j]?.status !== 'completed') host.cancelChild?.(id(j));\n }\n throw new GatherError(\n [{ index: i, id: id(i), error: c.error ?? 'unknown' }],\n inputs.length,\n );\n }\n }\n }\n\n // Dispatch every item not yet completed in history; write its running placeholder once.\n let pending = false;\n for (let i = 0; i < inputs.length; i += 1) {\n const cp = existing[i];\n if (cp?.status === 'completed') continue;\n pending = true;\n const seq = positions[i] as number;\n const childId = id(i);\n // Carry the fan `group` onto the waiter too: the child's terminal `signal:child:` checkpoint is\n // (re)written by engine.signal when the child notifies the parent, OVERWRITING the running\n // placeholder below at the same seq — so without this the resolved checkpoint would lose the\n // group and the dashboard would render the resolved fan as a sequential chain.\n await store.putSignalWaiter({ token: `child:${childId}`, runId, seq, parallelGroup: group });\n if (!(await store.getRun(childId))) host.startChild(name, inputs[i], childId);\n if (!cp) {\n await writeCheckpoint(\n instantCheckpoint({\n runId,\n seq,\n name: `signal:child:${childId}`,\n kind: 'signal',\n status: 'running',\n parallelGroup: group,\n }),\n );\n }\n }\n // Any item still outstanding → suspend once; the resume replays this whole block.\n if (pending) throw new WorkflowSuspended();\n\n // All resolved: build outputs in INPUT order, aggregating any failures.\n const outputs: T[] = [];\n const failures: { index: number; id: string; error: string }[] = [];\n for (let i = 0; i < inputs.length; i += 1) {\n const c = existing[i]?.output as { ok?: boolean; value?: T; error?: string } | null;\n if (c && typeof c === 'object' && 'ok' in c && c.ok === false) {\n failures.push({ index: i, id: id(i), error: c.error ?? 'unknown' });\n outputs.push(undefined as T);\n } else {\n outputs.push((c as { value?: T } | null)?.value as T);\n }\n }\n if (failures.length > 0) throw new GatherError(failures, inputs.length);\n return outputs;\n };\n\n // Child workflow (fire-and-forget): dispatch it once and return its id WITHOUT suspending. The\n // start is checkpointed at this position so replay returns the same id without re-dispatching, and\n // is idempotent by id, so `child(..., sameId)` later joins the same run rather than starting a new\n // one (start + join scatter-gather).\n const startChild = async (\n workflow: WorkflowRef,\n input: unknown,\n options?: string | ChildCallOptions,\n ): Promise<string> => {\n const { childId, priority } = normalizeChildOptions(options);\n const current = pos.next();\n const id = childId ?? `${runId}.child.${current}`;\n const existing = await readCheckpoint(current);\n if (existing && existing.status === 'completed') return existing.output as string;\n if (!(await store.getRun(id))) host.startChild(workflowName(workflow), input, id, priority);\n await writeCheckpoint(\n instantCheckpoint({ runId, seq: current, name: `spawn:${id}`, kind: 'local', output: id }),\n );\n return id;\n };\n\n // Call a durable entity op and await its result: register a reply waiter at this position, dispatch\n // the op with the reply token, and suspend until the entity signals the result back (checkpointed,\n // so replay returns it without re-dispatching).\n const callEntity = async <R>(\n name: string,\n key: string,\n op: string,\n arg?: unknown,\n ): Promise<R> => {\n const current = pos.next();\n const existing = await readCheckpoint(current);\n if (existing && existing.status === 'completed') return existing.output as R;\n const reply = `entityreply:${runId}:${current}`;\n await store.putSignalWaiter({ token: reply, runId, seq: current });\n host.signalEntity?.(name, key, op, arg, reply);\n throw new WorkflowSuspended();\n };\n\n // Send a durable entity op without awaiting a result — dispatched once (checkpointed, replay-safe).\n const signalEntity = async (\n name: string,\n key: string,\n op: string,\n arg?: unknown,\n ): Promise<void> => {\n const current = pos.next();\n const existing = await readCheckpoint(current);\n if (existing && existing.status === 'completed') return;\n host.signalEntity?.(name, key, op, arg);\n await writeCheckpoint(\n instantCheckpoint({ runId, seq: current, name: `entitysig:${name}:${key}`, kind: 'local' }),\n );\n };\n\n // A breakpoint = a visible `pending` checkpoint + a signal waiter the dashboard resumes via\n // `engine.continue`. Reuses the signal machinery, so resume overwrites the pending checkpoint\n // with a completed one and the run replays past it.\n const breakpoint = async (label?: string): Promise<void> => {\n const current = pos.next();\n const existing = await readCheckpoint(current);\n if (existing && existing.status === 'completed') return;\n if (!existing) {\n await writeCheckpoint(\n instantCheckpoint({\n runId,\n seq: current,\n name: label ? `breakpoint:${label}` : 'breakpoint',\n kind: 'signal',\n status: 'pending',\n }),\n );\n await store.putSignalWaiter({ token: breakpointToken(runId, current), runId, seq: current });\n }\n throw new WorkflowSuspended();\n };\n\n // Guard an in-place change: a fresh run records a `patch:<id>` marker here and takes the new\n // branch; a run recorded under the OLD code finds a real step at this position instead, so we\n // rewind the logical position (the marker is transparent to it) and return false — its replay\n // reads that old step next and follows the old branch. No position shift → no corruption.\n const patched = async (id: string): Promise<boolean> => {\n const marker = `patch:${id}`;\n const current = pos.next();\n const existing = await readCheckpoint(current);\n if (existing) {\n if (existing.name === marker) return true;\n if (existing.name.startsWith('patch:')) {\n throw new NonDeterminismError(runId, current, marker, existing.name);\n }\n pos.rewind(); // not a marker: an old run's step lives here — give the position back to it\n return false;\n }\n await writeCheckpoint(\n instantCheckpoint({ runId, seq: current, name: marker, kind: 'local', output: true }),\n );\n return true;\n };\n\n // An update point: suspend on a run-scoped `update:<runId>:<name>` token that engine.update\n // delivers to (after its validator passes). Reuses the signal machinery; run-scoped like task/child.\n const onUpdate = <T>(name: string, opts?: { timeoutMs?: number }): Promise<T> =>\n waitForSignal<T>(`update:${runId}:${name}`, opts);\n\n // A queryable named value: a checkpoint whose `name` is `event:<key>`, so the latest value for a\n // key is just the highest-seq such checkpoint (read by engine.getEvent). Replay-idempotent.\n const setEvent = async (key: string, value: unknown): Promise<void> => {\n const current = pos.next();\n const name = `event:${key}`;\n const existing = await readCheckpoint(current);\n if (existing && existing.name !== name) {\n throw new NonDeterminismError(runId, current, name, existing.name);\n }\n if (existing && existing.status === 'completed') return; // replay: already published\n await writeCheckpoint(\n instantCheckpoint({ runId, seq: current, name, kind: 'local', output: value }),\n );\n };\n\n // A durable webhook reserves a logical position NOW to mint a stable token, so the url can be\n // handed to a third party before `wait()` suspends. `wait()` then parks on that same position\n // until the callback lands as engine.signal(token, body) — single position, replay-safe. The\n // deadline (when `wait({ timeoutMs })` is used) is a SEPARATE, later position — reserved lazily by\n // `wait()` itself, not at mint time, since the mint site has no `opts` to know a timeout was\n // requested. That's fine: `wait()` runs in the same deterministic order on every replay, so the\n // deadline seq it claims is stable too.\n const webhook = <T>(): DurableWebhook<T> => {\n const current = pos.next();\n const token = `wh:${runId}:${current}`;\n const wait = async (opts?: { timeoutMs?: number }): Promise<T> => {\n // A bounded wait claims its deadline position UNCONDITIONALLY, before the completed-replay\n // early return: the same `wait({ timeoutMs })` call re-runs on every replay, so the position\n // walk must be identical whether the callback has landed yet or not. (Claiming it lazily after\n // the early return would shift every later primitive by one on the post-callback replay and\n // trip the NonDeterminism guard on the stamped `timeout:*` checkpoint.)\n const timeoutMs = opts?.timeoutMs;\n const deadlineSeq = timeoutMs == null ? -1 : pos.next();\n const existing = await readCheckpoint(current);\n if (existing && existing.status === 'completed') return existing.output as T;\n if (timeoutMs == null) {\n await store.putSignalWaiter({ token, runId, seq: current });\n throw new WorkflowSuspended();\n }\n const deadline = await stampDeadline(deadlineSeq, token, timeoutMs);\n if (host.clock() >= deadline) {\n await store.takeSignalWaiter(token).catch(() => undefined);\n throw new SignalTimeoutError(token, timeoutMs);\n }\n await store.putSignalWaiter({ token, runId, seq: current });\n throw new WorkflowSuspended(deadline);\n };\n return { token, url: host.webhookUrl?.(token), wait };\n };\n\n // Deterministic capture: run `fn` once, checkpoint its output, and replay the SAME value verbatim\n // afterwards (fn is NOT re-run on replay). The general primitive for any non-deterministic value the\n // author controls the generator for — `ctx.sideEffect(() => uuidv7())`, `() => Math.random()`, a\n // config/env read. A raw `Date.now()`/`Math.random()` in a workflow body differs across replays and\n // corrupts the run; this captures it deterministically.\n const sideEffect = <T>(fn: () => T | Promise<T>): Promise<T> =>\n localStep('sideEffect', async () => fn());\n // `now` is the one ubiquitous convenience (a single obvious implementation, epoch ms like\n // `Date.now()`); everything else uses `sideEffect` so the author picks the generator.\n const now = () => localStep('now', async () => host.clock());\n\n // Merge into this run's searchAttributes exactly once: a checkpoint at this position marks it done,\n // so a replay SKIPS the write (mirrors `transaction` / the instant primitives) instead of re-merging\n // on every turn. Nondeterminism-guarded by the recorded marker name.\n const upsertSearchAttributes = async (attrs: SearchAttributes): Promise<void> => {\n const current = pos.next();\n const existing = await readCheckpoint(current);\n if (existing) {\n if (existing.name !== 'searchAttributes') {\n throw new NonDeterminismError(runId, current, 'searchAttributes', existing.name);\n }\n // Replayed: the write already happened on a prior turn — skip it, and (deliberately) skip\n // re-validating too. Validation only ever needs to run once, at the position it's recorded;\n // re-running it on replay would be redundant at best and, for a schema whose rules change\n // between deploys, a source of a replay throwing on history a live run already accepted.\n return;\n }\n if (searchAttributesSchema) {\n // The schema describes the whole run's search-attribute shape (optional keys included), so\n // validate the MERGED result — this call's `attrs` shallow-merged onto what's already on the\n // run — not `attrs` alone. Mirrors the merge `host.upsertSearchAttributes` itself performs;\n // read here is best-effort (not transactional with the host's own read+write), same as that\n // merge already is.\n const run = await store.getRun(runId);\n const merged = { ...(run?.searchAttributes ?? {}), ...attrs };\n const result = searchAttributesSchema['~standard'].validate(merged);\n if (result instanceof Promise) {\n throw new Error(\n `workflow \"${workflow}\": ctx.upsertSearchAttributes schema validation must be synchronous (the searchAttributes schema's \\`~standard.validate\\` returned a Promise) — replay-determinism requires a sync validator; drop any async refinement from the schema passed to @Workflow({ searchAttributes }).`,\n );\n }\n if (result.issues) {\n const offendingKeys = [\n ...new Set(result.issues.map((issue) => formatIssuePath(issue.path))),\n ];\n const details = result.issues\n .map((issue) => `${formatIssuePath(issue.path)}: ${issue.message}`)\n .join('; ');\n throw new Error(\n `workflow \"${workflow}\": ctx.upsertSearchAttributes rejected by its searchAttributes schema — ` +\n `offending key(s) ${offendingKeys.join(', ')} — ${details}`,\n );\n }\n }\n await host.upsertSearchAttributes(runId, attrs);\n await writeCheckpoint(\n instantCheckpoint({\n runId,\n seq: current,\n name: 'searchAttributes',\n kind: 'local',\n output: attrs,\n }),\n );\n };\n\n // Resolve a `ctx.step(..., { compensate })` ref/string into the undo's own dispatchable StepDef —\n // same routing-name resolution as the step it's attached to (see `step` below), but its dispatch\n // policy comes ONLY from its own `@Step`-stamped config (stepConfigOf), never the compensated\n // call's per-call `opts`: the undo is a separately-declared handler with its own retry/backoff, not\n // an extension of the step it undoes. The string form (cross-runtime, unchecked) has no stamped\n // config, so it dispatches with engine defaults. Takes `unknown` (like `stepNameOf`/`stepConfigOf`\n // themselves) rather than a `StepRef<StepUndo<TInput, TOutput>, ...>` — the caller's TInput/TOutput\n // are call-site type parameters with no runtime shape to check here; the compile-time contract is\n // already enforced by `WorkflowCtx.step`'s overload signature (interfaces.ts) that typed `opts`.\n function resolveCompensateDef(compensate: unknown): StepDef<StepUndo<unknown, unknown>, unknown> {\n const name = typeof compensate === 'string' ? compensate : stepNameOf(compensate);\n if (name === undefined) {\n throw new Error(\n 'ctx.step: compensate handler is not a @Step reference (no stamped step name) — pass a @Step-decorated method or a step name string',\n );\n }\n const config = typeof compensate === 'string' ? undefined : stepConfigOf(compensate);\n return { name, ...resolveStepPolicy(config, undefined) };\n }\n\n // ONE durable step primitive: always dispatched, always engine-scheduled — no local/remote\n // placement choice for the workflow author (see `WorkflowCtx.step`). Resolve the routing name off\n // a `@Step`-stamped handler reference, or take it literally for the cross-runtime string form; the\n // reference itself is NEVER invoked here — only its stamped name (and dispatch policy) is read (the\n // serving worker re-resolves the real handler from DI), so an unbound `this` on `handlerOrName` is\n // irrelevant. The effective durable-retry/liveness policy is `{ ...stepConfigOf(handlerOrName),\n // ...opts }` — the `@Step`-declared def-level policy, with a per-call `opts` field winning wherever\n // it's set. The string form has no stamped config, so it uses `opts` only. Carrying this policy onto\n // the `StepDef` re-enables `callRemote`'s durable retry/backoff and liveness-timeout branches (see\n // `engine.ts`), which were otherwise orphaned.\n function step<TInput, TOutput>(\n handlerOrName: StepRef<TInput, TOutput> | string,\n input: TInput,\n opts?: StepDispatchOpts & { compensate?: StepRef<StepUndo<TInput, TOutput>, unknown> | string },\n ): Promise<TOutput> {\n const name = typeof handlerOrName === 'string' ? handlerOrName : stepNameOf(handlerOrName);\n if (name === undefined) {\n throw new Error(\n 'ctx.step: handler is not a @Step reference (no stamped step name) — pass a @Step-decorated method or a step name string',\n );\n }\n const config = typeof handlerOrName === 'string' ? undefined : stepConfigOf(handlerOrName);\n const def: StepDef<TInput, TOutput> = { name, ...resolveStepPolicy(config, opts) };\n return host\n .callRemote(runId, pos.next(), def, input, opts?.queue, opts?.transport, {\n priority: opts?.priority,\n fairnessKey: opts?.fairnessKey,\n })\n .then((output) => {\n // `callRemote` resolves ONLY once this step is durably complete — the replay-completed branch\n // (a checkpointed output) or the in-memory `timeoutMs` liveness path once the live result\n // lands (engine.ts). Register the compensation HERE, after that resolution, so a saga only\n // ever undoes steps that actually finished. Mirrors `localStep`'s rebuild-on-replay: the\n // workflow body re-passes `compensate` on every replay of a completed call, and `input`/\n // `output` come straight from this call (the checkpointed ones on replay) — no store-schema\n // change needed to carry the undo's args.\n if (opts?.compensate) {\n compensations.push({\n name,\n dispatch: { def: resolveCompensateDef(opts.compensate), args: { input, output } },\n });\n }\n return output;\n });\n }\n\n return {\n runId,\n step,\n localStep,\n upsertSearchAttributes,\n transaction,\n callEntity,\n signalEntity,\n sleep,\n sleepUntil,\n continueAsNew,\n waitForSignal,\n waitForEvent,\n task,\n child,\n all,\n startChild,\n breakpoint,\n webhook,\n setEvent,\n onUpdate,\n patched,\n now,\n sideEffect,\n };\n}\n","import { type AdmissionBackend, InMemoryAdmissionBackend } from './admission';\nimport { runInWorkflowCtx } from './ambient-ctx';\nimport { backoffDelay } from './backoff';\nimport { instantCheckpoint, stepCheckpoint } from './checkpoints';\nimport { type Completion } from './completion';\nimport { parseDuration } from './duration';\nimport { Entities, type EntityConfig } from './entities';\nimport {\n ContinueAsNew,\n FatalError,\n NonDeterminismError,\n RemoteStepTimeout,\n RemoteWorkflowTimeout,\n SignalTimeoutError,\n WorkflowSuspended,\n} from './errors';\nimport { EventAccumulators, type EventBatchConfig } from './event-accumulators';\nimport {\n EVENT_BUFFER_SCAN_LIMIT,\n eventMatchOf,\n eventMatches,\n eventNameOf,\n eventPrefix,\n isEventToken,\n} from './events';\nimport type {\n ControlPlane,\n EngineEvent,\n EngineListener,\n GroupHealth,\n NamedTransport,\n RemoteTask,\n RunDispatcher,\n RunQuery,\n RunResult,\n RunStatus,\n SearchAttributes,\n SearchAttributesSchema,\n SignalWaiter,\n StateStore,\n StepCheckpoint,\n StepDef,\n StepError,\n StepEvent,\n StepInterceptor,\n StepInvocation,\n StepKind,\n StepResult,\n StepUndo,\n Transport,\n UpdateResult,\n UpdateValidator,\n WorkflowCommand,\n WorkflowCtx,\n WorkflowDecision,\n WorkflowExecutor,\n WorkflowRun,\n WorkflowStepEvent,\n} from './interfaces';\nimport type { HistoryEvent } from './interfaces';\nimport { breakpointToken, stepId } from './protocol';\nimport type { QueueConfig } from './queue';\nimport { RemoteWorkflowExecutor } from './remote-workflow-executor';\nimport { indexWaitersByRun } from './run-waiting';\nimport { SingletonGate } from './singleton-gate';\nimport { sanitizeQueueToken, tenantGroup } from './tenant-group';\nimport { TransportPool } from './transport-pool';\nimport {\n type Compensation,\n type CtxHost,\n type InternalWorkflowCtx,\n type StepRecord,\n createWorkflowCtx,\n} from './workflow-ctx';\nimport {\n type WorkflowClass,\n type WorkflowInputOf,\n type WorkflowRef,\n workflowName,\n} from './workflow-ref';\n\n// The engine ALWAYS runs a body with the InternalWorkflowCtx `createWorkflowCtx` produces (it carries\n// the internal `localStep` the entity runner + capture helpers need). Public authors type their body\n// with the narrower `WorkflowCtx`; contravariance keeps those assignable to this param, so the internal\n// type never leaks into the public authoring surface while `EntityHost.register` still lines up.\ntype WorkflowFn = (ctx: InternalWorkflowCtx, input: unknown) => Promise<unknown>;\n\n/** Options for {@link WorkflowEngine.start}. */\nexport interface StartOptions {\n /** Run-scoped tags, merged with the workflow's static `@Workflow({ tags })` onto the run. */\n tags?: string[] | undefined;\n /** Typed, queryable run data stamped on the run (e.g. `{ amount: 200, tier: 'pro' }`). */\n searchAttributes?: SearchAttributes | undefined;\n /**\n * Dispatch priority for a remote run — stamped on the run and carried onto every {@link WorkflowTask}\n * the engine dispatches to advance it. Higher wins; absent = unprioritised. See {@link WorkflowRun.priority}.\n */\n priority?: number | undefined;\n /**\n * Override the namespace stamped on the run. Defaults to the engine's own `namespace`. Set by the\n * control plane when it starts a run on behalf of a tenant (a {@link StartRunMessage}'s `tenant`\n * maps here), so one DB-less-tenant-facing engine can create runs across many namespaces.\n */\n namespace?: string | undefined;\n}\n\n/**\n * Serialize runs of a workflow that share a key — a durable, FIFO mutex (e.g. one pipeline per base).\n * Excess runs are admitted in creation order, `limit` at a time; the rest wait (suspended) and retry\n * admission on a timer until a slot frees. Race-free on a consistent store (admission order is the\n * same `(createdAt, id)` view for every instance).\n */\nexport interface SingletonConfig {\n /** Derive the serialization key from the workflow input. */\n key: (input: unknown) => string;\n /** Max concurrent runs sharing the key. Default 1 (a mutex). */\n limit?: number;\n /**\n * Max GATED (waiting-for-admission) runs allowed to queue behind the `limit` in-flight ones. When\n * set, `start` rejects with {@link SingletonQueueFullError} once in-flight + gated reaches\n * `limit + maxQueueDepth` — back-pressure against an unbounded same-key backlog. Omit for the\n * default unbounded queue. Counts `pending`/`running`/`suspended` runs sharing the key.\n */\n maxQueueDepth?: number;\n}\n\n/** Union of a workflow's static tags and a run's start-time tags, de-duplicated, or undefined if none. */\nfunction mergeTags(staticTags?: string[], runTags?: string[]): string[] | undefined {\n if (!staticTags?.length && !runTags?.length) return undefined;\n return [...new Set([...(staticTags ?? []), ...(runTags ?? [])])];\n}\n\n/** A breakpoint checkpoint's `name` is `breakpoint` (or `breakpoint:<label>`). This name — not the\n * reused `signal` kind — is the explicit marker the dashboard and `continue()` detect it by. */\nconst BREAKPOINT = 'breakpoint';\nconst isBreakpoint = (cp: { status: string; name: string }): boolean =>\n cp.status === 'pending' && cp.name.startsWith(BREAKPOINT);\n\ninterface RegisteredWorkflow {\n name: string;\n version: string;\n fn: WorkflowFn;\n /** Static `@Workflow({ tags })` — merged with per-run tags onto each run at start. */\n tags?: string[] | undefined;\n /** Per-key serialization (a durable mutex). See {@link SingletonConfig}. */\n singleton?: SingletonConfig | undefined;\n /** Max wall-clock lifetime (ms) before a run is cancelled by `sweepTimeouts`. */\n executionTimeoutMs?: number | undefined;\n /** Validate the input at start; throw to reject before a run is created. Validator-agnostic. */\n validateInput?: ((input: unknown) => void | Promise<void>) | undefined;\n /** Typed/validated `searchAttributes` shape. When set, `ctx.upsertSearchAttributes` validates the\n * merged result against it (see `createWorkflowCtx`). See `WorkflowMeta.searchAttributes`. */\n searchAttributesSchema?: SearchAttributesSchema | undefined;\n /** Event names that start a fresh run of this workflow when published. See `publishEvent`. */\n onEvent?: string[] | undefined;\n /** Coalesce `onEvent` triggers: debounce (fire once it's quiet) or batch (fire on size/window). */\n eventBatch?: EventBatchConfig | undefined;\n /** Set for a workflow advanced by DISPATCH instead of an inline `fn`: a cross-SDK (e.g. Python)\n * body via {@link WorkflowEngine.registerRemote}, OR a group-served TS body via\n * `register(..., { group, executor })`. The engine hands the run's history to `executor` (which\n * dispatches a workflow task to `group`) rather than running `fn` in-process. See\n * {@link WorkflowExecutor}. */\n remote?: { group: string; executor: WorkflowExecutor };\n /** True when `fn` is a real in-process body (`register`), false/absent for a body-less remote whose\n * `fn` is the throwing stub (`registerRemote` / a synthesized remote child). Gates\n * {@link WorkflowEngine.workflowBody} so an in-app worker only ever gets a runnable body. */\n hasBody?: boolean | undefined;\n}\n\nconst versionKey = (name: string, version: string): string => `${name}@${version}`;\n\n/** The id for the next continuation of a run: `r` → `r~1` → `r~2` … (stable, traceable lineage). */\nfunction nextContinuationId(runId: string): string {\n const m = runId.match(/^(.*)~(\\d+)$/);\n return m ? `${m[1]}~${Number(m[2]) + 1}` : `${runId}~1`;\n}\n\n/** True when version `a` is newer than `b` (numeric when both parse as numbers, else natural sort). */\nfunction isNewerVersion(a: string, b: string): boolean {\n const na = Number(a);\n const nb = Number(b);\n if (!Number.isNaN(na) && !Number.isNaN(nb)) return na > nb;\n return a.localeCompare(b, undefined, { numeric: true }) > 0;\n}\n\n/** What a remote worker hands back: the output plus when it actually began (for queue-wait timing). */\ninterface RemoteResolution {\n output: unknown;\n startedAt?: number | undefined;\n events?: StepEvent[] | undefined;\n}\n\ninterface PendingRemote {\n resolve: (result: RemoteResolution) => void;\n reject: (error: Error) => void;\n}\n\n/** A terminal/suspended transition handed to {@link WorkflowEngine.settleRun}. */\ntype RunOutcome =\n | { kind: 'completed'; output: unknown }\n | { kind: 'failed'; error: StepError }\n | { kind: 'suspended'; wakeAt?: number | undefined };\n\n/**\n * What {@link WorkflowEngine.unwindCompensations} returns when the run must keep waiting on a\n * dispatched compensation — `wakeAt` set while backing off a durable retry (the due-timer poller\n * re-drives it once elapsed), absent while freshly dispatched/in flight (only the worker's result,\n * via `completeRemoteResult`, re-drives it). `undefined` (no `UnwindPending`) means every\n * compensation resolved. Deliberately NOT a `RunResult`: the two callers persist \"still unwinding\"\n * differently (a plain `suspended` run for the failure path; `cancelling` held as-is for the cancel\n * path — see `compensateAndCancel`), so the settling is left to them.\n */\ninterface UnwindPending {\n wakeAt?: number | undefined;\n}\n\nexport interface WorkflowEngineDeps {\n store: StateStore;\n /** A single task transport. Shorthand for a one-entry `transports` pool (id `default`). */\n transport?: Transport | undefined;\n /**\n * An ordered pool of named transports. The engine dispatches on the first and fails over to the\n * next on a dispatch error; a step pins one via `ctx.step(step, input, { transport: id })`. Use\n * this instead of `transport` for failover / multi-broker setups.\n */\n transports?: NamedTransport[] | undefined;\n /**\n * Cross-instance broadcast pub/sub for lifecycle events + cancellation (see {@link ControlPlane}).\n * Separate from the task `transport`; omit for a single-instance / local-only setup. A transport\n * that can also broadcast may be passed here as well.\n */\n controlPlane?: ControlPlane | undefined;\n /** Epoch-ms clock; injectable for tests. Defaults to `Date.now`. */\n clock?: (() => number) | undefined;\n /**\n * Flow-control admission backend for `ctx.step(step, input, { queue })`. Defaults to an in-process\n * {@link InMemoryAdmissionBackend} (per-instance caps). Inject a store/Redis-backed backend to make\n * concurrency / rate-limit / ordering GLOBAL across engine replicas.\n */\n admission?: AdmissionBackend | undefined;\n /** Unique id for this engine instance, used for recovery leases. Defaults to a random id. */\n instanceId?: string | undefined;\n /**\n * Worker-pool partition for this engine. Stamped on every run it creates; the poll paths\n * (`runPending`/`recoverIncomplete`/`resumeDueTimers`/`sweepTimeouts`) only act on runs in this\n * namespace. Set distinct values to safely share ONE state store across non-interchangeable pools\n * (e.g. local dev vs a cluster). **Omit it to make this engine an OPERATOR** — an unset namespace\n * drives/recovers/resumes runs of EVERY namespace (the poll filters no-op, the resume/decision\n * guards fall through) and leaves the transport on its bare prefix. This is the hosted control\n * plane: \"ver tudo = ausência de namespace\".\n */\n namespace?: string | undefined;\n /** Recovery lease duration in ms — how long this instance owns a run it picked up. Default 30s. */\n leaseMs?: number | undefined;\n /**\n * Cap how many times crash-recovery may pick up the same still-`running` run before giving up and\n * moving it to the `dead` dead-letter state (a poison pill that crashes the process every boot).\n * Omit for unlimited (the default — recovery always retries).\n */\n maxRecoveryAttempts?: number | undefined;\n /**\n * Opt-in liveness deadline (ms) for a remote workflow `advance`. If the worker neither returns a\n * decision NOR sends a run-scoped {@link Heartbeat} within this window, the engine presumes it dead:\n * it rejects the advance with {@link RemoteWorkflowTimeout}, releases the lease, and lets recovery\n * re-drive (replaying completed steps from history). Each beat REARMS the window, so a worker still\n * legitimately replaying a long turn (it keeps beating) is never re-driven — closing the duplicate-\n * side-effect hazard a fixed {@link RemoteWorkflowExecutor} `timeoutMs` cannot avoid. Omit (default)\n * for the prior unbounded await — byte-identical behavior when unset. If a `RemoteWorkflowExecutor` is\n * ALSO constructed with its own `timeoutMs`, the shorter of the two deadlines wins; prefer setting only\n * one (this rearmed window for heartbeat-aware workers, or the fixed `timeoutMs` otherwise).\n */\n remoteAdvanceSilenceMs?: number | undefined;\n /**\n * Fallback re-drive window (ms) for a run that SUSPENDS with no natural timer — i.e. it's waiting on\n * an EVENT to wake it (a child's completion, a signal, a remote step with no `timeoutMs`) rather than\n * a `ctx.sleep`. Those events re-drive the run directly; but if the wake is LOST (the delivering pod\n * crashed / rolled mid-handoff), the run would otherwise sit `suspended` forever with `wakeAt: null` —\n * invisible to both the timer poller (no `wakeAt`) and crash-recovery (no lease). This stamps a\n * fallback `wakeAt` so {@link resumeDueTimers} re-drives it after the window; the re-drive is an\n * idempotent replay (a still-pending dependency re-suspends via the checkpoint guard, a settled one\n * advances), so it's a safe self-heal, not a retry that can double-dispatch. The primary event path\n * still wins first for a healthy run (it re-drives long before this fires), so this only ever fires\n * for a genuinely-orphaned run. Default 5min; set `0` to disable (the prior wake-forever behavior).\n */\n reconcileMs?: number | undefined;\n /**\n * Retention for a BUFFERED event that no `waitForEvent` ever claims (see\n * {@link WorkflowEngine.publishEvent}'s buffering — a publish matching no live waiter keeps ONE\n * copy around for a later matching wait). Default `undefined`: keep it until consumed, same as\n * {@link StateStore.bufferSignal}'s buffered signals — no silent expiry. Set a duration (ms) to\n * have the {@link resumeDueTimers} reconcile pass prune rows past `publishedAt + eventBufferTtlMs`\n * as it encounters them. Scoped to event NAMES the current reconcile tick's registered waiters\n * reference (the sweep has no reason to otherwise enumerate every buffered name) — a name with a\n * stale buffered event but zero waiters ever registered against it is not visited by this pass; that\n * is an accepted gap given `listBufferedEvents` is name-scoped by design (see interfaces.ts), not a\n * bug to route around here.\n */\n eventBufferTtlMs?: number | undefined;\n /**\n * Opt-in self-heal window (ms) for a remote step with NO `timeoutMs` whose dispatched job was LOST —\n * the worker crashed mid-step leaving no result, or the transport dropped the job (a Redis\n * flush/eviction, or BullMQ moving a stalled job to `failed` and removing it). The `pending`\n * checkpoint then has no result to resume on, and — BY DESIGN (see {@link reconcileMs}) — the\n * reconcile re-drive re-suspends a still-pending step rather than re-dispatching, so a slow-but-live\n * worker is never double-run. That safety means a genuinely-lost dispatch would otherwise hang\n * forever. When set, a reconcile re-drive that finds a remote step still `pending` PAST this window\n * re-dispatches it (bumping `attempts`, bounded by {@link remoteRedispatchMax}). Off by default:\n * re-dispatch can double-run a step whose original job is merely slow, so the window MUST exceed the\n * longest such step and the step MUST be idempotent. Prefer a per-step `timeoutMs` (tighter,\n * heartbeat-aware) where you can; this is the store-driven net for no-timeout steps that must\n * survive a lost dispatch. {@link WorkflowEngine.redispatchPending} is the manual counterpart.\n */\n remoteRedispatchMs?: number | undefined;\n /**\n * Max times {@link remoteRedispatchMs} re-dispatches one lost remote step before giving up and\n * failing it as a {@link RemoteStepError} (`code: 'remote_step_lost'`), so the run fails / dead-letters\n * instead of re-dispatching forever. Default 10. Ignored when `remoteRedispatchMs` is unset.\n */\n remoteRedispatchMax?: number | undefined;\n /**\n * Build the public callback URL for a `ctx.webhook()` token (e.g.\n * ``(t) => `https://api.example.com/durable/webhooks/${t}` ``). Populates\n * {@link DurableWebhook.url}. Omit if you build URLs yourself from the token.\n */\n webhookUrl?: ((token: string) => string) | undefined;\n /**\n * Provide the current W3C `traceparent` to stamp on each dispatched {@link RemoteTask}, so a\n * worker (including the Python SDK) continues the distributed trace. Keep core OTel-free: supply\n * `otelTraceparent` from `@dudousxd/nestjs-durable-otel`, or your own context reader. Omit to send none.\n */\n traceparent?: (() => string | undefined) | undefined;\n /**\n * Provide an opaque context carrier (tenant / user / correlation ids) to attach to each dispatched\n * {@link RemoteTask} as its `context`, so a worker (including the Python SDK) re-exposes it to the\n * step handler — cross-process propagation alongside the {@link traceparent}. Keep core dependency-free:\n * supply this from `@dudousxd/nestjs-context` or your own request-scoped reader. The engine never\n * inspects the returned object's shape. Omit to send none.\n *\n * Re-evaluated at each (re)dispatch — including a retry or a resume that the engine drives AFTER a\n * crash/scale-down, which runs OUTSIDE the originating request scope. On such a path this provider\n * may return empty or stale values (the request-scoped tenant/user is gone). Treat the carrier as\n * best-effort correlation/propagation metadata only — do NOT treat it as an authorization boundary.\n */\n context?: (() => Record<string, unknown> | undefined) | undefined;\n /**\n * Re-hydrate the originating context around a LOCAL step body, so a `@DurableStep` reader sees the\n * tenant / user / correlation ids that were live when the run was started — even on a path the\n * engine drives outside the originating request scope (a resume after crash/scale-down, a timer).\n * Given the carrier produced by {@link context} (may be empty/undefined) and the step body `fn`, it\n * runs `fn` with that context ambiently established (e.g. inside `@dudousxd/nestjs-context`'s ALS)\n * and returns its result. Keep core dependency-free: supply this from the nestjs wiring (which owns\n * nestjs-context) or your own ALS bridge. The handler signature is unchanged — re-hydration is\n * ambient. Default: passthrough (`(_, fn) => fn()`), so behavior is byte-identical when unset.\n */\n rehydrate?: (<T>(carrier: Record<string, unknown> | undefined, fn: () => T) => T) | undefined;\n /**\n * Attempts for each saga compensation when the run fails (a transient undo — e.g. a refund API\n * hiccup — gets another try). Default 1 (no retry). Compensations must be idempotent.\n */\n compensationRetries?: number | undefined;\n /**\n * Persist a `running` checkpoint when a local step's body begins, so an in-flight step shows up\n * in the dashboard (and a fresh page load / REST query) the moment it starts — not only once it\n * completes. The `step.started` lifecycle event is emitted either way (the live SSE view always\n * sees the start); this flag only controls the extra checkpoint write. Default `true`. Set\n * `false` on hot paths with many short local steps to halve their checkpoint writes — you keep\n * the live event but lose reload-survivable in-flight visibility.\n */\n trackStepStart?: boolean | undefined;\n /**\n * Where a freshly-`start`ed run executes (see {@link RunDispatcher}). Defaults to in-process: the\n * run executes on this instance asynchronously (a microtask), so `start` returns without blocking.\n * Pass a no-op dispatcher on a caller that must NOT run workflows (e.g. an API/dashboard pod), and\n * run `runPending` on a worker pod to pick those up; or a broker-backed one for a worker pool.\n */\n runDispatcher?: RunDispatcher | undefined;\n}\n\n/** Thrown by {@link WorkflowEngine.resume} when the run belongs to a different namespace. */\nclass NamespaceMismatch extends Error {\n constructor() {\n super('namespace-mismatch');\n }\n}\n\n/**\n * The orchestrator. Owns workflow state and replays runs deterministically: each step's\n * result is checkpointed, so on resume a completed step returns its saved output instead of\n * re-executing. Remote steps are dispatched over the Transport; their results checkpoint the\n * same way local steps do.\n */\nexport class WorkflowEngine {\n private readonly store: StateStore;\n /** Ordered transport pool (dispatch + failover). Empty = no remote steps. */\n private readonly pool: TransportPool;\n private readonly controlPlane?: ControlPlane | undefined;\n private readonly clock: () => number;\n private readonly instanceId: string;\n private readonly namespace: string | undefined;\n private readonly leaseMs: number;\n private readonly maxRecoveryAttempts?: number | undefined;\n private readonly remoteAdvanceSilenceMs?: number | undefined;\n private readonly reconcileMs: number | undefined;\n private readonly eventBufferTtlMs: number | undefined;\n private readonly remoteRedispatchMs: number | undefined;\n private readonly remoteRedispatchMax: number;\n private readonly webhookUrl?: ((token: string) => string) | undefined;\n private readonly traceparent?: (() => string | undefined) | undefined;\n private readonly context?: (() => Record<string, unknown> | undefined) | undefined;\n /** Establish the originating context ambiently around a local step body (see {@link WorkflowEngineDeps.rehydrate}). Default passthrough. */\n private readonly rehydrate: <T>(carrier: Record<string, unknown> | undefined, fn: () => T) => T;\n private readonly compensationRetries: number;\n /** Persist a `running` checkpoint at the start of a local step body (see {@link WorkflowEngineDeps.trackStepStart}). */\n private readonly trackStepStart: boolean;\n /** Where a freshly-started run executes — in-process by default (see {@link RunDispatcher}). */\n private readonly runDispatcher: RunDispatcher;\n\n /** Per-key serialization for singleton workflows (admission, back-pressure, notify-on-release). */\n private readonly singletons: SingletonGate;\n /** Every registered workflow, keyed by `name@version` — so old versions stay runnable. */\n private readonly workflows = new Map<string, RegisteredWorkflow>();\n /** The newest registered version per workflow name — used to `start` new runs. */\n private readonly latest = new Map<string, RegisteredWorkflow>();\n /** Event name → workflow names started when that event is published (see `onEvent`). */\n private readonly eventTriggers = new Map<string, Set<string>>();\n /** Durable-entity subsystem (registers the `__entity` runner; see `registerEntity`). */\n private readonly entities: Entities;\n /** Event debounce/batch accumulators (register the `__evt_*` runners; see `accumulators.route`). */\n private readonly accumulators: EventAccumulators;\n /** In-flight remote steps awaiting a worker result, keyed by stepId. */\n private readonly pending = new Map<string, PendingRemote>();\n /** \"Reset the liveness timer\" callbacks keyed by the beat's target — a stepId (in-flight remote step)\n * or a runId (in-flight remote workflow turn) — invoked when a matching heartbeat arrives. The two id\n * shapes don't collide in practice: a stepId is `${runId}:${seq}`, a run key is the bare runId. */\n private readonly heartbeatResets = new Map<string, () => void>();\n private readonly listeners = new Set<EngineListener>();\n /** Step interceptors (onion middleware around real local-step execution), first = outermost. */\n private readonly interceptors: StepInterceptor[] = [];\n /** Callbacks notified (on any instance) when a run is cancelled — for cooperative cancellation. */\n private readonly cancelListeners = new Set<(runId: string) => void>();\n /** Callbacks notified when a run is enqueued elsewhere — for low-latency cross-pod dispatch. */\n private readonly enqueuedListeners = new Set<(runId: string) => void>();\n /** Notified when a run is dead-lettered (moved to `dead`) — a hook for a DLQ handler. */\n private readonly deadListeners = new Set<(run: WorkflowRun) => void>();\n /** Validators gating `engine.update`, keyed by `<workflow>:<updateName>`. */\n private readonly updateValidators = new Map<string, UpdateValidator>();\n /** Runs being cancelled WITH saga compensation — see `cancel({ compensate: true })`. */\n private readonly cancelRequested = new Set<string>();\n /** Flow-control admission backend for remote steps (see {@link registerQueue}). */\n private readonly admission: AdmissionBackend;\n /** Runs on THIS instance blocked on admission, by queue — woken early on a freed-slot signal. */\n private readonly queueWaiters = new Map<string, Set<string>>();\n /** Which queue a dispatched step took a slot from, by stepId — so the result can release it. */\n private readonly stepQueue = new Map<string, string>();\n /** Executions currently in flight, so a graceful shutdown can wait for them to settle. */\n private readonly inflight = new Set<Promise<RunResult>>();\n private draining = false;\n\n constructor(deps: WorkflowEngineDeps) {\n this.store = deps.store;\n this.pool = new TransportPool(\n deps.transports ?? (deps.transport ? [{ id: 'default', transport: deps.transport }] : []),\n );\n this.controlPlane = deps.controlPlane;\n this.clock = deps.clock ?? Date.now;\n this.admission = deps.admission ?? new InMemoryAdmissionBackend(this.clock);\n // Wake this instance's admission-blocked runs the moment a slot frees anywhere in the fleet,\n // instead of waiting for their retry tick. Best-effort (the retry tick remains the guarantee).\n this.admission.onFreed?.((queue) => this.wakeQueueWaiters(queue));\n this.instanceId = deps.instanceId ?? globalThis.crypto.randomUUID();\n this.namespace = deps.namespace;\n // The engine's namespace deliberately does NOT touch the transport(s). The two tenancy axes are\n // orthogonal and encode differently ON PURPOSE (the cross-SDK canonical wire convention):\n // - `namespace` scopes the STORE (which runs this engine drives/recovers) and stamps every run\n // it starts; per-run routing then suffixes GROUP tokens (`<name>@<tenant>`, see tenantGroup)\n // on the transport's own prefix — the same convention every worker SDK (Python, the TS\n // tenant role) speaks natively.\n // - Whole-DEPLOYMENT isolation on a shared broker is the transport's `prefix`/`namespace`\n // constructor options — explicit, never inferred from the engine.\n // (An earlier design auto-folded a scoped engine's namespace into the transport prefix,\n // producing a keyspace no tenant worker could see — the tenant ended up encoded twice, once in\n // the prefix and once in the group suffix, and cross-runtime discovery silently failed.)\n this.leaseMs = deps.leaseMs ?? 30_000;\n this.maxRecoveryAttempts = deps.maxRecoveryAttempts;\n this.remoteAdvanceSilenceMs = deps.remoteAdvanceSilenceMs;\n // Default 5min; an explicit 0 disables the fallback (opt back into wake-forever-on-lost-event).\n this.reconcileMs = deps.reconcileMs === undefined ? 300_000 : deps.reconcileMs || undefined;\n // Opt-in: unset (or 0) keeps buffered events around forever, same as buffered signals.\n this.eventBufferTtlMs = deps.eventBufferTtlMs || undefined;\n // Opt-in: unset (or 0) leaves the by-design \"re-suspend a lost dispatch, never re-dispatch\" behavior.\n this.remoteRedispatchMs = deps.remoteRedispatchMs || undefined;\n this.remoteRedispatchMax = Math.max(1, deps.remoteRedispatchMax ?? 10);\n this.webhookUrl = deps.webhookUrl;\n this.traceparent = deps.traceparent;\n this.context = deps.context;\n // Default passthrough: with no bridge supplied, a local step body runs exactly as before.\n this.rehydrate = deps.rehydrate ?? ((_carrier, fn) => fn());\n this.compensationRetries = Math.max(1, deps.compensationRetries ?? 1);\n this.trackStepStart = deps.trackStepStart ?? true;\n // Default: execute the run on this instance, asynchronously, so `start` never blocks on the body.\n // A failed pickup is swallowed here (the run stays `pending` for a `runPending` poll to retry);\n // run failures themselves are handled inside `execute` and surfaced as the run's `failed` state.\n this.runDispatcher = deps.runDispatcher ?? {\n dispatch: (runId) => queueMicrotask(() => void this.runOne(runId).catch(() => {})),\n };\n this.singletons = new SingletonGate({\n store: this.store,\n clock: this.clock,\n dispatch: (runId) => {\n this.runDispatcher.dispatch(runId);\n },\n configFor: (run) =>\n (\n this.workflows.get(versionKey(run.workflow, run.workflowVersion)) ??\n this.latest.get(run.workflow)\n )?.singleton,\n });\n this.pool.bind(\n async (result) => {\n // In-memory path (a `timeoutMs` step awaiting on THIS instance): resolve its pending promise.\n const waiter = this.pending.get(result.stepId);\n if (waiter) {\n this.pending.delete(result.stepId);\n if (result.status === 'completed') {\n waiter.resolve({\n output: result.output,\n startedAt: result.startedAt,\n events: result.events,\n });\n } else {\n waiter.reject(new RemoteStepError(result.error));\n }\n return;\n }\n // Durable path: no in-memory waiter (the step suspended the run, possibly on another\n // instance) → complete the checkpoint and resume the run here.\n await this.completeRemoteResult(result);\n },\n // A heartbeat resets the liveness window for whatever it targets: an in-flight long STEP (keyed\n // by stepId, see callRemote) or — when stepId is absent — the in-flight workflow TURN (keyed by\n // runId). For an INLINE-advance turn the reset is an in-memory callback; for a DISPATCH-suspend\n // turn there is no in-memory waiter, so a run-scoped beat rearms the suspended turn's durable\n // re-drive deadline (`wakeAt`) instead, keeping a live worker's turn from being re-dispatched.\n async (beat) => {\n const reset = this.heartbeatResets.get(beat.stepId ?? beat.runId);\n if (reset) {\n reset();\n return;\n }\n if (beat.stepId === undefined) await this.rearmDecisionDeadline(beat.runId);\n },\n // A remote workflow worker streams each local step's lifecycle (running → completed/failed) so\n // it's checkpointed live, not all-at-once when the long turn ends.\n async (event) => {\n await this.persistStepEvent(event);\n },\n // A workflow-turn DECISION delivered over the broker — applied durably (by run id) on whatever\n // instance consumes it, NOT correlated to an in-memory promise on the dispatcher. This is the\n // multi-instance fix: a point-to-point broker may hand the decision to a non-dispatching instance.\n async (decision) => {\n await this.completeRemoteDecision(decision);\n },\n );\n // Control-plane start-run: a DB-less tenant worker publishes a StartRunMessage and this\n // (control-plane) engine turns it into a durable run stamped with the tenant's namespace. Guarded\n // by the transport's `onStartRun` capability (like the other optional transport hooks) — a pool\n // whose transport can't carry the channel simply never registers, so a worker-only engine no-ops.\n this.pool.onStartRun(async (message) => {\n await this.start(\n message.workflow,\n message.input,\n message.runId ?? globalThis.crypto.randomUUID(),\n {\n namespace: message.tenant,\n tags: message.tags,\n searchAttributes: message.searchAttributes,\n },\n );\n });\n // Control plane: re-broadcast lifecycle events from OTHER instances to this instance's\n // subscribers (cross-pod live-tail), and act on cancellations issued elsewhere. A broker may\n // echo our own publish back — ignore those (we already handled them locally) to avoid duplicates.\n this.controlPlane?.onControl((msg) => {\n if (msg.from === this.instanceId) return;\n if (msg.kind === 'event') {\n // `at` may be a string after JSON transit (Redis) — normalize back to a Date.\n this.deliver({ ...msg.event, at: new Date(msg.event.at) });\n } else if (msg.kind === 'cancel') {\n this.notifyCancelled(msg.runId);\n } else if (msg.kind === 'enqueued') {\n // A run was enqueued on another instance — let worker subscribers pick it up immediately\n // instead of waiting for the next poll. (Self-broadcasts are already filtered above.)\n for (const fn of this.enqueuedListeners) {\n try {\n fn(msg.runId);\n } catch {\n /* an enqueue listener must not break the engine */\n }\n }\n }\n });\n this.accumulators = new EventAccumulators(this);\n this.entities = new Entities(this);\n }\n\n /**\n * Register a **durable entity** (a virtual object): a keyed actor whose `handlers` run **serialized\n * per key** over **durable state**, exactly once. Drive it with `signalEntity` (fire) /\n * `ctx.callEntity` (call + await result) and read its state with `getEntityState`. See {@link Entities}.\n */\n registerEntity<S>(name: string, config: EntityConfig<S>): void {\n this.entities.register(name, config);\n }\n\n /** Send an operation to an entity (fire-and-forget). Ordered + exactly-once per key. */\n signalEntity(name: string, key: string, op: string, arg?: unknown): Promise<void> {\n return this.entities.signal(name, key, op, arg);\n }\n\n /** Read an entity's current durable state (published after each op), or undefined if it has none yet. */\n getEntityState<S = unknown>(name: string, key: string): Promise<S | undefined> {\n return this.entities.getState<S>(name, key);\n }\n\n /**\n * Be notified when a run is enqueued on ANOTHER instance (via the control plane), so a worker can\n * pick it up at once — e.g. `engine.onEnqueued((runId) => engine.runOne(runId))`. Returns an\n * unsubscribe function. Only wire this on instances that should execute runs (workers).\n */\n onEnqueued(listener: (runId: string) => void): () => void {\n this.enqueuedListeners.add(listener);\n return () => this.enqueuedListeners.delete(listener);\n }\n\n /** Fire cooperative-cancellation listeners for `runId` (a worker bridge aborts in-flight work). */\n private notifyCancelled(runId: string): void {\n for (const fn of this.cancelListeners) {\n try {\n fn(runId);\n } catch {\n /* a cancel listener must not break the engine */\n }\n }\n }\n\n /**\n * Register a workflow version. Register multiple versions of the same name to keep in-flight\n * runs working across a breaking change: old runs resume on the version they started on, new\n * runs start on the newest registered version.\n *\n * GROUP-SERVED (uniform dispatch, opt-in): pass `{ group, executor }` to have the engine DISPATCH\n * this workflow's turns to a worker `group` (via `executor.advance`) instead of running `fn`\n * inline — exactly as {@link registerRemote} does for a cross-SDK (e.g. Python) body, EXCEPT the\n * body is a TS `fn` the engine retains so an IN-APP worker on `group` can fetch it by name\n * ({@link workflowBody}) and run it. This is \"one app, both roles\": the same process owns the\n * engine AND consumes its own group. Recovery, timers, singleton, cancel and dead-lettering stay\n * engine concerns, identical to a remote run. OMIT `group`/`executor` (the default) to keep the\n * inline fast path — `fn` runs in-process and the run pays zero dispatch round-trips. The first\n * step toward routing every run through a group with no local/remote flag (Phase 3).\n */\n register(\n name: string,\n version: string,\n fn: WorkflowFn,\n opts?: {\n tags?: string[] | undefined;\n singleton?: SingletonConfig | undefined;\n executionTimeout?: string | number | undefined;\n validateInput?: ((input: unknown) => void | Promise<void>) | undefined;\n /** Typed/validated `searchAttributes` shape — see `RegisteredWorkflow.searchAttributesSchema`. */\n searchAttributesSchema?: SearchAttributesSchema | undefined;\n onEvent?: string[] | undefined;\n eventBatch?: EventBatchConfig | undefined;\n /** Worker group to DISPATCH this workflow's turns to (uniform dispatch). Requires `executor`.\n * Omit for the default inline fast path. See the method doc. */\n group?: string | undefined;\n /** Advances a turn by dispatching a {@link WorkflowTask} to `group`. Requires `group`. For an\n * in-app worker, pair a transport-backed {@link RemoteWorkflowExecutor} (group consumed by a\n * worker that calls {@link workflowBody}) so the retained `fn` runs through the transport hop. */\n executor?: WorkflowExecutor | undefined;\n },\n ): void {\n // Group-served is all-or-nothing: a `group` with no `executor` (or vice-versa) is a wiring bug —\n // fail loudly at registration rather than silently falling back to the inline path at dispatch.\n if ((opts?.group == null) !== (opts?.executor == null)) {\n throw new Error(\n `workflow ${name}@${version}: register({ group, executor }) needs BOTH group and executor (or neither)`,\n );\n }\n const registered: RegisteredWorkflow = {\n name,\n version,\n fn,\n tags: opts?.tags,\n singleton: opts?.singleton,\n executionTimeoutMs:\n opts?.executionTimeout != null ? parseDuration(opts.executionTimeout) : undefined,\n validateInput: opts?.validateInput,\n searchAttributesSchema: opts?.searchAttributesSchema,\n onEvent: opts?.onEvent,\n eventBatch: opts?.eventBatch,\n // A real, retained in-process body — so `workflowBody` can hand it to an in-app worker, and so\n // it is NOT confused with the throwing stub `registerRemote` installs for a body-less remote.\n hasBody: true,\n };\n // When group-served, route DISPATCH through the executor (the same `remote` branch a Python\n // workflow takes); `fn` above stays usable for the in-app worker. Omitted = inline fast path.\n if (opts?.group != null && opts?.executor != null) {\n registered.remote = { group: opts.group, executor: opts.executor };\n }\n this.workflows.set(versionKey(name, version), registered);\n const current = this.latest.get(name);\n if (!current || isNewerVersion(version, current.version)) this.latest.set(name, registered);\n for (const event of opts?.onEvent ?? []) {\n const subscribers = this.eventTriggers.get(event) ?? new Set<string>();\n subscribers.add(name);\n this.eventTriggers.set(event, subscribers);\n }\n }\n\n /**\n * The retained in-process body for `name@version`, for an IN-APP worker that consumes this engine's\n * own group to SERVE a group-served `register(..., { group, executor })` workflow (uniform dispatch):\n * the worker fetches the body by name when it picks up the dispatched {@link WorkflowTask}, replays\n * it, and returns the {@link WorkflowDecision}. `undefined` for an unregistered name or a body-less\n * remote (a `registerRemote` / synthesized child carries only a throwing stub, never handed out).\n */\n workflowBody(name: string, version: string): WorkflowFn | undefined {\n const reg = this.workflows.get(versionKey(name, version));\n return reg?.hasBody ? reg.fn : undefined;\n }\n\n /**\n * Register a workflow whose body runs in another SDK (e.g. Python). The engine owns the run exactly\n * as for a TS workflow — it persists checkpoints, recovers, runs timers — but advances it by handing\n * the run's history to `executor` (which dispatches a {@link WorkflowTask} to the worker) and applying\n * the {@link WorkflowDecision} the worker's replay returns. The worker never touches the store.\n */\n registerRemote(\n name: string,\n version: string,\n opts: {\n group: string;\n executor: WorkflowExecutor;\n tags?: string[];\n singleton?: SingletonConfig;\n executionTimeout?: string | number;\n validateInput?: (input: unknown) => void | Promise<void>;\n },\n ): void {\n const registered: RegisteredWorkflow = {\n name,\n version,\n // A remote workflow has no in-process body; execute() branches on `remote` before this is read.\n fn: () => {\n throw new Error(`workflow ${name} is remote — it has no in-process body`);\n },\n tags: opts.tags,\n singleton: opts.singleton,\n executionTimeoutMs:\n opts.executionTimeout != null ? parseDuration(opts.executionTimeout) : undefined,\n validateInput: opts.validateInput,\n remote: { group: opts.group, executor: opts.executor },\n };\n this.workflows.set(versionKey(name, version), registered);\n const current = this.latest.get(name);\n if (!current || isNewerVersion(version, current.version)) this.latest.set(name, registered);\n }\n\n /**\n * The convenience form of {@link registerRemote}: register a workflow whose body runs on a worker\n * `group` (e.g. the Python `durable-worker`, or a separate TS worker), without hand-building a\n * {@link RemoteWorkflowExecutor}. It wires the standard broker executor — a `RemoteWorkflowExecutor`\n * over the engine's own transport, dispatching to `opts.group` — for you, so you write\n * `engine.remote('processing', { group: 'processing' })` instead of\n * `engine.registerRemote('processing', '1', { group: 'processing', executor: new RemoteWorkflowExecutor(transport, 'processing') })`.\n *\n * Defaults the version to `'1'`. All the other {@link registerRemote} options\n * (`tags` / `singleton` / `executionTimeout` / `validateInput`) pass straight through. Reach for the\n * low-level {@link registerRemote} when you need a custom {@link WorkflowExecutor} (a different\n * transport, a fixed `timeoutMs`, a polyglot stub) — `remote()` is the standard wiring on the rails.\n */\n remote(\n name: string,\n opts: {\n /** Worker group this workflow's turns are dispatched to (also the executor's target group). */\n group: string;\n /** Workflow version. Defaults to `'1'`. */\n version?: string;\n tags?: string[];\n singleton?: SingletonConfig;\n executionTimeout?: string | number;\n validateInput?: (input: unknown) => void | Promise<void>;\n },\n ): void {\n const { group, version, ...rest } = opts;\n const executor = new RemoteWorkflowExecutor(this.pool.primary, group);\n this.registerRemote(name, version ?? '1', { group, executor, ...rest });\n }\n\n /**\n * Register a flow-control queue referenced by `ctx.step(step, input, { queue })`. Caps concurrent\n * in-flight steps and/or the admission rate; blocked calls re-suspend and retry, so the limit is\n * durable. Per engine instance (see {@link QueueConfig}). Registering the same name replaces it.\n */\n registerQueue(config: QueueConfig): void {\n this.admission.register(config);\n }\n\n /** Subscribe to lifecycle events. Returns an unsubscribe function. */\n subscribe(listener: EngineListener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /**\n * Register a {@link StepInterceptor} — onion middleware run around the real execution of every\n * local `ctx.step` (timing, logging, tracing, error enrichment, context propagation). First\n * registered is outermost; interceptors fire only when a step executes, never on replay. Returns\n * an unsubscribe function.\n */\n use(interceptor: StepInterceptor): () => void {\n this.interceptors.push(interceptor);\n return () => {\n const i = this.interceptors.indexOf(interceptor);\n if (i >= 0) this.interceptors.splice(i, 1);\n };\n }\n\n /**\n * Fold the registered interceptors around a local step body (identity when there are none), then\n * run the whole thing inside the re-hydrated originating context. The carrier is read at execution\n * time from {@link context} — the SAME reader stamped on dispatched remote tasks — so a local step\n * sees the live tenant / user / trace ids ambiently (via the {@link rehydrate} bridge). Default\n * `rehydrate` is a passthrough, so this is byte-identical to a bare body call when unwired.\n */\n private interceptStep<T>(invocation: StepInvocation, body: () => Promise<T>): Promise<T> {\n const carrier = this.context?.();\n const run = (): Promise<T> => {\n if (this.interceptors.length === 0) return body();\n const chain = this.interceptors.reduceRight<() => Promise<unknown>>(\n (next, interceptor) => () => interceptor(invocation, next),\n body as () => Promise<unknown>,\n );\n return chain() as Promise<T>;\n };\n return this.rehydrate(carrier, run);\n }\n\n /**\n * Be notified when a run is cancelled — on ANY instance, via the transport control plane. A\n * worker bridge can use this for cooperative cancellation: abort the in-flight work for `runId`\n * instead of finishing it just to have the result discarded. Returns an unsubscribe function.\n */\n onCancel(listener: (runId: string) => void): () => void {\n this.cancelListeners.add(listener);\n return () => this.cancelListeners.delete(listener);\n }\n\n /**\n * Be notified when a run is **dead-lettered** — moved to `dead` after exceeding\n * `maxRecoveryAttempts`. The listener receives the dead run (status `dead`, with its error), so a\n * DLQ handler can do something other than just leaving it parked: alert, push to a real queue, or\n * start a dead-letter workflow (e.g. `engine.onDead((run) => engine.start('pipeline-dlq', run, ...))`).\n * Returns an unsubscribe function.\n */\n onDead(listener: (run: WorkflowRun) => void): () => void {\n this.deadListeners.add(listener);\n return () => this.deadListeners.delete(listener);\n }\n\n private notifyDead(run: WorkflowRun): void {\n for (const fn of this.deadListeners) {\n try {\n fn(run);\n } catch {\n /* a dead-letter handler must not break recovery */\n }\n }\n }\n\n /** Emit a locally-produced lifecycle event: deliver to subscribers AND broadcast it on the\n * control plane so other instances (e.g. a dashboard pod) can live-tail this run. */\n private emit(event: Omit<EngineEvent, 'at'>): void {\n const full: EngineEvent = { ...event, at: new Date() };\n this.deliver(full);\n if (this.controlPlane) {\n void this.controlPlane\n .publishControl({ kind: 'event', event: full, from: this.instanceId })\n .catch(() => {\n // control-plane delivery is best-effort observability; never break execution\n });\n }\n }\n\n /** Deliver an event to local subscribers only (no re-broadcast) — used for both locally-produced\n * events and ones received from the control plane, so an event shows up once on every instance. */\n private deliver(event: EngineEvent): void {\n for (const listener of this.listeners) {\n try {\n listener(event);\n } catch {\n // a misbehaving subscriber must never break workflow execution\n }\n }\n }\n\n async start<C extends WorkflowClass>(\n workflow: C,\n input: WorkflowInputOf<C>,\n runId: string,\n opts?: StartOptions,\n ): Promise<RunResult>;\n async start<TInput>(\n workflow: string,\n input: TInput,\n runId: string,\n opts?: StartOptions,\n ): Promise<RunResult>;\n async start(\n workflow: WorkflowRef,\n input: unknown,\n runId: string,\n opts?: StartOptions,\n ): Promise<RunResult> {\n const name = workflowName(workflow);\n let registered = this.latest.get(name);\n if (!registered) {\n // An unregistered run inherits remote routing from its spawning ancestor (see\n // {@link findInheritedRegistration}): the child of a remote workflow can be started without a\n // redundant `registerRemote` for its name. The child run doesn't exist yet, but its parent\n // already wrote the `child:<runId>` waiter BEFORE calling start (the remote `startChild` command\n // and `ctx.child`/`ctx.all` all put the waiter first), so the ancestor is discoverable now.\n const ancestor = await this.findRemoteAncestor(runId);\n if (ancestor) registered = this.synthesizeRemoteChild(name, ancestor.version, ancestor);\n }\n if (!registered) {\n // Convention routing: if the transport reports a live group of the same name, synthesize a\n // remote registration on the fly. Version '1' is the convention default (same as engine.remote()).\n const conventionRun: WorkflowRun = {\n id: runId,\n workflow: name,\n workflowVersion: '1',\n status: 'pending',\n // Stamp the namespace the REAL run will carry (below) so convention routing resolves the same\n // tenant-suffixed group the run will dispatch to — an operator starting a tenant's run via the\n // `onStartRun` wire (opts.namespace = tenant) must find the live `<workflow>@<tenant>` group,\n // not the bare group. Without this the start-run entry path can't reach a suffixed-only worker.\n namespace: opts?.namespace ?? this.namespace,\n input,\n createdAt: new Date(),\n updatedAt: new Date(),\n };\n registered = await this.resolveRemoteByConvention(conventionRun);\n }\n if (!registered) throw new Error(`workflow ${name} is not registered`);\n // Validate the input up front — a bad payload is rejected before any run is created.\n await registered.validateInput?.(input);\n // Idempotent by run id: a redelivered trigger (at-least-once queues) or a scheduler re-tick for\n // the same id is a no-op, returning the existing run's state instead of starting a duplicate.\n const prior = await this.store.getRun(runId);\n if (prior) {\n return { runId, status: prior.status, output: prior.output, error: prior.error };\n }\n const now = new Date();\n // A singleton workflow stamps a `singleton:<key>` tag so the admission gate (in execute) can find\n // the other in-flight runs sharing the key via a tag+status query.\n const tags = mergeTags(\n registered.tags,\n registered.singleton\n ? [...(opts?.tags ?? []), this.singletons.tag(registered.singleton, input)]\n : opts?.tags,\n );\n // Singleton back-pressure: reject a start that would grow the same-key backlog past\n // `limit + maxQueueDepth` (no-op when no maxQueueDepth is configured).\n if (registered.singleton) {\n await this.singletons.assertCapacity(name, registered.singleton, input);\n }\n const run: WorkflowRun = {\n id: runId,\n workflow: name,\n workflowVersion: registered.version,\n status: 'pending',\n namespace: opts?.namespace ?? this.namespace,\n input,\n tags,\n searchAttributes: opts?.searchAttributes,\n priority: opts?.priority,\n createdAt: now,\n updatedAt: now,\n };\n await this.store.createRun(run);\n // The run is durably enqueued; a dispatcher (in-process by default) executes it — `start` does\n // NOT run the body inline. Await the terminal/suspended state with `waitForRun(runId)` if needed.\n await this.runDispatcher.dispatch(runId);\n // Nudge worker instances to pick it up now instead of on their next poll (no-op without a control\n // plane; self-receipt is filtered, so it only helps OTHER pods — e.g. an API pod's enqueue).\n if (this.controlPlane) {\n void this.controlPlane\n .publishControl({ kind: 'enqueued', runId, from: this.instanceId })\n .catch(() => undefined);\n }\n return { runId, status: 'pending' };\n }\n\n /** Read a run's current persisted state (or null if unknown). A thin pass-through to the store. */\n getRun(runId: string): Promise<WorkflowRun | null> {\n return this.store.getRun(runId);\n }\n\n async resume(runId: string): Promise<RunResult> {\n const run = await this.store.getRun(runId);\n if (!run) throw new Error(`run ${runId} not found`);\n // A definitively-finished run must not be re-executed (e.g. a worker result landing after the\n // run was cancelled, or a duplicate resume) — that would replay the body and clobber the\n // terminal state. `failed` is intentionally NOT terminal here: retry resumes a failed run.\n if (run.status === 'cancelled' || run.status === 'completed' || run.status === 'dead') {\n return { runId, status: run.status, output: run.output, error: run.error };\n }\n // Namespace guard: release the lock and bail when this run belongs to a different worker pool.\n // Piggybacked on the existing store.getRun above — no extra async step on the happy path.\n // An undefined namespace (a store adapter that doesn't persist the field yet) is treated as\n // \"belongs to everyone\" for back-compat: don't skip it. Likewise, this ENGINE having an\n // undefined namespace means it's an operator control plane — it belongs to every namespace too,\n // so the guard never applies to it.\n if (\n this.namespace !== undefined &&\n run.namespace !== undefined &&\n run.namespace !== this.namespace\n ) {\n await this.store.releaseRunLock(runId);\n throw new NamespaceMismatch();\n }\n // Pin to the version the run STARTED on — replay is positional, so running a changed\n // workflow body against old checkpoints would corrupt the run. The direct lookup is synchronous\n // (`??` short-circuits): a registered run never awaits here, so its resume timing is unchanged —\n // only an UNREGISTERED run pays the inheritance walk (see {@link findInheritedRegistration}).\n const registered =\n this.workflows.get(versionKey(run.workflow, run.workflowVersion)) ??\n (await this.findInheritedRegistration(run)) ??\n (await this.resolveRemoteByConvention(run));\n if (!registered) {\n throw new Error(\n `workflow ${run.workflow}@${run.workflowVersion} is not registered — keep the prior version deployed so in-flight runs can drain (skew protection)`,\n );\n }\n return this.track(this.execute(run, registered.fn));\n }\n\n /**\n * The registration for an UNREGISTERED run, INHERITED from its nearest REMOTE ancestor — or\n * `undefined` if it has none (the skew-protection error case in {@link resume}). Callers check the\n * flat registry FIRST (so an explicit `registerRemote(name, …)` ALWAYS wins, and a registered run\n * never reaches here); this resolves only the new case: a child spawned by a remote workflow (e.g. a\n * Python `gather_children` / `start_child` fan-out) of a name the host never `registerRemote`-ed. It\n * is driven as a remote run on the ancestor's group + the SAME executor instance, so the host needs\n * no redundant registration per child name.\n *\n * RECOMPUTED per resume rather than memoized into `this.workflows`: a synthesized child is not a real\n * registration and must not leak into `latest`, `knownGroups`, or `sweepTimeouts` (which iterate the\n * registry); recomputing also stays correct if the ancestor's remote registration is re-pointed at a\n * new executor across a deploy. Only unregistered runs pay it, so registered workflows pay nothing.\n */\n private async findInheritedRegistration(\n run: WorkflowRun,\n ): Promise<RegisteredWorkflow | undefined> {\n const ancestor = await this.findRemoteAncestor(run.id);\n if (!ancestor) return undefined;\n return this.synthesizeRemoteChild(run.workflow, run.workflowVersion, ancestor);\n }\n\n /**\n * A throwaway {@link RegisteredWorkflow} that routes `name@version` as a remote run on the ancestor's\n * group via the ancestor's SAME executor instance. The executor is group-scoped (it dispatches a\n * {@link WorkflowTask} carrying `run.workflow`, and the worker picks the body by name), so reusing it\n * is correct AND required — a second executor on the same group would race the worker for results.\n * Only `remote` is inherited; the child gets none of the ancestor's singleton/timeout/validator, so\n * its identity stays its own.\n */\n private synthesizeRemoteChild(\n name: string,\n version: string,\n ancestor: RegisteredWorkflow,\n ): RegisteredWorkflow {\n // `ancestor` always carries `remote` (findRemoteAncestor / start only pass a remote registration);\n // the guard narrows the optional type without an unsafe cast and documents the invariant.\n const remote = ancestor.remote;\n if (!remote) throw new Error(`workflow ${ancestor.name} is not a remote workflow`);\n return {\n name,\n version,\n fn: () => {\n throw new Error(`workflow ${name} is remote — it has no in-process body`);\n },\n remote,\n };\n }\n\n /**\n * Attempt to route an unregistered workflow to the live worker group of the same name: if the\n * transport reports a live heartbeat for group `run.workflow`, synthesize a throwaway\n * {@link RegisteredWorkflow} that dispatches to that group over the primary transport. Returns\n * `undefined` when the group is not live. Always attempted — there is no opt-in flag; an explicit\n * `register`/`registerRemote` still takes precedence (this only runs when nothing is registered).\n *\n * Recomputed per call (never memoized into `this.workflows`) so it stays correct if group\n * liveness changes between calls, exactly as {@link synthesizeRemoteChild} does.\n */\n private async resolveRemoteByConvention(\n run: WorkflowRun,\n ): Promise<RegisteredWorkflow | undefined> {\n // Workers register/heartbeat their liveGroups under the SANITIZED token (`sanitizeQueueToken`),\n // so the membership check must sanitize too — else a `:`-named workflow's live worker is under\n // `orders-fulfill` while this computes `orders:fulfill` and never matches.\n const group = tenantGroup(sanitizeQueueToken(run.workflow), run.namespace);\n // Resolve the TRANSPORT the group is live on, not just membership in the merged list: in a\n // mixed pool (a tenant-scoped control plane pairing its namespaced transport with a bare-prefix\n // one for operator-convention tenant workers), each transport scans a different keyspace —\n // dispatching on `primary` while the worker heartbeats on another transport would park the turn\n // on a queue nobody consumes.\n const liveTransport = await this.pool.transportWithLiveGroup(group);\n if (!liveTransport) return undefined;\n // Feed the workflow NAME + namespace-as-partition through, rather than the pre-combined\n // `group` string above — the executor computes the identical token itself (name+partition is\n // the new routing primitive; `group` here still exists only for the liveGroups membership check).\n const executor = new RemoteWorkflowExecutor(liveTransport, run.workflow, run.namespace);\n return {\n name: run.workflow,\n version: run.workflowVersion,\n fn: () => {\n throw new Error(`remote workflow ${run.workflow} has no local body`);\n },\n hasBody: false,\n remote: { group, executor },\n };\n }\n\n /**\n * Walk the parent chain of `childRunId` to the nearest ancestor registered as REMOTE, returning its\n * registration (or `undefined` if there is none). The parent of an awaited child is found via its\n * live `child:<childId>` signal waiter — present for as long as the parent is suspended awaiting the\n * child, i.e. throughout the child's executable lifetime (start, every resume, crash recovery, cancel\n * cascade), which is exactly when we resolve. A registered-but-LOCAL parent stops the walk (an\n * unregistered child of a TS workflow is a genuine misconfiguration → skew error); only an\n * unregistered parent keeps walking, so a child of an inherited child still reaches the remote root.\n * `visited` guards against a pathological cyclic id graph.\n */\n private async findRemoteAncestor(\n childRunId: string,\n visited = new Set<string>(),\n ): Promise<RegisteredWorkflow | undefined> {\n if (visited.has(childRunId)) return undefined;\n visited.add(childRunId);\n const parentRunId = await this.findParentRunId(childRunId);\n if (!parentRunId) return undefined;\n const parent = await this.store.getRun(parentRunId);\n if (!parent) return undefined;\n const parentReg = this.workflows.get(versionKey(parent.workflow, parent.workflowVersion));\n if (parentReg?.remote) return parentReg;\n if (parentReg) return undefined;\n return this.findRemoteAncestor(parent.id, visited);\n }\n\n /**\n * The run that spawned `childRunId`, via its live `child:<childRunId>` signal waiter — every awaited\n * child (`ctx.child`, `ctx.all`, a remote `start_child`) suspends its parent on exactly this waiter,\n * and the waiter is written BEFORE the child is started. Only reached for an UNREGISTERED child, so\n * registered runs never pay the scan; returns `undefined` once the parent has settled the child (the\n * waiter is consumed), but by then the child is terminal and no longer resolved.\n */\n private async findParentRunId(childRunId: string): Promise<string | undefined> {\n const token = `child:${childRunId}`;\n for (const waiter of await this.store.listSignalWaiters('child:')) {\n if (waiter.token === token) return waiter.runId;\n }\n return undefined;\n }\n\n /** Track an in-flight execution so {@link drain} can wait for it. */\n private track(p: Promise<RunResult>): Promise<RunResult> {\n this.inflight.add(p);\n void p.finally(() => this.inflight.delete(p));\n return p;\n }\n\n /**\n * Graceful shutdown: stop picking up new runs (recovery/timer become no-ops) and wait for\n * in-flight executions to settle, up to `timeoutMs`. Call from your app's shutdown hook so a\n * deploy hands off cleanly instead of leaving runs to the lease timeout.\n */\n async drain(timeoutMs = 10_000): Promise<void> {\n this.draining = true;\n if (this.inflight.size === 0) return;\n const timer = new Promise<void>((resolve) => {\n const t = setTimeout(resolve, timeoutMs);\n (t as { unref?: () => void }).unref?.();\n });\n await Promise.race([Promise.allSettled([...this.inflight]), timer]);\n }\n\n /**\n * Cancel in-flight runs that have outlived their workflow's `executionTimeout`. Call it from the\n * timer poller alongside {@link resumeDueTimers}. A timed-out run is moved to `cancelled` with an\n * `execution_timeout` error (terminal, so a late step result can't resurrect it).\n */\n async sweepTimeouts(now: number = this.clock()): Promise<void> {\n for (const reg of new Set(this.latest.values())) {\n if (reg.executionTimeoutMs == null) continue;\n const deadline = now - reg.executionTimeoutMs;\n const inflight = [\n ...(await this.store.listRuns({\n workflow: reg.name,\n status: 'running',\n namespace: this.namespace,\n })),\n ...(await this.store.listRuns({\n workflow: reg.name,\n status: 'suspended',\n namespace: this.namespace,\n })),\n ];\n for (const run of inflight) {\n if (run.createdAt.getTime() > deadline) continue;\n const error = { message: 'execution timeout', code: 'execution_timeout' };\n await this.store.updateRun(run.id, { status: 'cancelled', error, updatedAt: new Date() });\n this.emit({\n type: 'run.failed',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n error,\n });\n }\n }\n }\n\n /**\n * Resume every run left incomplete by a crash or deploy. Called on boot. Completed steps\n * replay from their checkpoints, so only the work that had not finished runs again.\n */\n async recoverIncomplete(nowMs: number = this.clock()): Promise<RunResult[]> {\n if (this.draining) return [];\n const results: RunResult[] = [];\n for (const run of await this.store.listIncompleteRuns(this.namespace)) {\n // A live worker renews its lease, so an acquirable lease means the run is genuinely orphaned\n // (its worker crashed). Skip the ones still owned.\n const acquired = await this.store.tryLockRun(\n run.id,\n this.instanceId,\n nowMs + this.leaseMs,\n nowMs,\n );\n if (!acquired) continue;\n // Count the attempt / dead-letter a poison pill past maxRecoveryAttempts.\n const settled = await this.countRecovery(run);\n if (settled) {\n results.push(settled);\n continue;\n }\n // Re-enqueue rather than resume inline: recovery must NOT block (boot, or a poll tick) on a\n // long workflow step. A dispatcher/worker re-runs it, replaying its checkpoints.\n await this.store.releaseRunLock(run.id);\n // A `cancelling` run keeps its status (resetting to `pending` would lose the persisted cancel\n // intent and resurrect the run): the re-driven turn re-derives it from the status and finishes\n // the cancel. Every other run re-enqueues as `pending` for a clean (re)start.\n if (run.status !== 'cancelling') {\n await this.store.updateRun(run.id, { status: 'pending', updatedAt: new Date() });\n }\n await this.runDispatcher.dispatch(run.id);\n results.push({\n runId: run.id,\n status: run.status === 'cancelling' ? 'cancelling' : 'pending',\n });\n }\n return results;\n }\n\n /**\n * Per-recovery bookkeeping (called once the lease is held): count the attempt, or — past\n * `maxRecoveryAttempts` — move a poison pill to the `dead` dead-letter state. Returns a terminal\n * result to skip the resume, or `undefined` to proceed.\n */\n private async countRecovery(run: WorkflowRun): Promise<RunResult | undefined> {\n const attempts = (run.recoveryAttempts ?? 0) + 1;\n if (this.maxRecoveryAttempts != null && attempts > this.maxRecoveryAttempts) {\n const error = {\n message: `run exceeded maxRecoveryAttempts (${this.maxRecoveryAttempts}) — moved to dead-letter`,\n code: 'max_recovery_attempts',\n };\n await this.store.updateRun(run.id, { status: 'dead', error, updatedAt: new Date() });\n await this.store.releaseRunLock(run.id);\n this.emit({\n type: 'run.failed',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n error,\n });\n this.notifyDead({ ...run, status: 'dead', error, recoveryAttempts: attempts });\n return { runId: run.id, status: 'dead', error };\n }\n // Count BEFORE resuming, so a crash mid-resume still advances the counter.\n await this.store.updateRun(run.id, { recoveryAttempts: attempts, updatedAt: new Date() });\n return undefined;\n }\n\n /**\n * Resume every suspended run whose durable timer is due. Call periodically (a poller) and on\n * boot. A run still not due re-suspends cheaply without running new work.\n *\n * Piggy-backs the signal/event-waiter reconcile safety net (see {@link reconcileSignalWaiter}): a\n * crash between the waiter/buffer pairing ops on EITHER side (this run's own `putSignalWaiter` →\n * `takeBufferedSignal`/`listBufferedEvents`, or the other side's `takeSignalWaiter`/fan-out →\n * `bufferSignal`/`bufferEvent` → re-check — see `signal`'s interleaving proof, which `publishEvent`\n * mirrors for events) can leave both rows stranded with nothing left to pair them: the waiter's turn\n * already suspended, the other side that buffered it already returned. Event-wait suspends already\n * carry a `reconcileMs` fallback `wakeAt` (see {@link reconcileWakeAt}) precisely so they show up\n * HERE — that's what makes this due-timer pass the natural place for the sweep (and, for events, also\n * where an `eventBufferTtlMs` prune piggy-backs — see {@link reconcileBufferedEvent}). One bulk waiter\n * scan, filtered to just this tick's batch, keeps it cheap regardless of store size.\n */\n async resumeDueTimers(nowMs: number = this.clock()): Promise<RunResult[]> {\n const due = await this.store.listDueTimers(nowMs, this.namespace);\n if (due.length === 0) return [];\n const waiterByRun = indexWaitersByRun(await this.store.listSignalWaiters(''));\n return this.resumeLeased(due, nowMs, (run) =>\n this.reconcileSignalWaiter(run, waiterByRun.get(run.id)),\n );\n }\n\n /**\n * The reconcile safety net's per-run check (see {@link resumeDueTimers}): if this suspended run has\n * a registered signal OR event waiter and a matching payload is already buffered, pair and deliver\n * them directly instead of falling through to a full replay. Child/breakpoint waiter tokens are\n * never buffered (a child/breakpoint notifies via `signal` only once its counterpart is already\n * registered) — `takeBufferedSignal` on those is a guaranteed miss, so this only ever does real work\n * for a plain signal or an event waiter (classified via {@link isEventToken}).\n *\n * Also opportunistically prunes expired buffered EVENTS for this waiter's name when\n * {@link eventBufferTtlMs} is set (see its doc — scoped to names a registered waiter references in\n * this tick's batch, piggy-backing the SAME scan rather than a separate pass), even on a miss.\n *\n * Returns `undefined` (not settled — `resumeLeased` proceeds with its normal `resume`) when there's\n * no waiter or no buffered hit. Deliberately never returns `null`: a delivered signal always resumes\n * via {@link deliverSignal}, and even a `NamespaceMismatch` there is reported as a real (non-nullish)\n * result — returning `null` would read as \"not settled\" to `resumeLeased`'s `??` fallback and\n * trigger a second, redundant `resume` call on the same run.\n */\n private async reconcileSignalWaiter(\n run: WorkflowRun,\n waiter: SignalWaiter | undefined,\n ): Promise<RunResult | undefined> {\n if (!waiter) return undefined;\n if (isEventToken(waiter.token)) return this.reconcileBufferedEvent(run, waiter);\n const buffered = await this.store.takeBufferedSignal(waiter.token);\n if (!buffered) return undefined;\n await this.store.removeSignalWaiter(waiter);\n const settled = await this.deliverSignal(waiter, buffered.payload);\n return settled ?? { runId: run.id, status: run.status };\n }\n\n /**\n * The EVENT half of {@link reconcileSignalWaiter}: scan this waiter's name for a matching buffered\n * event (same list+evaluate+claim shape as `waitForEvent`'s own consumption — the match predicate\n * belongs to the waiter, never the store), pruning any expired candidates it encounters along the\n * way when {@link eventBufferTtlMs} is configured. A pruned-but-non-matching candidate does not stop\n * the scan; only a MATCHING hit (or exhausting the scan window) does.\n */\n private async reconcileBufferedEvent(\n run: WorkflowRun,\n waiter: SignalWaiter,\n ): Promise<RunResult | undefined> {\n const name = eventNameOf(waiter.token);\n const match = eventMatchOf(waiter.token);\n const candidates = await this.store.listBufferedEvents(name, EVENT_BUFFER_SCAN_LIMIT);\n const nowMs = this.clock();\n for (const candidate of candidates) {\n if (this.eventBufferTtlMs != null && nowMs - candidate.publishedAt > this.eventBufferTtlMs) {\n await this.store.removeBufferedEvent(candidate.id); // expired — prune regardless of match\n continue;\n }\n if (!eventMatches(candidate.payload, match)) continue;\n if (!(await this.store.removeBufferedEvent(candidate.id))) continue; // raced away — try the next\n await this.store.removeSignalWaiter(waiter);\n const settled = await this.deliverSignal(waiter, candidate.payload);\n return settled ?? { runId: run.id, status: run.status };\n }\n return undefined;\n }\n\n /**\n * Lease and execute one run by id — the worker side of dispatch. Acquires the recovery lease (so\n * exactly one instance runs it), then resumes the body. Returns the result, or null if another\n * instance holds the lease or the engine is draining. The default in-process dispatcher calls this;\n * a broker-backed worker calls it per consumed run id.\n */\n async runOne(runId: string): Promise<RunResult | null> {\n if (this.draining) return null;\n const nowMs = this.clock();\n const acquired = await this.store.tryLockRun(\n runId,\n this.instanceId,\n nowMs + this.leaseMs,\n nowMs,\n );\n if (!acquired) return null;\n // resume() checks the namespace and throws NamespaceMismatch when it doesn't match — no extra\n // await before the call, so the microtask ordering (critical for cancel-safety) is unchanged.\n return this.resume(runId).catch((err) => {\n if (err instanceof NamespaceMismatch) return null;\n throw err;\n });\n }\n\n /**\n * Re-enqueue a run for a worker to (re-)execute — the dispatch-model **retry**. Sets it back to\n * `pending`, clears any stale lease, and dispatches; a worker resumes it (replaying its checkpoints,\n * re-attempting the failed step). Returns the enqueued state immediately — never runs the body\n * inline — or null if the run is unknown. The dashboard \"retry\" goes through here so it can't block\n * the HTTP request on workflow execution.\n */\n async requeue(runId: string): Promise<RunResult | null> {\n const run = await this.store.getRun(runId);\n if (!run) return null;\n // A FAILED/DEAD run's replay deterministically re-throws its recorded failures — an exhausted\n // failed checkpoint rethrows, and an awaited child's failure completion rethrows through\n // unwrapCompletion — so \"retry\" without resetting that state is a no-op that re-fails in\n // milliseconds. Reset the failure state first so replay RE-EXECUTES the failed parts:\n // - a `failed` checkpoint becomes retryable-now (attempts 0, wake immediately, `retryable`\n // forced back on): the durable-retry machinery re-dispatches it as a fresh first attempt;\n // - an awaited-child `signal:child:` checkpoint holding a FAILURE completion returns to its\n // live `running` placeholder, so replay re-registers the `child:<id>` waiter — a separately\n // retried child's completion (already buffered, or still to come) then resumes this run.\n // Retry child and parent in either order; signal buffering makes it converge.\n if (run.status === 'failed' || run.status === 'dead') {\n const isFailureCompletion = (v: unknown): boolean =>\n typeof v === 'object' && v !== null && (v as { ok?: unknown }).ok === false;\n for (const cp of await this.store.listCheckpoints(runId)) {\n if (cp.status === 'failed') {\n await this.store.saveCheckpoint({\n ...cp,\n attempts: 0,\n wakeAt: this.clock(),\n ...(cp.error ? { error: { ...cp.error, retryable: true } } : {}),\n });\n } else if (\n cp.kind === 'signal' &&\n cp.name.startsWith('signal:child:') &&\n cp.status === 'completed' &&\n isFailureCompletion(cp.output)\n ) {\n await this.store.saveCheckpoint({ ...cp, status: 'running', output: undefined });\n }\n }\n }\n await this.store.releaseRunLock(runId);\n await this.store.updateRun(runId, { status: 'pending', updatedAt: new Date() });\n await this.runDispatcher.dispatch(runId);\n return { runId, status: 'pending' };\n }\n\n /**\n * Explicitly re-dispatch every remote step of `runId` stuck `pending` — the OPERATOR escape hatch for\n * a run whose dispatched step job was LOST (worker crashed with no result, or a transport that dropped\n * the job). No automatic recovery re-drives these: a reconcile re-drive re-suspends a still-pending\n * step by design (unless `remoteRedispatchMs` is set), `recoverIncomplete` only reclaims LEASED runs,\n * and `requeue` just replays back to the pending guard. This re-enqueues the same `stepId` so the\n * (idempotent) step re-runs and its result resumes the run. Safe to call on a healthy run — it re-runs\n * only in-flight `pending` remote steps, which are idempotent by the durable contract. Returns the\n * run's current status (with the count re-dispatched), or null if the run is unknown.\n */\n async redispatchPending(runId: string): Promise<(RunResult & { redispatched: number }) | null> {\n const run = await this.store.getRun(runId);\n if (!run) return null;\n const pending = (await this.store.listCheckpoints(runId)).filter(\n (cp) => cp.kind === 'remote' && cp.status === 'pending',\n );\n let redispatched = 0;\n for (const cp of pending) {\n if (!cp.stepId) continue;\n const reAttempt = cp.attempts + 1;\n const reEnqueuedAt = new Date();\n await this.store.saveCheckpoint({\n ...cp,\n attempts: reAttempt,\n enqueuedAt: reEnqueuedAt,\n startedAt: reEnqueuedAt,\n finishedAt: reEnqueuedAt,\n });\n await this.dispatchRemoteTask({\n runId,\n seq: cp.seq,\n name: cp.name,\n stepId: cp.stepId,\n group: cp.workerGroup ?? sanitizeQueueToken(cp.name),\n input: cp.input,\n attempt: reAttempt,\n });\n redispatched += 1;\n }\n return { runId, status: run.status, redispatched };\n }\n\n /**\n * **Fix-and-replay**: re-run a run (typically a `dead`/`failed` one) with a corrected `input`, as a\n * fresh run with clean history. It's a NEW run — `newRunId` defaults to `<runId>~retry~<uuid>` — so\n * the original stays inspectable. Returns the new run's id, or null if `runId` is unknown.\n */\n async retryWithInput(\n runId: string,\n input: unknown,\n newRunId?: string,\n ): Promise<{ runId: string } | null> {\n const run = await this.store.getRun(runId);\n if (!run) return null;\n const id = newRunId ?? `${runId}~retry~${globalThis.crypto.randomUUID().slice(0, 8)}`;\n // Inherit the original run's namespace so a retry of a tenant's run stays that tenant's — on an\n // operator (this.namespace === undefined) an unstamped retry would fall to 'default' and route to\n // the bare worker group, orphaning it if only the tenant-suffixed worker is live.\n await this.start(run.workflow, input, id, { tags: run.tags, namespace: run.namespace });\n return { runId: id };\n }\n\n /**\n * Pick up and execute every `pending` run — the poll-based side of dispatch for a worker pod with\n * no broker. Runs enqueued by other pods (or by a caller using a no-op dispatcher) sit `pending`\n * in the store until polled; leasing ensures exactly one pod runs each. Call periodically alongside\n * {@link resumeDueTimers}.\n */\n async runPending(nowMs: number = this.clock()): Promise<RunResult[]> {\n // Oldest-first (FIFO), capped per call so a backlog drains over several polls without one sweep\n // fetching unboundedly. A run not picked up this tick is picked up the next.\n return this.resumeLeased(await this.store.listPendingRuns(100, this.namespace), nowMs);\n }\n\n /**\n * Resolve once `runId` reaches a settled state — terminal (completed/failed/cancelled/dead) or\n * suspended (handed off to a timer/signal/event). The async counterpart to dispatch: pair it with\n * `start` when a call site needs the outcome — `await start(...); const r = await waitForRun(id)`.\n */\n waitForRun(\n runId: string,\n opts?: { timeoutMs?: number; until?: 'settled' | 'terminal' },\n ): Promise<RunResult> {\n // `cancelling` is NON-terminal (the saga undo is still running), so a `waitForRun` after a\n // compensating cancel keeps waiting until the run reaches the terminal `cancelled`.\n //\n // A run in the DISPATCH-AND-SUSPEND liveness state — `suspended` while still awaiting a dispatched\n // workflow TURN's decision (`awaitingDecisionTaskId` set) — is mid-turn, NOT settled: that\n // `suspended` is the engine's re-drive marker, not a body-emitted sleep/signal suspend. Resolving on\n // it would hand back a half-applied turn (e.g. a sleep whose `wakeAt` the decision hasn't written\n // yet). Wait until the decision lands and clears the marker (a real suspend) or the run goes terminal.\n //\n // `until: 'terminal'` skips settling on a real suspend too — it resolves only on\n // completed/failed/cancelled/dead (the wait behind `MyWorkflow.execute()` outside a workflow).\n const TERMINAL: ReadonlySet<string> = new Set(['completed', 'failed', 'cancelled', 'dead']);\n const isSettled = (run: WorkflowRun): boolean =>\n opts?.until === 'terminal'\n ? TERMINAL.has(run.status)\n : run.status !== 'pending' &&\n run.status !== 'running' &&\n run.status !== 'cancelling' &&\n !(run.status === 'suspended' && run.awaitingDecisionTaskId !== undefined);\n const toResult = (run: WorkflowRun): RunResult => ({\n runId,\n status: run.status,\n output: run.output,\n error: run.error,\n });\n return new Promise<RunResult>((resolve, reject) => {\n let done = false;\n let off: () => void = () => {};\n const timer =\n opts?.timeoutMs != null\n ? setTimeout(() => {\n if (done) return;\n done = true;\n if (poller) clearInterval(poller);\n off();\n reject(new Error(`waitForRun(${runId}) timed out after ${opts.timeoutMs}ms`));\n }, opts.timeoutMs)\n : undefined;\n const finish = (run: WorkflowRun): void => {\n if (done) return;\n done = true;\n if (timer) clearTimeout(timer);\n if (poller) clearInterval(poller);\n off();\n resolve(toResult(run));\n };\n const check = (): void => {\n void this.store.getRun(runId).then((run) => {\n if (run && isSettled(run)) finish(run);\n });\n };\n // Terminal mode also polls: cancelled/dead transitions have no `run.*` lifecycle event to\n // react to (and a resume may happen on ANOTHER instance), so events alone can miss them.\n const poller =\n opts?.until === 'terminal'\n ? (() => {\n const interval = setInterval(check, 250);\n interval.unref?.();\n return interval;\n })()\n : undefined;\n // React only to this run's settling events (not its every step event), and subscribe BEFORE the\n // initial read so a run that settles in between isn't missed.\n off = this.subscribe((ev) => {\n if (\n ev.runId === runId &&\n (ev.type === 'run.completed' || ev.type === 'run.failed' || ev.type === 'run.suspended')\n ) {\n check();\n }\n });\n check();\n });\n }\n\n /**\n * Resume each run only if this instance can acquire its recovery lease — so when several\n * replicas recover or poll at once, each run is picked up by exactly one of them.\n */\n private async resumeLeased(\n runs: WorkflowRun[],\n nowMs: number = this.clock(),\n onLocked?: (run: WorkflowRun) => Promise<RunResult | undefined>,\n ): Promise<RunResult[]> {\n if (this.draining) return []; // shutting down — don't pick up new runs\n const results: RunResult[] = [];\n for (const run of runs) {\n const acquired = await this.store.tryLockRun(\n run.id,\n this.instanceId,\n nowMs + this.leaseMs,\n nowMs,\n );\n if (!acquired) continue;\n // A per-run hook (recovery counting / dead-lettering) may settle the run terminally instead.\n const settled = onLocked ? await onLocked(run) : undefined;\n results.push(settled ?? (await this.resume(run.id)));\n }\n return results;\n }\n\n /**\n * Deliver an external signal to the run waiting on `token` and resume it with `payload`.\n * Returns the run result, or null if no run is waiting for that token.\n */\n /**\n * Publish a named event. It does two things, and returns how many runs it touched (the sum):\n * 1. **Resumes** every in-flight run waiting on it via `ctx.waitForEvent(name, { match })` whose\n * match the payload satisfies (fan-out, vs `signal`'s point-to-point token).\n * 2. **Starts** a fresh run of every workflow registered with `onEvent: [name]`, passing the\n * payload as input. Idempotent by `evt:<id>:<workflow>` — pass `opts.id` to dedupe redeliveries\n * of the same logical event (default: a fresh uuid, so each publish triggers once).\n *\n * Semantics (deliberate — mirrors `signalWithStart`'s reliability contract, so document it exactly):\n * a publish that resumes ≥1 live waiter, OR routes into an `eventBatch` accumulator / starts ≥1\n * subscriber, behaves exactly as above and is NOT buffered — fan-out stays live-only, same as\n * today. A publish that touches NEITHER — no live waiter matched, no subscriber exists/started —\n * buffers ONE copy (via {@link StateStore.bufferEvent}) unless `opts.buffer === false`, so it isn't\n * silently dropped just because nobody happened to be listening yet. That buffered copy is consumed\n * by the FIRST future `ctx.waitForEvent(name, { match })` whose match accepts its payload —\n * point-to-point on redelivery, by design (only one waiter ever gets it, even though the LIVE path\n * above is fan-out) — never by a second, later-registered onEvent subscriber (subscriber starts stay\n * live-only; `opts.id` dedupe applies to those only, unchanged). Right after buffering, this re-checks\n * `listSignalWaiters` ONCE — sandwich parity with `signal`'s own take → buffer → re-check — so a\n * waiter that registers in the sliver between the initial miss and the buffer write is still paired\n * instead of leaving both rows stranded (see `signal`'s interleaving proof; `waitForEvent`'s own\n * post-registration buffer scan is the mirror-image half of this same race).\n */\n async publishEvent(\n name: string,\n payload: unknown,\n opts?: { id?: string; buffer?: boolean },\n ): Promise<number> {\n let touched = 0;\n const waiters = await this.store.listSignalWaiters(eventPrefix(name));\n for (const w of waiters) {\n if (eventMatches(payload, eventMatchOf(w.token))) {\n await this.signal(w.token, payload);\n touched += 1;\n }\n }\n const subscribers = this.eventTriggers.get(name);\n if (subscribers?.size) {\n const eventId = opts?.id ?? globalThis.crypto.randomUUID();\n for (const workflow of subscribers) {\n // A subscriber that rejects the payload (validateInput) must not block the others or the\n // waiters — its run simply never starts, mirroring fire-and-forget dead-letter routing.\n try {\n const batch = this.latest.get(workflow)?.eventBatch;\n if (batch) {\n // Coalesce: route the event into a per-workflow accumulator (one long-lived run that\n // debounces/batches and then starts the target with the collected payload(s)).\n await this.accumulators.route(workflow, batch, payload);\n } else {\n await this.start(workflow, payload, `evt:${eventId}:${workflow}`);\n }\n touched += 1;\n } catch {\n // skip this subscriber\n }\n }\n }\n // Nobody received it live (no waiter matched, no subscriber exists/started) — buffer ONE copy\n // unless the caller opted out. `touched > 0` covers BOTH the waiter fan-out and the subscriber\n // loop above, matching the \"no one received it\" condition the semantics doc promises.\n if (touched > 0 || opts?.buffer === false) return touched;\n const bufferedId = globalThis.crypto.randomUUID();\n await this.store.bufferEvent({ name, payload, id: bufferedId, publishedAt: this.clock() });\n // Re-check: a waiter may have registered in the window between the miss above and this buffer\n // write (see the interleaving proof at `signal` — this is the events-side mirror of it). Only the\n // FIRST late-registered matching waiter is considered: only one buffered copy exists, so once a\n // claim attempt below either succeeds or finds the buffer already gone, there is nothing left for\n // any other candidate regardless.\n const lateWaiters = await this.store.listSignalWaiters(eventPrefix(name));\n const lateWaiter = lateWaiters.find((w) => eventMatches(payload, eventMatchOf(w.token)));\n if (!lateWaiter) return touched;\n if (!(await this.store.removeBufferedEvent(bufferedId))) return touched; // claimed elsewhere already\n // `takeSignalWaiter` is safe here even though it deletes ANY row for the token: an event token\n // embeds this ONE `waitForEvent` call's own `runId#seq` (see eventToken in events.ts), so no other\n // registration could ever share it.\n const waiter = await this.store.takeSignalWaiter(lateWaiter.token);\n if (waiter) {\n const settled = await this.deliverSignal(waiter, payload);\n if (settled) touched += 1;\n }\n // If `waiter` is null, that exact registration resolved itself some other way in the interim (most\n // likely its own timeout deadline landing in this same sliver) — the buffered copy is already\n // spent (claimed above), so — mirroring `signal`'s own reclaim precedent — drop it rather than\n // resuming a run a second time or re-buffering for a THIRD, unrelated waiter to pick up later.\n return touched;\n }\n\n /**\n * Deliver a signal to an already-known waiter: write its resolving `signal:<token>` checkpoint and\n * resume the run. Shared by {@link signal}'s direct hit, its post-buffer re-check reclaim, and the\n * due-timer reconcile sweep ({@link reconcileSignalWaiter}) — all three resolve a waiter the exact\n * same way.\n */\n private async deliverSignal(waiter: SignalWaiter, payload: unknown): Promise<RunResult | null> {\n await this.store.saveCheckpoint(\n instantCheckpoint({\n runId: waiter.runId,\n seq: waiter.seq,\n name: `signal:${waiter.token}`,\n kind: 'signal',\n output: payload,\n // Carry the awaiting command's fan group (set when a `ctx.gather_children`/`ctx.all` fan-out\n // registered this waiter) onto the resolving `signal:child:<id>` checkpoint, so the dashboard\n // groups the child fan-out vertically instead of rendering it as a sequential chain. Undefined\n // for an ordinary (non-fan) signal/child await.\n parallelGroup: waiter.parallelGroup,\n }),\n );\n return this.resume(waiter.runId).catch((err) => {\n if (err instanceof NamespaceMismatch) return null;\n throw err;\n });\n }\n\n /**\n * Deliver an external signal to the run waiting on `token`, resume it with `payload`, and return\n * the run result — or null if no run is (or ends up) waiting for it.\n *\n * Race with the waiter side (`waitForSignal`'s check → `putSignalWaiter` → re-check, same shape in\n * the remote `waitSignal` command): a waiter can register in the sliver between this method's\n * initial `takeSignalWaiter` miss and its `bufferSignal` write, and the naive old flow (buffer and\n * return) would then leave BOTH a buffered payload and a registered waiter sitting in the store with\n * nothing left to pair them — a lost wake, forever suspended.\n *\n * The interleaving proof: the waiter side does check → put → re-check, this side does take → buffer\n * → re-check. Whichever side's SECOND look runs last is guaranteed to observe the other side's\n * write, because it always follows that write in real time:\n * - If the waiter's `put` lands before this method's first `take`, the take just finds it directly\n * (the pre-existing, non-racy path).\n * - If the waiter's `put` lands after this method's `bufferSignal`, our re-check below either sees\n * it (if `put` also lands before the re-check) or the waiter's OWN post-put re-check sees our\n * buffer (if `put` lands after our re-check but the waiter hasn't re-checked yet either — its\n * re-check strictly follows its own put).\n * - If the waiter's `put` lands between this method's `take` and its re-`take`, the re-check below\n * catches it.\n * Either way, the destructive `take*` ops (on the waiter row, on the buffer) arbitrate: whichever\n * side actually removes the row is the one that delivers, so a signal is never delivered twice.\n */\n async signal(token: string, payload: unknown): Promise<RunResult | null> {\n const waiter = await this.store.takeSignalWaiter(token);\n if (waiter) return this.deliverSignal(waiter, payload);\n // No one was waiting yet — buffer it so the next `waitForSignal(token)` consumes it instead of\n // dropping it (reliable signals; the basis of `signalWithStart`).\n await this.store.bufferSignal(token, payload);\n // Re-check: a waiter may have registered in the window between the miss above and this buffer\n // write (see the interleaving proof above).\n const lateWaiter = await this.store.takeSignalWaiter(token);\n if (!lateWaiter) return null;\n const reclaimed = await this.store.takeBufferedSignal(token);\n if (!reclaimed) {\n // The waiter side won the race to consume the buffer itself (its own checkpoint+resume already\n // delivered the payload) in the sliver between our takeSignalWaiter and takeBufferedSignal just\n // above. We've already (destructively) taken `lateWaiter` off the store, but there is nothing\n // left to deliver — drop it deliberately rather than resuming the run a second time.\n return null;\n }\n return this.deliverSignal(lateWaiter, reclaimed.payload);\n }\n\n /**\n * Ensure a run exists for `runId`, then deliver a signal to it — atomically race-free thanks to\n * signal buffering: if the run is new (or busy / not yet waiting), the signal is buffered and\n * consumed when it reaches `waitForSignal(token)`. The canonical **durable-entity / accumulator**\n * pattern: one long-lived run per key (the `runId`) that loops on `waitForSignal`, fed events by\n * many `signalWithStart` calls. `start` is idempotent by `runId`, so concurrent callers converge on\n * one run. (Use a per-run `token`, e.g. derived from `runId`, so the signal targets this entity.)\n */\n async signalWithStart(\n workflow: WorkflowRef,\n input: unknown,\n runId: string,\n signal: { token: string; payload?: unknown },\n opts?: StartOptions,\n ): Promise<{ runId: string }> {\n // `start` is overloaded per ref kind (class | string); a `WorkflowRef` union fits neither\n // overload, so resolve to the string overload (the engine handles both at runtime).\n await this.start(workflow as string, input, runId, opts); // idempotent: no-op if run exists\n await this.signal(signal.token, signal.payload);\n return { runId };\n }\n\n /**\n * Report the result of a `ctx.task(name, …)` back to its run (async completion). The external\n * worker that the task dispatched to calls this when done; the run resumes with `result`. Returns\n * null if no run is waiting on the task (e.g. a duplicate/late delivery) — a safe no-op.\n */\n async completeTask(runId: string, name: string, result: unknown): Promise<RunResult | null> {\n return this.signal(`task:${runId}:${name}`, {\n ok: true,\n value: result,\n } satisfies Completion<unknown>);\n }\n\n /** Report that a `ctx.task` failed — the run resumes and throws a FatalError at the task. */\n async failTask(runId: string, name: string, error: string): Promise<RunResult | null> {\n return this.signal(`task:${runId}:${name}`, { ok: false, error } satisfies Completion<never>);\n }\n\n /**\n * Notify a parent that's waiting on `runId` as a child of its terminal outcome (the `ctx.child`\n * rendezvous). A no-op when no parent is waiting, so `execute()` can call it on every run without\n * knowing about the child feature.\n */\n private notifyParent(runId: string, completion: Completion<unknown>): void {\n void this.signal(`child:${runId}`, completion).catch(() => undefined);\n }\n\n /**\n * Deferred child start shared by the in-process ctx host and the remote `startChild` command.\n * Deferred (microtask) so a fast child can't reentrantly resume a still-suspending parent. A start\n * that THROWS (unregistered/unroutable workflow, input validation, singleton back-pressure, store\n * failure) must NOT be swallowed: the parent is already suspended on `child:<childId>` (the waiter\n * is put BEFORE start on every path), so a silent drop parks it in suspended-forever, invisibly\n * re-attempting on every recovery wake — a misconfigured remote child looks exactly like a healthy\n * long wait. Instead the failure is delivered to that waiter like a failed child (notifyParent):\n * the parent resumes and fails loudly with the cause. For a fire-and-forget `ctx.startChild`\n * (spawn — no waiter) the completion is buffered; a later join by the same id consumes it and\n * correctly observes the failed start.\n */\n private startChildDeferred(\n workflow: string,\n input: unknown,\n childId: string,\n opts?: StartOptions,\n ): void {\n queueMicrotask(\n () =>\n void this.start(workflow, input, childId, opts).catch((err) => {\n const message = err instanceof Error ? err.message : String(err);\n this.notifyParent(childId, {\n ok: false,\n error: `child workflow \"${workflow}\" failed to start: ${message}`,\n });\n }),\n );\n }\n\n /**\n * Cancel a run (e.g. from the dashboard). Returns null if the run does not exist. Pass\n * `{ compensate: true }` to undo the saga first: the suspended run is resumed so its completed\n * steps' compensations run in reverse (visible as `compensate:<step>` events), then it's marked\n * cancelled. Without it, cancellation is immediate (no undo).\n */\n async cancel(runId: string, opts?: { compensate?: boolean }): Promise<RunResult | null> {\n const run = await this.store.getRun(runId);\n if (!run) return null;\n // Already finished — nothing to cancel (and don't clobber a completed/dead run). This also stops\n // the child cascade below from looping on already-cancelled runs.\n if (run.status === 'completed' || run.status === 'cancelled' || run.status === 'dead') {\n return { runId, status: run.status, output: run.output, error: run.error };\n }\n // Already compensating (status persisted as `cancelling`): idempotent — don't re-queue the resume,\n // and crucially don't fall through to the instant-cancel path below (which would mark `cancelled`\n // and SKIP the in-flight saga undo). A repeat cancel just echoes the in-progress status.\n if (run.status === 'cancelling') {\n return { runId, status: 'cancelling' };\n }\n // Compensating cancel: resume the run with a cancellation pending — replay re-registers the saga,\n // and at the suspension point execute() runs the undo and marks it cancelled. Run that resume in\n // the BACKGROUND so the caller (e.g. an HTTP request) never blocks on replaying the workflow +\n // compensations. `execute` holds the run's lease, so this can't double-run one a live worker owns\n // (its lease acquire fails and it no-ops); the broadcast tells that worker to abort cooperatively.\n if (opts?.compensate && (run.status === 'suspended' || run.status === 'running')) {\n this.cancelRequested.add(runId);\n // Persist `cancelling` so the dashboard/API show \"compensation in progress\" instead of a\n // misleading `running`/`suspended` while the background undo runs. NON-TERMINAL: the admission\n // gate still counts it and recovery re-drives it on crash (runExecution re-derives the cancel\n // intent from this status), so the cancel is durable; it flips to `cancelled` when the resumed\n // replay finishes compensating.\n await this.store.updateRun(runId, { status: 'cancelling', updatedAt: new Date() });\n run.status = 'cancelling';\n if (this.controlPlane) {\n void this.controlPlane\n .publishControl({ kind: 'cancel', runId, from: this.instanceId })\n .catch(() => undefined);\n }\n queueMicrotask(() => {\n void this.resume(runId)\n .then(() => this.notifyCancelled(runId))\n .catch(() => undefined);\n });\n await this.cancelChildren(runId, opts);\n return { runId, status: 'cancelling' };\n }\n const error = { message: 'cancelled' };\n await this.store.updateRun(runId, { status: 'cancelled', error, updatedAt: new Date() });\n this.emit({\n type: 'run.failed',\n runId,\n workflow: run.workflow,\n namespace: run.namespace,\n error,\n });\n await this.cancelChildren(runId, opts);\n // Notify local cancel listeners now (a worker on this pod), and broadcast so the instance/worker\n // actually running this run learns of it and can abort cooperatively (the store already records\n // `cancelled`, but a busy worker won't re-read it).\n this.notifyCancelled(runId);\n if (this.controlPlane) {\n void this.controlPlane\n .publishControl({ kind: 'cancel', runId, from: this.instanceId })\n .catch(() => undefined);\n }\n // A cancelled singleton run frees its slot — wake the next gated waiter now (notify-on-release).\n void this.singletons.wakeNext(run).catch(() => undefined);\n return { runId, status: 'cancelled', error };\n }\n\n /**\n * Bulk-cancel every run matching a filter — e.g. cancel all `order` runs tagged `vip`, or every run\n * whose `tier` search attribute is `free`. The filter is a {@link RunQuery} (workflow / status / tag\n * / search-attribute predicates), so it reuses the same matching the dashboard list uses. Each match\n * is run through {@link cancel}, so the same plumbing applies per run: child cascade, the optional\n * saga `compensate`, local cancel listeners, and the control-plane broadcast that tells the owning\n * worker to abort. Returns one {@link RunResult} per matched run (already-finished matches report\n * their terminal status — `cancel` is a no-op on them, never clobbering a completed/dead run).\n */\n async cancelWhere(\n filter: Omit<RunQuery, 'limit' | 'offset'>,\n opts?: { compensate?: boolean },\n ): Promise<RunResult[]> {\n const runs = await this.store.listRuns(filter);\n const results: RunResult[] = [];\n for (const run of runs) {\n const r = await this.cancel(run.id, opts);\n if (r) results.push(r);\n }\n return results;\n }\n\n /**\n * Hard-delete a run and its entire subtree. Unlike {@link cancel} (which marks a run `cancelled`\n * but keeps it as history), delete REMOVES the run and all its rows (checkpoints, signal waiters,\n * search-attribute rows) — it vanishes from {@link getRun} and {@link listRuns}. Use it to purge a\n * finished run whose data is being deleted (e.g. a pipeline run whose result rows are cleared).\n *\n * Cascades depth-first via {@link getRunChildren} so children are gone before the parent (no\n * orphaned child runs). Prefer {@link cancel} first for a live run — deleting one mid-flight orphans\n * its worker (its next checkpoint write fails). Returns the number of runs deleted (0 if absent).\n */\n async deleteRun(runId: string): Promise<number> {\n const run = await this.store.getRun(runId);\n if (!run) return 0;\n // Collect children BEFORE deleting this run's checkpoints (getRunChildren reads them).\n let deleted = 0;\n for (const childId of await this.getRunChildren(runId)) {\n deleted += await this.deleteRun(childId);\n }\n await this.store.deleteRun(runId);\n return deleted + 1;\n }\n\n /**\n * Cascade cancellation to a run's children — both awaited (`ctx.child`, found via its live\n * `child:<id>` waiter) and fire-and-forget (`ctx.startChild`, found via its `spawn:<id>`\n * checkpoint). Recursive, so a whole subtree is cancelled; the terminal guard in `cancel` stops it\n * at finished / already-cancelled runs (no loops, no re-cancel).\n */\n private async cancelChildren(\n parentRunId: string,\n opts?: { compensate?: boolean },\n ): Promise<void> {\n for (const id of await this.getRunChildren(parentRunId)) {\n await this.cancel(id, opts).catch(() => undefined);\n }\n }\n\n /**\n * The ids of the runs a run spawned — both awaited (`ctx.child`) and fire-and-forget\n * (`ctx.startChild`, found via its `spawn:<id>` checkpoint). The canonical parent→children edge,\n * used for both cancellation cascades and the dashboard run-tree.\n *\n * An awaited child is discovered two ways, because the live `child:<id>` waiter only exists WHILE\n * the parent is suspended on it: the waiter resolves and is consumed the moment the child settles,\n * so a completed parent (or a completed awaited child) would otherwise drop out of the tree. The\n * `signal:child:<id>` checkpoint (the placeholder written when the parent first awaits the child,\n * overwritten as completed/failed when it settles) persists across completion, so we read both and\n * dedupe — the edge stays stable for a finished run, not just a live one.\n */\n async getRunChildren(parentRunId: string): Promise<string[]> {\n const childIds = new Set<string>();\n for (const w of await this.store.listSignalWaiters('child:')) {\n if (w.runId === parentRunId) childIds.add(w.token.slice('child:'.length));\n }\n // Targeted read: only the `signal:child:` / `spawn:` checkpoints, not the whole history. Falls\n // back to a full listCheckpoints + in-JS prefix scan for a custom store that omits the method.\n const prefixes = ['signal:child:', 'spawn:'];\n const childCheckpoints = this.store.listCheckpointsByNamePrefix\n ? await this.store.listCheckpointsByNamePrefix(parentRunId, prefixes)\n : (await this.store.listCheckpoints(parentRunId)).filter((cp) =>\n prefixes.some((p) => cp.name.startsWith(p)),\n );\n for (const cp of childCheckpoints) {\n if (cp.name.startsWith('signal:child:')) childIds.add(cp.name.slice('signal:child:'.length));\n if (cp.name.startsWith('spawn:') && typeof cp.output === 'string') childIds.add(cp.output);\n }\n return [...childIds];\n }\n\n /** The worker groups this engine dispatches to: every registered remote workflow's group, plus any\n * `extra` the caller declares. Local-step groups (a group consumed by in-process `@DurableStep`\n * workers, e.g. `pipeline`) aren't derivable from registrations — pass them via `extra` so a group\n * with backlog and ZERO workers is still reported (the alert case has no heartbeat to discover). */\n knownGroups(extra: string[] = []): string[] {\n const groups = new Set<string>(extra);\n for (const def of this.workflows.values()) {\n if (def.remote?.group) groups.add(def.remote.group);\n }\n return [...groups];\n }\n\n /** Per-group worker health (queue backlog + live worker heartbeats). Covers {@link knownGroups}\n * (so a registered group with backlog and ZERO workers still reports — the alert case) UNION the\n * groups discovered from live heartbeats (so a local-step group like `pipeline`, not derivable\n * from registrations, shows once its workers beat). Empty when no transport can introspect health\n * (only the BullMQ transport implements `groupHealth`). */\n async workerHealth(extra: string[] = []): Promise<GroupHealth[]> {\n const groups = new Set([...this.knownGroups(extra), ...(await this.pool.listWorkerGroups())]);\n // Classify each group workflow-vs-step from the registry (authoritative — no name heuristic): a\n // group whose base token is a registered workflow serves a `@Workflow` body; anything else (an\n // in-process `@Step`, a remote `handle_*` step) is a step. A LOCAL workflow's queue token is\n // `sanitizeQueueToken(name)`; a REMOTE one (e.g. Python) routes to its `remote.group`, which can\n // differ from the name — so seed the workflow-token set with BOTH.\n const workflowTokens = new Set<string>();\n for (const def of this.workflows.values()) {\n workflowTokens.add(sanitizeQueueToken(def.name));\n if (def.remote?.group) workflowTokens.add(def.remote.group);\n }\n const out: GroupHealth[] = [];\n for (const group of groups) {\n const health = await this.pool.groupHealth(group);\n if (!health) continue;\n const at = group.lastIndexOf('@');\n const baseToken = at === -1 ? group : group.slice(0, at);\n out.push({ ...health, kind: workflowTokens.has(baseToken) ? 'workflow' : 'step' });\n }\n return out;\n }\n\n /**\n * Persist a streamed local-step lifecycle event from a remote workflow worker (see\n * {@link WorkflowStepEvent}). A Python `@workflow` runs its `ctx.step`s inline over one turn that\n * can last minutes; the worker streams each step's start/finish so the engine checkpoints it LIVE —\n * a step shows `running` the moment its body begins, then resolves to `completed`/`failed` with its\n * real wall-clock window and sub-process events — instead of every step appearing at once when the\n * turn ends. The turn's final `recordStep` command re-persists the same (runId, seq) checkpoint\n * idempotently, so this is purely additive observability and never changes the run's outcome.\n */\n private async persistStepEvent(event: WorkflowStepEvent): Promise<void> {\n const startedAt = new Date(event.startedAt);\n if (event.phase === 'running') {\n await this.store.saveCheckpoint(\n stepCheckpoint({\n runId: event.runId,\n seq: event.seq,\n name: event.name,\n kind: 'local',\n status: 'running',\n events: event.events,\n attempts: 1,\n enqueuedAt: startedAt,\n startedAt,\n finishedAt: startedAt, // placeholder until the step settles\n parallelGroup: event.parallelGroup,\n }),\n );\n this.emit({\n type: 'step.started',\n runId: event.runId,\n seq: event.seq,\n name: event.name,\n kind: 'local',\n });\n return;\n }\n const failed = event.phase === 'failed';\n await this.store.saveCheckpoint(\n stepCheckpoint({\n runId: event.runId,\n seq: event.seq,\n name: event.name,\n kind: 'local',\n status: failed ? 'failed' : 'completed',\n output: failed ? undefined : event.output,\n error: failed ? event.error : undefined,\n events: event.events,\n attempts: 1,\n enqueuedAt: startedAt,\n startedAt,\n finishedAt: event.finishedAt != null ? new Date(event.finishedAt) : new Date(),\n parallelGroup: event.parallelGroup,\n }),\n );\n this.emit({\n type: failed ? 'step.failed' : 'step.completed',\n runId: event.runId,\n seq: event.seq,\n name: event.name,\n kind: 'local',\n output: failed ? undefined : event.output,\n error: failed ? event.error : undefined,\n });\n }\n\n /**\n * Announce a local step's body has begun and (when `trackStepStart`) checkpoint it as `running`,\n * so it's visible in flight rather than appearing only on completion. The checkpoint is a\n * placeholder overwritten by {@link completeStep}/{@link failStep}; it never short-circuits replay\n * (only `completed` does), so a crash mid-body just re-runs the step. The `step.started` event\n * fires regardless — the live SSE view sees the start even with persistence off.\n */\n private async startStep(step: StepRecord): Promise<void> {\n if (this.trackStepStart) {\n await this.store.saveCheckpoint(\n stepCheckpoint({\n runId: step.runId,\n seq: step.seq,\n name: step.name,\n kind: step.kind,\n status: 'running',\n input: step.input,\n events: step.events,\n attempts: step.attempts,\n workerGroup: step.workerGroup,\n enqueuedAt: step.enqueuedAt,\n startedAt: step.startedAt,\n finishedAt: step.startedAt, // placeholder until the body settles\n }),\n );\n }\n this.emit({\n type: 'step.started',\n runId: step.runId,\n seq: step.seq,\n name: step.name,\n kind: step.kind,\n });\n }\n\n /** Checkpoint a finished step and announce it — the two things that must always happen together. */\n private async completeStep(step: StepRecord & { output: unknown }): Promise<void> {\n await this.store.saveCheckpoint(\n stepCheckpoint({\n runId: step.runId,\n seq: step.seq,\n name: step.name,\n kind: step.kind,\n status: 'completed',\n input: step.input,\n output: step.output,\n events: step.events,\n attempts: step.attempts,\n workerGroup: step.workerGroup,\n enqueuedAt: step.enqueuedAt,\n startedAt: step.startedAt,\n finishedAt: new Date(),\n }),\n );\n this.emit({\n type: 'step.completed',\n runId: step.runId,\n seq: step.seq,\n name: step.name,\n kind: step.kind,\n output: step.output,\n queueMs: step.startedAt.getTime() - step.enqueuedAt.getTime(),\n durationMs: Date.now() - step.startedAt.getTime(),\n });\n }\n\n /** Checkpoint a step that failed terminally, so the failure point is visible (not just the run). */\n private async failStep(step: StepRecord & { error: StepError }): Promise<void> {\n await this.store.saveCheckpoint(\n stepCheckpoint({\n runId: step.runId,\n seq: step.seq,\n name: step.name,\n kind: step.kind,\n status: 'failed',\n input: step.input,\n error: step.error,\n events: step.events,\n attempts: step.attempts,\n workerGroup: step.workerGroup,\n enqueuedAt: step.enqueuedAt,\n startedAt: step.startedAt,\n finishedAt: new Date(),\n }),\n );\n this.emit({\n type: 'step.failed',\n runId: step.runId,\n seq: step.seq,\n name: step.name,\n kind: step.kind,\n error: step.error,\n queueMs: step.startedAt.getTime() - step.enqueuedAt.getTime(),\n durationMs: Date.now() - step.startedAt.getTime(),\n });\n }\n\n private async execute(run: WorkflowRun, fn: WorkflowFn): Promise<RunResult> {\n // Synchronous fast path (`??` short-circuits) for registered runs — no extra await, so execution\n // timing for the common case is unchanged; only an unregistered (inherited-remote) run awaits.\n const registered =\n this.workflows.get(versionKey(run.workflow, run.workflowVersion)) ??\n (await this.findInheritedRegistration(run)) ??\n (await this.resolveRemoteByConvention(run));\n // Hold the lease for the WHOLE execution — whatever path got us here (leased sweep, a signal, a\n // remote result, a dashboard action). The leased sweeps already own it; the event-driven paths\n // don't, so acquire it here. If another instance owns it, don't double-run. While we run, renew\n // the lease periodically so a long run keeps it (a crashed worker's lease still expires and is\n // reclaimed by periodic recovery).\n const lockNow = this.clock();\n if (run.lockedBy !== this.instanceId || (run.lockedUntil ?? 0) <= lockNow) {\n if (\n !(await this.store.tryLockRun(run.id, this.instanceId, lockNow + this.leaseMs, lockNow))\n ) {\n return { runId: run.id, status: run.status };\n }\n }\n const renew = setInterval(\n () => {\n void this.store\n .renewRunLock(run.id, this.instanceId, this.clock() + this.leaseMs)\n .catch(() => undefined);\n },\n Math.max(50, Math.floor(this.leaseMs / 2)),\n );\n renew.unref?.();\n try {\n // A remote (e.g. Python) workflow is advanced by dispatching workflow tasks, not by running an\n // in-process body — but everything around it (lease, recovery, timers, the resume that lands us\n // here on a step result) is identical, so it branches here under the same lease.\n const result = registered?.remote\n ? await this.runRemoteExecution(run, registered)\n : await this.runExecution(run, fn, registered);\n // Notify-on-release: a singleton run that just reached a terminal state freed a slot — wake the\n // next gated waiter(s) now instead of waiting for the ~1s retry timer. Fire-and-forget so it\n // never blocks the settling run; the durable timer is still the cross-instance/crash fallback.\n if (\n registered?.singleton &&\n (result.status === 'completed' ||\n result.status === 'failed' ||\n result.status === 'cancelled' ||\n result.status === 'dead')\n ) {\n void this.singletons.wakeNext(run).catch(() => undefined);\n }\n return result;\n } finally {\n clearInterval(renew);\n }\n }\n\n /**\n * Advance a remote (cross-SDK) workflow one turn: hand its history to the executor (which dispatches\n * a workflow task to the worker and awaits its replay) and apply the decision. Mirrors\n * {@link runExecution}'s settle/suspend; the lease is held by {@link execute}. The result that lands\n * us back here (a remote step finished, a timer fired) goes through `resume` like any TS workflow.\n */\n /**\n * Apply a terminal/suspended transition once: persist the new run status, emit the matching\n * lifecycle event, and (on completion/failure) wake a waiting parent. Both the TS and remote\n * executors funnel their completed/failed/suspended outcomes through here so a status update can\n * never drift from its event or `notifyParent` call. Does NOT touch the run lock — each executor\n * keeps its own lease handling (the TS executor's `finally`, the remote path's caller).\n */\n private async settleRun(run: WorkflowRun, outcome: RunOutcome): Promise<RunResult> {\n const updatedAt = new Date();\n if (outcome.kind === 'completed') {\n // Clear any error from an earlier failed-then-retried attempt — a completed run is a success.\n await this.store.updateRun(run.id, {\n status: 'completed',\n output: outcome.output,\n error: undefined,\n updatedAt,\n });\n this.emit({\n type: 'run.completed',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n output: outcome.output,\n });\n void this.notifyParent(run.id, { ok: true, value: outcome.output });\n return { runId: run.id, status: 'completed', output: outcome.output };\n }\n if (outcome.kind === 'failed') {\n await this.store.updateRun(run.id, { status: 'failed', error: outcome.error, updatedAt });\n this.emit({\n type: 'run.failed',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n error: outcome.error,\n });\n void this.notifyParent(run.id, { ok: false, error: outcome.error.message });\n return { runId: run.id, status: 'failed', error: outcome.error };\n }\n // This outcome was computed by a turn that started from a possibly-stale run snapshot. If the run\n // was cancelled WHILE that turn was still executing (e.g. `ctx.all`'s failFast cancelling a\n // sibling mid-turn — plain `cancel()` writes `cancelled` directly, without waiting for the target's\n // in-flight turn to notice), this now-stale \"suspended\" outcome must not resurrect it: re-check the\n // CURRENT persisted status right before writing and echo it instead of clobbering a real cancel.\n const latest = await this.store.getRun(run.id);\n if (latest?.status === 'cancelled') {\n return { runId: run.id, status: 'cancelled', error: latest.error };\n }\n await this.store.updateRun(run.id, {\n status: 'suspended',\n wakeAt: this.reconcileWakeAt(outcome.wakeAt),\n updatedAt,\n });\n this.emit({\n type: 'run.suspended',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n });\n return { runId: run.id, status: 'suspended' };\n }\n\n /**\n * A wakeAt to persist on a suspend: the natural timer if the turn produced one (a `ctx.sleep`, a\n * remote-step deadline), else the {@link reconcileMs} fallback so an event-waiting run (child/signal/\n * timeout-less remote step) can't be orphaned forever if its wake is lost. `undefined` only when the\n * fallback is disabled (`reconcileMs: 0`). See {@link WorkflowEngineDeps.reconcileMs}.\n */\n private reconcileWakeAt(wakeAt: number | undefined): number | undefined {\n if (wakeAt != null) return wakeAt;\n return this.reconcileMs != null ? this.clock() + this.reconcileMs : undefined;\n }\n\n private async runRemoteExecution(\n run: WorkflowRun,\n registered: RegisteredWorkflow,\n ): Promise<RunResult> {\n // Compensating cancel in flight for a remote workflow: its steps execute in the worker, so there\n // are no TS-side compensations to replay here — finalize to cancelled. Re-broadcast so a live worker\n // mid-turn aborts cooperatively; on recovery (the broadcast was lost to a crash) this still settles\n // the run deterministically instead of resurrecting it by re-advancing.\n if (run.status === 'cancelling') {\n const error = { message: 'cancelled' };\n await this.store.updateRun(run.id, { status: 'cancelled', error, updatedAt: new Date() });\n this.emit({\n type: 'run.failed',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n error,\n });\n this.notifyCancelled(run.id);\n if (this.controlPlane) {\n void this.controlPlane\n .publishControl({ kind: 'cancel', runId: run.id, from: this.instanceId })\n .catch(() => undefined);\n }\n await this.store.releaseRunLock(run.id);\n return { runId: run.id, status: 'cancelled', error };\n }\n const remote = registered.remote as NonNullable<RegisteredWorkflow['remote']>;\n if (run.status === 'pending') {\n await this.store.updateRun(run.id, { status: 'running', updatedAt: new Date() });\n run.status = 'running';\n this.emit({\n type: 'run.started',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n });\n }\n if (registered.singleton && !(await this.singletons.admit(run, registered.singleton))) {\n const wakeAt = this.singletons.retryWakeAt();\n await this.store.updateRun(run.id, { status: 'suspended', wakeAt, updatedAt: new Date() });\n this.emit({\n type: 'run.suspended',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n });\n await this.store.releaseRunLock(run.id);\n return { runId: run.id, status: 'suspended' };\n }\n\n const history = await this.remoteHistory(run.id);\n\n // DISPATCH-AND-SUSPEND (broker-backed executors): SUSPEND-then-ENQUEUE. The engine generates the\n // turn's `taskId`, records it on the run as the awaited marker, and RELEASES the lease — all BEFORE\n // enqueuing the turn — so a fast worker's decision (delivered over `onDecision`, applied durably by\n // `completeRemoteDecision` on WHATEVER instance consumes it) can NEVER arrive ahead of its marker,\n // nor contend with a still-held lease, and be dropped. (The original dispatch-then-mark order lost a\n // sub-millisecond cached-replay decision that round-tripped the in-cluster broker before the marker\n // write to the remote store committed — the multi-instance decision-drop's deeper race.) Liveness is\n // the suspended turn's heartbeat-rearmed window (`remoteAdvanceSilenceMs` → `wakeAt`): if no\n // decision/heartbeat lands before it lapses (including a dispatch that throws below), the timer\n // poller re-drives by re-marking + re-enqueuing a fresh turn.\n if (remote.executor.dispatch) {\n const taskId = `${run.id}:wf:${globalThis.crypto.randomUUID().slice(0, 8)}`;\n const silenceMs = this.remoteAdvanceSilenceMs;\n const wakeAt = silenceMs != null ? this.clock() + silenceMs : undefined;\n // MARK FIRST: record the awaited turn before it is enqueued. No resurrection risk — unlike the old\n // mark-AFTER-dispatch order, nothing rewrites `status` past this point, so a parent-cancel that\n // writes a terminal status during the enqueue below simply wins (its decision is later dropped by\n // `completeRemoteDecision`'s terminal-status check).\n await this.store.updateRun(run.id, {\n status: 'suspended',\n awaitingDecisionTaskId: taskId,\n wakeAt,\n updatedAt: new Date(),\n });\n this.emit({\n type: 'run.suspended',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n });\n // RELEASE BEFORE ENQUEUE: the decision must be able to BOTH match the marker AND acquire the lease\n // the instant it arrives — even a few ms after the enqueue. Holding the lease through the enqueue\n // would drop a fast decision at lock contention. Idempotent vs. `execute`'s own finally release.\n await this.store.releaseRunLock(run.id);\n // THEN enqueue. A failed/lost dispatch leaves the run suspended-awaiting with `wakeAt` set, so the\n // timer poller re-drives it — no lost run.\n await remote.executor.dispatch(run, history, taskId);\n return { runId: run.id, status: 'suspended' };\n }\n\n // INLINE advance (in-process group-served executors): the decision is produced in-process, so await\n // it under the lease. Single-instance by nature; the dispatch path above is the multi-instance one.\n const advanceExecutor = remote.executor.advance;\n if (!advanceExecutor) {\n throw new Error(\n `workflow ${run.workflow}@${run.workflowVersion}: executor implements neither advance nor dispatch`,\n );\n }\n let decision: WorkflowDecision;\n try {\n // When `remoteAdvanceSilenceMs` is configured, wrap the advance in a heartbeat-rearmed deadline\n // keyed by `run.id`: a worker replaying this turn beats (a run-scoped Heartbeat) to keep it alive,\n // and only a genuinely-silent worker trips RemoteWorkflowTimeout → recovery re-drive. Unset = the\n // prior unbounded await. INVARIANT: `advance()` is created and passed to awaitWithLivenessDeadline\n // SYNCHRONOUSLY (no await between), so the `heartbeatResets` entry is registered before the event\n // loop can deliver any beat — an early beat is never lost. If the executor ALSO carries its own\n // `timeoutMs`, the shorter of the two deadlines wins (both raise the same RemoteWorkflowTimeout,\n // handled identically by the catch below).\n const silenceMs = this.remoteAdvanceSilenceMs;\n const advance = advanceExecutor.call(remote.executor, run, history);\n decision =\n silenceMs != null\n ? await this.awaitWithLivenessDeadline(\n run.id,\n advance,\n silenceMs,\n () => new RemoteWorkflowTimeout(run.id, silenceMs),\n )\n : await advance;\n } catch (err) {\n // A RemoteWorkflowTimeout is NOT a failure: the advance only timed out (the decision was likely\n // dropped, while the work may have actually completed). Failing the run here would be wrong — and\n // would notify the parent of a false failure. Instead RELEASE the lease and leave the run in its\n // current `running` state so `recoverIncomplete` re-acquires the now-free lease and re-drives it;\n // the re-driven turn replays completed steps from history and, if the work was done, returns the same\n // `completed` decision → settles → notifies the parent. Opt-in: only reachable when the executor\n // was constructed with a `timeoutMs` (absent = prior unbounded await, unchanged).\n //\n // FIXED-TIMEOUT HAZARD: a bare RemoteWorkflowExecutor `timeoutMs` that fires while a worker is\n // LEGITIMATELY still executing a not-yet-checkpointed step re-drives → DUPLICATE side effects, so\n // that knob is only safe set GENEROUSLY (> the longest legitimate single turn). The robust fix is\n // the heartbeat-rearmed deadline above (`remoteAdvanceSilenceMs`): the worker beats while it works,\n // so only a genuinely-silent (dead) worker trips the timeout — no re-drive of a live turn.\n //\n // Lease lifecycle: `execute` clears its renew interval in its `finally` once this returns, so the\n // lease (released just below) stays free. `releaseRunLock` is idempotent, and `renewRunLock` is a\n // no-op once `lockedBy` is cleared, so a renew tick racing the release cannot re-acquire it.\n if (err instanceof RemoteWorkflowTimeout) {\n await this.store.releaseRunLock(run.id);\n // The suspended path returned early above; run is always `running` here — left for recovery to re-drive.\n return { runId: run.id, status: 'running' as const };\n }\n const error = {\n message: err instanceof Error ? err.message : String(err),\n stack: err instanceof Error ? err.stack : undefined,\n };\n // terminal failure: lease expires naturally — no recovery re-drive will race it\n await this.store.updateRun(run.id, { status: 'failed', error, updatedAt: new Date() });\n this.emit({\n type: 'run.failed',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n error,\n });\n return { runId: run.id, status: 'failed', error };\n }\n\n return this.applyDecision(run, decision);\n }\n\n /**\n * Apply a remote workflow turn's {@link WorkflowDecision}: persist the local steps it ran, then\n * settle (completed/failed/cancelled) or dispatch its blocking ops and suspend (continue). Shared by\n * the INLINE-advance path ({@link runRemoteExecution}, under the held lease) and the durable\n * DISPATCH path ({@link completeRemoteDecision}, which holds the lease itself). Idempotent transitions\n * — the caller has already ensured this is the decision for the currently-awaited turn.\n */\n private async applyDecision(run: WorkflowRun, decision: WorkflowDecision): Promise<RunResult> {\n if (decision.status === 'completed') {\n // Persist the local steps THIS turn ran before marking the run done. A workflow that runs\n // straight to completion in a single turn (every step inline, never suspending — e.g. a Python\n // @workflow whose body is a sequence of ctx.step calls) emits ALL its recordStep commands on\n // this terminal turn; without applying them the run shows `completed` with zero recorded steps.\n // Only this turn's NEW steps are present (prior turns' steps replay as `found`, emitting no\n // command), so there's no duplication.\n await this.applyCommands(run, decision.commands);\n return this.settleRun(run, { kind: 'completed', output: decision.output });\n }\n if (decision.status === 'failed') {\n // Same as completed: persist the steps this turn ran — including the failed one (the worker\n // records a failed-step command before raising) — so the dashboard shows WHERE it failed.\n await this.applyCommands(run, decision.commands);\n return this.settleRun(run, {\n kind: 'failed',\n error: decision.error ?? { message: 'workflow failed' },\n });\n }\n\n if (decision.status === 'cancelled') {\n // The worker bailed at an op boundary because the run was cancelled mid-turn — `cancel` already\n // set status=cancelled, cascaded to children and emitted the lifecycle event. Persist the steps\n // that DID run this turn (partial progress / where it stopped) and reassert `cancelled`\n // (idempotent with `cancel`'s write; preserves the existing error). The point is to NOT resurrect\n // the run to `suspended` or flip it to `failed` — both of which a normal turn result would do.\n await this.applyCommands(run, decision.commands);\n await this.store.updateRun(run.id, { status: 'cancelled', updatedAt: new Date() });\n return { runId: run.id, status: 'cancelled' };\n }\n\n // continue: persist any local steps the replay ran, dispatch the blocking ops, then suspend. When\n // those resolve (a result lands, a timer fires) `resume` brings us back for the next turn.\n //\n // Guard: re-read the run BEFORE writing `suspended` — a parent-cancel cascade may have written\n // `cancelled` to the store WHILE the executor was replaying this turn (the advance() awaited above\n // runs outside the store transaction). Overwriting `cancelled` → `suspended` would let recovery\n // re-drive the run forever. If the store already shows a terminal/cancelled state, bail without\n // touching it — identical to the guard in `completeRemoteResult` for remote step results.\n const fresh = await this.store.getRun(run.id);\n if (\n fresh &&\n (fresh.status === 'cancelled' || fresh.status === 'completed' || fresh.status === 'dead')\n ) {\n return { runId: run.id, status: fresh.status, output: fresh.output, error: fresh.error };\n }\n const wakeAt = await this.applyCommands(run, decision.commands);\n return this.settleRun(run, { kind: 'suspended', wakeAt });\n }\n\n /** The run's resolved durable ops as replay inputs: completed/failed steps + elapsed timers. */\n private async remoteHistory(runId: string): Promise<HistoryEvent[]> {\n const checkpoints = await this.store.listCheckpoints(runId);\n const kindOf: Record<StepKind, HistoryEvent['kind']> = {\n remote: 'call',\n local: 'step',\n sleep: 'timer',\n signal: 'signal',\n };\n const events: HistoryEvent[] = [];\n for (const cp of checkpoints) {\n if (cp.status === 'completed' || cp.status === 'failed') {\n // A child run resolves THROUGH the signal machinery (a `child:<id>` waiter notified on the\n // child's terminal state), so its checkpoint is kind `signal` with a `signal:child:` name and\n // a Completion payload. Surface it as a `child` event with the value/error unwrapped.\n if (cp.kind === 'signal' && cp.name.startsWith('signal:child:')) {\n const completion = cp.output as Completion<unknown> | undefined;\n events.push({\n seq: cp.seq,\n kind: 'child',\n output: completion?.ok ? completion.value : undefined,\n error:\n completion && completion.ok === false ? { message: completion.error } : undefined,\n });\n continue;\n }\n events.push({\n seq: cp.seq,\n kind: kindOf[cp.kind] ?? 'step',\n // A signal checkpoint's name is the internal `signal:<token>`, not the workflow-level signal\n // name the replay used — omit it so the replay matches on seq + kind (its determinism anchor).\n name: cp.kind === 'signal' ? undefined : cp.name,\n output: cp.status === 'completed' ? cp.output : undefined,\n error: cp.status === 'failed' ? cp.error : undefined,\n });\n } else if (cp.kind === 'sleep' && cp.wakeAt != null && cp.wakeAt <= this.clock()) {\n // a still-`pending` sleep whose deadline has passed reads as a resolved timer on replay.\n events.push({ seq: cp.seq, kind: 'timer', name: cp.name });\n }\n }\n return events.sort((a, b) => a.seq - b.seq);\n }\n\n /** Apply a turn's commands: persist recorded local steps, dispatch remote calls, schedule timers.\n * Returns the earliest timer deadline to suspend on (or undefined — suspended on a result). */\n private async applyCommands(\n run: WorkflowRun,\n commands: WorkflowCommand[],\n ): Promise<number | undefined> {\n let wakeAt: number | undefined;\n for (const cmd of commands) {\n const at = new Date();\n const id = stepId(run.id, cmd.seq);\n if (cmd.kind === 'recordStep') {\n // Prefer the step's real wall-clock window + sub-process events (carried by the command, and\n // already streamed live via persistStepEvent) so the checkpoint shows a true duration and its\n // p-process trail — not a 0ms placeholder. Fall back to apply-time for older workers.\n const startedAt = cmd.startedAt != null ? new Date(cmd.startedAt) : at;\n const finishedAt = cmd.finishedAt != null ? new Date(cmd.finishedAt) : at;\n await this.store.saveCheckpoint(\n stepCheckpoint({\n runId: run.id,\n seq: cmd.seq,\n name: cmd.name,\n kind: 'local',\n status: cmd.error ? 'failed' : 'completed',\n output: cmd.output,\n error: cmd.error,\n events: cmd.events,\n attempts: 1,\n enqueuedAt: startedAt,\n startedAt,\n finishedAt,\n // Carry the worker's `parallelGroup` (a Python `ctx.gather` tags every step in the fan with\n // the same group) onto the checkpoint, so the dashboard can render the steps as one parallel\n // group instead of a sequential list. Additive: undefined for ordinary sequential steps.\n parallelGroup: cmd.parallelGroup,\n }),\n );\n this.emit({\n type: cmd.error ? 'step.failed' : 'step.completed',\n runId: run.id,\n seq: cmd.seq,\n name: cmd.name,\n kind: 'local',\n output: cmd.output,\n error: cmd.error,\n });\n } else if (cmd.kind === 'call') {\n // Idempotency (load-bearing for `ctx.gather_calls`): a fan-out re-emits its still-pending\n // `call` commands on every PARTIAL resume (a sibling settled, but not all). Without this guard\n // each re-emit would re-persist + re-dispatch an already-in-flight (or already-completed) step,\n // double-dispatching the worker and resetting attempts. So if a checkpoint for (run.id, seq)\n // already exists — pending OR terminal — skip the save + dispatch entirely; its result lands\n // independently via completeRemoteResult (keyed by seq, so concurrent calls never clobber).\n // Mirrors the `startChild` `getRun(childId)` guard below.\n if (await this.store.getCheckpoint(run.id, cmd.seq)) continue;\n await this.store.saveCheckpoint(\n stepCheckpoint({\n runId: run.id,\n seq: cmd.seq,\n name: cmd.name,\n kind: 'remote',\n status: 'pending',\n input: cmd.input,\n attempts: 1,\n // `cmd.group` is the routing declaration the worker's replay emitted (cross-SDK, or a\n // group-served TS body) — treated as an isolation partition on top of the step's own\n // name, mirroring the StepDef formula below (identical expression everywhere).\n workerGroup: tenantGroup(sanitizeQueueToken(cmd.name), cmd.group),\n enqueuedAt: at,\n startedAt: at,\n finishedAt: at,\n // A `ctx.gather_calls([...])` fan-out stamps every dispatched `call` in the fan with the\n // same group, so the dashboard renders the dispatched steps as one parallel fan (parity\n // with the gathered `recordStep`/`startChild` tags). Undefined for a lone sequential `ctx.step`.\n parallelGroup: cmd.parallelGroup,\n }),\n );\n await this.pool.dispatch(\n {\n runId: run.id,\n seq: cmd.seq,\n name: cmd.name,\n stepId: id,\n group: tenantGroup(sanitizeQueueToken(cmd.name), cmd.group),\n input: cmd.input,\n traceparent: this.traceparent?.(),\n context: this.context?.(),\n attempt: 1,\n },\n undefined,\n );\n this.emit({\n type: 'step.started',\n runId: run.id,\n seq: cmd.seq,\n name: cmd.name,\n kind: 'remote',\n });\n } else if (cmd.kind === 'sleep') {\n const deadline = this.clock() + cmd.ms;\n await this.store.saveCheckpoint(\n stepCheckpoint({\n runId: run.id,\n seq: cmd.seq,\n name: `sleep:${cmd.seq}`,\n kind: 'sleep',\n status: 'pending',\n attempts: 1,\n wakeAt: deadline,\n enqueuedAt: at,\n startedAt: at,\n finishedAt: at,\n }),\n );\n wakeAt = wakeAt == null ? deadline : Math.min(wakeAt, deadline);\n } else if (cmd.kind === 'waitSignal') {\n // Park on a signal: register a waiter at this seq so engine.signal(token) lands the resolving\n // `signal` checkpoint here and resumes the run. The token is the signal name, so an external\n // engine.signal(name, payload) delivers it. If the signal was already delivered (buffered\n // before the workflow reached this point — e.g. signalWithStart), resolve it now and re-drive\n // on a macrotask, AFTER this turn suspends and frees the run lock (a re-entrant resume bails).\n //\n // NOTE: `WorkflowCommand` has no `waitEvent` kind — a polyglot (remote-executor) workflow has\n // no way to issue `ctx.waitForEvent(name, { match })` today; only in-process TS workflows\n // (`workflow-ctx.ts`) can. So buffered EVENTS (`bufferEvent`/`listBufferedEvents`/\n // `removeBufferedEvent`) are reachable only from `engine.publishEvent` and the in-process\n // `waitForEvent`/reconcile paths — never from this remote command loop. Extending the\n // polyglot protocol with an event-wait command is future work, not something to invent here.\n const deliverBuffered = async (payload: unknown): Promise<void> => {\n await this.store.saveCheckpoint(\n instantCheckpoint({\n runId: run.id,\n seq: cmd.seq,\n name: `signal:${cmd.signal}`,\n kind: 'signal',\n output: payload,\n }),\n );\n setTimeout(() => void this.resume(run.id).catch(() => undefined), 0);\n };\n const buffered = await this.store.takeBufferedSignal(cmd.signal);\n if (buffered) {\n await deliverBuffered(buffered.payload);\n } else {\n // Same reorder as the in-process ctx.waitForSignal (see there for why registering\n // UNCONDITIONALLY before even the first check is unsafe — it would expose a \"this turn is\n // about to self-resolve\" waiter row to a concurrent signal for a token a polyglot entity\n // loop reuses, which could steal it and misdeliver): check first, and only on a miss\n // register, then re-check once more before suspending — closing the lost-wake window where\n // a signal races in between the miss above and the registration below (see the interleaving\n // proof at engine.signal).\n await this.store.putSignalWaiter({ token: cmd.signal, runId: run.id, seq: cmd.seq });\n const lateBuffered = await this.store.takeBufferedSignal(cmd.signal);\n if (lateBuffered) {\n // Resolved it ourselves — remove OUR OWN row via the exact match (not\n // takeSignalWaiter(cmd.signal), which deletes ANY row for this token and could steal a\n // different run's waiter that has since claimed the same token).\n await this.store.removeSignalWaiter({ token: cmd.signal, runId: run.id, seq: cmd.seq });\n await deliverBuffered(lateBuffered.payload);\n }\n }\n } else if (cmd.kind === 'startChild') {\n // Start a child run and await it (the worker's ctx.start_child suspends until the child's\n // result is in history). Mirror the in-process `ctx.child`: register a `child:<id>` waiter at\n // this seq — the child notifies it on its terminal state (engine.notifyParent) — then start the\n // child once, deferred so a fast child can't reentrantly resume this still-suspending parent,\n // and id-idempotent so replay/recovery never double-starts it.\n const childId = `${run.id}.child.${cmd.seq}`;\n await this.store.putSignalWaiter({\n token: `child:${childId}`,\n runId: run.id,\n seq: cmd.seq,\n // A `ctx.gather_children`/`ctx.all` fan-out stamps every `startChild` in the fan with the same\n // group. Thread it onto the waiter so the child's terminal `signal:child:<id>` checkpoint\n // (written by engine.signal when the child notifies the parent) carries the group and the\n // dashboard renders the fan as one parallel group. Undefined for a lone (non-fan) child.\n parallelGroup: cmd.parallelGroup,\n });\n if (!(await this.store.getRun(childId))) {\n // Inherit the parent run's namespace (see ctxHostFor.startChild) so a remote workflow's\n // child stays on the parent's tenant/partition regardless of which engine executes it.\n this.startChildDeferred(cmd.workflow, cmd.input, childId, { namespace: run.namespace });\n }\n } else {\n throw new Error(\n `remote workflow command '${(cmd as { kind: string }).kind}' is not supported yet`,\n );\n }\n }\n return wakeAt;\n }\n\n /**\n * Undo the registered saga compensations in reverse and settle the run `cancelled`. Shared by EVERY\n * exit path of a run with a compensating cancel in flight — whether the resumed replay returned,\n * suspended, hit continue-as-new, or threw — so a cancel is never lost just because the body didn't\n * stop at a suspension point.\n *\n * A dispatched compensation still in flight (or backing off a retry) needs the run to keep waiting:\n * unlike the failure path (which is fine going `suspended` — a resumable state no different from an\n * ordinary in-flight `ctx.step`), THIS run must stay `cancelling` — `engine.cancel`'s idempotent\n * re-check, `waitForRun`'s non-terminal treatment, and crash recovery (`recoverIncomplete` only\n * re-drives `running`/`cancelling` runs — a `cancelling` one with a free lease, whatever it's\n * internally waiting on) all key off that status. So on a pending unwind this returns WITHOUT\n * touching `status` (already `cancelling`, untouched since `engine.cancel` set it) — the in-memory\n * cancel flag stays too, re-derived from the status on any later re-drive regardless.\n */\n private async compensateAndCancel(\n run: WorkflowRun,\n compensations: Compensation[],\n replay?: Map<number, StepCheckpoint>,\n ): Promise<RunResult> {\n const pending = await this.unwindCompensations(run, compensations, replay);\n if (pending) return { runId: run.id, status: 'cancelling' };\n this.cancelRequested.delete(run.id);\n const error = { message: 'cancelled' };\n await this.store.updateRun(run.id, { status: 'cancelled', error, updatedAt: new Date() });\n this.emit({\n type: 'run.failed',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n error,\n });\n return { runId: run.id, status: 'cancelled', error };\n }\n\n /** The run body, lease held + renewed by {@link execute}. */\n private async runExecution(\n run: WorkflowRun,\n fn: WorkflowFn,\n registered: RegisteredWorkflow | undefined,\n ): Promise<RunResult> {\n // A run persisted as `cancelling` is a compensating cancel in flight — possibly re-driven by\n // recovery after a crash that lost the in-memory cancel flag. Re-derive the intent from the status\n // so the replay below reaches the WorkflowSuspended + cancelRequested branch and compensates →\n // cancelled (this is what makes a compensating cancel durable across a crash).\n if (run.status === 'cancelling') this.cancelRequested.add(run.id);\n // First execution of an enqueued run: mark it running and announce the start, BEFORE the singleton\n // gate — `singletons.admit` only counts `running`/`suspended` runs, so a still-`pending` run could\n // never be admitted. A resumed run is already past `pending`, so this fires exactly once.\n if (run.status === 'pending') {\n await this.store.updateRun(run.id, { status: 'running', updatedAt: new Date() });\n run.status = 'running';\n this.emit({\n type: 'run.started',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n });\n }\n // Singleton admission gate: if this run shares its key with `limit` older in-flight runs, wait\n // (suspend on a short timer) until a slot frees instead of running now. Re-checked on each resume.\n // A `cancelling` run skips the gate — it is tearing down, not competing for a slot, and suspending\n // it here would clobber the `cancelling` status.\n if (\n run.status !== 'cancelling' &&\n registered?.singleton &&\n !(await this.singletons.admit(run, registered.singleton))\n ) {\n const wakeAt = this.singletons.retryWakeAt();\n await this.store.updateRun(run.id, { status: 'suspended', wakeAt, updatedAt: new Date() });\n this.emit({\n type: 'run.suspended',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n });\n await this.store.releaseRunLock(run.id);\n return { runId: run.id, status: 'suspended' };\n }\n // Saga compensations registered by completed steps; run in reverse if the run later fails.\n const compensations: Compensation[] = [];\n // Load this run's checkpoints ONCE and key them by seq, so replaying the completed prefix reads\n // from memory instead of one `getCheckpoint` SELECT per primitive (the O(N²) replay-reads fix).\n // Read once at execution start: a checkpoint written AFTER this snapshot (the signal/timer/child\n // this resume wakes on, or one written later in this same execution) is absent from the map, and\n // the ctx falls back to the live store for any absent seq — so replay semantics are unchanged.\n const snapshot = await this.store.listCheckpoints(run.id);\n const replay = new Map<number, StepCheckpoint>();\n for (const cp of snapshot) replay.set(cp.seq, cp);\n const ctx = createWorkflowCtx(\n this.ctxHostFor(replay, run.namespace),\n run.id,\n compensations,\n run.workflow,\n registered?.searchAttributesSchema,\n );\n try {\n // The ambient-context wrap is what lets class-first statics (`MyWorkflow.execute()`) find\n // this ctx from anywhere on the body's async path — first run and every replay alike.\n const output = await runInWorkflowCtx(ctx, () => fn(ctx, run.input));\n // A compensating cancel may have been requested while this turn ran (or re-derived from a\n // `cancelling` status on recovery): undo + settle cancelled rather than completing, so the cancel\n // is never lost when the body returns without first hitting a suspension point.\n if (this.cancelRequested.has(run.id)) {\n return this.compensateAndCancel(run, compensations, replay);\n }\n return this.settleRun(run, { kind: 'completed', output });\n } catch (err) {\n if (err instanceof ContinueAsNew) {\n // A cancel in flight wins over continue-as-new: undo + cancel instead of spawning the next run.\n if (this.cancelRequested.has(run.id)) {\n return this.compensateAndCancel(run, compensations, replay);\n }\n // Hand off to a fresh execution with a clean history: complete this run, then start the next\n // (`<id>~N`) with the new input. Deferred + idempotent by the continuation id, so a crash\n // mid-handoff re-derives the same next run instead of forking.\n await this.store.updateRun(run.id, {\n status: 'completed',\n output: undefined,\n error: undefined,\n updatedAt: new Date(),\n });\n this.emit({\n type: 'run.completed',\n runId: run.id,\n workflow: run.workflow,\n namespace: run.namespace,\n });\n void this.notifyParent(run.id, { ok: true, value: undefined });\n const nextId = nextContinuationId(run.id);\n queueMicrotask(\n () => void this.start(run.workflow, err.input, nextId).catch(() => undefined),\n );\n return { runId: run.id, status: 'completed' };\n }\n if (err instanceof WorkflowSuspended) {\n // A compensating cancel resumed this run to reach here: undo + cancel instead of re-suspending.\n if (this.cancelRequested.has(run.id)) {\n return this.compensateAndCancel(run, compensations, replay);\n }\n return this.settleRun(run, { kind: 'suspended', wakeAt: err.wakeAt });\n }\n // A cancel in flight that surfaced as a thrown error still settles cancelled (not failed) — the\n // saga undo runs either way; this just keeps the terminal status faithful to the cancel request.\n if (this.cancelRequested.has(run.id)) {\n return this.compensateAndCancel(run, compensations, replay);\n }\n const error = {\n message: err instanceof Error ? err.message : String(err),\n stack: err instanceof Error ? err.stack : undefined,\n };\n // Saga: undo completed steps in reverse — local ones in-process, dispatched ones as durable\n // remote-step dispatches (see `unwindCompensations`) — each made VISIBLE as a `compensate:<step>`\n // step event/checkpoint so a stranded undo is never silently swallowed; a failing one is still\n // skipped so it can't mask the original failure or strand the rest (compensations should be\n // idempotent). A dispatched undo still in flight (or backing off a retry) SUSPENDS the run\n // exactly like an ordinary `ctx.step` dispatch — the next re-drive (the worker's result landing,\n // or the retry backoff elapsing) resumes `unwindCompensations` right where it left off.\n const pending = await this.unwindCompensations(run, compensations, replay);\n if (pending) return this.settleRun(run, { kind: 'suspended', wakeAt: pending.wakeAt });\n return this.settleRun(run, { kind: 'failed', error });\n } finally {\n // Release the recovery lease once the run reaches a terminal/suspended state, so the\n // next instance (or the timer poller) can pick it up promptly.\n await this.store.releaseRunLock(run.id);\n }\n }\n\n /**\n * Undo every registered saga compensation in strict reverse order — the shared unwind both the\n * run-failure path (`runExecution`'s catch) and the compensating-cancel path\n * (`compensateAndCancel`) drive. Every entry, LOCAL or DISPATCHED, gets a NEGATIVE checkpoint seq\n * `-(k + 1)` for its position `k` (0, 1, 2… walking the stack in reverse) — reserved space that can\n * never collide with a body position (those start at 0), so a saga's undo trail composes onto the\n * run's ordinary checkpoint history with no store-schema change, and shows up in run detail exactly\n * like any other step. Deterministic because `compensations` is rebuilt identically on every replay\n * (see `workflow-ctx.ts`), so the same comp always lands on the same negative seq across a crash +\n * re-drive — the crash-safety this whole scheme rests on.\n *\n * A LOCAL entry runs in-process (`runCompensation`), which checkpoints its own outcome — completed,\n * or failed once `compensationRetries` are exhausted — so a crash mid-unwind SKIPS an\n * already-resolved one on the next pass instead of re-running it (and re-spending its retry budget)\n * from attempt 1. A DISPATCHED entry is an ordinary remote-step dispatch under the hood\n * (`dispatchCompensation`): when it needs the run to WAIT — freshly dispatched, still in flight, or\n * backing off a durable retry — this function returns that wait signal immediately (skipping every\n * comp after it in this pass); the CALLER decides how to represent \"still unwinding\" (see\n * `compensateAndCancel`'s doc comment for why that differs between the two callers). Either way, the\n * run resumes later exactly like any other dispatched step: `completeRemoteResult` completes the\n * negative-seq checkpoint and re-drives, the body replays and deterministically re-throws the same\n * exit it took before (the original failure, or the suspension `compensateAndCancel` resumed from),\n * this function runs again, the now-resolved comp is skipped, and the unwind continues from there.\n *\n * Returns `undefined` once every compensation has resolved — the caller then finalizes the run\n * (`failed` with the ORIGINAL body error, never masked by a comp outcome; or `cancelled`).\n */\n private async unwindCompensations(\n run: WorkflowRun,\n compensations: Compensation[],\n replay?: Map<number, StepCheckpoint>,\n ): Promise<UnwindPending | undefined> {\n for (let i = compensations.length - 1; i >= 0; i -= 1) {\n const comp = compensations[i];\n if (!comp) continue;\n const seq = -(compensations.length - i);\n if ('fn' in comp) {\n const existing = replay?.get(seq) ?? (await this.store.getCheckpoint(run.id, seq));\n if (existing) continue; // already resolved (completed or exhausted-failed) in an earlier pass\n await this.runCompensation(run, comp, seq, replay);\n continue;\n }\n const pending = await this.dispatchCompensation(run, comp, seq, replay);\n if (pending) return pending;\n }\n return undefined;\n }\n\n /**\n * Run one LOCAL saga compensation, retried up to `compensationRetries`, emitting a\n * `compensate:<step>` step event for its outcome so a stranded undo is visible. Never throws — a\n * permanently-failing compensation is skipped so it can't mask the original failure. Checkpoints\n * its outcome at `seq` (a negative unwind position reserved by {@link unwindCompensations}) so a\n * crash mid-unwind skips an already-resolved undo on a later pass instead of re-running it (and\n * re-spending its retry budget) from attempt 1 — the checkpoint is durability/visibility only; the\n * runtime retry-in-process-back-to-back semantics of `comp.fn()` are unchanged.\n */\n private async runCompensation(\n run: WorkflowRun,\n comp: Extract<Compensation, { fn: () => Promise<void> }>,\n seq: number,\n replay?: Map<number, StepCheckpoint>,\n ): Promise<void> {\n const name = `compensate:${comp.name}`;\n const enqueuedAt = new Date();\n for (let attempt = 1; attempt <= this.compensationRetries; attempt += 1) {\n const startedAt = new Date();\n try {\n await comp.fn();\n this.emit({\n type: 'step.completed',\n runId: run.id,\n workflow: run.workflow,\n name,\n kind: 'local',\n durationMs: Date.now() - startedAt.getTime(),\n });\n const cp = stepCheckpoint({\n runId: run.id,\n seq,\n name,\n kind: 'local',\n status: 'completed',\n attempts: attempt,\n enqueuedAt,\n startedAt,\n finishedAt: new Date(),\n });\n await this.store.saveCheckpoint(cp);\n replay?.set(seq, cp);\n return;\n } catch (err) {\n if (attempt >= this.compensationRetries) {\n const error = { message: err instanceof Error ? err.message : String(err) };\n this.emit({\n type: 'step.failed',\n runId: run.id,\n workflow: run.workflow,\n name,\n kind: 'local',\n error,\n durationMs: Date.now() - startedAt.getTime(),\n });\n const cp = stepCheckpoint({\n runId: run.id,\n seq,\n name,\n kind: 'local',\n status: 'failed',\n attempts: attempt,\n error,\n enqueuedAt,\n startedAt,\n finishedAt: new Date(),\n });\n await this.store.saveCheckpoint(cp);\n replay?.set(seq, cp);\n }\n }\n }\n }\n\n /**\n * Resolve (or advance) ONE dispatched saga compensation at its reserved negative `seq` — the undo\n * handler is an ordinary remote `@Step`, so this mirrors `callRemote`'s pending/failed/absent\n * branches (engine.ts's `callRemote`), minus the queue/admission and in-memory-`timeoutMs` paths\n * (V1: dispatch direct by name, always durable). Returns the wait signal when the run must pause for\n * this compensation (freshly dispatched, still in flight, or backing off before a durable retry);\n * `undefined` once it's resolved — completed (crash-safe skip), or retries exhausted/non-retryable\n * (already visible: `completeRemoteResult` emitted `step.failed` for `compensate:<name>` when that\n * checkpoint landed — never re-emitted here, and never allowed to block the rest of the unwind or\n * mask the run's original failure).\n */\n private async dispatchCompensation(\n run: WorkflowRun,\n comp: Extract<Compensation, { dispatch: unknown }>,\n seq: number,\n replay?: Map<number, StepCheckpoint>,\n ): Promise<UnwindPending | undefined> {\n const { def, args } = comp.dispatch;\n const name = `compensate:${comp.name}`;\n const existing = replay?.get(seq) ?? (await this.store.getCheckpoint(run.id, seq));\n if (existing?.status === 'completed') return undefined;\n if (existing?.status === 'pending') return {}; // dispatched, awaiting the worker's result\n if (existing?.status === 'failed') {\n const maxAttempts = Math.max(1, def.retries ?? 1);\n const retryable = existing.error?.retryable !== false;\n if (!retryable || existing.attempts >= maxAttempts) return undefined;\n if (existing.wakeAt == null) {\n const wakeAt = this.clock() + backoffDelay(existing.attempts, def);\n const withWakeAt = { ...existing, wakeAt };\n await this.store.saveCheckpoint(withWakeAt);\n replay?.set(seq, withWakeAt);\n return { wakeAt };\n }\n if (this.clock() < existing.wakeAt) return { wakeAt: existing.wakeAt };\n await this.dispatchCompensationAttempt(\n run,\n seq,\n name,\n def,\n args,\n existing.attempts + 1,\n replay,\n );\n return {};\n }\n // Absent: first dispatch.\n await this.dispatchCompensationAttempt(run, seq, name, def, args, 1, replay);\n return {};\n }\n\n /**\n * Dispatch (or re-dispatch, on a durable retry) one compensation's undo handler — mirrors\n * `callRemote`'s dispatch block (persist the `pending` checkpoint BEFORE handing off to the\n * transport, so a fast result always finds it to complete). Two DIFFERENT names are in play: the\n * checkpoint's `name` is `compensate:<originalStepName>` (what makes this undo show up on the run's\n * timeline, and what `completeRemoteResult` emits `step.completed`/`step.failed` under); the WIRE\n * task's `name` is the undo handler's OWN routing name (`def.name`) — a worker dispatches to the\n * `@Step` it registered, not to this saga-visibility label.\n */\n private async dispatchCompensationAttempt(\n run: WorkflowRun,\n seq: number,\n name: string,\n def: StepDef<StepUndo<unknown, unknown>, unknown>,\n args: StepUndo<unknown, unknown>,\n attempt: number,\n replay?: Map<number, StepCheckpoint>,\n ): Promise<void> {\n if (this.pool.size === 0) throw new Error('remote steps require a Transport');\n const group = tenantGroup(sanitizeQueueToken(def.name), def.partition);\n const enqueuedAt = new Date();\n const cp = stepCheckpoint({\n runId: run.id,\n seq,\n name,\n kind: 'remote',\n status: 'pending',\n input: args,\n attempts: attempt,\n workerGroup: group,\n enqueuedAt,\n startedAt: enqueuedAt,\n finishedAt: enqueuedAt,\n });\n await this.store.saveCheckpoint(cp);\n replay?.set(seq, cp);\n await this.pool.dispatch({\n runId: run.id,\n seq,\n name: def.name,\n stepId: cp.stepId,\n group,\n input: args,\n traceparent: this.traceparent?.(),\n context: this.context?.(),\n attempt,\n });\n this.emit({ type: 'step.started', runId: run.id, seq, name, kind: 'remote' });\n }\n\n /** The seam handed to {@link createWorkflowCtx}: the authoring API reaches durability + lifecycle\n * (checkpointing, dispatch, child start) through this, so the ctx primitives live in their own\n * module and the engine stays the orchestrator. */\n private ctxHostFor(replay?: Map<number, StepCheckpoint>, parentNamespace?: string): CtxHost {\n return {\n store: this.store,\n replay,\n clock: this.clock,\n webhookUrl: this.webhookUrl,\n startStep: (s) => this.startStep(s),\n completeStep: (s) => this.completeStep(s),\n failStep: (s) => this.failStep(s),\n callRemote: (runId, seq, step, input, queue, transport, admission) =>\n this.callRemote(runId, seq, step, input, queue, transport, replay, admission),\n // Defer so a fast child can't reentrantly resume a still-running parent. Stamp the child with\n // the PARENT run's namespace (not this engine's) so a child belongs to the tenant/partition of\n // the run it was spawned from — even when an operator (namespace: undefined, drives every\n // namespace) is the one executing the parent. Otherwise an operator recovery-resuming a\n // `davi-local` pipeline would stamp its `processing` child `default` and it would leak off the\n // tenant's worker pool onto the shared/dev workers.\n startChild: (workflow, input, id, priority) => {\n this.startChildDeferred(workflow, input, id, { priority, namespace: parentNamespace });\n },\n // Deferred for the same reentrancy reason as `startChild` above. `cancel()` is already\n // idempotent on a terminal/cancelled run (returns its existing status without side effects), so\n // no extra guard is needed here for the failFast replay case (re-issuing the same cancel calls).\n cancelChild: (childId) => {\n queueMicrotask(() => void this.cancel(childId).catch(() => undefined));\n },\n // Shallow-merge into the run's searchAttributes (the ctx primitive makes this exactly-once).\n upsertSearchAttributes: async (runId, attrs) => {\n const run = await this.store.getRun(runId);\n await this.store.updateRun(runId, {\n searchAttributes: { ...(run?.searchAttributes ?? {}), ...attrs },\n updatedAt: new Date(),\n });\n },\n signalEntity: (name, key, op, arg, reply) => {\n queueMicrotask(\n () => void this.entities.dispatch(name, key, op, arg, reply).catch(() => undefined),\n );\n },\n interceptStep: (invocation, body) => this.interceptStep(invocation, body),\n };\n }\n\n /**\n * Resume a run paused at a {@link WorkflowCtx.breakpoint} (e.g. the dashboard \"continue\" button).\n * Finds the run's pending breakpoint checkpoint and signals it. Returns null if the run isn't\n * paused at a breakpoint.\n */\n async continue(runId: string): Promise<RunResult | null> {\n const checkpoints = await this.store.listCheckpoints(runId);\n const bp = checkpoints.find(isBreakpoint);\n if (!bp) return null;\n return this.signal(breakpointToken(runId, bp.seq), undefined);\n }\n\n /**\n * Read the latest value a run published for `key` via {@link WorkflowCtx.setEvent} — a\n * side-effect-free query of a live (or finished) run's state. Returns `undefined` if the run\n * never published that key. The suspend-model counterpart of a Temporal query.\n */\n async getEvent<TValue = unknown>(runId: string, key: string): Promise<TValue | undefined> {\n const name = `event:${key}`;\n // Targeted read: the highest-seq checkpoint for this name is the most recent value (a re-published\n // key overwrites at a higher seq), matching the old \"last in seq order wins\" scan. Falls back to a\n // full listCheckpoints scan (last match in seq-ascending order wins) for a store that omits it.\n if (this.store.getLatestCheckpointByName) {\n const latest = await this.store.getLatestCheckpointByName(runId, name);\n return latest?.output as TValue | undefined;\n }\n // listCheckpoints is ordered by seq ascending, so the last match is the most recent value.\n let latest: TValue | undefined;\n for (const cp of await this.store.listCheckpoints(runId))\n if (cp.name === name) latest = cp.output as TValue;\n return latest;\n }\n\n /**\n * Register a validator gating `engine.update(runId, name, …)` for runs of `workflow`. The\n * validator runs BEFORE the update is delivered, so a rejection leaves the run untouched. One\n * validator per (workflow, update name); registering again replaces it.\n */\n registerUpdateValidator<TArg>(\n workflow: string,\n name: string,\n validate: UpdateValidator<TArg>,\n ): void {\n this.updateValidators.set(`${workflow}:${name}`, validate as UpdateValidator);\n }\n\n /**\n * Deliver a validated update to the run waiting at `ctx.onUpdate(name)`. Runs the registered\n * validator (if any) first: on rejection returns `{ accepted: false, reason }` without disturbing\n * the run; otherwise delivers `arg` and resumes, returning `{ accepted: true, run }` (`run` is null\n * if nothing was waiting — a too-early or duplicate update).\n */\n async update(runId: string, name: string, arg: unknown): Promise<UpdateResult> {\n const run = await this.store.getRun(runId);\n if (!run) return { accepted: false, reason: `run ${runId} not found` };\n const validate = this.updateValidators.get(`${run.workflow}:${name}`);\n if (validate) {\n try {\n const reason = await validate(arg);\n if (typeof reason === 'string' && reason.length > 0) return { accepted: false, reason };\n } catch (err) {\n return { accepted: false, reason: err instanceof Error ? err.message : String(err) };\n }\n }\n const result = await this.signal(`update:${runId}:${name}`, arg);\n return { accepted: true, run: result };\n }\n\n private async callRemote<TInput, TOutput>(\n runId: string,\n seq: number,\n step: StepDef<TInput, TOutput>,\n input: TInput,\n queue?: string,\n transport?: string,\n replay?: Map<number, StepCheckpoint>,\n admission?: { priority?: number | undefined; fairnessKey?: string | undefined },\n ): Promise<TOutput> {\n // Read the prefix from the per-execution snapshot (avoids the O(N²) replay SELECTs); a seq absent\n // from the snapshot — not yet dispatched, or written after the snapshot — falls back to the store.\n const existing = replay?.get(seq) ?? (await this.store.getCheckpoint(runId, seq));\n if (existing && existing.name !== step.name) {\n throw new NonDeterminismError(runId, seq, step.name, existing.name);\n }\n if (existing?.status === 'completed') return existing.output as TOutput;\n if (this.pool.size === 0) throw new Error('remote steps require a Transport');\n // A step with a liveness `timeoutMs` keeps the in-memory await + heartbeat path (re-dispatch a\n // presumed-dead worker). Without one, the call SUSPENDS DURABLY: dispatch, persist a `pending`\n // checkpoint, and let the result resume the run on whichever instance receives it — so a worker\n // pod can scale down or crash mid-step without losing the run or re-running completed work.\n if (step.timeoutMs) return this.callRemoteInMemory(runId, seq, step, input, transport);\n if (existing?.status === 'pending') {\n // Dispatched; normally we just keep waiting for the result to resume the run. But a LOST dispatch\n // (worker crashed with no result, or the transport dropped the job) would hang here forever — a\n // reconcile re-drive replays straight back to this guard. Opt-in self-heal: once the step has been\n // pending longer than `remoteRedispatchMs`, re-dispatch the same stepId (the idempotent step\n // re-runs, its result resumes the run), bounded by `remoteRedispatchMax` so a never-settling step\n // fails instead of looping. Unset (default) keeps the by-design \"re-suspend, never re-dispatch\".\n if (this.remoteRedispatchMs == null) throw new WorkflowSuspended();\n // Stamp a redispatch deadline (clock-space, persisted) the first time we see this pending step,\n // stable across replays and crashes — mirrors the failed-retry backoff below. The run's wakeAt\n // becomes this deadline, so a reconcile re-drive lands exactly when it's due to re-dispatch.\n if (existing.wakeAt == null) {\n const wakeAt = this.clock() + this.remoteRedispatchMs;\n await this.store.saveCheckpoint({ ...existing, wakeAt });\n throw new WorkflowSuspended(wakeAt);\n }\n if (this.clock() < existing.wakeAt) throw new WorkflowSuspended(existing.wakeAt);\n // Past the deadline with no result — the dispatch is presumed lost. Re-dispatch (bounded by\n // `remoteRedispatchMax` so a step that never settles fails the run instead of looping forever).\n if (existing.attempts >= this.remoteRedispatchMax) {\n throw new RemoteStepError({\n message: `remote step \"${step.name}\" lost — no result after ${existing.attempts} re-dispatch(es)`,\n code: 'remote_step_lost',\n });\n }\n const reAttempt = existing.attempts + 1;\n const nextDeadline = this.clock() + this.remoteRedispatchMs;\n const reEnqueuedAt = new Date();\n await this.store.saveCheckpoint({\n ...existing,\n attempts: reAttempt,\n wakeAt: nextDeadline,\n enqueuedAt: reEnqueuedAt,\n startedAt: reEnqueuedAt,\n finishedAt: reEnqueuedAt,\n });\n await this.dispatchRemoteTask({\n runId,\n seq,\n name: step.name,\n stepId: existing.stepId ?? stepId(runId, seq),\n group: existing.workerGroup ?? tenantGroup(sanitizeQueueToken(step.name), step.partition),\n input: existing.input,\n priority: admission?.priority,\n attempt: reAttempt,\n transport,\n });\n throw new WorkflowSuspended(nextDeadline);\n }\n\n // Durable retry: a failed attempt re-dispatches up to `retries`, spacing attempts by `backoff` —\n // unless the worker marked the error non-retryable (a deterministic verdict like a declined card).\n // The retry deadline is stamped on the failed checkpoint as `wakeAt` (clock-space, persisted) the\n // first time we see it, so it's stable across replays and survives a crash.\n let attempt = 1;\n if (existing?.status === 'failed') {\n const maxAttempts = Math.max(1, step.retries ?? 1);\n const retryable = existing.error?.retryable !== false;\n if (!retryable || existing.attempts >= maxAttempts) throw new RemoteStepError(existing.error);\n if (existing.wakeAt == null) {\n const wakeAt = this.clock() + backoffDelay(existing.attempts, step);\n await this.store.saveCheckpoint({ ...existing, wakeAt });\n throw new WorkflowSuspended(wakeAt);\n }\n if (this.clock() < existing.wakeAt) throw new WorkflowSuspended(existing.wakeAt);\n attempt = existing.attempts + 1;\n }\n\n const id = stepId(runId, seq);\n // Flow control: a queued call that can't be admitted (concurrency/rate) does NOT dispatch — the\n // run re-suspends with the queue's retry time and the timer poller re-tries admission later, so\n // the limit is durable. The admitted slot is released when the result lands (completeRemoteResult).\n if (queue && this.admission.handles(queue)) {\n // Admission carries the per-call priority + fairness key (default the runId so each run is its\n // own fairness bucket), and the stepId as a STABLE waiter id so the backend tracks one waiter\n // across this call's durable retries. Ordering lives in the backend (in-process by default, or\n // global) — this is the dispatch/admission layer, not the positional replay path.\n const decision = await this.admission.tryAdmit(queue, {\n priority: admission?.priority,\n key: admission?.fairnessKey ?? runId,\n waiterId: id,\n });\n if (!decision.ok) {\n // Remember this run as blocked on `queue` so a freed-slot signal can wake it early.\n const waiters = this.queueWaiters.get(queue) ?? new Set<string>();\n waiters.add(runId);\n this.queueWaiters.set(queue, waiters);\n throw new WorkflowSuspended(decision.retryAt);\n }\n this.queueWaiters.get(queue)?.delete(runId);\n this.stepQueue.set(id, queue);\n }\n\n const enqueuedAt = new Date();\n // Persist the pending checkpoint BEFORE dispatching, so a fast result always finds it to complete.\n await this.store.saveCheckpoint({\n runId,\n seq,\n name: step.name,\n kind: 'remote',\n stepId: id,\n status: 'pending',\n input,\n attempts: attempt,\n workerGroup: tenantGroup(sanitizeQueueToken(step.name), step.partition),\n enqueuedAt,\n startedAt: enqueuedAt, // placeholders until the worker result lands\n finishedAt: enqueuedAt,\n });\n await this.dispatchRemoteTask({\n runId,\n seq,\n name: step.name,\n stepId: id,\n group: tenantGroup(sanitizeQueueToken(step.name), step.partition),\n input,\n priority: admission?.priority,\n attempt,\n transport,\n });\n this.emit({ type: 'step.started', runId, seq, name: step.name, kind: 'remote' });\n throw new WorkflowSuspended();\n }\n\n /** Enqueue a remote step task to its worker group via the transport pool. Shared by the initial\n * dispatch, the opt-in self-heal re-dispatch (see `remoteRedispatchMs`), and the explicit\n * {@link redispatchPending}. Carries the current trace/context so a re-dispatch is traceable. */\n private dispatchRemoteTask(task: {\n runId: string;\n seq: number;\n name: string;\n stepId: string;\n group: string;\n input: unknown;\n attempt: number;\n priority?: number | undefined;\n transport?: string | undefined;\n }): Promise<void> {\n return this.pool.dispatch(\n {\n runId: task.runId,\n seq: task.seq,\n name: task.name,\n stepId: task.stepId,\n group: task.group,\n input: task.input,\n traceparent: this.traceparent?.(),\n context: this.context?.(),\n priority: task.priority,\n attempt: task.attempt,\n },\n task.transport,\n );\n }\n\n /**\n * Complete a durable remote step from its worker result and resume the run — runs on whichever\n * instance receives the result (the dispatching one may be gone), so the run is crash/scale-safe.\n * A no-op if the checkpoint isn't `pending` (a duplicate or late delivery).\n */\n private async completeRemoteResult(result: StepResult): Promise<void> {\n const cp = await this.store.getCheckpoint(result.runId, result.seq);\n if (!cp || cp.status !== 'pending') return;\n // A result settling this step frees its flow-control slot (no-op if it wasn't queued). Done\n // before the cancelled-run early-return below, so a cancellation can't leak the slot. Released\n // fire-and-forget: the slot/notify is best-effort (a global backend self-heals via lease), and\n // not awaiting keeps it off the result-processing critical path (no ordering shift).\n void this.releaseQueueSlot(cp.stepId).catch(() => undefined);\n // Drop a late result for a run that was cancelled/finished meanwhile — don't complete the step\n // or resume (the run is already terminal). This is the engine side of cooperative cancellation.\n const run = await this.store.getRun(result.runId);\n if (run && (run.status === 'cancelled' || run.status === 'completed')) return;\n const finishedAt = new Date();\n const startedAt = result.startedAt ? new Date(result.startedAt) : cp.startedAt;\n await this.store.saveCheckpoint({\n ...cp,\n status: result.status,\n output: result.status === 'completed' ? result.output : cp.output,\n error: result.error,\n events: result.events ?? cp.events,\n startedAt,\n finishedAt,\n });\n this.emit({\n type: result.status === 'completed' ? 'step.completed' : 'step.failed',\n runId: result.runId,\n seq: result.seq,\n name: cp.name,\n kind: cp.kind,\n output: result.output,\n error: result.error,\n queueMs: startedAt.getTime() - cp.enqueuedAt.getTime(),\n durationMs: finishedAt.getTime() - startedAt.getTime(),\n });\n await this.resume(result.runId).catch((err) => {\n if (err instanceof NamespaceMismatch) return null;\n throw err;\n });\n }\n\n /**\n * Apply a remote workflow-turn {@link WorkflowDecision} durably — runs on WHATEVER instance receives\n * it over the broker (the dispatching one may be gone, or a point-to-point broker handed it to a\n * non-dispatcher). The durable, multi-instance-safe twin of {@link completeRemoteResult} for the\n * workflow TURN: look the run up by `decision.runId`, verify the decision matches the run's\n * CURRENTLY-awaited turn (`awaitingDecisionTaskId`) — so a stale / duplicate / foreign / re-driven\n * decision is dropped (applied AT MOST ONCE) — lease it, clear the marker, and apply the decision.\n */\n private async completeRemoteDecision(decision: WorkflowDecision): Promise<void> {\n // Cheap pre-checks before contending for the lease: only the run currently awaiting THIS taskId\n // (and not already terminal) is a candidate. A re-driven turn has a different taskId, so a late\n // decision for the prior turn is dropped here.\n const run = await this.store.getRun(decision.runId);\n if (!run || run.awaitingDecisionTaskId !== decision.taskId) return;\n if (run.status === 'cancelled' || run.status === 'completed' || run.status === 'dead') return;\n if (\n this.namespace !== undefined &&\n run.namespace !== undefined &&\n run.namespace !== this.namespace\n ) {\n return;\n }\n const nowMs = this.clock();\n // Lease so exactly one instance applies it — serialized with a concurrent timer re-drive of the\n // same run. If the lease is held (a re-drive in flight), drop: the re-driven turn produces a fresh\n // decision. The common single-decision path is uncontended, so this acquires immediately.\n if (\n !(await this.store.tryLockRun(decision.runId, this.instanceId, nowMs + this.leaseMs, nowMs))\n ) {\n return;\n }\n const renew = setInterval(\n () => {\n void this.store\n .renewRunLock(decision.runId, this.instanceId, this.clock() + this.leaseMs)\n .catch(() => undefined);\n },\n Math.max(50, Math.floor(this.leaseMs / 2)),\n );\n renew.unref?.();\n try {\n // Re-read under the lease and re-check the marker — it may have changed (a re-drive applied\n // first, or another decision raced in) between the unlocked pre-check and acquiring the lease.\n const fresh = await this.store.getRun(decision.runId);\n if (!fresh || fresh.awaitingDecisionTaskId !== decision.taskId) return;\n if (fresh.status === 'cancelled' || fresh.status === 'completed' || fresh.status === 'dead') {\n return;\n }\n // Clear the awaited-turn marker and the re-drive deadline: this turn is now being applied exactly\n // once. `applyDecision` resets `wakeAt` itself when it suspends on the turn's blocking ops.\n await this.store.updateRun(decision.runId, {\n awaitingDecisionTaskId: undefined,\n wakeAt: undefined,\n updatedAt: new Date(),\n });\n fresh.awaitingDecisionTaskId = undefined;\n await this.applyDecision(fresh, decision);\n } finally {\n clearInterval(renew);\n await this.store.releaseRunLock(decision.runId);\n }\n }\n\n /**\n * A run-scoped heartbeat for a run suspended awaiting a workflow-turn decision (the dispatch path):\n * push its durable re-drive deadline (`wakeAt`) forward so a still-working worker's turn is not\n * re-dispatched. The durable counterpart of an inline turn's in-memory `heartbeatResets` rearm.\n */\n private async rearmDecisionDeadline(runId: string): Promise<void> {\n const silenceMs = this.remoteAdvanceSilenceMs;\n if (silenceMs == null) return;\n const run = await this.store.getRun(runId);\n if (!run || run.status !== 'suspended' || run.awaitingDecisionTaskId === undefined) return;\n await this.store.updateRun(runId, { wakeAt: this.clock() + silenceMs, updatedAt: new Date() });\n }\n\n /**\n * A slot freed on `queue` (a fleet-wide signal): resume this instance's runs blocked on it so they\n * re-contend now instead of at their retry tick. Snapshot-and-clear — a run still blocked after the\n * retry re-registers itself, and one that's gone (cancelled/admitted) is dropped. Best-effort.\n */\n private wakeQueueWaiters(queue: string): void {\n const waiters = this.queueWaiters.get(queue);\n if (!waiters || waiters.size === 0) return;\n const runIds = [...waiters];\n waiters.clear();\n for (const runId of runIds) void this.resume(runId).catch(() => undefined);\n }\n\n /** Release the flow-control slot a dispatched step held (if any), by its stepId. */\n private async releaseQueueSlot(id: string): Promise<void> {\n const queue = this.stepQueue.get(id);\n if (queue === undefined) return;\n this.stepQueue.delete(id);\n await this.admission.release(queue, id);\n }\n\n /** In-memory await path for a remote step with a liveness `timeoutMs` (re-dispatch on timeout). */\n private async callRemoteInMemory<TInput, TOutput>(\n runId: string,\n seq: number,\n step: StepDef<TInput, TOutput>,\n input: TInput,\n transport?: string,\n ): Promise<TOutput> {\n if (this.pool.size === 0) throw new Error('remote steps require a Transport');\n // A bare `@Step()` (no `input`/`output` schemas attached) skips validation.\n const validInput = step.input ? step.input.parse(input) : input;\n const id = stepId(runId, seq);\n const enqueuedAt = new Date();\n this.emit({ type: 'step.started', runId, seq, name: step.name, kind: 'remote' });\n // Retry policy differs from an in-process step on purpose: the internal in-process primitives\n // (`ctx.task`'s dispatch, `ctx.now`/`ctx.sideEffect`) retry any non-fatal throw (the work is in-process),\n // but a dispatched `ctx.step` only re-dispatches on a liveness TIMEOUT (presumed-dead worker). A\n // worker that *reported* an error returned a deterministic verdict, so we surface it to the\n // workflow instead of hammering the worker. Timeout retries need a window to detect death, so\n // they're gated on `timeoutMs` being set.\n const maxAttempts = step.timeoutMs ? Math.max(1, step.retries ?? 1) : 1;\n\n for (let attempt = 1; ; attempt += 1) {\n const resultPromise = new Promise<RemoteResolution>((resolve, reject) => {\n this.pending.set(id, { resolve, reject });\n });\n await this.pool.dispatch(\n {\n runId,\n seq,\n name: step.name,\n stepId: id,\n group: tenantGroup(sanitizeQueueToken(step.name), step.partition),\n input: validInput,\n traceparent: this.traceparent?.(),\n context: this.context?.(),\n attempt,\n },\n transport,\n );\n try {\n const resolution = step.timeoutMs\n ? await this.awaitWithHeartbeat(id, resultPromise, step.timeoutMs)\n : await resultPromise;\n const output = step.output\n ? (step.output.parse(resolution.output) as TOutput)\n : (resolution.output as TOutput);\n // The worker reports when it actually picked the task up; fall back to dispatch time if a\n // transport doesn't carry it (queue-wait then reads as zero rather than going negative).\n const startedAt = resolution.startedAt ? new Date(resolution.startedAt) : enqueuedAt;\n await this.completeStep({\n runId,\n seq,\n name: step.name,\n kind: 'remote',\n input: validInput,\n output,\n events: resolution.events,\n attempts: attempt,\n workerGroup: tenantGroup(sanitizeQueueToken(step.name), step.partition),\n enqueuedAt,\n startedAt,\n });\n return output;\n } catch (err) {\n this.pending.delete(id);\n if (err instanceof RemoteStepTimeout && attempt < maxAttempts) continue;\n throw err;\n }\n }\n }\n\n /**\n * Await `resultPromise`, but reject with `onTimeout()` if neither it settles nor a heartbeat for `id`\n * arrives within `timeoutMs`. Each heartbeat (delivered via `transport.onHeartbeat`, looked up in\n * `heartbeatResets` by `id`) REARMS the window, so a worker that keeps beating stays alive past\n * `timeoutMs`. Shared by the remote-STEP liveness (keyed by stepId) and the remote-WORKFLOW advance\n * liveness (keyed by runId); the caller supplies the timeout error and any extra cleanup via `onTimeout`.\n */\n private awaitWithLivenessDeadline<T>(\n id: string,\n resultPromise: Promise<T>,\n timeoutMs: number,\n onTimeout: () => Error,\n ): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout>;\n const cleanup = () => {\n clearTimeout(timer);\n this.heartbeatResets.delete(id);\n };\n const arm = () => {\n timer = setTimeout(() => {\n cleanup();\n reject(onTimeout());\n }, timeoutMs);\n (timer as { unref?: () => void }).unref?.();\n };\n this.heartbeatResets.set(id, () => {\n clearTimeout(timer);\n arm();\n });\n arm();\n resultPromise.then(\n (value) => {\n cleanup();\n resolve(value);\n },\n (err) => {\n cleanup();\n reject(err);\n },\n );\n });\n }\n\n /** Remote-STEP liveness: await a worker result, timing out (with the step's pending-map cleanup) to\n * `RemoteStepTimeout` if it neither lands nor beats within `timeoutMs`. See {@link awaitWithLivenessDeadline}. */\n private awaitWithHeartbeat(\n id: string,\n resultPromise: Promise<RemoteResolution>,\n timeoutMs: number,\n ): Promise<RemoteResolution> {\n return this.awaitWithLivenessDeadline(id, resultPromise, timeoutMs, () => {\n this.pending.delete(id);\n return new RemoteStepTimeout(id, timeoutMs);\n });\n }\n}\n\n/** Raised inside the workflow when a remote worker reports a step failure. */\nexport class RemoteStepError extends Error {\n readonly stepError?: StepError | undefined;\n constructor(stepError?: StepError) {\n super(stepError?.message ?? 'remote step failed');\n this.name = 'RemoteStepError';\n this.stepError = stepError;\n }\n}\n","import type { z } from 'zod';\nimport type { StandardSchemaV1 } from './standard-schema';\nimport type { StepRef } from './step-name-symbol';\nimport type { WorkflowClass, WorkflowInputOf, WorkflowOutputOf } from './workflow-ref';\n\n/**\n * Core type contracts for nestjs-durable.\n *\n * These are intentionally framework-agnostic: `@dudousxd/nestjs-durable-core` knows only\n * these interfaces, never a concrete transport, store or ORM. Adapters implement them.\n */\n\n// ---------------------------------------------------------------------------\n// Runs & checkpoints — the durable state owned by the orchestrator\n// ---------------------------------------------------------------------------\n\nexport type RunStatus =\n /** Created + enqueued by `start`, not yet picked up — a worker will lease and execute it. */\n | 'pending'\n | 'running'\n | 'suspended'\n /**\n * Compensating cancel in progress: `cancel(runId, { compensate: true })` has been requested and the\n * saga undo is running in the background. NON-TERMINAL — the run is still in-flight (counted by the\n * admission gate, re-driven by recovery if the engine crashes mid-compensation), and flips to\n * `cancelled` once compensation completes. A non-compensating cancel skips this and goes straight to\n * `cancelled`.\n */\n | 'cancelling'\n | 'completed'\n | 'failed'\n | 'cancelled'\n /** Dead-letter: recovery gave up after `maxRecoveryAttempts` (a poison pill). Terminal; inspect it. */\n | 'dead';\n\n/** One execution of a workflow. The unit of durability and the unit shown in the dashboard. */\nexport interface WorkflowRun {\n id: string;\n /** Registered workflow name, e.g. `checkout`. */\n workflow: string;\n /** Code version at start; old runs must resume on the version they began on. */\n workflowVersion: string;\n status: RunStatus;\n /** Serialized workflow input (the args the run was started with). */\n input: unknown;\n /** Serialized workflow output, once `completed`. */\n output?: unknown;\n /** Structured error, once `failed`. */\n error?: StepError | undefined;\n /** When `suspended` on a durable sleep: epoch ms at which the run becomes due to resume. */\n wakeAt?: number | undefined;\n /** Recovery lease owner (engine instance id) while a run is being resumed. */\n lockedBy?: string | undefined;\n /** Recovery lease expiry (epoch ms); another instance may take over once it passes. */\n lockedUntil?: number | undefined;\n /** How many times crash-recovery has picked this run up — caps poison pills (see maxRecoveryAttempts). */\n recoveryAttempts?: number | undefined;\n /** Searchable labels: the workflow's static `@Workflow({ tags })` merged with the run's start-time tags. */\n tags?: string[] | undefined;\n /** Typed, queryable run data (e.g. `{ amount: 200, tier: 'pro' }`) — see {@link RunQuery.attributes}. */\n searchAttributes?: SearchAttributes | undefined;\n /**\n * The worker-pool partition this run belongs to. Stamped at creation from the creating engine's\n * `namespace` (default `'default'`). A worker only picks up / recovers / resumes-timers-for /\n * times-out runs in its own namespace. `undefined` on a run created before this field existed; the\n * store persists it as `'default'`. Read paths (dashboard, `getRun`) are NOT namespace-scoped.\n */\n namespace?: string | undefined;\n /**\n * Dispatch priority for a REMOTE run (one advanced by a {@link WorkflowExecutor} over a broker):\n * carried onto each {@link WorkflowTask} so an urgent child workflow can jump ahead of enqueued\n * lower-priority ones at the worker. Higher wins; absent = unprioritised. Best-effort ordering, not\n * durable state required for correctness — a transport without priority support ignores it.\n */\n priority?: number | undefined;\n /**\n * REMOTE workflow turn awaiting a decision: the `taskId` of the turn the engine dispatched to a\n * workflow worker and then SUSPENDED on. Set by the dispatch-and-suspend path; matched by\n * {@link WorkflowEngine.completeRemoteDecision} so ONLY the decision for the currently-awaited turn\n * is applied (a stale/duplicate/foreign decision is dropped), then cleared the moment it is applied.\n * This is what makes a workflow-turn decision multi-instance safe: any engine instance that receives\n * the decision looks the run up by `decision.runId` and applies it durably, instead of resolving an\n * in-memory promise that only the dispatching instance held. Absent on non-remote / not-awaiting runs.\n */\n awaitingDecisionTaskId?: string | undefined;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * WHAT an event-parked suspended run is waiting on, resolved for display — the engine keeps one\n * generic `suspended` status (it's what drives recovery/timers/queries), but to a human \"waiting on\n * signal `approve`\" reads very differently from \"waiting on webhook `stripe-cb`\". Computed by the\n * store-backed gateway from the run's signal waiters (`listSignalWaiters`, ONE bulk scan), so the\n * dashboard can NAME the wait in a list row without fetching each run's timeline. `on` is derived from\n * the waiter token's prefix (see `classifyWaiterToken`): `wh:<runId>:<seq>` ⇒ `webhook`, `child:<id>`\n * ⇒ `child`, `bp:<runId>:<seq>` ⇒ `breakpoint` (a `ctx.breakpoint` DOES register a signal waiter —\n * same machinery, `engine.continue` resumes it — so it's classified here, not left to fall through to\n * the generic `signal` case with the raw token as its ugly display name), `event:<name>:…` ⇒ `signal`\n * (name decoded), anything else ⇒ `signal` (the token IS the signal name).\n *\n * Deliberately EVENT-only (no timer/step): `wakeAt` alone can't tell a real `ctx.sleep` from the\n * reconcile-fallback `wakeAt` an event/step suspend now carries, and the store exposes no cheap bulk\n * checkpoint scan to disambiguate — so the client shows a non-event suspend with a live worker as\n * `running` (it flips off \"no worker\" the moment a worker returns) rather than guessing \"sleeping\".\n * The detail view (which has the timeline) still distinguishes sleep vs in-flight step precisely.\n */\nexport interface RunWaiting {\n on: 'signal' | 'webhook' | 'child' | 'breakpoint';\n /**\n * The token/name the run is parked on — the signal name, webhook token, or awaited child id. For a\n * breakpoint this is always the literal `'breakpoint'`: the real label (if any) lives on the pending\n * `breakpoint`/`breakpoint:<label>` checkpoint, which the detail view's timeline already shows —\n * naming it here would need an extra per-run checkpoint read, defeating the bulk waiter scan.\n */\n name: string;\n}\n\nexport type StepKind = 'local' | 'remote' | 'sleep' | 'signal';\n\n/**\n * The recorded result of a single step at a deterministic logical position (`seq`).\n * On replay, a `completed` checkpoint means the step is NOT re-executed — its `output` is\n * returned. A non-terminal checkpoint (`pending`/`running`) does not short-circuit: the step is\n * re-awaited (remote) or re-run (local).\n */\nexport interface StepCheckpoint {\n runId: string;\n /** Deterministic logical position of the step within the run. */\n seq: number;\n /** Registered step name (matches the remote handler name for remote steps). */\n name: string;\n kind: StepKind;\n /** Stable id passed to remote workers so they can dedupe a re-delivered task. */\n stepId: string;\n /**\n * `pending` = a remote step dispatched and awaiting its worker result (the run is durably\n * suspended, not held in memory); it becomes `completed`/`failed` when the result arrives.\n * `running` = a local step whose body is executing in-process right now (see `trackStepStart`);\n * it's overwritten by `completed`/`failed` when the body settles, and on a crash mid-body it\n * simply re-runs on replay (only `completed` short-circuits).\n */\n status: 'pending' | 'running' | 'completed' | 'failed';\n /** What the step was called with — the `ctx.step` (dispatched) args for a remote step (a local step has none). */\n input?: unknown;\n output?: unknown;\n error?: StepError | undefined;\n attempts: number;\n /** For remote steps: which worker group ran it. */\n workerGroup?: string | undefined;\n /** Structured events/logs the step emitted (sub-step outcomes, debug/error lines). */\n events?: StepEvent[] | undefined;\n /** For sleep steps: epoch ms the sleep elapses at. */\n wakeAt?: number | undefined;\n /**\n * Set on the running placeholder checkpoints of the children dispatched by one `ctx.all` call —\n * a shared tag (`all:<firstSeq>`) grouping the N siblings so the dashboard can render them as one\n * parallel fan-out. Optional and additive: absent on every non-`all` checkpoint. Mirrors the\n * Python SDK's `parallelGroup`.\n */\n parallelGroup?: string | undefined;\n /**\n * When the step entered the system: for a remote step, when the engine dispatched it to the\n * transport; for a local step, when it began. Queue-wait time = `startedAt − enqueuedAt`.\n */\n enqueuedAt: Date;\n /** When processing actually began: worker pickup for a remote step, execution start for a local one. */\n startedAt: Date;\n finishedAt: Date;\n}\n\n/**\n * A structured event a step (or its worker) emits while running — a log line and/or a sub-step\n * outcome. The dashboard renders these under the step, so you can see what happened inside a step\n * that the workflow treats as one unit (e.g. which of N parallel sub-processes ok/failed/skipped).\n */\nexport interface StepEvent {\n /** Epoch ms. */\n at: number;\n level: 'debug' | 'info' | 'warn' | 'error';\n message: string;\n /** Stable run identity for a sub-process. Distinct invocations of the same `name` carry distinct\n * ids, so their phases and log trails never collapse into one. Absent on events emitted by the\n * legacy `sub()` path, which keys by `name` instead. */\n subId?: string;\n /** For a sub-step/sub-process within the step: its name. */\n name?: string;\n /** Open, consumer-defined grouping label for a sub-process (e.g. a handler/lane). The dashboard\n * groups rows by it. The library never interprets it. */\n group?: string;\n /** For a sub-step: its terminal outcome (closed enum — drives colour + aggregation). */\n status?: 'ok' | 'failed' | 'skipped';\n /** Open, consumer-defined intermediate phase label for a sub-process transition. Carries no\n * terminal `status`; the library timestamps and orders it but never interprets it. */\n phase?: string;\n /** For a log line emitted *inside* a sub-process: that owning sub-process's name, so the dashboard\n * can group a step's log trail under each sub-process instead of one flat list. Set on logs (no\n * `status`); a worker stamps it from the sub-process it's running.\n * @deprecated Superseded by `subId` for run-distinct grouping; kept so existing workers/runs render. */\n process?: string;\n /** Optional structured payload. `data.durationMs` (number) overrides the derived duration. */\n data?: unknown;\n}\n\n/**\n * Handed to a local step's body (`ctx.step(name, (log) => …)`) so it can record what happened\n * inside the step — debug/info/warn/error lines and per-sub-process outcomes. The events are\n * checkpointed with the step and rendered under it in the dashboard. The remote/cross-language\n * counterpart is the worker attaching the same `StepEvent[]` to its `StepResult` (see the Python\n * SDK's `StepContext`), so observability is symmetric regardless of where the step ran.\n */\nexport interface StepLogger {\n debug(message: string, data?: unknown): void;\n info(message: string, data?: unknown): void;\n warn(message: string, data?: unknown): void;\n error(message: string, data?: unknown): void;\n /** Record a sub-step / sub-process outcome (e.g. one of N parallel p-processes). */\n sub(name: string, status: 'ok' | 'failed' | 'skipped', message?: string, data?: unknown): void;\n /** Record a sub-process event. Typically pass `phase` for an intermediate transition (carrying no\n * terminal status), or `status` for the terminal outcome — the type permits either; the engine\n * interprets which is set. `id` is the run identity (distinct per invocation); `group` is an\n * open grouping label. */\n subEvent(e: {\n id: string;\n name: string;\n group?: string | undefined;\n phase?: string | undefined;\n status?: 'ok' | 'failed' | 'skipped' | undefined;\n message?: string | undefined;\n data?: unknown;\n }): void;\n /**\n * Ergonomic sub-process lifecycle: run `body`, timing it, and record a terminal `ok` with the\n * measured `durationMs` on success — or `failed` (with the error message) if it throws, then\n * re-throw. `sp.phase(label)` records an intermediate transition; `sp.skip(reason)` a terminal\n * `skipped`. Logs emitted inside `body` are tagged to this sub-process so the dashboard groups\n * them under it. Returns whatever `body` returns. The TS twin of the Python SDK's `sub_process`.\n *\n * ```ts\n * const rows = await log.subProcess('fetch-data', async () => readEverything());\n * await log.subProcess('export-file', () => upload(rows));\n * ```\n */\n subProcess<T>(\n name: string,\n body: (sp: SubProcessHandle) => Promise<T> | T,\n opts?: { group?: string; id?: string },\n ): Promise<T>;\n}\n\n/** The handle a {@link StepLogger.subProcess} body receives to mark phases / a non-`ok` outcome. */\nexport interface SubProcessHandle {\n /** Record an intermediate phase transition (a consumer-defined label, no terminal status). */\n phase(phase: string, data?: unknown): SubProcessHandle;\n /** Record a terminal `skipped` outcome (e.g. nothing to do / validation failed). */\n skip(reason?: string, data?: unknown): void;\n /** Record a terminal `failed` outcome explicitly (the wrapper also does this if the body throws). */\n fail(reason?: string, data?: unknown): void;\n}\n\nexport interface StepError {\n message: string;\n /** Optional machine-readable code, e.g. `declined`, `timeout`. */\n code?: string | undefined;\n /** Whether the engine should treat this as retryable. */\n retryable?: boolean | undefined;\n stack?: string | undefined;\n}\n\n// ---------------------------------------------------------------------------\n// StateStore — where runs and checkpoints live (Postgres / MySQL / SQLite via ORM adapters)\n// ---------------------------------------------------------------------------\n\nexport interface StateStore {\n /**\n * Provision the tables/collections this store needs, idempotently. Called on boot when the\n * module's `autoSchema` is on. Optional: stores that need no setup (in-memory) omit it.\n */\n ensureSchema?(): Promise<void>;\n\n createRun(run: WorkflowRun): Promise<void>;\n updateRun(runId: string, patch: Partial<WorkflowRun>): Promise<void>;\n getRun(runId: string): Promise<WorkflowRun | null>;\n\n /**\n * Hard-delete a run and all of its rows — the run plus its checkpoints, signal waiters, and\n * normalized search-attribute rows. Unlike a cancelled run (which stays as terminal history), a\n * deleted run is GONE: it no longer appears in {@link getRun} or {@link listRuns}. This removes\n * exactly the one run — the engine's {@link WorkflowEngine.deleteRun} handles the child cascade.\n * No-op if the run doesn't exist. (Token-keyed buffered signals are transient and left alone.)\n */\n deleteRun(runId: string): Promise<void>;\n\n /**\n * Hard-delete up to `limit` terminal runs that fall OUTSIDE `policy` (oldest / over the count cap\n * first), cascading to their child rows exactly like {@link deleteRun}. Returns how many runs were\n * deleted — call again while it returns `limit` to drain a large backlog in bounded batches.\n *\n * Optional: only adapters that implement a bulk prune provide it; the retention poller no-ops with a\n * warning when the configured store omits it. See {@link RetentionPolicy} for the keep/prune rule.\n */\n pruneTerminalRuns?(policy: RetentionPolicy, nowMs: number, limit: number): Promise<number>;\n\n getCheckpoint(runId: string, seq: number): Promise<StepCheckpoint | null>;\n /**\n * Persist a checkpoint and advance the run atomically. Durable semantics depend on this\n * being a single transaction; stores without transactions cannot give the strong guarantee.\n */\n saveCheckpoint(checkpoint: StepCheckpoint): Promise<void>;\n\n /** Used by recovery on boot to find runs to resume (crashed, left `running`). */\n listIncompleteRuns(namespace?: string): Promise<WorkflowRun[]>;\n\n /** The oldest `pending` runs awaiting dispatch (FIFO, by `createdAt`), capped at `limit`. */\n listPendingRuns(limit: number, namespace?: string): Promise<WorkflowRun[]>;\n\n /** Suspended runs whose durable timer is due (`wakeAt <= nowMs`), ready to resume. */\n listDueTimers(nowMs: number, namespace?: string): Promise<WorkflowRun[]>;\n\n /**\n * Atomically acquire the recovery lease on a run for `owner` until `leaseUntilMs`, but only if\n * it is currently unlocked or its lease has expired (`<= nowMs`). Returns whether it was\n * acquired — so concurrent engine instances never recover the same run twice.\n */\n tryLockRun(runId: string, owner: string, leaseUntilMs: number, nowMs: number): Promise<boolean>;\n\n /** Release a run's recovery lease so another instance can pick it up (e.g. once it suspends). */\n releaseRunLock(runId: string): Promise<void>;\n\n /**\n * Extend a run's lease to `leaseUntilMs`, but ONLY if `owner` still holds it — so a live worker\n * heartbeating its long run keeps the lease, while a dead worker's lease still expires and gets\n * reclaimed. Returns false if the lease was lost (taken over or released).\n */\n renewRunLock(runId: string, owner: string, leaseUntilMs: number): Promise<boolean>;\n\n /** Record that a run is suspended waiting for an external signal `token`. */\n putSignalWaiter(waiter: SignalWaiter): Promise<void>;\n /** Atomically take (and remove) the run waiting on `token`, if any. */\n takeSignalWaiter(token: string): Promise<SignalWaiter | null>;\n /** List waiters whose `token` starts with `prefix` — used to fan out an event to its subscribers. */\n listSignalWaiters(prefix: string): Promise<SignalWaiter[]>;\n\n /**\n * Delete the EXACT waiter row — `token` AND `runId` AND `seq` must all match — no-op if absent.\n * Unlike {@link takeSignalWaiter}, which deletes ANY row for `token` (fine when the caller just won\n * the race to consume it), this is for a caller removing its OWN registration after resolving the\n * wait some other way (a buffered hit, a timeout): blind `takeSignalWaiter(token)` there could steal\n * a DIFFERENT run's waiter that has since claimed the same token (`token` is the store's primary key,\n * so a later `putSignalWaiter` for the same token replaces the row). The exact-match variant only\n * ever removes the row this caller itself put there.\n */\n removeSignalWaiter(waiter: SignalWaiter): Promise<void>;\n\n /**\n * Buffer a signal whose waiter hasn't arrived yet, so the next `waitForSignal(token)` consumes it\n * instead of it being lost (FIFO per token). Makes signals reliable regardless of timing and\n * powers `signalWithStart`.\n */\n bufferSignal(token: string, payload: unknown): Promise<void>;\n /** Take the oldest buffered signal for `token` (FIFO), or null if none is buffered. */\n takeBufferedSignal(token: string): Promise<{ payload: unknown } | null>;\n\n /**\n * Buffer a published event that matched NO live waiter, so a LATER `ctx.waitForEvent(name, { match })`\n * still consumes it instead of it being silently dropped — the events analog of {@link bufferSignal}'s\n * reliability contract for signals, but MATCH-based rather than token-based: an event's buffer is keyed\n * by `name` alone (many waiters can share a name with different `match` criteria), so consumption is\n * list ({@link listBufferedEvents}) + evaluate the WAITER's own match predicate + claim\n * ({@link removeBufferedEvent}) — never a blind take, because the store has no way to know which\n * candidate a given waiter wants. `input.id` is minted by the caller (engine.publishEvent) so\n * {@link removeBufferedEvent} can later target this exact row.\n */\n bufferEvent(input: {\n name: string;\n payload: unknown;\n id: string;\n publishedAt: number;\n }): Promise<void>;\n /**\n * Buffered events for `name`, OLDEST (`publishedAt`) first, capped at `limit`. A waiter scans these,\n * evaluates its own `eventMatches(payload, match)` locally, and claims the one it wants via\n * {@link removeBufferedEvent} — the match predicate belongs to the WAITER, never the store.\n */\n listBufferedEvents(\n name: string,\n limit: number,\n ): Promise<Array<{ id: string; payload: unknown; publishedAt: number }>>;\n /**\n * Atomically delete the buffered event `id`. Returns `true` iff a row was actually deleted, `false`\n * if it was already gone (claimed by a concurrent waiter, reclaimed by `engine.publishEvent`'s own\n * late re-check, or pruned as expired) — the arbiter under concurrency: whichever caller's delete\n * returns `true` is the one that gets to deliver the payload; every other caller backs off.\n */\n removeBufferedEvent(id: string): Promise<boolean>;\n\n /**\n * Run `work` in a SINGLE store transaction — giving it the store-native transaction handle (`raw`)\n * for the caller's own DB writes plus a `saveCheckpoint` that commits IN THE SAME transaction, so a\n * business write and the step's \"done\" checkpoint are atomic (exactly-once). Optional — only the SQL\n * adapters implement it; `ctx.transaction` errors on a store without it.\n */\n transaction?<T>(work: (tx: StoreTransaction) => Promise<T>): Promise<T>;\n\n // Dashboard queries\n listRuns(query: RunQuery): Promise<WorkflowRun[]>;\n listCheckpoints(runId: string): Promise<StepCheckpoint[]>;\n\n /**\n * The LATEST checkpoint for `runId` whose `name` equals `name` exactly (highest `seq` wins), or\n * `undefined` if none. A targeted read that avoids fetching + deserializing every checkpoint just to\n * keep one match — the store does the filter (`WHERE name = … ORDER BY seq DESC LIMIT 1`). Preserves\n * the \"last in seq order wins\" semantics the engine relies on for `getEvent` (a re-published key\n * overwrites the prior value at a higher seq, so the highest-seq match is the current value).\n *\n * Optional: a store that omits it still works — the engine falls back to {@link listCheckpoints}\n * plus an in-JS filter that produces the identical result.\n */\n getLatestCheckpointByName?(runId: string, name: string): Promise<StepCheckpoint | undefined>;\n\n /**\n * All checkpoints for `runId` whose `name` starts with ANY of `prefixes`, ordered by `seq` ascending\n * (same order as {@link listCheckpoints}). A targeted read that avoids scanning every checkpoint just\n * to keep the prefix matches — the store does the filter (`WHERE name LIKE 'prefix%' …`). Used by the\n * run-tree to find a parent's child edges (`signal:child:` / `spawn:` checkpoints) without loading the\n * whole history. An empty `prefixes` array matches nothing.\n *\n * Optional: a store that omits it still works — the engine falls back to {@link listCheckpoints}\n * plus an in-JS prefix scan that produces the identical result.\n */\n listCheckpointsByNamePrefix?(runId: string, prefixes: string[]): Promise<StepCheckpoint[]>;\n}\n\n/** The terminal run statuses — a run in one of these is finished and will never change on its own.\n * Only these are eligible for retention pruning (a {@link RetentionPolicy} targeting a non-terminal\n * status would race the engine and delete live work). */\nexport const TERMINAL_RUN_STATUSES: readonly RunStatus[] = [\n 'completed',\n 'failed',\n 'cancelled',\n 'dead',\n];\n\n/**\n * One retention rule for hard-pruning terminal run history. Within `statuses` (terminal only), a run\n * is KEPT only if it satisfies EVERY bound you set, and pruned the moment it violates any:\n * - `maxAge` — prune runs whose `updatedAt` (≈ the time they reached terminal) is older than\n * `now - maxAge`. A number is milliseconds; a string is an `ms`-style duration parsed by\n * {@link parseDuration} (`'7d'`, `'2w'`, `'90m'` — note `'m'` is MINUTES; use `'30d'` for a month).\n * - `maxCount` — keep only the `maxCount` most-recent (by `updatedAt`) runs in the status set; prune\n * everything past that.\n *\n * Set one or both (both = the most-restrictive wins: capped at `maxCount` rows AND nothing older than\n * `maxAge`). Statuses not named by any policy are never pruned.\n */\nexport interface RetentionPolicy {\n statuses: RunStatus[];\n maxAge?: number | string;\n maxCount?: number;\n}\n\n/** Typed, queryable per-run data — exact values for `eq`/`ne`, numbers/strings for range ops. */\nexport type SearchAttributes = Record<string, string | number | boolean>;\n\n/**\n * A Standard Schema (https://standardschema.dev — implemented by zod 3.24+, valibot, arktype, …)\n * whose validated OUTPUT is search-attribute-shaped: flat `string`/`number`/`boolean` values only.\n * Declared via `@Workflow({ searchAttributes })`, this makes `ctx.upsertSearchAttributes` reject any\n * write whose merged result doesn't conform. The `Output extends SearchAttributes` bound is enforced\n * structurally at the declaration site — a schema whose inferred output has a nested object/array\n * value (e.g. `z.object({ meta: z.object({ ... }) })`) fails to satisfy this type, so it's a\n * compile-time error to declare it as a `searchAttributes` schema, not a runtime surprise.\n *\n * @example\n * ```ts\n * import { z } from 'zod';\n *\n * const orderAttrs = z.object({\n * tier: z.enum(['free', 'pro']),\n * amount: z.number(),\n * rushOrder: z.boolean().optional(),\n * });\n *\n * @Workflow({ name: 'checkout', searchAttributes: orderAttrs })\n * class CheckoutWorkflow {\n * async run(ctx: WorkflowCtx<InferSearchAttributes<typeof orderAttrs>>, input: CheckoutInput) {\n * await ctx.upsertSearchAttributes({ tier: input.tier, amount: input.total });\n * }\n * }\n * ```\n */\nexport type SearchAttributesSchema<A extends SearchAttributes = SearchAttributes> =\n StandardSchemaV1<unknown, A>;\n\n/** Infer the validated OUTPUT shape of a {@link SearchAttributesSchema} — the typed attributes a\n * workflow declares via `@Workflow({ searchAttributes })`. Feed it straight into `WorkflowCtx<A>`:\n * `WorkflowCtx<InferSearchAttributes<typeof mySchema>>`. */\nexport type InferSearchAttributes<S extends StandardSchemaV1<unknown, SearchAttributes>> =\n StandardSchemaV1.InferOutput<S>;\n\nexport type AttributeOp = 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte';\n\n/** One predicate over a run's {@link SearchAttributes}; a {@link RunQuery} ANDs them all. */\nexport interface AttributeFilter {\n key: string;\n op: AttributeOp;\n value: string | number | boolean;\n}\n\nexport interface RunQuery {\n workflow?: string | undefined;\n status?: RunStatus | undefined;\n /**\n * Match any of these statuses (a `status IN (...)` filter). ORed together, and ANDed with the other\n * predicates. Use this instead of issuing one {@link listRuns} call per status — e.g. the singleton\n * admission gate counts `running` + `suspended` in-flight runs in a single scan. If both `status` and\n * `statuses` are set, both must hold (the single `status` further narrows the set). Empty array =\n * matches nothing.\n */\n statuses?: RunStatus[] | undefined;\n /** Only runs carrying this tag (exact match against {@link WorkflowRun.tags}). */\n tag?: string | undefined;\n /**\n * Typed/range predicates over {@link WorkflowRun.searchAttributes}, ANDed together (e.g. `amount`\n * >= 200 and `tier` = 'pro'). Applied in-process after the coarse filters, so pair with\n * `workflow`/`status`/`tag` to bound the scan on large stores.\n */\n attributes?: AttributeFilter[] | undefined;\n /** Restrict to runs in this namespace (exact match), ANDed with the other predicates. */\n namespace?: string | undefined;\n limit?: number | undefined;\n offset?: number | undefined;\n}\n\n/** The transaction handle `StateStore.transaction` hands to its work callback. */\nexport interface StoreTransaction {\n /** The store-native transaction handle (TypeORM `EntityManager`, Prisma tx client, MikroORM `EntityManager`,\n * Drizzle tx) — do your business DB writes on THIS so they commit atomically with the checkpoint. */\n readonly raw: unknown;\n /** Persist the step checkpoint inside this transaction. */\n saveCheckpoint(checkpoint: StepCheckpoint): Promise<void>;\n}\n\n/** Binds an external signal `token` to the suspended run/step position waiting for it. */\nexport interface SignalWaiter {\n token: string;\n runId: string;\n seq: number;\n /**\n * The parallel-fan group this waiter belongs to, carried from the awaiting command so the resolving\n * `signal:<token>` checkpoint (notably `signal:child:<id>` for an awaited child run) can be tagged\n * with it. A worker's `ctx.gather_children`/`ctx.all` fan-out stamps every `startChild` with the same\n * group; without threading it through the waiter, the child-await checkpoint comes out untagged and the\n * dashboard renders the fan as a sequential chain instead of one parallel group. Undefined for an\n * ordinary (non-fan) signal/child await.\n */\n parallelGroup?: string | undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Transport — how a remote task travels to a worker and the result returns\n// ---------------------------------------------------------------------------\n\n/**\n * A DB-less tenant worker → control plane request to start a run. Published by a worker that has\n * no direct DB access (the hosted-control-plane tenant model) onto the\n * `<effectivePrefix>-start-run` queue; the control plane consumes it and turns it into a durable\n * run (P4 of the tenants plan).\n *\n * The `tenant` identifies the namespace that owns the run (maps to the engine's `namespace`); it\n * is separate from the wire-level key prefix so a single transport can serve multiple tenants.\n */\nexport interface StartRunMessage {\n tenant: string;\n /** Registered workflow name. */\n workflow: string;\n input: unknown;\n /** Optional caller-supplied run id (idempotency key). The engine generates one if absent. */\n runId?: string | undefined;\n /** Tags to stamp on the run (merged with the workflow's static @Workflow tags). */\n tags?: string[] | undefined;\n /** Typed, queryable run data to stamp on the run (same as {@link StartOptions.searchAttributes}). */\n searchAttributes?: SearchAttributes | undefined;\n}\n\n/**\n * A tenant worker → control plane read/control request over the shared transport. Enqueued on\n * `<effectivePrefix>-run-request`; the control plane's `onRunRequest` consumer answers it, scoped to\n * `tenant`, and publishes a {@link RunReply} on `<effectivePrefix>-run-reply` correlated by `requestId`.\n */\nexport interface RunRequest {\n /** Correlation id minted by the tenant; the matching {@link RunReply} carries it back. */\n requestId: string;\n /** The requesting tenant — the operator scopes the run's namespace to this. */\n tenant: string;\n body: RunRequestKind;\n}\n\n/** The discriminated verb + args of a {@link RunRequest}. Mirrors the tenant-facing `RunGateway`. */\nexport type RunRequestKind =\n | { kind: 'getRunDetail'; runId: string }\n | { kind: 'listRuns'; query: RunQuery }\n // Per-group worker health — the operator answers it scoped to the requester's own groups (see\n // `RunRequestResponder`), so a tenant's Workers panel shows ITS queues, never another tenant's.\n | { kind: 'workerHealth' }\n | { kind: 'cancel'; runId: string; opts?: { compensate?: boolean } }\n | { kind: 'retry'; runId: string }\n | { kind: 'continue'; runId: string }\n | { kind: 'retryWithInput'; runId: string; input: unknown }\n | { kind: 'redispatch'; runId: string }\n // Bulk, not runId-bearing (like `listRuns`/`workerHealth`) — the operator answers it in one shot\n // and filters the result to runs the requester's tenant actually owns (see `RunRequestResponder`).\n | { kind: 'waitingFor'; runIds: string[] };\n\n/** The control plane's answer to a {@link RunRequest}, correlated by `requestId`. */\nexport interface RunReply {\n requestId: string;\n result: RunReplyResult;\n}\n\n/** Success carries the verb's payload (JSON-serialised); failure carries a re-throwable error. */\nexport type RunReplyResult =\n | { ok: true; data: unknown }\n | { ok: false; error: { message: string; code?: string } };\n\n/** A lifecycle event re-published to a single tenant's channel (`<effectivePrefix>-tenant-events-<tenant>`)\n * so a store-less tenant can live-tail ITS OWN runs. Scoped by the run's namespace at publish time. */\nexport interface TenantEvent {\n tenant: string;\n event: EngineEvent;\n}\n\n/** A unit of work dispatched to a remote worker. This is the documented wire payload. */\nexport interface RemoteTask {\n runId: string;\n seq: number;\n /** Handler name the worker registered, e.g. `payments.charge-card`. */\n name: string;\n stepId: string;\n /** Worker group expected to handle this task. */\n group: string;\n input: unknown;\n /** W3C traceparent so the worker can continue the distributed trace. */\n traceparent?: string | undefined;\n /**\n * Opaque context carrier (tenant / user / correlation ids) the worker re-exposes to the step\n * handler, for cross-process propagation alongside the {@link traceparent}. The engine treats it\n * as a pass-through object and never inspects its shape — the producer (e.g. `@dudousxd/nestjs-context`)\n * owns the keys. Absent when no `context` provider is configured.\n */\n context?: Record<string, unknown> | undefined;\n /**\n * Id of the transport this task was dispatched on (when the engine runs a pool — see\n * {@link NamedTransport}). A worker that consumes several transports replies via the matching one,\n * so failover is symmetric without the worker choosing a transport. Absent for a single transport.\n */\n transport?: string | undefined;\n /**\n * Admission priority carried through to the broker (BullMQ job `priority`) so a transport that\n * supports priority ordering lets an urgent task jump ahead of already-enqueued lower-priority\n * ones at the worker. Mirrors the per-call `priority` from `ctx.step(..., { priority })`. Higher\n * wins; absent means default/unprioritised. Transports without priority support ignore it.\n */\n priority?: number | undefined;\n attempt: number;\n}\n\nexport interface StepResult {\n runId: string;\n seq: number;\n stepId: string;\n status: 'completed' | 'failed';\n output?: unknown;\n error?: StepError | undefined;\n /** Epoch ms when the worker began processing — lets the engine report queue-wait time. */\n startedAt?: number | undefined;\n /** Structured events the worker emitted while running the step (sub-step outcomes, logs). */\n events?: StepEvent[] | undefined;\n}\n\nexport interface Heartbeat {\n runId: string;\n seq: number;\n /**\n * The in-flight step this beat keeps alive. ABSENT for a RUN-scoped (workflow-turn) heartbeat: a\n * worker replaying a long workflow turn beats for its `runId` so the engine rearms the run's\n * `advance` deadline (see `WorkflowEngineDeps.remoteAdvanceSilenceMs`). The engine then keys the\n * liveness reset by `runId` instead of `stepId`.\n */\n stepId?: string | undefined;\n group: string;\n}\n\n// ---------------------------------------------------------------------------\n// Polyglot workflows — the workflow-task / commands protocol\n//\n// A workflow authored in a non-TS SDK (e.g. Python) runs coordinator-driven: the engine stays the\n// sole owner of the durable state + recovery/timers and advances the run one TURN at a time by\n// dispatching a {@link WorkflowTask} (the run's history) to a workflow worker, which REPLAYS the\n// function locally and returns a {@link WorkflowDecision} (the commands it produced). The engine\n// applies the decision (persist checkpoints, dispatch steps, schedule timers, settle the run). The\n// worker never touches the store. See docs/plans/2026-06-15-polyglot-workflows-protocol.md.\n// ---------------------------------------------------------------------------\n\n/** engine → workflow worker: advance this run one turn by replaying the function against `history`. */\nexport interface WorkflowTask {\n /** Dedupe id for this turn (a re-delivered task must be idempotent). */\n taskId: string;\n runId: string;\n /** Registered workflow name + the version the run started on — replay must use that version. */\n workflow: string;\n workflowVersion: string;\n input: unknown;\n /** Completed durable ops so far, ordered by seq — what the worker replays its results from. */\n history: HistoryEvent[];\n /** Signals delivered to the run but not yet consumed, so `wait_signal` resolves on replay. */\n pendingSignals?: Array<{ seq: number; signal: string; payload: unknown }>;\n group: string;\n /** Id of the transport this task was dispatched on (pool failover) — see {@link NamedTransport}. */\n transport?: string;\n traceparent?: string;\n /**\n * Admission priority carried to the broker (BullMQ job `priority`) so an urgent child workflow can\n * jump ahead of already-enqueued lower-priority ones at the worker. Higher wins; absent means\n * default/unprioritised. Transports without priority support ignore it.\n */\n priority?: number | undefined;\n attempt: number;\n}\n\n/** One resolved durable op in a run's history — a superset of a completed {@link StepCheckpoint}. */\nexport interface HistoryEvent {\n seq: number;\n kind: 'step' | 'call' | 'timer' | 'signal' | 'child';\n name?: string | undefined;\n /** Resolved value: a step/call output, a child run's output, a signal payload. */\n output?: unknown;\n /** Set when the op resolved to a failure (e.g. a failed remote step the workflow may catch). */\n error?: StepError | undefined;\n}\n\n/** A decision the workflow function produced at a `seq` that was not yet in history. */\nexport type WorkflowCommand =\n /** `ctx.step(handlerOrName, input)` — dispatch a step (by typed handler reference or by name) and\n * await it. A worker's `ctx.gather_calls([...])` fan-out tags every dispatched call with the same\n * `parallelGroup` so the dashboard renders the dispatched steps as one parallel fan (parity with\n * the gathered `recordStep` / `startChild` tags). Undefined for a lone sequential `ctx.step`. */\n | {\n kind: 'call';\n seq: number;\n name: string;\n group: string;\n input: unknown;\n parallelGroup?: string;\n }\n /** `ctx.step(name, body)` — a LOCAL step the worker already ran this turn; the engine persists its\n * result so replay returns it instead of re-running (durability for side-effectful work).\n * `startedAt`/`finishedAt` (epoch ms) carry the step's real wall-clock window so the dashboard\n * shows a true duration instead of 0ms, and `events` carry the sub-process/log trail the step\n * emitted (so each handler's p-processes show under it). All optional for back-compat. */\n | {\n kind: 'recordStep';\n seq: number;\n name: string;\n output?: unknown;\n error?: StepError;\n startedAt?: number;\n finishedAt?: number;\n events?: StepEvent[];\n /** A worker's `ctx.gather([...])` tags every step in the parallel fan with the same group, so the\n * engine carries it onto the checkpoint and the dashboard renders the fan as one group. */\n parallelGroup?: string;\n }\n /** `ctx.sleep(ms)` — a durable timer of `ms` duration. The engine computes the absolute deadline\n * (now + ms) when it applies the command, so the worker never reads the clock (determinism). */\n | { kind: 'sleep'; seq: number; ms: number }\n /** `ctx.wait_signal(name)` — block until a signal `name` is delivered to the run. */\n | { kind: 'waitSignal'; seq: number; signal: string }\n /** `ctx.start_child(workflow, input)` — start a child run with its own lifecycle. A worker's\n * `ctx.all([...])` fan-out tags every dispatched child with the same `parallelGroup` so the\n * dashboard can render the fan as one group (parity with the gathered `recordStep` tag). */\n | {\n kind: 'startChild';\n seq: number;\n workflow: string;\n input: unknown;\n parallelGroup?: string;\n };\n\n/** workflow worker → engine: the result of replaying one turn of a remote workflow. */\nexport interface WorkflowDecision {\n taskId: string;\n runId: string;\n /** `continue` = produced `commands` and is blocked on an await; otherwise the run settles.\n * `cancelled` = the worker bailed at an op boundary because the run was cancelled mid-turn. */\n status: 'continue' | 'completed' | 'failed' | 'cancelled';\n /** New durable ops the replay produced this turn (status === 'continue'), ordered by seq. */\n commands: WorkflowCommand[];\n /** Final workflow output (status === 'completed'). */\n output?: unknown;\n /** Terminal error (status === 'failed'). */\n error?: StepError;\n}\n\n/**\n * workflow worker → engine: a LOCAL step's lifecycle, streamed AS IT HAPPENS (not batched into the\n * turn's final {@link WorkflowDecision}). A Python `@workflow` runs its `ctx.step`s inline over one\n * turn that can last minutes; without this the engine learns of the steps only when the turn ends,\n * so the dashboard shows nothing mid-run. The worker emits `running` when a step's body starts and\n * `completed`/`failed` when it settles; the engine checkpoints each immediately, so a step appears\n * in-flight and then resolves live. The turn's final `recordStep` command re-persists the same\n * checkpoint idempotently (replay history), so this is purely additive observability.\n */\nexport interface WorkflowStepEvent {\n runId: string;\n seq: number;\n name: string;\n phase: 'running' | 'completed' | 'failed';\n /** Epoch ms the step body began (all phases) and settled (`completed`/`failed`). */\n startedAt: number;\n finishedAt?: number;\n /** The replayed result / failure for the settled phases. */\n output?: unknown;\n error?: StepError;\n /** Sub-process + log trail the step emitted so far (the handler's p-processes). */\n events?: StepEvent[];\n /** A worker's `ctx.gather([...])` fan tags every step's lifecycle with the same group so the\n * dashboard renders the live fan-out as one group (parity with the `recordStep` tag). */\n parallelGroup?: string | undefined;\n}\n\n/**\n * Advances a workflow run one turn. The engine has one per workflow: the default {@link InProcess}\n * one runs a registered TS function with the in-process replay machinery; a remote one dispatches a\n * {@link WorkflowTask} to a worker (Python) and awaits its {@link WorkflowDecision}. Either way the\n * engine applies the returned decision — so recovery, timers, singleton and dead-letter stay engine\n * concerns, identical for in-process and remote workflows.\n */\nexport interface WorkflowExecutor {\n /**\n * INLINE replay: advance the turn and RETURN its decision (the in-process executor runs the\n * registered TS function synchronously). The engine awaits this under the run's lease. Provide this\n * OR {@link dispatch} — exactly one. An executor with only `advance` is single-instance by nature\n * (the decision is produced in-process, not delivered over a broker).\n */\n advance?(\n run: WorkflowRun,\n history: HistoryEvent[],\n pendingSignals?: WorkflowTask['pendingSignals'],\n ): Promise<WorkflowDecision>;\n /**\n * DISPATCH-AND-SUSPEND (broker-backed, multi-instance safe): enqueue the turn to a worker under the\n * ENGINE-SUPPLIED `taskId`, WITHOUT awaiting the decision. The engine generates `taskId`, records it\n * on the run as the awaited marker, AND releases the run's lease — all BEFORE calling this — so the\n * worker's {@link WorkflowDecision} (delivered over {@link Transport.onDecision} and applied DURABLY\n * by {@link WorkflowEngine.completeRemoteDecision}, which looks the run up by `decision.runId`) can\n * never arrive ahead of its marker or contend with a still-held lease and be dropped. This method\n * therefore ONLY enqueues — it owns no taskId generation and returns nothing. No in-memory await, so\n * the decision is never lost to a point-to-point broker handing it to a non-dispatching instance.\n * Provide this OR {@link advance} — exactly one.\n */\n dispatch?(\n run: WorkflowRun,\n history: HistoryEvent[],\n taskId: string,\n pendingSignals?: WorkflowTask['pendingSignals'],\n ): Promise<void>;\n}\n\n/**\n * A transport in an ordered pool, identified by `id`. The engine dispatches on the first by default\n * and fails over to the next on a dispatch error; a step can pin one via `ctx.step(…, { transport })`.\n * The chosen `id` is stamped on the {@link RemoteTask} so a worker replies through the matching one.\n */\nexport interface NamedTransport {\n id: string;\n transport: Transport;\n}\n\n/**\n * Decides where a freshly-`start`ed run executes. `start` creates the run as `pending` and hands its\n * id here instead of running the body inline — so the API/caller never blocks on workflow execution.\n * The default in-process dispatcher runs it on this instance (a microtask); a broker-backed one\n * enqueues the id for a worker pool to consume (`engine.runOne(runId)`); a no-op one leaves it\n * `pending` in the store for a worker's `runPending` poll to pick up (DB-only, caller-doesn't-execute).\n */\nexport interface RunDispatcher {\n dispatch(runId: string): void | Promise<void>;\n}\n\nexport interface Transport {\n /** engine → worker */\n dispatch(task: RemoteTask): Promise<void>;\n /** worker → engine: a step finished (ok or error). */\n onResult(handler: (result: StepResult) => Promise<void>): void;\n /** worker → engine: liveness signal for an in-flight long step. */\n onHeartbeat(handler: (beat: Heartbeat) => Promise<void>): void;\n /** Release the transport's resources (broker workers, queues, connections) for a clean shutdown.\n * Optional — an in-process transport has nothing to close. Called on `onApplicationShutdown`\n * after the engine drains, so a deploy hands off instead of leaving the broker to time out. */\n close?(): Promise<void>;\n /** engine → workflow worker: dispatch a {@link WorkflowTask} (the polyglot-workflow path). Optional\n * — only transports that carry workflow tasks (BullMQ) implement it; the {@link RemoteWorkflowExecutor}\n * uses it + {@link onDecision} to advance a remote workflow over the broker. */\n dispatchWorkflowTask?(task: WorkflowTask): Promise<void>;\n /** workflow worker → engine: a replayed turn's {@link WorkflowDecision}. Pair with dispatchWorkflowTask. */\n onDecision?(handler: (decision: WorkflowDecision) => Promise<void>): void;\n /** workflow worker → engine: a LOCAL step's {@link WorkflowStepEvent}, streamed mid-turn so the\n * engine can checkpoint it live. Point-to-point (a single engine instance consumes each event and\n * persists it once — no cross-pod duplicate writes). Optional; only broker transports carry it. */\n dispatchStepEvent?(event: WorkflowStepEvent): Promise<void>;\n /** engine ← workflow worker: consume streamed {@link WorkflowStepEvent}s. Pair with dispatchStepEvent. */\n onStepEvent?(handler: (event: WorkflowStepEvent) => Promise<void>): void;\n /** Worker-health for a group: queue backlog + live worker heartbeats. Optional — only broker\n * transports (BullMQ) that can introspect the task queue and the worker-heartbeat keys implement\n * it. The engine aggregates this across its groups in {@link WorkflowEngine.workerHealth}. */\n groupHealth?(group: string): Promise<GroupHealth>;\n /** Distinct groups that currently have a live worker heartbeat — discovered from the heartbeat\n * keyspace, so a group with workers but no engine-side registration (e.g. a local-step group)\n * still surfaces. Pairs with {@link groupHealth}. */\n listWorkerGroups?(): Promise<string[]>;\n /**\n * DB-less tenant worker → control plane: publish a {@link StartRunMessage} requesting a new run.\n * Optional — only transports that carry the hosted-control-plane protocol (P4) implement this.\n * The message is enqueued on `<effectivePrefix>-start-run`; the control plane's\n * `onStartRun` consumer turns it into a durable run.\n */\n dispatchStartRun?(msg: StartRunMessage): Promise<void>;\n /**\n * control plane ← tenant worker: consume {@link StartRunMessage}s and start runs. Pair with\n * {@link dispatchStartRun}. Optional — only control-plane-side transports implement this.\n */\n onStartRun?(handler: (msg: StartRunMessage) => Promise<void>): void;\n /**\n * Tenant worker → control plane: publish a {@link RunRequest} (read/control) on\n * `<effectivePrefix>-run-request`. Optional — only broker transports carry it.\n */\n dispatchRunRequest?(msg: RunRequest): Promise<void>;\n /** control plane ← tenant worker: consume {@link RunRequest}s. Pair with {@link dispatchRunRequest}. */\n onRunRequest?(handler: (msg: RunRequest) => Promise<void>): void;\n /** control plane → tenant worker: publish a correlated {@link RunReply} on `<effectivePrefix>-run-reply`\n * (pub/sub; every tenant subscribes and filters by `requestId`). */\n publishRunReply?(reply: RunReply): Promise<void>;\n /** tenant worker ← control plane: consume {@link RunReply}s (filter by `requestId` client-side). */\n onRunReply?(handler: (reply: RunReply) => void): void;\n /** control plane → tenant worker: re-publish a lifecycle {@link TenantEvent} on the run's per-tenant\n * channel `<effectivePrefix>-tenant-events-<tenant>`. */\n publishTenantEvent?(evt: TenantEvent): Promise<void>;\n /** tenant worker ← control plane: subscribe to THIS tenant's event channel. Returns an unsubscribe fn. */\n onTenantEvent?(tenant: string, handler: (evt: TenantEvent) => void): () => void;\n}\n\n/** How a worker decides its concurrency, carried in {@link WorkerStatus} so a dashboard can tell a\n * fixed knob from a self-regulating one (and, for the latter, where the controller currently sits). */\nexport interface WorkerConcurrencyStatus {\n /** `fixed` = the configured `concurrency` number, never moves. `adaptive` = the controller tunes it. */\n mode: 'fixed' | 'adaptive';\n /** The concurrency ceiling in effect right now (fixed: the configured value; adaptive: the live limit). */\n limit: number;\n /** Adaptive only — the floor the controller won't go below. */\n min?: number;\n /** Adaptive only — the ceiling the controller won't exceed. */\n max?: number;\n}\n\n/** The adaptive controller's most recent limit change — the \"why did it move\" a dashboard shows so an\n * auto-tuner isn't a black box. Absent until the controller first adjusts (or for a fixed worker). */\nexport interface WorkerAdjust {\n /** Epoch ms of the adjustment. */\n at: number;\n /** Limit before this change. */\n from: number;\n /** Limit after this change. */\n to: number;\n /** Why it moved: `ram_ceiling` (hard brake), `backpressure` (errors/stall), `grow` (had headroom),\n * `shrink` (latency gradient showed queuing), `cpu_ceiling`. */\n reason: 'ram_ceiling' | 'cpu_ceiling' | 'backpressure' | 'grow' | 'shrink';\n}\n\n/** A live snapshot of a worker's execution state, carried in the worker-liveness heartbeat (so it\n * rides the existing TTL'd key — no extra round-trip) and surfaced per worker in the dashboard. Every\n * field beyond {@link concurrency}/{@link inFlight} is best-effort: a field a runtime can't measure is\n * simply omitted. The shape is shared by the TS and Python SDKs so a mixed-language group reports\n * uniformly. */\nexport interface WorkerStatus {\n /** Which SDK is running this worker — `node` (TS) or `python`. */\n runtime?: 'node' | 'python';\n /** The worker's concurrency knob and its live ceiling. */\n concurrency: WorkerConcurrencyStatus;\n /** Tasks executing right now (0..limit). With `limit`, this is the saturation a dashboard charts. */\n inFlight: number;\n /** Resident set size in bytes, if the runtime can read it. */\n rssBytes?: number;\n /** The process memory ceiling in bytes (cgroup `memory.max`, else host total), if known. */\n rssLimitBytes?: number;\n /** RSS as a percent of {@link rssLimitBytes} (0..100) — what the adaptive RAM brake watches. */\n rssPct?: number;\n /** Process CPU utilisation percent over the last control tick (0..100×cores), if measured. */\n cpuPct?: number;\n /** Completed tasks per minute over the recent window — the controller's throughput signal. */\n throughputPerMin?: number;\n /** p95 of recent task durations in ms — the latency a dashboard charts against the limit. */\n p95Ms?: number;\n /** The adaptive controller's last limit change (absent for a fixed worker or before the first move). */\n lastAdjust?: WorkerAdjust;\n}\n\n/** One worker's liveness record — a TTL'd heartbeat a worker refreshes while it's consuming. Its\n * ABSENCE (the key expired) is the signal: a worker that died or stalled stops refreshing. */\nexport interface WorkerHeartbeat {\n /** The worker group this instance serves (e.g. `pipeline`, `processing-workflows`). */\n group: string;\n /** Stable per-process id (host + pid), so N replicas of a group each show as a distinct worker. */\n instanceId: string;\n /** Epoch ms of the worker's most recent heartbeat. */\n lastBeatAt: number;\n /** The worker's live execution snapshot, when its heartbeat carries one (newer SDKs stamp a JSON\n * value; an older SDK's bare-timestamp heartbeat leaves this undefined). */\n status?: WorkerStatus;\n}\n\n/** Per-group worker-health snapshot: how much work is queued vs. how many workers are alive to do it.\n * The actionable alert state is `depth > 0 && liveWorkers.length === 0` — work piling up with no\n * consumer (exactly the failure where a worker is \"alive but not consuming\"). */\nexport interface GroupHealth {\n group: string;\n /** Outstanding jobs in the group's task queue (waiting + active + delayed + prioritized). */\n depth: number;\n /** Workers with a non-expired heartbeat for this group. */\n liveWorkers: WorkerHeartbeat[];\n /**\n * Whether this group serves a `@Workflow` body or a `@Step`/handler — route-by-handler gives each\n * its own queue, so a health list mixes both. Classified by the CONTROL PLANE from its authoritative\n * registry (`workerHealth()`): a group whose base name is a registered workflow is `'workflow'`,\n * everything else (in-process steps, remote `handle_*`) is `'step'`. `undefined` only when no\n * control-plane registry was available to classify (e.g. a transport that reports health with no\n * engine). Lets a dashboard summarise the fleet in domain terms (\"N workflows · M steps\") instead of\n * leaking the raw queue count.\n */\n kind?: 'workflow' | 'step';\n}\n\n/**\n * The **control plane** — a broadcast pub/sub across ALL engine instances (every pod), separate\n * from the {@link Transport}'s point-to-point work queues (`dispatch`/`onResult`). It carries what\n * every instance may need regardless of who runs a given run: lifecycle events (so a dashboard-only\n * pod can live-tail a run executing on a worker pod) and cancellation (so the pod actually running a\n * run learns it was cancelled elsewhere). In-process implementations broadcast locally; a\n * cross-process one (BullMQ) fans out over its broker (Redis pub/sub). Give the engine a\n * `controlPlane` to enable cross-instance events/cancellation; omit it and the engine is local-only.\n * A transport that can broadcast may implement this too and be passed as both.\n */\nexport interface ControlPlane {\n publishControl(msg: ControlMessage): Promise<void>;\n onControl(handler: (msg: ControlMessage) => void): void;\n}\n\n/** A message on the {@link ControlPlane}. `from` is the originating engine's `instanceId`, so a\n * broker that echoes a publish back to its own subscriber (e.g. Redis pub/sub) can be deduped by\n * the originator. */\nexport type ControlMessage = { from?: string } & (\n | { kind: 'event'; event: EngineEvent }\n | { kind: 'cancel'; runId: string }\n // A run was just enqueued — nudge worker instances to pick it up now instead of on the next poll.\n | { kind: 'enqueued'; runId: string }\n);\n\n// ---------------------------------------------------------------------------\n// Authoring — workflows, local steps, and typed remote steps\n// ---------------------------------------------------------------------------\n\nexport type BackoffStrategy = 'fixed' | 'exp';\n\n/**\n * Options for `ctx.child` / `ctx.startChild`. A bare string passed instead is shorthand for\n * `{ childId }`, so the existing `ctx.child(ref, input, 'my-id')` form keeps working.\n */\nexport interface ChildCallOptions {\n /** Deterministic child run id; defaults to one derived from the parent run id + call position. */\n childId?: string | undefined;\n /**\n * Dispatch priority for a REMOTE child workflow — stamped on the child run and carried onto every\n * {@link WorkflowTask} dispatched to advance it, so an urgent child can jump ahead of enqueued\n * lower-priority ones at the worker. Higher wins; absent = unprioritised. Ignored for an in-process\n * (TS class) child, which runs in the engine and never hits a broker queue.\n */\n priority?: number | undefined;\n}\n\nexport interface StepOptions {\n /** Max attempts before the step (and run) fails. */\n retries?: number;\n /** How the delay between retries grows: `fixed` (constant) or `exp` (doubles each attempt). */\n backoff?: BackoffStrategy;\n /** Base delay in ms between retries. Omit (or 0) to retry with no delay. */\n backoffMs?: number;\n /** Upper bound on the (exponential) backoff delay. */\n backoffMaxMs?: number;\n /** Add random jitter (50–100% of the computed delay) to avoid thundering-herd retries. */\n jitter?: boolean;\n /**\n * Liveness window for a dispatched step (`ctx.step`): if the worker produces no result and no\n * heartbeat within this many ms, the engine presumes it dead and fails the dispatch with a\n * `RemoteStepTimeout` (retryable — it re-dispatches per `retries`). Each heartbeat resets the\n * window. Omit to wait indefinitely.\n */\n timeoutMs?: number;\n /**\n * Saga compensation: if this step completes but the run later **fails**, the engine runs the\n * registered `compensate` callbacks in reverse order (undo what was done). Local steps only.\n * Idempotency note: a step is already deduplicated by its deterministic `stepId` (runId:seq) —\n * remote workers can use it as the idempotency key, so there's no separate key option.\n */\n compensate?: () => Promise<void>;\n}\n\n/**\n * The structural carrier a dispatched `ctx.step` call resolves to and hands the engine: `name` is\n * the routing contract (the worker registers a handler under the same name, and routing is BY that\n * name — a worker subscribes per registered handler name, not a hand-declared group). There is no\n * public factory for this anymore — a `ctx.step(ref, input)` call builds one internally from the\n * `@Step`-stamped name (see {@link StepRef}/`stepNameOf`); a `ctx.step(name, input)` call builds one\n * from the literal string. `input`/`output` are optional runtime zod schemas an authoring layer MAY\n * attach (e.g. `@Step({ input, output })`) for validation at the dispatch boundary — a bare `@Step()`\n * carries neither, and the engine skips validation when they're absent.\n */\nexport interface StepDef<TInput = unknown, TOutput = unknown> extends StepOptions {\n name: string;\n /** Optional isolation partition; routing is by `name`. Suffixes the routing token as\n * `<name>@<partition>` (via {@link tenantGroup}) — omit to route by the bare (sanitized) `name`. */\n partition?: string | undefined;\n input?: z.ZodType<TInput> | undefined;\n output?: z.ZodType<TOutput> | undefined;\n}\n\n/**\n * A durable webhook handle minted by {@link WorkflowCtx.webhook}. Hand `url` to a third party,\n * then `await wait()` — the run suspends with zero compute until the external system POSTs the\n * callback (delivered as `engine.signal(token, body)`), and resumes with the body.\n */\nexport interface DurableWebhook<TPayload = unknown> {\n /** Deterministic signal token (`wh:<runId>:<seq>`) the callback delivers on — stable across replay. */\n readonly token: string;\n /**\n * Public callback URL for `token`, built by the engine's `webhookUrl` option. Hand this to the\n * third party. `undefined` when no builder is configured (use {@link DurableWebhook.token} to\n * build your own).\n */\n readonly url?: string | undefined;\n /**\n * Suspend until the callback arrives, then resume with its payload. Waits indefinitely by default —\n * no compute consumed. Pass `{ timeoutMs }` to bound the wait: if the deadline passes first the call\n * throws a `SignalTimeoutError` (catch it in the workflow to branch) — same timeout semantics as\n * {@link WorkflowCtx.waitForSignal}. The deadline is computed once (on the first call) and persisted,\n * so a replay reuses the recorded deadline rather than recomputing it from the current clock.\n */\n wait(opts?: { timeoutMs?: number }): Promise<TPayload>;\n}\n\n/**\n * Options for a dispatched {@link WorkflowCtx.step} call. `retries`/`backoff`/`backoffMs`/\n * `backoffMaxMs`/`jitter`/`timeoutMs` are a PER-CALL override of the `@Step`-declared\n * {@link StepConfig} (see `stepConfigOf`) — the effective policy `ctx.step` builds into the dispatched\n * {@link StepDef} is `{ ...stepConfigOf(ref), ...opts }`, so a call-site value wins field-by-field. The\n * string (cross-runtime) form of `ctx.step` has no stamped `@Step` to read, so it uses these fields\n * as-is.\n */\nexport interface StepDispatchOpts {\n /** Subject the dispatch to a registered flow-control queue (concurrency / rate limit). */\n queue?: string;\n /** Admission priority within `queue`; higher is admitted first when a slot is contended\n * (default 0). No effect without a `queue`. */\n priority?: number;\n /** The fairness bucket for a queue with `fairness: 'key'` (e.g. a tenant id) — the queue\n * round-robins across distinct keys so one key can't monopolize the budget. Defaults to the run\n * id when omitted. No effect without a `queue`. */\n fairnessKey?: string;\n /** Pin the dispatch to a named transport in the pool (else the pool's first, with failover to the\n * rest). See `engine.registerQueue` / the engine's `transports` option. */\n transport?: string;\n /** Max attempts before the step (and run) fails. Overrides the `@Step`-declared value. */\n retries?: number;\n /** How the delay between retries grows: `fixed` (constant) or `exp` (doubles each attempt).\n * Overrides the `@Step`-declared value. */\n backoff?: BackoffStrategy;\n /** Base delay in ms between retries. Omit (or 0) to retry with no delay. Overrides the\n * `@Step`-declared value. */\n backoffMs?: number;\n /** Upper bound on the (exponential) backoff delay. Overrides the `@Step`-declared value. */\n backoffMaxMs?: number;\n /** Add random jitter (50–100% of the computed delay) to avoid thundering-herd retries. Overrides\n * the `@Step`-declared value. */\n jitter?: boolean;\n /** Liveness window for this dispatched step: no result/heartbeat within this many ms presumes the\n * worker dead and fails the dispatch with a `RemoteStepTimeout` (retryable — re-dispatches per\n * `retries`). Omit to wait indefinitely. Overrides the `@Step`-declared value. */\n timeoutMs?: number;\n}\n\n/** What a saga undo handler receives: the compensated step's original input and its result — the\n * ONE argument a compensation `@Step` is called with, so it's self-describing on the wire (a\n * Python worker sees `{ input, output }` with no side-channel lookup needed). */\nexport interface StepUndo<TInput, TOutput> {\n input: TInput;\n output: TOutput;\n}\n\n/**\n * Derive a `ctx.step` compensation handler's expected argument from the ORIGINAL step's method\n * type, so the ref form is compile-checked against the step it undoes:\n *\n * ```ts\n * async cancelBooking(undo: UndoOf<FlightService['book']>) { ... }\n * ```\n *\n * `...rest: never[]` pins this to a single-argument method (the shape every `@Step` handler has —\n * see {@link StepRef}); `Awaited<R>` unwraps a `Promise<TOutput>` return down to `TOutput`.\n */\nexport type UndoOf<H> = H extends (input: infer I, ...rest: never[]) => infer R\n ? StepUndo<I, Awaited<R>>\n : never;\n\n/**\n * The context handed to a workflow function. Every interaction with the outside world goes\n * through it so the engine can checkpoint — the workflow body itself stays deterministic.\n *\n * Generic over `A`, the run's {@link SearchAttributes} shape — narrows {@link upsertSearchAttributes}\n * when a workflow declares a `@Workflow({ searchAttributes })` schema (pass\n * `WorkflowCtx<InferSearchAttributes<typeof mySchema>>` as the `run` method's ctx type). Defaults to\n * the untyped `SearchAttributes`, so every existing `WorkflowCtx` usage is unaffected.\n */\nexport interface WorkflowCtx<A extends SearchAttributes = SearchAttributes> {\n readonly runId: string;\n /**\n * Run a durable step — always dispatched, always engine-scheduled: the ONE step primitive (no\n * local/remote placement choice). Pass the step's method **reference** (a `@Step`-decorated\n * method, typed by its own signature — refactor-safe, autocompleted):\n *\n * ```ts\n * const r = await ctx.step(this.extraction.runExtractionPage, { page, key });\n * ```\n *\n * or its **name** for a cross-runtime handler (no JS reference to import, e.g. a Python `@step`):\n *\n * ```ts\n * const out = await ctx.step<ProcResult>('processing:proc', input);\n * ```\n *\n * Both forms dispatch identically — a step runs on whatever worker serves that name and the run\n * suspends (zero compute) until the result lands, then resumes with it (durable, replay-safe).\n *\n * `opts.compensate` registers a SAGA UNDO for this call, dispatched (durably, in reverse order\n * with every other registered undo) if the run later fails or is cancelled with\n * `{ compensate: true }`. The undo is itself a normal `@Step` — pass its reference (compile-time\n * checked: it must accept `StepUndo<TInput, TOutput>` of THIS call, see {@link UndoOf}) or its\n * name for a cross-runtime undo handler. It runs on whatever worker serves that name, called with\n * the ONE `{ input, output }` envelope — never the original handler re-invoked in-process.\n */\n step<TInput, TOutput>(\n handler: StepRef<TInput, TOutput>,\n input: TInput,\n opts?: StepDispatchOpts & { compensate?: StepRef<StepUndo<TInput, TOutput>, unknown> | string },\n ): Promise<TOutput>;\n step<TOutput = unknown, TInput = unknown>(\n name: string,\n input: TInput,\n opts?: StepDispatchOpts & { compensate?: StepRef<StepUndo<TInput, TOutput>, unknown> | string },\n ): Promise<TOutput>;\n /**\n * **Exactly-once** durable step for DB work: runs `fn` and writes the step's checkpoint in ONE\n * store transaction, so the business write and the \"done\" marker commit atomically — a crash can\n * never leave the write done-but-not-checkpointed (which a plain `ctx.step` would re-run). `fn`\n * receives the store-native transaction handle (`tx` — a TypeORM/MikroORM `EntityManager`, a Prisma\n * tx client, or a Drizzle tx); do your writes on it. Needs a SQL store that supports transactions\n * (the bundled SQL adapters do); throws otherwise.\n */\n transaction<TOutput>(name: string, fn: (tx: unknown) => Promise<TOutput>): Promise<TOutput>;\n /**\n * Call a durable **entity** op and await its result — the entity (`engine.registerEntity`) runs the\n * op serialized per `key` over durable state. e.g. `await ctx.callEntity('cart', userId, 'add', item)`.\n */\n callEntity<TResult = unknown>(\n name: string,\n key: string,\n op: string,\n arg?: unknown,\n ): Promise<TResult>;\n /** Send a durable entity op without awaiting a result (fire-and-forget, dispatched once). */\n signalEntity(name: string, key: string, op: string, arg?: unknown): Promise<void>;\n /**\n * Durable sleep: suspends the run for `duration` (e.g. `'30s'`, `'2h'`, `'7 days'`, or ms as a\n * number) without consuming resources, resuming automatically once the timer is due — even\n * across restarts.\n */\n sleep(duration: string | number): Promise<void>;\n /**\n * Durable sleep until an **absolute** time (a `Date` or epoch ms) — like {@link sleep} but for a\n * fixed deadline (e.g. \"resume at midnight\"). Resumes automatically once the time passes, across\n * restarts. The recorded wake time is fixed on the first run, so it's replay-stable.\n */\n sleepUntil(when: Date | number): Promise<void>;\n /**\n * End this run and **continue as a fresh execution** of the same workflow with `input` and a clean\n * history — for long-running / looping workflows that would otherwise accumulate unbounded\n * checkpoints (and slow replays). The next run gets id `<runId>~N`. Terminal: it always throws, so\n * code after it never runs. Carry forward whatever state the next iteration needs in `input`.\n */\n continueAsNew(input?: unknown): Promise<never>;\n /**\n * Suspend the run until an external `engine.signal(token, payload)` arrives (e.g. a webhook or\n * human approval), then resume with the payload. Waits indefinitely by default — no compute\n * consumed. Pass `{ timeoutMs }` to bound the wait: if the deadline passes first the call throws\n * a `SignalTimeoutError` (catch it in the workflow to branch).\n */\n waitForSignal<TPayload>(token: string, opts?: { timeoutMs?: number }): Promise<TPayload>;\n /**\n * Wait for a named **event** published via `engine.publishEvent(name, payload)`, then resume with\n * the payload. Unlike a signal (point-to-point by token), events are name-based pub/sub: pass an\n * optional `match` (a subset of the payload that must deep-equal) so a publish fans out only to the\n * runs it concerns — e.g. `ctx.waitForEvent('payment.settled', { match: { orderId } })`. `timeoutMs`\n * bounds the wait (throws `SignalTimeoutError`). No compute consumed while waiting.\n */\n waitForEvent<TPayload>(\n name: string,\n opts?: { match?: Record<string, unknown>; timeoutMs?: number },\n ): Promise<TPayload>;\n /**\n * An external task with **async completion**: run `dispatch` once (checkpointed — e.g. send to a\n * queue, kick off a non-durable worker or a foreign service like a Python process), then suspend\n * with zero compute until `engine.completeTask(runId, name, result)` (or `failTask`) reports back,\n * and resume with the result. The durable, first-class counterpart of the hand-rolled\n * \"dispatch over SQS → wait for COMPLETE_PHASE → signal\" pattern. `name` must be unique per run.\n */\n task<TResult>(\n name: string,\n dispatch: () => Promise<void>,\n options?: StepOptions,\n ): Promise<TResult>;\n /**\n * Run another registered workflow as a **tracked child** and await its result: starts it once and\n * suspends — zero compute — until the child reaches a terminal state, then resumes with the child's\n * output (or throws a FatalError if the child failed). `childId` defaults to a deterministic id\n * derived from this run and the call position, so it's stable across replay.\n *\n * Pass the child's **class** (`ctx.child(ShippingWorkflow, input)`) for a typed input + result; pass\n * a **string** name for a cross-runtime child (e.g. a Python workflow) where there's no class.\n */\n child<C extends WorkflowClass>(\n workflow: C,\n input: WorkflowInputOf<C>,\n options?: string | ChildCallOptions,\n ): Promise<WorkflowOutputOf<C>>;\n child<TOutput>(\n workflow: string,\n input: unknown,\n options?: string | ChildCallOptions,\n ): Promise<TOutput>;\n /**\n * Start a child workflow **fire-and-forget**: dispatches it once (checkpointed, replay-safe) and\n * returns its run id immediately — the parent keeps running instead of suspending. Use it to kick\n * off side work (an audit log, a notification) you don't need to wait on, or to fan out: collect\n * the ids, then later `await ctx.child(...)` each with the same id to join (the start is idempotent\n * by id, so the child runs exactly once). Class or string ref, like {@link child}.\n */\n startChild<C extends WorkflowClass>(\n workflow: C,\n input: WorkflowInputOf<C>,\n options?: string | ChildCallOptions,\n ): Promise<string>;\n startChild(\n workflow: string,\n input: unknown,\n options?: string | ChildCallOptions,\n ): Promise<string>;\n /**\n * Run N children of the SAME workflow **in parallel** and wait for ALL of them: dispatches one\n * child per entry in `inputs` (concurrently, each with its own durable lifecycle), suspends — zero\n * compute — until every child reaches a terminal state, then resumes with their outputs in **input\n * order**. Child ids are group-scoped and stable (`<runId>.all.<firstSeq>.<i>`), and the running\n * placeholders share a `parallelGroup` tag so the dashboard renders the fan-out as one group.\n *\n * `mode` (default `waitAll`): `waitAll` waits for all then throws an aggregate {@link GatherError}\n * if any failed; `failFast` throws as soon as a failed child is seen, and requests cancellation of\n * every sibling that hasn't completed yet (best-effort, plain cancel — no saga undo; a sibling\n * mid-step only observes it at its next checkpoint, it isn't force-killed mid-synchronous-execution,\n * so a fast sibling can still slip through and complete). Empty `inputs` returns `[]` with no side\n * effects. The wait-all / fan-out counterpart to {@link child}; parity with the Python SDK's\n * `gather_children`.\n */\n all<C extends WorkflowClass>(\n workflow: C,\n inputs: WorkflowInputOf<C>[],\n opts?: { mode?: 'waitAll' | 'failFast' },\n ): Promise<WorkflowOutputOf<C>[]>;\n all<TOutput = unknown>(\n workflow: string,\n inputs: unknown[],\n opts?: { mode?: 'waitAll' | 'failFast' },\n ): Promise<TOutput[]>;\n /**\n * Pause the run at this point until a human resumes it from the dashboard (or\n * `engine.continue(runId)`). Records a visible `pending` checkpoint so the breakpoint shows up\n * in the timeline, then suspends with zero compute — the durable equivalent of a debugger\n * breakpoint. Gate it on your own config to make breakpoints opt-in per run:\n * `if (cfg.breakAfterExtraction) await ctx.breakpoint('after-extraction')`.\n */\n breakpoint(label?: string): Promise<void>;\n /**\n * Mint a durable webhook: returns a handle with a deterministic `token` and (if the engine has a\n * `webhookUrl` builder) a public `url`. Hand the url to a third party — inside a `ctx.step` — then\n * `await handle.wait()` to suspend with zero compute until they POST the callback (the dashboard\n * turns that POST into `engine.signal(token, body)`). The first-class, replay-safe version of\n * \"expose a callback URL and wait for it\".\n */\n webhook<TPayload>(): DurableWebhook<TPayload>;\n /**\n * Publish a named, queryable value from inside the run — the latest value for `key` is readable\n * externally via `engine.getEvent(runId, key)` while the run is still in flight (progress, a\n * partial result, a status). Checkpointed and replay-safe (overwrites the previous value for the\n * same key). The read side has no effect on the run — the durable, suspend-model counterpart of a\n * Temporal query.\n */\n setEvent<TValue>(key: string, value: TValue): Promise<void>;\n /**\n * Expose a named **update point**: suspend until an external `engine.update(runId, name, arg)`\n * delivers `arg`, then resume with it. The update is run-scoped (`name` need only be unique within\n * the run) and gated by any validator registered via `engine.registerUpdateValidator` — a rejected\n * update never reaches here. Pass `{ timeoutMs }` to bound the wait (throws `SignalTimeoutError`).\n * The durable counterpart of a Temporal update handler.\n */\n onUpdate<TArg>(name: string, opts?: { timeoutMs?: number }): Promise<TArg>;\n /**\n * Guard an in-place workflow change without a new version. Wrap the changed code in\n * `if (await ctx.patched('my-change')) { …new… } else { …old… }`: a fresh run records a marker and\n * takes the new branch (`true`); a run already recorded under the old code keeps the old branch\n * (`false`), because its history has a real step where the marker would sit. The marker is\n * position-transparent for old runs (it doesn't shift their recorded steps), so guarding code is\n * replay-safe. Once every old run has drained, remove the guard (keep the new branch).\n */\n patched(id: string): Promise<boolean>;\n /**\n * Deterministic wall-clock, epoch **milliseconds** (like `Date.now()`): records the time on the\n * first run and replays the SAME value afterwards. Use this instead of `Date.now()`/`new Date()`\n * inside a workflow — a raw clock read returns a different value on every replay, which silently\n * corrupts a durable run. Returns a number so it composes in arithmetic (deadlines, elapsed);\n * for an ISO string do `new Date(await ctx.now()).toISOString()`. Every step is dispatched now\n * (see {@link step}), so a trivial timestamp capture gets this lightweight deterministic helper\n * instead of a full `@Step` + worker round-trip.\n */\n now(): Promise<number>;\n /**\n * **Deterministic capture.** Run `fn` once, checkpoint its result, and on replay return the SAME\n * value WITHOUT re-running `fn` — the durable way to bring a non-deterministic value into a workflow\n * where you control the generator: `ctx.sideEffect(() => uuidv7())`, `() => ulid()`,\n * `() => Math.random()`, a config/env read. Prefer a {@link step} for real work with side effects\n * (a DB write, an API call): `fn` here runs only once and MUST be effectively pure (it produces a\n * value; it is not re-executed on replay), like Temporal's `sideEffect`. For a plain timestamp use\n * {@link now}.\n */\n sideEffect<TValue>(fn: () => TValue | Promise<TValue>): Promise<TValue>;\n /**\n * Merge `attrs` into THIS run's {@link WorkflowRun.searchAttributes} — the indexed metadata the\n * dashboard and {@link RunQuery} filter on. Shallow merge: keys you don't pass are kept. Durable +\n * exactly-once — recorded at this position on the first run and SKIPPED on replay, so it does one\n * write, not one per turn. Use this instead of injecting the {@link StateStore} to mutate the run\n * you're executing (`@Inject(state-store)` + `store.updateRun(ctx.runId, …)` becomes\n * `ctx.upsertSearchAttributes(…)`).\n *\n * When the workflow declares a `@Workflow({ searchAttributes })` schema, the MERGED result (this\n * run's existing `searchAttributes` shallow-merged with `attrs`) is validated against it before the\n * write — an invalid merge throws, naming the workflow, the offending key(s), and the schema's\n * issues. Validation runs once, on the same first-run-only position as the write itself (skipped\n * entirely on replay, so it's never a source of nondeterminism); it must be synchronous — a schema\n * whose `validate` returns a `Promise` throws instead of being awaited. No schema declared ⇒\n * unchanged, unvalidated behavior.\n */\n upsertSearchAttributes(attrs: Partial<A>): Promise<void>;\n /**\n * Run a checkpointed step **in-process** — the escape hatch from the always-dispatched {@link step}\n * for work that must run inline in the workflow body. Like `step`, its result is a durable checkpoint\n * (returned, not re-run, on replay); unlike `step`, the body `fn` executes here rather than on a\n * worker, so it can carry an in-memory `compensate` callback for **sagas** — an undo the engine runs\n * in reverse if the run later fails (see [Sagas & compensation](/docs/reliability/sagas)). `fn`\n * receives a {@link StepLogger} for sub-process events. Prefer {@link step} for ordinary work; reach\n * for `localStep` when you need in-process execution or a compensation.\n */\n localStep<TOutput>(\n name: string,\n fn: (log: StepLogger) => Promise<TOutput>,\n options?: StepOptions,\n ): Promise<TOutput>;\n}\n\n/** Result of executing or resuming a workflow run. */\nexport interface RunResult {\n runId: string;\n status: RunStatus;\n output?: unknown;\n error?: StepError | undefined;\n}\n\n/**\n * Validates an incoming `engine.update` before it is delivered to the run. Throw (or return a\n * non-empty string) to reject — the run is left untouched. Return nothing/void to accept. May be\n * async (e.g. a business-rule check against a DB).\n */\n// A validator may return nothing (accept) or a reason string (reject); `void` is the intended\n// \"returned nothing\" case, sync or async.\nexport type UpdateValidator<TArg = unknown> =\n // biome-ignore lint/suspicious/noConfusingVoidType: `void` here means \"returned nothing\" (accept).\n (arg: TArg) => void | string | Promise<void | string>;\n\n/** Outcome of `engine.update`: rejected by the validator, or accepted and delivered. */\nexport type UpdateResult =\n | { accepted: false; reason: string }\n | { accepted: true; run: RunResult | null };\n\nexport type EngineEventType =\n | 'run.started'\n | 'run.completed'\n | 'run.failed'\n | 'run.suspended'\n | 'step.started'\n | 'step.completed'\n | 'step.failed'\n // A single step event (log line / sub-process outcome) emitted WHILE a step is still running, so\n // observers tail a long step's progress live instead of waiting for `step.completed` to deliver\n // the whole `events` array at once. Carries `event`; never persisted (live-tail only).\n | 'step.progress';\n\n/**\n * A lifecycle event emitted by the engine. The observability surfaces (dashboard, OTel, the\n * Telescope integration) all subscribe to these rather than reaching into the store.\n */\nexport interface EngineEvent {\n type: EngineEventType;\n runId: string;\n workflow?: string | undefined;\n /** The run's worker-pool partition (see {@link WorkflowRun.namespace}), stamped on the `run.*`\n * lifecycle events (where the emitting call site already has the run in hand) so a tenant-event\n * re-publisher can scope without a per-event store read. Absent on `step.*` events. */\n namespace?: string | undefined;\n seq?: number | undefined;\n name?: string | undefined;\n kind?: StepKind | undefined;\n output?: unknown;\n error?: StepError | undefined;\n /** Wall-clock duration of the unit that just finished (step or run), when known. */\n durationMs?: number | undefined;\n /** For a remote step: how long it waited in the queue before a worker picked it up. */\n queueMs?: number | undefined;\n /** The live step event carried by a `step.progress` (the single log line / sub-process outcome a\n * running step just emitted). Absent on lifecycle events. */\n event?: StepEvent | undefined;\n at: Date;\n}\n\nexport type EngineListener = (event: EngineEvent) => void;\n\n/** What a {@link StepInterceptor} is told about the local step it is wrapping. */\nexport interface StepInvocation {\n readonly runId: string;\n readonly workflow: string;\n /** The step name passed to `ctx.step(name, ...)` (also `'now'`/`'random'`/`'uuid'` internals). */\n readonly stepName: string;\n /** The step's logical position within the run. */\n readonly seq: number;\n /** 1-based attempt number — increments across `ctx.step` retries. */\n readonly attempt: number;\n}\n\n/**\n * Wraps the **real execution** of a local `ctx.step` (Template/Nest-style onion middleware). Call\n * `next()` to run the step body (or the next interceptor) and return — or transform — its result;\n * throw to fail the step. First-registered runs outermost. Interceptors fire only when a step\n * actually executes, NOT on replay (a replayed step returns its recorded output without running),\n * so they see true execution timing. Register with `engine.use`.\n */\nexport type StepInterceptor = (\n invocation: StepInvocation,\n next: () => Promise<unknown>,\n) => Promise<unknown>;\n","import type { RunQuery, SignalWaiter, StateStore, StepCheckpoint, WorkflowRun } from './interfaces';\n\n/**\n * Transforms a payload value as it crosses the store boundary — e.g. encrypt-at-rest, compress, or\n * redact PII. `decode` must be the exact inverse of `encode`. Both are synchronous (use a local\n * cipher / codec); wrap an async KMS yourself if you need one.\n */\nexport interface PayloadCodec {\n encode(value: unknown): unknown;\n decode(value: unknown): unknown;\n}\n\n/**\n * A `StateStore` decorator that runs run/step **payloads** (input + output) through a\n * {@link PayloadCodec} — encoded on write, decoded on read — so they're never stored in the clear.\n * Adapter-agnostic: wrap any store. Searchable metadata (id, status, workflow, tags, timestamps) and\n * the structured `error` are left untouched so the dashboard, queries, and recovery still work.\n *\n * ```ts\n * const store = new CodecStateStore(new TypeOrmStateStore(ds), aesCodec);\n * ```\n */\nexport class CodecStateStore implements StateStore {\n constructor(\n private readonly inner: StateStore,\n private readonly codec: PayloadCodec,\n ) {}\n\n private enc(v: unknown): unknown {\n return v === undefined ? undefined : this.codec.encode(v);\n }\n private dec(v: unknown): unknown {\n return v === undefined ? undefined : this.codec.decode(v);\n }\n\n private encRun(run: WorkflowRun): WorkflowRun {\n return { ...run, input: this.enc(run.input), output: this.enc(run.output) };\n }\n private decRun<T extends WorkflowRun | null>(run: T): T {\n return (run && { ...run, input: this.dec(run.input), output: this.dec(run.output) }) as T;\n }\n private encCp(cp: StepCheckpoint): StepCheckpoint {\n return { ...cp, input: this.enc(cp.input), output: this.enc(cp.output) };\n }\n private decCp<T extends StepCheckpoint | null>(cp: T): T {\n return (cp && { ...cp, input: this.dec(cp.input), output: this.dec(cp.output) }) as T;\n }\n\n ensureSchema(): Promise<void> {\n return this.inner.ensureSchema?.() ?? Promise.resolve();\n }\n\n createRun(run: WorkflowRun): Promise<void> {\n return this.inner.createRun(this.encRun(run));\n }\n updateRun(runId: string, patch: Partial<WorkflowRun>): Promise<void> {\n const next = { ...patch };\n if ('input' in patch) next.input = this.enc(patch.input);\n if ('output' in patch) next.output = this.enc(patch.output);\n return this.inner.updateRun(runId, next);\n }\n async getRun(runId: string): Promise<WorkflowRun | null> {\n return this.decRun(await this.inner.getRun(runId));\n }\n deleteRun(runId: string): Promise<void> {\n return this.inner.deleteRun(runId);\n }\n async getCheckpoint(runId: string, seq: number): Promise<StepCheckpoint | null> {\n return this.decCp(await this.inner.getCheckpoint(runId, seq));\n }\n saveCheckpoint(checkpoint: StepCheckpoint): Promise<void> {\n return this.inner.saveCheckpoint(this.encCp(checkpoint));\n }\n transaction<T>(\n work: (tx: {\n raw: unknown;\n saveCheckpoint: (cp: StepCheckpoint) => Promise<void>;\n }) => Promise<T>,\n ): Promise<T> {\n if (!this.inner.transaction) {\n throw new Error('the wrapped store does not support transactions');\n }\n // Encode the checkpoint inside the tx, so payloads stay encoded at rest like the normal path.\n return this.inner.transaction((tx) =>\n work({ raw: tx.raw, saveCheckpoint: (cp) => tx.saveCheckpoint(this.encCp(cp)) }),\n );\n }\n async listIncompleteRuns(namespace?: string): Promise<WorkflowRun[]> {\n return (await this.inner.listIncompleteRuns(namespace)).map((r) => this.decRun(r));\n }\n async listPendingRuns(limit: number, namespace?: string): Promise<WorkflowRun[]> {\n return (await this.inner.listPendingRuns(limit, namespace)).map((r) => this.decRun(r));\n }\n async listDueTimers(nowMs: number, namespace?: string): Promise<WorkflowRun[]> {\n return (await this.inner.listDueTimers(nowMs, namespace)).map((r) => this.decRun(r));\n }\n tryLockRun(runId: string, owner: string, leaseUntilMs: number, nowMs: number): Promise<boolean> {\n return this.inner.tryLockRun(runId, owner, leaseUntilMs, nowMs);\n }\n releaseRunLock(runId: string): Promise<void> {\n return this.inner.releaseRunLock(runId);\n }\n renewRunLock(runId: string, owner: string, leaseUntilMs: number): Promise<boolean> {\n return this.inner.renewRunLock(runId, owner, leaseUntilMs);\n }\n putSignalWaiter(waiter: SignalWaiter): Promise<void> {\n return this.inner.putSignalWaiter(waiter);\n }\n takeSignalWaiter(token: string): Promise<SignalWaiter | null> {\n return this.inner.takeSignalWaiter(token);\n }\n listSignalWaiters(prefix: string): Promise<SignalWaiter[]> {\n return this.inner.listSignalWaiters(prefix);\n }\n removeSignalWaiter(waiter: SignalWaiter): Promise<void> {\n return this.inner.removeSignalWaiter(waiter);\n }\n bufferSignal(token: string, payload: unknown): Promise<void> {\n return this.inner.bufferSignal(token, this.enc(payload));\n }\n async takeBufferedSignal(token: string): Promise<{ payload: unknown } | null> {\n const buffered = await this.inner.takeBufferedSignal(token);\n return buffered && { payload: this.dec(buffered.payload) };\n }\n bufferEvent(input: {\n name: string;\n payload: unknown;\n id: string;\n publishedAt: number;\n }): Promise<void> {\n return this.inner.bufferEvent({ ...input, payload: this.enc(input.payload) });\n }\n async listBufferedEvents(\n name: string,\n limit: number,\n ): Promise<Array<{ id: string; payload: unknown; publishedAt: number }>> {\n const events = await this.inner.listBufferedEvents(name, limit);\n return events.map((e) => ({ ...e, payload: this.dec(e.payload) }));\n }\n removeBufferedEvent(id: string): Promise<boolean> {\n return this.inner.removeBufferedEvent(id);\n }\n async listRuns(query: RunQuery): Promise<WorkflowRun[]> {\n return (await this.inner.listRuns(query)).map((r) => this.decRun(r));\n }\n async listCheckpoints(runId: string): Promise<StepCheckpoint[]> {\n return (await this.inner.listCheckpoints(runId)).map((c) => this.decCp(c));\n }\n async getLatestCheckpointByName(\n runId: string,\n name: string,\n ): Promise<StepCheckpoint | undefined> {\n // Forward the targeted read when the inner store implements it; otherwise fall back to the\n // (always-present) listCheckpoints scan so wrapping a legacy custom store keeps working.\n if (this.inner.getLatestCheckpointByName) {\n const cp = await this.inner.getLatestCheckpointByName(runId, name);\n return cp ? this.decCp(cp) : undefined;\n }\n let latest: StepCheckpoint | undefined;\n for (const cp of await this.inner.listCheckpoints(runId)) if (cp.name === name) latest = cp;\n return latest ? this.decCp(latest) : undefined;\n }\n async listCheckpointsByNamePrefix(runId: string, prefixes: string[]): Promise<StepCheckpoint[]> {\n const matches = this.inner.listCheckpointsByNamePrefix\n ? await this.inner.listCheckpointsByNamePrefix(runId, prefixes)\n : (await this.inner.listCheckpoints(runId)).filter((cp) =>\n prefixes.some((p) => cp.name.startsWith(p)),\n );\n return matches.map((c) => this.decCp(c));\n }\n}\n","import type { EngineEvent } from './interfaces';\n\nexport interface MetricsSnapshot {\n runs: { started: number; completed: number; failed: number; suspended: number };\n steps: { started: number; completed: number; failed: number };\n /** Per-workflow run counters, keyed by workflow name. */\n byWorkflow: Record<string, { started: number; completed: number; failed: number }>;\n /** Sum + count of recorded step durations (ms), for an average. */\n stepDuration: { sumMs: number; count: number };\n}\n\nexport interface MetricsCollector {\n snapshot(): MetricsSnapshot;\n /** Prometheus text exposition of the counters — serve this from a `/metrics` endpoint. */\n prometheus(): string;\n /** Unsubscribe from the engine. */\n stop(): void;\n}\n\ntype Subscribable = { subscribe(listener: (event: EngineEvent) => void): () => void };\n\n/**\n * Subscribe to an engine's lifecycle events and accumulate Prometheus-style counters (runs + steps by\n * outcome, per-workflow run counts, step-duration sum/count). Dependency-free — call `.prometheus()`\n * from your metrics endpoint, or `.snapshot()` for the raw numbers. Counters are per process; scrape\n * each instance.\n */\nexport function collectMetrics(engine: Subscribable): MetricsCollector {\n const m: MetricsSnapshot = {\n runs: { started: 0, completed: 0, failed: 0, suspended: 0 },\n steps: { started: 0, completed: 0, failed: 0 },\n byWorkflow: {},\n stepDuration: { sumMs: 0, count: 0 },\n };\n const wf = (name?: string) => {\n const k = name ?? 'unknown';\n let entry = m.byWorkflow[k];\n if (!entry) {\n entry = { started: 0, completed: 0, failed: 0 };\n m.byWorkflow[k] = entry;\n }\n return entry;\n };\n\n const stop = engine.subscribe((e) => {\n switch (e.type) {\n case 'run.started':\n m.runs.started += 1;\n wf(e.workflow).started += 1;\n break;\n case 'run.completed':\n m.runs.completed += 1;\n wf(e.workflow).completed += 1;\n break;\n case 'run.failed':\n m.runs.failed += 1;\n wf(e.workflow).failed += 1;\n break;\n case 'run.suspended':\n m.runs.suspended += 1;\n break;\n case 'step.started':\n m.steps.started += 1;\n break;\n case 'step.completed':\n m.steps.completed += 1;\n if (e.durationMs != null) {\n m.stepDuration.sumMs += e.durationMs;\n m.stepDuration.count += 1;\n }\n break;\n case 'step.failed':\n m.steps.failed += 1;\n break;\n }\n });\n\n return {\n snapshot: () => structuredClone(m),\n stop,\n prometheus: () => {\n const lines: string[] = [];\n lines.push('# TYPE durable_runs_total counter');\n for (const [k, v] of Object.entries(m.runs))\n lines.push(`durable_runs_total{event=\"${k}\"} ${v}`);\n lines.push('# TYPE durable_steps_total counter');\n for (const [k, v] of Object.entries(m.steps))\n lines.push(`durable_steps_total{event=\"${k}\"} ${v}`);\n lines.push('# TYPE durable_runs_by_workflow_total counter');\n for (const [name, v] of Object.entries(m.byWorkflow))\n for (const [event, n] of Object.entries(v))\n lines.push(`durable_runs_by_workflow_total{workflow=\"${name}\",event=\"${event}\"} ${n}`);\n lines.push('# TYPE durable_step_duration_ms_sum counter');\n lines.push(`durable_step_duration_ms_sum ${m.stepDuration.sumMs}`);\n lines.push('# TYPE durable_step_duration_count counter');\n lines.push(`durable_step_duration_count ${m.stepDuration.count}`);\n return `${lines.join('\\n')}\\n`;\n },\n };\n}\n","import { createRequire } from 'node:module';\nimport type { WorkflowEngine } from './engine';\n\n// Resolve the optional `cron-parser` peer dependency in a way that works in BOTH the ESM and CJS\n// builds of this package (dual publish). `createRequire(import.meta.url)` gives a real `require` in\n// ESM output; in the CJS build, tsup's banner shims `import.meta.url` to the file URL, so the same\n// call resolves there too. This keeps the load synchronous (no async leak into the scheduler API).\nconst nodeRequire = createRequire(import.meta.url);\n\nexport interface ScheduledWorkflow {\n /** Stable key identifying this schedule — part of the deterministic run id. */\n key: string;\n workflow: string;\n input?: unknown;\n /** Start one run every `everyMs`. Mutually exclusive with `cron`. */\n everyMs?: number;\n /**\n * A cron expression (5 fields `m h dom mon dow`, or 6 with leading seconds) evaluated in\n * {@link ScheduledWorkflow.timezone}. Mutually exclusive with `everyMs`. Needs the optional peer\n * dependency `cron-parser`.\n */\n cron?: string;\n /** IANA timezone the `cron` fires in (e.g. `America/Sao_Paulo`). Defaults to UTC. */\n timezone?: string;\n /** Temporarily stop firing this schedule (kept registered). Defaults to false. */\n paused?: boolean;\n /**\n * What to do when the previous window's run hasn't finished yet (fixed-interval schedules only):\n * `'allow'` (default) starts the new window anyway; `'skip'` skips it while the prior run is still\n * `running`/`suspended`, so a slow run can't pile up overlapping executions.\n */\n overlap?: 'allow' | 'skip';\n /**\n * Randomly delay the dispatch by up to this many ms BEFORE firing, to spread load when many\n * instances tick on the same boundary (avoids a thundering herd). Opt-in; absent = fire immediately.\n *\n * This is dispatch-path jitter only — it does NOT affect the run id (still the time bucket), so\n * idempotency is unchanged: two instances jittering the same window still start it exactly once.\n * (The engine forbids `Math.random` inside workflow code; the scheduler dispatch path is not\n * workflow code, so jitter here is fine.)\n */\n jitter?: number;\n /**\n * Enqueue windows that were missed while the scheduler was down, instead of silently skipping\n * them. Opt-in; absent = only the current window fires. `maxCatchup` bounds how many PRIOR windows\n * are backfilled (a long outage can't flood the system). Backfilled runs use each missed window's\n * deterministic bucket run id, so `engine.start` idempotency skips any that already ran.\n */\n backfill?: { maxCatchup: number };\n}\n\n/** Injectable dispatch-path effects (kept out of the deterministic run-id logic). Defaults to real\n * `Math.random` + `setTimeout`; overridden in tests so jitter is deterministic and instant. */\nexport interface RunSchedulesOptions {\n random?: () => number;\n sleep?: (ms: number) => Promise<void>;\n}\n\nconst defaultSleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));\n\n/** Deterministic run id for a fixed-interval schedule's current time window. */\nexport function scheduledRunId(key: string, everyMs: number, nowMs: number): string {\n return `sched:${key}:${Math.floor(nowMs / everyMs)}`;\n}\n\ntype CronParser = typeof import('cron-parser');\nlet cronParser: CronParser | undefined;\nfunction loadCronParser(): CronParser {\n if (cronParser) return cronParser;\n try {\n // Lazy + optional: core stays dependency-free; only users who schedule by cron need this.\n cronParser = nodeRequire('cron-parser') as CronParser;\n } catch {\n throw new Error(\n 'cron schedules need the optional peer dependency \"cron-parser\" — install it (e.g. `npm i cron-parser`).',\n );\n }\n return cronParser;\n}\n\n/**\n * Epoch ms of the most recent cron fire at or before `nowMs`, evaluated in `timezone` (default UTC).\n * This is the deterministic \"bucket\" a cron run is keyed on, so polling repeatedly within an\n * interval resolves to the same fire time — and thus the same idempotent run id.\n */\nexport function prevCronFireMs(expr: string, nowMs: number, timezone = 'UTC'): number {\n const parser = loadCronParser();\n // `+1` makes a fire landing exactly on `nowMs` count as \"at or before now\", not the prior one.\n const it = parser.parseExpression(expr, { currentDate: new Date(nowMs + 1), tz: timezone });\n return it.prev().toDate().getTime();\n}\n\n/** The deterministic, idempotent run id for a schedule at `nowMs` — its current fire window. */\nfunction scheduleRunIdAt(s: ScheduledWorkflow, nowMs: number): string {\n if (s.cron != null) return `sched:${s.key}:${prevCronFireMs(s.cron, nowMs, s.timezone)}`;\n if (s.everyMs != null) return scheduledRunId(s.key, s.everyMs, nowMs);\n throw new Error(`schedule \"${s.key}\" needs either \"everyMs\" or \"cron\"`);\n}\n\n/**\n * The run ids this schedule should fire at `nowMs`: the current window, plus — when `backfill` is set\n * — up to `maxCatchup` prior windows that may have been missed. Oldest-first, so a backfill catches\n * up in chronological order. Ids are the same deterministic buckets `scheduleRunIdAt` produces, so\n * `engine.start` idempotency drops any window that already ran.\n */\nfunction scheduleRunIdsAt(s: ScheduledWorkflow, nowMs: number): string[] {\n const current = scheduleRunIdAt(s, nowMs);\n if (!s.backfill || s.backfill.maxCatchup <= 0) return [current];\n\n const ids: string[] = [];\n if (s.everyMs != null) {\n const bucket = Math.floor(nowMs / s.everyMs);\n const oldest = Math.max(0, bucket - s.backfill.maxCatchup);\n for (let b = oldest; b < bucket; b += 1) ids.push(`sched:${s.key}:${b}`);\n } else if (s.cron != null) {\n // Walk back through prior cron fire times (most-recent missed first), then reverse to oldest-first.\n const prior: string[] = [];\n let cursor = prevCronFireMs(s.cron, nowMs, s.timezone);\n for (let i = 0; i < s.backfill.maxCatchup; i += 1) {\n // `cursor` (exclusive) → the fire strictly before it.\n const before = prevCronFireMs(s.cron, cursor - 1, s.timezone);\n prior.push(`sched:${s.key}:${before}`);\n cursor = before;\n }\n ids.push(...prior.reverse());\n }\n ids.push(current);\n return ids;\n}\n\n/**\n * Start each schedule's current-window run. The run id is the time bucket (a fixed-interval index,\n * or the cron fire time) and `engine.start` is idempotent, so firing this on an interval — or\n * racing two instances on the same tick — starts **each window exactly once**. Wire it to a\n * `setInterval`, the durable timer poller, or `@nestjs/schedule`. Returns the run ids for the\n * current windows.\n */\nexport async function runSchedules(\n engine: Pick<WorkflowEngine, 'start' | 'getRun'>,\n schedules: readonly ScheduledWorkflow[],\n nowMs: number,\n opts?: RunSchedulesOptions,\n): Promise<string[]> {\n const random = opts?.random ?? Math.random;\n const sleep = opts?.sleep ?? defaultSleep;\n const ids: string[] = [];\n for (const s of schedules) {\n if (s.paused) continue;\n // overlap:'skip' (fixed-interval): don't start this window while the previous window's run is\n // still in-flight, so a slow run can't pile up. Interval-only — cron windows aren't adjacent ids.\n if (s.overlap === 'skip' && s.everyMs) {\n const prevBucket = Math.floor(nowMs / s.everyMs) - 1;\n if (prevBucket >= 0) {\n const prev = await engine.getRun(`sched:${s.key}:${prevBucket}`);\n if (prev && (prev.status === 'running' || prev.status === 'suspended')) continue;\n }\n }\n // Dispatch-path jitter (not workflow code): spread same-boundary ticks across instances. Applied\n // once per schedule, before firing — the run ids below are unaffected, so idempotency holds.\n if (s.jitter && s.jitter > 0) await sleep(Math.floor(random() * s.jitter));\n for (const runId of scheduleRunIdsAt(s, nowMs)) {\n await engine.start(s.workflow, s.input, runId);\n ids.push(runId);\n }\n }\n return ids;\n}\n","import type { AttributeFilter, AttributeOp, RunQuery, WorkflowRun } from './interfaces';\nimport type { SearchAttributes } from './interfaces';\n\n/** Compare one attribute value against a filter operand. Range ops need both sides comparable. */\nfunction compare(actual: unknown, op: AttributeOp, expected: string | number | boolean): boolean {\n switch (op) {\n case 'eq':\n return actual === expected;\n case 'ne':\n return actual !== expected;\n case 'gt':\n return actual != null && actual > expected;\n case 'gte':\n return actual != null && actual >= expected;\n case 'lt':\n return actual != null && actual < expected;\n case 'lte':\n return actual != null && actual <= expected;\n }\n}\n\n/**\n * Does a run's search attributes satisfy EVERY filter (AND)? A missing key never matches (so `ne`\n * on an absent key is false too — the attribute simply isn't there to compare). Empty/undefined\n * filters match everything. Shared by every store so typed/range queries behave identically across\n * adapters (applied in-process after the coarse workflow/status/tag filters).\n */\nexport function matchesAttributes(\n attributes: SearchAttributes | undefined,\n filters: AttributeFilter[] | undefined,\n): boolean {\n if (!filters?.length) return true;\n if (!attributes) return false;\n return filters.every((f) => f.key in attributes && compare(attributes[f.key], f.op, f.value));\n}\n\n/**\n * Apply a query's attribute predicates then its `offset`/`limit`, in-process — for store adapters\n * that can't express typed/range predicates in SQL. Pass rows already coarse-filtered (workflow /\n * status / tag) and sorted newest-first; this filters by `attributes` and paginates. Only call it\n * when `query.attributes` is set (otherwise let the DB do `LIMIT`/`OFFSET`).\n */\nexport function applyAttributeQuery(rows: WorkflowRun[], query: RunQuery): WorkflowRun[] {\n const filtered = rows.filter((r) => matchesAttributes(r.searchAttributes, query.attributes));\n const offset = query.offset ?? 0;\n const limit = query.limit ?? filtered.length;\n return filtered.slice(offset, offset + limit);\n}\n\n/**\n * One normalized row of the `durable_run_attributes` side-table: a single (key → value) pair of a\n * run's search attributes, split into typed columns so SQL can index/range-scan it. Exactly one of\n * `strValue`/`numValue` is set per row (booleans normalize to a string `\"true\"`/`\"false\"` so `eq`/`ne`\n * still match). NULL for the column that doesn't apply, which keeps `(key, numValue)` /\n * `(key, strValue)` indexes selective.\n */\nexport interface RunAttributeRow {\n runId: string;\n key: string;\n strValue: string | null;\n numValue: number | null;\n}\n\n/**\n * Explode a run's search attributes into normalized side-table rows (one per key). Used by SQL stores\n * to maintain `durable_run_attributes` on every create/update and by the in-memory store's index, so\n * attribute predicates can be pushed DOWN into a join/EXISTS instead of scanned in-process. Numbers go\n * to `numValue`; strings to `strValue`; booleans to `strValue` as `\"true\"`/`\"false\"` (matching how the\n * in-process `compare` treats `eq`/`ne` on booleans). Returns `[]` for a run with no attributes.\n */\nexport function normalizeAttributeRows(\n runId: string,\n attributes: SearchAttributes | undefined,\n): RunAttributeRow[] {\n if (!attributes) return [];\n const out: RunAttributeRow[] = [];\n for (const [key, value] of Object.entries(attributes)) {\n if (typeof value === 'number') {\n out.push({ runId, key, strValue: null, numValue: value });\n } else if (typeof value === 'boolean') {\n out.push({ runId, key, strValue: value ? 'true' : 'false', numValue: null });\n } else {\n out.push({ runId, key, strValue: value, numValue: null });\n }\n }\n return out;\n}\n\n/** SQL comparison operator for an {@link AttributeOp} (used to build pushdown predicates). */\nexport function sqlComparator(op: AttributeOp): string {\n switch (op) {\n case 'eq':\n return '=';\n case 'ne':\n return '<>';\n case 'gt':\n return '>';\n case 'gte':\n return '>=';\n case 'lt':\n return '<';\n case 'lte':\n return '<=';\n }\n}\n\n/**\n * Which side-table column an attribute filter compares against: numeric operands (and range ops on\n * numbers) hit `numValue`; everything else hits `strValue` (booleans are stored as `\"true\"`/`\"false\"`).\n * Keeping this in core means every SQL adapter pushes predicates down identically.\n */\nexport function attributeColumnFor(filter: AttributeFilter): 'numValue' | 'strValue' {\n return typeof filter.value === 'number' ? 'numValue' : 'strValue';\n}\n\n/** The literal a side-table predicate compares against (booleans → `\"true\"`/`\"false\"` strings). */\nexport function attributeOperand(filter: AttributeFilter): string | number {\n if (typeof filter.value === 'boolean') return filter.value ? 'true' : 'false';\n return filter.value;\n}\n","import type { InferSearchAttributes, SearchAttributes, SearchAttributesSchema } from './interfaces';\n\n/**\n * Read a run's `searchAttributes` through a {@link SearchAttributesSchema}, typed to the schema's\n * inferred output. **Safe-parse semantics, deliberately lenient** — unlike\n * `ctx.upsertSearchAttributes` (which is strict: an invalid merge throws), a failed validation here\n * returns `{}` rather than throwing. This is intentional: `run.searchAttributes` may predate the\n * schema (an older deploy wrote it under a looser or absent schema, or a run started before this\n * workflow ever declared one), and a dashboard/read path crashing on old history is worse than it\n * quietly reporting no typed attributes for that run. Write-time enforcement is what keeps NEW writes\n * conformant; this is the read-side counterpart for consuming them.\n *\n * The schema's `validate` must be synchronous (matching the write-side constraint in\n * `ctx.upsertSearchAttributes`) — one returning a `Promise` throws with a clear error rather than\n * being silently awaited or silently treated as a failure.\n *\n * @example\n * ```ts\n * import { z } from 'zod';\n * import { readSearchAttributes } from '@dudousxd/nestjs-durable-core';\n *\n * const orderAttrs = z.object({ tier: z.enum(['free', 'pro']), amount: z.number() });\n *\n * const run = await store.getRun(runId);\n * const attrs = readSearchAttributes(orderAttrs, run ?? {}); // { tier: 'pro', amount: 42 } | {}\n * ```\n */\nexport function readSearchAttributes<S extends SearchAttributesSchema>(\n schema: S,\n // `| null` because ORM store entities (MikroORM/TypeORM/Prisma) type the JSON column as\n // nullable — the entity row is the argument every real consumer passes.\n run: { searchAttributes?: SearchAttributes | null | undefined },\n): InferSearchAttributes<S> {\n const result = schema['~standard'].validate(run.searchAttributes ?? {});\n if (result instanceof Promise) {\n throw new Error(\n \"readSearchAttributes: schema validation must be synchronous (the searchAttributes schema's \" +\n '`~standard.validate` returned a Promise) — async Standard Schema validators are not supported.',\n );\n }\n if (result.issues) {\n // Lenient by design (see doc comment) — old/foreign runs shouldn't crash a read path. The `{}`\n // is cast, not `Partial<InferSearchAttributes<S>>`, to keep the common case (destructuring known\n // keys straight off the result) ergonomic; callers reading untrusted history should still treat\n // every field as possibly absent.\n return {} as InferSearchAttributes<S>;\n }\n return result.value as InferSearchAttributes<S>;\n}\n","/**\n * Dependency-injection tokens. Adapters bind their implementations to these so `core` and\n * `@dudousxd/nestjs-durable` depend only on the interfaces in `./interfaces`.\n *\n * These use `Symbol.for(key)` (the global symbol registry), NOT `Symbol(key)`, so the token is the\n * SAME instance no matter how many times `core` is evaluated in a process. A consumer can hold more\n * than one physical copy of `core` at runtime — pnpm peer-dependency multiplexing installs a\n * separate virtual copy per distinct peer set, and the dual ESM/CJS build can be loaded once as\n * `import` (`index.js`) and once as `require` (`index.cjs`). A plain `Symbol()` would mint a\n * DISTINCT token per copy, so `DurableModule` (provider) and `DashboardService` / a store adapter\n * (injector) could resolve different symbols → Nest can't satisfy the dependency\n * (`STATE_STORE is not available in the DurableApiModule context`). A registered symbol collapses\n * them to one. Mirrors the `CONTEXT_ACCESSOR` token in `@dudousxd/nestjs-durable`'s `tokens.ts`.\n */\n\n/**\n * @deprecated Use {@link STATE_STORE_CANONICAL} (`@dudousxd/nestjs-durable:state-store`). The legacy\n * token stays bound as a back-compat alias and still resolves; it will be removed in a future major.\n */\nexport const STATE_STORE = Symbol.for('nestjs-durable:STATE_STORE');\n/**\n * @deprecated Use {@link TRANSPORT_CANONICAL} (`@dudousxd/nestjs-durable:transport`). The legacy\n * token stays bound as a back-compat alias and still resolves; it will be removed in a future major.\n */\nexport const TRANSPORT = Symbol.for('nestjs-durable:TRANSPORT');\n/**\n * @deprecated Use {@link DURABLE_OPTIONS_CANONICAL} (`@dudousxd/nestjs-durable:options`). The legacy\n * token stays bound as a back-compat alias and still resolves; it will be removed in a future major.\n */\nexport const DURABLE_OPTIONS = Symbol.for('nestjs-durable:DURABLE_OPTIONS');\n\n/**\n * Canonical, cross-lib-discoverable aliases of the durable DI tokens, following the ecosystem\n * capability naming `@dudousxd/nestjs-durable:<name>` (identical to `capability('durable', <name>)`).\n * `DurableModule` binds these alongside the legacy tokens (dual-bind), so an external library can\n * resolve durable's store/transport/options by the canonical name without importing durable\n * internals. Bare `Symbol.for` (same cross-copy-stability rationale as the legacy tokens above)\n * keeps `core` free of any `@dudousxd/nestjs-diagnostics` runtime dependency.\n */\nexport const STATE_STORE_CANONICAL = Symbol.for('@dudousxd/nestjs-durable:state-store');\nexport const TRANSPORT_CANONICAL = Symbol.for('@dudousxd/nestjs-durable:transport');\nexport const DURABLE_OPTIONS_CANONICAL = Symbol.for('@dudousxd/nestjs-durable:options');\n","import type {\n RunQuery,\n SignalWaiter,\n StateStore,\n StepCheckpoint,\n WorkflowRun,\n} from '../interfaces';\nimport type { AttributeFilter } from '../interfaces';\nimport { type RunAttributeRow, normalizeAttributeRows } from '../search-attributes';\n\n/**\n * A non-durable, in-process `StateStore` for tests and local development.\n * The shipped `@dudousxd/nestjs-durable-store` package re-exports an equivalent.\n */\nexport class InMemoryStateStore implements StateStore {\n private readonly runs = new Map<string, WorkflowRun>();\n private readonly checkpoints = new Map<string, StepCheckpoint>();\n private readonly signalWaiters = new Map<string, SignalWaiter>();\n\n /**\n * Normalized search-attribute side-table, the in-memory analog of the SQL stores'\n * `durable_run_attributes`: `key -> (runId -> row)`. Maintained on every create/update so an\n * attribute query can be pushed DOWN to a key-indexed candidate set instead of scanning every run\n * and comparing in-process. Mirrors {@link normalizeAttributeRows} so behavior matches the SQL path.\n */\n private readonly attributeIndex = new Map<string, Map<string, RunAttributeRow>>();\n /** Test/observability hook: how many candidate runs the last attribute query's index produced. */\n lastAttributeCandidates = 0;\n /**\n * Test/observability hook: how many checkpoint rows the LAST checkpoint read materialized (the rows\n * actually returned to the caller). `listCheckpoints` returns all rows for the run; the targeted\n * {@link getLatestCheckpointByName} / {@link listCheckpointsByNamePrefix} return only the matches —\n * so this lets the benchmark contrast \"fetch N, scan in JS\" against \"fetch the k that match\".\n */\n lastCheckpointRowsRead = 0;\n\n private key(runId: string, seq: number): string {\n return `${runId}:${seq}`;\n }\n\n /** Drop then re-add a run's normalized attribute rows so the index tracks its current attributes. */\n private reindexAttributes(runId: string, attributes: WorkflowRun['searchAttributes']): void {\n for (const byRun of this.attributeIndex.values()) byRun.delete(runId);\n for (const row of normalizeAttributeRows(runId, attributes)) {\n let byRun = this.attributeIndex.get(row.key);\n if (!byRun) {\n byRun = new Map();\n this.attributeIndex.set(row.key, byRun);\n }\n byRun.set(runId, row);\n }\n }\n\n async createRun(run: WorkflowRun): Promise<void> {\n // Normalize undefined namespace to 'default', matching the SQL stores' column DEFAULT 'default'\n // (interfaces.ts: \"the store persists it as 'default'\"). This ensures legacy runs (created without\n // a namespace, e.g. in tests that bypass the engine) are reachable via a namespace='default' filter.\n this.runs.set(run.id, { ...run, namespace: run.namespace ?? 'default' });\n this.reindexAttributes(run.id, run.searchAttributes);\n }\n\n async updateRun(runId: string, patch: Partial<WorkflowRun>): Promise<void> {\n const existing = this.runs.get(runId);\n if (!existing) throw new Error(`run ${runId} not found`);\n const next = { ...existing, ...patch };\n this.runs.set(runId, next);\n if ('searchAttributes' in patch) this.reindexAttributes(runId, next.searchAttributes);\n }\n\n async getRun(runId: string): Promise<WorkflowRun | null> {\n const run = this.runs.get(runId);\n return run ? { ...run } : null;\n }\n\n async deleteRun(runId: string): Promise<void> {\n this.runs.delete(runId);\n for (const [key, cp] of this.checkpoints) {\n if (cp.runId === runId) this.checkpoints.delete(key);\n }\n for (const [token, waiter] of this.signalWaiters) {\n if (waiter.runId === runId) this.signalWaiters.delete(token);\n }\n // Drop the run's normalized attribute rows (reindex with no attributes clears them).\n this.reindexAttributes(runId, undefined);\n }\n\n async getCheckpoint(runId: string, seq: number): Promise<StepCheckpoint | null> {\n const cp = this.checkpoints.get(this.key(runId, seq));\n return cp ? { ...cp } : null;\n }\n\n async saveCheckpoint(checkpoint: StepCheckpoint): Promise<void> {\n this.checkpoints.set(this.key(checkpoint.runId, checkpoint.seq), { ...checkpoint });\n }\n\n async listIncompleteRuns(namespace?: string): Promise<WorkflowRun[]> {\n return [...this.runs.values()]\n .filter(\n (r) =>\n (r.status === 'running' || r.status === 'cancelling') &&\n (namespace === undefined || r.namespace === namespace),\n )\n .map((r) => ({ ...r }));\n }\n\n async listPendingRuns(limit: number, namespace?: string): Promise<WorkflowRun[]> {\n return [...this.runs.values()]\n .filter(\n (r) => r.status === 'pending' && (namespace === undefined || r.namespace === namespace),\n )\n .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id))\n .slice(0, limit)\n .map((r) => ({ ...r }));\n }\n\n async listDueTimers(nowMs: number, namespace?: string): Promise<WorkflowRun[]> {\n return [...this.runs.values()]\n .filter(\n (r) =>\n r.status === 'suspended' &&\n r.wakeAt !== undefined &&\n r.wakeAt <= nowMs &&\n (namespace === undefined || r.namespace === namespace),\n )\n .map((r) => ({ ...r }));\n }\n\n async tryLockRun(\n runId: string,\n owner: string,\n leaseUntilMs: number,\n nowMs: number,\n ): Promise<boolean> {\n const run = this.runs.get(runId);\n if (!run) return false;\n if (run.lockedUntil !== undefined && run.lockedUntil > nowMs) return false;\n run.lockedBy = owner;\n run.lockedUntil = leaseUntilMs;\n return true;\n }\n\n async releaseRunLock(runId: string): Promise<void> {\n const run = this.runs.get(runId);\n if (run) {\n run.lockedBy = undefined;\n run.lockedUntil = undefined;\n }\n }\n\n async renewRunLock(runId: string, owner: string, leaseUntilMs: number): Promise<boolean> {\n const run = this.runs.get(runId);\n if (!run || run.lockedBy !== owner) return false;\n run.lockedUntil = leaseUntilMs;\n return true;\n }\n\n async putSignalWaiter(waiter: SignalWaiter): Promise<void> {\n this.signalWaiters.set(waiter.token, { ...waiter });\n }\n\n async takeSignalWaiter(token: string): Promise<SignalWaiter | null> {\n const waiter = this.signalWaiters.get(token);\n if (!waiter) return null;\n this.signalWaiters.delete(token);\n return { ...waiter };\n }\n\n async listSignalWaiters(prefix: string): Promise<SignalWaiter[]> {\n return [...this.signalWaiters.values()]\n .filter((w) => w.token.startsWith(prefix))\n .map((w) => ({ ...w }));\n }\n\n async removeSignalWaiter(waiter: SignalWaiter): Promise<void> {\n // Keyed by token only (one row per token) — only delete if the CURRENT row still matches this\n // exact (runId, seq); a later putSignalWaiter for the same token may have already replaced it\n // with a different run's row, which must be left alone.\n const current = this.signalWaiters.get(waiter.token);\n if (current && current.runId === waiter.runId && current.seq === waiter.seq) {\n this.signalWaiters.delete(waiter.token);\n }\n }\n\n // No real DB transaction (there's no DB) — run the work and save the checkpoint. Exactly-once\n // across a crash needs a SQL store; this keeps `ctx.transaction` usable in tests / local dev.\n async transaction<T>(\n work: (tx: {\n raw: unknown;\n saveCheckpoint: (cp: StepCheckpoint) => Promise<void>;\n }) => Promise<T>,\n ): Promise<T> {\n return work({ raw: this, saveCheckpoint: (cp) => this.saveCheckpoint(cp) });\n }\n\n private readonly bufferedSignals = new Map<string, unknown[]>();\n async bufferSignal(token: string, payload: unknown): Promise<void> {\n const queue = this.bufferedSignals.get(token) ?? [];\n queue.push(payload);\n this.bufferedSignals.set(token, queue);\n }\n async takeBufferedSignal(token: string): Promise<{ payload: unknown } | null> {\n const queue = this.bufferedSignals.get(token);\n if (!queue || queue.length === 0) return null;\n const payload = queue.shift();\n if (queue.length === 0) this.bufferedSignals.delete(token);\n return { payload };\n }\n\n /** `id -> row`, so {@link removeBufferedEvent} can delete an exact row regardless of iteration\n * order — mirrors the SQL stores' PK-by-id delete. */\n private readonly bufferedEvents = new Map<\n string,\n { name: string; payload: unknown; publishedAt: number }\n >();\n async bufferEvent(input: {\n name: string;\n payload: unknown;\n id: string;\n publishedAt: number;\n }): Promise<void> {\n this.bufferedEvents.set(input.id, {\n name: input.name,\n payload: input.payload,\n publishedAt: input.publishedAt,\n });\n }\n async listBufferedEvents(\n name: string,\n limit: number,\n ): Promise<Array<{ id: string; payload: unknown; publishedAt: number }>> {\n return [...this.bufferedEvents.entries()]\n .filter(([, e]) => e.name === name)\n .sort((a, b) => a[1].publishedAt - b[1].publishedAt) // oldest first\n .slice(0, limit)\n .map(([id, e]) => ({ id, payload: e.payload, publishedAt: e.publishedAt }));\n }\n async removeBufferedEvent(id: string): Promise<boolean> {\n return this.bufferedEvents.delete(id);\n }\n\n /**\n * Candidate run ids satisfying ONE attribute predicate, served from {@link attributeIndex} — the\n * pushdown step. Numeric predicates scan only `numValue` rows under the key; string/boolean ones\n * scan `strValue` rows. This is the in-memory analog of the SQL EXISTS on `durable_run_attributes`.\n */\n private candidatesForFilter(f: AttributeFilter): Set<string> {\n const byRun = this.attributeIndex.get(f.key);\n const out = new Set<string>();\n if (!byRun) return out;\n const numeric = typeof f.value === 'number';\n const operand = typeof f.value === 'boolean' ? (f.value ? 'true' : 'false') : f.value;\n for (const row of byRun.values()) {\n const actual = numeric ? row.numValue : row.strValue;\n if (actual == null) continue;\n let ok = false;\n switch (f.op) {\n case 'eq':\n ok = actual === operand;\n break;\n case 'ne':\n ok = actual !== operand;\n break;\n case 'gt':\n ok = actual > operand;\n break;\n case 'gte':\n ok = actual >= operand;\n break;\n case 'lt':\n ok = actual < operand;\n break;\n case 'lte':\n ok = actual <= operand;\n break;\n }\n if (ok) out.add(row.runId);\n }\n return out;\n }\n\n async listRuns(query: RunQuery): Promise<WorkflowRun[]> {\n let runs = [...this.runs.values()];\n if (query.workflow) runs = runs.filter((r) => r.workflow === query.workflow);\n if (query.status) runs = runs.filter((r) => r.status === query.status);\n if (query.statuses) runs = runs.filter((r) => query.statuses?.includes(r.status));\n if (query.tag) runs = runs.filter((r) => r.tags?.includes(query.tag as string));\n if (query.namespace !== undefined) runs = runs.filter((r) => r.namespace === query.namespace);\n if (query.attributes?.length) {\n // Pushdown: intersect per-predicate candidate sets from the key-indexed side-table, so we only\n // ever materialize the runs that already satisfy EVERY attribute filter (no full per-run scan).\n let candidates: Set<string> | null = null;\n for (const f of query.attributes) {\n const next = this.candidatesForFilter(f);\n if (candidates == null) {\n candidates = next;\n } else {\n const prev: Set<string> = candidates;\n candidates = new Set([...prev].filter((id) => next.has(id)));\n }\n if (candidates.size === 0) break;\n }\n const ids = candidates ?? new Set<string>();\n this.lastAttributeCandidates = ids.size;\n runs = runs.filter((r) => ids.has(r.id));\n }\n // Newest first (matches the store adapters' `createdAt DESC`) — recent runs on top in the dashboard.\n runs.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());\n const offset = query.offset ?? 0;\n const limit = query.limit ?? runs.length;\n return runs.slice(offset, offset + limit).map((r) => ({ ...r }));\n }\n\n async listCheckpoints(runId: string): Promise<StepCheckpoint[]> {\n const rows = [...this.checkpoints.values()]\n .filter((cp) => cp.runId === runId)\n .sort((a, b) => a.seq - b.seq)\n .map((cp) => ({ ...cp }));\n this.lastCheckpointRowsRead = rows.length;\n return rows;\n }\n\n async getLatestCheckpointByName(\n runId: string,\n name: string,\n ): Promise<StepCheckpoint | undefined> {\n let latest: StepCheckpoint | undefined;\n for (const cp of this.checkpoints.values()) {\n if (cp.runId !== runId || cp.name !== name) continue;\n if (!latest || cp.seq > latest.seq) latest = cp;\n }\n this.lastCheckpointRowsRead = latest ? 1 : 0;\n return latest ? { ...latest } : undefined;\n }\n\n async listCheckpointsByNamePrefix(runId: string, prefixes: string[]): Promise<StepCheckpoint[]> {\n const rows = [...this.checkpoints.values()]\n .filter((cp) => cp.runId === runId && prefixes.some((p) => cp.name.startsWith(p)))\n .sort((a, b) => a.seq - b.seq)\n .map((cp) => ({ ...cp }));\n this.lastCheckpointRowsRead = rows.length;\n return rows;\n }\n}\n","import type {\n ControlMessage,\n ControlPlane,\n Heartbeat,\n RemoteTask,\n StepResult,\n Transport,\n WorkflowStepEvent,\n} from '../interfaces';\nimport { type StepHandler, runStepHandler } from '../protocol';\n\n/**\n * An in-process `Transport` (and `ControlPlane`) for tests and local development: registered\n * handlers stand in for remote workers, so a whole cross-app workflow runs in a single process,\n * and control messages broadcast locally. Pass the same instance as both `transport` and\n * `controlPlane`.\n */\nexport class InMemoryTransport implements Transport, ControlPlane {\n private readonly handlers = new Map<string, StepHandler>();\n private resultHandler?: (result: StepResult) => Promise<void>;\n private heartbeatHandler?: (beat: Heartbeat) => Promise<void>;\n private stepEventHandler?: (event: WorkflowStepEvent) => Promise<void>;\n private readonly controlHandlers = new Set<(msg: ControlMessage) => void>();\n\n /** Register a fake worker handler for a step name. */\n handle(name: string, fn: StepHandler): void {\n this.handlers.set(name, fn);\n }\n\n async dispatch(task: RemoteTask): Promise<void> {\n if (!this.resultHandler) throw new Error('no result handler registered');\n const result = await runStepHandler(task, this.handlers.get(task.name));\n // Deliver the result ASYNCHRONOUSLY, not inline: a durable `ctx.call` suspends the run right\n // after dispatch, so the result must land AFTER that unwinds (else the resume re-enters\n // mid-suspend). Real brokers are async; this mirrors them.\n setImmediate(() => void this.resultHandler?.(result));\n }\n\n onResult(handler: (result: StepResult) => Promise<void>): void {\n this.resultHandler = handler;\n }\n\n onHeartbeat(handler: (beat: Heartbeat) => Promise<void>): void {\n // In-process step handlers run synchronously (no step liveness to track), but a test can drive a\n // RUN-scoped beat via `emitHeartbeat` to exercise the engine's heartbeat-rearmed advance deadline.\n this.heartbeatHandler = handler;\n }\n\n /** Test hook: deliver a liveness heartbeat to the engine, as a real broker would on its channel. */\n async emitHeartbeat(beat: Heartbeat): Promise<void> {\n await this.heartbeatHandler?.(beat);\n }\n\n /** Workflow step lifecycle: deliver to the engine's handler (async, mirroring a real broker). */\n async dispatchStepEvent(event: WorkflowStepEvent): Promise<void> {\n await this.stepEventHandler?.(event);\n }\n\n onStepEvent(handler: (event: WorkflowStepEvent) => Promise<void>): void {\n this.stepEventHandler = handler;\n }\n\n // Control plane: broadcast to every registered handler (including the publisher's own — the\n // engine dedupes by `from`), mirroring how a real broker echoes a publish to all subscribers.\n async publishControl(msg: ControlMessage): Promise<void> {\n for (const handler of this.controlHandlers) handler(msg);\n }\n\n onControl(handler: (msg: ControlMessage) => void): void {\n this.controlHandlers.add(handler);\n }\n}\n"],"mappings":";;;;AAyEO,IAAMA,kBAAN,MAAMA;EAzEb,OAyEaA;;;;;EACHC,WAAW;EACXC,cAAc;EACdC,cAAc;;EAELC,UAAU,oBAAIC,IAAAA;;EAEvBC,YAAY;;EAEHC,YAAY,oBAAIF,IAAAA;EACzBG,aAAa;EAErB,YACWC,QACQC,OACjB;SAFSD,SAAAA;SACQC,QAAAA;EAChB;;EAGH,IAAYC,UAAmB;AAC7B,WAAO,KAAKF,OAAOG,aAAa,SAAS,KAAKH,OAAOI,UAAU;EACjE;;;;;;;;;EAUAC,SAASC,MAAiC;AACxC,UAAMC,MAAM,KAAKN,MAAK;AACtB,UAAMO,KAAK,KAAKR,OAAOS;AAEvB,QAAID,IAAI;AACN,UAAID,MAAM,KAAKd,eAAee,GAAGE,UAAU;AACzC,aAAKjB,cAAcc;AACnB,aAAKb,cAAc;MACrB;AACA,UAAI,KAAKA,eAAec,GAAGG,MACzB,QAAO;QAAEC,IAAI;QAAOC,SAAS,KAAKpB,cAAce,GAAGE;MAAS;IAChE;AAEA,UAAMI,aAAa,KAAKZ,WAAWI,MAAMS,YAAY,QAAQT,MAAMU,YAAY;AAC/E,UAAMA,WAAWV,MAAMU;AAGvB,UAAMC,OAAO,KAAKjB,OAAOkB,eAAe,QAAQ,KAAK1B,YAAY,KAAKQ,OAAOkB;AAC7E,QAAID,MAAM;AAER,UAAIH,cAAcE,YAAY,KAAM,MAAKG,SAASH,UAAUV,IAAAA;AAC5D,aAAO;QAAEM,IAAI;QAAOC,SAASN,OAAO,KAAKP,OAAOoB,WAAW;MAAM;IACnE;AAKA,QAAIN,cAAc,KAAKnB,QAAQ0B,OAAO,GAAG;AACvC,UAAIL,YAAY,KAAM,MAAKG,SAASH,UAAUV,IAAAA;AAC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,MAAcC,IAAuB;AAC1C,SAAKT,SAASU,IAAIF,MAAMC,EAAAA;EAC1B;EAEA,MAAME,SAASC,MAAiC;AAC9C,QAAI,CAAC,KAAKV,cAAe,OAAM,IAAIW,MAAM,8BAAA;AACzC,UAAMC,SAAS,MAAMC,eAAeH,MAAM,KAAKZ,SAASgB,IAAIJ,KAAKJ,IAAI,CAAA;AAIrES,iBAAa,MAAM,KAAK,KAAKf,gBAAgBY,MAAAA,CAAAA;EAC/C;EAEAI,SAASC,SAAsD;AAC7D,SAAKjB,gBAAgBiB;EACvB;EAEAC,YAAYD,SAAmD;AAG7D,SAAKhB,mBAAmBgB;EAC1B;;EAGA,MAAME,cAAcC,MAAgC;AAClD,UAAM,KAAKnB,mBAAmBmB,IAAAA;EAChC;;EAGA,MAAMC,kBAAkBC,OAAyC;AAC/D,UAAM,KAAKpB,mBAAmBoB,KAAAA;EAChC;EAEAC,YAAYN,SAA4D;AACtE,SAAKf,mBAAmBe;EAC1B;;;EAIA,MAAMO,eAAeC,KAAoC;AACvD,eAAWR,WAAW,KAAKd,gBAAiBc,SAAQQ,GAAAA;EACtD;EAEAC,UAAUT,SAA8C;AACtD,SAAKd,gBAAgBwB,IAAIV,OAAAA;EAC3B;AACF;","names":["QueueController","inFlight","windowStart","windowCount","waiters","Map","waiterSeq","keyServed","servedTick","config","clock","ordered","fairness","order","tryAdmit","item","now","rl","rateLimit","periodMs","limit","ok","retryAt","usingOrder","priority","waiterId","full","concurrency","register","retryMs","size","isNext","delete","key","set","release","existing","get","seq","self","undefined","Number","POSITIVE_INFINITY","best","w","values","better","a","b","sa","servedOf","sb","InMemoryAdmissionBackend","controllers","Map","clock","register","config","set","name","QueueController","handles","queue","has","tryAdmit","item","controller","get","ok","release","_slotId","AsyncLocalStorage","STORAGE_KEY","Symbol","for","globalRef","globalThis","AsyncLocalStorage","storage","runInWorkflowCtx","ctx","fn","run","currentWorkflowCtx","getStore","CONTROL_FLOW_SIGNAL","Symbol","for","isWorkflowControlFlowSignal","error","FatalError","Error","code","message","name","SingletonQueueFullError","workflow","key","maxQueueDepth","SignalTimeoutError","token","timeoutMs","RemoteStepTimeout","stepId","RemoteWorkflowTimeout","taskId","NonDeterminismError","runId","seq","expected","recorded","GatherError","failures","total","ids","map","f","id","join","denom","length","WorkflowSuspended","wakeAt","CONTROL_FLOW_SIGNAL","ContinueAsNew","input","WORKFLOW_NAME_KEY","Symbol","for","workflowName","ref","name","Error","BINDINGS_KEY","Symbol","for","globalRef","globalThis","WeakMap","bindings","bindWorkflowClass","ctor","client","set","clientOf","get","Error","workflowName","DurableWorkflow","start","input","opts","cls","ctx","currentWorkflowCtx","runId","startChild","id","status","crypto","randomUUID","execute","child","waitForRun","FatalError","settled","timeoutMs","until","output","detail","error","message","code","UNIT_MS","ms","s","sec","second","seconds","m","min","minute","minutes","h","hr","hour","hours","d","day","days","w","week","weeks","parseDuration","duration","match","trim","Error","value","Number","unit","toLowerCase","factor","undefined","backoffDelay","attempt","options","base","backoffMs","raw","backoff","capped","backoffMaxMs","Math","min","jitter","round","random","withDuration","start","now","data","base","durationMs","createStepLogger","events","currentSub","push","level","message","at","subId","id","undefined","subEvent","e","status","phase","name","group","subProcess","body","opts","globalThis","crypto","randomUUID","prevSub","terminal","emit","handle","skip","reason","fail","result","err","Error","String","debug","m","d","info","warn","error","sub","stepId","runId","seq","breakpointToken","runStepHandler","task","handler","base","startedAt","Date","now","status","error","message","name","retryable","events","withEvents","result","length","output","input","createStepLogger","err","e","Error","String","code","nonEmptyEvents","events","length","undefined","stepCheckpoint","p","runId","seq","name","kind","stepId","status","input","output","error","attempts","workerGroup","wakeAt","parallelGroup","enqueuedAt","startedAt","finishedAt","instantCheckpoint","at","Date","ENTITY_WORKFLOW","entityRunId","name","key","Entities","configs","Map","host","register","ctx","input","run","config","set","dispatch","op","arg","reply","runId","signalWithStart","token","payload","signal","getState","getEvent","get","FatalError","state","initialState","i","msg","waitForSignal","out","localStep","handler","handlers","result","setEvent","accToken","target","EventAccumulators","host","register","ctx","input","debounce","batch","route","config","payload","workflow","mode","windowMs","maxSize","signalWithStart","token","last","waitForSignal","timeoutMs","e","SignalTimeoutError","startChild","continueAsNew","events","deadline","now","length","remaining","push","enc","s","Buffer","from","toString","dec","EVENT_BUFFER_SCAN_LIMIT","EVENT_TOKEN_PREFIX","eventPrefix","name","isEventToken","token","startsWith","eventToken","match","runId","seq","JSON","stringify","eventNameOf","split","eventMatchOf","parse","eventMatches","payload","keys","Object","length","p","every","k","tenantGroup","baseGroup","tenant","undefined","sanitizeQueueToken","name","replace","RemoteWorkflowExecutor","transport","name","partition","_opts","dispatch","run","history","taskId","pendingSignals","dispatchWorkflowTask","Error","task","runId","id","workflow","workflowVersion","input","group","tenantGroup","sanitizeQueueToken","priority","attempt","WEBHOOK_PREFIX","CHILD_PREFIX","BREAKPOINT_PREFIX","EVENT_PREFIX","EVENT_TOKEN_PREFIX","classifyWaiterToken","token","startsWith","on","name","slice","length","eventNameOf","resolveRunWaiting","run","waiterByRun","status","undefined","waiter","get","id","indexWaitersByRun","waiters","byRun","Map","w","has","runId","set","SINGLETON_RETRY_MS","SINGLETON_RETRY_JITTER_MS","SingletonGate","deps","tag","cfg","input","key","retryWakeAt","clock","Math","floor","random","assertCapacity","workflow","maxQueueDepth","cap","limit","queued","store","listRuns","statuses","length","SingletonQueueFullError","admit","run","inflight","sort","a","b","createdAt","getTime","id","localeCompare","idx","findIndex","r","wakeNext","settled","configFor","tags","find","t","startsWith","gated","next","slice","wakeAt","updateRun","undefined","updatedAt","Date","catch","dispatch","TransportPool","transports","size","length","primary","first","Error","transport","bind","onResult","onHeartbeat","onStepEvent","onDecision","dispatch","task","preferId","lastErr","id","ordered","err","groupHealth","group","reports","push","undefined","depth","reduce","sum","r","liveWorkers","flatMap","onStartRun","handler","listWorkerGroups","groups","Set","g","add","transportWithLiveGroup","includes","pref","filter","t","unwrapCompletion","payload","label","c","ok","FatalError","error","value","DURABLE_STEP_NAME","Symbol","for","DURABLE_STEP_CONFIG","isStepConfig","value","stepNameOf","ref","undefined","stamped","stepConfigOf","normalizeChildOptions","options","childId","formatIssuePath","path","length","map","segment","String","key","join","resolveStepPolicy","config","opts","policy","retries","undefined","backoff","backoffMs","backoffMaxMs","jitter","timeoutMs","Position","seq","next","rewind","createWorkflowCtx","host","runId","compensations","workflow","searchAttributesSchema","store","replay","pos","readCheckpoint","hit","get","getCheckpoint","writeCheckpoint","cp","saveCheckpoint","set","localStep","name","fn","current","existing","NonDeterminismError","status","compensate","push","output","maxAttempts","Math","max","startedAt","Date","startStep","kind","attempts","enqueuedAt","attempt","events","invocation","stepName","body","createStepLogger","clock","interceptStep","completeStep","err","FatalError","failStep","error","message","Error","stack","wait","backoffDelay","Promise","resolve","setTimeout","transaction","tx","raw","instantCheckpoint","suspendUntil","wakeAt","now","WorkflowSuspended","at","sleep","duration","parseDuration","sleepUntil","when","getTime","continueAsNew","input","ContinueAsNew","consumeBuffered","token","buffered","takeBufferedSignal","payload","value","consumeBufferedEvent","match","candidates","listBufferedEvents","EVENT_BUFFER_SCAN_LIMIT","candidate","eventMatches","removeBufferedEvent","id","removeSignalWaiter","stampDeadline","deadlineSeq","label","recorded","deadline","waitForSignal","putSignalWaiter","lateBuffered","waitSeq","waited","catch","SignalTimeoutError","waitForEvent","eventToken","bufferedHit","task","dispatch","unwrapCompletion","child","priority","getRun","startChild","workflowName","all","inputs","mode","positions","group","i","c","ok","j","cancelChild","GatherError","index","pending","parallelGroup","outputs","failures","callEntity","op","arg","reply","signalEntity","breakpoint","breakpointToken","patched","marker","startsWith","onUpdate","setEvent","webhook","takeSignalWaiter","url","webhookUrl","sideEffect","upsertSearchAttributes","attrs","run","merged","searchAttributes","result","validate","issues","offendingKeys","Set","issue","details","resolveCompensateDef","stepNameOf","stepConfigOf","step","handlerOrName","def","callRemote","queue","transport","fairnessKey","then","args","mergeTags","staticTags","runTags","length","undefined","Set","BREAKPOINT","isBreakpoint","cp","status","name","startsWith","versionKey","version","nextContinuationId","runId","m","match","Number","isNewerVersion","a","b","na","nb","isNaN","localeCompare","numeric","NamespaceMismatch","Error","WorkflowEngine","store","pool","controlPlane","clock","instanceId","namespace","leaseMs","maxRecoveryAttempts","remoteAdvanceSilenceMs","reconcileMs","eventBufferTtlMs","remoteRedispatchMs","remoteRedispatchMax","webhookUrl","traceparent","context","rehydrate","compensationRetries","trackStepStart","runDispatcher","singletons","workflows","Map","latest","eventTriggers","entities","accumulators","pending","heartbeatResets","listeners","interceptors","cancelListeners","enqueuedListeners","deadListeners","updateValidators","cancelRequested","admission","queueWaiters","stepQueue","inflight","draining","deps","TransportPool","transports","transport","id","Date","now","InMemoryAdmissionBackend","onFreed","queue","wakeQueueWaiters","globalThis","crypto","randomUUID","Math","max","_carrier","fn","dispatch","queueMicrotask","runOne","catch","SingletonGate","configFor","run","get","workflow","workflowVersion","singleton","bind","result","waiter","stepId","delete","resolve","output","startedAt","events","reject","RemoteStepError","error","completeRemoteResult","beat","reset","rearmDecisionDeadline","event","persistStepEvent","decision","completeRemoteDecision","onStartRun","message","start","input","tenant","tags","searchAttributes","onControl","msg","from","kind","deliver","at","notifyCancelled","EventAccumulators","Entities","registerEntity","config","register","signalEntity","key","op","arg","signal","getEntityState","getState","onEnqueued","listener","add","opts","group","executor","registered","executionTimeoutMs","executionTimeout","parseDuration","validateInput","searchAttributesSchema","onEvent","eventBatch","hasBody","remote","set","current","subscribers","workflowBody","reg","registerRemote","rest","RemoteWorkflowExecutor","primary","registerQueue","subscribe","use","interceptor","push","i","indexOf","splice","interceptStep","invocation","body","carrier","chain","reduceRight","next","onCancel","onDead","notifyDead","emit","full","publishControl","workflowName","ancestor","findRemoteAncestor","synthesizeRemoteChild","conventionRun","createdAt","updatedAt","resolveRemoteByConvention","prior","getRun","tag","assertCapacity","priority","createRun","resume","releaseRunLock","findInheritedRegistration","track","execute","tenantGroup","sanitizeQueueToken","liveTransport","transportWithLiveGroup","childRunId","visited","has","parentRunId","findParentRunId","parent","parentReg","token","listSignalWaiters","p","finally","drain","timeoutMs","size","timer","Promise","t","setTimeout","unref","race","allSettled","sweepTimeouts","values","deadline","listRuns","getTime","code","updateRun","type","recoverIncomplete","nowMs","results","listIncompleteRuns","acquired","tryLockRun","settled","countRecovery","attempts","recoveryAttempts","resumeDueTimers","due","listDueTimers","waiterByRun","indexWaitersByRun","resumeLeased","reconcileSignalWaiter","isEventToken","reconcileBufferedEvent","buffered","takeBufferedSignal","removeSignalWaiter","deliverSignal","payload","eventNameOf","eventMatchOf","candidates","listBufferedEvents","EVENT_BUFFER_SCAN_LIMIT","candidate","publishedAt","removeBufferedEvent","eventMatches","err","requeue","isFailureCompletion","v","ok","listCheckpoints","saveCheckpoint","wakeAt","retryable","redispatchPending","filter","redispatched","reAttempt","reEnqueuedAt","enqueuedAt","finishedAt","dispatchRemoteTask","seq","workerGroup","attempt","retryWithInput","newRunId","slice","runPending","listPendingRuns","waitForRun","TERMINAL","isSettled","until","awaitingDecisionTaskId","toResult","done","off","poller","clearInterval","finish","clearTimeout","check","then","interval","setInterval","ev","runs","onLocked","publishEvent","touched","waiters","eventPrefix","w","eventId","batch","route","buffer","bufferedId","bufferEvent","lateWaiters","lateWaiter","find","takeSignalWaiter","instantCheckpoint","parallelGroup","bufferSignal","reclaimed","signalWithStart","completeTask","value","failTask","notifyParent","completion","startChildDeferred","childId","String","cancel","compensate","cancelChildren","wakeNext","cancelWhere","r","deleteRun","deleted","getRunChildren","childIds","prefixes","childCheckpoints","listCheckpointsByNamePrefix","some","knownGroups","extra","groups","def","workerHealth","listWorkerGroups","workflowTokens","out","health","groupHealth","lastIndexOf","baseToken","phase","stepCheckpoint","failed","startStep","step","completeStep","queueMs","durationMs","failStep","lockNow","lockedBy","lockedUntil","renew","renewRunLock","floor","runRemoteExecution","runExecution","settleRun","outcome","reconcileWakeAt","admit","retryWakeAt","history","remoteHistory","taskId","silenceMs","advanceExecutor","advance","call","awaitWithLivenessDeadline","RemoteWorkflowTimeout","stack","applyDecision","applyCommands","commands","fresh","checkpoints","kindOf","local","sleep","sort","cmd","getCheckpoint","ms","min","deliverBuffered","putSignalWaiter","lateBuffered","compensateAndCancel","compensations","replay","unwindCompensations","snapshot","ctx","createWorkflowCtx","ctxHostFor","runInWorkflowCtx","ContinueAsNew","nextId","WorkflowSuspended","comp","existing","runCompensation","dispatchCompensation","args","maxAttempts","retries","backoffDelay","withWakeAt","dispatchCompensationAttempt","partition","parentNamespace","s","callRemote","startChild","cancelChild","upsertSearchAttributes","attrs","reply","continue","bp","breakpointToken","getEvent","getLatestCheckpointByName","registerUpdateValidator","validate","update","accepted","reason","NonDeterminismError","callRemoteInMemory","nextDeadline","handles","tryAdmit","fairnessKey","waiterId","retryAt","task","releaseQueueSlot","runIds","clear","release","validInput","parse","resultPromise","resolution","awaitWithHeartbeat","RemoteStepTimeout","onTimeout","cleanup","arm","stepError","TERMINAL_RUN_STATUSES","CodecStateStore","inner","codec","enc","v","undefined","encode","dec","decode","encRun","run","input","output","decRun","encCp","cp","decCp","ensureSchema","Promise","resolve","createRun","updateRun","runId","patch","next","getRun","deleteRun","getCheckpoint","seq","saveCheckpoint","checkpoint","transaction","work","Error","tx","raw","listIncompleteRuns","namespace","map","r","listPendingRuns","limit","listDueTimers","nowMs","tryLockRun","owner","leaseUntilMs","releaseRunLock","renewRunLock","putSignalWaiter","waiter","takeSignalWaiter","token","listSignalWaiters","prefix","removeSignalWaiter","bufferSignal","payload","takeBufferedSignal","buffered","bufferEvent","listBufferedEvents","name","events","e","removeBufferedEvent","id","listRuns","query","listCheckpoints","c","getLatestCheckpointByName","latest","listCheckpointsByNamePrefix","prefixes","matches","filter","some","p","startsWith","collectMetrics","engine","m","runs","started","completed","failed","suspended","steps","byWorkflow","stepDuration","sumMs","count","wf","name","k","entry","stop","subscribe","e","type","workflow","durationMs","snapshot","structuredClone","prometheus","lines","push","v","Object","entries","event","n","join","createRequire","nodeRequire","createRequire","url","defaultSleep","ms","Promise","r","setTimeout","scheduledRunId","key","everyMs","nowMs","Math","floor","cronParser","loadCronParser","Error","prevCronFireMs","expr","timezone","parser","it","parseExpression","currentDate","Date","tz","prev","toDate","getTime","scheduleRunIdAt","s","cron","scheduleRunIdsAt","current","backfill","maxCatchup","ids","bucket","oldest","max","b","push","prior","cursor","i","before","reverse","runSchedules","engine","schedules","opts","random","sleep","paused","overlap","prevBucket","getRun","status","jitter","runId","start","workflow","input","compare","actual","op","expected","matchesAttributes","attributes","filters","length","every","f","key","value","applyAttributeQuery","rows","query","filtered","filter","r","searchAttributes","offset","limit","slice","normalizeAttributeRows","runId","out","Object","entries","push","strValue","numValue","sqlComparator","attributeColumnFor","attributeOperand","readSearchAttributes","schema","run","result","validate","searchAttributes","Promise","Error","issues","value","STATE_STORE","Symbol","for","TRANSPORT","DURABLE_OPTIONS","STATE_STORE_CANONICAL","TRANSPORT_CANONICAL","DURABLE_OPTIONS_CANONICAL","InMemoryStateStore","runs","Map","checkpoints","signalWaiters","attributeIndex","lastAttributeCandidates","lastCheckpointRowsRead","key","runId","seq","reindexAttributes","attributes","byRun","values","delete","row","normalizeAttributeRows","get","set","createRun","run","id","namespace","searchAttributes","updateRun","patch","existing","Error","next","getRun","deleteRun","cp","token","waiter","undefined","getCheckpoint","saveCheckpoint","checkpoint","listIncompleteRuns","filter","r","status","map","listPendingRuns","limit","sort","a","b","createdAt","getTime","localeCompare","slice","listDueTimers","nowMs","wakeAt","tryLockRun","owner","leaseUntilMs","lockedUntil","lockedBy","releaseRunLock","renewRunLock","putSignalWaiter","takeSignalWaiter","listSignalWaiters","prefix","w","startsWith","removeSignalWaiter","current","transaction","work","raw","bufferedSignals","bufferSignal","payload","queue","push","takeBufferedSignal","length","shift","bufferedEvents","bufferEvent","input","name","publishedAt","listBufferedEvents","entries","e","removeBufferedEvent","candidatesForFilter","f","out","Set","numeric","value","operand","actual","numValue","strValue","ok","op","add","listRuns","query","workflow","statuses","includes","tag","tags","candidates","prev","has","size","ids","offset","listCheckpoints","rows","getLatestCheckpointByName","latest","listCheckpointsByNamePrefix","prefixes","some","p","InMemoryTransport","handlers","Map","resultHandler","heartbeatHandler","stepEventHandler","controlHandlers","Set","handle","name","fn","set","dispatch","task","Error","result","runStepHandler","get","setImmediate","onResult","handler","onHeartbeat","emitHeartbeat","beat","dispatchStepEvent","event","onStepEvent","publishControl","msg","onControl","add"]}