@nagi-js/core 0.1.1-rc.18 → 0.1.1-rc.19

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.
@@ -0,0 +1,1833 @@
1
+ // src/state.ts
2
+ var PENDING = { tag: "pending" };
3
+ function stepStateOf(runState, stepId) {
4
+ return runState.steps[stepId] ?? PENDING;
5
+ }
6
+ function runStatusOf(state) {
7
+ return state.phase.tag;
8
+ }
9
+ function stepStatusOf(s) {
10
+ switch (s.tag) {
11
+ case "pending":
12
+ return "pending";
13
+ case "running":
14
+ case "awaitingSignal":
15
+ case "awaitingChild":
16
+ case "backoff":
17
+ case "aborting":
18
+ return "running";
19
+ case "completed":
20
+ return "completed";
21
+ case "failed":
22
+ return "failed";
23
+ case "skipped":
24
+ return "skipped";
25
+ case "canceled":
26
+ return "canceled";
27
+ }
28
+ }
29
+ function outputOf(s) {
30
+ return s.tag === "completed" ? s.output : null;
31
+ }
32
+ function errorOf(s) {
33
+ if (s.tag === "failed" || s.tag === "backoff") return s.error;
34
+ if (s.tag === "canceled" && s.cause.kind === "aborted") return s.cause.error;
35
+ return void 0;
36
+ }
37
+ function attemptOf(s) {
38
+ switch (s.tag) {
39
+ case "running":
40
+ case "awaitingSignal":
41
+ case "awaitingChild":
42
+ case "aborting":
43
+ case "completed":
44
+ case "failed":
45
+ return s.attempt;
46
+ case "backoff":
47
+ return s.failedAttempt;
48
+ case "pending":
49
+ case "skipped":
50
+ case "canceled":
51
+ return 0;
52
+ }
53
+ }
54
+ function resolvedOf(s) {
55
+ if (s.tag === "completed") return { tag: "value", value: s.output };
56
+ if (s.tag === "skipped") return { tag: "skipped" };
57
+ return { tag: "value", value: null };
58
+ }
59
+ function unwrap(r) {
60
+ if (r.tag === "skipped") {
61
+ throw new Error("nagi: upstream was skipped \u2014 its value is unavailable");
62
+ }
63
+ return r.value;
64
+ }
65
+ function isTerminalRun(state) {
66
+ return state.phase.tag !== "pending" && state.phase.tag !== "running";
67
+ }
68
+ function isAbortRequested(s, attempt) {
69
+ return s.tag === "aborting" && s.attempt === attempt;
70
+ }
71
+ function isStepTerminal(s) {
72
+ return s.tag === "completed" || s.tag === "failed" || s.tag === "skipped" || s.tag === "canceled";
73
+ }
74
+
75
+ // src/retry.ts
76
+ var DEFAULT_RETRY = {
77
+ maxAttempts: 3,
78
+ backoff: "exponential",
79
+ initialDelayMs: 1e3,
80
+ maxDelayMs: 6e4
81
+ };
82
+ function resolveRetry(handlerPolicy, runtimeDefault) {
83
+ return handlerPolicy ?? runtimeDefault ?? DEFAULT_RETRY;
84
+ }
85
+ function stepBackoff(policy) {
86
+ const initial = policy.initialDelayMs ?? DEFAULT_RETRY.initialDelayMs;
87
+ const max = policy.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs;
88
+ return (attempt) => {
89
+ switch (policy.backoff) {
90
+ case "exponential":
91
+ return Math.min(initial * 2 ** Math.max(0, attempt - 1), max);
92
+ case "linear":
93
+ return Math.min(initial * Math.max(1, attempt), max);
94
+ case "fixed":
95
+ return Math.min(initial, max);
96
+ }
97
+ };
98
+ }
99
+ var MAX_DEQUEUE_BACKOFF_MS = 3e4;
100
+ var MIN_DEQUEUE_BACKOFF_MS = 50;
101
+ function dequeueBackoff(pollIntervalMs) {
102
+ const base = Math.max(pollIntervalMs, MIN_DEQUEUE_BACKOFF_MS);
103
+ return (consecutiveFailures) => Math.min(base * 2 ** (consecutiveFailures - 1), MAX_DEQUEUE_BACKOFF_MS);
104
+ }
105
+ var SNAPSHOT_GONE_DELIVERY_BUDGET = 60;
106
+ var MAX_SNAPSHOT_GONE_BACKOFF_MS = 3e5;
107
+ var snapshotGoneBackoff = (readCount) => Math.min(readCount * readCount * 1e3, MAX_SNAPSHOT_GONE_BACKOFF_MS);
108
+ var defaultSnapshotGonePolicy = (readCount) => readCount > SNAPSHOT_GONE_DELIVERY_BUDGET ? { action: "fail" } : { action: "retry", delayMs: snapshotGoneBackoff(readCount) };
109
+ var reapBackoff = () => 0;
110
+
111
+ // src/internal.ts
112
+ function isOptional(ref) {
113
+ return "__optional" in ref;
114
+ }
115
+ function normalizeNeeds(needs) {
116
+ const out = {};
117
+ if (needs === void 0) return out;
118
+ for (const [key, ref] of Object.entries(needs)) {
119
+ out[key] = isOptional(ref) ? { step: ref.__optional, optional: true } : { step: ref, optional: false };
120
+ }
121
+ return out;
122
+ }
123
+ function makeEmit(onLog) {
124
+ if (!onLog) return () => {
125
+ };
126
+ return (entry) => {
127
+ try {
128
+ onLog(entry);
129
+ } catch {
130
+ }
131
+ };
132
+ }
133
+ function compact(obj) {
134
+ const out = {};
135
+ for (const [key, value] of Object.entries(obj)) {
136
+ if (value !== void 0) out[key] = value;
137
+ }
138
+ return out;
139
+ }
140
+ var DEF = /* @__PURE__ */ Symbol("nagi.def");
141
+ function attachDef(meta, def) {
142
+ return { kind: meta.kind, id: meta.id, [DEF]: def };
143
+ }
144
+ function setDef(step, def) {
145
+ step[DEF] = def;
146
+ }
147
+ function getDef(step) {
148
+ return step[DEF];
149
+ }
150
+ function peekDef(step) {
151
+ return step[DEF];
152
+ }
153
+ function handlerDef(def) {
154
+ return def.kind === "task" || def.kind === "activity" || def.kind === "streaming" ? def : void 0;
155
+ }
156
+ function needsStepIds(def) {
157
+ return Object.values(def.needs).map((ref) => ref.step.id);
158
+ }
159
+ function resolveNeeds(def, loadResolved) {
160
+ const result = {};
161
+ for (const [localKey, ref] of Object.entries(def.needs)) {
162
+ const resolved = loadResolved(ref.step.id);
163
+ result[localKey] = ref.optional ? resolved : unwrap(resolved);
164
+ }
165
+ return result;
166
+ }
167
+ function asStepMapWithDefs(steps) {
168
+ return steps;
169
+ }
170
+ function selectArm(def, args) {
171
+ for (const arm of def.arms) {
172
+ if (arm.guard.kind === "otherwise") return arm.id;
173
+ if (arm.guard.when(args)) return arm.id;
174
+ }
175
+ throw new Error(
176
+ `match: no arm matched and no { otherwise: true } fallback was provided`
177
+ );
178
+ }
179
+
180
+ // src/errors.ts
181
+ var NagiValidationError = class extends Error {
182
+ issues;
183
+ constructor(issues) {
184
+ super(issues.map((i) => i.message).join("; "));
185
+ this.name = "NagiValidationError";
186
+ this.issues = issues;
187
+ }
188
+ };
189
+ function validationError(message, path) {
190
+ return new NagiValidationError([{ message, path }]);
191
+ }
192
+ var NagiRuntimeError = class extends Error {
193
+ constructor(message) {
194
+ super(message);
195
+ this.name = "NagiRuntimeError";
196
+ }
197
+ };
198
+ var NagiNonRetryableError = class extends Error {
199
+ constructor(message, opts) {
200
+ super(message, opts);
201
+ this.name = "NagiNonRetryableError";
202
+ }
203
+ };
204
+ var NagiCanceledError = class extends Error {
205
+ runId;
206
+ canceledByRunId;
207
+ concurrencyKey;
208
+ constructor({
209
+ runId,
210
+ canceledByRunId,
211
+ concurrencyKey
212
+ }) {
213
+ super(
214
+ `Run ${runId} was canceled (superseded by run ${canceledByRunId} for concurrency key "${concurrencyKey}").`
215
+ );
216
+ this.name = "NagiCanceledError";
217
+ this.runId = runId;
218
+ this.canceledByRunId = canceledByRunId;
219
+ this.concurrencyKey = concurrencyKey;
220
+ this.cause = {
221
+ canceledByRunId,
222
+ concurrencyKey
223
+ };
224
+ }
225
+ };
226
+ var NagiSignalTimeoutError = class extends Error {
227
+ runId;
228
+ stepId;
229
+ fireAt;
230
+ constructor({
231
+ runId,
232
+ stepId,
233
+ fireAt
234
+ }) {
235
+ super(
236
+ `Signal step "${stepId}" (run ${runId}) timed out \u2014 no signal arrived before its deadline ${fireAt.toISOString()}.`
237
+ );
238
+ this.name = "NagiSignalTimeoutError";
239
+ this.runId = runId;
240
+ this.stepId = stepId;
241
+ this.fireAt = fireAt;
242
+ }
243
+ };
244
+ var NagiFlowSnapshotGoneError = class extends Error {
245
+ runId;
246
+ flowId;
247
+ pinnedHash;
248
+ currentHash;
249
+ constructor({
250
+ runId,
251
+ flowId,
252
+ pinnedHash,
253
+ currentHash
254
+ }) {
255
+ super(
256
+ currentHash === null ? `Run ${runId} is pinned to flow "${flowId}" hash ${pinnedHash.slice(0, 12)}\u2026, but flow "${flowId}" is not registered with the current nagi(). Pin a worker on the prior code version or migrate the run.` : `Run ${runId} is pinned to flow "${flowId}" hash ${pinnedHash.slice(0, 12)}\u2026, but the current registry has hash ${currentHash.slice(0, 12)}\u2026. Pin a worker on the prior code version or migrate the run.`
257
+ );
258
+ this.name = "NagiFlowSnapshotGoneError";
259
+ this.runId = runId;
260
+ this.flowId = flowId;
261
+ this.pinnedHash = pinnedHash;
262
+ this.currentHash = currentHash;
263
+ }
264
+ };
265
+ var NagiConcurrencyConflictError = class extends Error {
266
+ runId;
267
+ flowId;
268
+ concurrencyKey;
269
+ constructor({
270
+ runId,
271
+ flowId,
272
+ concurrencyKey
273
+ }) {
274
+ super(
275
+ `Run ${runId}: concurrent start lost the race on flow "${flowId}" concurrency key "${concurrencyKey}" \u2014 retry the caller transaction.`
276
+ );
277
+ this.name = "NagiConcurrencyConflictError";
278
+ this.runId = runId;
279
+ this.flowId = flowId;
280
+ this.concurrencyKey = concurrencyKey;
281
+ }
282
+ };
283
+ var NagiSnapshotDriftError = class extends Error {
284
+ runId;
285
+ expected;
286
+ actual;
287
+ constructor({
288
+ runId,
289
+ expected,
290
+ actual
291
+ }) {
292
+ super(
293
+ `Run ${runId} was pinned to flow hash ${expected.slice(0, 12)}\u2026 but the live flow's hash is ${actual.slice(0, 12)}\u2026. Pass replayOpts.allowDrift = true to replay against the live code anyway.`
294
+ );
295
+ this.name = "NagiSnapshotDriftError";
296
+ this.runId = runId;
297
+ this.expected = expected;
298
+ this.actual = actual;
299
+ }
300
+ };
301
+ function serializeError(err) {
302
+ if (err instanceof Error) {
303
+ return {
304
+ name: err.name,
305
+ message: err.message,
306
+ ...compact({ stack: err.stack })
307
+ };
308
+ }
309
+ return { name: "Error", message: String(err) };
310
+ }
311
+
312
+ // src/facts/flow.ts
313
+ var flowFacts = {
314
+ flowStarted(a) {
315
+ return {
316
+ kind: "flow.started",
317
+ runId: a.runId,
318
+ flowId: a.flowId,
319
+ input: a.input,
320
+ at: a.at,
321
+ ...compact({
322
+ codeVersion: a.codeVersion,
323
+ flowHash: a.flowHash,
324
+ parent: a.parent
325
+ })
326
+ };
327
+ },
328
+ flowCompleted(runId, output, at) {
329
+ return { kind: "flow.completed", runId, output, at };
330
+ },
331
+ flowFailed(runId, error, at) {
332
+ return { kind: "flow.failed", runId, error, at };
333
+ },
334
+ flowCanceled(runId, args, at) {
335
+ return { ...args, kind: "flow.canceled", runId, at };
336
+ },
337
+ flowCanceledByConcurrency(a) {
338
+ return {
339
+ kind: "flow.canceled",
340
+ cause: "concurrency",
341
+ runId: a.runId,
342
+ at: a.at,
343
+ canceledByRunId: a.canceledByRunId,
344
+ concurrencyKey: a.concurrencyKey
345
+ };
346
+ },
347
+ flowRefUpdated(a) {
348
+ return {
349
+ kind: "flow_ref.updated",
350
+ flowId: a.flowId,
351
+ from: a.from,
352
+ to: a.to,
353
+ at: a.at
354
+ };
355
+ }
356
+ };
357
+ function runCancelCause(fact) {
358
+ switch (fact.cause) {
359
+ case "concurrency":
360
+ return {
361
+ kind: "concurrency",
362
+ canceledByRunId: fact.canceledByRunId,
363
+ concurrencyKey: fact.concurrencyKey
364
+ };
365
+ case "explicit":
366
+ return {
367
+ kind: "explicit",
368
+ reason: fact.reason,
369
+ ...compact({ note: fact.note })
370
+ };
371
+ case "operator":
372
+ return {
373
+ kind: "operator",
374
+ actor: fact.actor,
375
+ reason: fact.reason,
376
+ ...compact({ note: fact.note })
377
+ };
378
+ }
379
+ }
380
+ var flowKinds = {
381
+ "flow.started": {
382
+ fold: (draft, fact) => {
383
+ draft.flowId = fact.flowId;
384
+ draft.input = fact.input;
385
+ draft.phase = { tag: "running" };
386
+ draft.parent = fact.parent;
387
+ draft.flowHash = fact.flowHash;
388
+ draft.codeVersion = fact.codeVersion;
389
+ },
390
+ rows: (fact) => ({
391
+ row: "run",
392
+ status: "running",
393
+ flowId: fact.flowId,
394
+ input: fact.input,
395
+ startedAt: fact.at,
396
+ flowHash: fact.flowHash ?? null,
397
+ codeVersion: fact.codeVersion ?? null,
398
+ parent: fact.parent ?? null
399
+ })
400
+ },
401
+ "flow.completed": {
402
+ fold: (draft, fact) => {
403
+ draft.phase = { tag: "completed", output: fact.output };
404
+ },
405
+ rows: (fact) => ({
406
+ row: "run",
407
+ status: "completed",
408
+ output: fact.output,
409
+ completedAt: fact.at
410
+ })
411
+ },
412
+ "flow.failed": {
413
+ fold: (draft, fact) => {
414
+ draft.phase = { tag: "failed", error: fact.error };
415
+ },
416
+ rows: (fact) => ({
417
+ row: "run",
418
+ status: "failed",
419
+ error: fact.error,
420
+ completedAt: fact.at
421
+ })
422
+ },
423
+ "flow.canceled": {
424
+ fold: (draft, fact) => {
425
+ draft.phase = { tag: "canceled", cause: runCancelCause(fact) };
426
+ },
427
+ rows: (fact) => ({
428
+ row: "run",
429
+ status: "canceled",
430
+ canceledByRunId: fact.cause === "concurrency" ? fact.canceledByRunId : null,
431
+ completedAt: fact.at
432
+ })
433
+ }
434
+ };
435
+
436
+ // src/facts/lease.ts
437
+ var leaseFacts = {
438
+ leaseReaped(a) {
439
+ return {
440
+ kind: "lease.reaped",
441
+ runId: a.runId,
442
+ stepId: a.stepId,
443
+ attempt: a.attempt,
444
+ at: a.at,
445
+ reapedAt: a.reapedAt,
446
+ reason: "expired"
447
+ };
448
+ }
449
+ };
450
+ var leaseKinds = {
451
+ // Audit-only: the reaper re-enqueues at attempt+1; the projection updates
452
+ // when the next attempt writes its step.started/step.failed.
453
+ "lease.reaped": { fold: () => {
454
+ }, rows: null }
455
+ };
456
+
457
+ // src/facts/signal.ts
458
+ var signalFacts = {
459
+ signalReceived(a) {
460
+ return {
461
+ kind: "signal.received",
462
+ runId: a.runId,
463
+ stepId: a.stepId,
464
+ payload: a.payload,
465
+ at: a.at,
466
+ ...compact({ signalName: a.signalName })
467
+ };
468
+ },
469
+ signalBuffered(a) {
470
+ return {
471
+ kind: "signal.buffered",
472
+ runId: a.runId,
473
+ stepId: a.stepId,
474
+ payload: a.payload,
475
+ at: a.at,
476
+ ...compact({ signalName: a.signalName })
477
+ };
478
+ }
479
+ };
480
+ var signalKinds = {
481
+ "signal.received": {
482
+ // Delivery settles the step through its own step.completed; here the
483
+ // buffer is spent. Leaving it would make the next incoming signal a silent
484
+ // no-op and a later reset auto-complete.
485
+ fold: (draft, fact) => {
486
+ delete draft.bufferedSignals[fact.stepId];
487
+ },
488
+ rows: null
489
+ },
490
+ "signal.buffered": {
491
+ // First buffered signal per step wins, mirroring the happy path where the
492
+ // first delivered signal completes the step and later ones no-op.
493
+ fold: (draft, fact) => {
494
+ if (!(fact.stepId in draft.bufferedSignals)) {
495
+ draft.bufferedSignals[fact.stepId] = {
496
+ payload: fact.payload,
497
+ ...compact({ signalName: fact.signalName })
498
+ };
499
+ }
500
+ },
501
+ rows: null
502
+ }
503
+ };
504
+
505
+ // src/facts/base.ts
506
+ function foldStep(draft, stepId, next) {
507
+ draft.steps[stepId] = next(draft.steps[stepId] ?? PENDING);
508
+ }
509
+
510
+ // src/facts/step.ts
511
+ var stepFacts = {
512
+ stepStarted(runId, stepId, attempt, stepKind, at) {
513
+ return { kind: "step.started", runId, stepId, attempt, stepKind, at };
514
+ },
515
+ stepCompleted(runId, stepId, attempt, output, at) {
516
+ return { kind: "step.completed", runId, stepId, attempt, output, at };
517
+ },
518
+ stepFailed(runId, stepId, attempt, error, at) {
519
+ return { kind: "step.failed", runId, stepId, attempt, error, at };
520
+ },
521
+ stepCanceled(runId, stepId, attempt, at, error) {
522
+ return {
523
+ kind: "step.canceled",
524
+ runId,
525
+ stepId,
526
+ attempt,
527
+ at,
528
+ ...compact({ error })
529
+ };
530
+ },
531
+ stepRetried(runId, stepId, attempt, nextAttemptAt, error, at) {
532
+ return {
533
+ kind: "step.retried",
534
+ runId,
535
+ stepId,
536
+ attempt,
537
+ nextAttemptAt,
538
+ error,
539
+ at
540
+ };
541
+ },
542
+ stepSkipped(a) {
543
+ return {
544
+ kind: "step.skipped",
545
+ runId: a.runId,
546
+ stepId: a.stepId,
547
+ reason: a.reason,
548
+ at: a.at,
549
+ ...compact({ actor: a.actor, note: a.note })
550
+ };
551
+ },
552
+ stepReset(a) {
553
+ return {
554
+ kind: "step.reset",
555
+ runId: a.runId,
556
+ stepId: a.stepId,
557
+ at: a.at,
558
+ ...compact({
559
+ cascadedFrom: a.cascadedFrom,
560
+ actor: a.actor,
561
+ note: a.note
562
+ })
563
+ };
564
+ },
565
+ stepAbortRequested(a) {
566
+ return {
567
+ kind: "step.abort-requested",
568
+ runId: a.runId,
569
+ stepId: a.stepId,
570
+ attempt: a.attempt,
571
+ actor: a.actor,
572
+ at: a.at,
573
+ ...compact({ note: a.note })
574
+ };
575
+ },
576
+ matchArmSelected(runId, stepId, arm, at) {
577
+ return { kind: "match.arm-selected", runId, stepId, arm, at };
578
+ }
579
+ };
580
+ function startTarget(stepKind, attempt) {
581
+ switch (stepKind) {
582
+ case "signal":
583
+ return { tag: "awaitingSignal", attempt };
584
+ case "subflow":
585
+ return { tag: "awaitingChild", attempt };
586
+ case "task":
587
+ case "activity":
588
+ case "streaming":
589
+ case "match":
590
+ return { tag: "running", attempt };
591
+ }
592
+ }
593
+ var stepKinds = {
594
+ "step.started": {
595
+ fold: (draft, fact) => foldStep(
596
+ draft,
597
+ fact.stepId,
598
+ (prev) => prev.tag === "pending" || prev.tag === "backoff" ? startTarget(fact.stepKind, fact.attempt) : prev
599
+ ),
600
+ rows: (fact) => ({
601
+ row: "step",
602
+ status: "running",
603
+ stepId: fact.stepId,
604
+ attempt: fact.attempt,
605
+ startedAt: fact.at
606
+ })
607
+ },
608
+ "step.completed": {
609
+ fold: (draft, fact) => foldStep(
610
+ draft,
611
+ fact.stepId,
612
+ (prev) => isStepTerminal(prev) ? prev : { tag: "completed", attempt: fact.attempt, output: fact.output }
613
+ ),
614
+ rows: (fact) => ({
615
+ row: "step",
616
+ status: "completed",
617
+ stepId: fact.stepId,
618
+ attempt: fact.attempt,
619
+ output: fact.output
620
+ })
621
+ },
622
+ "step.failed": {
623
+ fold: (draft, fact) => foldStep(
624
+ draft,
625
+ fact.stepId,
626
+ (prev) => isStepTerminal(prev) ? prev : { tag: "failed", attempt: fact.attempt, error: fact.error }
627
+ ),
628
+ rows: (fact) => ({
629
+ row: "step",
630
+ status: "failed",
631
+ stepId: fact.stepId,
632
+ attempt: fact.attempt,
633
+ error: fact.error
634
+ })
635
+ },
636
+ "step.canceled": {
637
+ fold: (draft, fact) => foldStep(draft, fact.stepId, (prev) => {
638
+ if (isStepTerminal(prev)) return prev;
639
+ const cause = prev.tag === "aborting" ? { kind: "aborted", ...compact({ error: fact.error }) } : { kind: "run-canceled" };
640
+ return { tag: "canceled", cause };
641
+ }),
642
+ rows: (fact) => ({
643
+ row: "step",
644
+ status: "canceled",
645
+ stepId: fact.stepId,
646
+ attempt: fact.attempt,
647
+ error: fact.error ?? null
648
+ })
649
+ },
650
+ "step.retried": {
651
+ fold: (draft, fact) => foldStep(
652
+ draft,
653
+ fact.stepId,
654
+ (prev) => prev.tag === "running" ? {
655
+ tag: "backoff",
656
+ failedAttempt: fact.attempt,
657
+ retryAt: fact.nextAttemptAt,
658
+ error: fact.error
659
+ } : prev
660
+ ),
661
+ rows: null
662
+ },
663
+ "step.skipped": {
664
+ // An operator may skip an in-flight step, not just a pending one.
665
+ fold: (draft, fact) => foldStep(
666
+ draft,
667
+ fact.stepId,
668
+ (prev) => isStepTerminal(prev) ? prev : { tag: "skipped", reason: fact.reason }
669
+ ),
670
+ rows: (fact) => ({ row: "step", status: "skipped", stepId: fact.stepId })
671
+ },
672
+ "step.reset": {
673
+ fold: (draft, fact) => {
674
+ draft.steps[fact.stepId] = PENDING;
675
+ delete draft.selectedArms[fact.stepId];
676
+ delete draft.bufferedSignals[fact.stepId];
677
+ if (draft.phase.tag === "completed" || draft.phase.tag === "failed") {
678
+ draft.phase = { tag: "running" };
679
+ }
680
+ },
681
+ rows: (fact) => ({ row: "step", status: "reset", stepId: fact.stepId })
682
+ },
683
+ "step.abort-requested": {
684
+ fold: (draft, fact) => foldStep(
685
+ draft,
686
+ fact.stepId,
687
+ (prev) => prev.tag === "running" || prev.tag === "awaitingSignal" || prev.tag === "awaitingChild" ? { tag: "aborting", attempt: fact.attempt } : prev
688
+ ),
689
+ rows: null
690
+ },
691
+ "match.arm-selected": {
692
+ fold: (draft, fact) => {
693
+ draft.selectedArms[fact.stepId] = fact.arm;
694
+ },
695
+ rows: null
696
+ },
697
+ "once.recorded": {
698
+ fold: () => {
699
+ },
700
+ rows: (fact) => ({
701
+ row: "once",
702
+ stepId: fact.stepId,
703
+ scope: fact.scope,
704
+ value: fact.value
705
+ })
706
+ }
707
+ };
708
+
709
+ // src/facts/index.ts
710
+ var Facts = {
711
+ ...flowFacts,
712
+ ...stepFacts,
713
+ ...signalFacts,
714
+ ...leaseFacts
715
+ };
716
+ var KINDS = {
717
+ ...flowKinds,
718
+ ...stepKinds,
719
+ ...signalKinds,
720
+ ...leaseKinds
721
+ };
722
+ function armOf(kind) {
723
+ return KINDS[kind];
724
+ }
725
+ function foldRun(runId, facts) {
726
+ const draft = {
727
+ flowId: "",
728
+ input: null,
729
+ phase: { tag: "pending" },
730
+ parent: void 0,
731
+ flowHash: void 0,
732
+ codeVersion: void 0,
733
+ steps: {},
734
+ selectedArms: {},
735
+ bufferedSignals: {}
736
+ };
737
+ for (const fact of facts) armOf(fact.kind)?.fold(draft, fact);
738
+ const { parent, flowHash, codeVersion, ...projected } = draft;
739
+ return {
740
+ runId,
741
+ ...projected,
742
+ facts,
743
+ ...compact({ parent, flowHash, codeVersion })
744
+ };
745
+ }
746
+ function rowDeltaOf(fact) {
747
+ return armOf(fact.kind)?.rows?.(fact) ?? null;
748
+ }
749
+
750
+ // src/lease-reaper.ts
751
+ function decideExpiredLeaseAction(args) {
752
+ const { lease, stepStatus, childActive, now } = args;
753
+ if (stepStatus === "completed" || stepStatus === "failed" || stepStatus === "canceled" || stepStatus === "skipped") {
754
+ return { tag: "skip", reason: "terminal" };
755
+ }
756
+ if (childActive) {
757
+ return { tag: "skip", reason: "child-active" };
758
+ }
759
+ if (lease.expiresAt > now) {
760
+ return { tag: "skip", reason: "still-live" };
761
+ }
762
+ const nextAttempt = lease.attempt + 1;
763
+ return { tag: "reap", nextAttempt, backoffMs: reapBackoff() };
764
+ }
765
+ var DEFAULT_REAPER_INTERVAL_MS = 3e4;
766
+
767
+ // src/validate.ts
768
+ async function validate(schema, value) {
769
+ const result = await schema["~standard"].validate(value);
770
+ if ("issues" in result && result.issues !== void 0) {
771
+ throw new NagiValidationError(result.issues);
772
+ }
773
+ return result.value;
774
+ }
775
+
776
+ // src/signals.ts
777
+ var NOOP = { kind: "noop", result: { tag: "noop" } };
778
+ function decideSignal(args) {
779
+ const { runState, stepId, at, incoming } = args;
780
+ const { runId } = runState;
781
+ const step = stepStateOf(runState, stepId);
782
+ if (isStepTerminal(step)) return NOOP;
783
+ if (step.tag === "awaitingSignal") {
784
+ const source = incoming ?? runState.bufferedSignals[stepId];
785
+ if (source === void 0) return NOOP;
786
+ const { attempt } = step;
787
+ return {
788
+ kind: "deliver",
789
+ attempt,
790
+ received: Facts.signalReceived({
791
+ runId,
792
+ stepId,
793
+ payload: source.payload,
794
+ at,
795
+ ...compact({ signalName: source.signalName })
796
+ }),
797
+ completed: Facts.stepCompleted(
798
+ runId,
799
+ stepId,
800
+ attempt,
801
+ source.payload,
802
+ at
803
+ ),
804
+ result: {
805
+ tag: "delivered",
806
+ attempt,
807
+ payload: source.payload,
808
+ ...compact({ signalName: source.signalName })
809
+ }
810
+ };
811
+ }
812
+ if (incoming === void 0) return NOOP;
813
+ if (runState.bufferedSignals[stepId] !== void 0) {
814
+ return { kind: "buffer", fact: null, result: { tag: "buffered" } };
815
+ }
816
+ return {
817
+ kind: "buffer",
818
+ fact: Facts.signalBuffered({
819
+ runId,
820
+ stepId,
821
+ payload: incoming.payload,
822
+ at,
823
+ ...compact({ signalName: incoming.signalName })
824
+ }),
825
+ result: { tag: "buffered" }
826
+ };
827
+ }
828
+ function decideTimeout(args) {
829
+ const { runState, stepId, fireAt, at } = args;
830
+ const step = stepStateOf(runState, stepId);
831
+ if (step.tag !== "awaitingSignal") return { kind: "noop" };
832
+ const error = serializeError(
833
+ new NagiSignalTimeoutError({ runId: runState.runId, stepId, fireAt })
834
+ );
835
+ return {
836
+ kind: "fail",
837
+ attempt: step.attempt,
838
+ fact: Facts.stepFailed(runState.runId, stepId, step.attempt, error, at)
839
+ };
840
+ }
841
+ function makeSignals(deps) {
842
+ const { dispatcher, store, clock, registry, hooks, flowHooks, emitLog } = deps;
843
+ async function signal(runId, signalName, payload) {
844
+ const runState = await store.loadRunState(runId);
845
+ const flow = registry.require(runState.flowId);
846
+ const resolved = resolveSignalStep(flow, signalName);
847
+ if (resolved === null) {
848
+ throw new NagiRuntimeError(
849
+ `Flow "${flow.id}" has no signal step accepting "${signalName}".`
850
+ );
851
+ }
852
+ const { stepId, def } = resolved;
853
+ const validated = await validate(def.schema, payload);
854
+ const carriesAlias = signalName !== stepId;
855
+ const result = await store.settleSignal({
856
+ runId,
857
+ stepId,
858
+ at: clock.now(),
859
+ incoming: {
860
+ payload: validated,
861
+ ...carriesAlias ? { signalName } : {}
862
+ }
863
+ });
864
+ switch (result.tag) {
865
+ case "delivered":
866
+ await hooks.fireHook(
867
+ flowHooks?.onSignalReceived,
868
+ {
869
+ runId,
870
+ flowId: flow.id,
871
+ stepId,
872
+ attempt: result.attempt,
873
+ kind: "signal",
874
+ payload: validated,
875
+ at: clock.now()
876
+ },
877
+ "onSignalReceived"
878
+ );
879
+ await dispatcher.advance(runId);
880
+ return;
881
+ case "buffered":
882
+ emitLog({
883
+ level: "info",
884
+ msg: "nagi: signal buffered before step ready; will apply on dispatch",
885
+ attrs: { runId, stepId, signalName }
886
+ });
887
+ return;
888
+ case "noop":
889
+ emitLog({
890
+ level: "info",
891
+ msg: "nagi: signal arrived after step resolved",
892
+ attrs: { runId, stepId, signalName }
893
+ });
894
+ return;
895
+ }
896
+ }
897
+ return { signal };
898
+ }
899
+ function resolveSignalStep(flow, signalName) {
900
+ const steps = asStepMapWithDefs(flow.steps);
901
+ const direct = steps[signalName];
902
+ if (direct !== void 0) {
903
+ const d = getDef(direct);
904
+ if (d.kind === "signal" && d.names === void 0) {
905
+ return { stepId: signalName, def: d };
906
+ }
907
+ }
908
+ for (const [id, s] of Object.entries(steps)) {
909
+ const d = getDef(s);
910
+ if (d.kind === "signal" && d.names?.includes(signalName)) {
911
+ return { stepId: id, def: d };
912
+ }
913
+ }
914
+ return null;
915
+ }
916
+
917
+ // src/store-policy.ts
918
+ var QUERY_RUNS_DEFAULT_LIMIT = 50;
919
+ var QUERY_RUNS_MAX_LIMIT = 500;
920
+ function clampQueryLimit(limit) {
921
+ if (limit === void 0) return QUERY_RUNS_DEFAULT_LIMIT;
922
+ if (!Number.isInteger(limit) || limit < 1) return QUERY_RUNS_DEFAULT_LIMIT;
923
+ return Math.min(limit, QUERY_RUNS_MAX_LIMIT);
924
+ }
925
+ function compareRunOrder(a, b) {
926
+ const t = b.startedAt.getTime() - a.startedAt.getTime();
927
+ if (t !== 0) return t;
928
+ return a.runId < b.runId ? 1 : a.runId > b.runId ? -1 : 0;
929
+ }
930
+ function isPastCursor(row, cursor) {
931
+ return compareRunOrder(row, cursor) > 0;
932
+ }
933
+ function encodeRunCursor(c) {
934
+ const bytes = new TextEncoder().encode(
935
+ JSON.stringify({ t: c.startedAt.getTime(), r: c.runId })
936
+ );
937
+ let binary = "";
938
+ for (const b of bytes) binary += String.fromCharCode(b);
939
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
940
+ }
941
+ function decodeRunCursor(s) {
942
+ try {
943
+ const binary = atob(s.replace(/-/g, "+").replace(/_/g, "/"));
944
+ const bytes = Uint8Array.from(binary, (ch) => ch.charCodeAt(0));
945
+ const parsed = JSON.parse(new TextDecoder().decode(bytes));
946
+ if (typeof parsed === "object" && parsed !== null && typeof parsed.t === "number" && typeof parsed.r === "string") {
947
+ const { t, r } = parsed;
948
+ return { startedAt: new Date(t), runId: r };
949
+ }
950
+ throw new Error("malformed cursor body");
951
+ } catch (err) {
952
+ throw new Error(
953
+ `queryRuns: invalid cursor \u2014 ${err instanceof Error ? err.message : String(err)}`
954
+ );
955
+ }
956
+ }
957
+ function jsonContains(haystack, needle) {
958
+ if (Array.isArray(needle)) {
959
+ if (!Array.isArray(haystack)) return false;
960
+ return needle.every((n) => haystack.some((h) => jsonContains(h, n)));
961
+ }
962
+ if (needle !== null && typeof needle === "object") {
963
+ if (haystack === null || Array.isArray(haystack) || typeof haystack !== "object")
964
+ return false;
965
+ return Object.entries(needle).every(
966
+ ([k, v]) => k in haystack && jsonContains(haystack[k], v)
967
+ );
968
+ }
969
+ return haystack === needle;
970
+ }
971
+ var DEFAULT_SWEEP_LIMIT = 100;
972
+ function selectExpired(items, args) {
973
+ const nowMs = args.now.getTime();
974
+ const out = [];
975
+ for (const item of items) {
976
+ if (out.length >= args.limit) break;
977
+ if (args.deadline(item).getTime() < nowMs) out.push(item);
978
+ }
979
+ return out;
980
+ }
981
+ function selectPruneBatch(candidates, opts) {
982
+ const cutoff = opts.olderThan.getTime();
983
+ const wanted = new Set(opts.statuses);
984
+ const eligible = [];
985
+ for (const item of candidates) {
986
+ if (item.completedAt === null || !wanted.has(item.status)) continue;
987
+ const at = item.completedAt.getTime();
988
+ if (at < cutoff) eligible.push({ item, at });
989
+ }
990
+ eligible.sort(
991
+ (a, b) => a.at - b.at || (a.item.runId < b.item.runId ? -1 : a.item.runId > b.item.runId ? 1 : 0)
992
+ );
993
+ return eligible.slice(0, opts.batchSize).map((e) => e.item);
994
+ }
995
+ var NONE = { tag: "none" };
996
+ var RELEASE_RUN = { tag: "release-run" };
997
+ function factEffects(fact) {
998
+ switch (fact.kind) {
999
+ case "step.completed":
1000
+ case "step.reset":
1001
+ return { tag: "release-step", stepId: fact.stepId, timer: true };
1002
+ case "step.failed":
1003
+ case "step.canceled":
1004
+ return { tag: "release-step", stepId: fact.stepId, timer: false };
1005
+ case "flow.completed":
1006
+ case "flow.failed":
1007
+ case "flow.canceled":
1008
+ return RELEASE_RUN;
1009
+ case "flow.started":
1010
+ case "step.started":
1011
+ case "step.retried":
1012
+ case "step.skipped":
1013
+ case "step.abort-requested":
1014
+ case "signal.received":
1015
+ case "signal.buffered":
1016
+ case "once.recorded":
1017
+ case "match.arm-selected":
1018
+ case "lease.reaped":
1019
+ return NONE;
1020
+ }
1021
+ }
1022
+
1023
+ // src/stream-hub.ts
1024
+ var STREAM_SUBSCRIBER_BUFFER_CAP = 256;
1025
+ var STREAM_REPLAY_BUFFER_CAP = 256;
1026
+ function makeWake() {
1027
+ let resolve;
1028
+ const promise = new Promise((r) => {
1029
+ resolve = r;
1030
+ });
1031
+ return { promise, resolve };
1032
+ }
1033
+ var Subscriber = class {
1034
+ buffer = [];
1035
+ pendingDropped = 0;
1036
+ closed = false;
1037
+ wake = null;
1038
+ push(event) {
1039
+ if (this.closed) return;
1040
+ if (this.buffer.length >= STREAM_SUBSCRIBER_BUFFER_CAP) {
1041
+ const idx = this.buffer.findIndex((e) => e.kind === "chunk");
1042
+ if (idx === -1) {
1043
+ if (event.kind === "chunk") {
1044
+ this.pendingDropped += 1;
1045
+ this.signal();
1046
+ return;
1047
+ }
1048
+ } else {
1049
+ this.buffer.splice(idx, 1);
1050
+ this.pendingDropped += 1;
1051
+ }
1052
+ }
1053
+ this.buffer.push(event);
1054
+ this.signal();
1055
+ }
1056
+ close() {
1057
+ if (this.closed) return;
1058
+ this.closed = true;
1059
+ this.signal();
1060
+ }
1061
+ signal() {
1062
+ if (this.wake !== null) {
1063
+ const w = this.wake;
1064
+ this.wake = null;
1065
+ w.resolve();
1066
+ }
1067
+ }
1068
+ async next() {
1069
+ for (; ; ) {
1070
+ if (this.pendingDropped > 0) {
1071
+ const count = this.pendingDropped;
1072
+ this.pendingDropped = 0;
1073
+ return { kind: "dropped", count };
1074
+ }
1075
+ const head = this.buffer.shift();
1076
+ if (head !== void 0) return head;
1077
+ if (this.closed) return null;
1078
+ const w = makeWake();
1079
+ this.wake = w;
1080
+ await w.promise;
1081
+ }
1082
+ }
1083
+ };
1084
+ var InMemoryStreamHub = class _InMemoryStreamHub {
1085
+ channels = /* @__PURE__ */ new Map();
1086
+ static key(runId, stepId) {
1087
+ return `${runId}::${stepId}`;
1088
+ }
1089
+ getOrCreate(runId, stepId) {
1090
+ const key = _InMemoryStreamHub.key(runId, stepId);
1091
+ let channel = this.channels.get(key);
1092
+ if (channel === void 0) {
1093
+ channel = { subscribers: /* @__PURE__ */ new Set(), replay: [], closed: false };
1094
+ this.channels.set(key, channel);
1095
+ }
1096
+ return channel;
1097
+ }
1098
+ publishChunk(runId, stepId, chunk) {
1099
+ const channel = this.getOrCreate(runId, stepId);
1100
+ if (channel.closed) return;
1101
+ const event = { kind: "chunk", chunk };
1102
+ channel.replay.push(event);
1103
+ if (channel.replay.length > STREAM_REPLAY_BUFFER_CAP)
1104
+ channel.replay.shift();
1105
+ for (const sub of channel.subscribers) sub.push(event);
1106
+ }
1107
+ signalRetry(runId, stepId, attempt) {
1108
+ const channel = this.getOrCreate(runId, stepId);
1109
+ if (channel.closed) return;
1110
+ channel.replay.length = 0;
1111
+ const event = { kind: "retry", attempt };
1112
+ for (const sub of channel.subscribers) sub.push(event);
1113
+ }
1114
+ // NB: no-op when no channel exists. InMemoryStore.appendFact fires this for
1115
+ // EVERY step.completed — including non-streaming steps that never published —
1116
+ // so creating a channel here would leak one per such step. Closed-ness is
1117
+ // authoritative in the durable facts, not the hub.
1118
+ closeOk(runId, stepId) {
1119
+ const channel = this.channels.get(_InMemoryStreamHub.key(runId, stepId));
1120
+ if (channel === void 0 || channel.closed) return;
1121
+ channel.closed = true;
1122
+ channel.replay.length = 0;
1123
+ for (const sub of channel.subscribers) sub.close();
1124
+ channel.subscribers.clear();
1125
+ }
1126
+ closeError(runId, stepId, error) {
1127
+ const channel = this.channels.get(_InMemoryStreamHub.key(runId, stepId));
1128
+ if (channel === void 0 || channel.closed) return;
1129
+ channel.closed = true;
1130
+ channel.replay.length = 0;
1131
+ const event = { kind: "error", error };
1132
+ for (const sub of channel.subscribers) {
1133
+ sub.push(event);
1134
+ sub.close();
1135
+ }
1136
+ channel.subscribers.clear();
1137
+ }
1138
+ closeRun(runId) {
1139
+ const prefix = `${runId}::`;
1140
+ for (const [key, channel] of this.channels) {
1141
+ if (!key.startsWith(prefix) || channel.closed) continue;
1142
+ channel.closed = true;
1143
+ channel.replay.length = 0;
1144
+ for (const sub of channel.subscribers) sub.close();
1145
+ channel.subscribers.clear();
1146
+ }
1147
+ }
1148
+ subscribeStream(runId, stepId, opts) {
1149
+ const channel = this.getOrCreate(runId, stepId);
1150
+ if (channel.closed) {
1151
+ return {
1152
+ [Symbol.asyncIterator]() {
1153
+ return {
1154
+ next: async () => ({ value: void 0, done: true })
1155
+ };
1156
+ }
1157
+ };
1158
+ }
1159
+ const sub = new Subscriber();
1160
+ if (opts?.replayBuffered === true) {
1161
+ for (const event of channel.replay) sub.push(event);
1162
+ }
1163
+ channel.subscribers.add(sub);
1164
+ const remove = () => {
1165
+ channel.subscribers.delete(sub);
1166
+ };
1167
+ return {
1168
+ [Symbol.asyncIterator]() {
1169
+ return {
1170
+ next: async () => {
1171
+ const event = await sub.next();
1172
+ if (event === null) {
1173
+ remove();
1174
+ return { value: void 0, done: true };
1175
+ }
1176
+ return { value: event, done: false };
1177
+ },
1178
+ return: async () => {
1179
+ sub.close();
1180
+ remove();
1181
+ return { value: void 0, done: true };
1182
+ }
1183
+ };
1184
+ }
1185
+ };
1186
+ }
1187
+ };
1188
+
1189
+ // src/memory.ts
1190
+ function leaseKey(runId, stepId, attempt) {
1191
+ return `${runId}::${stepId}::${attempt}`;
1192
+ }
1193
+ function timerKey(runId, stepId) {
1194
+ return `${runId}::${stepId}`;
1195
+ }
1196
+ var DEFAULT_STORE_LEASE_MS = 6e4;
1197
+ var InMemoryStore = class {
1198
+ facts = /* @__PURE__ */ new Map();
1199
+ onces = /* @__PURE__ */ new Map();
1200
+ leases = /* @__PURE__ */ new Map();
1201
+ snapshots = /* @__PURE__ */ new Map();
1202
+ refs = /* @__PURE__ */ new Map();
1203
+ globalFacts = [];
1204
+ activeByKey = /* @__PURE__ */ new Map();
1205
+ keyByActiveRun = /* @__PURE__ */ new Map();
1206
+ // Kept past terminal facts so a reopened run can re-take its slot.
1207
+ slotByRun = /* @__PURE__ */ new Map();
1208
+ childrenByParent = /* @__PURE__ */ new Map();
1209
+ summaries = /* @__PURE__ */ new Map();
1210
+ streamHub = new InMemoryStreamHub();
1211
+ // Durable signal-timeout deadlines (the Postgres `timer` table), distinct
1212
+ // from InMemoryClock's setTimeout-based scheduler.
1213
+ signalTimers = /* @__PURE__ */ new Map();
1214
+ leaseMs;
1215
+ constructor(opts = {}) {
1216
+ this.leaseMs = opts.leaseMs ?? DEFAULT_STORE_LEASE_MS;
1217
+ }
1218
+ async appendFact(runId, fact) {
1219
+ const list = this.facts.get(runId) ?? [];
1220
+ if (fact.kind === "step.reset") {
1221
+ const prior = foldRun(runId, list);
1222
+ if (prior.phase.tag === "completed" || prior.phase.tag === "failed") {
1223
+ const slot = this.slotByRun.get(runId);
1224
+ if (slot !== void 0) {
1225
+ const holder = this.activeByKey.get(slot);
1226
+ if (holder !== void 0 && holder !== runId) {
1227
+ throw new NagiConcurrencyConflictError({
1228
+ runId,
1229
+ flowId: prior.flowId,
1230
+ concurrencyKey: slot.slice(slot.indexOf("::") + 2)
1231
+ });
1232
+ }
1233
+ this.activeByKey.set(slot, runId);
1234
+ this.keyByActiveRun.set(runId, slot);
1235
+ }
1236
+ }
1237
+ }
1238
+ list.push(fact);
1239
+ this.facts.set(runId, list);
1240
+ switch (fact.kind) {
1241
+ case "step.completed":
1242
+ this.streamHub.closeOk(runId, fact.stepId);
1243
+ break;
1244
+ case "step.failed":
1245
+ this.streamHub.closeError(runId, fact.stepId, fact.error);
1246
+ break;
1247
+ case "step.retried":
1248
+ this.streamHub.signalRetry(
1249
+ runId,
1250
+ fact.stepId,
1251
+ fact.attempt + 1
1252
+ );
1253
+ break;
1254
+ case "flow.completed":
1255
+ case "flow.failed":
1256
+ case "flow.canceled":
1257
+ this.streamHub.closeRun(runId);
1258
+ break;
1259
+ }
1260
+ const effects = factEffects(fact);
1261
+ switch (effects.tag) {
1262
+ case "none":
1263
+ return;
1264
+ case "release-step":
1265
+ this.releaseLeases(runId, effects.stepId);
1266
+ if (effects.timer) {
1267
+ this.signalTimers.delete(timerKey(runId, effects.stepId));
1268
+ }
1269
+ return;
1270
+ case "release-run": {
1271
+ const slot = this.keyByActiveRun.get(runId);
1272
+ if (slot === void 0) return;
1273
+ this.keyByActiveRun.delete(runId);
1274
+ if (this.activeByKey.get(slot) === runId) {
1275
+ this.activeByKey.delete(slot);
1276
+ }
1277
+ return;
1278
+ }
1279
+ }
1280
+ }
1281
+ releaseLeases(runId, stepId) {
1282
+ for (const [key, lease] of this.leases) {
1283
+ if (lease.runId === runId && lease.stepId === stepId) {
1284
+ this.leases.delete(key);
1285
+ }
1286
+ }
1287
+ }
1288
+ async tryStartRun(runId, fact, concurrency) {
1289
+ if (this.facts.has(runId) || this.summaries.has(runId)) {
1290
+ return { started: false, canceled: [] };
1291
+ }
1292
+ const canceled = [];
1293
+ if (concurrency !== void 0) {
1294
+ const slot = `${fact.flowId}::${concurrency.key}`;
1295
+ const priorRunId = this.activeByKey.get(slot);
1296
+ if (priorRunId !== void 0) {
1297
+ const cancelFact = Facts.flowCanceledByConcurrency({
1298
+ runId: priorRunId,
1299
+ at: fact.at,
1300
+ canceledByRunId: runId,
1301
+ concurrencyKey: concurrency.key
1302
+ });
1303
+ await this.appendFact(priorRunId, cancelFact);
1304
+ canceled.push({ runId: priorRunId, fact: cancelFact });
1305
+ }
1306
+ this.activeByKey.set(slot, runId);
1307
+ this.keyByActiveRun.set(runId, slot);
1308
+ this.slotByRun.set(runId, slot);
1309
+ }
1310
+ this.facts.set(runId, [fact]);
1311
+ const parentRunId = fact.parent?.runId;
1312
+ if (parentRunId !== void 0) {
1313
+ const set = this.childrenByParent.get(parentRunId) ?? /* @__PURE__ */ new Set();
1314
+ set.add(runId);
1315
+ this.childrenByParent.set(parentRunId, set);
1316
+ }
1317
+ return { started: true, canceled };
1318
+ }
1319
+ // In-memory has no real tx; we share the underlying maps with tryStartRun,
1320
+ // so the implementation is intentionally a straight delegate. The `tx`
1321
+ // parameter is accepted for shape-compat with the Store contract.
1322
+ async tryStartRunOnTx(_tx, runId, fact, concurrency) {
1323
+ return this.tryStartRun(runId, fact, concurrency);
1324
+ }
1325
+ async listChildren(parentRunId) {
1326
+ const set = this.childrenByParent.get(parentRunId);
1327
+ if (set === void 0) return [];
1328
+ return Array.from(set);
1329
+ }
1330
+ // Does a non-terminal child exist for this (parentRunId, stepId)? Used by the
1331
+ // reaper to leave a subflow step parked while its child still runs (instead
1332
+ // of re-dispatching it at attempt+1). childrenByParent is keyed by parent run
1333
+ // only, so filter on the child's parent.stepId.
1334
+ hasActiveChild(parentRunId, parentStepId) {
1335
+ const childIds = this.childrenByParent.get(parentRunId);
1336
+ if (childIds === void 0) return false;
1337
+ for (const childId of childIds) {
1338
+ const factList = this.facts.get(childId);
1339
+ if (factList === void 0) continue;
1340
+ const child = foldRun(childId, factList);
1341
+ if (child.parent?.stepId === parentStepId && !isTerminalRun(child)) {
1342
+ return true;
1343
+ }
1344
+ }
1345
+ return false;
1346
+ }
1347
+ async loadRunState(runId) {
1348
+ return foldRun(runId, this.facts.get(runId) ?? []);
1349
+ }
1350
+ async claimStep(runId, stepId, attempt) {
1351
+ const key = leaseKey(runId, stepId, attempt);
1352
+ const now = Date.now();
1353
+ const existing = this.leases.get(key);
1354
+ if (existing && existing.expiresAt > now) {
1355
+ return null;
1356
+ }
1357
+ const token = `lease-${crypto.randomUUID()}`;
1358
+ this.leases.set(key, {
1359
+ runId,
1360
+ stepId,
1361
+ attempt,
1362
+ token,
1363
+ expiresAt: now + this.leaseMs
1364
+ });
1365
+ return token;
1366
+ }
1367
+ async extendLease(runId, stepId, attempt, leaseMs) {
1368
+ const key = leaseKey(runId, stepId, attempt);
1369
+ const existing = this.leases.get(key);
1370
+ if (existing === void 0) return;
1371
+ this.leases.set(key, { ...existing, expiresAt: Date.now() + leaseMs });
1372
+ }
1373
+ async sweepLeases(args) {
1374
+ const { now, queue, limit = DEFAULT_SWEEP_LIMIT } = args;
1375
+ const reaped = [];
1376
+ const candidates = selectExpired(this.leases.values(), {
1377
+ now,
1378
+ limit,
1379
+ deadline: (l) => new Date(l.expiresAt)
1380
+ });
1381
+ for (const lease of candidates) {
1382
+ const { runId, stepId, attempt } = lease;
1383
+ const factList = this.facts.get(runId);
1384
+ const state = factList ? foldRun(runId, factList) : null;
1385
+ const stepStatus = state ? stepStatusOf(stepStateOf(state, stepId)) : "pending";
1386
+ const decision = decideExpiredLeaseAction({
1387
+ lease: {
1388
+ runId,
1389
+ stepId,
1390
+ attempt,
1391
+ expiresAt: new Date(lease.expiresAt)
1392
+ },
1393
+ stepStatus,
1394
+ childActive: this.hasActiveChild(runId, stepId),
1395
+ now
1396
+ });
1397
+ if (decision.tag === "skip") continue;
1398
+ this.leases.delete(leaseKey(runId, stepId, attempt));
1399
+ await this.appendFact(
1400
+ runId,
1401
+ Facts.leaseReaped({ runId, stepId, attempt, at: now, reapedAt: now })
1402
+ );
1403
+ await queue.enqueue(runId, stepId, {
1404
+ attempt: decision.nextAttempt,
1405
+ delayMs: decision.backoffMs,
1406
+ ...state?.flowId !== void 0 ? { flowId: state.flowId } : {}
1407
+ });
1408
+ reaped.push({
1409
+ runId,
1410
+ stepId,
1411
+ attempt,
1412
+ nextAttempt: decision.nextAttempt
1413
+ });
1414
+ }
1415
+ return reaped;
1416
+ }
1417
+ async settleStep(runId, _stepId, fact) {
1418
+ await this.appendFact(runId, fact);
1419
+ }
1420
+ async settleSignal(args) {
1421
+ const { runId, stepId, at, incoming } = args;
1422
+ const runState = foldRun(runId, this.facts.get(runId) ?? []);
1423
+ const decision = decideSignal({ runState, stepId, at, incoming });
1424
+ switch (decision.kind) {
1425
+ case "noop":
1426
+ return decision.result;
1427
+ case "buffer":
1428
+ if (decision.fact !== null) await this.appendFact(runId, decision.fact);
1429
+ return decision.result;
1430
+ case "deliver":
1431
+ await this.appendFact(runId, decision.received);
1432
+ await this.appendFact(runId, decision.completed);
1433
+ return decision.result;
1434
+ }
1435
+ }
1436
+ async upsertTimer(runId, stepId, fireAt) {
1437
+ const key = timerKey(runId, stepId);
1438
+ if (!this.signalTimers.has(key)) {
1439
+ this.signalTimers.set(key, { runId, stepId, fireAt });
1440
+ }
1441
+ }
1442
+ async sweepSignalTimeouts(args) {
1443
+ const { now, limit = DEFAULT_SWEEP_LIMIT } = args;
1444
+ const timedOut = [];
1445
+ const due = selectExpired(this.signalTimers.values(), {
1446
+ now,
1447
+ limit,
1448
+ deadline: (t) => t.fireAt
1449
+ });
1450
+ for (const { runId, stepId, fireAt } of due) {
1451
+ const runState = foldRun(runId, this.facts.get(runId) ?? []);
1452
+ const decision = decideTimeout({ runState, stepId, fireAt, at: now });
1453
+ this.signalTimers.delete(timerKey(runId, stepId));
1454
+ if (decision.kind === "noop") continue;
1455
+ await this.appendFact(runId, decision.fact);
1456
+ timedOut.push({ runId, stepId, attempt: decision.attempt, fireAt });
1457
+ }
1458
+ return timedOut;
1459
+ }
1460
+ async recordOnce(runId, stepId, scope, value) {
1461
+ const key = `${runId}::${stepId}::${scope}`;
1462
+ if (!this.onces.has(key)) this.onces.set(key, value);
1463
+ }
1464
+ async getOnce(runId, stepId, scope) {
1465
+ return this.onces.get(`${runId}::${stepId}::${scope}`) ?? null;
1466
+ }
1467
+ async runStep(runId, _stepId, _attempt, body) {
1468
+ const result = await body(void 0);
1469
+ await this.appendFact(runId, result.fact);
1470
+ return result.output;
1471
+ }
1472
+ async upsertSnapshot(args) {
1473
+ if (this.snapshots.has(args.flowHash)) return;
1474
+ this.snapshots.set(args.flowHash, { flowId: args.flowId, dag: args.dag });
1475
+ }
1476
+ async getRef(flowId) {
1477
+ return this.refs.get(flowId) ?? null;
1478
+ }
1479
+ async setRef(flowId, flowHash) {
1480
+ this.refs.set(flowId, flowHash);
1481
+ }
1482
+ async loadSnapshot(flowHash) {
1483
+ return this.snapshots.get(flowHash) ?? null;
1484
+ }
1485
+ async appendGlobalFact(fact) {
1486
+ this.globalFacts.push(fact);
1487
+ }
1488
+ readGlobalFacts() {
1489
+ return this.globalFacts;
1490
+ }
1491
+ async queryRuns(opts) {
1492
+ const where = opts.where ?? {};
1493
+ const wanted = where.status && new Set(where.status);
1494
+ const matches = (summary) => (where.flowId === void 0 || summary.flowId === where.flowId) && (!wanted || wanted.has(summary.status)) && (where.input === void 0 || jsonContains(summary.input, where.input));
1495
+ const summaries = [];
1496
+ for (const [runId, factList] of this.facts) {
1497
+ const summary = summarize(runId, factList);
1498
+ if (summary === null) continue;
1499
+ if (matches(summary)) summaries.push(summary);
1500
+ }
1501
+ for (const summary of this.summaries.values()) {
1502
+ if (matches(summary)) summaries.push(summary);
1503
+ }
1504
+ summaries.sort(compareRunOrder);
1505
+ if (opts.latest === true) {
1506
+ return { runs: summaries.slice(0, 1), cursor: null };
1507
+ }
1508
+ const limit = clampQueryLimit(opts.limit);
1509
+ const cursor = opts.cursor === void 0 ? null : decodeRunCursor(opts.cursor);
1510
+ const rest = cursor === null ? summaries : summaries.filter((s) => isPastCursor(s, cursor));
1511
+ const page = rest.slice(0, limit);
1512
+ const last = page[page.length - 1];
1513
+ const next = rest.length > limit && last !== void 0 ? encodeRunCursor({ startedAt: last.startedAt, runId: last.runId }) : null;
1514
+ return { runs: page, cursor: next };
1515
+ }
1516
+ async describe(runId) {
1517
+ const factList = this.facts.get(runId);
1518
+ if (factList === void 0 || factList.length === 0) {
1519
+ return this.describeSummary(runId);
1520
+ }
1521
+ const first = factList[0];
1522
+ if (first === void 0 || first.kind !== "flow.started") return null;
1523
+ const state = foldRun(runId, factList);
1524
+ const status = runStatusOf(state);
1525
+ let completedAt;
1526
+ let output;
1527
+ let error;
1528
+ let canceledByRunId;
1529
+ let concurrencyKey;
1530
+ for (let i = isTerminalRun(state) ? factList.length - 1 : -1; i >= 0; i--) {
1531
+ const f = factList[i];
1532
+ if (f === void 0) continue;
1533
+ if (f.kind === "flow.completed") {
1534
+ completedAt = f.at;
1535
+ output = f.output;
1536
+ break;
1537
+ }
1538
+ if (f.kind === "flow.failed") {
1539
+ completedAt = f.at;
1540
+ error = f.error;
1541
+ break;
1542
+ }
1543
+ if (f.kind === "flow.canceled") {
1544
+ completedAt = f.at;
1545
+ if (f.cause === "concurrency") {
1546
+ canceledByRunId = f.canceledByRunId;
1547
+ }
1548
+ break;
1549
+ }
1550
+ }
1551
+ const slot = this.keyByActiveRun.get(runId);
1552
+ if (slot !== void 0) {
1553
+ const sep = slot.indexOf("::");
1554
+ if (sep >= 0) concurrencyKey = slot.slice(sep + 2);
1555
+ }
1556
+ if (concurrencyKey === void 0) {
1557
+ for (const f of factList) {
1558
+ if (f.kind === "flow.canceled" && f.cause === "concurrency") {
1559
+ concurrencyKey = f.concurrencyKey;
1560
+ break;
1561
+ }
1562
+ }
1563
+ }
1564
+ const childSet = this.childrenByParent.get(runId);
1565
+ const children = childSet ? Array.from(childSet) : [];
1566
+ const parent = first.parent;
1567
+ const run = {
1568
+ runId,
1569
+ flowId: first.flowId,
1570
+ flowHash: first.flowHash ?? "",
1571
+ status,
1572
+ startedAt: first.at,
1573
+ input: first.input,
1574
+ children,
1575
+ ...completedAt !== void 0 ? { completedAt } : {},
1576
+ ...output !== void 0 ? { output } : {},
1577
+ ...error !== void 0 ? { error } : {},
1578
+ ...canceledByRunId !== void 0 ? { canceledByRunId } : {},
1579
+ ...concurrencyKey !== void 0 ? { concurrencyKey } : {},
1580
+ ...parent !== void 0 ? { parent } : {}
1581
+ };
1582
+ const steps = [];
1583
+ const startedAtByStep = /* @__PURE__ */ new Map();
1584
+ const completedAtByStep = /* @__PURE__ */ new Map();
1585
+ for (const f of factList) {
1586
+ if (f.kind === "step.started" && !startedAtByStep.has(f.stepId)) {
1587
+ startedAtByStep.set(f.stepId, f.at);
1588
+ }
1589
+ if ((f.kind === "step.completed" || f.kind === "step.failed" || f.kind === "step.canceled" || f.kind === "step.skipped") && !completedAtByStep.has(f.stepId)) {
1590
+ completedAtByStep.set(f.stepId, f.at);
1591
+ }
1592
+ }
1593
+ const now = Date.now();
1594
+ for (const [stepId, stepState] of Object.entries(state.steps)) {
1595
+ const status2 = stepStatusOf(stepState);
1596
+ const attempt = attemptOf(stepState);
1597
+ const out = outputOf(stepState);
1598
+ const err = errorOf(stepState);
1599
+ const startedAt = startedAtByStep.get(stepId);
1600
+ const completedAt2 = completedAtByStep.get(stepId);
1601
+ let lease;
1602
+ let bestExpiry = 0;
1603
+ for (const l of this.leases.values()) {
1604
+ if (l.runId !== runId || l.stepId !== stepId) continue;
1605
+ if (l.expiresAt > now && l.expiresAt > bestExpiry) {
1606
+ bestExpiry = l.expiresAt;
1607
+ }
1608
+ }
1609
+ if (bestExpiry > 0) lease = { expiresAt: new Date(bestExpiry) };
1610
+ steps.push({
1611
+ stepId,
1612
+ attempt,
1613
+ status: status2,
1614
+ ...startedAt !== void 0 ? { startedAt } : {},
1615
+ ...completedAt2 !== void 0 ? { completedAt: completedAt2 } : {},
1616
+ ...out !== null ? { output: out } : {},
1617
+ ...err !== void 0 ? { error: err } : {},
1618
+ ...lease !== void 0 ? { lease } : {}
1619
+ });
1620
+ }
1621
+ steps.sort((a, b) => {
1622
+ const ta = a.startedAt?.getTime() ?? Number.POSITIVE_INFINITY;
1623
+ const tb = b.startedAt?.getTime() ?? Number.POSITIVE_INFINITY;
1624
+ if (ta !== tb) return ta - tb;
1625
+ return a.stepId < b.stepId ? -1 : a.stepId > b.stepId ? 1 : 0;
1626
+ });
1627
+ return { run, steps };
1628
+ }
1629
+ // A run pruned with keepSummary keeps its row in Postgres; the summary is
1630
+ // the in-memory equivalent, so describe() stays non-null for it.
1631
+ describeSummary(runId) {
1632
+ const s = this.summaries.get(runId);
1633
+ if (s === void 0) return null;
1634
+ const childSet = this.childrenByParent.get(runId);
1635
+ return {
1636
+ run: {
1637
+ runId,
1638
+ flowId: s.flowId,
1639
+ flowHash: "",
1640
+ status: s.status,
1641
+ startedAt: s.startedAt,
1642
+ input: s.input,
1643
+ children: childSet ? Array.from(childSet) : [],
1644
+ ...s.completedAt !== null ? { completedAt: s.completedAt } : {}
1645
+ },
1646
+ steps: []
1647
+ };
1648
+ }
1649
+ async pruneFacts(opts) {
1650
+ let runsPruned = 0;
1651
+ let factsPruned = 0;
1652
+ for (; ; ) {
1653
+ const batch = selectPruneBatch(this.pruneCandidates(), opts);
1654
+ if (batch.length === 0) break;
1655
+ for (const { factCount, parentRunId, ...summary } of batch) {
1656
+ const runId = summary.runId;
1657
+ this.facts.delete(runId);
1658
+ deleteByRunPrefix(this.onces, runId);
1659
+ deleteByRunPrefix(this.leases, runId);
1660
+ deleteByRunPrefix(this.signalTimers, runId);
1661
+ this.childrenByParent.delete(runId);
1662
+ if (parentRunId !== void 0) {
1663
+ const siblings = this.childrenByParent.get(parentRunId);
1664
+ if (siblings !== void 0) {
1665
+ siblings.delete(runId);
1666
+ if (siblings.size === 0) this.childrenByParent.delete(parentRunId);
1667
+ }
1668
+ }
1669
+ if (opts.keepSummary) {
1670
+ this.summaries.set(runId, summary);
1671
+ } else {
1672
+ this.summaries.delete(runId);
1673
+ }
1674
+ runsPruned += 1;
1675
+ factsPruned += factCount;
1676
+ }
1677
+ }
1678
+ return { runsPruned, factsPruned };
1679
+ }
1680
+ pruneCandidates() {
1681
+ const out = [];
1682
+ for (const [runId, factList] of this.facts) {
1683
+ const summary = summarize(runId, factList);
1684
+ if (summary === null) continue;
1685
+ const first = factList[0];
1686
+ const parentRunId = first !== void 0 && first.kind === "flow.started" ? first.parent?.runId : void 0;
1687
+ out.push({ ...summary, factCount: factList.length, parentRunId });
1688
+ }
1689
+ return out;
1690
+ }
1691
+ stream = {
1692
+ subscribeStream: (runId, stepId, opts) => {
1693
+ const state = foldRun(runId, this.facts.get(runId) ?? []);
1694
+ const stepStatus = stepStatusOf(stepStateOf(state, stepId));
1695
+ const runIsTerminal = isTerminalRun(state);
1696
+ if (runIsTerminal || stepStatus === "completed" || stepStatus === "failed" || stepStatus === "canceled" || stepStatus === "skipped") {
1697
+ return EMPTY_CLOSED_STREAM;
1698
+ }
1699
+ return this.streamHub.subscribeStream(runId, stepId, opts);
1700
+ },
1701
+ publishChunk: (runId, stepId, chunk) => {
1702
+ this.streamHub.publishChunk(runId, stepId, chunk);
1703
+ }
1704
+ };
1705
+ };
1706
+ var EMPTY_CLOSED_STREAM = {
1707
+ [Symbol.asyncIterator]() {
1708
+ return { next: async () => ({ value: void 0, done: true }) };
1709
+ }
1710
+ };
1711
+ function deleteByRunPrefix(map, runId) {
1712
+ const prefix = `${runId}::`;
1713
+ for (const key of map.keys()) {
1714
+ if (key.startsWith(prefix)) map.delete(key);
1715
+ }
1716
+ }
1717
+ function summarize(runId, facts) {
1718
+ const first = facts[0];
1719
+ if (first === void 0 || first.kind !== "flow.started") return null;
1720
+ const projected = foldRun(runId, facts);
1721
+ let completedAt = null;
1722
+ for (let i = isTerminalRun(projected) ? facts.length - 1 : -1; i >= 0; i--) {
1723
+ const f = facts[i];
1724
+ if (f === void 0) continue;
1725
+ if (f.kind === "flow.completed" || f.kind === "flow.failed" || f.kind === "flow.canceled") {
1726
+ completedAt = f.at;
1727
+ break;
1728
+ }
1729
+ }
1730
+ return {
1731
+ runId,
1732
+ flowId: first.flowId,
1733
+ status: runStatusOf(projected),
1734
+ startedAt: first.at,
1735
+ completedAt,
1736
+ input: first.input
1737
+ };
1738
+ }
1739
+ var DEFAULT_QUEUE_LEASE_MS = 6e4;
1740
+ var InMemoryQueue = class {
1741
+ pending = [];
1742
+ leased = /* @__PURE__ */ new Map();
1743
+ leaseMs;
1744
+ constructor(opts = {}) {
1745
+ this.leaseMs = opts.leaseMs ?? DEFAULT_QUEUE_LEASE_MS;
1746
+ }
1747
+ async enqueue(runId, stepId, opts) {
1748
+ const now = Date.now();
1749
+ const item = {
1750
+ receipt: crypto.randomUUID(),
1751
+ runId,
1752
+ stepId,
1753
+ payload: opts?.payload ?? null,
1754
+ attempt: opts?.attempt ?? 1,
1755
+ readCount: 0,
1756
+ enqueuedAt: now,
1757
+ visibleAt: now + (opts?.delayMs ?? 0),
1758
+ ...opts?.flowId !== void 0 ? { flowId: opts.flowId } : {}
1759
+ };
1760
+ this.pending.push(item);
1761
+ }
1762
+ async dequeue(opts) {
1763
+ const now = Date.now();
1764
+ const claimed = [];
1765
+ for (let i = 0; i < this.pending.length && claimed.length < opts.count; i++) {
1766
+ const item = this.pending[i];
1767
+ if (item === void 0) continue;
1768
+ if (item.visibleAt > now) continue;
1769
+ const delivered = {
1770
+ ...item,
1771
+ readCount: item.readCount + 1,
1772
+ visibleAt: now + this.leaseMs
1773
+ };
1774
+ this.pending.splice(i, 1);
1775
+ i--;
1776
+ this.leased.set(item.receipt, delivered);
1777
+ claimed.push(delivered);
1778
+ }
1779
+ return claimed;
1780
+ }
1781
+ async ack(receipt) {
1782
+ this.leased.delete(receipt);
1783
+ }
1784
+ async nack(receipt, opts) {
1785
+ const item = this.leased.get(receipt);
1786
+ if (!item) return;
1787
+ this.leased.delete(receipt);
1788
+ const requeued = {
1789
+ ...item,
1790
+ visibleAt: Date.now() + (opts?.delayMs ?? 0)
1791
+ };
1792
+ this.pending.push(requeued);
1793
+ }
1794
+ async extend(receipt, leaseMs) {
1795
+ const item = this.leased.get(receipt);
1796
+ if (!item) return;
1797
+ this.leased.set(receipt, { ...item, visibleAt: Date.now() + leaseMs });
1798
+ }
1799
+ async inspect(runId) {
1800
+ const all = [...this.pending, ...this.leased.values()];
1801
+ return all.filter((m) => m.runId === runId).map((m) => ({
1802
+ stepId: m.stepId,
1803
+ attempt: m.attempt,
1804
+ readCount: m.readCount,
1805
+ visibleAt: new Date(m.visibleAt)
1806
+ }));
1807
+ }
1808
+ };
1809
+ var InMemoryClock = class {
1810
+ now() {
1811
+ return /* @__PURE__ */ new Date();
1812
+ }
1813
+ async sleep(ms, signal) {
1814
+ if (signal?.aborted) {
1815
+ throw signal.reason ?? new Error("aborted");
1816
+ }
1817
+ return new Promise((resolve, reject) => {
1818
+ const timer = setTimeout(() => {
1819
+ signal?.removeEventListener("abort", onAbort);
1820
+ resolve();
1821
+ }, ms);
1822
+ const onAbort = () => {
1823
+ clearTimeout(timer);
1824
+ reject(signal?.reason ?? new Error("aborted"));
1825
+ };
1826
+ signal?.addEventListener("abort", onAbort, { once: true });
1827
+ });
1828
+ }
1829
+ };
1830
+
1831
+ export { DEFAULT_REAPER_INTERVAL_MS, DEFAULT_RETRY, DEFAULT_SWEEP_LIMIT, Facts, InMemoryClock, InMemoryQueue, InMemoryStore, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiNonRetryableError, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiValidationError, QUERY_RUNS_DEFAULT_LIMIT, QUERY_RUNS_MAX_LIMIT, asStepMapWithDefs, attachDef, attemptOf, clampQueryLimit, compact, compareRunOrder, decideExpiredLeaseAction, decideSignal, decideTimeout, decodeRunCursor, defaultSnapshotGonePolicy, dequeueBackoff, encodeRunCursor, errorOf, factEffects, foldRun, getDef, handlerDef, isAbortRequested, isPastCursor, isStepTerminal, isTerminalRun, jsonContains, makeEmit, makeSignals, needsStepIds, normalizeNeeds, outputOf, peekDef, resolveNeeds, resolveRetry, resolvedOf, rowDeltaOf, runStatusOf, selectArm, selectExpired, selectPruneBatch, serializeError, setDef, stepBackoff, stepStateOf, stepStatusOf, unwrap, validate, validationError };
1832
+ //# sourceMappingURL=chunk-VQTYTI6X.js.map
1833
+ //# sourceMappingURL=chunk-VQTYTI6X.js.map