@dudousxd/nestjs-durable-core 0.0.0-beta-20260701163515

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 ADDED
@@ -0,0 +1,4652 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/queue.ts
5
+ var QueueController = class {
6
+ static {
7
+ __name(this, "QueueController");
8
+ }
9
+ config;
10
+ clock;
11
+ inFlight = 0;
12
+ windowStart = 0;
13
+ windowCount = 0;
14
+ /** Registered waiters by id (only used when priority/fairness ordering is in play). */
15
+ waiters = /* @__PURE__ */ new Map();
16
+ /** Monotonic counter stamping each newly-seen waiter for a stable FIFO tiebreak. */
17
+ waiterSeq = 0;
18
+ /** Per-key "last served" order for round-robin fairness — higher = more recently served. */
19
+ keyServed = /* @__PURE__ */ new Map();
20
+ servedTick = 0;
21
+ constructor(config, clock) {
22
+ this.config = config;
23
+ this.clock = clock;
24
+ }
25
+ /** Whether this controller does any priority/fairness ordering (else it's a plain FIFO gate). */
26
+ get ordered() {
27
+ return this.config.fairness === "key" || this.config.order === "lifo";
28
+ }
29
+ /**
30
+ * Try to admit one unit of work. On `ok`, the caller has taken a concurrency slot and must call
31
+ * {@link release} when the step settles. On block, `retryAt` is when admission may next succeed.
32
+ *
33
+ * `item` carries optional priority/fairness hints; omitting it is the legacy FIFO path. When
34
+ * ordering is configured (or a priority is given), a blocked call REGISTERS as a waiter and is only
35
+ * admitted on a later retry once it is the rightful next under (priority desc, fairness, FIFO).
36
+ */
37
+ tryAdmit(item) {
38
+ const now = this.clock();
39
+ const rl = this.config.rateLimit;
40
+ if (rl) {
41
+ if (now - this.windowStart >= rl.periodMs) {
42
+ this.windowStart = now;
43
+ this.windowCount = 0;
44
+ }
45
+ if (this.windowCount >= rl.limit) return {
46
+ ok: false,
47
+ retryAt: this.windowStart + rl.periodMs
48
+ };
49
+ }
50
+ const usingOrder = this.ordered || item?.priority != null || item?.waiterId != null;
51
+ const waiterId = item?.waiterId;
52
+ const full = this.config.concurrency != null && this.inFlight >= this.config.concurrency;
53
+ if (full) {
54
+ if (usingOrder && waiterId != null) this.register(waiterId, item);
55
+ return {
56
+ ok: false,
57
+ retryAt: now + (this.config.retryMs ?? 1e3)
58
+ };
59
+ }
60
+ if (usingOrder && this.waiters.size > 0) {
61
+ if (waiterId != null) this.register(waiterId, item);
62
+ if (!this.isNext(waiterId, item)) {
63
+ return {
64
+ ok: false,
65
+ retryAt: now + (this.config.retryMs ?? 1e3)
66
+ };
67
+ }
68
+ }
69
+ if (rl) this.windowCount += 1;
70
+ this.inFlight += 1;
71
+ if (waiterId != null) this.waiters.delete(waiterId);
72
+ if (item?.key != null) this.keyServed.set(item.key, ++this.servedTick);
73
+ return {
74
+ ok: true
75
+ };
76
+ }
77
+ /** Release a concurrency slot taken by a successful {@link tryAdmit}. */
78
+ release() {
79
+ if (this.inFlight > 0) this.inFlight -= 1;
80
+ }
81
+ /** Track (or refresh) a blocked call as a waiter; its FIFO seq is stamped only on first sight. */
82
+ register(waiterId, item) {
83
+ const existing = this.waiters.get(waiterId);
84
+ if (existing) {
85
+ existing.priority = item?.priority ?? 0;
86
+ existing.key = item?.key;
87
+ return;
88
+ }
89
+ this.waiters.set(waiterId, {
90
+ priority: item?.priority ?? 0,
91
+ key: item?.key,
92
+ seq: this.waiterSeq++
93
+ });
94
+ }
95
+ /**
96
+ * Is the calling item the best candidate among all registered waiters? Ordering, best first:
97
+ * 1. higher `priority`;
98
+ * 2. fairness: with `fairness: 'key'`, the least-recently-served key wins (round-robin);
99
+ * 3. earliest registration (FIFO) — stable tiebreak.
100
+ * A bare item (no waiterId) is compared on its hints directly.
101
+ */
102
+ isNext(waiterId, item) {
103
+ const self = (waiterId != null ? this.waiters.get(waiterId) : void 0) ?? {
104
+ priority: item?.priority ?? 0,
105
+ key: item?.key,
106
+ seq: Number.POSITIVE_INFINITY
107
+ };
108
+ let best = self;
109
+ for (const w of this.waiters.values()) {
110
+ if (this.better(w, best)) best = w;
111
+ }
112
+ return best === self;
113
+ }
114
+ /** Strict "a should be admitted before b" comparison under the active policy. */
115
+ better(a, b) {
116
+ if (a.priority !== b.priority) return a.priority > b.priority;
117
+ if (this.config.fairness === "key") {
118
+ const sa = this.servedOf(a.key);
119
+ const sb = this.servedOf(b.key);
120
+ if (sa !== sb) return sa < sb;
121
+ }
122
+ return this.config.order === "lifo" ? a.seq > b.seq : a.seq < b.seq;
123
+ }
124
+ /** Last-served tick for a key (0 = never served, so an unseen key is admitted before a busy one). */
125
+ servedOf(key) {
126
+ if (key == null) return 0;
127
+ return this.keyServed.get(key) ?? 0;
128
+ }
129
+ };
130
+
131
+ // src/admission.ts
132
+ var InMemoryAdmissionBackend = class {
133
+ static {
134
+ __name(this, "InMemoryAdmissionBackend");
135
+ }
136
+ clock;
137
+ controllers = /* @__PURE__ */ new Map();
138
+ constructor(clock) {
139
+ this.clock = clock;
140
+ }
141
+ register(config) {
142
+ this.controllers.set(config.name, new QueueController(config, this.clock));
143
+ }
144
+ handles(queue) {
145
+ return this.controllers.has(queue);
146
+ }
147
+ async tryAdmit(queue, item) {
148
+ const controller = this.controllers.get(queue);
149
+ if (!controller) return {
150
+ ok: true
151
+ };
152
+ return controller.tryAdmit(item);
153
+ }
154
+ async release(queue, _slotId) {
155
+ this.controllers.get(queue)?.release();
156
+ }
157
+ };
158
+
159
+ // src/duration.ts
160
+ var UNIT_MS = {
161
+ ms: 1,
162
+ s: 1e3,
163
+ sec: 1e3,
164
+ second: 1e3,
165
+ seconds: 1e3,
166
+ m: 6e4,
167
+ min: 6e4,
168
+ minute: 6e4,
169
+ minutes: 6e4,
170
+ h: 36e5,
171
+ hr: 36e5,
172
+ hour: 36e5,
173
+ hours: 36e5,
174
+ d: 864e5,
175
+ day: 864e5,
176
+ days: 864e5,
177
+ w: 6048e5,
178
+ week: 6048e5,
179
+ weeks: 6048e5
180
+ };
181
+ function parseDuration(duration) {
182
+ if (typeof duration === "number") return duration;
183
+ const match = duration.trim().match(/^(\d+(?:\.\d+)?)\s*([a-z]+)$/i);
184
+ if (!match) throw new Error(`invalid duration: ${duration}`);
185
+ const value = Number(match[1]);
186
+ const unit = (match[2] ?? "").toLowerCase();
187
+ const factor = UNIT_MS[unit];
188
+ if (factor === void 0) throw new Error(`unknown duration unit: ${unit}`);
189
+ return value * factor;
190
+ }
191
+ __name(parseDuration, "parseDuration");
192
+
193
+ // src/backoff.ts
194
+ function backoffDelay(attempt, options) {
195
+ const base = options?.backoffMs ?? 0;
196
+ if (base <= 0) return 0;
197
+ const raw = options?.backoff === "exp" ? base * 2 ** (attempt - 1) : base;
198
+ const capped = options?.backoffMaxMs ? Math.min(raw, options.backoffMaxMs) : raw;
199
+ return options?.jitter ? Math.round(capped * (0.5 + Math.random() * 0.5)) : capped;
200
+ }
201
+ __name(backoffDelay, "backoffDelay");
202
+
203
+ // src/step-logger.ts
204
+ function withDuration(start, now, data) {
205
+ if (data && typeof data === "object" && "durationMs" in data) {
206
+ return data;
207
+ }
208
+ const base = data && typeof data === "object" ? data : {};
209
+ return {
210
+ ...base,
211
+ durationMs: now() - start
212
+ };
213
+ }
214
+ __name(withDuration, "withDuration");
215
+ function createStepLogger(events, now) {
216
+ let currentSub;
217
+ const push = /* @__PURE__ */ __name((level, message, data) => events.push({
218
+ at: now(),
219
+ level,
220
+ message,
221
+ ...currentSub ? {
222
+ subId: currentSub.id
223
+ } : {},
224
+ ...data === void 0 ? {} : {
225
+ data
226
+ }
227
+ }), "push");
228
+ const subEvent = /* @__PURE__ */ __name((e) => events.push({
229
+ at: now(),
230
+ level: e.status === "failed" ? "error" : e.status === "skipped" ? "warn" : "info",
231
+ message: e.message ?? e.phase ?? e.name,
232
+ subId: e.id,
233
+ name: e.name,
234
+ ...e.group === void 0 ? {} : {
235
+ group: e.group
236
+ },
237
+ ...e.phase === void 0 ? {} : {
238
+ phase: e.phase
239
+ },
240
+ ...e.status === void 0 ? {} : {
241
+ status: e.status
242
+ },
243
+ ...e.data === void 0 ? {} : {
244
+ data: e.data
245
+ }
246
+ }), "subEvent");
247
+ const subProcess = /* @__PURE__ */ __name(async (name, body, opts) => {
248
+ const id = opts?.id ?? globalThis.crypto.randomUUID();
249
+ const group = opts?.group;
250
+ const start = now();
251
+ const prevSub = currentSub;
252
+ currentSub = {
253
+ id
254
+ };
255
+ let terminal = false;
256
+ const emit = /* @__PURE__ */ __name((status, message, data) => {
257
+ if (terminal) return;
258
+ terminal = true;
259
+ subEvent({
260
+ id,
261
+ name,
262
+ group,
263
+ status,
264
+ message,
265
+ data: withDuration(start, now, data)
266
+ });
267
+ }, "emit");
268
+ const handle = {
269
+ phase: /* @__PURE__ */ __name((phase, data) => {
270
+ if (!terminal) subEvent({
271
+ id,
272
+ name,
273
+ group,
274
+ phase,
275
+ data
276
+ });
277
+ return handle;
278
+ }, "phase"),
279
+ skip: /* @__PURE__ */ __name((reason, data) => emit("skipped", reason, data), "skip"),
280
+ fail: /* @__PURE__ */ __name((reason, data) => emit("failed", reason, data), "fail")
281
+ };
282
+ try {
283
+ const result = await body(handle);
284
+ emit("ok");
285
+ return result;
286
+ } catch (err) {
287
+ emit("failed", err instanceof Error ? err.message : String(err));
288
+ throw err;
289
+ } finally {
290
+ currentSub = prevSub;
291
+ }
292
+ }, "subProcess");
293
+ return {
294
+ debug: /* @__PURE__ */ __name((m, d) => push("debug", m, d), "debug"),
295
+ info: /* @__PURE__ */ __name((m, d) => push("info", m, d), "info"),
296
+ warn: /* @__PURE__ */ __name((m, d) => push("warn", m, d), "warn"),
297
+ error: /* @__PURE__ */ __name((m, d) => push("error", m, d), "error"),
298
+ sub: /* @__PURE__ */ __name((name, status, message, data) => events.push({
299
+ at: now(),
300
+ level: status === "failed" ? "error" : status === "skipped" ? "warn" : "info",
301
+ message: message ?? name,
302
+ name,
303
+ status,
304
+ ...data === void 0 ? {} : {
305
+ data
306
+ }
307
+ }), "sub"),
308
+ subEvent,
309
+ subProcess
310
+ };
311
+ }
312
+ __name(createStepLogger, "createStepLogger");
313
+
314
+ // src/protocol.ts
315
+ function stepId(runId, seq) {
316
+ return `${runId}:${seq}`;
317
+ }
318
+ __name(stepId, "stepId");
319
+ var breakpointToken = /* @__PURE__ */ __name((runId, seq) => `bp:${runId}:${seq}`, "breakpointToken");
320
+ async function runStepHandler(task, handler) {
321
+ const base = {
322
+ runId: task.runId,
323
+ seq: task.seq,
324
+ stepId: task.stepId,
325
+ startedAt: Date.now()
326
+ };
327
+ if (!handler) {
328
+ return {
329
+ ...base,
330
+ status: "failed",
331
+ error: {
332
+ message: `no handler for ${task.name}`,
333
+ retryable: false
334
+ }
335
+ };
336
+ }
337
+ const events = [];
338
+ const withEvents = /* @__PURE__ */ __name((result) => events.length > 0 ? {
339
+ ...result,
340
+ events
341
+ } : result, "withEvents");
342
+ try {
343
+ const output = await handler(task.input, createStepLogger(events, Date.now));
344
+ return withEvents({
345
+ ...base,
346
+ status: "completed",
347
+ output
348
+ });
349
+ } catch (err) {
350
+ const e = err;
351
+ return withEvents({
352
+ ...base,
353
+ status: "failed",
354
+ error: {
355
+ message: err instanceof Error ? err.message : String(err),
356
+ ...typeof e?.code === "string" ? {
357
+ code: e.code
358
+ } : {},
359
+ ...typeof e?.retryable === "boolean" ? {
360
+ retryable: e.retryable
361
+ } : {}
362
+ }
363
+ });
364
+ }
365
+ }
366
+ __name(runStepHandler, "runStepHandler");
367
+
368
+ // src/checkpoints.ts
369
+ function nonEmptyEvents(events) {
370
+ return events && events.length > 0 ? events : void 0;
371
+ }
372
+ __name(nonEmptyEvents, "nonEmptyEvents");
373
+ function stepCheckpoint(p) {
374
+ return {
375
+ runId: p.runId,
376
+ seq: p.seq,
377
+ name: p.name,
378
+ kind: p.kind,
379
+ stepId: stepId(p.runId, p.seq),
380
+ status: p.status,
381
+ input: p.input,
382
+ output: p.output,
383
+ error: p.error,
384
+ events: nonEmptyEvents(p.events),
385
+ attempts: p.attempts,
386
+ workerGroup: p.workerGroup,
387
+ wakeAt: p.wakeAt,
388
+ parallelGroup: p.parallelGroup,
389
+ enqueuedAt: p.enqueuedAt,
390
+ startedAt: p.startedAt,
391
+ finishedAt: p.finishedAt
392
+ };
393
+ }
394
+ __name(stepCheckpoint, "stepCheckpoint");
395
+ function instantCheckpoint(p) {
396
+ const at = /* @__PURE__ */ new Date();
397
+ return {
398
+ runId: p.runId,
399
+ seq: p.seq,
400
+ name: p.name,
401
+ kind: p.kind,
402
+ stepId: stepId(p.runId, p.seq),
403
+ status: p.status ?? "completed",
404
+ output: p.output,
405
+ wakeAt: p.wakeAt,
406
+ parallelGroup: p.parallelGroup,
407
+ attempts: 1,
408
+ enqueuedAt: at,
409
+ startedAt: at,
410
+ finishedAt: at
411
+ };
412
+ }
413
+ __name(instantCheckpoint, "instantCheckpoint");
414
+
415
+ // src/errors.ts
416
+ var FatalError = class extends Error {
417
+ static {
418
+ __name(this, "FatalError");
419
+ }
420
+ code;
421
+ constructor(message, code) {
422
+ super(message);
423
+ this.name = "FatalError";
424
+ this.code = code;
425
+ }
426
+ };
427
+ var SingletonQueueFullError = class extends Error {
428
+ static {
429
+ __name(this, "SingletonQueueFullError");
430
+ }
431
+ workflow;
432
+ key;
433
+ maxQueueDepth;
434
+ constructor(workflow, key, maxQueueDepth) {
435
+ super(`singleton queue for ${workflow} key "${key}" is full (maxQueueDepth=${maxQueueDepth}); retry later`);
436
+ this.name = "SingletonQueueFullError";
437
+ this.workflow = workflow;
438
+ this.key = key;
439
+ this.maxQueueDepth = maxQueueDepth;
440
+ }
441
+ };
442
+ var SignalTimeoutError = class extends Error {
443
+ static {
444
+ __name(this, "SignalTimeoutError");
445
+ }
446
+ token;
447
+ timeoutMs;
448
+ constructor(token, timeoutMs) {
449
+ super(`timed out after ${timeoutMs}ms waiting for signal "${token}"`);
450
+ this.name = "SignalTimeoutError";
451
+ this.token = token;
452
+ this.timeoutMs = timeoutMs;
453
+ }
454
+ };
455
+ var RemoteStepTimeout = class extends Error {
456
+ static {
457
+ __name(this, "RemoteStepTimeout");
458
+ }
459
+ stepId;
460
+ timeoutMs;
461
+ constructor(stepId2, timeoutMs) {
462
+ super(`remote step ${stepId2} produced no result/heartbeat within ${timeoutMs}ms`);
463
+ this.name = "RemoteStepTimeout";
464
+ this.stepId = stepId2;
465
+ this.timeoutMs = timeoutMs;
466
+ }
467
+ };
468
+ var RemoteWorkflowTimeout = class extends Error {
469
+ static {
470
+ __name(this, "RemoteWorkflowTimeout");
471
+ }
472
+ taskId;
473
+ timeoutMs;
474
+ constructor(taskId, timeoutMs) {
475
+ super(`remote workflow task ${taskId} produced no decision within ${timeoutMs}ms \u2014 presumed dropped; re-driving via recovery`);
476
+ this.name = "RemoteWorkflowTimeout";
477
+ this.taskId = taskId;
478
+ this.timeoutMs = timeoutMs;
479
+ }
480
+ };
481
+ var NonDeterminismError = class extends Error {
482
+ static {
483
+ __name(this, "NonDeterminismError");
484
+ }
485
+ runId;
486
+ seq;
487
+ constructor(runId, seq, expected, recorded) {
488
+ super(`non-determinism at ${runId}#${seq}: code expects "${expected}" but history recorded "${recorded}". The workflow changed under an in-flight run \u2014 register a new @Workflow version.`);
489
+ this.name = "NonDeterminismError";
490
+ this.runId = runId;
491
+ this.seq = seq;
492
+ }
493
+ };
494
+ var GatherError = class extends Error {
495
+ static {
496
+ __name(this, "GatherError");
497
+ }
498
+ failures;
499
+ constructor(failures, total) {
500
+ const ids = failures.map((f) => f.id).join(", ");
501
+ const denom = total ?? failures.length;
502
+ super(`ctx.all: ${failures.length} of ${denom} child(ren) failed: ${ids}`);
503
+ this.name = "GatherError";
504
+ this.failures = failures;
505
+ }
506
+ };
507
+ var WorkflowSuspended = class extends Error {
508
+ static {
509
+ __name(this, "WorkflowSuspended");
510
+ }
511
+ /** Epoch ms to auto-resume (durable sleep), or undefined when waiting on an external signal. */
512
+ wakeAt;
513
+ constructor(wakeAt) {
514
+ super("workflow suspended");
515
+ this.name = "WorkflowSuspended";
516
+ this.wakeAt = wakeAt;
517
+ }
518
+ };
519
+ var ContinueAsNew = class extends Error {
520
+ static {
521
+ __name(this, "ContinueAsNew");
522
+ }
523
+ input;
524
+ constructor(input) {
525
+ super("workflow continued as new"), this.input = input;
526
+ this.name = "ContinueAsNew";
527
+ }
528
+ };
529
+
530
+ // src/entities.ts
531
+ var ENTITY_WORKFLOW = "__entity";
532
+ var entityRunId = /* @__PURE__ */ __name((name, key) => `entity:${name}:${key}`, "entityRunId");
533
+ var Entities = class {
534
+ static {
535
+ __name(this, "Entities");
536
+ }
537
+ host;
538
+ configs = /* @__PURE__ */ new Map();
539
+ constructor(host) {
540
+ this.host = host;
541
+ host.register(ENTITY_WORKFLOW, "1", (ctx, input) => this.run(ctx, input));
542
+ }
543
+ register(name, config) {
544
+ this.configs.set(name, config);
545
+ }
546
+ /** Deliver an op to an entity's runner, starting it on first contact. `reply` (a signal token)
547
+ * receives the handler's result, for `ctx.callEntity`. */
548
+ dispatch(name, key, op, arg, reply) {
549
+ const runId = entityRunId(name, key);
550
+ return this.host.signalWithStart(ENTITY_WORKFLOW, {
551
+ name,
552
+ key
553
+ }, runId, {
554
+ token: runId,
555
+ payload: {
556
+ op,
557
+ arg,
558
+ reply
559
+ }
560
+ });
561
+ }
562
+ async signal(name, key, op, arg) {
563
+ await this.dispatch(name, key, op, arg);
564
+ }
565
+ getState(name, key) {
566
+ return this.host.getEvent(entityRunId(name, key), "state");
567
+ }
568
+ /** The built-in runner: one long-lived run per key, processing ops serially over state. */
569
+ async run(ctx, input) {
570
+ const { name, key } = input;
571
+ const config = this.configs.get(name);
572
+ if (!config) throw new FatalError(`entity "${name}" is not registered`);
573
+ const token = entityRunId(name, key);
574
+ let state = config.initialState();
575
+ for (let i = 0; ; i += 1) {
576
+ const msg = await ctx.waitForSignal(token);
577
+ const out = await ctx.step(`op:${i}`, async () => {
578
+ const handler = config.handlers[msg.op];
579
+ if (!handler) throw new FatalError(`entity "${name}" has no handler for op "${msg.op}"`);
580
+ const result = await handler(state, msg.arg);
581
+ return {
582
+ result,
583
+ state
584
+ };
585
+ });
586
+ state = out.state;
587
+ await ctx.setEvent("state", state);
588
+ if (msg.reply) {
589
+ await ctx.step(`reply:${i}`, async () => {
590
+ await this.host.signal(msg.reply, out.result);
591
+ });
592
+ }
593
+ }
594
+ }
595
+ };
596
+
597
+ // src/event-accumulators.ts
598
+ var accToken = /* @__PURE__ */ __name((target) => `__evtacc__:${target}`, "accToken");
599
+ var EventAccumulators = class {
600
+ static {
601
+ __name(this, "EventAccumulators");
602
+ }
603
+ host;
604
+ constructor(host) {
605
+ this.host = host;
606
+ host.register("__evt_debounce", "1", (ctx, input) => this.debounce(ctx, input));
607
+ host.register("__evt_batch", "1", (ctx, input) => this.batch(ctx, input));
608
+ }
609
+ /** Route an `onEvent` payload into its target's debounce/batch accumulator. */
610
+ route(target, config, payload) {
611
+ const [workflow, input] = config.mode === "debounce" ? [
612
+ "__evt_debounce",
613
+ {
614
+ target,
615
+ windowMs: config.windowMs
616
+ }
617
+ ] : [
618
+ "__evt_batch",
619
+ {
620
+ target,
621
+ maxSize: config.maxSize,
622
+ windowMs: config.windowMs
623
+ }
624
+ ];
625
+ return this.host.signalWithStart(workflow, input, accToken(target), {
626
+ token: accToken(target),
627
+ payload
628
+ });
629
+ }
630
+ /** Fire the target with the LAST payload once events have been quiet for `windowMs`. */
631
+ async debounce(ctx, input) {
632
+ const { target, windowMs } = input;
633
+ const token = accToken(target);
634
+ let last = await ctx.waitForSignal(token);
635
+ for (; ; ) {
636
+ try {
637
+ last = await ctx.waitForSignal(token, {
638
+ timeoutMs: windowMs
639
+ });
640
+ } catch (e) {
641
+ if (e instanceof SignalTimeoutError) break;
642
+ throw e;
643
+ }
644
+ }
645
+ await ctx.startChild(target, last);
646
+ return ctx.continueAsNew(input);
647
+ }
648
+ /** Fire the target with all payloads (`{ events }`) once `maxSize` or `windowMs` from the first. */
649
+ async batch(ctx, input) {
650
+ const { target, maxSize, windowMs } = input;
651
+ const token = accToken(target);
652
+ const events = [
653
+ await ctx.waitForSignal(token)
654
+ ];
655
+ const deadline = await ctx.now() + windowMs;
656
+ while (events.length < maxSize) {
657
+ const remaining = deadline - await ctx.now();
658
+ if (remaining <= 0) break;
659
+ try {
660
+ events.push(await ctx.waitForSignal(token, {
661
+ timeoutMs: remaining
662
+ }));
663
+ } catch (e) {
664
+ if (e instanceof SignalTimeoutError) break;
665
+ throw e;
666
+ }
667
+ }
668
+ await ctx.startChild(target, {
669
+ events
670
+ });
671
+ return ctx.continueAsNew(input);
672
+ }
673
+ };
674
+
675
+ // src/events.ts
676
+ var enc = /* @__PURE__ */ __name((s) => Buffer.from(s, "utf8").toString("base64"), "enc");
677
+ var dec = /* @__PURE__ */ __name((s) => Buffer.from(s, "base64").toString("utf8"), "dec");
678
+ function eventPrefix(name) {
679
+ return `event:${enc(name)}:`;
680
+ }
681
+ __name(eventPrefix, "eventPrefix");
682
+ function eventToken(name, match, runId, seq) {
683
+ return `${eventPrefix(name)}${enc(JSON.stringify(match ?? {}))}:${runId}#${seq}`;
684
+ }
685
+ __name(eventToken, "eventToken");
686
+ function eventMatchOf(token) {
687
+ try {
688
+ return JSON.parse(dec(token.split(":")[2] ?? ""));
689
+ } catch {
690
+ return {};
691
+ }
692
+ }
693
+ __name(eventMatchOf, "eventMatchOf");
694
+ function eventMatches(payload, match) {
695
+ const keys = Object.keys(match);
696
+ if (keys.length === 0) return true;
697
+ if (!payload || typeof payload !== "object") return false;
698
+ const p = payload;
699
+ return keys.every((k) => JSON.stringify(p[k]) === JSON.stringify(match[k]));
700
+ }
701
+ __name(eventMatches, "eventMatches");
702
+
703
+ // src/remote-workflow-executor.ts
704
+ var RemoteWorkflowExecutor = class {
705
+ static {
706
+ __name(this, "RemoteWorkflowExecutor");
707
+ }
708
+ transport;
709
+ group;
710
+ constructor(transport, group, _opts = {}) {
711
+ this.transport = transport;
712
+ this.group = group;
713
+ }
714
+ /**
715
+ * Enqueue one workflow turn under the engine-supplied `taskId`. Does NOT await the decision — the
716
+ * engine has already suspended the run on `taskId` and applies the decision durably via `onDecision`.
717
+ */
718
+ async dispatch(run, history, taskId, pendingSignals) {
719
+ if (!this.transport.dispatchWorkflowTask) {
720
+ throw new Error("transport does not support workflow tasks (dispatchWorkflowTask)");
721
+ }
722
+ const task = {
723
+ taskId,
724
+ runId: run.id,
725
+ workflow: run.workflow,
726
+ workflowVersion: run.workflowVersion,
727
+ input: run.input,
728
+ history,
729
+ ...pendingSignals ? {
730
+ pendingSignals
731
+ } : {},
732
+ group: this.group,
733
+ priority: run.priority,
734
+ attempt: 1
735
+ };
736
+ await this.transport.dispatchWorkflowTask(task);
737
+ }
738
+ };
739
+
740
+ // src/singleton-gate.ts
741
+ var SINGLETON_RETRY_MS = 1e3;
742
+ var SINGLETON_RETRY_JITTER_MS = 250;
743
+ var SingletonGate = class {
744
+ static {
745
+ __name(this, "SingletonGate");
746
+ }
747
+ deps;
748
+ constructor(deps) {
749
+ this.deps = deps;
750
+ }
751
+ /** The tag a singleton run carries, so the gate can find others sharing its key. */
752
+ tag(cfg, input) {
753
+ return `singleton:${cfg.key(input)}`;
754
+ }
755
+ /** Next wake time for a gated run: the base retry delay jittered to avoid a wakeup stampede. */
756
+ retryWakeAt() {
757
+ return this.deps.clock() + SINGLETON_RETRY_MS + Math.floor((Math.random() * 2 - 1) * SINGLETON_RETRY_JITTER_MS);
758
+ }
759
+ /**
760
+ * Reject a start that would grow the same-key backlog past `limit + maxQueueDepth` (counting
761
+ * `pending`/`running`/`suspended` runs sharing the key in one scan). No-op when no `maxQueueDepth`
762
+ * is configured.
763
+ */
764
+ async assertCapacity(workflow, cfg, input) {
765
+ if (cfg.maxQueueDepth == null) return;
766
+ const cap = (cfg.limit ?? 1) + cfg.maxQueueDepth;
767
+ const queued = await this.deps.store.listRuns({
768
+ tag: this.tag(cfg, input),
769
+ workflow,
770
+ statuses: [
771
+ "pending",
772
+ "running",
773
+ "suspended",
774
+ "cancelling"
775
+ ]
776
+ });
777
+ if (queued.length >= cap) {
778
+ throw new SingletonQueueFullError(workflow, cfg.key(input), cfg.maxQueueDepth);
779
+ }
780
+ }
781
+ /**
782
+ * Whether `run` may run now under its key: it's among the `limit` oldest in-flight (running or
783
+ * suspended) runs sharing the key, by `(createdAt, id)` order. A consistent store gives every
784
+ * instance the same ordering, so admission is race-free + FIFO.
785
+ */
786
+ async admit(run, cfg) {
787
+ const inflight = (await this.deps.store.listRuns({
788
+ tag: this.tag(cfg, run.input),
789
+ workflow: run.workflow,
790
+ statuses: [
791
+ "running",
792
+ "suspended",
793
+ "cancelling"
794
+ ]
795
+ })).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id));
796
+ const idx = inflight.findIndex((r) => r.id === run.id);
797
+ return idx >= 0 && idx < (cfg.limit ?? 1);
798
+ }
799
+ /**
800
+ * Notify-on-release: a singleton run settled (freeing a slot), so dispatch the oldest gated
801
+ * (`suspended` + same tag) waiters now instead of waiting for their ~1s retry timer. Each re-checks
802
+ * admission in the executor and runs only if it actually wins a slot, so FIFO/race-free guarantees
803
+ * hold; the durable timer remains the cross-instance/crash fallback.
804
+ */
805
+ async wakeNext(settled) {
806
+ const cfg = this.deps.configFor(settled);
807
+ if (!cfg) return;
808
+ const tag = settled.tags?.find((t) => t.startsWith("singleton:"));
809
+ if (!tag) return;
810
+ const gated = (await this.deps.store.listRuns({
811
+ tag,
812
+ workflow: settled.workflow,
813
+ statuses: [
814
+ "suspended"
815
+ ]
816
+ })).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id));
817
+ for (const next of gated.slice(0, cfg.limit ?? 1)) {
818
+ if (next.wakeAt != null) {
819
+ await this.deps.store.updateRun(next.id, {
820
+ wakeAt: void 0,
821
+ updatedAt: /* @__PURE__ */ new Date()
822
+ }).catch(() => void 0);
823
+ }
824
+ this.deps.dispatch(next.id);
825
+ }
826
+ }
827
+ };
828
+
829
+ // src/tenant-group.ts
830
+ function tenantGroup(baseGroup, tenant) {
831
+ return tenant !== void 0 && tenant !== "" && tenant !== "default" ? `${baseGroup}@${tenant}` : baseGroup;
832
+ }
833
+ __name(tenantGroup, "tenantGroup");
834
+
835
+ // src/transport-pool.ts
836
+ var TransportPool = class {
837
+ static {
838
+ __name(this, "TransportPool");
839
+ }
840
+ transports;
841
+ constructor(transports) {
842
+ this.transports = transports;
843
+ }
844
+ get size() {
845
+ return this.transports.length;
846
+ }
847
+ /**
848
+ * The primary (first) transport — the one `dispatch` prefers when no `preferId` is pinned. A
849
+ * {@link RemoteWorkflowExecutor} built by `engine.remote()` rides it (it needs a single
850
+ * `dispatchWorkflowTask`/`onDecision` Transport, not the whole failover pool). Throws if the pool
851
+ * is empty — there is nothing to dispatch a remote workflow over.
852
+ */
853
+ get primary() {
854
+ const first = this.transports[0];
855
+ if (!first) {
856
+ throw new Error("no transport configured \u2014 engine.remote() needs a transport (or transports)");
857
+ }
858
+ return first.transport;
859
+ }
860
+ /** Register the engine's result/heartbeat/step-event handlers on EVERY transport — a result can come
861
+ * back on whichever one delivered the task, so failover stays symmetric. `onStepEvent` is wired only
862
+ * on transports that carry streamed workflow step lifecycle (BullMQ); others simply skip it. */
863
+ bind(onResult, onHeartbeat, onStepEvent, onDecision) {
864
+ for (const { transport } of this.transports) {
865
+ transport.onResult(onResult);
866
+ transport.onHeartbeat(onHeartbeat);
867
+ if (onStepEvent && transport.onStepEvent) {
868
+ transport.onStepEvent(onStepEvent);
869
+ }
870
+ if (onDecision && transport.onDecision) {
871
+ transport.onDecision(onDecision);
872
+ }
873
+ }
874
+ }
875
+ /**
876
+ * Dispatch `task` over the pool: try the preferred (or first) transport, fail over to the next on
877
+ * a dispatch error, and stamp the task with the id of the transport that accepted it (so a worker
878
+ * replies on the matching one). Throws if every transport fails.
879
+ */
880
+ async dispatch(task, preferId) {
881
+ let lastErr;
882
+ for (const { id, transport } of this.ordered(preferId)) {
883
+ try {
884
+ await transport.dispatch({
885
+ ...task,
886
+ transport: id
887
+ });
888
+ return;
889
+ } catch (err) {
890
+ lastErr = err;
891
+ }
892
+ }
893
+ throw lastErr ?? new Error("no transport accepted the dispatch");
894
+ }
895
+ /** Worker-health for `group`, merged across every transport that can report it (a group's queue
896
+ * and its workers may live on any pinned transport). Undefined when no transport implements
897
+ * `groupHealth` (e.g. a pure in-process transport — nothing to introspect). */
898
+ async groupHealth(group) {
899
+ const reports = [];
900
+ for (const { transport } of this.transports) {
901
+ if (transport.groupHealth) reports.push(await transport.groupHealth(group));
902
+ }
903
+ if (reports.length === 0) return void 0;
904
+ return {
905
+ group,
906
+ depth: reports.reduce((sum, r) => sum + r.depth, 0),
907
+ liveWorkers: reports.flatMap((r) => r.liveWorkers)
908
+ };
909
+ }
910
+ /**
911
+ * Register a control-plane `start-run` consumer on every transport that carries the channel. Only
912
+ * control-plane-side transports implement {@link Transport.onStartRun}; a transport without it is
913
+ * skipped, so a plain worker/in-process pool is a no-op. Mirrors {@link bind}'s per-transport wiring.
914
+ */
915
+ onStartRun(handler) {
916
+ for (const { transport } of this.transports) {
917
+ transport.onStartRun?.(handler);
918
+ }
919
+ }
920
+ /** Distinct worker groups with a live heartbeat, merged across every transport that can report it. */
921
+ async listWorkerGroups() {
922
+ const groups = /* @__PURE__ */ new Set();
923
+ for (const { transport } of this.transports) {
924
+ if (transport.listWorkerGroups) {
925
+ for (const g of await transport.listWorkerGroups()) groups.add(g);
926
+ }
927
+ }
928
+ return [
929
+ ...groups
930
+ ];
931
+ }
932
+ /**
933
+ * Propagate the engine's `namespace` to every transport that partitions by it — so the same
934
+ * namespace that scopes the store also scopes each transport's queues/keys. A transport that
935
+ * doesn't partition (no `useNamespace`) is skipped. Idempotent; a transport given an explicit
936
+ * namespace at construction ignores this (see {@link Transport.useNamespace}).
937
+ */
938
+ useNamespace(namespace) {
939
+ for (const { transport } of this.transports) {
940
+ transport.useNamespace?.(namespace);
941
+ }
942
+ }
943
+ /** Pinned `preferId` first, then the rest (failover order). */
944
+ ordered(preferId) {
945
+ if (!preferId) return this.transports;
946
+ const pref = this.transports.filter((t) => t.id === preferId);
947
+ if (pref.length === 0) throw new Error(`transport "${preferId}" is not registered`);
948
+ return [
949
+ ...pref,
950
+ ...this.transports.filter((t) => t.id !== preferId)
951
+ ];
952
+ }
953
+ };
954
+
955
+ // src/completion.ts
956
+ function unwrapCompletion(payload, label) {
957
+ const c = payload;
958
+ if (c && typeof c === "object" && "ok" in c && c.ok === false) {
959
+ throw new FatalError(`${label} failed: ${c.error}`);
960
+ }
961
+ return c?.value;
962
+ }
963
+ __name(unwrapCompletion, "unwrapCompletion");
964
+
965
+ // src/workflow-ref.ts
966
+ var WORKFLOW_NAME_KEY = Symbol.for("nestjs-durable:workflow-name");
967
+ function workflowName(ref) {
968
+ if (typeof ref === "string") return ref;
969
+ const name = ref[WORKFLOW_NAME_KEY];
970
+ if (!name) {
971
+ throw new Error(`workflow class ${ref.name} has no registered name \u2014 is it decorated with @Workflow({ name })?`);
972
+ }
973
+ return name;
974
+ }
975
+ __name(workflowName, "workflowName");
976
+
977
+ // src/workflow-ctx.ts
978
+ function normalizeChildOptions(options) {
979
+ return typeof options === "string" ? {
980
+ childId: options
981
+ } : options ?? {};
982
+ }
983
+ __name(normalizeChildOptions, "normalizeChildOptions");
984
+ var Position = class Position2 {
985
+ static {
986
+ __name(this, "Position");
987
+ }
988
+ seq = -1;
989
+ next() {
990
+ this.seq += 1;
991
+ return this.seq;
992
+ }
993
+ rewind() {
994
+ this.seq -= 1;
995
+ }
996
+ };
997
+ function createWorkflowCtx(host, runId, compensations, workflow = "") {
998
+ const { store, replay } = host;
999
+ const pos = new Position();
1000
+ const readCheckpoint = /* @__PURE__ */ __name((seq) => {
1001
+ const hit = replay?.get(seq);
1002
+ if (hit !== void 0) return hit;
1003
+ return store.getCheckpoint(runId, seq);
1004
+ }, "readCheckpoint");
1005
+ const writeCheckpoint = /* @__PURE__ */ __name(async (cp) => {
1006
+ await store.saveCheckpoint(cp);
1007
+ replay?.set(cp.seq, cp);
1008
+ }, "writeCheckpoint");
1009
+ const step = /* @__PURE__ */ __name(async (name, fn, options) => {
1010
+ const current = pos.next();
1011
+ const existing = await readCheckpoint(current);
1012
+ if (existing && existing.name !== name) {
1013
+ throw new NonDeterminismError(runId, current, name, existing.name);
1014
+ }
1015
+ if (existing && existing.status === "completed") {
1016
+ if (options?.compensate) compensations.push({
1017
+ name,
1018
+ fn: options.compensate
1019
+ });
1020
+ return existing.output;
1021
+ }
1022
+ const maxAttempts = Math.max(1, options?.retries ?? 1);
1023
+ const startedAt = /* @__PURE__ */ new Date();
1024
+ await host.startStep({
1025
+ runId,
1026
+ seq: current,
1027
+ name,
1028
+ kind: "local",
1029
+ attempts: 1,
1030
+ enqueuedAt: startedAt,
1031
+ startedAt
1032
+ });
1033
+ for (let attempt = 1; ; attempt += 1) {
1034
+ const events = [];
1035
+ try {
1036
+ const invocation = {
1037
+ runId,
1038
+ workflow,
1039
+ stepName: name,
1040
+ seq: current,
1041
+ attempt
1042
+ };
1043
+ const body = /* @__PURE__ */ __name(() => fn(createStepLogger(events, host.clock)), "body");
1044
+ const output = host.interceptStep ? await host.interceptStep(invocation, body) : await body();
1045
+ await host.completeStep({
1046
+ runId,
1047
+ seq: current,
1048
+ name,
1049
+ kind: "local",
1050
+ output,
1051
+ events,
1052
+ attempts: attempt,
1053
+ enqueuedAt: startedAt,
1054
+ startedAt
1055
+ });
1056
+ if (options?.compensate) compensations.push({
1057
+ name,
1058
+ fn: options.compensate
1059
+ });
1060
+ return output;
1061
+ } catch (err) {
1062
+ if (err instanceof FatalError || attempt >= maxAttempts) {
1063
+ await host.failStep({
1064
+ runId,
1065
+ seq: current,
1066
+ name,
1067
+ kind: "local",
1068
+ error: {
1069
+ message: err instanceof Error ? err.message : String(err),
1070
+ stack: err instanceof Error ? err.stack : void 0
1071
+ },
1072
+ events,
1073
+ attempts: attempt,
1074
+ enqueuedAt: startedAt,
1075
+ startedAt
1076
+ });
1077
+ throw err;
1078
+ }
1079
+ const wait = backoffDelay(attempt, options);
1080
+ if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));
1081
+ }
1082
+ }
1083
+ }, "step");
1084
+ const transaction = /* @__PURE__ */ __name(async (name, fn) => {
1085
+ if (!store.transaction) {
1086
+ throw new Error("ctx.transaction needs a store that supports transactions (the SQL adapters do). Use ctx.step for non-transactional work.");
1087
+ }
1088
+ const current = pos.next();
1089
+ const existing = await readCheckpoint(current);
1090
+ if (existing && existing.name !== name) {
1091
+ throw new NonDeterminismError(runId, current, name, existing.name);
1092
+ }
1093
+ if (existing && existing.status === "completed") return existing.output;
1094
+ return store.transaction(async (tx) => {
1095
+ const output = await fn(tx.raw);
1096
+ const cp = instantCheckpoint({
1097
+ runId,
1098
+ seq: current,
1099
+ name,
1100
+ kind: "local",
1101
+ output
1102
+ });
1103
+ await tx.saveCheckpoint(cp);
1104
+ replay?.set(current, cp);
1105
+ return output;
1106
+ });
1107
+ }, "transaction");
1108
+ const suspendUntil = /* @__PURE__ */ __name(async (wakeAt) => {
1109
+ const current = pos.next();
1110
+ const now2 = host.clock();
1111
+ const existing = await readCheckpoint(current);
1112
+ if (existing) {
1113
+ if (now2 >= (existing.wakeAt ?? 0)) return;
1114
+ throw new WorkflowSuspended(existing.wakeAt ?? now2);
1115
+ }
1116
+ const at = wakeAt();
1117
+ await writeCheckpoint(instantCheckpoint({
1118
+ runId,
1119
+ seq: current,
1120
+ name: "sleep",
1121
+ kind: "sleep",
1122
+ wakeAt: at
1123
+ }));
1124
+ throw new WorkflowSuspended(at);
1125
+ }, "suspendUntil");
1126
+ const sleep = /* @__PURE__ */ __name((duration) => suspendUntil(() => host.clock() + parseDuration(duration)), "sleep");
1127
+ const sleepUntil = /* @__PURE__ */ __name((when) => suspendUntil(() => typeof when === "number" ? when : when.getTime()), "sleepUntil");
1128
+ const continueAsNew = /* @__PURE__ */ __name((input) => {
1129
+ throw new ContinueAsNew(input);
1130
+ }, "continueAsNew");
1131
+ const consumeBuffered = /* @__PURE__ */ __name(async (token, seq) => {
1132
+ const buffered = await store.takeBufferedSignal(token);
1133
+ if (!buffered) return null;
1134
+ await writeCheckpoint(instantCheckpoint({
1135
+ runId,
1136
+ seq,
1137
+ name: `signal:${token}`,
1138
+ kind: "signal",
1139
+ output: buffered.payload
1140
+ }));
1141
+ return {
1142
+ value: buffered.payload
1143
+ };
1144
+ }, "consumeBuffered");
1145
+ const waitForSignal = /* @__PURE__ */ __name(async (token, opts) => {
1146
+ if (opts?.timeoutMs == null) {
1147
+ const current = pos.next();
1148
+ const existing = await readCheckpoint(current);
1149
+ if (existing && existing.status === "completed") return existing.output;
1150
+ const buffered2 = await consumeBuffered(token, current);
1151
+ if (buffered2) return buffered2.value;
1152
+ await store.putSignalWaiter({
1153
+ token,
1154
+ runId,
1155
+ seq: current
1156
+ });
1157
+ throw new WorkflowSuspended();
1158
+ }
1159
+ const timeoutMs = opts.timeoutMs;
1160
+ const deadlineSeq = pos.next();
1161
+ const waitSeq = pos.next();
1162
+ const recorded = await readCheckpoint(deadlineSeq);
1163
+ const deadline = recorded?.wakeAt ?? host.clock() + timeoutMs;
1164
+ if (!recorded) {
1165
+ await writeCheckpoint(instantCheckpoint({
1166
+ runId,
1167
+ seq: deadlineSeq,
1168
+ name: `timeout:${token}`,
1169
+ kind: "sleep",
1170
+ wakeAt: deadline
1171
+ }));
1172
+ }
1173
+ const waited = await readCheckpoint(waitSeq);
1174
+ if (waited && waited.status === "completed") return waited.output;
1175
+ const buffered = await consumeBuffered(token, waitSeq);
1176
+ if (buffered) return buffered.value;
1177
+ if (host.clock() >= deadline) {
1178
+ await store.takeSignalWaiter(token).catch(() => void 0);
1179
+ throw new SignalTimeoutError(token, timeoutMs);
1180
+ }
1181
+ await store.putSignalWaiter({
1182
+ token,
1183
+ runId,
1184
+ seq: waitSeq
1185
+ });
1186
+ throw new WorkflowSuspended(deadline);
1187
+ }, "waitForSignal");
1188
+ const waitForEvent = /* @__PURE__ */ __name(async (name, opts) => {
1189
+ if (opts?.timeoutMs == null) {
1190
+ const current = pos.next();
1191
+ const token2 = eventToken(name, opts?.match, runId, current);
1192
+ const existing = await readCheckpoint(current);
1193
+ if (existing && existing.status === "completed") return existing.output;
1194
+ await store.putSignalWaiter({
1195
+ token: token2,
1196
+ runId,
1197
+ seq: current
1198
+ });
1199
+ throw new WorkflowSuspended();
1200
+ }
1201
+ const timeoutMs = opts.timeoutMs;
1202
+ const deadlineSeq = pos.next();
1203
+ const waitSeq = pos.next();
1204
+ const token = eventToken(name, opts.match, runId, waitSeq);
1205
+ const recorded = await readCheckpoint(deadlineSeq);
1206
+ const deadline = recorded?.wakeAt ?? host.clock() + timeoutMs;
1207
+ if (!recorded) {
1208
+ await writeCheckpoint(instantCheckpoint({
1209
+ runId,
1210
+ seq: deadlineSeq,
1211
+ name: `timeout:event:${name}`,
1212
+ kind: "sleep",
1213
+ wakeAt: deadline
1214
+ }));
1215
+ }
1216
+ const waited = await readCheckpoint(waitSeq);
1217
+ if (waited && waited.status === "completed") return waited.output;
1218
+ if (host.clock() >= deadline) {
1219
+ await store.takeSignalWaiter(token).catch(() => void 0);
1220
+ throw new SignalTimeoutError(`event:${name}`, timeoutMs);
1221
+ }
1222
+ await store.putSignalWaiter({
1223
+ token,
1224
+ runId,
1225
+ seq: waitSeq
1226
+ });
1227
+ throw new WorkflowSuspended(deadline);
1228
+ }, "waitForEvent");
1229
+ const task = /* @__PURE__ */ __name(async (name, dispatch, options) => {
1230
+ await step(`task:dispatch:${name}`, dispatch, options);
1231
+ return unwrapCompletion(await waitForSignal(`task:${runId}:${name}`), `task "${name}"`);
1232
+ }, "task");
1233
+ const child = /* @__PURE__ */ __name(async (workflow2, input, options) => {
1234
+ const { childId, priority } = normalizeChildOptions(options);
1235
+ const current = pos.next();
1236
+ const id = childId ?? `${runId}.child.${current}`;
1237
+ const existing = await readCheckpoint(current);
1238
+ if (existing && existing.status === "completed") {
1239
+ return unwrapCompletion(existing.output, `child "${id}"`);
1240
+ }
1241
+ await store.putSignalWaiter({
1242
+ token: `child:${id}`,
1243
+ runId,
1244
+ seq: current
1245
+ });
1246
+ if (!await store.getRun(id)) host.startChild(workflowName(workflow2), input, id, priority);
1247
+ if (!existing) {
1248
+ await writeCheckpoint(instantCheckpoint({
1249
+ runId,
1250
+ seq: current,
1251
+ name: `signal:child:${id}`,
1252
+ kind: "signal",
1253
+ status: "running"
1254
+ }));
1255
+ }
1256
+ throw new WorkflowSuspended();
1257
+ }, "child");
1258
+ const all = /* @__PURE__ */ __name(async (workflow2, inputs, opts) => {
1259
+ if (inputs.length === 0) return [];
1260
+ const mode = opts?.mode ?? "waitAll";
1261
+ const name = workflowName(workflow2);
1262
+ const positions = inputs.map(() => pos.next());
1263
+ const group = `all:${positions[0]}`;
1264
+ const id = /* @__PURE__ */ __name((i) => `${runId}.all.${positions[0]}.${i}`, "id");
1265
+ const existing = await Promise.all(positions.map((seq) => readCheckpoint(seq)));
1266
+ if (mode === "failFast") {
1267
+ for (let i = 0; i < inputs.length; i += 1) {
1268
+ const cp = existing[i];
1269
+ const c = cp?.status === "completed" ? cp.output : null;
1270
+ if (c && c.ok === false) {
1271
+ throw new GatherError([
1272
+ {
1273
+ index: i,
1274
+ id: id(i),
1275
+ error: c.error ?? "unknown"
1276
+ }
1277
+ ], inputs.length);
1278
+ }
1279
+ }
1280
+ }
1281
+ let pending = false;
1282
+ for (let i = 0; i < inputs.length; i += 1) {
1283
+ const cp = existing[i];
1284
+ if (cp?.status === "completed") continue;
1285
+ pending = true;
1286
+ const seq = positions[i];
1287
+ const childId = id(i);
1288
+ await store.putSignalWaiter({
1289
+ token: `child:${childId}`,
1290
+ runId,
1291
+ seq,
1292
+ parallelGroup: group
1293
+ });
1294
+ if (!await store.getRun(childId)) host.startChild(name, inputs[i], childId);
1295
+ if (!cp) {
1296
+ await writeCheckpoint(instantCheckpoint({
1297
+ runId,
1298
+ seq,
1299
+ name: `signal:child:${childId}`,
1300
+ kind: "signal",
1301
+ status: "running",
1302
+ parallelGroup: group
1303
+ }));
1304
+ }
1305
+ }
1306
+ if (pending) throw new WorkflowSuspended();
1307
+ const outputs = [];
1308
+ const failures = [];
1309
+ for (let i = 0; i < inputs.length; i += 1) {
1310
+ const c = existing[i]?.output;
1311
+ if (c && typeof c === "object" && "ok" in c && c.ok === false) {
1312
+ failures.push({
1313
+ index: i,
1314
+ id: id(i),
1315
+ error: c.error ?? "unknown"
1316
+ });
1317
+ outputs.push(void 0);
1318
+ } else {
1319
+ outputs.push(c?.value);
1320
+ }
1321
+ }
1322
+ if (failures.length > 0) throw new GatherError(failures, inputs.length);
1323
+ return outputs;
1324
+ }, "all");
1325
+ const startChild = /* @__PURE__ */ __name(async (workflow2, input, options) => {
1326
+ const { childId, priority } = normalizeChildOptions(options);
1327
+ const current = pos.next();
1328
+ const id = childId ?? `${runId}.child.${current}`;
1329
+ const existing = await readCheckpoint(current);
1330
+ if (existing && existing.status === "completed") return existing.output;
1331
+ if (!await store.getRun(id)) host.startChild(workflowName(workflow2), input, id, priority);
1332
+ await writeCheckpoint(instantCheckpoint({
1333
+ runId,
1334
+ seq: current,
1335
+ name: `spawn:${id}`,
1336
+ kind: "local",
1337
+ output: id
1338
+ }));
1339
+ return id;
1340
+ }, "startChild");
1341
+ const callEntity = /* @__PURE__ */ __name(async (name, key, op, arg) => {
1342
+ const current = pos.next();
1343
+ const existing = await readCheckpoint(current);
1344
+ if (existing && existing.status === "completed") return existing.output;
1345
+ const reply = `entityreply:${runId}:${current}`;
1346
+ await store.putSignalWaiter({
1347
+ token: reply,
1348
+ runId,
1349
+ seq: current
1350
+ });
1351
+ host.signalEntity?.(name, key, op, arg, reply);
1352
+ throw new WorkflowSuspended();
1353
+ }, "callEntity");
1354
+ const signalEntity = /* @__PURE__ */ __name(async (name, key, op, arg) => {
1355
+ const current = pos.next();
1356
+ const existing = await readCheckpoint(current);
1357
+ if (existing && existing.status === "completed") return;
1358
+ host.signalEntity?.(name, key, op, arg);
1359
+ await writeCheckpoint(instantCheckpoint({
1360
+ runId,
1361
+ seq: current,
1362
+ name: `entitysig:${name}:${key}`,
1363
+ kind: "local"
1364
+ }));
1365
+ }, "signalEntity");
1366
+ const breakpoint = /* @__PURE__ */ __name(async (label) => {
1367
+ const current = pos.next();
1368
+ const existing = await readCheckpoint(current);
1369
+ if (existing && existing.status === "completed") return;
1370
+ if (!existing) {
1371
+ await writeCheckpoint(instantCheckpoint({
1372
+ runId,
1373
+ seq: current,
1374
+ name: label ? `breakpoint:${label}` : "breakpoint",
1375
+ kind: "signal",
1376
+ status: "pending"
1377
+ }));
1378
+ await store.putSignalWaiter({
1379
+ token: breakpointToken(runId, current),
1380
+ runId,
1381
+ seq: current
1382
+ });
1383
+ }
1384
+ throw new WorkflowSuspended();
1385
+ }, "breakpoint");
1386
+ const patched = /* @__PURE__ */ __name(async (id) => {
1387
+ const marker = `patch:${id}`;
1388
+ const current = pos.next();
1389
+ const existing = await readCheckpoint(current);
1390
+ if (existing) {
1391
+ if (existing.name === marker) return true;
1392
+ if (existing.name.startsWith("patch:")) {
1393
+ throw new NonDeterminismError(runId, current, marker, existing.name);
1394
+ }
1395
+ pos.rewind();
1396
+ return false;
1397
+ }
1398
+ await writeCheckpoint(instantCheckpoint({
1399
+ runId,
1400
+ seq: current,
1401
+ name: marker,
1402
+ kind: "local",
1403
+ output: true
1404
+ }));
1405
+ return true;
1406
+ }, "patched");
1407
+ const onUpdate = /* @__PURE__ */ __name((name, opts) => waitForSignal(`update:${runId}:${name}`, opts), "onUpdate");
1408
+ const setEvent = /* @__PURE__ */ __name(async (key, value) => {
1409
+ const current = pos.next();
1410
+ const name = `event:${key}`;
1411
+ const existing = await readCheckpoint(current);
1412
+ if (existing && existing.name !== name) {
1413
+ throw new NonDeterminismError(runId, current, name, existing.name);
1414
+ }
1415
+ if (existing && existing.status === "completed") return;
1416
+ await writeCheckpoint(instantCheckpoint({
1417
+ runId,
1418
+ seq: current,
1419
+ name,
1420
+ kind: "local",
1421
+ output: value
1422
+ }));
1423
+ }, "setEvent");
1424
+ const webhook = /* @__PURE__ */ __name(() => {
1425
+ const current = pos.next();
1426
+ const token = `wh:${runId}:${current}`;
1427
+ const wait = /* @__PURE__ */ __name(async () => {
1428
+ const existing = await readCheckpoint(current);
1429
+ if (existing && existing.status === "completed") return existing.output;
1430
+ await store.putSignalWaiter({
1431
+ token,
1432
+ runId,
1433
+ seq: current
1434
+ });
1435
+ throw new WorkflowSuspended();
1436
+ }, "wait");
1437
+ return {
1438
+ token,
1439
+ url: host.webhookUrl?.(token),
1440
+ wait
1441
+ };
1442
+ }, "webhook");
1443
+ const now = /* @__PURE__ */ __name(() => step("now", async () => host.clock()), "now");
1444
+ const random = /* @__PURE__ */ __name(() => step("random", async () => Math.random()), "random");
1445
+ const uuid = /* @__PURE__ */ __name(() => step("uuid", async () => globalThis.crypto.randomUUID()), "uuid");
1446
+ const upsertSearchAttributes = /* @__PURE__ */ __name(async (attrs) => {
1447
+ const current = pos.next();
1448
+ const existing = await readCheckpoint(current);
1449
+ if (existing) {
1450
+ if (existing.name !== "searchAttributes") {
1451
+ throw new NonDeterminismError(runId, current, "searchAttributes", existing.name);
1452
+ }
1453
+ return;
1454
+ }
1455
+ await host.upsertSearchAttributes(runId, attrs);
1456
+ await writeCheckpoint(instantCheckpoint({
1457
+ runId,
1458
+ seq: current,
1459
+ name: "searchAttributes",
1460
+ kind: "local",
1461
+ output: attrs
1462
+ }));
1463
+ }, "upsertSearchAttributes");
1464
+ return {
1465
+ runId,
1466
+ step,
1467
+ upsertSearchAttributes,
1468
+ transaction,
1469
+ callEntity,
1470
+ signalEntity,
1471
+ sleep,
1472
+ sleepUntil,
1473
+ continueAsNew,
1474
+ waitForSignal,
1475
+ waitForEvent,
1476
+ task,
1477
+ child,
1478
+ all,
1479
+ startChild,
1480
+ breakpoint,
1481
+ webhook,
1482
+ setEvent,
1483
+ onUpdate,
1484
+ patched,
1485
+ now,
1486
+ random,
1487
+ uuid,
1488
+ call: /* @__PURE__ */ __name((remote, input, opts) => host.callRemote(runId, pos.next(), remote, input, opts?.queue, opts?.transport, {
1489
+ priority: opts?.priority,
1490
+ fairnessKey: opts?.fairnessKey
1491
+ }), "call")
1492
+ };
1493
+ }
1494
+ __name(createWorkflowCtx, "createWorkflowCtx");
1495
+
1496
+ // src/engine.ts
1497
+ function mergeTags(staticTags, runTags) {
1498
+ if (!staticTags?.length && !runTags?.length) return void 0;
1499
+ return [
1500
+ .../* @__PURE__ */ new Set([
1501
+ ...staticTags ?? [],
1502
+ ...runTags ?? []
1503
+ ])
1504
+ ];
1505
+ }
1506
+ __name(mergeTags, "mergeTags");
1507
+ var BREAKPOINT = "breakpoint";
1508
+ var isBreakpoint = /* @__PURE__ */ __name((cp) => cp.status === "pending" && cp.name.startsWith(BREAKPOINT), "isBreakpoint");
1509
+ var versionKey = /* @__PURE__ */ __name((name, version) => `${name}@${version}`, "versionKey");
1510
+ function nextContinuationId(runId) {
1511
+ const m = runId.match(/^(.*)~(\d+)$/);
1512
+ return m ? `${m[1]}~${Number(m[2]) + 1}` : `${runId}~1`;
1513
+ }
1514
+ __name(nextContinuationId, "nextContinuationId");
1515
+ function isNewerVersion(a, b) {
1516
+ const na = Number(a);
1517
+ const nb = Number(b);
1518
+ if (!Number.isNaN(na) && !Number.isNaN(nb)) return na > nb;
1519
+ return a.localeCompare(b, void 0, {
1520
+ numeric: true
1521
+ }) > 0;
1522
+ }
1523
+ __name(isNewerVersion, "isNewerVersion");
1524
+ var NamespaceMismatch = class NamespaceMismatch2 extends Error {
1525
+ static {
1526
+ __name(this, "NamespaceMismatch");
1527
+ }
1528
+ constructor() {
1529
+ super("namespace-mismatch");
1530
+ }
1531
+ };
1532
+ var WorkflowEngine = class {
1533
+ static {
1534
+ __name(this, "WorkflowEngine");
1535
+ }
1536
+ store;
1537
+ /** Ordered transport pool (dispatch + failover). Empty = no remote steps. */
1538
+ pool;
1539
+ controlPlane;
1540
+ clock;
1541
+ instanceId;
1542
+ namespace;
1543
+ leaseMs;
1544
+ maxRecoveryAttempts;
1545
+ remoteAdvanceSilenceMs;
1546
+ webhookUrl;
1547
+ traceparent;
1548
+ context;
1549
+ /** Establish the originating context ambiently around a local step body (see {@link WorkflowEngineDeps.rehydrate}). Default passthrough. */
1550
+ rehydrate;
1551
+ compensationRetries;
1552
+ /** Persist a `running` checkpoint at the start of a local step body (see {@link WorkflowEngineDeps.trackStepStart}). */
1553
+ trackStepStart;
1554
+ /** Where a freshly-started run executes — in-process by default (see {@link RunDispatcher}). */
1555
+ runDispatcher;
1556
+ /** Per-key serialization for singleton workflows (admission, back-pressure, notify-on-release). */
1557
+ singletons;
1558
+ /** Every registered workflow, keyed by `name@version` — so old versions stay runnable. */
1559
+ workflows = /* @__PURE__ */ new Map();
1560
+ /** The newest registered version per workflow name — used to `start` new runs. */
1561
+ latest = /* @__PURE__ */ new Map();
1562
+ /** Event name → workflow names started when that event is published (see `onEvent`). */
1563
+ eventTriggers = /* @__PURE__ */ new Map();
1564
+ /** Durable-entity subsystem (registers the `__entity` runner; see `registerEntity`). */
1565
+ entities;
1566
+ /** Event debounce/batch accumulators (register the `__evt_*` runners; see `accumulators.route`). */
1567
+ accumulators;
1568
+ /** In-flight remote steps awaiting a worker result, keyed by stepId. */
1569
+ pending = /* @__PURE__ */ new Map();
1570
+ /** "Reset the liveness timer" callbacks keyed by the beat's target — a stepId (in-flight remote step)
1571
+ * or a runId (in-flight remote workflow turn) — invoked when a matching heartbeat arrives. The two id
1572
+ * shapes don't collide in practice: a stepId is `${runId}:${seq}`, a run key is the bare runId. */
1573
+ heartbeatResets = /* @__PURE__ */ new Map();
1574
+ listeners = /* @__PURE__ */ new Set();
1575
+ /** Step interceptors (onion middleware around real local-step execution), first = outermost. */
1576
+ interceptors = [];
1577
+ /** Callbacks notified (on any instance) when a run is cancelled — for cooperative cancellation. */
1578
+ cancelListeners = /* @__PURE__ */ new Set();
1579
+ /** Callbacks notified when a run is enqueued elsewhere — for low-latency cross-pod dispatch. */
1580
+ enqueuedListeners = /* @__PURE__ */ new Set();
1581
+ /** Notified when a run is dead-lettered (moved to `dead`) — a hook for a DLQ handler. */
1582
+ deadListeners = /* @__PURE__ */ new Set();
1583
+ /** Validators gating `engine.update`, keyed by `<workflow>:<updateName>`. */
1584
+ updateValidators = /* @__PURE__ */ new Map();
1585
+ /** Runs being cancelled WITH saga compensation — see `cancel({ compensate: true })`. */
1586
+ cancelRequested = /* @__PURE__ */ new Set();
1587
+ /** Flow-control admission backend for remote steps (see {@link registerQueue}). */
1588
+ admission;
1589
+ /** Runs on THIS instance blocked on admission, by queue — woken early on a freed-slot signal. */
1590
+ queueWaiters = /* @__PURE__ */ new Map();
1591
+ /** Which queue a dispatched step took a slot from, by stepId — so the result can release it. */
1592
+ stepQueue = /* @__PURE__ */ new Map();
1593
+ /** Executions currently in flight, so a graceful shutdown can wait for them to settle. */
1594
+ inflight = /* @__PURE__ */ new Set();
1595
+ draining = false;
1596
+ /** When true, route an unregistered workflow to the live worker group of the same name. */
1597
+ remoteByConvention;
1598
+ constructor(deps) {
1599
+ this.store = deps.store;
1600
+ this.pool = new TransportPool(deps.transports ?? (deps.transport ? [
1601
+ {
1602
+ id: "default",
1603
+ transport: deps.transport
1604
+ }
1605
+ ] : []));
1606
+ this.controlPlane = deps.controlPlane;
1607
+ this.clock = deps.clock ?? Date.now;
1608
+ this.admission = deps.admission ?? new InMemoryAdmissionBackend(this.clock);
1609
+ this.admission.onFreed?.((queue) => this.wakeQueueWaiters(queue));
1610
+ this.instanceId = deps.instanceId ?? globalThis.crypto.randomUUID();
1611
+ this.namespace = deps.namespace;
1612
+ if (this.namespace !== void 0) {
1613
+ this.pool.useNamespace(this.namespace);
1614
+ }
1615
+ this.leaseMs = deps.leaseMs ?? 3e4;
1616
+ this.maxRecoveryAttempts = deps.maxRecoveryAttempts;
1617
+ this.remoteAdvanceSilenceMs = deps.remoteAdvanceSilenceMs;
1618
+ this.webhookUrl = deps.webhookUrl;
1619
+ this.traceparent = deps.traceparent;
1620
+ this.context = deps.context;
1621
+ this.rehydrate = deps.rehydrate ?? ((_carrier, fn) => fn());
1622
+ this.compensationRetries = Math.max(1, deps.compensationRetries ?? 1);
1623
+ this.trackStepStart = deps.trackStepStart ?? true;
1624
+ this.runDispatcher = deps.runDispatcher ?? {
1625
+ dispatch: /* @__PURE__ */ __name((runId) => queueMicrotask(() => void this.runOne(runId).catch(() => {
1626
+ })), "dispatch")
1627
+ };
1628
+ this.remoteByConvention = deps.remoteByConvention ?? false;
1629
+ this.singletons = new SingletonGate({
1630
+ store: this.store,
1631
+ clock: this.clock,
1632
+ dispatch: /* @__PURE__ */ __name((runId) => {
1633
+ this.runDispatcher.dispatch(runId);
1634
+ }, "dispatch"),
1635
+ configFor: /* @__PURE__ */ __name((run) => (this.workflows.get(versionKey(run.workflow, run.workflowVersion)) ?? this.latest.get(run.workflow))?.singleton, "configFor")
1636
+ });
1637
+ this.pool.bind(
1638
+ async (result) => {
1639
+ const waiter = this.pending.get(result.stepId);
1640
+ if (waiter) {
1641
+ this.pending.delete(result.stepId);
1642
+ if (result.status === "completed") {
1643
+ waiter.resolve({
1644
+ output: result.output,
1645
+ startedAt: result.startedAt,
1646
+ events: result.events
1647
+ });
1648
+ } else {
1649
+ waiter.reject(new RemoteStepError(result.error));
1650
+ }
1651
+ return;
1652
+ }
1653
+ await this.completeRemoteResult(result);
1654
+ },
1655
+ // A heartbeat resets the liveness window for whatever it targets: an in-flight long STEP (keyed
1656
+ // by stepId, see callRemote) or — when stepId is absent — the in-flight workflow TURN (keyed by
1657
+ // runId). For an INLINE-advance turn the reset is an in-memory callback; for a DISPATCH-suspend
1658
+ // turn there is no in-memory waiter, so a run-scoped beat rearms the suspended turn's durable
1659
+ // re-drive deadline (`wakeAt`) instead, keeping a live worker's turn from being re-dispatched.
1660
+ async (beat) => {
1661
+ const reset = this.heartbeatResets.get(beat.stepId ?? beat.runId);
1662
+ if (reset) {
1663
+ reset();
1664
+ return;
1665
+ }
1666
+ if (beat.stepId === void 0) await this.rearmDecisionDeadline(beat.runId);
1667
+ },
1668
+ // A remote workflow worker streams each local step's lifecycle (running → completed/failed) so
1669
+ // it's checkpointed live, not all-at-once when the long turn ends.
1670
+ async (event) => {
1671
+ await this.persistStepEvent(event);
1672
+ },
1673
+ // A workflow-turn DECISION delivered over the broker — applied durably (by run id) on whatever
1674
+ // instance consumes it, NOT correlated to an in-memory promise on the dispatcher. This is the
1675
+ // multi-instance fix: a point-to-point broker may hand the decision to a non-dispatching instance.
1676
+ async (decision) => {
1677
+ await this.completeRemoteDecision(decision);
1678
+ }
1679
+ );
1680
+ this.pool.onStartRun(async (message) => {
1681
+ await this.start(message.workflow, message.input, message.runId ?? globalThis.crypto.randomUUID(), {
1682
+ namespace: message.tenant,
1683
+ tags: message.tags
1684
+ });
1685
+ });
1686
+ this.controlPlane?.onControl((msg) => {
1687
+ if (msg.from === this.instanceId) return;
1688
+ if (msg.kind === "event") {
1689
+ this.deliver({
1690
+ ...msg.event,
1691
+ at: new Date(msg.event.at)
1692
+ });
1693
+ } else if (msg.kind === "cancel") {
1694
+ this.notifyCancelled(msg.runId);
1695
+ } else if (msg.kind === "enqueued") {
1696
+ for (const fn of this.enqueuedListeners) {
1697
+ try {
1698
+ fn(msg.runId);
1699
+ } catch {
1700
+ }
1701
+ }
1702
+ }
1703
+ });
1704
+ this.accumulators = new EventAccumulators(this);
1705
+ this.entities = new Entities(this);
1706
+ }
1707
+ /**
1708
+ * Register a **durable entity** (a virtual object): a keyed actor whose `handlers` run **serialized
1709
+ * per key** over **durable state**, exactly once. Drive it with `signalEntity` (fire) /
1710
+ * `ctx.callEntity` (call + await result) and read its state with `getEntityState`. See {@link Entities}.
1711
+ */
1712
+ registerEntity(name, config) {
1713
+ this.entities.register(name, config);
1714
+ }
1715
+ /** Send an operation to an entity (fire-and-forget). Ordered + exactly-once per key. */
1716
+ signalEntity(name, key, op, arg) {
1717
+ return this.entities.signal(name, key, op, arg);
1718
+ }
1719
+ /** Read an entity's current durable state (published after each op), or undefined if it has none yet. */
1720
+ getEntityState(name, key) {
1721
+ return this.entities.getState(name, key);
1722
+ }
1723
+ /**
1724
+ * Be notified when a run is enqueued on ANOTHER instance (via the control plane), so a worker can
1725
+ * pick it up at once — e.g. `engine.onEnqueued((runId) => engine.runOne(runId))`. Returns an
1726
+ * unsubscribe function. Only wire this on instances that should execute runs (workers).
1727
+ */
1728
+ onEnqueued(listener) {
1729
+ this.enqueuedListeners.add(listener);
1730
+ return () => this.enqueuedListeners.delete(listener);
1731
+ }
1732
+ /** Fire cooperative-cancellation listeners for `runId` (a worker bridge aborts in-flight work). */
1733
+ notifyCancelled(runId) {
1734
+ for (const fn of this.cancelListeners) {
1735
+ try {
1736
+ fn(runId);
1737
+ } catch {
1738
+ }
1739
+ }
1740
+ }
1741
+ /**
1742
+ * Register a workflow version. Register multiple versions of the same name to keep in-flight
1743
+ * runs working across a breaking change: old runs resume on the version they started on, new
1744
+ * runs start on the newest registered version.
1745
+ *
1746
+ * GROUP-SERVED (uniform dispatch, opt-in): pass `{ group, executor }` to have the engine DISPATCH
1747
+ * this workflow's turns to a worker `group` (via `executor.advance`) instead of running `fn`
1748
+ * inline — exactly as {@link registerRemote} does for a cross-SDK (e.g. Python) body, EXCEPT the
1749
+ * body is a TS `fn` the engine retains so an IN-APP worker on `group` can fetch it by name
1750
+ * ({@link workflowBody}) and run it. This is "one app, both roles": the same process owns the
1751
+ * engine AND consumes its own group. Recovery, timers, singleton, cancel and dead-lettering stay
1752
+ * engine concerns, identical to a remote run. OMIT `group`/`executor` (the default) to keep the
1753
+ * inline fast path — `fn` runs in-process and the run pays zero dispatch round-trips. The first
1754
+ * step toward routing every run through a group with no local/remote flag (Phase 3).
1755
+ */
1756
+ register(name, version, fn, opts) {
1757
+ if (opts?.group == null !== (opts?.executor == null)) {
1758
+ throw new Error(`workflow ${name}@${version}: register({ group, executor }) needs BOTH group and executor (or neither)`);
1759
+ }
1760
+ const registered = {
1761
+ name,
1762
+ version,
1763
+ fn,
1764
+ tags: opts?.tags,
1765
+ singleton: opts?.singleton,
1766
+ executionTimeoutMs: opts?.executionTimeout != null ? parseDuration(opts.executionTimeout) : void 0,
1767
+ validateInput: opts?.validateInput,
1768
+ onEvent: opts?.onEvent,
1769
+ eventBatch: opts?.eventBatch,
1770
+ // A real, retained in-process body — so `workflowBody` can hand it to an in-app worker, and so
1771
+ // it is NOT confused with the throwing stub `registerRemote` installs for a body-less remote.
1772
+ hasBody: true
1773
+ };
1774
+ if (opts?.group != null && opts?.executor != null) {
1775
+ registered.remote = {
1776
+ group: opts.group,
1777
+ executor: opts.executor
1778
+ };
1779
+ }
1780
+ this.workflows.set(versionKey(name, version), registered);
1781
+ const current = this.latest.get(name);
1782
+ if (!current || isNewerVersion(version, current.version)) this.latest.set(name, registered);
1783
+ for (const event of opts?.onEvent ?? []) {
1784
+ const subscribers = this.eventTriggers.get(event) ?? /* @__PURE__ */ new Set();
1785
+ subscribers.add(name);
1786
+ this.eventTriggers.set(event, subscribers);
1787
+ }
1788
+ }
1789
+ /**
1790
+ * The retained in-process body for `name@version`, for an IN-APP worker that consumes this engine's
1791
+ * own group to SERVE a group-served `register(..., { group, executor })` workflow (uniform dispatch):
1792
+ * the worker fetches the body by name when it picks up the dispatched {@link WorkflowTask}, replays
1793
+ * it, and returns the {@link WorkflowDecision}. `undefined` for an unregistered name or a body-less
1794
+ * remote (a `registerRemote` / synthesized child carries only a throwing stub, never handed out).
1795
+ */
1796
+ workflowBody(name, version) {
1797
+ const reg = this.workflows.get(versionKey(name, version));
1798
+ return reg?.hasBody ? reg.fn : void 0;
1799
+ }
1800
+ /**
1801
+ * Register a workflow whose body runs in another SDK (e.g. Python). The engine owns the run exactly
1802
+ * as for a TS workflow — it persists checkpoints, recovers, runs timers — but advances it by handing
1803
+ * the run's history to `executor` (which dispatches a {@link WorkflowTask} to the worker) and applying
1804
+ * the {@link WorkflowDecision} the worker's replay returns. The worker never touches the store.
1805
+ */
1806
+ registerRemote(name, version, opts) {
1807
+ const registered = {
1808
+ name,
1809
+ version,
1810
+ // A remote workflow has no in-process body; execute() branches on `remote` before this is read.
1811
+ fn: /* @__PURE__ */ __name(() => {
1812
+ throw new Error(`workflow ${name} is remote \u2014 it has no in-process body`);
1813
+ }, "fn"),
1814
+ tags: opts.tags,
1815
+ singleton: opts.singleton,
1816
+ executionTimeoutMs: opts.executionTimeout != null ? parseDuration(opts.executionTimeout) : void 0,
1817
+ validateInput: opts.validateInput,
1818
+ remote: {
1819
+ group: opts.group,
1820
+ executor: opts.executor
1821
+ }
1822
+ };
1823
+ this.workflows.set(versionKey(name, version), registered);
1824
+ const current = this.latest.get(name);
1825
+ if (!current || isNewerVersion(version, current.version)) this.latest.set(name, registered);
1826
+ }
1827
+ /**
1828
+ * The convenience form of {@link registerRemote}: register a workflow whose body runs on a worker
1829
+ * `group` (e.g. the Python `durable-worker`, or a separate TS worker), without hand-building a
1830
+ * {@link RemoteWorkflowExecutor}. It wires the standard broker executor — a `RemoteWorkflowExecutor`
1831
+ * over the engine's own transport, dispatching to `opts.group` — for you, so you write
1832
+ * `engine.remote('processing', { group: 'processing' })` instead of
1833
+ * `engine.registerRemote('processing', '1', { group: 'processing', executor: new RemoteWorkflowExecutor(transport, 'processing') })`.
1834
+ *
1835
+ * Defaults the version to `'1'`. All the other {@link registerRemote} options
1836
+ * (`tags` / `singleton` / `executionTimeout` / `validateInput`) pass straight through. Reach for the
1837
+ * low-level {@link registerRemote} when you need a custom {@link WorkflowExecutor} (a different
1838
+ * transport, a fixed `timeoutMs`, a polyglot stub) — `remote()` is the standard wiring on the rails.
1839
+ */
1840
+ remote(name, opts) {
1841
+ const { group, version, ...rest } = opts;
1842
+ const executor = new RemoteWorkflowExecutor(this.pool.primary, group);
1843
+ this.registerRemote(name, version ?? "1", {
1844
+ group,
1845
+ executor,
1846
+ ...rest
1847
+ });
1848
+ }
1849
+ /**
1850
+ * Register a flow-control queue referenced by `ctx.call(step, input, { queue })`. Caps concurrent
1851
+ * in-flight steps and/or the admission rate; blocked calls re-suspend and retry, so the limit is
1852
+ * durable. Per engine instance (see {@link QueueConfig}). Registering the same name replaces it.
1853
+ */
1854
+ registerQueue(config) {
1855
+ this.admission.register(config);
1856
+ }
1857
+ /** Subscribe to lifecycle events. Returns an unsubscribe function. */
1858
+ subscribe(listener) {
1859
+ this.listeners.add(listener);
1860
+ return () => this.listeners.delete(listener);
1861
+ }
1862
+ /**
1863
+ * Register a {@link StepInterceptor} — onion middleware run around the real execution of every
1864
+ * local `ctx.step` (timing, logging, tracing, error enrichment, context propagation). First
1865
+ * registered is outermost; interceptors fire only when a step executes, never on replay. Returns
1866
+ * an unsubscribe function.
1867
+ */
1868
+ use(interceptor) {
1869
+ this.interceptors.push(interceptor);
1870
+ return () => {
1871
+ const i = this.interceptors.indexOf(interceptor);
1872
+ if (i >= 0) this.interceptors.splice(i, 1);
1873
+ };
1874
+ }
1875
+ /**
1876
+ * Fold the registered interceptors around a local step body (identity when there are none), then
1877
+ * run the whole thing inside the re-hydrated originating context. The carrier is read at execution
1878
+ * time from {@link context} — the SAME reader stamped on dispatched remote tasks — so a local step
1879
+ * sees the live tenant / user / trace ids ambiently (via the {@link rehydrate} bridge). Default
1880
+ * `rehydrate` is a passthrough, so this is byte-identical to a bare body call when unwired.
1881
+ */
1882
+ interceptStep(invocation, body) {
1883
+ const carrier = this.context?.();
1884
+ const run = /* @__PURE__ */ __name(() => {
1885
+ if (this.interceptors.length === 0) return body();
1886
+ const chain = this.interceptors.reduceRight((next, interceptor) => () => interceptor(invocation, next), body);
1887
+ return chain();
1888
+ }, "run");
1889
+ return this.rehydrate(carrier, run);
1890
+ }
1891
+ /**
1892
+ * Be notified when a run is cancelled — on ANY instance, via the transport control plane. A
1893
+ * worker bridge can use this for cooperative cancellation: abort the in-flight work for `runId`
1894
+ * instead of finishing it just to have the result discarded. Returns an unsubscribe function.
1895
+ */
1896
+ onCancel(listener) {
1897
+ this.cancelListeners.add(listener);
1898
+ return () => this.cancelListeners.delete(listener);
1899
+ }
1900
+ /**
1901
+ * Be notified when a run is **dead-lettered** — moved to `dead` after exceeding
1902
+ * `maxRecoveryAttempts`. The listener receives the dead run (status `dead`, with its error), so a
1903
+ * DLQ handler can do something other than just leaving it parked: alert, push to a real queue, or
1904
+ * start a dead-letter workflow (e.g. `engine.onDead((run) => engine.start('pipeline-dlq', run, ...))`).
1905
+ * Returns an unsubscribe function.
1906
+ */
1907
+ onDead(listener) {
1908
+ this.deadListeners.add(listener);
1909
+ return () => this.deadListeners.delete(listener);
1910
+ }
1911
+ notifyDead(run) {
1912
+ for (const fn of this.deadListeners) {
1913
+ try {
1914
+ fn(run);
1915
+ } catch {
1916
+ }
1917
+ }
1918
+ }
1919
+ /** Emit a locally-produced lifecycle event: deliver to subscribers AND broadcast it on the
1920
+ * control plane so other instances (e.g. a dashboard pod) can live-tail this run. */
1921
+ emit(event) {
1922
+ const full = {
1923
+ ...event,
1924
+ at: /* @__PURE__ */ new Date()
1925
+ };
1926
+ this.deliver(full);
1927
+ if (this.controlPlane) {
1928
+ void this.controlPlane.publishControl({
1929
+ kind: "event",
1930
+ event: full,
1931
+ from: this.instanceId
1932
+ }).catch(() => {
1933
+ });
1934
+ }
1935
+ }
1936
+ /** Deliver an event to local subscribers only (no re-broadcast) — used for both locally-produced
1937
+ * events and ones received from the control plane, so an event shows up once on every instance. */
1938
+ deliver(event) {
1939
+ for (const listener of this.listeners) {
1940
+ try {
1941
+ listener(event);
1942
+ } catch {
1943
+ }
1944
+ }
1945
+ }
1946
+ async start(workflow, input, runId, opts) {
1947
+ const name = workflowName(workflow);
1948
+ let registered = this.latest.get(name);
1949
+ if (!registered) {
1950
+ const ancestor = await this.findRemoteAncestor(runId);
1951
+ if (ancestor) registered = this.synthesizeRemoteChild(name, ancestor.version, ancestor);
1952
+ }
1953
+ if (!registered) {
1954
+ const conventionRun = {
1955
+ id: runId,
1956
+ workflow: name,
1957
+ workflowVersion: "1",
1958
+ status: "pending",
1959
+ // Stamp the namespace the REAL run will carry (:893) so convention routing resolves the same
1960
+ // tenant-suffixed group the run will dispatch to — an operator starting a tenant's run via the
1961
+ // `onStartRun` wire (opts.namespace = tenant) must find the live `<workflow>@<tenant>` group,
1962
+ // not the bare group. Without this the start-run entry path can't reach a suffixed-only worker.
1963
+ namespace: opts?.namespace ?? this.namespace,
1964
+ input,
1965
+ createdAt: /* @__PURE__ */ new Date(),
1966
+ updatedAt: /* @__PURE__ */ new Date()
1967
+ };
1968
+ registered = await this.resolveRemoteByConvention(conventionRun);
1969
+ }
1970
+ if (!registered) throw new Error(`workflow ${name} is not registered`);
1971
+ await registered.validateInput?.(input);
1972
+ const prior = await this.store.getRun(runId);
1973
+ if (prior) {
1974
+ return {
1975
+ runId,
1976
+ status: prior.status,
1977
+ output: prior.output,
1978
+ error: prior.error
1979
+ };
1980
+ }
1981
+ const now = /* @__PURE__ */ new Date();
1982
+ const tags = mergeTags(registered.tags, registered.singleton ? [
1983
+ ...opts?.tags ?? [],
1984
+ this.singletons.tag(registered.singleton, input)
1985
+ ] : opts?.tags);
1986
+ if (registered.singleton) {
1987
+ await this.singletons.assertCapacity(name, registered.singleton, input);
1988
+ }
1989
+ const run = {
1990
+ id: runId,
1991
+ workflow: name,
1992
+ workflowVersion: registered.version,
1993
+ status: "pending",
1994
+ namespace: opts?.namespace ?? this.namespace,
1995
+ input,
1996
+ tags,
1997
+ searchAttributes: opts?.searchAttributes,
1998
+ priority: opts?.priority,
1999
+ createdAt: now,
2000
+ updatedAt: now
2001
+ };
2002
+ await this.store.createRun(run);
2003
+ await this.runDispatcher.dispatch(runId);
2004
+ if (this.controlPlane) {
2005
+ void this.controlPlane.publishControl({
2006
+ kind: "enqueued",
2007
+ runId,
2008
+ from: this.instanceId
2009
+ }).catch(() => void 0);
2010
+ }
2011
+ return {
2012
+ runId,
2013
+ status: "pending"
2014
+ };
2015
+ }
2016
+ /** Read a run's current persisted state (or null if unknown). A thin pass-through to the store. */
2017
+ getRun(runId) {
2018
+ return this.store.getRun(runId);
2019
+ }
2020
+ async resume(runId) {
2021
+ const run = await this.store.getRun(runId);
2022
+ if (!run) throw new Error(`run ${runId} not found`);
2023
+ if (run.status === "cancelled" || run.status === "completed" || run.status === "dead") {
2024
+ return {
2025
+ runId,
2026
+ status: run.status,
2027
+ output: run.output,
2028
+ error: run.error
2029
+ };
2030
+ }
2031
+ if (this.namespace !== void 0 && run.namespace !== void 0 && run.namespace !== this.namespace) {
2032
+ await this.store.releaseRunLock(runId);
2033
+ throw new NamespaceMismatch();
2034
+ }
2035
+ const registered = this.workflows.get(versionKey(run.workflow, run.workflowVersion)) ?? await this.findInheritedRegistration(run) ?? await this.resolveRemoteByConvention(run);
2036
+ if (!registered) {
2037
+ throw new Error(`workflow ${run.workflow}@${run.workflowVersion} is not registered \u2014 keep the prior version deployed so in-flight runs can drain (skew protection)`);
2038
+ }
2039
+ return this.track(this.execute(run, registered.fn));
2040
+ }
2041
+ /**
2042
+ * The registration for an UNREGISTERED run, INHERITED from its nearest REMOTE ancestor — or
2043
+ * `undefined` if it has none (the skew-protection error case in {@link resume}). Callers check the
2044
+ * flat registry FIRST (so an explicit `registerRemote(name, …)` ALWAYS wins, and a registered run
2045
+ * never reaches here); this resolves only the new case: a child spawned by a remote workflow (e.g. a
2046
+ * Python `gather_children` / `start_child` fan-out) of a name the host never `registerRemote`-ed. It
2047
+ * is driven as a remote run on the ancestor's group + the SAME executor instance, so the host needs
2048
+ * no redundant registration per child name.
2049
+ *
2050
+ * RECOMPUTED per resume rather than memoized into `this.workflows`: a synthesized child is not a real
2051
+ * registration and must not leak into `latest`, `knownGroups`, or `sweepTimeouts` (which iterate the
2052
+ * registry); recomputing also stays correct if the ancestor's remote registration is re-pointed at a
2053
+ * new executor across a deploy. Only unregistered runs pay it, so registered workflows pay nothing.
2054
+ */
2055
+ async findInheritedRegistration(run) {
2056
+ const ancestor = await this.findRemoteAncestor(run.id);
2057
+ if (!ancestor) return void 0;
2058
+ return this.synthesizeRemoteChild(run.workflow, run.workflowVersion, ancestor);
2059
+ }
2060
+ /**
2061
+ * A throwaway {@link RegisteredWorkflow} that routes `name@version` as a remote run on the ancestor's
2062
+ * group via the ancestor's SAME executor instance. The executor is group-scoped (it dispatches a
2063
+ * {@link WorkflowTask} carrying `run.workflow`, and the worker picks the body by name), so reusing it
2064
+ * is correct AND required — a second executor on the same group would race the worker for results.
2065
+ * Only `remote` is inherited; the child gets none of the ancestor's singleton/timeout/validator, so
2066
+ * its identity stays its own.
2067
+ */
2068
+ synthesizeRemoteChild(name, version, ancestor) {
2069
+ const remote = ancestor.remote;
2070
+ if (!remote) throw new Error(`workflow ${ancestor.name} is not a remote workflow`);
2071
+ return {
2072
+ name,
2073
+ version,
2074
+ fn: /* @__PURE__ */ __name(() => {
2075
+ throw new Error(`workflow ${name} is remote \u2014 it has no in-process body`);
2076
+ }, "fn"),
2077
+ remote
2078
+ };
2079
+ }
2080
+ /**
2081
+ * When `remoteByConvention` is enabled, attempt to route an unregistered workflow to the live
2082
+ * worker group of the same name: if the transport reports a live heartbeat for group
2083
+ * `run.workflow`, synthesize a throwaway {@link RegisteredWorkflow} that dispatches to that group
2084
+ * over the primary transport. Returns `undefined` when the flag is off or the group is not live.
2085
+ *
2086
+ * Recomputed per call (never memoized into `this.workflows`) so it stays correct if group
2087
+ * liveness changes between calls, exactly as {@link synthesizeRemoteChild} does.
2088
+ */
2089
+ async resolveRemoteByConvention(run) {
2090
+ if (!this.remoteByConvention) return void 0;
2091
+ const liveGroups = await this.pool.listWorkerGroups();
2092
+ const group = tenantGroup(run.workflow, run.namespace);
2093
+ if (!liveGroups.includes(group)) return void 0;
2094
+ const executor = new RemoteWorkflowExecutor(this.pool.primary, group);
2095
+ return {
2096
+ name: run.workflow,
2097
+ version: run.workflowVersion,
2098
+ fn: /* @__PURE__ */ __name(() => {
2099
+ throw new Error(`remote workflow ${run.workflow} has no local body`);
2100
+ }, "fn"),
2101
+ hasBody: false,
2102
+ remote: {
2103
+ group,
2104
+ executor
2105
+ }
2106
+ };
2107
+ }
2108
+ /**
2109
+ * Walk the parent chain of `childRunId` to the nearest ancestor registered as REMOTE, returning its
2110
+ * registration (or `undefined` if there is none). The parent of an awaited child is found via its
2111
+ * live `child:<childId>` signal waiter — present for as long as the parent is suspended awaiting the
2112
+ * child, i.e. throughout the child's executable lifetime (start, every resume, crash recovery, cancel
2113
+ * cascade), which is exactly when we resolve. A registered-but-LOCAL parent stops the walk (an
2114
+ * unregistered child of a TS workflow is a genuine misconfiguration → skew error); only an
2115
+ * unregistered parent keeps walking, so a child of an inherited child still reaches the remote root.
2116
+ * `visited` guards against a pathological cyclic id graph.
2117
+ */
2118
+ async findRemoteAncestor(childRunId, visited = /* @__PURE__ */ new Set()) {
2119
+ if (visited.has(childRunId)) return void 0;
2120
+ visited.add(childRunId);
2121
+ const parentRunId = await this.findParentRunId(childRunId);
2122
+ if (!parentRunId) return void 0;
2123
+ const parent = await this.store.getRun(parentRunId);
2124
+ if (!parent) return void 0;
2125
+ const parentReg = this.workflows.get(versionKey(parent.workflow, parent.workflowVersion));
2126
+ if (parentReg?.remote) return parentReg;
2127
+ if (parentReg) return void 0;
2128
+ return this.findRemoteAncestor(parent.id, visited);
2129
+ }
2130
+ /**
2131
+ * The run that spawned `childRunId`, via its live `child:<childRunId>` signal waiter — every awaited
2132
+ * child (`ctx.child`, `ctx.all`, a remote `start_child`) suspends its parent on exactly this waiter,
2133
+ * and the waiter is written BEFORE the child is started. Only reached for an UNREGISTERED child, so
2134
+ * registered runs never pay the scan; returns `undefined` once the parent has settled the child (the
2135
+ * waiter is consumed), but by then the child is terminal and no longer resolved.
2136
+ */
2137
+ async findParentRunId(childRunId) {
2138
+ const token = `child:${childRunId}`;
2139
+ for (const waiter of await this.store.listSignalWaiters("child:")) {
2140
+ if (waiter.token === token) return waiter.runId;
2141
+ }
2142
+ return void 0;
2143
+ }
2144
+ /** Track an in-flight execution so {@link drain} can wait for it. */
2145
+ track(p) {
2146
+ this.inflight.add(p);
2147
+ void p.finally(() => this.inflight.delete(p));
2148
+ return p;
2149
+ }
2150
+ /**
2151
+ * Graceful shutdown: stop picking up new runs (recovery/timer become no-ops) and wait for
2152
+ * in-flight executions to settle, up to `timeoutMs`. Call from your app's shutdown hook so a
2153
+ * deploy hands off cleanly instead of leaving runs to the lease timeout.
2154
+ */
2155
+ async drain(timeoutMs = 1e4) {
2156
+ this.draining = true;
2157
+ if (this.inflight.size === 0) return;
2158
+ const timer = new Promise((resolve) => {
2159
+ const t = setTimeout(resolve, timeoutMs);
2160
+ t.unref?.();
2161
+ });
2162
+ await Promise.race([
2163
+ Promise.allSettled([
2164
+ ...this.inflight
2165
+ ]),
2166
+ timer
2167
+ ]);
2168
+ }
2169
+ /**
2170
+ * Cancel in-flight runs that have outlived their workflow's `executionTimeout`. Call it from the
2171
+ * timer poller alongside {@link resumeDueTimers}. A timed-out run is moved to `cancelled` with an
2172
+ * `execution_timeout` error (terminal, so a late step result can't resurrect it).
2173
+ */
2174
+ async sweepTimeouts(now = this.clock()) {
2175
+ for (const reg of new Set(this.latest.values())) {
2176
+ if (reg.executionTimeoutMs == null) continue;
2177
+ const deadline = now - reg.executionTimeoutMs;
2178
+ const inflight = [
2179
+ ...await this.store.listRuns({
2180
+ workflow: reg.name,
2181
+ status: "running",
2182
+ namespace: this.namespace
2183
+ }),
2184
+ ...await this.store.listRuns({
2185
+ workflow: reg.name,
2186
+ status: "suspended",
2187
+ namespace: this.namespace
2188
+ })
2189
+ ];
2190
+ for (const run of inflight) {
2191
+ if (run.createdAt.getTime() > deadline) continue;
2192
+ const error = {
2193
+ message: "execution timeout",
2194
+ code: "execution_timeout"
2195
+ };
2196
+ await this.store.updateRun(run.id, {
2197
+ status: "cancelled",
2198
+ error,
2199
+ updatedAt: /* @__PURE__ */ new Date()
2200
+ });
2201
+ this.emit({
2202
+ type: "run.failed",
2203
+ runId: run.id,
2204
+ workflow: run.workflow,
2205
+ error
2206
+ });
2207
+ }
2208
+ }
2209
+ }
2210
+ /**
2211
+ * Resume every run left incomplete by a crash or deploy. Called on boot. Completed steps
2212
+ * replay from their checkpoints, so only the work that had not finished runs again.
2213
+ */
2214
+ async recoverIncomplete(nowMs = this.clock()) {
2215
+ if (this.draining) return [];
2216
+ const results = [];
2217
+ for (const run of await this.store.listIncompleteRuns(this.namespace)) {
2218
+ const acquired = await this.store.tryLockRun(run.id, this.instanceId, nowMs + this.leaseMs, nowMs);
2219
+ if (!acquired) continue;
2220
+ const settled = await this.countRecovery(run);
2221
+ if (settled) {
2222
+ results.push(settled);
2223
+ continue;
2224
+ }
2225
+ await this.store.releaseRunLock(run.id);
2226
+ if (run.status !== "cancelling") {
2227
+ await this.store.updateRun(run.id, {
2228
+ status: "pending",
2229
+ updatedAt: /* @__PURE__ */ new Date()
2230
+ });
2231
+ }
2232
+ await this.runDispatcher.dispatch(run.id);
2233
+ results.push({
2234
+ runId: run.id,
2235
+ status: run.status === "cancelling" ? "cancelling" : "pending"
2236
+ });
2237
+ }
2238
+ return results;
2239
+ }
2240
+ /**
2241
+ * Per-recovery bookkeeping (called once the lease is held): count the attempt, or — past
2242
+ * `maxRecoveryAttempts` — move a poison pill to the `dead` dead-letter state. Returns a terminal
2243
+ * result to skip the resume, or `undefined` to proceed.
2244
+ */
2245
+ async countRecovery(run) {
2246
+ const attempts = (run.recoveryAttempts ?? 0) + 1;
2247
+ if (this.maxRecoveryAttempts != null && attempts > this.maxRecoveryAttempts) {
2248
+ const error = {
2249
+ message: `run exceeded maxRecoveryAttempts (${this.maxRecoveryAttempts}) \u2014 moved to dead-letter`,
2250
+ code: "max_recovery_attempts"
2251
+ };
2252
+ await this.store.updateRun(run.id, {
2253
+ status: "dead",
2254
+ error,
2255
+ updatedAt: /* @__PURE__ */ new Date()
2256
+ });
2257
+ await this.store.releaseRunLock(run.id);
2258
+ this.emit({
2259
+ type: "run.failed",
2260
+ runId: run.id,
2261
+ workflow: run.workflow,
2262
+ error
2263
+ });
2264
+ this.notifyDead({
2265
+ ...run,
2266
+ status: "dead",
2267
+ error,
2268
+ recoveryAttempts: attempts
2269
+ });
2270
+ return {
2271
+ runId: run.id,
2272
+ status: "dead",
2273
+ error
2274
+ };
2275
+ }
2276
+ await this.store.updateRun(run.id, {
2277
+ recoveryAttempts: attempts,
2278
+ updatedAt: /* @__PURE__ */ new Date()
2279
+ });
2280
+ return void 0;
2281
+ }
2282
+ /**
2283
+ * Resume every suspended run whose durable timer is due. Call periodically (a poller) and on
2284
+ * boot. A run still not due re-suspends cheaply without running new work.
2285
+ */
2286
+ async resumeDueTimers(nowMs = this.clock()) {
2287
+ return this.resumeLeased(await this.store.listDueTimers(nowMs, this.namespace), nowMs);
2288
+ }
2289
+ /**
2290
+ * Lease and execute one run by id — the worker side of dispatch. Acquires the recovery lease (so
2291
+ * exactly one instance runs it), then resumes the body. Returns the result, or null if another
2292
+ * instance holds the lease or the engine is draining. The default in-process dispatcher calls this;
2293
+ * a broker-backed worker calls it per consumed run id.
2294
+ */
2295
+ async runOne(runId) {
2296
+ if (this.draining) return null;
2297
+ const nowMs = this.clock();
2298
+ const acquired = await this.store.tryLockRun(runId, this.instanceId, nowMs + this.leaseMs, nowMs);
2299
+ if (!acquired) return null;
2300
+ return this.resume(runId).catch((err) => {
2301
+ if (err instanceof NamespaceMismatch) return null;
2302
+ throw err;
2303
+ });
2304
+ }
2305
+ /**
2306
+ * Re-enqueue a run for a worker to (re-)execute — the dispatch-model **retry**. Sets it back to
2307
+ * `pending`, clears any stale lease, and dispatches; a worker resumes it (replaying its checkpoints,
2308
+ * re-attempting the failed step). Returns the enqueued state immediately — never runs the body
2309
+ * inline — or null if the run is unknown. The dashboard "retry" goes through here so it can't block
2310
+ * the HTTP request on workflow execution.
2311
+ */
2312
+ async requeue(runId) {
2313
+ const run = await this.store.getRun(runId);
2314
+ if (!run) return null;
2315
+ await this.store.releaseRunLock(runId);
2316
+ await this.store.updateRun(runId, {
2317
+ status: "pending",
2318
+ updatedAt: /* @__PURE__ */ new Date()
2319
+ });
2320
+ await this.runDispatcher.dispatch(runId);
2321
+ return {
2322
+ runId,
2323
+ status: "pending"
2324
+ };
2325
+ }
2326
+ /**
2327
+ * **Fix-and-replay**: re-run a run (typically a `dead`/`failed` one) with a corrected `input`, as a
2328
+ * fresh run with clean history. It's a NEW run — `newRunId` defaults to `<runId>~retry~<uuid>` — so
2329
+ * the original stays inspectable. Returns the new run's id, or null if `runId` is unknown.
2330
+ */
2331
+ async retryWithInput(runId, input, newRunId) {
2332
+ const run = await this.store.getRun(runId);
2333
+ if (!run) return null;
2334
+ const id = newRunId ?? `${runId}~retry~${globalThis.crypto.randomUUID().slice(0, 8)}`;
2335
+ await this.start(run.workflow, input, id, {
2336
+ tags: run.tags,
2337
+ namespace: run.namespace
2338
+ });
2339
+ return {
2340
+ runId: id
2341
+ };
2342
+ }
2343
+ /**
2344
+ * Pick up and execute every `pending` run — the poll-based side of dispatch for a worker pod with
2345
+ * no broker. Runs enqueued by other pods (or by a caller using a no-op dispatcher) sit `pending`
2346
+ * in the store until polled; leasing ensures exactly one pod runs each. Call periodically alongside
2347
+ * {@link resumeDueTimers}.
2348
+ */
2349
+ async runPending(nowMs = this.clock()) {
2350
+ return this.resumeLeased(await this.store.listPendingRuns(100, this.namespace), nowMs);
2351
+ }
2352
+ /**
2353
+ * Resolve once `runId` reaches a settled state — terminal (completed/failed/cancelled/dead) or
2354
+ * suspended (handed off to a timer/signal/event). The async counterpart to dispatch: pair it with
2355
+ * `start` when a call site needs the outcome — `await start(...); const r = await waitForRun(id)`.
2356
+ */
2357
+ waitForRun(runId, opts) {
2358
+ const isSettled = /* @__PURE__ */ __name((run) => run.status !== "pending" && run.status !== "running" && run.status !== "cancelling" && !(run.status === "suspended" && run.awaitingDecisionTaskId !== void 0), "isSettled");
2359
+ const toResult = /* @__PURE__ */ __name((run) => ({
2360
+ runId,
2361
+ status: run.status,
2362
+ output: run.output,
2363
+ error: run.error
2364
+ }), "toResult");
2365
+ return new Promise((resolve, reject) => {
2366
+ let done = false;
2367
+ let off = /* @__PURE__ */ __name(() => {
2368
+ }, "off");
2369
+ const timer = opts?.timeoutMs != null ? setTimeout(() => {
2370
+ if (done) return;
2371
+ done = true;
2372
+ off();
2373
+ reject(new Error(`waitForRun(${runId}) timed out after ${opts.timeoutMs}ms`));
2374
+ }, opts.timeoutMs) : void 0;
2375
+ const finish = /* @__PURE__ */ __name((run) => {
2376
+ if (done) return;
2377
+ done = true;
2378
+ if (timer) clearTimeout(timer);
2379
+ off();
2380
+ resolve(toResult(run));
2381
+ }, "finish");
2382
+ const check = /* @__PURE__ */ __name(() => {
2383
+ void this.store.getRun(runId).then((run) => {
2384
+ if (run && isSettled(run)) finish(run);
2385
+ });
2386
+ }, "check");
2387
+ off = this.subscribe((ev) => {
2388
+ if (ev.runId === runId && (ev.type === "run.completed" || ev.type === "run.failed" || ev.type === "run.suspended")) {
2389
+ check();
2390
+ }
2391
+ });
2392
+ check();
2393
+ });
2394
+ }
2395
+ /**
2396
+ * Resume each run only if this instance can acquire its recovery lease — so when several
2397
+ * replicas recover or poll at once, each run is picked up by exactly one of them.
2398
+ */
2399
+ async resumeLeased(runs, nowMs = this.clock(), onLocked) {
2400
+ if (this.draining) return [];
2401
+ const results = [];
2402
+ for (const run of runs) {
2403
+ const acquired = await this.store.tryLockRun(run.id, this.instanceId, nowMs + this.leaseMs, nowMs);
2404
+ if (!acquired) continue;
2405
+ const settled = onLocked ? await onLocked(run) : void 0;
2406
+ results.push(settled ?? await this.resume(run.id));
2407
+ }
2408
+ return results;
2409
+ }
2410
+ /**
2411
+ * Deliver an external signal to the run waiting on `token` and resume it with `payload`.
2412
+ * Returns the run result, or null if no run is waiting for that token.
2413
+ */
2414
+ /**
2415
+ * Publish a named event. It does two things, and returns how many runs it touched (the sum):
2416
+ * 1. **Resumes** every in-flight run waiting on it via `ctx.waitForEvent(name, { match })` whose
2417
+ * match the payload satisfies (fan-out, vs `signal`'s point-to-point token).
2418
+ * 2. **Starts** a fresh run of every workflow registered with `onEvent: [name]`, passing the
2419
+ * payload as input. Idempotent by `evt:<id>:<workflow>` — pass `opts.id` to dedupe redeliveries
2420
+ * of the same logical event (default: a fresh uuid, so each publish triggers once).
2421
+ */
2422
+ async publishEvent(name, payload, opts) {
2423
+ let touched = 0;
2424
+ const waiters = await this.store.listSignalWaiters(eventPrefix(name));
2425
+ for (const w of waiters) {
2426
+ if (eventMatches(payload, eventMatchOf(w.token))) {
2427
+ await this.signal(w.token, payload);
2428
+ touched += 1;
2429
+ }
2430
+ }
2431
+ const subscribers = this.eventTriggers.get(name);
2432
+ if (subscribers?.size) {
2433
+ const eventId = opts?.id ?? globalThis.crypto.randomUUID();
2434
+ for (const workflow of subscribers) {
2435
+ try {
2436
+ const batch = this.latest.get(workflow)?.eventBatch;
2437
+ if (batch) {
2438
+ await this.accumulators.route(workflow, batch, payload);
2439
+ } else {
2440
+ await this.start(workflow, payload, `evt:${eventId}:${workflow}`);
2441
+ }
2442
+ touched += 1;
2443
+ } catch {
2444
+ }
2445
+ }
2446
+ }
2447
+ return touched;
2448
+ }
2449
+ async signal(token, payload) {
2450
+ const waiter = await this.store.takeSignalWaiter(token);
2451
+ if (!waiter) {
2452
+ await this.store.bufferSignal(token, payload);
2453
+ return null;
2454
+ }
2455
+ await this.store.saveCheckpoint(instantCheckpoint({
2456
+ runId: waiter.runId,
2457
+ seq: waiter.seq,
2458
+ name: `signal:${token}`,
2459
+ kind: "signal",
2460
+ output: payload,
2461
+ // Carry the awaiting command's fan group (set when a `ctx.gather_children`/`ctx.all` fan-out
2462
+ // registered this waiter) onto the resolving `signal:child:<id>` checkpoint, so the dashboard
2463
+ // groups the child fan-out vertically instead of rendering it as a sequential chain. Undefined
2464
+ // for an ordinary (non-fan) signal/child await.
2465
+ parallelGroup: waiter.parallelGroup
2466
+ }));
2467
+ return this.resume(waiter.runId).catch((err) => {
2468
+ if (err instanceof NamespaceMismatch) return null;
2469
+ throw err;
2470
+ });
2471
+ }
2472
+ /**
2473
+ * Ensure a run exists for `runId`, then deliver a signal to it — atomically race-free thanks to
2474
+ * signal buffering: if the run is new (or busy / not yet waiting), the signal is buffered and
2475
+ * consumed when it reaches `waitForSignal(token)`. The canonical **durable-entity / accumulator**
2476
+ * pattern: one long-lived run per key (the `runId`) that loops on `waitForSignal`, fed events by
2477
+ * many `signalWithStart` calls. `start` is idempotent by `runId`, so concurrent callers converge on
2478
+ * one run. (Use a per-run `token`, e.g. derived from `runId`, so the signal targets this entity.)
2479
+ */
2480
+ async signalWithStart(workflow, input, runId, signal, opts) {
2481
+ await this.start(workflow, input, runId, opts);
2482
+ await this.signal(signal.token, signal.payload);
2483
+ return {
2484
+ runId
2485
+ };
2486
+ }
2487
+ /**
2488
+ * Report the result of a `ctx.task(name, …)` back to its run (async completion). The external
2489
+ * worker that the task dispatched to calls this when done; the run resumes with `result`. Returns
2490
+ * null if no run is waiting on the task (e.g. a duplicate/late delivery) — a safe no-op.
2491
+ */
2492
+ async completeTask(runId, name, result) {
2493
+ return this.signal(`task:${runId}:${name}`, {
2494
+ ok: true,
2495
+ value: result
2496
+ });
2497
+ }
2498
+ /** Report that a `ctx.task` failed — the run resumes and throws a FatalError at the task. */
2499
+ async failTask(runId, name, error) {
2500
+ return this.signal(`task:${runId}:${name}`, {
2501
+ ok: false,
2502
+ error
2503
+ });
2504
+ }
2505
+ /**
2506
+ * Notify a parent that's waiting on `runId` as a child of its terminal outcome (the `ctx.child`
2507
+ * rendezvous). A no-op when no parent is waiting, so `execute()` can call it on every run without
2508
+ * knowing about the child feature.
2509
+ */
2510
+ notifyParent(runId, completion) {
2511
+ void this.signal(`child:${runId}`, completion).catch(() => void 0);
2512
+ }
2513
+ /**
2514
+ * Cancel a run (e.g. from the dashboard). Returns null if the run does not exist. Pass
2515
+ * `{ compensate: true }` to undo the saga first: the suspended run is resumed so its completed
2516
+ * steps' compensations run in reverse (visible as `compensate:<step>` events), then it's marked
2517
+ * cancelled. Without it, cancellation is immediate (no undo).
2518
+ */
2519
+ async cancel(runId, opts) {
2520
+ const run = await this.store.getRun(runId);
2521
+ if (!run) return null;
2522
+ if (run.status === "completed" || run.status === "cancelled" || run.status === "dead") {
2523
+ return {
2524
+ runId,
2525
+ status: run.status,
2526
+ output: run.output,
2527
+ error: run.error
2528
+ };
2529
+ }
2530
+ if (run.status === "cancelling") {
2531
+ return {
2532
+ runId,
2533
+ status: "cancelling"
2534
+ };
2535
+ }
2536
+ if (opts?.compensate && (run.status === "suspended" || run.status === "running")) {
2537
+ this.cancelRequested.add(runId);
2538
+ await this.store.updateRun(runId, {
2539
+ status: "cancelling",
2540
+ updatedAt: /* @__PURE__ */ new Date()
2541
+ });
2542
+ run.status = "cancelling";
2543
+ if (this.controlPlane) {
2544
+ void this.controlPlane.publishControl({
2545
+ kind: "cancel",
2546
+ runId,
2547
+ from: this.instanceId
2548
+ }).catch(() => void 0);
2549
+ }
2550
+ queueMicrotask(() => {
2551
+ void this.resume(runId).then(() => this.notifyCancelled(runId)).catch(() => void 0);
2552
+ });
2553
+ await this.cancelChildren(runId, opts);
2554
+ return {
2555
+ runId,
2556
+ status: "cancelling"
2557
+ };
2558
+ }
2559
+ const error = {
2560
+ message: "cancelled"
2561
+ };
2562
+ await this.store.updateRun(runId, {
2563
+ status: "cancelled",
2564
+ error,
2565
+ updatedAt: /* @__PURE__ */ new Date()
2566
+ });
2567
+ this.emit({
2568
+ type: "run.failed",
2569
+ runId,
2570
+ workflow: run.workflow,
2571
+ error
2572
+ });
2573
+ await this.cancelChildren(runId, opts);
2574
+ this.notifyCancelled(runId);
2575
+ if (this.controlPlane) {
2576
+ void this.controlPlane.publishControl({
2577
+ kind: "cancel",
2578
+ runId,
2579
+ from: this.instanceId
2580
+ }).catch(() => void 0);
2581
+ }
2582
+ void this.singletons.wakeNext(run).catch(() => void 0);
2583
+ return {
2584
+ runId,
2585
+ status: "cancelled",
2586
+ error
2587
+ };
2588
+ }
2589
+ /**
2590
+ * Bulk-cancel every run matching a filter — e.g. cancel all `order` runs tagged `vip`, or every run
2591
+ * whose `tier` search attribute is `free`. The filter is a {@link RunQuery} (workflow / status / tag
2592
+ * / search-attribute predicates), so it reuses the same matching the dashboard list uses. Each match
2593
+ * is run through {@link cancel}, so the same plumbing applies per run: child cascade, the optional
2594
+ * saga `compensate`, local cancel listeners, and the control-plane broadcast that tells the owning
2595
+ * worker to abort. Returns one {@link RunResult} per matched run (already-finished matches report
2596
+ * their terminal status — `cancel` is a no-op on them, never clobbering a completed/dead run).
2597
+ */
2598
+ async cancelWhere(filter, opts) {
2599
+ const runs = await this.store.listRuns(filter);
2600
+ const results = [];
2601
+ for (const run of runs) {
2602
+ const r = await this.cancel(run.id, opts);
2603
+ if (r) results.push(r);
2604
+ }
2605
+ return results;
2606
+ }
2607
+ /**
2608
+ * Hard-delete a run and its entire subtree. Unlike {@link cancel} (which marks a run `cancelled`
2609
+ * but keeps it as history), delete REMOVES the run and all its rows (checkpoints, signal waiters,
2610
+ * search-attribute rows) — it vanishes from {@link getRun} and {@link listRuns}. Use it to purge a
2611
+ * finished run whose data is being deleted (e.g. a pipeline run whose result rows are cleared).
2612
+ *
2613
+ * Cascades depth-first via {@link getRunChildren} so children are gone before the parent (no
2614
+ * orphaned child runs). Prefer {@link cancel} first for a live run — deleting one mid-flight orphans
2615
+ * its worker (its next checkpoint write fails). Returns the number of runs deleted (0 if absent).
2616
+ */
2617
+ async deleteRun(runId) {
2618
+ const run = await this.store.getRun(runId);
2619
+ if (!run) return 0;
2620
+ let deleted = 0;
2621
+ for (const childId of await this.getRunChildren(runId)) {
2622
+ deleted += await this.deleteRun(childId);
2623
+ }
2624
+ await this.store.deleteRun(runId);
2625
+ return deleted + 1;
2626
+ }
2627
+ /**
2628
+ * Cascade cancellation to a run's children — both awaited (`ctx.child`, found via its live
2629
+ * `child:<id>` waiter) and fire-and-forget (`ctx.startChild`, found via its `spawn:<id>`
2630
+ * checkpoint). Recursive, so a whole subtree is cancelled; the terminal guard in `cancel` stops it
2631
+ * at finished / already-cancelled runs (no loops, no re-cancel).
2632
+ */
2633
+ async cancelChildren(parentRunId, opts) {
2634
+ for (const id of await this.getRunChildren(parentRunId)) {
2635
+ await this.cancel(id, opts).catch(() => void 0);
2636
+ }
2637
+ }
2638
+ /**
2639
+ * The ids of the runs a run spawned — both awaited (`ctx.child`) and fire-and-forget
2640
+ * (`ctx.startChild`, found via its `spawn:<id>` checkpoint). The canonical parent→children edge,
2641
+ * used for both cancellation cascades and the dashboard run-tree.
2642
+ *
2643
+ * An awaited child is discovered two ways, because the live `child:<id>` waiter only exists WHILE
2644
+ * the parent is suspended on it: the waiter resolves and is consumed the moment the child settles,
2645
+ * so a completed parent (or a completed awaited child) would otherwise drop out of the tree. The
2646
+ * `signal:child:<id>` checkpoint (the placeholder written when the parent first awaits the child,
2647
+ * overwritten as completed/failed when it settles) persists across completion, so we read both and
2648
+ * dedupe — the edge stays stable for a finished run, not just a live one.
2649
+ */
2650
+ async getRunChildren(parentRunId) {
2651
+ const childIds = /* @__PURE__ */ new Set();
2652
+ for (const w of await this.store.listSignalWaiters("child:")) {
2653
+ if (w.runId === parentRunId) childIds.add(w.token.slice("child:".length));
2654
+ }
2655
+ const prefixes = [
2656
+ "signal:child:",
2657
+ "spawn:"
2658
+ ];
2659
+ const childCheckpoints = this.store.listCheckpointsByNamePrefix ? await this.store.listCheckpointsByNamePrefix(parentRunId, prefixes) : (await this.store.listCheckpoints(parentRunId)).filter((cp) => prefixes.some((p) => cp.name.startsWith(p)));
2660
+ for (const cp of childCheckpoints) {
2661
+ if (cp.name.startsWith("signal:child:")) childIds.add(cp.name.slice("signal:child:".length));
2662
+ if (cp.name.startsWith("spawn:") && typeof cp.output === "string") childIds.add(cp.output);
2663
+ }
2664
+ return [
2665
+ ...childIds
2666
+ ];
2667
+ }
2668
+ /** The worker groups this engine dispatches to: every registered remote workflow's group, plus any
2669
+ * `extra` the caller declares. Local-step groups (a group consumed by in-process `@DurableStep`
2670
+ * workers, e.g. `pipeline`) aren't derivable from registrations — pass them via `extra` so a group
2671
+ * with backlog and ZERO workers is still reported (the alert case has no heartbeat to discover). */
2672
+ knownGroups(extra = []) {
2673
+ const groups = new Set(extra);
2674
+ for (const def of this.workflows.values()) {
2675
+ if (def.remote?.group) groups.add(def.remote.group);
2676
+ }
2677
+ return [
2678
+ ...groups
2679
+ ];
2680
+ }
2681
+ /** Per-group worker health (queue backlog + live worker heartbeats). Covers {@link knownGroups}
2682
+ * (so a registered group with backlog and ZERO workers still reports — the alert case) UNION the
2683
+ * groups discovered from live heartbeats (so a local-step group like `pipeline`, not derivable
2684
+ * from registrations, shows once its workers beat). Empty when no transport can introspect health
2685
+ * (only the BullMQ transport implements `groupHealth`). */
2686
+ async workerHealth(extra = []) {
2687
+ const groups = /* @__PURE__ */ new Set([
2688
+ ...this.knownGroups(extra),
2689
+ ...await this.pool.listWorkerGroups()
2690
+ ]);
2691
+ const out = [];
2692
+ for (const group of groups) {
2693
+ const health = await this.pool.groupHealth(group);
2694
+ if (health) out.push(health);
2695
+ }
2696
+ return out;
2697
+ }
2698
+ /**
2699
+ * Persist a streamed local-step lifecycle event from a remote workflow worker (see
2700
+ * {@link WorkflowStepEvent}). A Python `@workflow` runs its `ctx.step`s inline over one turn that
2701
+ * can last minutes; the worker streams each step's start/finish so the engine checkpoints it LIVE —
2702
+ * a step shows `running` the moment its body begins, then resolves to `completed`/`failed` with its
2703
+ * real wall-clock window and sub-process events — instead of every step appearing at once when the
2704
+ * turn ends. The turn's final `recordStep` command re-persists the same (runId, seq) checkpoint
2705
+ * idempotently, so this is purely additive observability and never changes the run's outcome.
2706
+ */
2707
+ async persistStepEvent(event) {
2708
+ const startedAt = new Date(event.startedAt);
2709
+ if (event.phase === "running") {
2710
+ await this.store.saveCheckpoint(stepCheckpoint({
2711
+ runId: event.runId,
2712
+ seq: event.seq,
2713
+ name: event.name,
2714
+ kind: "local",
2715
+ status: "running",
2716
+ events: event.events,
2717
+ attempts: 1,
2718
+ enqueuedAt: startedAt,
2719
+ startedAt,
2720
+ finishedAt: startedAt,
2721
+ parallelGroup: event.parallelGroup
2722
+ }));
2723
+ this.emit({
2724
+ type: "step.started",
2725
+ runId: event.runId,
2726
+ seq: event.seq,
2727
+ name: event.name,
2728
+ kind: "local"
2729
+ });
2730
+ return;
2731
+ }
2732
+ const failed = event.phase === "failed";
2733
+ await this.store.saveCheckpoint(stepCheckpoint({
2734
+ runId: event.runId,
2735
+ seq: event.seq,
2736
+ name: event.name,
2737
+ kind: "local",
2738
+ status: failed ? "failed" : "completed",
2739
+ output: failed ? void 0 : event.output,
2740
+ error: failed ? event.error : void 0,
2741
+ events: event.events,
2742
+ attempts: 1,
2743
+ enqueuedAt: startedAt,
2744
+ startedAt,
2745
+ finishedAt: event.finishedAt != null ? new Date(event.finishedAt) : /* @__PURE__ */ new Date(),
2746
+ parallelGroup: event.parallelGroup
2747
+ }));
2748
+ this.emit({
2749
+ type: failed ? "step.failed" : "step.completed",
2750
+ runId: event.runId,
2751
+ seq: event.seq,
2752
+ name: event.name,
2753
+ kind: "local",
2754
+ output: failed ? void 0 : event.output,
2755
+ error: failed ? event.error : void 0
2756
+ });
2757
+ }
2758
+ /**
2759
+ * Announce a local step's body has begun and (when `trackStepStart`) checkpoint it as `running`,
2760
+ * so it's visible in flight rather than appearing only on completion. The checkpoint is a
2761
+ * placeholder overwritten by {@link completeStep}/{@link failStep}; it never short-circuits replay
2762
+ * (only `completed` does), so a crash mid-body just re-runs the step. The `step.started` event
2763
+ * fires regardless — the live SSE view sees the start even with persistence off.
2764
+ */
2765
+ async startStep(step) {
2766
+ if (this.trackStepStart) {
2767
+ await this.store.saveCheckpoint(stepCheckpoint({
2768
+ runId: step.runId,
2769
+ seq: step.seq,
2770
+ name: step.name,
2771
+ kind: step.kind,
2772
+ status: "running",
2773
+ input: step.input,
2774
+ events: step.events,
2775
+ attempts: step.attempts,
2776
+ workerGroup: step.workerGroup,
2777
+ enqueuedAt: step.enqueuedAt,
2778
+ startedAt: step.startedAt,
2779
+ finishedAt: step.startedAt
2780
+ }));
2781
+ }
2782
+ this.emit({
2783
+ type: "step.started",
2784
+ runId: step.runId,
2785
+ seq: step.seq,
2786
+ name: step.name,
2787
+ kind: step.kind
2788
+ });
2789
+ }
2790
+ /** Checkpoint a finished step and announce it — the two things that must always happen together. */
2791
+ async completeStep(step) {
2792
+ await this.store.saveCheckpoint(stepCheckpoint({
2793
+ runId: step.runId,
2794
+ seq: step.seq,
2795
+ name: step.name,
2796
+ kind: step.kind,
2797
+ status: "completed",
2798
+ input: step.input,
2799
+ output: step.output,
2800
+ events: step.events,
2801
+ attempts: step.attempts,
2802
+ workerGroup: step.workerGroup,
2803
+ enqueuedAt: step.enqueuedAt,
2804
+ startedAt: step.startedAt,
2805
+ finishedAt: /* @__PURE__ */ new Date()
2806
+ }));
2807
+ this.emit({
2808
+ type: "step.completed",
2809
+ runId: step.runId,
2810
+ seq: step.seq,
2811
+ name: step.name,
2812
+ kind: step.kind,
2813
+ output: step.output,
2814
+ queueMs: step.startedAt.getTime() - step.enqueuedAt.getTime(),
2815
+ durationMs: Date.now() - step.startedAt.getTime()
2816
+ });
2817
+ }
2818
+ /** Checkpoint a step that failed terminally, so the failure point is visible (not just the run). */
2819
+ async failStep(step) {
2820
+ await this.store.saveCheckpoint(stepCheckpoint({
2821
+ runId: step.runId,
2822
+ seq: step.seq,
2823
+ name: step.name,
2824
+ kind: step.kind,
2825
+ status: "failed",
2826
+ input: step.input,
2827
+ error: step.error,
2828
+ events: step.events,
2829
+ attempts: step.attempts,
2830
+ workerGroup: step.workerGroup,
2831
+ enqueuedAt: step.enqueuedAt,
2832
+ startedAt: step.startedAt,
2833
+ finishedAt: /* @__PURE__ */ new Date()
2834
+ }));
2835
+ this.emit({
2836
+ type: "step.failed",
2837
+ runId: step.runId,
2838
+ seq: step.seq,
2839
+ name: step.name,
2840
+ kind: step.kind,
2841
+ error: step.error,
2842
+ queueMs: step.startedAt.getTime() - step.enqueuedAt.getTime(),
2843
+ durationMs: Date.now() - step.startedAt.getTime()
2844
+ });
2845
+ }
2846
+ async execute(run, fn) {
2847
+ const registered = this.workflows.get(versionKey(run.workflow, run.workflowVersion)) ?? await this.findInheritedRegistration(run) ?? await this.resolveRemoteByConvention(run);
2848
+ const lockNow = this.clock();
2849
+ if (run.lockedBy !== this.instanceId || (run.lockedUntil ?? 0) <= lockNow) {
2850
+ if (!await this.store.tryLockRun(run.id, this.instanceId, lockNow + this.leaseMs, lockNow)) {
2851
+ return {
2852
+ runId: run.id,
2853
+ status: run.status
2854
+ };
2855
+ }
2856
+ }
2857
+ const renew = setInterval(() => {
2858
+ void this.store.renewRunLock(run.id, this.instanceId, this.clock() + this.leaseMs).catch(() => void 0);
2859
+ }, Math.max(50, Math.floor(this.leaseMs / 2)));
2860
+ renew.unref?.();
2861
+ try {
2862
+ const result = registered?.remote ? await this.runRemoteExecution(run, registered) : await this.runExecution(run, fn, registered);
2863
+ if (registered?.singleton && (result.status === "completed" || result.status === "failed" || result.status === "cancelled" || result.status === "dead")) {
2864
+ void this.singletons.wakeNext(run).catch(() => void 0);
2865
+ }
2866
+ return result;
2867
+ } finally {
2868
+ clearInterval(renew);
2869
+ }
2870
+ }
2871
+ /**
2872
+ * Advance a remote (cross-SDK) workflow one turn: hand its history to the executor (which dispatches
2873
+ * a workflow task to the worker and awaits its replay) and apply the decision. Mirrors
2874
+ * {@link runExecution}'s settle/suspend; the lease is held by {@link execute}. The result that lands
2875
+ * us back here (a remote step finished, a timer fired) goes through `resume` like any TS workflow.
2876
+ */
2877
+ /**
2878
+ * Apply a terminal/suspended transition once: persist the new run status, emit the matching
2879
+ * lifecycle event, and (on completion/failure) wake a waiting parent. Both the TS and remote
2880
+ * executors funnel their completed/failed/suspended outcomes through here so a status update can
2881
+ * never drift from its event or `notifyParent` call. Does NOT touch the run lock — each executor
2882
+ * keeps its own lease handling (the TS executor's `finally`, the remote path's caller).
2883
+ */
2884
+ async settleRun(run, outcome) {
2885
+ const updatedAt = /* @__PURE__ */ new Date();
2886
+ if (outcome.kind === "completed") {
2887
+ await this.store.updateRun(run.id, {
2888
+ status: "completed",
2889
+ output: outcome.output,
2890
+ error: void 0,
2891
+ updatedAt
2892
+ });
2893
+ this.emit({
2894
+ type: "run.completed",
2895
+ runId: run.id,
2896
+ workflow: run.workflow,
2897
+ output: outcome.output
2898
+ });
2899
+ void this.notifyParent(run.id, {
2900
+ ok: true,
2901
+ value: outcome.output
2902
+ });
2903
+ return {
2904
+ runId: run.id,
2905
+ status: "completed",
2906
+ output: outcome.output
2907
+ };
2908
+ }
2909
+ if (outcome.kind === "failed") {
2910
+ await this.store.updateRun(run.id, {
2911
+ status: "failed",
2912
+ error: outcome.error,
2913
+ updatedAt
2914
+ });
2915
+ this.emit({
2916
+ type: "run.failed",
2917
+ runId: run.id,
2918
+ workflow: run.workflow,
2919
+ error: outcome.error
2920
+ });
2921
+ void this.notifyParent(run.id, {
2922
+ ok: false,
2923
+ error: outcome.error.message
2924
+ });
2925
+ return {
2926
+ runId: run.id,
2927
+ status: "failed",
2928
+ error: outcome.error
2929
+ };
2930
+ }
2931
+ await this.store.updateRun(run.id, {
2932
+ status: "suspended",
2933
+ wakeAt: outcome.wakeAt,
2934
+ updatedAt
2935
+ });
2936
+ this.emit({
2937
+ type: "run.suspended",
2938
+ runId: run.id,
2939
+ workflow: run.workflow
2940
+ });
2941
+ return {
2942
+ runId: run.id,
2943
+ status: "suspended"
2944
+ };
2945
+ }
2946
+ async runRemoteExecution(run, registered) {
2947
+ if (run.status === "cancelling") {
2948
+ const error = {
2949
+ message: "cancelled"
2950
+ };
2951
+ await this.store.updateRun(run.id, {
2952
+ status: "cancelled",
2953
+ error,
2954
+ updatedAt: /* @__PURE__ */ new Date()
2955
+ });
2956
+ this.emit({
2957
+ type: "run.failed",
2958
+ runId: run.id,
2959
+ workflow: run.workflow,
2960
+ error
2961
+ });
2962
+ this.notifyCancelled(run.id);
2963
+ if (this.controlPlane) {
2964
+ void this.controlPlane.publishControl({
2965
+ kind: "cancel",
2966
+ runId: run.id,
2967
+ from: this.instanceId
2968
+ }).catch(() => void 0);
2969
+ }
2970
+ await this.store.releaseRunLock(run.id);
2971
+ return {
2972
+ runId: run.id,
2973
+ status: "cancelled",
2974
+ error
2975
+ };
2976
+ }
2977
+ const remote = registered.remote;
2978
+ if (run.status === "pending") {
2979
+ await this.store.updateRun(run.id, {
2980
+ status: "running",
2981
+ updatedAt: /* @__PURE__ */ new Date()
2982
+ });
2983
+ run.status = "running";
2984
+ this.emit({
2985
+ type: "run.started",
2986
+ runId: run.id,
2987
+ workflow: run.workflow
2988
+ });
2989
+ }
2990
+ if (registered.singleton && !await this.singletons.admit(run, registered.singleton)) {
2991
+ const wakeAt = this.singletons.retryWakeAt();
2992
+ await this.store.updateRun(run.id, {
2993
+ status: "suspended",
2994
+ wakeAt,
2995
+ updatedAt: /* @__PURE__ */ new Date()
2996
+ });
2997
+ this.emit({
2998
+ type: "run.suspended",
2999
+ runId: run.id,
3000
+ workflow: run.workflow
3001
+ });
3002
+ await this.store.releaseRunLock(run.id);
3003
+ return {
3004
+ runId: run.id,
3005
+ status: "suspended"
3006
+ };
3007
+ }
3008
+ const history = await this.remoteHistory(run.id);
3009
+ if (remote.executor.dispatch) {
3010
+ const taskId = `${run.id}:wf:${globalThis.crypto.randomUUID().slice(0, 8)}`;
3011
+ const silenceMs = this.remoteAdvanceSilenceMs;
3012
+ const wakeAt = silenceMs != null ? this.clock() + silenceMs : void 0;
3013
+ await this.store.updateRun(run.id, {
3014
+ status: "suspended",
3015
+ awaitingDecisionTaskId: taskId,
3016
+ wakeAt,
3017
+ updatedAt: /* @__PURE__ */ new Date()
3018
+ });
3019
+ this.emit({
3020
+ type: "run.suspended",
3021
+ runId: run.id,
3022
+ workflow: run.workflow
3023
+ });
3024
+ await this.store.releaseRunLock(run.id);
3025
+ await remote.executor.dispatch(run, history, taskId);
3026
+ return {
3027
+ runId: run.id,
3028
+ status: "suspended"
3029
+ };
3030
+ }
3031
+ const advanceExecutor = remote.executor.advance;
3032
+ if (!advanceExecutor) {
3033
+ throw new Error(`workflow ${run.workflow}@${run.workflowVersion}: executor implements neither advance nor dispatch`);
3034
+ }
3035
+ let decision;
3036
+ try {
3037
+ const silenceMs = this.remoteAdvanceSilenceMs;
3038
+ const advance = advanceExecutor.call(remote.executor, run, history);
3039
+ decision = silenceMs != null ? await this.awaitWithLivenessDeadline(run.id, advance, silenceMs, () => new RemoteWorkflowTimeout(run.id, silenceMs)) : await advance;
3040
+ } catch (err) {
3041
+ if (err instanceof RemoteWorkflowTimeout) {
3042
+ await this.store.releaseRunLock(run.id);
3043
+ return {
3044
+ runId: run.id,
3045
+ status: "running"
3046
+ };
3047
+ }
3048
+ const error = {
3049
+ message: err instanceof Error ? err.message : String(err),
3050
+ stack: err instanceof Error ? err.stack : void 0
3051
+ };
3052
+ await this.store.updateRun(run.id, {
3053
+ status: "failed",
3054
+ error,
3055
+ updatedAt: /* @__PURE__ */ new Date()
3056
+ });
3057
+ this.emit({
3058
+ type: "run.failed",
3059
+ runId: run.id,
3060
+ workflow: run.workflow,
3061
+ error
3062
+ });
3063
+ return {
3064
+ runId: run.id,
3065
+ status: "failed",
3066
+ error
3067
+ };
3068
+ }
3069
+ return this.applyDecision(run, decision);
3070
+ }
3071
+ /**
3072
+ * Apply a remote workflow turn's {@link WorkflowDecision}: persist the local steps it ran, then
3073
+ * settle (completed/failed/cancelled) or dispatch its blocking ops and suspend (continue). Shared by
3074
+ * the INLINE-advance path ({@link runRemoteExecution}, under the held lease) and the durable
3075
+ * DISPATCH path ({@link completeRemoteDecision}, which holds the lease itself). Idempotent transitions
3076
+ * — the caller has already ensured this is the decision for the currently-awaited turn.
3077
+ */
3078
+ async applyDecision(run, decision) {
3079
+ if (decision.status === "completed") {
3080
+ await this.applyCommands(run, decision.commands);
3081
+ return this.settleRun(run, {
3082
+ kind: "completed",
3083
+ output: decision.output
3084
+ });
3085
+ }
3086
+ if (decision.status === "failed") {
3087
+ await this.applyCommands(run, decision.commands);
3088
+ return this.settleRun(run, {
3089
+ kind: "failed",
3090
+ error: decision.error ?? {
3091
+ message: "workflow failed"
3092
+ }
3093
+ });
3094
+ }
3095
+ if (decision.status === "cancelled") {
3096
+ await this.applyCommands(run, decision.commands);
3097
+ await this.store.updateRun(run.id, {
3098
+ status: "cancelled",
3099
+ updatedAt: /* @__PURE__ */ new Date()
3100
+ });
3101
+ return {
3102
+ runId: run.id,
3103
+ status: "cancelled"
3104
+ };
3105
+ }
3106
+ const fresh = await this.store.getRun(run.id);
3107
+ if (fresh && (fresh.status === "cancelled" || fresh.status === "completed" || fresh.status === "dead")) {
3108
+ return {
3109
+ runId: run.id,
3110
+ status: fresh.status,
3111
+ output: fresh.output,
3112
+ error: fresh.error
3113
+ };
3114
+ }
3115
+ const wakeAt = await this.applyCommands(run, decision.commands);
3116
+ return this.settleRun(run, {
3117
+ kind: "suspended",
3118
+ wakeAt
3119
+ });
3120
+ }
3121
+ /** The run's resolved durable ops as replay inputs: completed/failed steps + elapsed timers. */
3122
+ async remoteHistory(runId) {
3123
+ const checkpoints = await this.store.listCheckpoints(runId);
3124
+ const kindOf = {
3125
+ remote: "call",
3126
+ local: "step",
3127
+ sleep: "timer",
3128
+ signal: "signal"
3129
+ };
3130
+ const events = [];
3131
+ for (const cp of checkpoints) {
3132
+ if (cp.status === "completed" || cp.status === "failed") {
3133
+ if (cp.kind === "signal" && cp.name.startsWith("signal:child:")) {
3134
+ const completion = cp.output;
3135
+ events.push({
3136
+ seq: cp.seq,
3137
+ kind: "child",
3138
+ output: completion?.ok ? completion.value : void 0,
3139
+ error: completion && completion.ok === false ? {
3140
+ message: completion.error
3141
+ } : void 0
3142
+ });
3143
+ continue;
3144
+ }
3145
+ events.push({
3146
+ seq: cp.seq,
3147
+ kind: kindOf[cp.kind] ?? "step",
3148
+ // A signal checkpoint's name is the internal `signal:<token>`, not the workflow-level signal
3149
+ // name the replay used — omit it so the replay matches on seq + kind (its determinism anchor).
3150
+ name: cp.kind === "signal" ? void 0 : cp.name,
3151
+ output: cp.status === "completed" ? cp.output : void 0,
3152
+ error: cp.status === "failed" ? cp.error : void 0
3153
+ });
3154
+ } else if (cp.kind === "sleep" && cp.wakeAt != null && cp.wakeAt <= this.clock()) {
3155
+ events.push({
3156
+ seq: cp.seq,
3157
+ kind: "timer",
3158
+ name: cp.name
3159
+ });
3160
+ }
3161
+ }
3162
+ return events.sort((a, b) => a.seq - b.seq);
3163
+ }
3164
+ /** Apply a turn's commands: persist recorded local steps, dispatch remote calls, schedule timers.
3165
+ * Returns the earliest timer deadline to suspend on (or undefined — suspended on a result). */
3166
+ async applyCommands(run, commands) {
3167
+ let wakeAt;
3168
+ for (const cmd of commands) {
3169
+ const at = /* @__PURE__ */ new Date();
3170
+ const id = stepId(run.id, cmd.seq);
3171
+ if (cmd.kind === "recordStep") {
3172
+ const startedAt = cmd.startedAt != null ? new Date(cmd.startedAt) : at;
3173
+ const finishedAt = cmd.finishedAt != null ? new Date(cmd.finishedAt) : at;
3174
+ await this.store.saveCheckpoint(stepCheckpoint({
3175
+ runId: run.id,
3176
+ seq: cmd.seq,
3177
+ name: cmd.name,
3178
+ kind: "local",
3179
+ status: cmd.error ? "failed" : "completed",
3180
+ output: cmd.output,
3181
+ error: cmd.error,
3182
+ events: cmd.events,
3183
+ attempts: 1,
3184
+ enqueuedAt: startedAt,
3185
+ startedAt,
3186
+ finishedAt,
3187
+ // Carry the worker's `parallelGroup` (a Python `ctx.gather` tags every step in the fan with
3188
+ // the same group) onto the checkpoint, so the dashboard can render the steps as one parallel
3189
+ // group instead of a sequential list. Additive: undefined for ordinary sequential steps.
3190
+ parallelGroup: cmd.parallelGroup
3191
+ }));
3192
+ this.emit({
3193
+ type: cmd.error ? "step.failed" : "step.completed",
3194
+ runId: run.id,
3195
+ seq: cmd.seq,
3196
+ name: cmd.name,
3197
+ kind: "local",
3198
+ output: cmd.output,
3199
+ error: cmd.error
3200
+ });
3201
+ } else if (cmd.kind === "call") {
3202
+ if (await this.store.getCheckpoint(run.id, cmd.seq)) continue;
3203
+ await this.store.saveCheckpoint(stepCheckpoint({
3204
+ runId: run.id,
3205
+ seq: cmd.seq,
3206
+ name: cmd.name,
3207
+ kind: "remote",
3208
+ status: "pending",
3209
+ input: cmd.input,
3210
+ attempts: 1,
3211
+ workerGroup: cmd.group,
3212
+ enqueuedAt: at,
3213
+ startedAt: at,
3214
+ finishedAt: at,
3215
+ // A `ctx.gather_calls([...])` fan-out stamps every dispatched `call` in the fan with the
3216
+ // same group, so the dashboard renders the remote steps as one parallel fan (parity with
3217
+ // the gathered `recordStep`/`startChild` tags). Undefined for a lone sequential `ctx.call`.
3218
+ parallelGroup: cmd.parallelGroup
3219
+ }));
3220
+ await this.pool.dispatch({
3221
+ runId: run.id,
3222
+ seq: cmd.seq,
3223
+ name: cmd.name,
3224
+ stepId: id,
3225
+ group: cmd.group,
3226
+ input: cmd.input,
3227
+ traceparent: this.traceparent?.(),
3228
+ context: this.context?.(),
3229
+ attempt: 1
3230
+ }, void 0);
3231
+ this.emit({
3232
+ type: "step.started",
3233
+ runId: run.id,
3234
+ seq: cmd.seq,
3235
+ name: cmd.name,
3236
+ kind: "remote"
3237
+ });
3238
+ } else if (cmd.kind === "sleep") {
3239
+ const deadline = this.clock() + cmd.ms;
3240
+ await this.store.saveCheckpoint(stepCheckpoint({
3241
+ runId: run.id,
3242
+ seq: cmd.seq,
3243
+ name: `sleep:${cmd.seq}`,
3244
+ kind: "sleep",
3245
+ status: "pending",
3246
+ attempts: 1,
3247
+ wakeAt: deadline,
3248
+ enqueuedAt: at,
3249
+ startedAt: at,
3250
+ finishedAt: at
3251
+ }));
3252
+ wakeAt = wakeAt == null ? deadline : Math.min(wakeAt, deadline);
3253
+ } else if (cmd.kind === "waitSignal") {
3254
+ const buffered = await this.store.takeBufferedSignal(cmd.signal);
3255
+ if (buffered) {
3256
+ await this.store.saveCheckpoint(instantCheckpoint({
3257
+ runId: run.id,
3258
+ seq: cmd.seq,
3259
+ name: `signal:${cmd.signal}`,
3260
+ kind: "signal",
3261
+ output: buffered.payload
3262
+ }));
3263
+ setTimeout(() => void this.resume(run.id).catch(() => void 0), 0);
3264
+ } else {
3265
+ await this.store.putSignalWaiter({
3266
+ token: cmd.signal,
3267
+ runId: run.id,
3268
+ seq: cmd.seq
3269
+ });
3270
+ }
3271
+ } else if (cmd.kind === "startChild") {
3272
+ const childId = `${run.id}.child.${cmd.seq}`;
3273
+ await this.store.putSignalWaiter({
3274
+ token: `child:${childId}`,
3275
+ runId: run.id,
3276
+ seq: cmd.seq,
3277
+ // A `ctx.gather_children`/`ctx.all` fan-out stamps every `startChild` in the fan with the same
3278
+ // group. Thread it onto the waiter so the child's terminal `signal:child:<id>` checkpoint
3279
+ // (written by engine.signal when the child notifies the parent) carries the group and the
3280
+ // dashboard renders the fan as one parallel group. Undefined for a lone (non-fan) child.
3281
+ parallelGroup: cmd.parallelGroup
3282
+ });
3283
+ if (!await this.store.getRun(childId)) {
3284
+ queueMicrotask(() => void this.start(cmd.workflow, cmd.input, childId).catch(() => void 0));
3285
+ }
3286
+ } else {
3287
+ throw new Error(`remote workflow command '${cmd.kind}' is not supported yet`);
3288
+ }
3289
+ }
3290
+ return wakeAt;
3291
+ }
3292
+ /**
3293
+ * Undo the registered saga compensations in reverse and settle the run `cancelled`. Shared by EVERY
3294
+ * exit path of a run with a compensating cancel in flight — whether the resumed replay returned,
3295
+ * suspended, hit continue-as-new, or threw — so a cancel is never lost just because the body didn't
3296
+ * stop at a suspension point. Clears the in-memory cancel flag.
3297
+ */
3298
+ async compensateAndCancel(run, compensations) {
3299
+ this.cancelRequested.delete(run.id);
3300
+ for (let i = compensations.length - 1; i >= 0; i -= 1) {
3301
+ const comp = compensations[i];
3302
+ if (comp) await this.runCompensation(run, comp);
3303
+ }
3304
+ const error = {
3305
+ message: "cancelled"
3306
+ };
3307
+ await this.store.updateRun(run.id, {
3308
+ status: "cancelled",
3309
+ error,
3310
+ updatedAt: /* @__PURE__ */ new Date()
3311
+ });
3312
+ this.emit({
3313
+ type: "run.failed",
3314
+ runId: run.id,
3315
+ workflow: run.workflow,
3316
+ error
3317
+ });
3318
+ return {
3319
+ runId: run.id,
3320
+ status: "cancelled",
3321
+ error
3322
+ };
3323
+ }
3324
+ /** The run body, lease held + renewed by {@link execute}. */
3325
+ async runExecution(run, fn, registered) {
3326
+ if (run.status === "cancelling") this.cancelRequested.add(run.id);
3327
+ if (run.status === "pending") {
3328
+ await this.store.updateRun(run.id, {
3329
+ status: "running",
3330
+ updatedAt: /* @__PURE__ */ new Date()
3331
+ });
3332
+ run.status = "running";
3333
+ this.emit({
3334
+ type: "run.started",
3335
+ runId: run.id,
3336
+ workflow: run.workflow
3337
+ });
3338
+ }
3339
+ if (run.status !== "cancelling" && registered?.singleton && !await this.singletons.admit(run, registered.singleton)) {
3340
+ const wakeAt = this.singletons.retryWakeAt();
3341
+ await this.store.updateRun(run.id, {
3342
+ status: "suspended",
3343
+ wakeAt,
3344
+ updatedAt: /* @__PURE__ */ new Date()
3345
+ });
3346
+ this.emit({
3347
+ type: "run.suspended",
3348
+ runId: run.id,
3349
+ workflow: run.workflow
3350
+ });
3351
+ await this.store.releaseRunLock(run.id);
3352
+ return {
3353
+ runId: run.id,
3354
+ status: "suspended"
3355
+ };
3356
+ }
3357
+ const compensations = [];
3358
+ const snapshot = await this.store.listCheckpoints(run.id);
3359
+ const replay = /* @__PURE__ */ new Map();
3360
+ for (const cp of snapshot) replay.set(cp.seq, cp);
3361
+ const ctx = createWorkflowCtx(this.ctxHostFor(replay), run.id, compensations, run.workflow);
3362
+ try {
3363
+ const output = await fn(ctx, run.input);
3364
+ if (this.cancelRequested.has(run.id)) return this.compensateAndCancel(run, compensations);
3365
+ return this.settleRun(run, {
3366
+ kind: "completed",
3367
+ output
3368
+ });
3369
+ } catch (err) {
3370
+ if (err instanceof ContinueAsNew) {
3371
+ if (this.cancelRequested.has(run.id)) return this.compensateAndCancel(run, compensations);
3372
+ await this.store.updateRun(run.id, {
3373
+ status: "completed",
3374
+ output: void 0,
3375
+ error: void 0,
3376
+ updatedAt: /* @__PURE__ */ new Date()
3377
+ });
3378
+ this.emit({
3379
+ type: "run.completed",
3380
+ runId: run.id,
3381
+ workflow: run.workflow
3382
+ });
3383
+ void this.notifyParent(run.id, {
3384
+ ok: true,
3385
+ value: void 0
3386
+ });
3387
+ const nextId = nextContinuationId(run.id);
3388
+ queueMicrotask(() => void this.start(run.workflow, err.input, nextId).catch(() => void 0));
3389
+ return {
3390
+ runId: run.id,
3391
+ status: "completed"
3392
+ };
3393
+ }
3394
+ if (err instanceof WorkflowSuspended) {
3395
+ if (this.cancelRequested.has(run.id)) return this.compensateAndCancel(run, compensations);
3396
+ return this.settleRun(run, {
3397
+ kind: "suspended",
3398
+ wakeAt: err.wakeAt
3399
+ });
3400
+ }
3401
+ if (this.cancelRequested.has(run.id)) return this.compensateAndCancel(run, compensations);
3402
+ const error = {
3403
+ message: err instanceof Error ? err.message : String(err),
3404
+ stack: err instanceof Error ? err.stack : void 0
3405
+ };
3406
+ for (let i = compensations.length - 1; i >= 0; i -= 1) {
3407
+ const comp = compensations[i];
3408
+ if (!comp) continue;
3409
+ await this.runCompensation(run, comp);
3410
+ }
3411
+ return this.settleRun(run, {
3412
+ kind: "failed",
3413
+ error
3414
+ });
3415
+ } finally {
3416
+ await this.store.releaseRunLock(run.id);
3417
+ }
3418
+ }
3419
+ /**
3420
+ * Run one saga compensation, retried up to `compensationRetries`, emitting a `compensate:<step>`
3421
+ * step event for its outcome so a stranded undo is visible. Never throws — a permanently-failing
3422
+ * compensation is skipped so it can't mask the original failure.
3423
+ */
3424
+ async runCompensation(run, comp) {
3425
+ const name = `compensate:${comp.name}`;
3426
+ for (let attempt = 1; attempt <= this.compensationRetries; attempt += 1) {
3427
+ const startedAt = Date.now();
3428
+ try {
3429
+ await comp.fn();
3430
+ this.emit({
3431
+ type: "step.completed",
3432
+ runId: run.id,
3433
+ workflow: run.workflow,
3434
+ name,
3435
+ kind: "local",
3436
+ durationMs: Date.now() - startedAt
3437
+ });
3438
+ return;
3439
+ } catch (err) {
3440
+ if (attempt >= this.compensationRetries) {
3441
+ this.emit({
3442
+ type: "step.failed",
3443
+ runId: run.id,
3444
+ workflow: run.workflow,
3445
+ name,
3446
+ kind: "local",
3447
+ error: {
3448
+ message: err instanceof Error ? err.message : String(err)
3449
+ },
3450
+ durationMs: Date.now() - startedAt
3451
+ });
3452
+ }
3453
+ }
3454
+ }
3455
+ }
3456
+ /** The seam handed to {@link createWorkflowCtx}: the authoring API reaches durability + lifecycle
3457
+ * (checkpointing, dispatch, child start) through this, so the ctx primitives live in their own
3458
+ * module and the engine stays the orchestrator. */
3459
+ ctxHostFor(replay) {
3460
+ return {
3461
+ store: this.store,
3462
+ replay,
3463
+ clock: this.clock,
3464
+ webhookUrl: this.webhookUrl,
3465
+ startStep: /* @__PURE__ */ __name((s) => this.startStep(s), "startStep"),
3466
+ completeStep: /* @__PURE__ */ __name((s) => this.completeStep(s), "completeStep"),
3467
+ failStep: /* @__PURE__ */ __name((s) => this.failStep(s), "failStep"),
3468
+ callRemote: /* @__PURE__ */ __name((runId, seq, step, input, queue, transport, admission) => this.callRemote(runId, seq, step, input, queue, transport, replay, admission), "callRemote"),
3469
+ // Defer so a fast child can't reentrantly resume a still-running parent.
3470
+ startChild: /* @__PURE__ */ __name((workflow, input, id, priority) => {
3471
+ queueMicrotask(() => void this.start(workflow, input, id, {
3472
+ priority
3473
+ }).catch(() => void 0));
3474
+ }, "startChild"),
3475
+ // Shallow-merge into the run's searchAttributes (the ctx primitive makes this exactly-once).
3476
+ upsertSearchAttributes: /* @__PURE__ */ __name(async (runId, attrs) => {
3477
+ const run = await this.store.getRun(runId);
3478
+ await this.store.updateRun(runId, {
3479
+ searchAttributes: {
3480
+ ...run?.searchAttributes ?? {},
3481
+ ...attrs
3482
+ },
3483
+ updatedAt: /* @__PURE__ */ new Date()
3484
+ });
3485
+ }, "upsertSearchAttributes"),
3486
+ signalEntity: /* @__PURE__ */ __name((name, key, op, arg, reply) => {
3487
+ queueMicrotask(() => void this.entities.dispatch(name, key, op, arg, reply).catch(() => void 0));
3488
+ }, "signalEntity"),
3489
+ interceptStep: /* @__PURE__ */ __name((invocation, body) => this.interceptStep(invocation, body), "interceptStep")
3490
+ };
3491
+ }
3492
+ /**
3493
+ * Resume a run paused at a {@link WorkflowCtx.breakpoint} (e.g. the dashboard "continue" button).
3494
+ * Finds the run's pending breakpoint checkpoint and signals it. Returns null if the run isn't
3495
+ * paused at a breakpoint.
3496
+ */
3497
+ async continue(runId) {
3498
+ const checkpoints = await this.store.listCheckpoints(runId);
3499
+ const bp = checkpoints.find(isBreakpoint);
3500
+ if (!bp) return null;
3501
+ return this.signal(breakpointToken(runId, bp.seq), void 0);
3502
+ }
3503
+ /**
3504
+ * Read the latest value a run published for `key` via {@link WorkflowCtx.setEvent} — a
3505
+ * side-effect-free query of a live (or finished) run's state. Returns `undefined` if the run
3506
+ * never published that key. The suspend-model counterpart of a Temporal query.
3507
+ */
3508
+ async getEvent(runId, key) {
3509
+ const name = `event:${key}`;
3510
+ if (this.store.getLatestCheckpointByName) {
3511
+ const latest2 = await this.store.getLatestCheckpointByName(runId, name);
3512
+ return latest2?.output;
3513
+ }
3514
+ let latest;
3515
+ for (const cp of await this.store.listCheckpoints(runId)) if (cp.name === name) latest = cp.output;
3516
+ return latest;
3517
+ }
3518
+ /**
3519
+ * Register a validator gating `engine.update(runId, name, …)` for runs of `workflow`. The
3520
+ * validator runs BEFORE the update is delivered, so a rejection leaves the run untouched. One
3521
+ * validator per (workflow, update name); registering again replaces it.
3522
+ */
3523
+ registerUpdateValidator(workflow, name, validate) {
3524
+ this.updateValidators.set(`${workflow}:${name}`, validate);
3525
+ }
3526
+ /**
3527
+ * Deliver a validated update to the run waiting at `ctx.onUpdate(name)`. Runs the registered
3528
+ * validator (if any) first: on rejection returns `{ accepted: false, reason }` without disturbing
3529
+ * the run; otherwise delivers `arg` and resumes, returning `{ accepted: true, run }` (`run` is null
3530
+ * if nothing was waiting — a too-early or duplicate update).
3531
+ */
3532
+ async update(runId, name, arg) {
3533
+ const run = await this.store.getRun(runId);
3534
+ if (!run) return {
3535
+ accepted: false,
3536
+ reason: `run ${runId} not found`
3537
+ };
3538
+ const validate = this.updateValidators.get(`${run.workflow}:${name}`);
3539
+ if (validate) {
3540
+ try {
3541
+ const reason = await validate(arg);
3542
+ if (typeof reason === "string" && reason.length > 0) return {
3543
+ accepted: false,
3544
+ reason
3545
+ };
3546
+ } catch (err) {
3547
+ return {
3548
+ accepted: false,
3549
+ reason: err instanceof Error ? err.message : String(err)
3550
+ };
3551
+ }
3552
+ }
3553
+ const result = await this.signal(`update:${runId}:${name}`, arg);
3554
+ return {
3555
+ accepted: true,
3556
+ run: result
3557
+ };
3558
+ }
3559
+ async callRemote(runId, seq, step, input, queue, transport, replay, admission) {
3560
+ const existing = replay?.get(seq) ?? await this.store.getCheckpoint(runId, seq);
3561
+ if (existing && existing.name !== step.name) {
3562
+ throw new NonDeterminismError(runId, seq, step.name, existing.name);
3563
+ }
3564
+ if (existing?.status === "completed") return existing.output;
3565
+ if (this.pool.size === 0) throw new Error("remote steps require a Transport");
3566
+ if (step.timeoutMs) return this.callRemoteInMemory(runId, seq, step, input, transport);
3567
+ if (existing?.status === "pending") throw new WorkflowSuspended();
3568
+ let attempt = 1;
3569
+ if (existing?.status === "failed") {
3570
+ const maxAttempts = Math.max(1, step.retries ?? 1);
3571
+ const retryable = existing.error?.retryable !== false;
3572
+ if (!retryable || existing.attempts >= maxAttempts) throw new RemoteStepError(existing.error);
3573
+ if (existing.wakeAt == null) {
3574
+ const wakeAt = this.clock() + backoffDelay(existing.attempts, step);
3575
+ await this.store.saveCheckpoint({
3576
+ ...existing,
3577
+ wakeAt
3578
+ });
3579
+ throw new WorkflowSuspended(wakeAt);
3580
+ }
3581
+ if (this.clock() < existing.wakeAt) throw new WorkflowSuspended(existing.wakeAt);
3582
+ attempt = existing.attempts + 1;
3583
+ }
3584
+ const id = stepId(runId, seq);
3585
+ if (queue && this.admission.handles(queue)) {
3586
+ const decision = await this.admission.tryAdmit(queue, {
3587
+ priority: admission?.priority,
3588
+ key: admission?.fairnessKey ?? runId,
3589
+ waiterId: id
3590
+ });
3591
+ if (!decision.ok) {
3592
+ const waiters = this.queueWaiters.get(queue) ?? /* @__PURE__ */ new Set();
3593
+ waiters.add(runId);
3594
+ this.queueWaiters.set(queue, waiters);
3595
+ throw new WorkflowSuspended(decision.retryAt);
3596
+ }
3597
+ this.queueWaiters.get(queue)?.delete(runId);
3598
+ this.stepQueue.set(id, queue);
3599
+ }
3600
+ const validInput = step.input.parse(input);
3601
+ const enqueuedAt = /* @__PURE__ */ new Date();
3602
+ await this.store.saveCheckpoint({
3603
+ runId,
3604
+ seq,
3605
+ name: step.name,
3606
+ kind: "remote",
3607
+ stepId: id,
3608
+ status: "pending",
3609
+ input: validInput,
3610
+ attempts: attempt,
3611
+ workerGroup: step.group,
3612
+ enqueuedAt,
3613
+ startedAt: enqueuedAt,
3614
+ finishedAt: enqueuedAt
3615
+ });
3616
+ await this.pool.dispatch({
3617
+ runId,
3618
+ seq,
3619
+ name: step.name,
3620
+ stepId: id,
3621
+ group: step.group,
3622
+ input: validInput,
3623
+ traceparent: this.traceparent?.(),
3624
+ context: this.context?.(),
3625
+ priority: admission?.priority,
3626
+ attempt
3627
+ }, transport);
3628
+ this.emit({
3629
+ type: "step.started",
3630
+ runId,
3631
+ seq,
3632
+ name: step.name,
3633
+ kind: "remote"
3634
+ });
3635
+ throw new WorkflowSuspended();
3636
+ }
3637
+ /**
3638
+ * Complete a durable remote step from its worker result and resume the run — runs on whichever
3639
+ * instance receives the result (the dispatching one may be gone), so the run is crash/scale-safe.
3640
+ * A no-op if the checkpoint isn't `pending` (a duplicate or late delivery).
3641
+ */
3642
+ async completeRemoteResult(result) {
3643
+ const cp = await this.store.getCheckpoint(result.runId, result.seq);
3644
+ if (!cp || cp.status !== "pending") return;
3645
+ void this.releaseQueueSlot(cp.stepId).catch(() => void 0);
3646
+ const run = await this.store.getRun(result.runId);
3647
+ if (run && (run.status === "cancelled" || run.status === "completed")) return;
3648
+ const finishedAt = /* @__PURE__ */ new Date();
3649
+ const startedAt = result.startedAt ? new Date(result.startedAt) : cp.startedAt;
3650
+ await this.store.saveCheckpoint({
3651
+ ...cp,
3652
+ status: result.status,
3653
+ output: result.status === "completed" ? result.output : cp.output,
3654
+ error: result.error,
3655
+ events: result.events ?? cp.events,
3656
+ startedAt,
3657
+ finishedAt
3658
+ });
3659
+ this.emit({
3660
+ type: result.status === "completed" ? "step.completed" : "step.failed",
3661
+ runId: result.runId,
3662
+ seq: result.seq,
3663
+ name: cp.name,
3664
+ kind: cp.kind,
3665
+ output: result.output,
3666
+ error: result.error,
3667
+ queueMs: startedAt.getTime() - cp.enqueuedAt.getTime(),
3668
+ durationMs: finishedAt.getTime() - startedAt.getTime()
3669
+ });
3670
+ await this.resume(result.runId).catch((err) => {
3671
+ if (err instanceof NamespaceMismatch) return null;
3672
+ throw err;
3673
+ });
3674
+ }
3675
+ /**
3676
+ * Apply a remote workflow-turn {@link WorkflowDecision} durably — runs on WHATEVER instance receives
3677
+ * it over the broker (the dispatching one may be gone, or a point-to-point broker handed it to a
3678
+ * non-dispatcher). The durable, multi-instance-safe twin of {@link completeRemoteResult} for the
3679
+ * workflow TURN: look the run up by `decision.runId`, verify the decision matches the run's
3680
+ * CURRENTLY-awaited turn (`awaitingDecisionTaskId`) — so a stale / duplicate / foreign / re-driven
3681
+ * decision is dropped (applied AT MOST ONCE) — lease it, clear the marker, and apply the decision.
3682
+ */
3683
+ async completeRemoteDecision(decision) {
3684
+ const run = await this.store.getRun(decision.runId);
3685
+ if (!run || run.awaitingDecisionTaskId !== decision.taskId) return;
3686
+ if (run.status === "cancelled" || run.status === "completed" || run.status === "dead") return;
3687
+ if (this.namespace !== void 0 && run.namespace !== void 0 && run.namespace !== this.namespace) {
3688
+ return;
3689
+ }
3690
+ const nowMs = this.clock();
3691
+ if (!await this.store.tryLockRun(decision.runId, this.instanceId, nowMs + this.leaseMs, nowMs)) {
3692
+ return;
3693
+ }
3694
+ const renew = setInterval(() => {
3695
+ void this.store.renewRunLock(decision.runId, this.instanceId, this.clock() + this.leaseMs).catch(() => void 0);
3696
+ }, Math.max(50, Math.floor(this.leaseMs / 2)));
3697
+ renew.unref?.();
3698
+ try {
3699
+ const fresh = await this.store.getRun(decision.runId);
3700
+ if (!fresh || fresh.awaitingDecisionTaskId !== decision.taskId) return;
3701
+ if (fresh.status === "cancelled" || fresh.status === "completed" || fresh.status === "dead") {
3702
+ return;
3703
+ }
3704
+ await this.store.updateRun(decision.runId, {
3705
+ awaitingDecisionTaskId: void 0,
3706
+ wakeAt: void 0,
3707
+ updatedAt: /* @__PURE__ */ new Date()
3708
+ });
3709
+ fresh.awaitingDecisionTaskId = void 0;
3710
+ await this.applyDecision(fresh, decision);
3711
+ } finally {
3712
+ clearInterval(renew);
3713
+ await this.store.releaseRunLock(decision.runId);
3714
+ }
3715
+ }
3716
+ /**
3717
+ * A run-scoped heartbeat for a run suspended awaiting a workflow-turn decision (the dispatch path):
3718
+ * push its durable re-drive deadline (`wakeAt`) forward so a still-working worker's turn is not
3719
+ * re-dispatched. The durable counterpart of an inline turn's in-memory `heartbeatResets` rearm.
3720
+ */
3721
+ async rearmDecisionDeadline(runId) {
3722
+ const silenceMs = this.remoteAdvanceSilenceMs;
3723
+ if (silenceMs == null) return;
3724
+ const run = await this.store.getRun(runId);
3725
+ if (!run || run.status !== "suspended" || run.awaitingDecisionTaskId === void 0) return;
3726
+ await this.store.updateRun(runId, {
3727
+ wakeAt: this.clock() + silenceMs,
3728
+ updatedAt: /* @__PURE__ */ new Date()
3729
+ });
3730
+ }
3731
+ /**
3732
+ * A slot freed on `queue` (a fleet-wide signal): resume this instance's runs blocked on it so they
3733
+ * re-contend now instead of at their retry tick. Snapshot-and-clear — a run still blocked after the
3734
+ * retry re-registers itself, and one that's gone (cancelled/admitted) is dropped. Best-effort.
3735
+ */
3736
+ wakeQueueWaiters(queue) {
3737
+ const waiters = this.queueWaiters.get(queue);
3738
+ if (!waiters || waiters.size === 0) return;
3739
+ const runIds = [
3740
+ ...waiters
3741
+ ];
3742
+ waiters.clear();
3743
+ for (const runId of runIds) void this.resume(runId).catch(() => void 0);
3744
+ }
3745
+ /** Release the flow-control slot a dispatched step held (if any), by its stepId. */
3746
+ async releaseQueueSlot(id) {
3747
+ const queue = this.stepQueue.get(id);
3748
+ if (queue === void 0) return;
3749
+ this.stepQueue.delete(id);
3750
+ await this.admission.release(queue, id);
3751
+ }
3752
+ /** In-memory await path for a remote step with a liveness `timeoutMs` (re-dispatch on timeout). */
3753
+ async callRemoteInMemory(runId, seq, step, input, transport) {
3754
+ if (this.pool.size === 0) throw new Error("remote steps require a Transport");
3755
+ const validInput = step.input.parse(input);
3756
+ const id = stepId(runId, seq);
3757
+ const enqueuedAt = /* @__PURE__ */ new Date();
3758
+ this.emit({
3759
+ type: "step.started",
3760
+ runId,
3761
+ seq,
3762
+ name: step.name,
3763
+ kind: "remote"
3764
+ });
3765
+ const maxAttempts = step.timeoutMs ? Math.max(1, step.retries ?? 1) : 1;
3766
+ for (let attempt = 1; ; attempt += 1) {
3767
+ const resultPromise = new Promise((resolve, reject) => {
3768
+ this.pending.set(id, {
3769
+ resolve,
3770
+ reject
3771
+ });
3772
+ });
3773
+ await this.pool.dispatch({
3774
+ runId,
3775
+ seq,
3776
+ name: step.name,
3777
+ stepId: id,
3778
+ group: step.group,
3779
+ input: validInput,
3780
+ traceparent: this.traceparent?.(),
3781
+ context: this.context?.(),
3782
+ attempt
3783
+ }, transport);
3784
+ try {
3785
+ const resolution = step.timeoutMs ? await this.awaitWithHeartbeat(id, resultPromise, step.timeoutMs) : await resultPromise;
3786
+ const output = step.output.parse(resolution.output);
3787
+ const startedAt = resolution.startedAt ? new Date(resolution.startedAt) : enqueuedAt;
3788
+ await this.completeStep({
3789
+ runId,
3790
+ seq,
3791
+ name: step.name,
3792
+ kind: "remote",
3793
+ input: validInput,
3794
+ output,
3795
+ events: resolution.events,
3796
+ attempts: attempt,
3797
+ workerGroup: step.group,
3798
+ enqueuedAt,
3799
+ startedAt
3800
+ });
3801
+ return output;
3802
+ } catch (err) {
3803
+ this.pending.delete(id);
3804
+ if (err instanceof RemoteStepTimeout && attempt < maxAttempts) continue;
3805
+ throw err;
3806
+ }
3807
+ }
3808
+ }
3809
+ /**
3810
+ * Await `resultPromise`, but reject with `onTimeout()` if neither it settles nor a heartbeat for `id`
3811
+ * arrives within `timeoutMs`. Each heartbeat (delivered via `transport.onHeartbeat`, looked up in
3812
+ * `heartbeatResets` by `id`) REARMS the window, so a worker that keeps beating stays alive past
3813
+ * `timeoutMs`. Shared by the remote-STEP liveness (keyed by stepId) and the remote-WORKFLOW advance
3814
+ * liveness (keyed by runId); the caller supplies the timeout error and any extra cleanup via `onTimeout`.
3815
+ */
3816
+ awaitWithLivenessDeadline(id, resultPromise, timeoutMs, onTimeout) {
3817
+ return new Promise((resolve, reject) => {
3818
+ let timer;
3819
+ const cleanup = /* @__PURE__ */ __name(() => {
3820
+ clearTimeout(timer);
3821
+ this.heartbeatResets.delete(id);
3822
+ }, "cleanup");
3823
+ const arm = /* @__PURE__ */ __name(() => {
3824
+ timer = setTimeout(() => {
3825
+ cleanup();
3826
+ reject(onTimeout());
3827
+ }, timeoutMs);
3828
+ timer.unref?.();
3829
+ }, "arm");
3830
+ this.heartbeatResets.set(id, () => {
3831
+ clearTimeout(timer);
3832
+ arm();
3833
+ });
3834
+ arm();
3835
+ resultPromise.then((value) => {
3836
+ cleanup();
3837
+ resolve(value);
3838
+ }, (err) => {
3839
+ cleanup();
3840
+ reject(err);
3841
+ });
3842
+ });
3843
+ }
3844
+ /** Remote-STEP liveness: await a worker result, timing out (with the step's pending-map cleanup) to
3845
+ * `RemoteStepTimeout` if it neither lands nor beats within `timeoutMs`. See {@link awaitWithLivenessDeadline}. */
3846
+ awaitWithHeartbeat(id, resultPromise, timeoutMs) {
3847
+ return this.awaitWithLivenessDeadline(id, resultPromise, timeoutMs, () => {
3848
+ this.pending.delete(id);
3849
+ return new RemoteStepTimeout(id, timeoutMs);
3850
+ });
3851
+ }
3852
+ };
3853
+ var RemoteStepError = class extends Error {
3854
+ static {
3855
+ __name(this, "RemoteStepError");
3856
+ }
3857
+ stepError;
3858
+ constructor(stepError) {
3859
+ super(stepError?.message ?? "remote step failed");
3860
+ this.name = "RemoteStepError";
3861
+ this.stepError = stepError;
3862
+ }
3863
+ };
3864
+
3865
+ // src/interfaces.ts
3866
+ var TERMINAL_RUN_STATUSES = [
3867
+ "completed",
3868
+ "failed",
3869
+ "cancelled",
3870
+ "dead"
3871
+ ];
3872
+
3873
+ // src/remote-step-factory.ts
3874
+ function remoteStep(config) {
3875
+ return {
3876
+ ...config,
3877
+ group: config.group ?? config.name.split(".")[0] ?? config.name,
3878
+ __remote: true
3879
+ };
3880
+ }
3881
+ __name(remoteStep, "remoteStep");
3882
+
3883
+ // src/codec-state-store.ts
3884
+ var CodecStateStore = class {
3885
+ static {
3886
+ __name(this, "CodecStateStore");
3887
+ }
3888
+ inner;
3889
+ codec;
3890
+ constructor(inner, codec) {
3891
+ this.inner = inner;
3892
+ this.codec = codec;
3893
+ }
3894
+ enc(v) {
3895
+ return v === void 0 ? void 0 : this.codec.encode(v);
3896
+ }
3897
+ dec(v) {
3898
+ return v === void 0 ? void 0 : this.codec.decode(v);
3899
+ }
3900
+ encRun(run) {
3901
+ return {
3902
+ ...run,
3903
+ input: this.enc(run.input),
3904
+ output: this.enc(run.output)
3905
+ };
3906
+ }
3907
+ decRun(run) {
3908
+ return run && {
3909
+ ...run,
3910
+ input: this.dec(run.input),
3911
+ output: this.dec(run.output)
3912
+ };
3913
+ }
3914
+ encCp(cp) {
3915
+ return {
3916
+ ...cp,
3917
+ input: this.enc(cp.input),
3918
+ output: this.enc(cp.output)
3919
+ };
3920
+ }
3921
+ decCp(cp) {
3922
+ return cp && {
3923
+ ...cp,
3924
+ input: this.dec(cp.input),
3925
+ output: this.dec(cp.output)
3926
+ };
3927
+ }
3928
+ ensureSchema() {
3929
+ return this.inner.ensureSchema?.() ?? Promise.resolve();
3930
+ }
3931
+ createRun(run) {
3932
+ return this.inner.createRun(this.encRun(run));
3933
+ }
3934
+ updateRun(runId, patch) {
3935
+ const next = {
3936
+ ...patch
3937
+ };
3938
+ if ("input" in patch) next.input = this.enc(patch.input);
3939
+ if ("output" in patch) next.output = this.enc(patch.output);
3940
+ return this.inner.updateRun(runId, next);
3941
+ }
3942
+ async getRun(runId) {
3943
+ return this.decRun(await this.inner.getRun(runId));
3944
+ }
3945
+ deleteRun(runId) {
3946
+ return this.inner.deleteRun(runId);
3947
+ }
3948
+ async getCheckpoint(runId, seq) {
3949
+ return this.decCp(await this.inner.getCheckpoint(runId, seq));
3950
+ }
3951
+ saveCheckpoint(checkpoint) {
3952
+ return this.inner.saveCheckpoint(this.encCp(checkpoint));
3953
+ }
3954
+ transaction(work) {
3955
+ if (!this.inner.transaction) {
3956
+ throw new Error("the wrapped store does not support transactions");
3957
+ }
3958
+ return this.inner.transaction((tx) => work({
3959
+ raw: tx.raw,
3960
+ saveCheckpoint: /* @__PURE__ */ __name((cp) => tx.saveCheckpoint(this.encCp(cp)), "saveCheckpoint")
3961
+ }));
3962
+ }
3963
+ async listIncompleteRuns(namespace) {
3964
+ return (await this.inner.listIncompleteRuns(namespace)).map((r) => this.decRun(r));
3965
+ }
3966
+ async listPendingRuns(limit, namespace) {
3967
+ return (await this.inner.listPendingRuns(limit, namespace)).map((r) => this.decRun(r));
3968
+ }
3969
+ async listDueTimers(nowMs, namespace) {
3970
+ return (await this.inner.listDueTimers(nowMs, namespace)).map((r) => this.decRun(r));
3971
+ }
3972
+ tryLockRun(runId, owner, leaseUntilMs, nowMs) {
3973
+ return this.inner.tryLockRun(runId, owner, leaseUntilMs, nowMs);
3974
+ }
3975
+ releaseRunLock(runId) {
3976
+ return this.inner.releaseRunLock(runId);
3977
+ }
3978
+ renewRunLock(runId, owner, leaseUntilMs) {
3979
+ return this.inner.renewRunLock(runId, owner, leaseUntilMs);
3980
+ }
3981
+ putSignalWaiter(waiter) {
3982
+ return this.inner.putSignalWaiter(waiter);
3983
+ }
3984
+ takeSignalWaiter(token) {
3985
+ return this.inner.takeSignalWaiter(token);
3986
+ }
3987
+ listSignalWaiters(prefix) {
3988
+ return this.inner.listSignalWaiters(prefix);
3989
+ }
3990
+ bufferSignal(token, payload) {
3991
+ return this.inner.bufferSignal(token, this.enc(payload));
3992
+ }
3993
+ async takeBufferedSignal(token) {
3994
+ const buffered = await this.inner.takeBufferedSignal(token);
3995
+ return buffered && {
3996
+ payload: this.dec(buffered.payload)
3997
+ };
3998
+ }
3999
+ async listRuns(query) {
4000
+ return (await this.inner.listRuns(query)).map((r) => this.decRun(r));
4001
+ }
4002
+ async listCheckpoints(runId) {
4003
+ return (await this.inner.listCheckpoints(runId)).map((c) => this.decCp(c));
4004
+ }
4005
+ async getLatestCheckpointByName(runId, name) {
4006
+ if (this.inner.getLatestCheckpointByName) {
4007
+ const cp = await this.inner.getLatestCheckpointByName(runId, name);
4008
+ return cp ? this.decCp(cp) : void 0;
4009
+ }
4010
+ let latest;
4011
+ for (const cp of await this.inner.listCheckpoints(runId)) if (cp.name === name) latest = cp;
4012
+ return latest ? this.decCp(latest) : void 0;
4013
+ }
4014
+ async listCheckpointsByNamePrefix(runId, prefixes) {
4015
+ const matches = this.inner.listCheckpointsByNamePrefix ? await this.inner.listCheckpointsByNamePrefix(runId, prefixes) : (await this.inner.listCheckpoints(runId)).filter((cp) => prefixes.some((p) => cp.name.startsWith(p)));
4016
+ return matches.map((c) => this.decCp(c));
4017
+ }
4018
+ };
4019
+
4020
+ // src/metrics.ts
4021
+ function collectMetrics(engine) {
4022
+ const m = {
4023
+ runs: {
4024
+ started: 0,
4025
+ completed: 0,
4026
+ failed: 0,
4027
+ suspended: 0
4028
+ },
4029
+ steps: {
4030
+ started: 0,
4031
+ completed: 0,
4032
+ failed: 0
4033
+ },
4034
+ byWorkflow: {},
4035
+ stepDuration: {
4036
+ sumMs: 0,
4037
+ count: 0
4038
+ }
4039
+ };
4040
+ const wf = /* @__PURE__ */ __name((name) => {
4041
+ const k = name ?? "unknown";
4042
+ let entry = m.byWorkflow[k];
4043
+ if (!entry) {
4044
+ entry = {
4045
+ started: 0,
4046
+ completed: 0,
4047
+ failed: 0
4048
+ };
4049
+ m.byWorkflow[k] = entry;
4050
+ }
4051
+ return entry;
4052
+ }, "wf");
4053
+ const stop = engine.subscribe((e) => {
4054
+ switch (e.type) {
4055
+ case "run.started":
4056
+ m.runs.started += 1;
4057
+ wf(e.workflow).started += 1;
4058
+ break;
4059
+ case "run.completed":
4060
+ m.runs.completed += 1;
4061
+ wf(e.workflow).completed += 1;
4062
+ break;
4063
+ case "run.failed":
4064
+ m.runs.failed += 1;
4065
+ wf(e.workflow).failed += 1;
4066
+ break;
4067
+ case "run.suspended":
4068
+ m.runs.suspended += 1;
4069
+ break;
4070
+ case "step.started":
4071
+ m.steps.started += 1;
4072
+ break;
4073
+ case "step.completed":
4074
+ m.steps.completed += 1;
4075
+ if (e.durationMs != null) {
4076
+ m.stepDuration.sumMs += e.durationMs;
4077
+ m.stepDuration.count += 1;
4078
+ }
4079
+ break;
4080
+ case "step.failed":
4081
+ m.steps.failed += 1;
4082
+ break;
4083
+ }
4084
+ });
4085
+ return {
4086
+ snapshot: /* @__PURE__ */ __name(() => structuredClone(m), "snapshot"),
4087
+ stop,
4088
+ prometheus: /* @__PURE__ */ __name(() => {
4089
+ const lines = [];
4090
+ lines.push("# TYPE durable_runs_total counter");
4091
+ for (const [k, v] of Object.entries(m.runs)) lines.push(`durable_runs_total{event="${k}"} ${v}`);
4092
+ lines.push("# TYPE durable_steps_total counter");
4093
+ for (const [k, v] of Object.entries(m.steps)) lines.push(`durable_steps_total{event="${k}"} ${v}`);
4094
+ lines.push("# TYPE durable_runs_by_workflow_total counter");
4095
+ for (const [name, v] of Object.entries(m.byWorkflow)) for (const [event, n] of Object.entries(v)) lines.push(`durable_runs_by_workflow_total{workflow="${name}",event="${event}"} ${n}`);
4096
+ lines.push("# TYPE durable_step_duration_ms_sum counter");
4097
+ lines.push(`durable_step_duration_ms_sum ${m.stepDuration.sumMs}`);
4098
+ lines.push("# TYPE durable_step_duration_count counter");
4099
+ lines.push(`durable_step_duration_count ${m.stepDuration.count}`);
4100
+ return `${lines.join("\n")}
4101
+ `;
4102
+ }, "prometheus")
4103
+ };
4104
+ }
4105
+ __name(collectMetrics, "collectMetrics");
4106
+
4107
+ // src/scheduler.ts
4108
+ import { createRequire } from "node:module";
4109
+ var nodeRequire = createRequire(import.meta.url);
4110
+ var defaultSleep = /* @__PURE__ */ __name((ms) => new Promise((r) => setTimeout(r, ms)), "defaultSleep");
4111
+ function scheduledRunId(key, everyMs, nowMs) {
4112
+ return `sched:${key}:${Math.floor(nowMs / everyMs)}`;
4113
+ }
4114
+ __name(scheduledRunId, "scheduledRunId");
4115
+ var cronParser;
4116
+ function loadCronParser() {
4117
+ if (cronParser) return cronParser;
4118
+ try {
4119
+ cronParser = nodeRequire("cron-parser");
4120
+ } catch {
4121
+ throw new Error('cron schedules need the optional peer dependency "cron-parser" \u2014 install it (e.g. `npm i cron-parser`).');
4122
+ }
4123
+ return cronParser;
4124
+ }
4125
+ __name(loadCronParser, "loadCronParser");
4126
+ function prevCronFireMs(expr, nowMs, timezone = "UTC") {
4127
+ const parser = loadCronParser();
4128
+ const it = parser.parseExpression(expr, {
4129
+ currentDate: new Date(nowMs + 1),
4130
+ tz: timezone
4131
+ });
4132
+ return it.prev().toDate().getTime();
4133
+ }
4134
+ __name(prevCronFireMs, "prevCronFireMs");
4135
+ function scheduleRunIdAt(s, nowMs) {
4136
+ if (s.cron != null) return `sched:${s.key}:${prevCronFireMs(s.cron, nowMs, s.timezone)}`;
4137
+ if (s.everyMs != null) return scheduledRunId(s.key, s.everyMs, nowMs);
4138
+ throw new Error(`schedule "${s.key}" needs either "everyMs" or "cron"`);
4139
+ }
4140
+ __name(scheduleRunIdAt, "scheduleRunIdAt");
4141
+ function scheduleRunIdsAt(s, nowMs) {
4142
+ const current = scheduleRunIdAt(s, nowMs);
4143
+ if (!s.backfill || s.backfill.maxCatchup <= 0) return [
4144
+ current
4145
+ ];
4146
+ const ids = [];
4147
+ if (s.everyMs != null) {
4148
+ const bucket = Math.floor(nowMs / s.everyMs);
4149
+ const oldest = Math.max(0, bucket - s.backfill.maxCatchup);
4150
+ for (let b = oldest; b < bucket; b += 1) ids.push(`sched:${s.key}:${b}`);
4151
+ } else if (s.cron != null) {
4152
+ const prior = [];
4153
+ let cursor = prevCronFireMs(s.cron, nowMs, s.timezone);
4154
+ for (let i = 0; i < s.backfill.maxCatchup; i += 1) {
4155
+ const before = prevCronFireMs(s.cron, cursor - 1, s.timezone);
4156
+ prior.push(`sched:${s.key}:${before}`);
4157
+ cursor = before;
4158
+ }
4159
+ ids.push(...prior.reverse());
4160
+ }
4161
+ ids.push(current);
4162
+ return ids;
4163
+ }
4164
+ __name(scheduleRunIdsAt, "scheduleRunIdsAt");
4165
+ async function runSchedules(engine, schedules, nowMs, opts) {
4166
+ const random = opts?.random ?? Math.random;
4167
+ const sleep = opts?.sleep ?? defaultSleep;
4168
+ const ids = [];
4169
+ for (const s of schedules) {
4170
+ if (s.paused) continue;
4171
+ if (s.overlap === "skip" && s.everyMs) {
4172
+ const prevBucket = Math.floor(nowMs / s.everyMs) - 1;
4173
+ if (prevBucket >= 0) {
4174
+ const prev = await engine.getRun(`sched:${s.key}:${prevBucket}`);
4175
+ if (prev && (prev.status === "running" || prev.status === "suspended")) continue;
4176
+ }
4177
+ }
4178
+ if (s.jitter && s.jitter > 0) await sleep(Math.floor(random() * s.jitter));
4179
+ for (const runId of scheduleRunIdsAt(s, nowMs)) {
4180
+ await engine.start(s.workflow, s.input, runId);
4181
+ ids.push(runId);
4182
+ }
4183
+ }
4184
+ return ids;
4185
+ }
4186
+ __name(runSchedules, "runSchedules");
4187
+
4188
+ // src/search-attributes.ts
4189
+ function compare(actual, op, expected) {
4190
+ switch (op) {
4191
+ case "eq":
4192
+ return actual === expected;
4193
+ case "ne":
4194
+ return actual !== expected;
4195
+ case "gt":
4196
+ return actual != null && actual > expected;
4197
+ case "gte":
4198
+ return actual != null && actual >= expected;
4199
+ case "lt":
4200
+ return actual != null && actual < expected;
4201
+ case "lte":
4202
+ return actual != null && actual <= expected;
4203
+ }
4204
+ }
4205
+ __name(compare, "compare");
4206
+ function matchesAttributes(attributes, filters) {
4207
+ if (!filters?.length) return true;
4208
+ if (!attributes) return false;
4209
+ return filters.every((f) => f.key in attributes && compare(attributes[f.key], f.op, f.value));
4210
+ }
4211
+ __name(matchesAttributes, "matchesAttributes");
4212
+ function applyAttributeQuery(rows, query) {
4213
+ const filtered = rows.filter((r) => matchesAttributes(r.searchAttributes, query.attributes));
4214
+ const offset = query.offset ?? 0;
4215
+ const limit = query.limit ?? filtered.length;
4216
+ return filtered.slice(offset, offset + limit);
4217
+ }
4218
+ __name(applyAttributeQuery, "applyAttributeQuery");
4219
+ function normalizeAttributeRows(runId, attributes) {
4220
+ if (!attributes) return [];
4221
+ const out = [];
4222
+ for (const [key, value] of Object.entries(attributes)) {
4223
+ if (typeof value === "number") {
4224
+ out.push({
4225
+ runId,
4226
+ key,
4227
+ strValue: null,
4228
+ numValue: value
4229
+ });
4230
+ } else if (typeof value === "boolean") {
4231
+ out.push({
4232
+ runId,
4233
+ key,
4234
+ strValue: value ? "true" : "false",
4235
+ numValue: null
4236
+ });
4237
+ } else {
4238
+ out.push({
4239
+ runId,
4240
+ key,
4241
+ strValue: value,
4242
+ numValue: null
4243
+ });
4244
+ }
4245
+ }
4246
+ return out;
4247
+ }
4248
+ __name(normalizeAttributeRows, "normalizeAttributeRows");
4249
+ function sqlComparator(op) {
4250
+ switch (op) {
4251
+ case "eq":
4252
+ return "=";
4253
+ case "ne":
4254
+ return "<>";
4255
+ case "gt":
4256
+ return ">";
4257
+ case "gte":
4258
+ return ">=";
4259
+ case "lt":
4260
+ return "<";
4261
+ case "lte":
4262
+ return "<=";
4263
+ }
4264
+ }
4265
+ __name(sqlComparator, "sqlComparator");
4266
+ function attributeColumnFor(filter) {
4267
+ return typeof filter.value === "number" ? "numValue" : "strValue";
4268
+ }
4269
+ __name(attributeColumnFor, "attributeColumnFor");
4270
+ function attributeOperand(filter) {
4271
+ if (typeof filter.value === "boolean") return filter.value ? "true" : "false";
4272
+ return filter.value;
4273
+ }
4274
+ __name(attributeOperand, "attributeOperand");
4275
+
4276
+ // src/tokens.ts
4277
+ var STATE_STORE = Symbol.for("nestjs-durable:STATE_STORE");
4278
+ var TRANSPORT = Symbol.for("nestjs-durable:TRANSPORT");
4279
+ var DURABLE_OPTIONS = Symbol.for("nestjs-durable:DURABLE_OPTIONS");
4280
+ var STATE_STORE_CANONICAL = Symbol.for("@dudousxd/nestjs-durable:state-store");
4281
+ var TRANSPORT_CANONICAL = Symbol.for("@dudousxd/nestjs-durable:transport");
4282
+ var DURABLE_OPTIONS_CANONICAL = Symbol.for("@dudousxd/nestjs-durable:options");
4283
+
4284
+ // src/testing/in-memory-state-store.ts
4285
+ var InMemoryStateStore = class {
4286
+ static {
4287
+ __name(this, "InMemoryStateStore");
4288
+ }
4289
+ runs = /* @__PURE__ */ new Map();
4290
+ checkpoints = /* @__PURE__ */ new Map();
4291
+ signalWaiters = /* @__PURE__ */ new Map();
4292
+ /**
4293
+ * Normalized search-attribute side-table, the in-memory analog of the SQL stores'
4294
+ * `durable_run_attributes`: `key -> (runId -> row)`. Maintained on every create/update so an
4295
+ * attribute query can be pushed DOWN to a key-indexed candidate set instead of scanning every run
4296
+ * and comparing in-process. Mirrors {@link normalizeAttributeRows} so behavior matches the SQL path.
4297
+ */
4298
+ attributeIndex = /* @__PURE__ */ new Map();
4299
+ /** Test/observability hook: how many candidate runs the last attribute query's index produced. */
4300
+ lastAttributeCandidates = 0;
4301
+ /**
4302
+ * Test/observability hook: how many checkpoint rows the LAST checkpoint read materialized (the rows
4303
+ * actually returned to the caller). `listCheckpoints` returns all rows for the run; the targeted
4304
+ * {@link getLatestCheckpointByName} / {@link listCheckpointsByNamePrefix} return only the matches —
4305
+ * so this lets the benchmark contrast "fetch N, scan in JS" against "fetch the k that match".
4306
+ */
4307
+ lastCheckpointRowsRead = 0;
4308
+ key(runId, seq) {
4309
+ return `${runId}:${seq}`;
4310
+ }
4311
+ /** Drop then re-add a run's normalized attribute rows so the index tracks its current attributes. */
4312
+ reindexAttributes(runId, attributes) {
4313
+ for (const byRun of this.attributeIndex.values()) byRun.delete(runId);
4314
+ for (const row of normalizeAttributeRows(runId, attributes)) {
4315
+ let byRun = this.attributeIndex.get(row.key);
4316
+ if (!byRun) {
4317
+ byRun = /* @__PURE__ */ new Map();
4318
+ this.attributeIndex.set(row.key, byRun);
4319
+ }
4320
+ byRun.set(runId, row);
4321
+ }
4322
+ }
4323
+ async createRun(run) {
4324
+ this.runs.set(run.id, {
4325
+ ...run,
4326
+ namespace: run.namespace ?? "default"
4327
+ });
4328
+ this.reindexAttributes(run.id, run.searchAttributes);
4329
+ }
4330
+ async updateRun(runId, patch) {
4331
+ const existing = this.runs.get(runId);
4332
+ if (!existing) throw new Error(`run ${runId} not found`);
4333
+ const next = {
4334
+ ...existing,
4335
+ ...patch
4336
+ };
4337
+ this.runs.set(runId, next);
4338
+ if ("searchAttributes" in patch) this.reindexAttributes(runId, next.searchAttributes);
4339
+ }
4340
+ async getRun(runId) {
4341
+ const run = this.runs.get(runId);
4342
+ return run ? {
4343
+ ...run
4344
+ } : null;
4345
+ }
4346
+ async deleteRun(runId) {
4347
+ this.runs.delete(runId);
4348
+ for (const [key, cp] of this.checkpoints) {
4349
+ if (cp.runId === runId) this.checkpoints.delete(key);
4350
+ }
4351
+ for (const [token, waiter] of this.signalWaiters) {
4352
+ if (waiter.runId === runId) this.signalWaiters.delete(token);
4353
+ }
4354
+ this.reindexAttributes(runId, void 0);
4355
+ }
4356
+ async getCheckpoint(runId, seq) {
4357
+ const cp = this.checkpoints.get(this.key(runId, seq));
4358
+ return cp ? {
4359
+ ...cp
4360
+ } : null;
4361
+ }
4362
+ async saveCheckpoint(checkpoint) {
4363
+ this.checkpoints.set(this.key(checkpoint.runId, checkpoint.seq), {
4364
+ ...checkpoint
4365
+ });
4366
+ }
4367
+ async listIncompleteRuns(namespace) {
4368
+ return [
4369
+ ...this.runs.values()
4370
+ ].filter((r) => (r.status === "running" || r.status === "cancelling") && (namespace === void 0 || r.namespace === namespace)).map((r) => ({
4371
+ ...r
4372
+ }));
4373
+ }
4374
+ async listPendingRuns(limit, namespace) {
4375
+ return [
4376
+ ...this.runs.values()
4377
+ ].filter((r) => r.status === "pending" && (namespace === void 0 || r.namespace === namespace)).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id)).slice(0, limit).map((r) => ({
4378
+ ...r
4379
+ }));
4380
+ }
4381
+ async listDueTimers(nowMs, namespace) {
4382
+ return [
4383
+ ...this.runs.values()
4384
+ ].filter((r) => r.status === "suspended" && r.wakeAt !== void 0 && r.wakeAt <= nowMs && (namespace === void 0 || r.namespace === namespace)).map((r) => ({
4385
+ ...r
4386
+ }));
4387
+ }
4388
+ async tryLockRun(runId, owner, leaseUntilMs, nowMs) {
4389
+ const run = this.runs.get(runId);
4390
+ if (!run) return false;
4391
+ if (run.lockedUntil !== void 0 && run.lockedUntil > nowMs) return false;
4392
+ run.lockedBy = owner;
4393
+ run.lockedUntil = leaseUntilMs;
4394
+ return true;
4395
+ }
4396
+ async releaseRunLock(runId) {
4397
+ const run = this.runs.get(runId);
4398
+ if (run) {
4399
+ run.lockedBy = void 0;
4400
+ run.lockedUntil = void 0;
4401
+ }
4402
+ }
4403
+ async renewRunLock(runId, owner, leaseUntilMs) {
4404
+ const run = this.runs.get(runId);
4405
+ if (!run || run.lockedBy !== owner) return false;
4406
+ run.lockedUntil = leaseUntilMs;
4407
+ return true;
4408
+ }
4409
+ async putSignalWaiter(waiter) {
4410
+ this.signalWaiters.set(waiter.token, {
4411
+ ...waiter
4412
+ });
4413
+ }
4414
+ async takeSignalWaiter(token) {
4415
+ const waiter = this.signalWaiters.get(token);
4416
+ if (!waiter) return null;
4417
+ this.signalWaiters.delete(token);
4418
+ return {
4419
+ ...waiter
4420
+ };
4421
+ }
4422
+ async listSignalWaiters(prefix) {
4423
+ return [
4424
+ ...this.signalWaiters.values()
4425
+ ].filter((w) => w.token.startsWith(prefix)).map((w) => ({
4426
+ ...w
4427
+ }));
4428
+ }
4429
+ // No real DB transaction (there's no DB) — run the work and save the checkpoint. Exactly-once
4430
+ // across a crash needs a SQL store; this keeps `ctx.transaction` usable in tests / local dev.
4431
+ async transaction(work) {
4432
+ return work({
4433
+ raw: this,
4434
+ saveCheckpoint: /* @__PURE__ */ __name((cp) => this.saveCheckpoint(cp), "saveCheckpoint")
4435
+ });
4436
+ }
4437
+ bufferedSignals = /* @__PURE__ */ new Map();
4438
+ async bufferSignal(token, payload) {
4439
+ const queue = this.bufferedSignals.get(token) ?? [];
4440
+ queue.push(payload);
4441
+ this.bufferedSignals.set(token, queue);
4442
+ }
4443
+ async takeBufferedSignal(token) {
4444
+ const queue = this.bufferedSignals.get(token);
4445
+ if (!queue || queue.length === 0) return null;
4446
+ const payload = queue.shift();
4447
+ if (queue.length === 0) this.bufferedSignals.delete(token);
4448
+ return {
4449
+ payload
4450
+ };
4451
+ }
4452
+ /**
4453
+ * Candidate run ids satisfying ONE attribute predicate, served from {@link attributeIndex} — the
4454
+ * pushdown step. Numeric predicates scan only `numValue` rows under the key; string/boolean ones
4455
+ * scan `strValue` rows. This is the in-memory analog of the SQL EXISTS on `durable_run_attributes`.
4456
+ */
4457
+ candidatesForFilter(f) {
4458
+ const byRun = this.attributeIndex.get(f.key);
4459
+ const out = /* @__PURE__ */ new Set();
4460
+ if (!byRun) return out;
4461
+ const numeric = typeof f.value === "number";
4462
+ const operand = typeof f.value === "boolean" ? f.value ? "true" : "false" : f.value;
4463
+ for (const row of byRun.values()) {
4464
+ const actual = numeric ? row.numValue : row.strValue;
4465
+ if (actual == null) continue;
4466
+ let ok = false;
4467
+ switch (f.op) {
4468
+ case "eq":
4469
+ ok = actual === operand;
4470
+ break;
4471
+ case "ne":
4472
+ ok = actual !== operand;
4473
+ break;
4474
+ case "gt":
4475
+ ok = actual > operand;
4476
+ break;
4477
+ case "gte":
4478
+ ok = actual >= operand;
4479
+ break;
4480
+ case "lt":
4481
+ ok = actual < operand;
4482
+ break;
4483
+ case "lte":
4484
+ ok = actual <= operand;
4485
+ break;
4486
+ }
4487
+ if (ok) out.add(row.runId);
4488
+ }
4489
+ return out;
4490
+ }
4491
+ async listRuns(query) {
4492
+ let runs = [
4493
+ ...this.runs.values()
4494
+ ];
4495
+ if (query.workflow) runs = runs.filter((r) => r.workflow === query.workflow);
4496
+ if (query.status) runs = runs.filter((r) => r.status === query.status);
4497
+ if (query.statuses) runs = runs.filter((r) => query.statuses?.includes(r.status));
4498
+ if (query.tag) runs = runs.filter((r) => r.tags?.includes(query.tag));
4499
+ if (query.namespace !== void 0) runs = runs.filter((r) => r.namespace === query.namespace);
4500
+ if (query.attributes?.length) {
4501
+ let candidates = null;
4502
+ for (const f of query.attributes) {
4503
+ const next = this.candidatesForFilter(f);
4504
+ if (candidates == null) {
4505
+ candidates = next;
4506
+ } else {
4507
+ const prev = candidates;
4508
+ candidates = new Set([
4509
+ ...prev
4510
+ ].filter((id) => next.has(id)));
4511
+ }
4512
+ if (candidates.size === 0) break;
4513
+ }
4514
+ const ids = candidates ?? /* @__PURE__ */ new Set();
4515
+ this.lastAttributeCandidates = ids.size;
4516
+ runs = runs.filter((r) => ids.has(r.id));
4517
+ }
4518
+ runs.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
4519
+ const offset = query.offset ?? 0;
4520
+ const limit = query.limit ?? runs.length;
4521
+ return runs.slice(offset, offset + limit).map((r) => ({
4522
+ ...r
4523
+ }));
4524
+ }
4525
+ async listCheckpoints(runId) {
4526
+ const rows = [
4527
+ ...this.checkpoints.values()
4528
+ ].filter((cp) => cp.runId === runId).sort((a, b) => a.seq - b.seq).map((cp) => ({
4529
+ ...cp
4530
+ }));
4531
+ this.lastCheckpointRowsRead = rows.length;
4532
+ return rows;
4533
+ }
4534
+ async getLatestCheckpointByName(runId, name) {
4535
+ let latest;
4536
+ for (const cp of this.checkpoints.values()) {
4537
+ if (cp.runId !== runId || cp.name !== name) continue;
4538
+ if (!latest || cp.seq > latest.seq) latest = cp;
4539
+ }
4540
+ this.lastCheckpointRowsRead = latest ? 1 : 0;
4541
+ return latest ? {
4542
+ ...latest
4543
+ } : void 0;
4544
+ }
4545
+ async listCheckpointsByNamePrefix(runId, prefixes) {
4546
+ const rows = [
4547
+ ...this.checkpoints.values()
4548
+ ].filter((cp) => cp.runId === runId && prefixes.some((p) => cp.name.startsWith(p))).sort((a, b) => a.seq - b.seq).map((cp) => ({
4549
+ ...cp
4550
+ }));
4551
+ this.lastCheckpointRowsRead = rows.length;
4552
+ return rows;
4553
+ }
4554
+ };
4555
+
4556
+ // src/testing/in-memory-transport.ts
4557
+ var InMemoryTransport = class {
4558
+ static {
4559
+ __name(this, "InMemoryTransport");
4560
+ }
4561
+ handlers = /* @__PURE__ */ new Map();
4562
+ resultHandler;
4563
+ heartbeatHandler;
4564
+ stepEventHandler;
4565
+ controlHandlers = /* @__PURE__ */ new Set();
4566
+ /** Register a fake worker handler for a step name. */
4567
+ handle(name, fn) {
4568
+ this.handlers.set(name, fn);
4569
+ }
4570
+ async dispatch(task) {
4571
+ if (!this.resultHandler) throw new Error("no result handler registered");
4572
+ const result = await runStepHandler(task, this.handlers.get(task.name));
4573
+ setImmediate(() => void this.resultHandler?.(result));
4574
+ }
4575
+ onResult(handler) {
4576
+ this.resultHandler = handler;
4577
+ }
4578
+ onHeartbeat(handler) {
4579
+ this.heartbeatHandler = handler;
4580
+ }
4581
+ /** Test hook: deliver a liveness heartbeat to the engine, as a real broker would on its channel. */
4582
+ async emitHeartbeat(beat) {
4583
+ await this.heartbeatHandler?.(beat);
4584
+ }
4585
+ /** Workflow step lifecycle: deliver to the engine's handler (async, mirroring a real broker). */
4586
+ async dispatchStepEvent(event) {
4587
+ await this.stepEventHandler?.(event);
4588
+ }
4589
+ onStepEvent(handler) {
4590
+ this.stepEventHandler = handler;
4591
+ }
4592
+ // Control plane: broadcast to every registered handler (including the publisher's own — the
4593
+ // engine dedupes by `from`), mirroring how a real broker echoes a publish to all subscribers.
4594
+ async publishControl(msg) {
4595
+ for (const handler of this.controlHandlers) handler(msg);
4596
+ }
4597
+ onControl(handler) {
4598
+ this.controlHandlers.add(handler);
4599
+ }
4600
+ };
4601
+ export {
4602
+ CodecStateStore,
4603
+ ContinueAsNew,
4604
+ DURABLE_OPTIONS,
4605
+ DURABLE_OPTIONS_CANONICAL,
4606
+ Entities,
4607
+ EventAccumulators,
4608
+ FatalError,
4609
+ GatherError,
4610
+ InMemoryAdmissionBackend,
4611
+ InMemoryStateStore,
4612
+ InMemoryTransport,
4613
+ NonDeterminismError,
4614
+ QueueController,
4615
+ RemoteStepError,
4616
+ RemoteStepTimeout,
4617
+ RemoteWorkflowExecutor,
4618
+ RemoteWorkflowTimeout,
4619
+ STATE_STORE,
4620
+ STATE_STORE_CANONICAL,
4621
+ SignalTimeoutError,
4622
+ SingletonQueueFullError,
4623
+ TERMINAL_RUN_STATUSES,
4624
+ TRANSPORT,
4625
+ TRANSPORT_CANONICAL,
4626
+ WORKFLOW_NAME_KEY,
4627
+ WorkflowEngine,
4628
+ WorkflowSuspended,
4629
+ applyAttributeQuery,
4630
+ attributeColumnFor,
4631
+ attributeOperand,
4632
+ breakpointToken,
4633
+ collectMetrics,
4634
+ createStepLogger,
4635
+ eventMatchOf,
4636
+ eventMatches,
4637
+ eventPrefix,
4638
+ eventToken,
4639
+ matchesAttributes,
4640
+ normalizeAttributeRows,
4641
+ parseDuration,
4642
+ prevCronFireMs,
4643
+ remoteStep,
4644
+ runSchedules,
4645
+ runStepHandler,
4646
+ scheduledRunId,
4647
+ sqlComparator,
4648
+ stepId,
4649
+ tenantGroup,
4650
+ workflowName
4651
+ };
4652
+ //# sourceMappingURL=index.js.map