@dudousxd/nestjs-durable-core 0.86.2 → 0.87.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.d.ts CHANGED
@@ -205,6 +205,13 @@ interface WorkflowRegistration {
205
205
  code?: string;
206
206
  workflow: string;
207
207
  }[];
208
+ /**
209
+ * The `onEvent` event names this workflow subscribes to, lifecycle events (`run.completed:<wf>`,
210
+ * `run.failed:<wf>`) included. An engine settling a run reads them so it owes the run's lifecycle
211
+ * event to a subscriber that only another worker has. Absent = not stated, which subscribes to
212
+ * nothing.
213
+ */
214
+ subscribes?: string[];
208
215
  }
209
216
  /**
210
217
  * A worker's (or control-plane's) advertised identity, wire-protocol support, feature capabilities
@@ -484,6 +491,303 @@ declare class WorkflowBlocked extends Error {
484
491
  */
485
492
  declare function planDispatch(requires: string[], liveDescriptors: readonly (RawWorkerDescriptor | WorkerDescriptor)[], cp: WorkerDescriptor, token: string): DispatchPlan;
486
493
 
494
+ /**
495
+ * A **workflow reference** is how one workflow names another to call it: either a registered workflow
496
+ * **name** (a string — the only option across runtimes, e.g. a Python workflow) or, for a same-runtime
497
+ * TypeScript workflow, its **class**. The class carries the input/output types through the call, so
498
+ * `ctx.child(ShippingWorkflow, input)` type-checks the input and returns a typed result — while a
499
+ * string stays available for the cross-runtime case.
500
+ */
501
+ /**
502
+ * The symbol the `@Workflow` decorator stamps a workflow's registered name onto, so a class ref can
503
+ * be resolved back to its name. A global-registry symbol (`Symbol.for`) so it survives duplicate
504
+ * copies of this package in a dependency tree.
505
+ */
506
+ declare const WORKFLOW_NAME_KEY: unique symbol;
507
+ /** Structural shape of a `@Workflow` class — its `run(ctx, input)` carries the input/output types. */
508
+ type WorkflowClass<TInput = unknown, TOutput = unknown> = abstract new (...args: never[]) => {
509
+ run(ctx: never, input: TInput): Promise<TOutput> | TOutput;
510
+ };
511
+ /** A workflow reference: a registered name (cross-runtime) or a workflow class (typed, same-runtime). */
512
+ type WorkflowRef<TInput = unknown, TOutput = unknown> = string | WorkflowClass<TInput, TOutput>;
513
+ /** The input type a workflow class's `run` accepts. */
514
+ type WorkflowInputOf<C> = C extends abstract new (...args: never[]) => {
515
+ run(ctx: never, input: infer I): unknown;
516
+ } ? I : unknown;
517
+ /** The output type a workflow class's `run` resolves to (Promise unwrapped). */
518
+ type WorkflowOutputOf<C> = C extends abstract new (...args: never[]) => {
519
+ run(ctx: never, input: never): infer R;
520
+ } ? Awaited<R> : unknown;
521
+ /**
522
+ * Resolve a {@link WorkflowRef} to its registered workflow name: a string is returned as-is; a
523
+ * `@Workflow` class is resolved via the name the decorator stamped on it. Throws if a class was
524
+ * never decorated (so it carries no registered name).
525
+ */
526
+ declare function workflowName(ref: WorkflowRef): string;
527
+
528
+ /**
529
+ * Lifecycle events: when a run settles, the engine publishes `run.completed:<workflow>` or
530
+ * `run.failed:<workflow>` on the same bus as `publishEvent`, so another workflow can start on it
531
+ * through `onEvent` (or `@OnWorkflowCompleted` / `@OnWorkflowFailed` in `@dudousxd/nestjs-durable`)
532
+ * without the settling workflow knowing it exists.
533
+ *
534
+ * Delivery is exactly once per subscriber and settled run. The terminal status write also tags the
535
+ * run {@link LIFECYCLE_PENDING_TAG} plus one {@link LIFECYCLE_OWED_TAG_PREFIX} tag per subscriber
536
+ * the event is owed to: the ones registered on the settling process and the ones live workers
537
+ * announce. A process that dies before publishing, or that does not have a subscriber, leaves the
538
+ * marker for the timer poller's lifecycle sweep on any instance that does; the subscriber's run id
539
+ * is deterministic ({@link lifecycleRunId}), so publishing twice starts it once.
540
+ *
541
+ * When the settling process has no usable read of the fleet's announcements (none yet, or the last
542
+ * one failed), the terminal write tags the run {@link LIFECYCLE_PENDING_TAG} alone: the owed set is
543
+ * unresolved, and the first publish with a good read resolves it. A subscriber announced after the
544
+ * run settled is caught by the sweep's heal pass for {@link LIFECYCLE_HEAL_WINDOW_MS}; later than
545
+ * that, `engine.republishLifecycle` backfills it.
546
+ */
547
+ /** The event published when a run of `workflow` completes. */
548
+ declare function runCompletedEvent(workflow: WorkflowRef): string;
549
+ /** The event published when a run of `workflow` ends failed, cancelled or dead. */
550
+ declare function runFailedEvent(workflow: WorkflowRef): string;
551
+ /**
552
+ * Tag written with a run's terminal status when some workflow subscribes to its lifecycle event,
553
+ * and removed once the event is published. A settled run still carrying it was never published.
554
+ * Carried with no {@link LIFECYCLE_OWED_TAG_PREFIX} tag, it means the owed set is unresolved: the
555
+ * settling process could not read the fleet's announcements, so the run is owed to every subscriber
556
+ * the first publish with a good read finds (minus the ones already started or failed).
557
+ */
558
+ declare const LIFECYCLE_PENDING_TAG = "durable:lifecycle:pending";
559
+ /**
560
+ * Whether a run's `tags` (an array, or the JSON text a raw SQL select returns) still carry
561
+ * {@link LIFECYCLE_PENDING_TAG}. Retention never prunes such a run: its lifecycle event is owed.
562
+ */
563
+ declare function carriesLifecyclePending(tags: unknown): boolean;
564
+ /** Prefix of the tags naming the subscribers a settled run started (`durable:triggered:<workflow>`). */
565
+ declare const LIFECYCLE_TRIGGERED_TAG_PREFIX = "durable:triggered:";
566
+ /**
567
+ * Prefix of the tags naming each subscriber a settled run's lifecycle event is still owed to
568
+ * (`durable:lifecycle:owed:<workflow>`). Written with {@link LIFECYCLE_PENDING_TAG} and removed one
569
+ * by one as the instances holding each subscriber publish to it; the pending tag goes with the last.
570
+ */
571
+ declare const LIFECYCLE_OWED_TAG_PREFIX = "durable:lifecycle:owed:";
572
+ /**
573
+ * How long after a run settled an owed subscriber that no live worker announces and the sweeping
574
+ * instance does not have is kept. Past it the sweep drops the owed tag and reports
575
+ * `run.trigger_failed`, so a removed subscriber cannot keep a run from being pruned forever.
576
+ */
577
+ declare const LIFECYCLE_ORPHAN_MS: number;
578
+ /**
579
+ * Prefix of the tags naming each subscriber whose start from a settled run's lifecycle event failed
580
+ * (`durable:trigger_failed:<workflow>`): its `where` threw, its input was rejected, its start threw,
581
+ * or the sweep dropped it as orphaned (see {@link LIFECYCLE_ORPHAN_MS}). Written in the same update
582
+ * that drops its owed tag, and removed by the update that records it started. The failure message
583
+ * is not stored; the `run.trigger_failed` event carries it.
584
+ */
585
+ declare const LIFECYCLE_TRIGGER_FAILED_TAG_PREFIX = "durable:trigger_failed:";
586
+ /** The subscribers whose start from a run's lifecycle event failed, read from its failed tags. */
587
+ declare function triggerFailedSubscribersOf(tags: readonly string[] | undefined): string[];
588
+ /** The subscribers a settled run started, read from its {@link LIFECYCLE_TRIGGERED_TAG_PREFIX} tags. */
589
+ declare function triggeredSubscribersOf(tags: readonly string[] | undefined): string[];
590
+ /**
591
+ * Prefix of the tags naming each subscriber a settled run's lifecycle event was routed into a
592
+ * debounce/batch accumulator for (`durable:coalesced:<workflow>`). Such a subscriber starts no run
593
+ * of the source's id, so this tag is what records the delivery: written in the same update that drops
594
+ * its owed tag, it keeps a heal or a republish from routing the event again.
595
+ */
596
+ declare const LIFECYCLE_COALESCED_TAG_PREFIX = "durable:coalesced:";
597
+ /** The subscribers a settled run's event was coalesced into, read from its coalesced tags. */
598
+ declare function coalescedSubscribersOf(tags: readonly string[] | undefined): string[];
599
+ /**
600
+ * How long after a run settled the lifecycle sweep still checks it for subscribers it missed: one
601
+ * the fleet announced only after the settling process last read the announcements. Such a
602
+ * subscriber is started (or owed to the instances that have it) as if it had been owed from the
603
+ * start. One announced later than this is backfill, for `engine.republishLifecycle`.
604
+ */
605
+ declare const LIFECYCLE_HEAL_WINDOW_MS: number;
606
+ /** The subscribers a run's lifecycle event is still owed to, read from its owed tags. */
607
+ declare function owedSubscribersOf(tags: readonly string[] | undefined): string[];
608
+ /**
609
+ * Prefix of the tag holding the W3C `traceparent` of a run's root span
610
+ * (`durable:lifecycle:trace:<traceparent>`). Written with the run's first suspend, or with the
611
+ * lifecycle marker when it settles without suspending, when some workflow subscribes to the run's
612
+ * ending and the engine has a run trace provider (see `WorkflowEngine.setRunTraceparent`), so a
613
+ * subscriber's trace can link to its source run from any process.
614
+ */
615
+ declare const LIFECYCLE_TRACE_TAG_PREFIX = "durable:lifecycle:trace:";
616
+ /** The traceparent a settled run recorded in its {@link LIFECYCLE_TRACE_TAG_PREFIX} tag, if any. */
617
+ declare function lifecycleTraceparentOf(tags: readonly string[] | undefined): string | undefined;
618
+ /** Whether `tag` is one the engine writes for lifecycle bookkeeping rather than one the run was given. */
619
+ declare function isLifecycleTag(tag: string): boolean;
620
+ /** The payload of a lifecycle event, read from the store after the run settled. */
621
+ interface WorkflowLifecycleEvent<TInput = unknown, TOutput = unknown> {
622
+ runId: string;
623
+ workflow: string;
624
+ workflowVersion: string;
625
+ /** `completed` on `run.completed:*`; `failed`, `cancelled` or `dead` on `run.failed:*`. */
626
+ status: RunStatus;
627
+ namespace?: string | undefined;
628
+ input: TInput;
629
+ /** Present on a completed run. */
630
+ output?: TOutput | undefined;
631
+ /** Present on a run that did not complete. */
632
+ error?: StepError | undefined;
633
+ tags?: string[] | undefined;
634
+ searchAttributes?: SearchAttributes | undefined;
635
+ }
636
+ /** The lifecycle event a run of workflow class `C` publishes, typed by its input and output. */
637
+ type LifecycleEventOf<C> = WorkflowLifecycleEvent<WorkflowInputOf<C>, WorkflowOutputOf<C>>;
638
+ /** Which lifecycle event a settled run publishes: `completed`, or `failed` for any other ending. */
639
+ type LifecycleKind = 'completed' | 'failed';
640
+ /**
641
+ * The id of the run a lifecycle event starts for `subscriber`. Deterministic, so the same settled
642
+ * run never starts the same subscriber twice, and either side of the link can be found from the other.
643
+ */
644
+ declare function lifecycleRunId(sourceRunId: string, kind: LifecycleKind, subscriber: string): string;
645
+ /** The lifecycle event a run in `status` published, or undefined while it has not settled. */
646
+ declare function lifecycleKindOf(status: RunStatus | undefined): LifecycleKind | undefined;
647
+ /** The event name a run of `workflow` publishes when it settles as `kind`. */
648
+ declare function lifecycleEventName(workflow: string, kind: LifecycleKind): string;
649
+ /** The workflow and ending a lifecycle event name stands for, or undefined for any other event. */
650
+ declare function parseLifecycleEvent(event: string): {
651
+ workflow: string;
652
+ kind: LifecycleKind;
653
+ } | undefined;
654
+ /**
655
+ * One workflow that starts when another settles, as the dashboard's workflow page lists it. `local`
656
+ * is what the answering instance has registered, with what its subscription does to the payload;
657
+ * an entry only live workers announce (a Python subscriber, or a TypeScript one served elsewhere)
658
+ * states none of that, since the announcement carries only the event name.
659
+ */
660
+ interface LifecycleSubscriptionLink {
661
+ /** The other end: the subscriber on `startsOnSettle`, the settling workflow on `startedBy`. */
662
+ workflow: string;
663
+ kind: LifecycleKind;
664
+ /** Registered on the answering instance (true) or only announced by live workers (false). */
665
+ local: boolean;
666
+ /** Announced by at least one live worker. */
667
+ announced: boolean;
668
+ /** The subscription filters payloads with `where`. */
669
+ where: boolean;
670
+ /** The subscription maps the payload to the run's input with `input`. */
671
+ input: boolean;
672
+ /** The subscriber coalesces events: debounced or batched, and whether per `key`. */
673
+ coalesce?: {
674
+ mode: 'debounce' | 'batch';
675
+ keyed: boolean;
676
+ } | undefined;
677
+ }
678
+ /**
679
+ * Who starts whom through lifecycle events, for one workflow: the subscribers of its
680
+ * `run.completed:<workflow>` / `run.failed:<workflow>` events, and the workflows whose settling
681
+ * starts it. Built from the answering instance's registry and the subscriptions live workers
682
+ * announce.
683
+ */
684
+ interface WorkflowLifecycleLinks {
685
+ workflow: string;
686
+ /** Workflows that start when this one settles, sorted by workflow then kind. */
687
+ startsOnSettle: LifecycleSubscriptionLink[];
688
+ /** Workflows whose settling starts this one, sorted by workflow then kind. */
689
+ startedBy: LifecycleSubscriptionLink[];
690
+ }
691
+ /**
692
+ * The run whose settling started `run`, when a lifecycle event started it. Read from the run's id,
693
+ * which ends in `:<kind>:<its own workflow>`, so it holds whatever input the subscriber was given.
694
+ */
695
+ declare function lifecycleSourceOf(run: {
696
+ id: string;
697
+ workflow: string;
698
+ }): {
699
+ runId: string;
700
+ kind: LifecycleKind;
701
+ } | undefined;
702
+ /**
703
+ * The runs `run`'s settling started, read from its {@link LIFECYCLE_TRIGGERED_TAG_PREFIX} tags.
704
+ * Empty for a run that has not settled or started nobody. Needs no subscriber registry, so any
705
+ * process holding the run row can answer it.
706
+ */
707
+ declare function triggeredRunsOf(run: Pick<WorkflowRun, 'id' | 'status' | 'tags'>): string[];
708
+ /** The {@link WorkflowLifecycleEvent} a settled run publishes. */
709
+ declare function lifecycleEventOf(run: WorkflowRun): WorkflowLifecycleEvent;
710
+ /**
711
+ * Which settled runs `engine.republishLifecycle` publishes again: one run, or the settled runs of a
712
+ * workflow (`kind` narrows to completed or to every other ending; `since`/`until` bound when they
713
+ * settled; `limit` caps how many runs are read, default 1000; `namespace` reads one namespace only,
714
+ * the engine's own when unset). `subscriber` restricts it to one subscribing workflow.
715
+ */
716
+ type RepublishLifecycleTarget = {
717
+ runId: string;
718
+ subscriber?: string | undefined;
719
+ } | {
720
+ workflow: string;
721
+ kind?: LifecycleKind | undefined;
722
+ since?: Date | undefined;
723
+ until?: Date | undefined;
724
+ subscriber?: string | undefined;
725
+ limit?: number | undefined;
726
+ namespace?: string | undefined;
727
+ };
728
+ /** What `engine.republishLifecycle` did: runs published, subscriber runs started, and the failures. */
729
+ interface RepublishLifecycleResult {
730
+ runs: number;
731
+ started: number;
732
+ failed: {
733
+ runId: string;
734
+ subscriber: string;
735
+ error: string;
736
+ }[];
737
+ }
738
+ /**
739
+ * The internal workflow whose runs make up the lifecycle subscription registry: one completed run
740
+ * per engine instance that has `onEvent` subscriptions, id {@link lifecycleRegistryRunId}, its
741
+ * subscriptions in `input` ({@link LifecycleRegistryEntry}) and its `updatedAt` the heartbeat. Kept
742
+ * in the state store, so an instance learns what the others subscribe to over any transport.
743
+ */
744
+ declare const LIFECYCLE_REGISTRY_WORKFLOW = "__lifecycle_registry";
745
+ /** Tag every registry run carries. Retention never prunes a run that has it. */
746
+ declare const LIFECYCLE_REGISTRY_TAG = "durable:lifecycle:registry";
747
+ /** How often an engine refreshes its registry run (from the timer poller's lifecycle sweep). */
748
+ declare const LIFECYCLE_REGISTRY_HEARTBEAT_MS = 10000;
749
+ /** How long after its last heartbeat a registry run still counts as a live instance's. */
750
+ declare const LIFECYCLE_REGISTRY_TTL_MS = 35000;
751
+ /** How long after its last heartbeat a registry run is deleted, by any engine's sweep. */
752
+ declare const LIFECYCLE_REGISTRY_STALE_MS: number;
753
+ /** The id of the registry run of engine instance `instanceId`. */
754
+ declare function lifecycleRegistryRunId(instanceId: string): string;
755
+ /** What a registry run holds in `input`: the `onEvent` subscriptions of one engine instance. */
756
+ interface LifecycleRegistryEntry {
757
+ instanceId: string;
758
+ runtime: 'node';
759
+ /**
760
+ * The engine's namespace, or `null` for an engine with no namespace. Recorded because both write
761
+ * the registry run under `default`. An engine with no namespace sweeps and starts its subscribers
762
+ * for the runs of every namespace, so its subscriptions are owed by settled runs of any namespace;
763
+ * an engine with one, only by its own.
764
+ */
765
+ engineNamespace: string | null;
766
+ /** Each subscribing workflow with the event names it starts on, lifecycle ones included. */
767
+ subscriptions: {
768
+ workflow: string;
769
+ events: string[];
770
+ }[];
771
+ }
772
+ /**
773
+ * The namespace whose settled runs owe their lifecycle events to the subscriptions of a registry
774
+ * run, or `null` for every namespace: the entry's `engineNamespace`, or for a row written without it,
775
+ * the row's `namespace`, read as every namespace when that is `default` (an engine with no namespace
776
+ * wrote it, as far as the row can tell).
777
+ */
778
+ declare function lifecycleRegistryNamespace(input: unknown, rowNamespace: string | undefined): string | null;
779
+ /** The subscriptions a registry run's `input` holds; malformed entries are skipped. */
780
+ declare function lifecycleRegistrySubscriptions(input: unknown): {
781
+ workflow: string;
782
+ events: string[];
783
+ }[];
784
+ /**
785
+ * Whether retention must keep a run with these `tags` (an array, or the JSON text a raw SQL select
786
+ * returns): its lifecycle event is still owed ({@link carriesLifecyclePending}), or it is a
787
+ * lifecycle registry run ({@link LIFECYCLE_REGISTRY_TAG}).
788
+ */
789
+ declare function retentionKeeps(tags: unknown): boolean;
790
+
487
791
  /**
488
792
  * A parallel fan (a `ctx.all`, a step fan, a polyglot `gather`) reduced to what a detail view needs
489
793
  * to draw it: one node, its progress and its failures. A run detail with a 40,000-item fan otherwise
@@ -562,6 +866,69 @@ declare function fanPageBounds(query: FanPageQuery): {
562
866
  limit: number;
563
867
  };
564
868
 
869
+ /**
870
+ * One end of a `ctx.waitForRun` wait, as a run detail lists it: the run waited for (`waitsFor`) or
871
+ * the waiting run (`awaitedBy`), the waiting run's `seq` of the call, and the other run's status and
872
+ * namespace when it was read.
873
+ */
874
+ interface RunWaitLink {
875
+ runId: string;
876
+ seq: number;
877
+ status?: RunStatus | undefined;
878
+ namespace?: string | undefined;
879
+ }
880
+ /**
881
+ * Where a settled run's lifecycle event stands for one subscriber:
882
+ * - `started`: its run exists (`runId`, a `durable:triggered:<subscriber>` tag);
883
+ * - `owed`: still pending (a `durable:lifecycle:owed:<subscriber>` tag);
884
+ * - `coalesced`: routed into a debounce/batch accumulator (a `durable:coalesced:<subscriber>` tag,
885
+ * or the caller's `coalesced` map; `runId` is the accumulator's, when it can be derived);
886
+ * - `failed`: its start failed (a `durable:trigger_failed:<subscriber>` tag): its `where` threw, its
887
+ * input was rejected, its start threw, or the sweep dropped it as orphaned. A republish retries it;
888
+ * - `not-started`: no run and nothing owed: its `where` declined the event, or it subscribed after
889
+ * the run settled.
890
+ */
891
+ type LifecycleDeliveryState = 'started' | 'owed' | 'coalesced' | 'failed' | 'not-started';
892
+ /** One subscriber of a settled run's lifecycle event, as the run detail lists it. */
893
+ interface LifecycleDelivery {
894
+ subscriber: string;
895
+ state: LifecycleDeliveryState;
896
+ /** The subscriber's run when `started`; the accumulator run when `coalesced` and derivable. */
897
+ runId?: string | undefined;
898
+ /** The status of a `started` subscriber's run, when it was read. */
899
+ status?: RunStatus | undefined;
900
+ /** The namespace of a `started` subscriber's run, when it was read. */
901
+ namespace?: string | undefined;
902
+ /** When an `owed` subscriber became owed: the settled run's last update (epoch ms). */
903
+ owedSince?: number | undefined;
904
+ /**
905
+ * When the lifecycle sweep drops an `owed` subscriber that no live instance registers or
906
+ * announces for the run's namespace (epoch ms; see {@link LIFECYCLE_ORPHAN_MS}). Absent while one
907
+ * does.
908
+ */
909
+ orphanAt?: number | undefined;
910
+ /**
911
+ * Why a `failed` subscriber did not start, when the caller knows it (the run's tags record only
912
+ * that it failed; the `run.trigger_failed` event carries the message). {@link lifecycleDeliveriesOf}
913
+ * leaves it unset.
914
+ */
915
+ error?: string | undefined;
916
+ }
917
+ /**
918
+ * The {@link LifecycleDelivery} of each subscriber of a settled run, sorted by subscriber: the
919
+ * union of `subscribers` (the ones the run's event goes to now) and the owed, triggered, coalesced
920
+ * and trigger-failed tags. `live` names the subscribers a live instance registers or announces; an owed subscriber
921
+ * outside it gets `orphanAt`. `coalesced` maps each subscriber that coalesces its events to its
922
+ * accumulator run id (undefined when it cannot be derived). Empty for a run that has not settled.
923
+ */
924
+ declare function lifecycleDeliveriesOf(run: Pick<WorkflowRun, 'id' | 'status' | 'tags' | 'updatedAt'>, opts: {
925
+ subscribers: readonly string[];
926
+ live: ReadonlySet<string>;
927
+ coalesced?: ReadonlyMap<string, string | undefined> | undefined;
928
+ }): LifecycleDelivery[];
929
+ /** The trace id of a W3C `traceparent` (`00-<trace id>-<span id>-<flags>`), or undefined. */
930
+ declare function traceIdOfTraceparent(traceparent: string | undefined): string | undefined;
931
+
565
932
  /** A run as returned by the gateway's list — the durable run plus an optional {@link RunWaiting}
566
933
  * descriptor the control plane resolves (what a suspended run is parked on), so the dashboard can
567
934
  * name the wait in a list row without fetching each run's timeline. Additive: `waiting` is absent
@@ -577,6 +944,15 @@ interface DurableTopology {
577
944
  /** The tenant's isolation partition name; set only when `role` is 'tenant'. */
578
945
  tenant?: string;
579
946
  }
947
+ /** The run whose settling started a run, as its detail names it. */
948
+ interface LifecycleSource {
949
+ runId: string;
950
+ kind: 'completed' | 'failed';
951
+ status?: RunStatus | undefined;
952
+ namespace?: string | undefined;
953
+ /** The W3C trace id of the source run's span, when it recorded one. */
954
+ traceId?: string | undefined;
955
+ }
580
956
  /** A run + its timeline + child ids — the detail view. Single source of truth: the dashboard server
581
957
  * re-exports this instead of re-declaring it, and the dashboard client derives its wire mirror from
582
958
  * it via {@link WireDates} instead of hand-mirroring field by field. */
@@ -593,6 +969,38 @@ interface RunDetail {
593
969
  fans?: FanSummary[] | undefined;
594
970
  /** How many children the run has, when `children` lists only the first of them. */
595
971
  childCount?: number | undefined;
972
+ /**
973
+ * Runs started by this run settling: subscribers of its `run.completed:<workflow>` or
974
+ * `run.failed:<workflow>` event. Not children: they are not cancelled with it or awaited by it.
975
+ */
976
+ triggered?: string[] | undefined;
977
+ /**
978
+ * The run whose settling started this one, when a lifecycle event started it, with the source
979
+ * run's `status` and `namespace`, and the trace id of its span (`traceId`) when the source
980
+ * recorded one (see `LIFECYCLE_TRACE_TAG_PREFIX`).
981
+ */
982
+ triggeredBy?: LifecycleSource | undefined;
983
+ /**
984
+ * The workflows subscribed to this settled run's lifecycle event, registered on the answering
985
+ * instance or announced by the live fleet. Present only when there is at least one, which is
986
+ * when the run's lifecycle event can be republished.
987
+ */
988
+ lifecycleSubscribers?: string[] | undefined;
989
+ /**
990
+ * Who starts whom through lifecycle events, for this run's workflow (see
991
+ * `WorkflowEngine.workflowLifecycle`). Present only when the workflow starts or is started by some
992
+ * other workflow.
993
+ */
994
+ workflowLifecycle?: WorkflowLifecycleLinks | undefined;
995
+ /**
996
+ * Where a settled run's lifecycle event stands for each subscriber: started, owed, coalesced or
997
+ * not started. Absent when the run has not settled or has no subscribers.
998
+ */
999
+ lifecycleDeliveries?: LifecycleDelivery[] | undefined;
1000
+ /** The runs a suspended run waits for through `ctx.waitForRun`. */
1001
+ waitsFor?: RunWaitLink[] | undefined;
1002
+ /** The runs waiting for this one through `ctx.waitForRun`. */
1003
+ awaitedBy?: RunWaitLink[] | undefined;
596
1004
  /**
597
1005
  * A validator for this detail, when the gateway can compute one without reading the timeline:
598
1006
  * it changes whenever the run or any of its checkpoints does. Absent when it cannot.
@@ -704,6 +1112,26 @@ declare abstract class RunGateway {
704
1112
  abstract retryWithInput(runId: string, input: unknown): Promise<{
705
1113
  runId: string;
706
1114
  } | null>;
1115
+ /**
1116
+ * Publish settled runs' lifecycle events again (see `WorkflowEngine.republishLifecycle`). Optional:
1117
+ * only a gateway backed by the canonical store and an engine implements it.
1118
+ */
1119
+ republishLifecycle?(target: RepublishLifecycleTarget): Promise<RepublishLifecycleResult>;
1120
+ /**
1121
+ * Who starts whom through lifecycle events, for one workflow (see
1122
+ * `WorkflowEngine.workflowLifecycle`), only the subscriptions of `opts.namespace` when given.
1123
+ * Optional: a gateway backed by an engine, or a tenant proxy (scoped to its tenant by the
1124
+ * operator), implements it.
1125
+ */
1126
+ workflowLifecycle?(workflow: string, opts?: {
1127
+ namespace?: string | undefined;
1128
+ }): Promise<WorkflowLifecycleLinks>;
1129
+ /**
1130
+ * The subscribers a run of `workflow` in `namespace` settling as `kind` owes its lifecycle event to
1131
+ * (see `WorkflowEngine.lifecycleSubscribers`). Optional: a gateway backed by an engine implements
1132
+ * it; the run-request responder checks a tenant republish's `subscriber` against it.
1133
+ */
1134
+ lifecycleSubscribers?(workflow: string, kind: LifecycleKind, namespace: string): Promise<string[]>;
707
1135
  /** Live lifecycle events for one run; returns an unsubscribe fn. Framework-agnostic (no rxjs). */
708
1136
  abstract subscribe(runId: string, onEvent: (event: EngineEvent) => void): () => void;
709
1137
  }
@@ -843,40 +1271,6 @@ declare function stepNameOf(ref: unknown): string | undefined;
843
1271
  * it via {@link StepDispatchOpts} instead). */
844
1272
  declare function stepConfigOf(ref: unknown): StepConfig | undefined;
845
1273
 
846
- /**
847
- * A **workflow reference** is how one workflow names another to call it: either a registered workflow
848
- * **name** (a string — the only option across runtimes, e.g. a Python workflow) or, for a same-runtime
849
- * TypeScript workflow, its **class**. The class carries the input/output types through the call, so
850
- * `ctx.child(ShippingWorkflow, input)` type-checks the input and returns a typed result — while a
851
- * string stays available for the cross-runtime case.
852
- */
853
- /**
854
- * The symbol the `@Workflow` decorator stamps a workflow's registered name onto, so a class ref can
855
- * be resolved back to its name. A global-registry symbol (`Symbol.for`) so it survives duplicate
856
- * copies of this package in a dependency tree.
857
- */
858
- declare const WORKFLOW_NAME_KEY: unique symbol;
859
- /** Structural shape of a `@Workflow` class — its `run(ctx, input)` carries the input/output types. */
860
- type WorkflowClass<TInput = unknown, TOutput = unknown> = abstract new (...args: never[]) => {
861
- run(ctx: never, input: TInput): Promise<TOutput> | TOutput;
862
- };
863
- /** A workflow reference: a registered name (cross-runtime) or a workflow class (typed, same-runtime). */
864
- type WorkflowRef<TInput = unknown, TOutput = unknown> = string | WorkflowClass<TInput, TOutput>;
865
- /** The input type a workflow class's `run` accepts. */
866
- type WorkflowInputOf<C> = C extends abstract new (...args: never[]) => {
867
- run(ctx: never, input: infer I): unknown;
868
- } ? I : unknown;
869
- /** The output type a workflow class's `run` resolves to (Promise unwrapped). */
870
- type WorkflowOutputOf<C> = C extends abstract new (...args: never[]) => {
871
- run(ctx: never, input: never): infer R;
872
- } ? Awaited<R> : unknown;
873
- /**
874
- * Resolve a {@link WorkflowRef} to its registered workflow name: a string is returned as-is; a
875
- * `@Workflow` class is resolved via the name the decorator stamped on it. Throws if a class was
876
- * never decorated (so it carries no registered name).
877
- */
878
- declare function workflowName(ref: WorkflowRef): string;
879
-
880
1274
  /**
881
1275
  * Core type contracts for nestjs-durable.
882
1276
  *
@@ -996,9 +1390,10 @@ interface WorkflowRun {
996
1390
  * The detail view (which has the timeline) still distinguishes sleep vs in-flight step precisely.
997
1391
  */
998
1392
  interface RunWaiting {
999
- on: 'signal' | 'webhook' | 'child' | 'breakpoint';
1393
+ on: 'signal' | 'webhook' | 'child' | 'breakpoint' | 'run';
1000
1394
  /**
1001
- * The token/name the run is parked on — the signal name, webhook token, or awaited child id. For a
1395
+ * The token/name the run is parked on — the signal name, webhook token, awaited child id, or the id
1396
+ * of the run it waits on in `ctx.waitForRun`. For a
1002
1397
  * breakpoint this is always the literal `'breakpoint'`: the real label (if any) lives on the pending
1003
1398
  * `breakpoint`/`breakpoint:<label>` checkpoint, which the detail view's timeline already shows —
1004
1399
  * naming it here would need an extra per-run checkpoint read, defeating the bulk waiter scan.
@@ -1805,6 +2200,17 @@ interface RunQuery {
1805
2200
  * Empty array = matches nothing.
1806
2201
  */
1807
2202
  workflows?: string[] | undefined;
2203
+ /**
2204
+ * Leave out the runs of these workflows (`workflow NOT IN (...)`), ANDed with everything else.
2205
+ * Empty array = excludes nothing. The run gateway uses it to keep engine bookkeeping runs (the
2206
+ * lifecycle registry) out of a console's lists and counts.
2207
+ */
2208
+ excludeWorkflows?: string[] | undefined;
2209
+ /**
2210
+ * Only runs last updated at or after this epoch ms (`updated_at >= updatedAfter`), ANDed with
2211
+ * everything else. For a settled run that is when it settled, unless something wrote it since.
2212
+ */
2213
+ updatedAfter?: number | undefined;
1808
2214
  status?: RunStatus | undefined;
1809
2215
  /**
1810
2216
  * Match any of these statuses (a `status IN (...)` filter). ORed together, and ANDed with the other
@@ -2102,6 +2508,12 @@ type RunRequestKind = {
2102
2508
  } | {
2103
2509
  kind: 'waitingFor';
2104
2510
  runIds: string[];
2511
+ } | {
2512
+ kind: 'republishLifecycle';
2513
+ target: RepublishLifecycleTarget;
2514
+ } | {
2515
+ kind: 'workflowLifecycle';
2516
+ workflow: string;
2105
2517
  };
2106
2518
  /** The control plane's answer to a {@link RunRequest}, correlated by `requestId`. */
2107
2519
  interface RunReply {
@@ -2807,6 +3219,11 @@ interface StepUndo<TInput, TOutput> {
2807
3219
  * see {@link StepRef}); `Awaited<R>` unwraps a `Promise<TOutput>` return down to `TOutput`.
2808
3220
  */
2809
3221
  type UndoOf<H> = H extends (input: infer I, ...rest: never[]) => infer R ? StepUndo<I, Awaited<R>> : never;
3222
+ /** Options for `ctx.waitForRun`. */
3223
+ interface WaitForRunOptions {
3224
+ /** Give up after this long (ms, or a duration like `'30m'`), throwing `SignalTimeoutError`. */
3225
+ timeoutMs?: number | string | undefined;
3226
+ }
2810
3227
  /**
2811
3228
  * The context handed to a workflow function. Every interaction with the outside world goes
2812
3229
  * through it so the engine can checkpoint — the workflow body itself stays deterministic.
@@ -2904,6 +3321,18 @@ interface WorkflowCtx<A extends SearchAttributes = SearchAttributes> {
2904
3321
  match?: Record<string, unknown>;
2905
3322
  timeoutMs?: number;
2906
3323
  }): Promise<TPayload>;
3324
+ /**
3325
+ * Wait for **any** run, not only a child, to settle, and resume with its
3326
+ * {@link WorkflowLifecycleEvent}: `status`, plus `output` on a completed run or `error` on one that
3327
+ * failed, was cancelled or died. Resolves at once when the run already settled; a run that
3328
+ * continued as new settles when the last run of its chain does. `timeoutMs` (ms, or a duration
3329
+ * like `'1h'`) bounds the wait and throws `SignalTimeoutError`. A run id that does not exist fails
3330
+ * with a non-retryable `run <id> not found`. No compute consumed while waiting.
3331
+ *
3332
+ * Pass the workflow class first to type the event by that workflow's input and output.
3333
+ */
3334
+ waitForRun<TOutput = unknown>(runId: string, opts?: WaitForRunOptions): Promise<WorkflowLifecycleEvent<unknown, TOutput>>;
3335
+ waitForRun<C extends WorkflowClass>(workflow: C, runId: string, opts?: WaitForRunOptions): Promise<LifecycleEventOf<C>>;
2907
3336
  /**
2908
3337
  * An external task with **async completion**: run `dispatch` once (checkpointed — e.g. send to a
2909
3338
  * queue, kick off a non-durable worker or a foreign service like a Python process), then suspend
@@ -3117,7 +3546,7 @@ type UpdateResult = {
3117
3546
  accepted: true;
3118
3547
  run: RunResult | null;
3119
3548
  };
3120
- type EngineEventType = 'run.started' | 'run.completed' | 'run.failed' | 'run.suspended' | 'step.started' | 'step.completed' | 'step.failed' | 'step.progress' | 'run.blocked' | 'run.routed' | 'run.unrouted';
3549
+ type EngineEventType = 'run.started' | 'run.completed' | 'run.failed' | 'run.suspended' | 'step.started' | 'step.completed' | 'step.failed' | 'step.progress' | 'run.blocked' | 'run.routed' | 'run.unrouted' | 'run.triggered' | 'run.trigger_failed';
3121
3550
  /**
3122
3551
  * A lifecycle event emitted by the engine. The observability surfaces (dashboard, OTel, the
3123
3552
  * Telescope integration) all subscribe to these rather than reaching into the store.
@@ -3159,6 +3588,14 @@ interface EngineEvent {
3159
3588
  diagnostics?: DispatchDiagnostics | undefined;
3160
3589
  /** Why a `run.unrouted` run's onError routes were not applied. */
3161
3590
  reason?: string | undefined;
3591
+ /** The run a `run.triggered` event started. */
3592
+ triggeredRunId?: string | undefined;
3593
+ /**
3594
+ * On the `run.started` of a run a lifecycle event started: the W3C traceparent of the source run's
3595
+ * span, when it is known (see `WorkflowEngine.setRunTraceparent`). A tracer links the run's span
3596
+ * to it.
3597
+ */
3598
+ sourceTraceparent?: string | undefined;
3162
3599
  at: Date;
3163
3600
  }
3164
3601
  type EngineListener = (event: EngineEvent) => void;
@@ -3475,14 +3912,21 @@ declare class Entities {
3475
3912
  private run;
3476
3913
  }
3477
3914
 
3478
- /** How `onEvent` triggers are coalesced into fewer runs (see `@Workflow({ debounce | batch })`). */
3915
+ /**
3916
+ * How `onEvent` triggers are coalesced into fewer runs (see `@Workflow({ debounce | batch })`).
3917
+ * `key` splits the coalescing per key: it receives each trigger's input (after the subscription's
3918
+ * `input` mapping) and triggers with the same key share one accumulator, so a burst for one key
3919
+ * starts one run without holding back or swallowing another key's.
3920
+ */
3479
3921
  type EventBatchConfig = {
3480
3922
  mode: 'debounce';
3481
3923
  windowMs: number;
3924
+ key?: ((input: unknown) => string) | undefined;
3482
3925
  } | {
3483
3926
  mode: 'batch';
3484
3927
  maxSize: number;
3485
3928
  windowMs: number;
3929
+ key?: ((input: unknown) => string) | undefined;
3486
3930
  };
3487
3931
  /** The slice of the engine the accumulators need (so they stay a standalone module). */
3488
3932
  interface AccumulatorHost {
@@ -3496,6 +3940,18 @@ interface AccumulatorHost {
3496
3940
  runId: string;
3497
3941
  }>;
3498
3942
  }
3943
+ /**
3944
+ * The accumulator run id, which is also its signal token. Without a key it is the target's alone;
3945
+ * with one, the key is percent-encoded (`~` and the other characters `encodeURIComponent` keeps
3946
+ * included), so any string makes a safe id that cannot read as a continue-as-new suffix.
3947
+ */
3948
+ declare function accumulatorRunId(target: string, key?: string): string;
3949
+ /**
3950
+ * How many routed event ids an accumulator remembers across bursts, so an event routed twice (a
3951
+ * lifecycle event published by two instances, or again by the sweep) counts once. The newest ids
3952
+ * are kept.
3953
+ */
3954
+ declare const ACCUMULATOR_SEEN_MAX = 1000;
3499
3955
  /**
3500
3956
  * Built-in workflows that coalesce `onEvent` triggers. Each is a long-lived per-target accumulator
3501
3957
  * fed by `signalWithStart`: it collects payloads then starts the target once, and `continueAsNew`s to
@@ -3505,8 +3961,12 @@ interface AccumulatorHost {
3505
3961
  declare class EventAccumulators {
3506
3962
  private readonly host;
3507
3963
  constructor(host: AccumulatorHost);
3508
- /** Route an `onEvent` payload into its target's debounce/batch accumulator. */
3509
- route(target: string, config: EventBatchConfig, payload: unknown): Promise<{
3964
+ /**
3965
+ * Route an `onEvent` payload into its target's debounce/batch accumulator: the target's one, or
3966
+ * with a `key`, the one for `String(config.key(payload))`. A `key` that throws rejects the route.
3967
+ * With `id`, the accumulator counts the event once however many times it is routed.
3968
+ */
3969
+ route(target: string, config: EventBatchConfig, payload: unknown, id?: string): Promise<{
3510
3970
  runId: string;
3511
3971
  }>;
3512
3972
  /** Fire the target with the LAST payload once events have been quiet for `windowMs`. */
@@ -3515,6 +3975,58 @@ declare class EventAccumulators {
3515
3975
  private batch;
3516
3976
  }
3517
3977
 
3978
+ /**
3979
+ * How many candidates a buffered-event scan considers (`listBufferedEvents(name, limit)`) before
3980
+ * giving up. An event's buffer is keyed by `name` only (see {@link eventMatches}'s match-based
3981
+ * consumption), so a hot name with many distinct payloads sitting unclaimed could in principle
3982
+ * accumulate an unbounded backlog; this caps the per-scan cost regardless. Shared by the workflow-ctx
3983
+ * consumer and the engine's reconcile sweep so both see the same window.
3984
+ */
3985
+ declare const EVENT_BUFFER_SCAN_LIMIT = 50;
3986
+ /** The literal prefix EVERY event-waiter token starts with, regardless of `name` — `eventPrefix(name)`
3987
+ * always begins with this; exported so a caller that only needs to CLASSIFY a token (not fan out a
3988
+ * specific name) doesn't have to re-derive or duplicate the literal (see run-waiting.ts's own copy,
3989
+ * kept in sync with this one, and engine.ts's reconcile sweep). */
3990
+ declare const EVENT_TOKEN_PREFIX = "event:";
3991
+ /** Token prefix for every waiter on `name` — used by `listSignalWaiters` to fan an event out. */
3992
+ declare function eventPrefix(name: string): string;
3993
+ /** Whether `token` is an event-waiter token (vs. a plain signal / child / webhook / breakpoint one). */
3994
+ declare function isEventToken(token: string): boolean;
3995
+ /** Build the unique waiter token for one `waitForEvent` call (name + match + run position). */
3996
+ declare function eventToken(name: string, match: Record<string, unknown> | undefined, runId: string, seq: number): string;
3997
+ /** The event name embedded in an event waiter token (the 2nd `:`-segment is the base64 name), so a
3998
+ * dashboard can show "waiting on event `<name>`" instead of the opaque token. */
3999
+ declare function eventNameOf(token: string): string;
4000
+ /** The match criteria embedded in an event waiter token (the 3rd `:`-segment is the base64 match). */
4001
+ declare function eventMatchOf(token: string): Record<string, unknown>;
4002
+ /** Whether `payload` satisfies a waiter's `match`: every match key deep-equals the payload's value. */
4003
+ declare function eventMatches(payload: unknown, match: Record<string, unknown>): boolean;
4004
+ /**
4005
+ * One `onEvent` subscription: the event name, plus an optional `where` that decides, per payload,
4006
+ * whether this workflow starts, and an optional `input` that turns the payload into the started
4007
+ * run's input. A bare string is shorthand for `{ event }`. Both functions run in the publishing
4008
+ * process, so they only exist for subscriptions registered in TypeScript.
4009
+ */
4010
+ interface EventSubscription {
4011
+ event: string;
4012
+ where?: ((payload: unknown) => boolean) | undefined;
4013
+ /** The started run's input, built from the payload. Defaults to the payload itself. */
4014
+ input?: ((payload: unknown) => unknown) | undefined;
4015
+ }
4016
+ /** An `onEvent` entry: an event name, or a {@link EventSubscription}. */
4017
+ type OnEventEntry = string | EventSubscription;
4018
+ /** Normalize an `onEvent` entry to its {@link EventSubscription} form. */
4019
+ declare function toEventSubscription(entry: OnEventEntry): EventSubscription;
4020
+ /**
4021
+ * Which of one workflow's subscriptions to an event takes `payload`: the first whose `where`
4022
+ * accepts it (a subscription without `where` accepts everything). A `where` that throws counts as
4023
+ * a rejection, and its error is returned so the caller can report it instead of losing it.
4024
+ */
4025
+ declare function acceptingSubscription(subscriptions: readonly EventSubscription[], payload: unknown): {
4026
+ accepted?: EventSubscription;
4027
+ errors: unknown[];
4028
+ };
4029
+
3518
4030
  /**
3519
4031
  * The announced workflow registry (design §7.9) — the aggregate answer to "what workflows exist in
3520
4032
  * this deployment?", built ONLY from what live workers say about themselves.
@@ -3640,6 +4152,10 @@ interface AnnouncedWorkflow {
3640
4152
  code?: string;
3641
4153
  workflow: string;
3642
4154
  }[][];
4155
+ /** Every event any live announcer says this workflow subscribes to (sorted, de-duplicated). Empty =
4156
+ * nobody stated one. A union, not a disagreement: during a rollout the engine owes a lifecycle
4157
+ * event to a subscriber as long as some live worker still has it. */
4158
+ subscribes: string[];
3643
4159
  /** Runtimes of the live announcers (sorted, de-duplicated). EMPTY on an `'observed'` entry: a
3644
4160
  * heartbeat does not say what runtime wrote it, and the instance id's shape is a convention, not
3645
4161
  * a statement, so it is not read as one. */
@@ -4703,7 +5219,7 @@ declare class WorkflowEngine {
4703
5219
  private readonly workflows;
4704
5220
  /** The newest registered version per workflow name — used to `start` new runs. */
4705
5221
  private readonly latest;
4706
- /** Event name → workflow names started when that event is published (see `onEvent`). */
5222
+ /** Event name → subscribing workflow name → that workflow's subscriptions to it. See `onEvent`. */
4707
5223
  private readonly eventTriggers;
4708
5224
  /** Durable-entity subsystem (registers the `__entity` runner; see `registerEntity`). */
4709
5225
  private readonly entities;
@@ -4959,7 +5475,7 @@ declare class WorkflowEngine {
4959
5475
  validateInput?: ((input: unknown) => void | Promise<void>) | undefined;
4960
5476
  /** Typed/validated `searchAttributes` shape — see `RegisteredWorkflow.searchAttributesSchema`. */
4961
5477
  searchAttributesSchema?: SearchAttributesSchema | undefined;
4962
- onEvent?: string[] | undefined;
5478
+ onEvent?: OnEventEntry[] | undefined;
4963
5479
  eventBatch?: EventBatchConfig | undefined;
4964
5480
  /** Worker group to DISPATCH this workflow's turns to (uniform dispatch). Requires `executor`.
4965
5481
  * Omit for the default inline fast path. See the method doc. */
@@ -5123,9 +5639,310 @@ declare class WorkflowEngine {
5123
5639
  */
5124
5640
  listStalledRuns(options?: ListStalledRunsOptions): Promise<StalledRunInfo[]>;
5125
5641
  private notifyDead;
5126
- /** Emit a locally-produced lifecycle event: deliver to subscribers AND broadcast it on the
5127
- * control plane so other instances (e.g. a dashboard pod) can live-tail this run. */
5642
+ /**
5643
+ * Emit a locally-produced lifecycle event: deliver to subscribers AND broadcast it on the control
5644
+ * plane so other instances (e.g. a dashboard pod) can live-tail this run. A `run.completed` or
5645
+ * `run.failed` also publishes the run's lifecycle event (see {@link publishLifecycle}) and resumes
5646
+ * the runs waiting on it with `ctx.waitForRun` (see {@link deliverRunWaits}); `lifecycle: false`
5647
+ * marks a `run.completed` that is not a real completion (a continue-as-new handoff).
5648
+ */
5128
5649
  private emit;
5650
+ /**
5651
+ * Start every workflow subscribed to `name` that takes `payload` (see {@link acceptingSubscription}),
5652
+ * each under `runIdOf(workflow)` and with its subscription's `input` applied. `only` restricts it
5653
+ * to those subscribers. `remote` are subscribers only live workers announce (see
5654
+ * {@link announcedRemoteSubscribers}): each is started by name with the payload as its input, since
5655
+ * an announcement carries no `where` or `input`. `routeIdOf` names the event for a subscriber's
5656
+ * debounce/batch accumulator, which counts an id once. Returns the subscribers reached, with the
5657
+ * run each started (none when the payload went into its debounce/batch accumulator), and the ones
5658
+ * that could not be started, with why.
5659
+ */
5660
+ private startSubscribers;
5661
+ /**
5662
+ * The subscribers of `event` that live workers announce for the settled runs of `namespace` (`null`:
5663
+ * any namespace, for an event no run published), are not registered on this engine with an `onEvent` for it, and that this engine can start: registered here (a `registerRemote`), or served
5664
+ * by convention on a live worker group of the same name (a Python `@workflow(on_event=...)`). One
5665
+ * this engine cannot start is left to the instances that can, so it stays owed rather than failing.
5666
+ */
5667
+ private announcedRemoteSubscribers;
5668
+ /** The workflows registered on this engine that subscribe to `event`. */
5669
+ private localSubscribers;
5670
+ /**
5671
+ * Whether some workflow may subscribe to `workflow` settling as `kind`: one registered on this
5672
+ * engine, or one in the last read of the fleet's announcements. True while there is no usable read
5673
+ * (none yet, or the last one failed), since the terminal write then marks the run unresolved (see
5674
+ * {@link withLifecycleMarker}).
5675
+ */
5676
+ private hasLifecycleSubscribers;
5677
+ /**
5678
+ * Whether this engine's own subscribers apply to the settled runs of `namespace`: an engine with
5679
+ * no namespace publishes the runs of every namespace, a namespaced one only its own.
5680
+ */
5681
+ private servesNamespace;
5682
+ /** This engine's subscribers of `event` that apply to the settled runs of `namespace`. */
5683
+ private localSubscribersIn;
5684
+ /** Answers the traceparent of a run's span in this process; see {@link setRunTraceparent}. */
5685
+ private runTraceparent;
5686
+ /**
5687
+ * Install the function that answers the W3C `traceparent` of a run's span in this process, or
5688
+ * `undefined` to remove it. `attachDurableOtel` installs one. With it, the first suspend or the
5689
+ * terminal write of a run some workflow subscribes to also records the run's traceparent (a
5690
+ * {@link LIFECYCLE_TRACE_TAG_PREFIX} tag, see {@link withRunTrace}), and the `run.started` of a run
5691
+ * a lifecycle event started carries its source run's as `sourceTraceparent`, so the subscriber's
5692
+ * trace links to the source's.
5693
+ */
5694
+ setRunTraceparent(provider: ((runId: string) => string | undefined) | undefined): void;
5695
+ /**
5696
+ * `{ sourceTraceparent }` for the `run.started` of `run`, when a lifecycle event started it and a
5697
+ * run trace provider is installed: the source run's recorded traceparent, else this process's.
5698
+ */
5699
+ private sourceTraceOf;
5700
+ /** The last read of the subscriptions live workers announce. See {@link announcedSubscriptions}. */
5701
+ private announcedSubscriptionsSnapshot;
5702
+ private announcedSubscriptionsRead;
5703
+ /**
5704
+ * The `onEvent` subscriptions the live fleet announces, by event name: the fresh lifecycle
5705
+ * registry runs in the state store (see {@link heartbeatLifecycleRegistry}) and, on a transport
5706
+ * that reads them, each worker descriptor's `subscribes`. Each entry records the namespace its
5707
+ * announcer serves (`null` for an engine with no namespace) and whether a Node engine announced it
5708
+ * (every registry run is one). Read at most once per
5709
+ * {@link ANNOUNCED_ROUTES_TTL_MS}, concurrent callers sharing one read. Never throws: `ok: false`
5710
+ * means a read failed and only the local registry is known.
5711
+ */
5712
+ private announcedSubscriptions;
5713
+ /**
5714
+ * The last read of the fleet's announcements as it is, without waiting: undefined before the first
5715
+ * read completes. Starts a read in the background when it is missing or older than
5716
+ * {@link ANNOUNCED_ROUTES_TTL_MS}. What the terminal write uses, so settling a run never waits on
5717
+ * the fleet.
5718
+ */
5719
+ private cachedAnnouncedSubscriptions;
5720
+ /**
5721
+ * When this engine first saw each subscription (`<event>\u0000<subscriber>`), in its registry or in
5722
+ * a good read of the fleet's announcements. The sweep's heal pass looks only at the ones first seen
5723
+ * within {@link LIFECYCLE_HEAL_WINDOW_MS}; see {@link healLifecycleEvents}.
5724
+ */
5725
+ private readonly subscriptionFirstSeen;
5726
+ /** Record the subscriptions of `snapshot` (a good read) and of this engine's registry as seen. */
5727
+ private noteSubscriptionsSeen;
5728
+ private readAnnouncedSubscriptions;
5729
+ /** How many registry runs one page of {@link listLifecycleRegistry} reads. */
5730
+ private static readonly LIFECYCLE_REGISTRY_PAGE;
5731
+ /**
5732
+ * The lifecycle registry runs this engine's namespace sees: its namespace's, plus `default`'s, where
5733
+ * the engines with no namespace keep theirs. Read a page of
5734
+ * {@link LIFECYCLE_REGISTRY_PAGE} at a time until a short page, so a large fleet is read whole.
5735
+ */
5736
+ private listLifecycleRegistry;
5737
+ /** When this engine last wrote its registry run, or undefined before the first heartbeat. */
5738
+ private lifecycleRegistryBeatAt;
5739
+ /**
5740
+ * Refresh this engine's lifecycle registry run and delete stale ones. At most once per
5741
+ * {@link LIFECYCLE_REGISTRY_HEARTBEAT_MS}; {@link sweepLifecycleEvents} calls it on every tick.
5742
+ *
5743
+ * An engine with `onEvent` subscriptions keeps one completed run of the internal
5744
+ * {@link LIFECYCLE_REGISTRY_WORKFLOW} workflow, id `__lifecycle_registry:<instanceId>`, holding
5745
+ * them in `input` and its heartbeat in `updatedAt`. Other instances read the fresh ones
5746
+ * ({@link LIFECYCLE_REGISTRY_TTL_MS}) as announced subscriptions, so a settled run is owed to a
5747
+ * subscriber registered only elsewhere whatever the transport. Any engine deletes the runs not
5748
+ * refreshed for {@link LIFECYCLE_REGISTRY_STALE_MS}. Retention never prunes them
5749
+ * ({@link LIFECYCLE_REGISTRY_TAG}), and the run gateway leaves them out of run lists.
5750
+ */
5751
+ heartbeatLifecycleRegistry(): Promise<void>;
5752
+ /** This engine's `onEvent` subscriptions, by subscribing workflow, as its registry run holds them. */
5753
+ private registrySubscriptions;
5754
+ private writeLifecycleRegistry;
5755
+ /**
5756
+ * The subscribers a run of `workflow` in `namespace` settling as `kind` owes its lifecycle event to:
5757
+ * the ones registered on this engine, when it publishes that namespace's runs (an engine with no
5758
+ * namespace publishes every namespace's), plus the ones live workers announce for that namespace
5759
+ * (see {@link announcedSubscriptions}): by announcers serving it, and by engines with no namespace.
5760
+ * Without `namespace`, every namespace's: what any run of `workflow` could owe. Empty for an
5761
+ * internal `__` workflow.
5762
+ */
5763
+ lifecycleSubscribers(workflow: string, kind: LifecycleKind, namespace?: string): Promise<string[]>;
5764
+ /** {@link lifecycleSubscribers} from one given read of the fleet's announcements. */
5765
+ private lifecycleSubscribersIn;
5766
+ /**
5767
+ * The subscribers registered here that coalesce `run`'s lifecycle event (debounce/batch) and
5768
+ * accept it, each with the accumulator run the event went to: the subscription's `where`, `input`
5769
+ * and `key` applied to the event as `startSubscribers` does. Undefined when the key cannot be
5770
+ * computed. A subscriber whose `where` declines the event is left out, and so is every one when
5771
+ * this engine does not publish the run's namespace. Empty for a run that has not settled.
5772
+ */
5773
+ coalescedSubscribers(run: WorkflowRun): Map<string, string | undefined>;
5774
+ /**
5775
+ * Who starts whom through lifecycle events, for `workflow`: the workflows that start when it
5776
+ * settles, and the workflows whose settling starts it. Built from this engine's registry and the
5777
+ * subscriptions live workers announce (see {@link announcedSubscriptions}); a failed fleet read
5778
+ * leaves the local registry alone. What a dashboard's workflow page shows.
5779
+ *
5780
+ * With `namespace`, only the subscriptions of that namespace: the ones announced by registry runs
5781
+ * and worker descriptors serving it, and this engine's own when it is that namespace's engine (an
5782
+ * engine with no namespace is `default`'s). What a tenant is shown.
5783
+ */
5784
+ workflowLifecycle(workflow: string, opts?: {
5785
+ namespace?: string | undefined;
5786
+ }): Promise<WorkflowLifecycleLinks>;
5787
+ /**
5788
+ * `patch` (a terminal status write of `run`) plus the lifecycle marker, when some workflow
5789
+ * subscribes to that ending: {@link LIFECYCLE_PENDING_TAG} and one owed tag per subscriber (see
5790
+ * {@link lifecycleSubscribers}). Written in the same update as the status, so a run can never be
5791
+ * settled without a record of who its lifecycle event is still owed to.
5792
+ *
5793
+ * Uses the last read of the fleet's announcements without waiting for a new one (see
5794
+ * {@link cachedAnnouncedSubscriptions}). With no usable read (none yet, or the last one failed) the
5795
+ * marker is {@link LIFECYCLE_PENDING_TAG} alone, for any workflow but an internal `__` one: the
5796
+ * owed set is unresolved, and {@link publishSettled} resolves it once a read succeeds.
5797
+ */
5798
+ private withLifecycleMarker;
5799
+ /**
5800
+ * `patch` (a suspend write of `run`) plus the run's {@link LIFECYCLE_TRACE_TAG_PREFIX} tag, when a
5801
+ * run trace provider is installed, some workflow subscribes to the run's ending, the provider
5802
+ * answers for the run and the run does not carry the tag yet. The first turn's suspend records the
5803
+ * run's root span this way, so a run that settles in a process that never saw its first turn still
5804
+ * links its subscribers' traces; a workflow nobody subscribes to gets no tag and no extra write.
5805
+ * Uses the last read of the fleet's announcements without waiting; with no usable read, any
5806
+ * workflow but an internal one may have subscribers, so it gets the tag.
5807
+ */
5808
+ private withRunTrace;
5809
+ /**
5810
+ * The runs started by `runId` settling (see {@link publishLifecycle}), read from the run's own
5811
+ * tags, so it needs no subscriber registry. Empty for a run that has not settled or started
5812
+ * nobody. Pass the run itself when it is already loaded, to skip reading it again.
5813
+ */
5814
+ triggeredRuns(source: string | WorkflowRun): Promise<string[]>;
5815
+ /** The live path of {@link publishSettled}: right after this instance settled the run. */
5816
+ private publishLifecycle;
5817
+ /** How long to wait before each new try at a run's lifecycle lease another publisher holds. */
5818
+ private static readonly LIFECYCLE_LEASE_BACKOFF_MS;
5819
+ /**
5820
+ * Run `fn` holding the lease on the settled run `runId` (`tryLockRun`, owner
5821
+ * `<instanceId>#lifecycle#<uuid>`, unique per call), so the live publish, the sweeps of every
5822
+ * instance and a republish update its lifecycle tags one at a time. Retried on the
5823
+ * {@link LIFECYCLE_LEASE_BACKOFF_MS} schedule while another holder has it (the settling execution
5824
+ * still holding its own, or another publisher); `busy` once those tries are spent.
5825
+ */
5826
+ private withLifecycleLease;
5827
+ /**
5828
+ * Publish a settled run's lifecycle event (`run.completed:<workflow>` / `run.failed:<workflow>`)
5829
+ * to the subscribers this engine has, and settle their part of the marker: drop each one's owed
5830
+ * tag, record each subscriber it started as a `durable:triggered:<workflow>` tag and each one it
5831
+ * routed into a debounce/batch accumulator as a `durable:coalesced:<workflow>` tag, and drop
5832
+ * {@link LIFECYCLE_PENDING_TAG} once no owed tag is left. Subscribers registered only elsewhere
5833
+ * keep their owed tags for the instances that have them.
5834
+ *
5835
+ * Which subscribers: `only` when given (a republish), plus `owe`, owed to the instances that have
5836
+ * them; `heal`, the ones a heal pass found missing (see {@link healLifecycleEvents}); else the owed
5837
+ * ones. A run marked with the pending tag alone is unresolved: with a good read of the fleet's
5838
+ * announcements it is owed to every subscriber (see {@link lifecycleSubscribers}) that has not
5839
+ * started, coalesced or failed, and published as such; without one, this engine starts its own subscribers
5840
+ * that do not coalesce and the run stays unresolved.
5841
+ *
5842
+ * Runs under the run's lifecycle lease (see {@link withLifecycleLease}), reading the run again
5843
+ * inside it; `busy` when the lease could not be taken. Idempotent, since every subscriber run id is
5844
+ * deterministic and a debounce/batch accumulator counts the event once, so the live path, the
5845
+ * sweeps and a republish may all reach the same run. `run.triggered` and `run.trigger_failed` are
5846
+ * emitted by the publish whose write recorded them: a subscriber it reached whose triggered or
5847
+ * coalesced tag the run did not have, and one it failed to start whose failed tag the run did not
5848
+ * have.
5849
+ *
5850
+ * A subscriber whose `where` throws or whose start fails is reported as `run.trigger_failed`,
5851
+ * tagged {@link LIFECYCLE_TRIGGER_FAILED_TAG_PREFIX} in the same update, and not retried; a
5852
+ * subscriber it starts loses that tag. A failure to write the marker leaves it, and the sweep
5853
+ * publishes the run again. Returns the subscribers acted on, or undefined when there was nothing
5854
+ * for this engine to do.
5855
+ */
5856
+ private publishSettled;
5857
+ /** {@link publishSettled}, under the run's lifecycle lease. */
5858
+ private publishSettledLocked;
5859
+ private reportTriggerFailed;
5860
+ /**
5861
+ * Drop the owed tags of `run`'s subscribers that no live worker announces and this engine does
5862
+ * not have, once the run settled more than {@link LIFECYCLE_ORPHAN_MS} ago, reporting each as
5863
+ * `run.trigger_failed` and tagging it {@link LIFECYCLE_TRIGGER_FAILED_TAG_PREFIX} in the same
5864
+ * update, under the run's lifecycle lease. Skipped when the fleet's announcements could not be
5865
+ * read, since a failed read would make every remote subscriber look orphaned.
5866
+ */
5867
+ private dropOrphanedSubscribers;
5868
+ /** How long a settled run's marker is left to the live publish before the sweep takes it over. */
5869
+ private static readonly LIFECYCLE_SWEEP_GRACE_MS;
5870
+ /**
5871
+ * How many marked runs (and `ctx.waitForRun` waiters) one sweep examines at most, looking for
5872
+ * `limit` it can act on. Runs owed only to subscribers other instances have are skipped without a
5873
+ * store read, so they cannot fill the window and keep this instance from the ones it can publish.
5874
+ */
5875
+ private static readonly LIFECYCLE_SWEEP_SCAN_MAX;
5876
+ /** How many recently settled runs of one workflow a heal pass reads at most. */
5877
+ private static readonly LIFECYCLE_HEAL_SCAN_CAP;
5878
+ /**
5879
+ * Publish the lifecycle event of every settled run still marked {@link LIFECYCLE_PENDING_TAG}:
5880
+ * one whose process died, or whose marker write failed, between settling it and publishing, one
5881
+ * owed to a subscriber the settling process does not have, or one whose owed set is unresolved.
5882
+ * Each instance publishes to the subscribers it has, and drops owed subscribers nobody has anymore
5883
+ * (see {@link dropOrphanedSubscribers}). Then heals the recently settled runs that missed a newly
5884
+ * announced subscriber (see {@link healLifecycleEvents}). Also delivers the `ctx.waitForRun` waits
5885
+ * whose run already settled (see {@link sweepRunWaits}). Called by the timer poller; a run settled
5886
+ * in the last {@link LIFECYCLE_SWEEP_GRACE_MS} is left to the live publish. Returns how many runs
5887
+ * it published to a subscriber.
5888
+ *
5889
+ * Reads the marked runs a page of `limit` at a time, skipping the ones it cannot act on, until it
5890
+ * has acted on `limit` runs (published, or dropped orphans) or examined
5891
+ * {@link LIFECYCLE_SWEEP_SCAN_MAX}. Pages advance by offset over a set the sweep itself shrinks,
5892
+ * so a run that moves into an earlier page is reached on the next tick, which starts over. A run
5893
+ * whose lifecycle lease another publisher holds is left for the next tick.
5894
+ */
5895
+ sweepLifecycleEvents(nowMs?: number, limit?: number): Promise<number>;
5896
+ /**
5897
+ * The (run, subscriber) pairs this engine already healed, until when it remembers them; see
5898
+ * {@link healLifecycleEvents}.
5899
+ */
5900
+ private readonly healedLifecycle;
5901
+ /**
5902
+ * Heal the runs settled in the last {@link LIFECYCLE_HEAL_WINDOW_MS} that missed a subscriber: one
5903
+ * the fleet announced only after the settling process last read the announcements, so it is in
5904
+ * none of the run's owed, triggered, coalesced or failed tags. Only subscriptions this engine first saw within
5905
+ * that window are checked (see {@link subscriptionFirstSeen}), since one the fleet already
5906
+ * announced when the run settled was in its owed set. Needs a good read of the fleet's
5907
+ * announcements.
5908
+ *
5909
+ * One `listRuns` per source workflow (`updatedAfter` the window, at most
5910
+ * {@link LIFECYCLE_HEAL_SCAN_CAP} runs), skipping unresolved runs (the sweep resolves those) and
5911
+ * the ones in their {@link LIFECYCLE_SWEEP_GRACE_MS}. Each missed subscriber is published like an
5912
+ * owed one (see {@link publishSettled}): started here when this engine can, owed to the instances
5913
+ * that have it otherwise. A subscriber whose `where` declines the event leaves no tag, so each
5914
+ * engine heals a pair once. Returns how many runs it published to a subscriber.
5915
+ */
5916
+ private healLifecycleEvents;
5917
+ /**
5918
+ * Publish the lifecycle events of settled runs again, to subscribers that missed them: one
5919
+ * registered after the runs settled, or one whose run was deleted. Unlike the sweep it needs no
5920
+ * marker. Each subscriber's run id is deterministic, so one already started is not started again.
5921
+ *
5922
+ * Subscribers registered on this engine are started here. A subscriber only live workers announce
5923
+ * is owed the event again (the run is re-marked), so the sweep on an instance that has it starts
5924
+ * it. Only subscribers of the run's lifecycle event in its namespace are published to; a
5925
+ * `subscriber` that is not one is reported in `failed`. Reads at most `limit` (a positive integer,
5926
+ * default 1000) settled runs of a workflow, a page at a time.
5927
+ */
5928
+ republishLifecycle(target: RepublishLifecycleTarget): Promise<RepublishLifecycleResult>;
5929
+ /** {@link republishLifecycle} for one settled run: start what is missing, report what failed. */
5930
+ private republishRun;
5931
+ /**
5932
+ * Resume the runs waiting on `targetRunId` with `ctx.waitForRun`, once it has settled. Each waiter
5933
+ * is taken before it is delivered to, so the settle path, the sweep and the waiting run's own
5934
+ * check never resume it twice. Returns how many it resumed.
5935
+ */
5936
+ private deliverRunWaits;
5937
+ /**
5938
+ * Deliver the `ctx.waitForRun` waits whose run has settled but which were never resumed: a crash
5939
+ * between settling and delivering, or a run that settled by handing off to a continue-as-new
5940
+ * chain that has since ended. Checks the waited-on runs in waiter order, skipping the ones that
5941
+ * have not settled, until it has resumed waiters of `limit` runs or checked
5942
+ * {@link LIFECYCLE_SWEEP_SCAN_MAX}, so long waits on runs still in flight cannot keep it from a
5943
+ * wait owed a delivery. Returns how many waiters it resumed.
5944
+ */
5945
+ sweepRunWaits(limit?: number): Promise<number>;
5129
5946
  /** Events waiting for the control-plane publish in flight, in emit order (see {@link broadcastEvents}). */
5130
5947
  private readonly eventsToBroadcast;
5131
5948
  private broadcastingEvents;
@@ -5554,7 +6371,8 @@ declare class WorkflowEngine {
5554
6371
  * 1. **Resumes** every in-flight run waiting on it via `ctx.waitForEvent(name, { match })` whose
5555
6372
  * match the payload satisfies (fan-out, vs `signal`'s point-to-point token).
5556
6373
  * 2. **Starts** a fresh run of every workflow registered with `onEvent: [name]`, passing the
5557
- * payload as input. Idempotent by `evt:<id>:<workflow>` — pass `opts.id` to dedupe redeliveries
6374
+ * payload as input, and of every workflow live workers announce as subscribing to it that this
6375
+ * engine can start by name (see {@link announcedRemoteSubscribers}). Idempotent by `evt:<id>:<workflow>` — pass `opts.id` to dedupe redeliveries
5558
6376
  * of the same logical event (default: a fresh uuid, so each publish triggers once).
5559
6377
  *
5560
6378
  * Semantics (deliberate — mirrors `signalWithStart`'s reliability contract, so document it exactly):
@@ -7028,6 +7846,12 @@ declare function pageFanFromStore(store: CheckpointAggregatingStore, runId: stri
7028
7846
  * plus its checkpoint buckets, and the threshold it was summarized with.
7029
7847
  */
7030
7848
  declare function runDetailEtag(run: WorkflowRun, stats: CheckpointStat[], over: number): string;
7849
+ /**
7850
+ * `etag` extended with a fingerprint of `extras`, the parts of a detail read from outside the run
7851
+ * row and its checkpoints (another run's status, the fleet's subscriptions), so a change to them
7852
+ * also changes the validator. `etag` itself when `extras` is undefined.
7853
+ */
7854
+ declare function extendEtag(etag: string, extras: unknown): string;
7031
7855
  /** The ETag of one page of a fan: its group's buckets and the page asked for. */
7032
7856
  declare function fanPageEtag(group: string, stats: CheckpointStat[], query: FanPageQuery): string;
7033
7857
  /** Whether an `If-None-Match` header value names `etag` (weak comparison, as RFC 9110 asks for). */
@@ -7052,8 +7876,11 @@ declare function parseWebhookToken(token: string): {
7052
7876
  * like any other), so without this case it would fall through to the generic `signal` branch with the
7053
7877
  * raw `bp:<runId>:<seq>` token as its display name — a real bug. Named `'breakpoint'` here instead;
7054
7878
  * the token carries no separate label to recover cheaply (see {@link RunWaiting.name}).
7879
+ *
7880
+ * A `ctx.waitForRun` token (`runwait:<target>#<runId>#<seq>`) is named by its target run, read
7881
+ * exactly against `waiter` when given, else from the token alone.
7055
7882
  */
7056
- declare function classifyWaiterToken(token: string): RunWaiting;
7883
+ declare function classifyWaiterToken(token: string, waiter?: Pick<SignalWaiter, 'runId' | 'seq'>): RunWaiting;
7057
7884
  /**
7058
7885
  * Resolve a suspended run's {@link RunWaiting} from the pending signal waiters (indexed by `runId`).
7059
7886
  * Event-only by design (see {@link RunWaiting}): a `waitForSignal`/`waitForEvent`/webhook/awaited-child
@@ -7273,31 +8100,22 @@ declare class CodecStateStore implements StateStore {
7273
8100
  }
7274
8101
 
7275
8102
  /**
7276
- * How many candidates a buffered-event scan considers (`listBufferedEvents(name, limit)`) before
7277
- * giving up. An event's buffer is keyed by `name` only (see {@link eventMatches}'s match-based
7278
- * consumption), so a hot name with many distinct payloads sitting unclaimed could in principle
7279
- * accumulate an unbounded backlog; this caps the per-scan cost regardless. Shared by the workflow-ctx
7280
- * consumer and the engine's reconcile sweep so both see the same window.
8103
+ * `ctx.waitForRun(runId)`: a durable wait for any run to settle, built on the signal-waiter table.
8104
+ * The waiter's token embeds the target run and the waiting call's own `runId#seq`, so no two calls
8105
+ * share one, and the engine finds a run's waiters by the {@link runWaitPrefix} of its id.
7281
8106
  */
7282
- declare const EVENT_BUFFER_SCAN_LIMIT = 50;
7283
- /** The literal prefix EVERY event-waiter token starts with, regardless of `name` — `eventPrefix(name)`
7284
- * always begins with this; exported so a caller that only needs to CLASSIFY a token (not fan out a
7285
- * specific name) doesn't have to re-derive or duplicate the literal (see run-waiting.ts's own copy,
7286
- * kept in sync with this one, and engine.ts's reconcile sweep). */
7287
- declare const EVENT_TOKEN_PREFIX = "event:";
7288
- /** Token prefix for every waiter on `name` — used by `listSignalWaiters` to fan an event out. */
7289
- declare function eventPrefix(name: string): string;
7290
- /** Whether `token` is an event-waiter token (vs. a plain signal / child / webhook / breakpoint one). */
7291
- declare function isEventToken(token: string): boolean;
7292
- /** Build the unique waiter token for one `waitForEvent` call (name + match + run position). */
7293
- declare function eventToken(name: string, match: Record<string, unknown> | undefined, runId: string, seq: number): string;
7294
- /** The event name embedded in an event waiter token (the 2nd `:`-segment is the base64 name), so a
7295
- * dashboard can show "waiting on event `<name>`" instead of the opaque token. */
7296
- declare function eventNameOf(token: string): string;
7297
- /** The match criteria embedded in an event waiter token (the 3rd `:`-segment is the base64 match). */
7298
- declare function eventMatchOf(token: string): Record<string, unknown>;
7299
- /** Whether `payload` satisfies a waiter's `match`: every match key deep-equals the payload's value. */
7300
- declare function eventMatches(payload: unknown, match: Record<string, unknown>): boolean;
8107
+ /** The literal every run-wait token starts with. */
8108
+ declare const RUN_WAIT_TOKEN_PREFIX = "runwait:";
8109
+ /** Token prefix shared by every waiter on `targetRunId`. */
8110
+ declare function runWaitPrefix(targetRunId: string): string;
8111
+ /** The waiter token for one `ctx.waitForRun(targetRunId)` call at `seq` of run `runId`. */
8112
+ declare function runWaitToken(targetRunId: string, runId: string, seq: number): string;
8113
+ /**
8114
+ * The run a `ctx.waitForRun` waiter waits on, or undefined when `waiter` is not one. Read against
8115
+ * the waiter's own `runId` and `seq`, so a target id containing `#` is still read exactly, and a
8116
+ * prefix listing for run `a` that also returns the waiters of run `a#b` can be told apart.
8117
+ */
8118
+ declare function runWaitTargetOf(waiter: Pick<SignalWaiter, 'token' | 'runId' | 'seq'>): string | undefined;
7301
8119
 
7302
8120
  interface MetricsSnapshot {
7303
8121
  /** `routed`: failures handed to an onError handler; `unrouted`: routes the engine could not apply. */
@@ -7311,6 +8129,16 @@ interface MetricsSnapshot {
7311
8129
  };
7312
8130
  /** Routed failures by error code (`*` for a failure without one). */
7313
8131
  routedByCode: Record<string, number>;
8132
+ /**
8133
+ * Subscriber runs a settled run's lifecycle event started (`run.triggered`), keyed by the settled
8134
+ * run's workflow, then by the subscriber. Exposed as `durable_runs_triggered_total{workflow,subscriber}`.
8135
+ */
8136
+ triggeredBySubscriber: Record<string, Record<string, number>>;
8137
+ /**
8138
+ * Subscribers a settled run's lifecycle event could not start (`run.trigger_failed`), keyed the
8139
+ * same way. Exposed as `durable_runs_trigger_failed_total{workflow,subscriber}`.
8140
+ */
8141
+ triggerFailedBySubscriber: Record<string, Record<string, number>>;
7314
8142
  steps: {
7315
8143
  started: number;
7316
8144
  completed: number;
@@ -7934,4 +8762,4 @@ declare function singletonAdmissionDenialPatch(runs: WorkflowRun[], runId: strin
7934
8762
  updatedAt: Date;
7935
8763
  } | undefined;
7936
8764
 
7937
- export { type AccumulatorHost, type Admission, type AdmissionBackend, type AdmissionItem, type AllOptions, type AllSettledOptions, type AllStepsOptions, type AllStepsSettledOptions, type AnnouncedWorkflow, type AnnouncementEvidence, type AttributeFilter, type AttributeOp, type AttributePredicateOperand, type AttributeValue, type BackoffStrategy, type BlockedDispatch, type BlockedResolution, type BufferedSignalRow, CHILD_EDGE_PREFIXES, CONTROL_FLOW_SIGNAL, CORE_ORIGIN, CURRENT_PROTOCOL_VERSION, type CapabilityRequirement, type CheckpointAggregatingStore, type CheckpointNameKind, type CheckpointQuery, type CheckpointStat, type ChildCallOptions, type ChildWait, CodecStateStore, type CodecStateStoreOptions, type ConcurrencyConfig, ConcurrencyLimitError, type ConcurrencyQuota, ContinueAsNew, type ControlMessage, type ControlPlane, DEFAULT_CONCURRENCY_STATUSES, DEFAULT_PARTITION, DEFAULT_STALLED_AFTER_MS, DURABLE_OPTIONS, DURABLE_OPTIONS_CANONICAL, DURABLE_STEP_CONFIG, DURABLE_STEP_NAME, type Disagreement, type DispatchDiagnostics, type DispatchPlan, type DurableExecution, type DurableExecutionWrapper, type DurableTopology, type DurableWebhook, DurableWorkflow, type DynamicWorkflowCtx, ENGINE_MINTED_TAG_PREFIXES, ENTITY_WORKFLOW, EVENT_BUFFER_SCAN_LIMIT, EVENT_TOKEN_PREFIX, type EngineEvent, type EngineEventType, type EngineListener, Entities, type EntityConfig, type EntityHandler, type EntityHost, type EntityWorkflowHost, EventAccumulators, type EventBatchConfig, FAN_SUMMARY_FAILURES, type FanJoin, type FanPage, type FanPageQuery, type FanSummary, type FanWait, FatalError, type FindStalledRunsOptions, GatherError, type GatherItemFailure, type GroupHealth, HANDOFF_SEQ_BASE, type Heartbeat, type HeartbeatSighting, type HeartbeatStatus, type HistoryEvent, InMemoryAdmissionBackend, InMemoryRunQueue, InMemoryStateStore, InMemoryTransport, type InferSearchAttributes, LEGACY_V1_CAPABILITIES, LEGACY_V1_PROTOCOL, type ListStalledRunsOptions, type MetricsCollector, type MetricsSnapshot, type NamedTransport, type NegotiateOptions, type NegotiationOutcome, type NegotiationReason, type NegotiationResult, NestedWorkflowCallError, NonDeterminismError, type OnErrorInput, type OnErrorRoute, type OwnedLeaseReclaim, type PartitionSighting, type PayloadCodec, type QueueConfig, QueueController, REMOTE_EVENT, RUN_HISTORY_FIXTURE_VERSION, RUN_VALUE_FACET_LIMIT, RUN_VALUE_FACET_SCAN, type RawWorkerDescriptor, RemoteStepError, RemoteStepTimeout, type RemoteTask, RemoteWorkflowExecutor, RemoteWorkflowTimeout, type RetentionPolicy, type RoutableDispatch, type RoutableResolution, type RoutingResolution, type RunAttributeRow, type RunConsumerOptions, type RunDetail, type RunDetailOptions, type RunDispatch, type RunDispatcher, type RunFacetQuery, type RunFacetRow, RunGateway, type RunListItem, type RunQuery, type RunQueueOptions, type RunReply, type RunReplyResult, type RunRequest, type RunRequestKind, type RunResult, type RunSchedulesOptions, type RunScope, type RunStatus, type RunValueAxis, type RunValueFacetOptions, type RunValueFacetOrder, type RunValueFacetRow, type RunWaiting, SINGLETON_ACTIVE_STATUSES, SINGLETON_ADMITTED_TAG, SINGLETON_LOCK_CHUNK, SINGLETON_RESERVED_TAGS, SINGLETON_TRACKED_TAG, STATE_STORE, STATE_STORE_CANONICAL, SUMMARY_CHILD_LIMIT, type ScalarAttributeFilter, ScheduleAlreadyExistsError, ScheduleClient, type ScheduleClientOptions, type ScheduleDescription, type ScheduleHost, type ScheduleListQuery, ScheduleNotFoundError, type ScheduleOptions, type ScheduleQuery, type ScheduleRecord, type ScheduledWorkflow, type SchemaIssue, type SchemaValidationCode, SchemaValidationError, type SearchAttributes, type SearchAttributesSchema, type Settled, SignalTimeoutError, type SignalWaiter, type SingletonConfig, SingletonQueueFullError, type StalePendingStep, type StalledRunInfo, StandardSchemaV1, type StartOptions, type StartRunMessage, type StateStore, type StepCheckpoint, type StepConfig, type StepDef, type StepDispatchOpts, type StepError, type StepEvent, type StepHandler, type StepInterceptor, type StepInvocation, type StepKind, type StepLogger, type StepOptions, type StepRef, type StepResult, type StepScope, type StepSettlement, type StepUndo, type StoreTransaction, type SubProcessHandle, TERMINAL_RUN_STATUSES, TRANSPORT, TRANSPORT_CANONICAL, type TenantEvent, type TenantTokenSource, type TenantVerifier, type Transport, type UndoOf, type UpdateResult, type UpdateValidator, VERSION_UNDECLARED_TAG, type VerifiedTenant, WORKFLOW_NAME_KEY, type WireDates, type WorkerAdjust, type WorkerConcurrencyStatus, type WorkerDescriptor, type WorkerHeartbeat, type WorkerLifecycle, type WorkerStatus, type WorkflowAnnouncement, WorkflowBlocked, type WorkflowClass, type WorkflowCommand, type WorkflowCtx, type WorkflowDecision, type WorkflowDirectory, WorkflowEngine, type WorkflowEngineDeps, type WorkflowExecutor, type WorkflowHandler, type WorkflowInputOf, WorkflowNotRegistered, type WorkflowOutputOf, type WorkflowRef, type WorkflowRegistration, type WorkflowRun, type WorkflowStartClient, type WorkflowStepEvent, WorkflowSuspended, type WorkflowTask, aggregateAnnouncements, aggregatesCheckpoints, announcementsOf, applyAttributeQuery, assertConcurrency, assertRoutes, attributeColumnFor, attributeOperand, attributePredicateOperands, axisIsRunColumn, bindWorkflowClass, breakpointToken, buildWorkflowDirectory, canRoute, capableWorkers, checkpointNameKind, checkpointStatsOf, childIdsOf, classifyWaiterToken, clearDurableExecutionWrappers, clearTerminalSingletonAdmission, codeAndDetails, codeOf, collectMetrics, concurrencyTag, controlPlaneDescriptor, countRuns, coveredTokens, createStepLogger, currentStep, currentStepScope, currentWorkflowCtx, debug, describeWorker, descriptorHash, detailsOf, error, etagMatches, eventMatchOf, eventMatches, eventNameOf, eventPrefix, eventToken, facetOrigin, fanPageBounds, fanPageEtag, findStalledRuns, foldedCount, getRunsByIds, handoffHandlerId, handoffName, hasDurableExecutionWrappers, heartbeatStatus, hmacTenantVerifier, indexWaitersByRun, info, isEngineMintedTag, isEventToken, isFailedMember, isLegacyDescriptor, isNonEmptyRunScope, isRemoteEvent, isWorkflowControlFlowSignal, legacySingletonHolders, listSignalWaitersOfRuns, liveHandoff, log, markRemoteEvent, matchesAttributes, mergeRunFacetRows, mergeRunValueFacetRows, missingCapabilities, negotiate, nextCronFireMs, normalizeAttributeRows, normalizeDescriptor, observedAnnouncements, onErrorRunId, pageFan, pageFanFromStore, parentRunIdOf, parseDuration, parseWebhookToken, partitionOfToken, planDispatch, poolNamespace, prevCronFireMs, queryCheckpointsOf, readRunsByIds, readSearchAttributes, requiredCapabilities, resolveConcurrency, resolveRouting, resolveRunWaiting, resolveTenantToken, resolveWireTenant, retiredHandoffName, routeFor, runDetailEtag, runDurableExecution, runInStepLogger, runInStepScope, runInWorkflowCtx, runOutsideWorkflowCtx, runSchedules, runStepHandler, runValueFacetsFromRuns, sanitizeQueueToken, scheduleRunIdAt, scheduledRunId, signTenantToken, singletonAdmissionDenialPatch, singletonAdmissionTags, singletonClaimantIds, sqlComparator, stepConfigOf, stepId, stepNameOf, sub, subEvent, subProcess, summarizeFan, summarizeRunFromStore, summarizeTimeline, tenantGroup, useDurableExecution, warn, withSingletonTracked, withoutSingletonMarkers, workflowName };
8765
+ export { ACCUMULATOR_SEEN_MAX, type AccumulatorHost, type Admission, type AdmissionBackend, type AdmissionItem, type AllOptions, type AllSettledOptions, type AllStepsOptions, type AllStepsSettledOptions, type AnnouncedWorkflow, type AnnouncementEvidence, type AttributeFilter, type AttributeOp, type AttributePredicateOperand, type AttributeValue, type BackoffStrategy, type BlockedDispatch, type BlockedResolution, type BufferedSignalRow, CHILD_EDGE_PREFIXES, CONTROL_FLOW_SIGNAL, CORE_ORIGIN, CURRENT_PROTOCOL_VERSION, type CapabilityRequirement, type CheckpointAggregatingStore, type CheckpointNameKind, type CheckpointQuery, type CheckpointStat, type ChildCallOptions, type ChildWait, CodecStateStore, type CodecStateStoreOptions, type ConcurrencyConfig, ConcurrencyLimitError, type ConcurrencyQuota, ContinueAsNew, type ControlMessage, type ControlPlane, DEFAULT_CONCURRENCY_STATUSES, DEFAULT_PARTITION, DEFAULT_STALLED_AFTER_MS, DURABLE_OPTIONS, DURABLE_OPTIONS_CANONICAL, DURABLE_STEP_CONFIG, DURABLE_STEP_NAME, type Disagreement, type DispatchDiagnostics, type DispatchPlan, type DurableExecution, type DurableExecutionWrapper, type DurableTopology, type DurableWebhook, DurableWorkflow, type DynamicWorkflowCtx, ENGINE_MINTED_TAG_PREFIXES, ENTITY_WORKFLOW, EVENT_BUFFER_SCAN_LIMIT, EVENT_TOKEN_PREFIX, type EngineEvent, type EngineEventType, type EngineListener, Entities, type EntityConfig, type EntityHandler, type EntityHost, type EntityWorkflowHost, EventAccumulators, type EventBatchConfig, type EventSubscription, FAN_SUMMARY_FAILURES, type FanJoin, type FanPage, type FanPageQuery, type FanSummary, type FanWait, FatalError, type FindStalledRunsOptions, GatherError, type GatherItemFailure, type GroupHealth, HANDOFF_SEQ_BASE, type Heartbeat, type HeartbeatSighting, type HeartbeatStatus, type HistoryEvent, InMemoryAdmissionBackend, InMemoryRunQueue, InMemoryStateStore, InMemoryTransport, type InferSearchAttributes, LEGACY_V1_CAPABILITIES, LEGACY_V1_PROTOCOL, LIFECYCLE_COALESCED_TAG_PREFIX, LIFECYCLE_HEAL_WINDOW_MS, LIFECYCLE_ORPHAN_MS, LIFECYCLE_OWED_TAG_PREFIX, LIFECYCLE_PENDING_TAG, LIFECYCLE_REGISTRY_HEARTBEAT_MS, LIFECYCLE_REGISTRY_STALE_MS, LIFECYCLE_REGISTRY_TAG, LIFECYCLE_REGISTRY_TTL_MS, LIFECYCLE_REGISTRY_WORKFLOW, LIFECYCLE_TRACE_TAG_PREFIX, LIFECYCLE_TRIGGERED_TAG_PREFIX, LIFECYCLE_TRIGGER_FAILED_TAG_PREFIX, type LifecycleDelivery, type LifecycleDeliveryState, type LifecycleEventOf, type LifecycleKind, type LifecycleRegistryEntry, type LifecycleSource, type LifecycleSubscriptionLink, type ListStalledRunsOptions, type MetricsCollector, type MetricsSnapshot, type NamedTransport, type NegotiateOptions, type NegotiationOutcome, type NegotiationReason, type NegotiationResult, NestedWorkflowCallError, NonDeterminismError, type OnErrorInput, type OnErrorRoute, type OnEventEntry, type OwnedLeaseReclaim, type PartitionSighting, type PayloadCodec, type QueueConfig, QueueController, REMOTE_EVENT, RUN_HISTORY_FIXTURE_VERSION, RUN_VALUE_FACET_LIMIT, RUN_VALUE_FACET_SCAN, RUN_WAIT_TOKEN_PREFIX, type RawWorkerDescriptor, RemoteStepError, RemoteStepTimeout, type RemoteTask, RemoteWorkflowExecutor, RemoteWorkflowTimeout, type RepublishLifecycleResult, type RepublishLifecycleTarget, type RetentionPolicy, type RoutableDispatch, type RoutableResolution, type RoutingResolution, type RunAttributeRow, type RunConsumerOptions, type RunDetail, type RunDetailOptions, type RunDispatch, type RunDispatcher, type RunFacetQuery, type RunFacetRow, RunGateway, type RunListItem, type RunQuery, type RunQueueOptions, type RunReply, type RunReplyResult, type RunRequest, type RunRequestKind, type RunResult, type RunSchedulesOptions, type RunScope, type RunStatus, type RunValueAxis, type RunValueFacetOptions, type RunValueFacetOrder, type RunValueFacetRow, type RunWaitLink, type RunWaiting, SINGLETON_ACTIVE_STATUSES, SINGLETON_ADMITTED_TAG, SINGLETON_LOCK_CHUNK, SINGLETON_RESERVED_TAGS, SINGLETON_TRACKED_TAG, STATE_STORE, STATE_STORE_CANONICAL, SUMMARY_CHILD_LIMIT, type ScalarAttributeFilter, ScheduleAlreadyExistsError, ScheduleClient, type ScheduleClientOptions, type ScheduleDescription, type ScheduleHost, type ScheduleListQuery, ScheduleNotFoundError, type ScheduleOptions, type ScheduleQuery, type ScheduleRecord, type ScheduledWorkflow, type SchemaIssue, type SchemaValidationCode, SchemaValidationError, type SearchAttributes, type SearchAttributesSchema, type Settled, SignalTimeoutError, type SignalWaiter, type SingletonConfig, SingletonQueueFullError, type StalePendingStep, type StalledRunInfo, StandardSchemaV1, type StartOptions, type StartRunMessage, type StateStore, type StepCheckpoint, type StepConfig, type StepDef, type StepDispatchOpts, type StepError, type StepEvent, type StepHandler, type StepInterceptor, type StepInvocation, type StepKind, type StepLogger, type StepOptions, type StepRef, type StepResult, type StepScope, type StepSettlement, type StepUndo, type StoreTransaction, type SubProcessHandle, TERMINAL_RUN_STATUSES, TRANSPORT, TRANSPORT_CANONICAL, type TenantEvent, type TenantTokenSource, type TenantVerifier, type Transport, type UndoOf, type UpdateResult, type UpdateValidator, VERSION_UNDECLARED_TAG, type VerifiedTenant, WORKFLOW_NAME_KEY, type WaitForRunOptions, type WireDates, type WorkerAdjust, type WorkerConcurrencyStatus, type WorkerDescriptor, type WorkerHeartbeat, type WorkerLifecycle, type WorkerStatus, type WorkflowAnnouncement, WorkflowBlocked, type WorkflowClass, type WorkflowCommand, type WorkflowCtx, type WorkflowDecision, type WorkflowDirectory, WorkflowEngine, type WorkflowEngineDeps, type WorkflowExecutor, type WorkflowHandler, type WorkflowInputOf, type WorkflowLifecycleEvent, type WorkflowLifecycleLinks, WorkflowNotRegistered, type WorkflowOutputOf, type WorkflowRef, type WorkflowRegistration, type WorkflowRun, type WorkflowStartClient, type WorkflowStepEvent, WorkflowSuspended, type WorkflowTask, acceptingSubscription, accumulatorRunId, aggregateAnnouncements, aggregatesCheckpoints, announcementsOf, applyAttributeQuery, assertConcurrency, assertRoutes, attributeColumnFor, attributeOperand, attributePredicateOperands, axisIsRunColumn, bindWorkflowClass, breakpointToken, buildWorkflowDirectory, canRoute, capableWorkers, carriesLifecyclePending, checkpointNameKind, checkpointStatsOf, childIdsOf, classifyWaiterToken, clearDurableExecutionWrappers, clearTerminalSingletonAdmission, coalescedSubscribersOf, codeAndDetails, codeOf, collectMetrics, concurrencyTag, controlPlaneDescriptor, countRuns, coveredTokens, createStepLogger, currentStep, currentStepScope, currentWorkflowCtx, debug, describeWorker, descriptorHash, detailsOf, error, etagMatches, eventMatchOf, eventMatches, eventNameOf, eventPrefix, eventToken, extendEtag, facetOrigin, fanPageBounds, fanPageEtag, findStalledRuns, foldedCount, getRunsByIds, handoffHandlerId, handoffName, hasDurableExecutionWrappers, heartbeatStatus, hmacTenantVerifier, indexWaitersByRun, info, isEngineMintedTag, isEventToken, isFailedMember, isLegacyDescriptor, isLifecycleTag, isNonEmptyRunScope, isRemoteEvent, isWorkflowControlFlowSignal, legacySingletonHolders, lifecycleDeliveriesOf, lifecycleEventName, lifecycleEventOf, lifecycleKindOf, lifecycleRegistryNamespace, lifecycleRegistryRunId, lifecycleRegistrySubscriptions, lifecycleRunId, lifecycleSourceOf, lifecycleTraceparentOf, listSignalWaitersOfRuns, liveHandoff, log, markRemoteEvent, matchesAttributes, mergeRunFacetRows, mergeRunValueFacetRows, missingCapabilities, negotiate, nextCronFireMs, normalizeAttributeRows, normalizeDescriptor, observedAnnouncements, onErrorRunId, owedSubscribersOf, pageFan, pageFanFromStore, parentRunIdOf, parseDuration, parseLifecycleEvent, parseWebhookToken, partitionOfToken, planDispatch, poolNamespace, prevCronFireMs, queryCheckpointsOf, readRunsByIds, readSearchAttributes, requiredCapabilities, resolveConcurrency, resolveRouting, resolveRunWaiting, resolveTenantToken, resolveWireTenant, retentionKeeps, retiredHandoffName, routeFor, runCompletedEvent, runDetailEtag, runDurableExecution, runFailedEvent, runInStepLogger, runInStepScope, runInWorkflowCtx, runOutsideWorkflowCtx, runSchedules, runStepHandler, runValueFacetsFromRuns, runWaitPrefix, runWaitTargetOf, runWaitToken, sanitizeQueueToken, scheduleRunIdAt, scheduledRunId, signTenantToken, singletonAdmissionDenialPatch, singletonAdmissionTags, singletonClaimantIds, sqlComparator, stepConfigOf, stepId, stepNameOf, sub, subEvent, subProcess, summarizeFan, summarizeRunFromStore, summarizeTimeline, tenantGroup, toEventSubscription, traceIdOfTraceparent, triggerFailedSubscribersOf, triggeredRunsOf, triggeredSubscribersOf, useDurableExecution, warn, withSingletonTracked, withoutSingletonMarkers, workflowName };