@nagi-js/core 0.1.1-rc.10 → 0.1.1-rc.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,113 @@
1
+ type SkipReason = "when-false" | "transitive" | "manual";
2
+ type StepCancelCause = {
3
+ readonly kind: "run-canceled";
4
+ } | {
5
+ readonly kind: "aborted";
6
+ readonly error?: SerializedError;
7
+ };
8
+ type RunCancelCause = {
9
+ readonly kind: "concurrency";
10
+ readonly canceledByRunId: RunId;
11
+ readonly concurrencyKey: string;
12
+ } | {
13
+ readonly kind: "explicit";
14
+ readonly reason: string;
15
+ readonly note?: string;
16
+ } | {
17
+ readonly kind: "operator";
18
+ readonly actor: string;
19
+ readonly reason: string;
20
+ readonly note?: string;
21
+ };
22
+ type StepState = {
23
+ readonly tag: "pending";
24
+ } | {
25
+ readonly tag: "running";
26
+ readonly attempt: AttemptNumber;
27
+ } | {
28
+ readonly tag: "awaitingSignal";
29
+ readonly attempt: AttemptNumber;
30
+ } | {
31
+ readonly tag: "awaitingChild";
32
+ readonly attempt: AttemptNumber;
33
+ } | {
34
+ readonly tag: "backoff";
35
+ readonly failedAttempt: AttemptNumber;
36
+ readonly retryAt: Date;
37
+ readonly error: SerializedError;
38
+ } | {
39
+ readonly tag: "aborting";
40
+ readonly attempt: AttemptNumber;
41
+ } | {
42
+ readonly tag: "completed";
43
+ readonly attempt: AttemptNumber;
44
+ readonly output: Json;
45
+ } | {
46
+ readonly tag: "failed";
47
+ readonly attempt: AttemptNumber;
48
+ readonly error: SerializedError;
49
+ } | {
50
+ readonly tag: "skipped";
51
+ readonly reason: SkipReason;
52
+ } | {
53
+ readonly tag: "canceled";
54
+ readonly cause: StepCancelCause;
55
+ };
56
+ type Resolved<T = Json> = {
57
+ readonly tag: "value";
58
+ readonly value: T;
59
+ } | {
60
+ readonly tag: "skipped";
61
+ };
62
+ type RunPhase = {
63
+ readonly tag: "pending";
64
+ } | {
65
+ readonly tag: "running";
66
+ } | {
67
+ readonly tag: "completed";
68
+ readonly output: Json;
69
+ } | {
70
+ readonly tag: "failed";
71
+ readonly error: SerializedError;
72
+ } | {
73
+ readonly tag: "canceled";
74
+ readonly cause: RunCancelCause;
75
+ };
76
+ interface Anomaly {
77
+ readonly at: Date;
78
+ readonly stepId?: StepId;
79
+ readonly from: string;
80
+ readonly fact: Fact["kind"];
81
+ }
82
+ interface RunState {
83
+ readonly runId: RunId;
84
+ readonly flowId: string;
85
+ readonly input: Json;
86
+ readonly phase: RunPhase;
87
+ readonly steps: Readonly<Record<StepId, StepState>>;
88
+ readonly selectedArms: Readonly<Record<StepId, string>>;
89
+ readonly bufferedSignals: Readonly<Record<StepId, {
90
+ readonly payload: Json;
91
+ readonly signalName?: string;
92
+ }>>;
93
+ readonly anomalies: readonly Anomaly[];
94
+ readonly facts: readonly Fact[];
95
+ readonly parent?: ParentLink;
96
+ readonly flowHash?: string;
97
+ readonly codeVersion?: string;
98
+ }
99
+ declare function stepStateOf(runState: RunState, stepId: StepId): StepState;
100
+ declare function runStatusOf(state: RunState): RunStatus;
101
+ declare function stepStatusOf(s: StepState): StepStatus;
102
+ declare function outputOf(s: StepState): Json | null;
103
+ declare function errorOf(s: StepState): SerializedError | undefined;
104
+ declare function attemptOf(s: StepState): AttemptNumber;
105
+ declare function resolvedOf(s: StepState): Resolved;
106
+ declare function unwrap<T>(r: Resolved<T>): T;
107
+ declare function isTerminalRun(state: RunState): boolean;
108
+ declare function isStepTerminal(s: StepState): boolean;
109
+ declare function foldRun(runId: RunId, facts: readonly Fact[]): RunState;
110
+
1
111
  type Json = string | number | boolean | null | Json[] | {
2
112
  [key: string]: Json;
3
113
  };
@@ -44,7 +154,7 @@ interface Register {
44
154
  type Tx = Register extends {
45
155
  tx: infer T;
46
156
  } ? T : unknown;
47
- type StepKind = "task" | "signal" | "match" | "subflow";
157
+ type StepKind = "task" | "activity" | "signal" | "match" | "subflow" | "streaming";
48
158
  interface Step<Output = unknown> {
49
159
  readonly kind: StepKind;
50
160
  readonly id: StepId;
@@ -52,10 +162,23 @@ interface Step<Output = unknown> {
52
162
  }
53
163
  type StepOutput<S> = S extends Step<infer O> ? O : never;
54
164
  type StepMap = Readonly<Record<string, Step<unknown>>>;
55
- type NeedsMap = StepMap;
165
+ interface Optional<S extends Step = Step> {
166
+ readonly __optional: S;
167
+ }
168
+ type NeedRef = Step | Optional<Step>;
169
+ type NeedsMap = Readonly<Record<string, NeedRef>>;
56
170
  type NeedsOutputs<N extends NeedsMap> = {
57
171
  readonly [K in keyof N]: StepOutput<N[K]>;
58
172
  };
173
+ type ResolvedNeeds<N extends NeedsMap> = {
174
+ readonly [K in keyof N]: N[K] extends Optional<infer S> ? Resolved<StepOutput<S>> : N[K] extends Step ? StepOutput<N[K]> : never;
175
+ };
176
+ type LogLevel = "debug" | "info" | "warn" | "error";
177
+ interface LogEntry {
178
+ readonly level: LogLevel;
179
+ readonly msg: string;
180
+ readonly attrs?: Record<string, unknown>;
181
+ }
59
182
  interface Logger {
60
183
  debug(message: string, attrs?: Record<string, unknown>): void;
61
184
  info(message: string, attrs?: Record<string, unknown>): void;
@@ -74,6 +197,23 @@ interface StepCtx<Input = unknown> {
74
197
  once<T extends Json>(scope: string, fn: () => Promise<T>): Promise<T>;
75
198
  idempotencyKey(scope: string): string;
76
199
  }
200
+ type ActivityCtx<Input = unknown> = Omit<StepCtx<Input>, "tx">;
201
+ type StreamEvent<C = Json> = {
202
+ readonly kind: "chunk";
203
+ readonly chunk: C;
204
+ } | {
205
+ readonly kind: "dropped";
206
+ readonly count: number;
207
+ } | {
208
+ readonly kind: "retry";
209
+ readonly attempt: AttemptNumber;
210
+ } | {
211
+ readonly kind: "error";
212
+ readonly error: SerializedError;
213
+ };
214
+ interface StreamingStepCtx<Input = unknown, Chunk = Json> extends StepCtx<Input> {
215
+ readonly emit: (chunk: Chunk) => Promise<void>;
216
+ }
77
217
  type BackoffStrategy = "exponential" | "linear" | "fixed";
78
218
  interface RetryPolicy {
79
219
  readonly maxAttempts: number;
@@ -86,17 +226,11 @@ interface StepConfigBase<Input, N extends NeedsMap> {
86
226
  readonly needs?: N;
87
227
  readonly when?: (args: {
88
228
  readonly input: NoInfer<Input>;
89
- readonly needs: NoInfer<NeedsOutputs<N>>;
229
+ readonly needs: NoInfer<ResolvedNeeds<N>>;
90
230
  }) => boolean;
91
231
  readonly timeoutMs?: Millis;
92
232
  }
93
- interface TaskConfig<Input, N extends NeedsMap, Output> extends StepConfigBase<Input, N> {
94
- readonly retry?: RetryPolicy;
95
- readonly run: (args: {
96
- readonly input: NoInfer<Input>;
97
- readonly needs: NoInfer<NeedsOutputs<N>>;
98
- readonly ctx: StepCtx<NoInfer<Input>>;
99
- }) => Promise<Output>;
233
+ interface StepLifecycleHooks<Output> {
100
234
  readonly onStart?: (event: StepStartEvent) => void | Promise<void>;
101
235
  readonly onComplete?: (event: StepCompleteEvent & {
102
236
  readonly output: NoInfer<Output>;
@@ -104,6 +238,30 @@ interface TaskConfig<Input, N extends NeedsMap, Output> extends StepConfigBase<I
104
238
  readonly onError?: (event: StepErrorEvent) => void | Promise<void>;
105
239
  readonly onRetry?: (event: StepRetryEvent) => void | Promise<void>;
106
240
  }
241
+ interface TaskConfig<Input, N extends NeedsMap, Output> extends StepConfigBase<Input, N>, StepLifecycleHooks<Output> {
242
+ readonly retry?: RetryPolicy;
243
+ readonly run: (args: {
244
+ readonly input: NoInfer<Input>;
245
+ readonly needs: NoInfer<ResolvedNeeds<N>>;
246
+ readonly ctx: StepCtx<NoInfer<Input>>;
247
+ }) => Promise<Output>;
248
+ }
249
+ interface ActivityConfig<Input, N extends NeedsMap, Output> extends StepConfigBase<Input, N>, StepLifecycleHooks<Output> {
250
+ readonly retry?: RetryPolicy;
251
+ readonly run: (args: {
252
+ readonly input: NoInfer<Input>;
253
+ readonly needs: NoInfer<ResolvedNeeds<N>>;
254
+ readonly ctx: ActivityCtx<NoInfer<Input>>;
255
+ }) => Promise<Output>;
256
+ }
257
+ interface StreamingTaskConfig<Input, N extends NeedsMap, Output, Chunk> extends StepConfigBase<Input, N>, StepLifecycleHooks<Output> {
258
+ readonly retry?: RetryPolicy;
259
+ readonly run: (args: {
260
+ readonly input: NoInfer<Input>;
261
+ readonly needs: NoInfer<ResolvedNeeds<N>>;
262
+ readonly ctx: StreamingStepCtx<NoInfer<Input>, Chunk>;
263
+ }) => Promise<Output>;
264
+ }
107
265
  interface SignalConfig<Input, N extends NeedsMap, Schema extends StandardSchemaV1> extends StepConfigBase<Input, N> {
108
266
  readonly schema: Schema;
109
267
  readonly names?: readonly [string, ...string[]];
@@ -111,7 +269,7 @@ interface SignalConfig<Input, N extends NeedsMap, Schema extends StandardSchemaV
111
269
  interface MatchArmGuard<Input, N extends NeedsMap, M extends StepMap> {
112
270
  readonly when: (args: {
113
271
  readonly input: NoInfer<Input>;
114
- readonly needs: NoInfer<NeedsOutputs<N>>;
272
+ readonly needs: NoInfer<ResolvedNeeds<N>>;
115
273
  }) => boolean;
116
274
  readonly otherwise?: never;
117
275
  readonly build: (b: Builder<Input>) => M;
@@ -125,7 +283,7 @@ type MatchArm<Input, N extends NeedsMap, M extends StepMap> = MatchArmGuard<Inpu
125
283
  type MatchArmShape<Input, N extends NeedsMap> = {
126
284
  readonly when: (args: {
127
285
  readonly input: NoInfer<Input>;
128
- readonly needs: NoInfer<NeedsOutputs<N>>;
286
+ readonly needs: NoInfer<ResolvedNeeds<N>>;
129
287
  }) => boolean;
130
288
  readonly otherwise?: never;
131
289
  readonly build: (b: Builder<Input>) => StepMap;
@@ -144,7 +302,7 @@ type MatchArmOutput<M extends StepMap> = {
144
302
  interface SubflowConfig<Input, N extends NeedsMap, Child extends Flow> extends StepConfigBase<Input, N> {
145
303
  readonly input: (args: {
146
304
  readonly input: NoInfer<Input>;
147
- readonly needs: NoInfer<NeedsOutputs<N>>;
305
+ readonly needs: NoInfer<ResolvedNeeds<N>>;
148
306
  }) => FlowInput<Child>;
149
307
  }
150
308
  interface SubflowStepOutput<ChildOutput> {
@@ -153,6 +311,8 @@ interface SubflowStepOutput<ChildOutput> {
153
311
  }
154
312
  interface Builder<Input = unknown> {
155
313
  task<N extends NeedsMap, Output>(config: TaskConfig<Input, N, Output>): Step<Output>;
314
+ activity<N extends NeedsMap, Output>(config: ActivityConfig<Input, N, Output>): Step<Output>;
315
+ streamingTask<N extends NeedsMap, O, C = Json>(config: StreamingTaskConfig<Input, N, O, C>): Step<O>;
156
316
  signal<N extends NeedsMap, S extends StandardSchemaV1>(config: SignalConfig<Input, N, S>): Step<InferSchemaOutput<S>>;
157
317
  subflow<N extends NeedsMap, Child extends Flow>(child: Child, config: SubflowConfig<Input, N, Child>): Step<SubflowStepOutput<FlowOutput<Child>>>;
158
318
  match<N extends NeedsMap, Arms extends ReadonlyArray<MatchArmShape<Input, N>>>(config: {
@@ -197,19 +357,10 @@ interface Flow<Id extends string = string, InputSchema extends StandardSchemaV1
197
357
  type FlowInput<F> = F extends Flow<string, infer S, StepMap, unknown> ? InferSchemaOutput<S> : never;
198
358
  type FlowOutput<F> = F extends Flow<string, StandardSchemaV1, StepMap, infer O> ? O : never;
199
359
  type FlowIdOf<T extends ReadonlyArray<Flow>> = T[number] extends Flow<infer Id> ? Id : never;
200
- /**
201
- * Durable parent linkage persisted on {@link FlowStartedFact}. Present when a
202
- * run was started as a subflow child; absent for top-level runs.
203
- */
204
360
  interface ParentLink {
205
361
  readonly runId: RunId;
206
362
  readonly stepId: StepId;
207
363
  }
208
- /**
209
- * In-process parent reference: a {@link ParentLink} plus the parent step's
210
- * attempt, used to thread otel spans and registry lookups. Not persisted — the
211
- * attempt is re-derived from parent run state when a subflow wakes its parent.
212
- */
213
364
  interface ParentRef extends ParentLink {
214
365
  readonly attempt: AttemptNumber;
215
366
  }
@@ -220,11 +371,6 @@ interface FlowEvent {
220
371
  }
221
372
  interface FlowStartEvent extends FlowEvent {
222
373
  readonly input: Json;
223
- /**
224
- * Set when this run was started as a subflow child. Undefined for
225
- * top-level runs (start / startById). Carried in-process only — for
226
- * durable linkage see {@link FlowStartedFact.parent}.
227
- */
228
374
  readonly parent?: ParentRef;
229
375
  }
230
376
  interface FlowCompleteEvent extends FlowEvent {
@@ -243,7 +389,7 @@ interface StepStartEvent extends StepEvent {
243
389
  }
244
390
  interface StepCompleteEvent extends StepEvent {
245
391
  readonly output: Json;
246
- readonly durationMs: Millis;
392
+ readonly durationMs?: Millis;
247
393
  }
248
394
  interface StepErrorEvent extends StepEvent {
249
395
  readonly error: SerializedError;
@@ -297,9 +443,28 @@ interface SerializedError {
297
443
  readonly stack?: string;
298
444
  readonly cause?: Json;
299
445
  }
446
+ type SettleSignalResult = {
447
+ readonly tag: "delivered";
448
+ readonly attempt: AttemptNumber;
449
+ readonly payload: Json;
450
+ readonly signalName?: string;
451
+ } | {
452
+ readonly tag: "buffered";
453
+ } | {
454
+ readonly tag: "noop";
455
+ };
300
456
  interface Store {
301
457
  appendFact(runId: RunId, fact: Fact): Promise<void>;
302
458
  loadRunState(runId: RunId): Promise<RunState>;
459
+ settleSignal(args: {
460
+ readonly runId: RunId;
461
+ readonly stepId: StepId;
462
+ readonly at: Date;
463
+ readonly incoming?: {
464
+ readonly payload: Json;
465
+ readonly signalName?: string;
466
+ };
467
+ }): Promise<SettleSignalResult>;
303
468
  tryStartRun(runId: RunId, fact: FlowStartedFact, concurrency?: {
304
469
  readonly key: string;
305
470
  readonly mode: ConcurrencyMode;
@@ -311,9 +476,7 @@ interface Store {
311
476
  }>;
312
477
  }>;
313
478
  claimStep(runId: RunId, stepId: StepId, attempt: AttemptNumber): Promise<ClaimToken | null>;
314
- completeStep(runId: RunId, stepId: StepId, output: Json, fact: Fact): Promise<void>;
315
- failStep(runId: RunId, stepId: StepId, error: SerializedError, fact: Fact): Promise<void>;
316
- getStepOutput(runId: RunId, stepId: StepId): Promise<Json | null>;
479
+ settleStep(runId: RunId, stepId: StepId, fact: StepCompletedFact | StepFailedFact): Promise<void>;
317
480
  recordOnce(runId: RunId, stepId: StepId, scope: string, value: Json): Promise<void>;
318
481
  getOnce(runId: RunId, stepId: StepId, scope: string): Promise<Json | null>;
319
482
  runStep<T extends Json>(runId: RunId, stepId: StepId, attempt: AttemptNumber, body: (tx: Tx) => Promise<{
@@ -336,9 +499,15 @@ interface Store {
336
499
  listChildren(parentRunId: RunId): Promise<ReadonlyArray<RunId>>;
337
500
  pruneFacts(opts: Required<PruneOpts>): Promise<PruneResult>;
338
501
  }
502
+ interface StreamTransport {
503
+ subscribeStream(runId: RunId, stepId: StepId, opts?: {
504
+ readonly replayBuffered?: boolean;
505
+ }): AsyncIterable<StreamEvent<Json>>;
506
+ publishChunk(runId: RunId, stepId: StepId, chunk: Json): void;
507
+ }
339
508
  interface QueryRunsWhere<FlowId extends string = string> {
340
509
  readonly flowId?: FlowId;
341
- readonly status?: RunStatus | ReadonlyArray<RunStatus>;
510
+ readonly status?: ReadonlyArray<RunStatus>;
342
511
  readonly input?: Record<string, Json>;
343
512
  }
344
513
  type QueryRunsOpts<FlowId extends string = string> = {
@@ -398,12 +567,6 @@ interface Queue {
398
567
  delayMs?: Millis;
399
568
  }): Promise<void>;
400
569
  extend(receipt: string, leaseMs: Millis): Promise<void>;
401
- /**
402
- * Optional one-shot, idempotent provisioning of the queue's backing schema.
403
- * When present, `nagi()` awaits it once at construction (fail-fast), so a
404
- * misconfigured queue surfaces at boot instead of on first enqueue. Adapters
405
- * needing no provisioning (e.g. in-memory) omit it.
406
- */
407
570
  ensureSchema?(): Promise<void>;
408
571
  }
409
572
  interface Clock {
@@ -414,7 +577,7 @@ interface Clock {
414
577
  interface Trigger {
415
578
  subscribe(handler: (runId: RunId) => void): () => void;
416
579
  }
417
- type FactKind = "flow.started" | "flow.completed" | "flow.failed" | "flow.canceled" | "step.started" | "step.completed" | "step.failed" | "step.canceled" | "step.retried" | "step.skipped" | "step.reset" | "step.abort-requested" | "signal.sent" | "signal.received" | "once.recorded" | "match.arm-selected";
580
+ type FactKind = "flow.started" | "flow.completed" | "flow.failed" | "flow.canceled" | "step.started" | "step.completed" | "step.failed" | "step.canceled" | "step.retried" | "step.skipped" | "step.reset" | "step.abort-requested" | "signal.sent" | "signal.received" | "signal.buffered" | "once.recorded" | "match.arm-selected";
418
581
  interface FactBase {
419
582
  readonly runId: RunId;
420
583
  readonly at: Date;
@@ -425,7 +588,6 @@ interface FlowStartedFact extends FactBase {
425
588
  readonly input: Json;
426
589
  readonly flowHash?: string;
427
590
  readonly codeVersion?: string;
428
- /** Present when this run was started as a subflow child; absent for roots. */
429
591
  readonly parent?: ParentLink;
430
592
  }
431
593
  interface FlowRefUpdatedFact {
@@ -464,10 +626,13 @@ interface FlowCanceledByOperatorFact extends FactBase {
464
626
  readonly note?: string;
465
627
  }
466
628
  type FlowCanceledFact = FlowCanceledByConcurrencyFact | FlowCanceledExplicitlyFact | FlowCanceledByOperatorFact;
629
+ type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
630
+ type CancelArgs = DistributiveOmit<FlowCanceledExplicitlyFact | FlowCanceledByOperatorFact, "kind" | "runId" | "at">;
467
631
  interface StepStartedFact extends FactBase {
468
632
  readonly kind: "step.started";
469
633
  readonly stepId: StepId;
470
634
  readonly attempt: AttemptNumber;
635
+ readonly stepKind: StepKind;
471
636
  }
472
637
  interface StepCompletedFact extends FactBase {
473
638
  readonly kind: "step.completed";
@@ -492,6 +657,7 @@ interface StepRetriedFact extends FactBase {
492
657
  readonly stepId: StepId;
493
658
  readonly attempt: AttemptNumber;
494
659
  readonly nextAttemptAt: Date;
660
+ readonly error: SerializedError;
495
661
  }
496
662
  interface StepSkippedFact extends FactBase {
497
663
  readonly kind: "step.skipped";
@@ -499,7 +665,6 @@ interface StepSkippedFact extends FactBase {
499
665
  readonly reason: "when-false" | "transitive" | "manual";
500
666
  readonly actor?: string;
501
667
  readonly note?: string;
502
- readonly cascade?: "skip" | "continue";
503
668
  }
504
669
  interface SignalSentFact extends FactBase {
505
670
  readonly kind: "signal.sent";
@@ -512,6 +677,12 @@ interface SignalReceivedFact extends FactBase {
512
677
  readonly payload: Json;
513
678
  readonly signalName?: string;
514
679
  }
680
+ interface SignalBufferedFact extends FactBase {
681
+ readonly kind: "signal.buffered";
682
+ readonly stepId: StepId;
683
+ readonly payload: Json;
684
+ readonly signalName?: string;
685
+ }
515
686
  interface OnceRecordedFact extends FactBase {
516
687
  readonly kind: "once.recorded";
517
688
  readonly stepId: StepId;
@@ -537,25 +708,10 @@ interface StepAbortRequestedFact extends FactBase {
537
708
  readonly actor: string;
538
709
  readonly note?: string;
539
710
  }
540
- type Fact = FlowStartedFact | FlowCompletedFact | FlowFailedFact | FlowCanceledFact | StepStartedFact | StepCompletedFact | StepFailedFact | StepCanceledFact | StepRetriedFact | StepSkippedFact | StepResetFact | StepAbortRequestedFact | SignalSentFact | SignalReceivedFact | OnceRecordedFact | MatchArmSelectedFact;
711
+ type Fact = FlowStartedFact | FlowCompletedFact | FlowFailedFact | FlowCanceledFact | StepStartedFact | StepCompletedFact | StepFailedFact | StepCanceledFact | StepRetriedFact | StepSkippedFact | StepResetFact | StepAbortRequestedFact | SignalSentFact | SignalReceivedFact | SignalBufferedFact | OnceRecordedFact | MatchArmSelectedFact;
541
712
  type RunStatus = "pending" | "running" | "completed" | "failed" | "canceled";
542
713
  type StepStatus = "pending" | "running" | "completed" | "failed" | "canceled" | "skipped";
543
- interface StepState {
544
- readonly stepId: StepId;
545
- readonly status: StepStatus;
546
- readonly attempts: AttemptNumber;
547
- readonly output?: Json;
548
- readonly error?: SerializedError;
549
- }
550
- interface RunState {
551
- readonly runId: RunId;
552
- readonly flowId: string;
553
- readonly status: RunStatus;
554
- readonly steps: Readonly<Record<StepId, StepState>>;
555
- readonly facts: ReadonlyArray<Fact>;
556
- readonly flowHash?: string;
557
- readonly codeVersion?: string;
558
- }
714
+
559
715
  type ReplayMode = "inspect" | "continue";
560
716
  interface ReplayOpts {
561
717
  readonly mode: ReplayMode;
@@ -567,16 +723,14 @@ interface OperatorAuditOpts {
567
723
  readonly actor: string;
568
724
  readonly note?: string;
569
725
  }
570
- interface OperatorSkipOpts extends OperatorAuditOpts {
571
- readonly cascade?: "skip" | "continue";
572
- }
573
726
  interface Operator {
574
- skip(runId: RunId, stepId: StepId, opts: OperatorSkipOpts): Promise<void>;
727
+ skip(runId: RunId, stepId: StepId, opts: OperatorAuditOpts): Promise<void>;
575
728
  retry(runId: RunId, stepId: StepId, opts: OperatorAuditOpts): Promise<void>;
576
729
  abort(runId: RunId, opts: OperatorAuditOpts): Promise<void>;
577
730
  }
578
731
 
579
732
  declare function flow<const Id extends string, InputSchema extends StandardSchemaV1, R extends StepMap, Output = unknown>(config: FlowConfig<Id, InputSchema, R, Output>): Flow<Id, InputSchema, R, Output>;
733
+ declare function optional<S extends Step>(step: S): Optional<S>;
580
734
 
581
735
  interface CanonicalRetryPolicy {
582
736
  readonly maxAttempts: number;
@@ -624,7 +778,7 @@ interface SnapshotChangedEdge {
624
778
  readonly before: "needed" | "absent";
625
779
  readonly after: "needed" | "absent";
626
780
  }
627
- interface SnapshotChangedField_ {
781
+ interface SnapshotChangedPredicate {
628
782
  readonly stepId: StepId;
629
783
  readonly field: SnapshotChangedField;
630
784
  }
@@ -632,16 +786,43 @@ interface SnapshotDiff {
632
786
  readonly addedSteps: readonly StepId[];
633
787
  readonly removedSteps: readonly StepId[];
634
788
  readonly changedEdges: readonly SnapshotChangedEdge[];
635
- readonly changedPredicates: readonly SnapshotChangedField_[];
789
+ readonly changedPredicates: readonly SnapshotChangedPredicate[];
636
790
  }
637
791
  declare function diffSnapshots(before: CanonicalDag, after: CanonicalDag): SnapshotDiff;
638
792
 
793
+ declare class NagiValidationError extends Error {
794
+ readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
795
+ constructor(issues: ReadonlyArray<StandardSchemaV1.Issue>);
796
+ }
797
+ declare class NagiRuntimeError extends Error {
798
+ constructor(message: string);
799
+ }
800
+ declare class NagiCanceledError extends Error {
801
+ readonly runId: RunId;
802
+ readonly canceledByRunId: RunId;
803
+ readonly concurrencyKey: string;
804
+ constructor({ runId, canceledByRunId, concurrencyKey, }: {
805
+ readonly runId: RunId;
806
+ readonly canceledByRunId: RunId;
807
+ readonly concurrencyKey: string;
808
+ });
809
+ }
810
+ declare class NagiSnapshotDriftError extends Error {
811
+ readonly runId: RunId;
812
+ readonly expected: string;
813
+ readonly actual: string;
814
+ constructor({ runId, expected, actual, }: {
815
+ readonly runId: RunId;
816
+ readonly expected: string;
817
+ readonly actual: string;
818
+ });
819
+ }
820
+
639
821
  interface InMemoryStoreOpts {
640
822
  readonly leaseMs?: Millis;
641
823
  }
642
- declare class InMemoryStore implements Store {
824
+ declare class InMemoryStore implements Store, StreamTransport {
643
825
  private readonly facts;
644
- private readonly outputs;
645
826
  private readonly onces;
646
827
  private readonly leases;
647
828
  private readonly snapshots;
@@ -651,6 +832,7 @@ declare class InMemoryStore implements Store {
651
832
  private readonly keyByActiveRun;
652
833
  private readonly childrenByParent;
653
834
  private readonly summaries;
835
+ private readonly streamHub;
654
836
  private readonly leaseMs;
655
837
  constructor(opts?: InMemoryStoreOpts);
656
838
  appendFact(runId: RunId, fact: Fact): Promise<void>;
@@ -667,12 +849,19 @@ declare class InMemoryStore implements Store {
667
849
  listChildren(parentRunId: RunId): Promise<ReadonlyArray<RunId>>;
668
850
  loadRunState(runId: RunId): Promise<RunState>;
669
851
  claimStep(runId: RunId, stepId: StepId, attempt: AttemptNumber): Promise<ClaimToken | null>;
670
- completeStep(runId: RunId, stepId: StepId, output: Json, fact: Fact): Promise<void>;
671
- failStep(runId: RunId, _stepId: StepId, _error: SerializedError, fact: Fact): Promise<void>;
672
- getStepOutput(runId: RunId, stepId: StepId): Promise<Json | null>;
852
+ settleStep(runId: RunId, _stepId: StepId, fact: StepCompletedFact | StepFailedFact): Promise<void>;
853
+ settleSignal(args: {
854
+ readonly runId: RunId;
855
+ readonly stepId: StepId;
856
+ readonly at: Date;
857
+ readonly incoming?: {
858
+ readonly payload: Json;
859
+ readonly signalName?: string;
860
+ };
861
+ }): Promise<SettleSignalResult>;
673
862
  recordOnce(runId: RunId, stepId: StepId, scope: string, value: Json): Promise<void>;
674
863
  getOnce(runId: RunId, stepId: StepId, scope: string): Promise<Json | null>;
675
- runStep<T extends Json>(runId: RunId, stepId: StepId, _attempt: AttemptNumber, body: (tx: Tx) => Promise<{
864
+ runStep<T extends Json>(runId: RunId, _stepId: StepId, _attempt: AttemptNumber, body: (tx: Tx) => Promise<{
676
865
  readonly output: T;
677
866
  readonly fact: StepCompletedFact | StepFailedFact | StepCanceledFact;
678
867
  }>): Promise<T>;
@@ -691,8 +880,12 @@ declare class InMemoryStore implements Store {
691
880
  readGlobalFacts(): ReadonlyArray<GlobalFact>;
692
881
  queryRuns(opts: QueryRunsOpts): Promise<QueryRunsResult>;
693
882
  pruneFacts(opts: Required<PruneOpts>): Promise<PruneResult>;
883
+ subscribeStream(runId: RunId, stepId: StepId, opts?: {
884
+ readonly replayBuffered?: boolean;
885
+ }): AsyncIterable<StreamEvent<Json>>;
886
+ publishChunk(runId: RunId, stepId: StepId, chunk: Json): void;
694
887
  }
695
- declare function projectRunState(runId: RunId, facts: readonly Fact[]): RunState;
888
+
696
889
  interface InMemoryQueueOpts {
697
890
  readonly leaseMs?: Millis;
698
891
  }
@@ -730,13 +923,16 @@ declare class InMemoryTrigger implements Trigger {
730
923
  interface NagiConfig {
731
924
  readonly flows: ReadonlyArray<Flow>;
732
925
  readonly store: Store;
926
+ readonly streamTransport?: StreamTransport;
733
927
  readonly queue: Queue;
734
928
  readonly clock?: Clock;
735
929
  readonly trigger?: Trigger;
736
930
  readonly hooks?: FlowHooks;
737
- readonly logger?: Logger;
931
+ readonly onLog?: (entry: LogEntry) => void;
738
932
  readonly defaultRetry?: RetryPolicy;
739
933
  readonly codeVersion?: string;
934
+ readonly heartbeatIntervalMs?: Millis;
935
+ readonly heartbeatLeaseMs?: Millis;
740
936
  }
741
937
  interface StartOpts {
742
938
  readonly runId?: RunId;
@@ -746,72 +942,25 @@ interface CancelOpts {
746
942
  }
747
943
  interface Wf<TFlows extends ReadonlyArray<Flow> = ReadonlyArray<Flow>> {
748
944
  start<F extends TFlows[number]>(flow: F, input: FlowInput<F>, opts?: StartOpts): Promise<RunId>;
749
- /**
750
- * Start a flow by id with a runtime-typed input. Intended for callers
751
- * holding a serialized payload (transactional-outbox reconcilers, queue
752
- * consumers replaying DLQs, admin CLIs replaying a runId): the input
753
- * is validated against the registered flow's schema before the run is
754
- * created, mirroring `start`'s runtime contract without requiring a
755
- * compile-time-typed input.
756
- *
757
- * Throws `NagiRuntimeError` when `flowId` is not registered with
758
- * `nagi()`, and `NagiValidationError` when the input fails the flow's
759
- * schema or when `opts.runId` is invalid.
760
- */
761
945
  startById(flowId: string, input: unknown, opts?: StartOpts): Promise<RunId>;
762
946
  signal(runId: RunId, stepName: string, payload: unknown): Promise<void>;
763
947
  cancel(runId: RunId, opts?: CancelOpts): Promise<void>;
764
948
  worker(config?: WorkerConfig): Worker;
765
949
  replay(runId: RunId, opts?: ReplayOpts): Promise<void>;
766
950
  queryRuns(opts?: QueryRunsOpts<FlowIdOf<TFlows>>): Promise<QueryRunsResult<FlowIdOf<TFlows>>>;
951
+ subscribe<C = Json>(runId: RunId, stepId: StepId, opts?: {
952
+ readonly replayBuffered?: boolean;
953
+ }): AsyncIterable<StreamEvent<C>>;
767
954
  operator(): Operator;
768
955
  pruneFacts(opts: PruneOpts): Promise<PruneResult>;
769
956
  }
770
- declare class NagiValidationError extends Error {
771
- readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
772
- constructor(issues: ReadonlyArray<StandardSchemaV1.Issue>);
773
- }
774
- declare class NagiRuntimeError extends Error {
775
- constructor(message: string);
776
- }
777
- declare class NagiCanceledError extends Error {
778
- readonly runId: RunId;
779
- readonly canceledByRunId: RunId;
780
- readonly concurrencyKey: string;
781
- constructor(args: {
782
- readonly runId: RunId;
783
- readonly canceledByRunId: RunId;
784
- readonly concurrencyKey: string;
785
- });
786
- }
787
- declare class NagiSnapshotDriftError extends Error {
788
- readonly runId: RunId;
789
- readonly expected: string;
790
- readonly actual: string;
791
- constructor(args: {
792
- readonly runId: RunId;
793
- readonly expected: string;
794
- readonly actual: string;
795
- });
796
- }
797
957
  declare function nagiImpl<const TFlows extends ReadonlyArray<Flow>>(config: NagiConfig & {
798
958
  flows: TFlows;
799
959
  }): Promise<Wf<TFlows>>;
800
- /**
801
- * Config for {@link nagi.run}: a `NagiConfig` plus optional worker tuning and an
802
- * external shutdown signal. The signal is merged with an internal controller, so
803
- * aborting either source drains the worker.
804
- */
805
960
  interface NagiRunConfig extends NagiConfig {
806
961
  readonly worker?: Omit<WorkerConfig, "signal">;
807
962
  readonly signal?: AbortSignal;
808
963
  }
809
- /**
810
- * Handle returned by {@link nagi.run}. `stop()` aborts the internal controller,
811
- * awaits the worker loop, and is idempotent (safe to call twice or concurrently).
812
- * It resolves cleanly even if the loop crashed — a true crash is logged once via
813
- * the configured `logger`.
814
- */
815
964
  interface RuntimeHandle<TFlows extends ReadonlyArray<Flow> = ReadonlyArray<Flow>> {
816
965
  readonly wf: Wf<TFlows>;
817
966
  stop(): Promise<void>;
@@ -819,12 +968,32 @@ interface RuntimeHandle<TFlows extends ReadonlyArray<Flow> = ReadonlyArray<Flow>
819
968
  declare function nagiRun<const TFlows extends ReadonlyArray<Flow>>(config: NagiRunConfig & {
820
969
  flows: TFlows;
821
970
  }): Promise<RuntimeHandle<TFlows>>;
822
- /**
823
- * The nagi runtime factory. Call `nagi(config)` for fine-grained control, or
824
- * `nagi.run(config)` for a turnkey worker lifecycle returning `{ wf, stop }`.
825
- */
826
971
  declare const nagi: typeof nagiImpl & {
827
972
  run: typeof nagiRun;
828
973
  };
829
974
 
830
- export { type AttemptNumber, type BackoffStrategy, type Builder, type CanonicalDag, type CanonicalMatchArm, type CanonicalRetryPolicy, type CanonicalSchema, type CanonicalStep, type ClaimToken, type Clock, type ConcurrencyMode, type Fact, type FactKind, type Flow, type FlowCanceledByConcurrencyFact, type FlowCanceledByOperatorFact, type FlowCanceledExplicitlyFact, type FlowCanceledFact, type FlowCompleteEvent, type FlowCompletedFact, type FlowConcurrency, type FlowConfig, type FlowErrorEvent, type FlowEvent, type FlowFailedFact, type FlowHooks, type FlowIdOf, type FlowInput, type FlowOutput, type FlowRefUpdatedFact, type FlowStartEvent, type FlowStartedFact, type GlobalFact, InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, type InferSchemaInput, type InferSchemaOutput, type Json, type Logger, type MatchArm, type MatchArmGuard, type MatchArmOtherwise, type MatchArmOutput, type MatchArmSelectedFact, type MatchArmShape, type MatchGuardConfig, type Millis, NagiCanceledError, type NagiConfig, type NagiRunConfig, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, type NeedsMap, type NeedsOutputs, type OnceRecordedFact, type Operator, type OperatorAuditOpts, type OperatorSkipOpts, type ParentLink, type ParentRef, type PrunableStatus, type PruneOpts, type PruneResult, type QueryRunsOpts, type QueryRunsResult, type QueryRunsWhere, type Queue, type QueueDequeueOpts, type QueueEnqueueOpts, type QueueMessage, type Register, type ReplayMode, type ReplayOpts, type ResolvedConcurrency, type RetryPolicy, type RunId, type RunState, type RunStatus, type RunSummary, type RuntimeHandle, type SerializedError, type SignalConfig, type SignalReceivedEvent, type SignalReceivedFact, type SignalSentEvent, type SignalSentFact, type SnapshotChangedEdge, type SnapshotChangedField, type SnapshotDiff, StandardSchemaV1, type StartOpts, type Step, type StepAbortRequestedFact, type StepCanceledFact, type StepCompleteEvent, type StepCompletedFact, type StepCtx, type StepErrorEvent, type StepEvent, type StepFailedFact, type StepId, type StepKind, type StepMap, type StepOutput, type StepResetFact, type StepRetriedFact, type StepRetryEvent, type StepSkippedFact, type StepStartEvent, type StepStartedFact, type StepState, type StepStatus, type Store, type StringKeyOf, type SubflowConfig, type SubflowStepOutput, type TaskConfig, type Trigger, type Tx, type Wf, type Worker, type WorkerConfig, type WorkerRunOnceOpts, type WorkerRunResult, type WorkerRunUntilEmptyOpts, canonicalize, diffSnapshots, fingerprintFlows, flow, nagi, projectRunState, sha256Canonical };
975
+ type SignalDecision = {
976
+ readonly kind: "noop";
977
+ readonly result: SettleSignalResult;
978
+ } | {
979
+ readonly kind: "buffer";
980
+ readonly fact: SignalBufferedFact | null;
981
+ readonly result: SettleSignalResult;
982
+ } | {
983
+ readonly kind: "deliver";
984
+ readonly attempt: AttemptNumber;
985
+ readonly received: SignalReceivedFact;
986
+ readonly completed: StepCompletedFact;
987
+ readonly result: SettleSignalResult;
988
+ };
989
+ declare function decideSignal(args: {
990
+ readonly runState: RunState;
991
+ readonly stepId: StepId;
992
+ readonly at: Date;
993
+ readonly incoming?: {
994
+ readonly payload: Json;
995
+ readonly signalName?: string;
996
+ } | undefined;
997
+ }): SignalDecision;
998
+
999
+ export { type Anomaly, type AttemptNumber, type BackoffStrategy, type Builder, type CancelArgs, type CanonicalDag, type CanonicalMatchArm, type CanonicalRetryPolicy, type CanonicalSchema, type CanonicalStep, type ClaimToken, type Clock, type ConcurrencyMode, type Fact, type FactKind, type Flow, type FlowCanceledByConcurrencyFact, type FlowCanceledByOperatorFact, type FlowCanceledExplicitlyFact, type FlowCanceledFact, type FlowCompleteEvent, type FlowCompletedFact, type FlowConcurrency, type FlowConfig, type FlowErrorEvent, type FlowEvent, type FlowFailedFact, type FlowHooks, type FlowIdOf, type FlowInput, type FlowOutput, type FlowRefUpdatedFact, type FlowStartEvent, type FlowStartedFact, type GlobalFact, InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, type InferSchemaInput, type InferSchemaOutput, type Json, type LogEntry, type LogLevel, type Logger, type MatchArm, type MatchArmGuard, type MatchArmOtherwise, type MatchArmOutput, type MatchArmSelectedFact, type MatchArmShape, type MatchGuardConfig, type Millis, NagiCanceledError, type NagiConfig, type NagiRunConfig, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, type NeedRef, type NeedsMap, type NeedsOutputs, type OnceRecordedFact, type Operator, type OperatorAuditOpts, type Optional, type ParentLink, type ParentRef, type PrunableStatus, type PruneOpts, type PruneResult, type QueryRunsOpts, type QueryRunsResult, type QueryRunsWhere, type Queue, type QueueDequeueOpts, type QueueEnqueueOpts, type QueueMessage, type Register, type ReplayMode, type ReplayOpts, type Resolved, type ResolvedConcurrency, type ResolvedNeeds, type RetryPolicy, type RunCancelCause, type RunId, type RunPhase, type RunState, type RunStatus, type RunSummary, type RuntimeHandle, type SerializedError, type SettleSignalResult, type SignalBufferedFact, type SignalConfig, type SignalDecision, type SignalReceivedEvent, type SignalReceivedFact, type SignalSentEvent, type SignalSentFact, type SkipReason, type SnapshotChangedEdge, type SnapshotChangedField, type SnapshotDiff, StandardSchemaV1, type StartOpts, type Step, type StepAbortRequestedFact, type StepCancelCause, type StepCanceledFact, type StepCompleteEvent, type StepCompletedFact, type StepCtx, type StepErrorEvent, type StepEvent, type StepFailedFact, type StepId, type StepKind, type StepMap, type StepOutput, type StepResetFact, type StepRetriedFact, type StepRetryEvent, type StepSkippedFact, type StepStartEvent, type StepStartedFact, type StepState, type StepStatus, type Store, type StreamEvent, type StreamTransport, type StreamingStepCtx, type StreamingTaskConfig, type StringKeyOf, type SubflowConfig, type SubflowStepOutput, type TaskConfig, type Trigger, type Tx, type Wf, type Worker, type WorkerConfig, type WorkerRunOnceOpts, type WorkerRunResult, type WorkerRunUntilEmptyOpts, attemptOf, canonicalize, decideSignal, diffSnapshots, errorOf, fingerprintFlows, flow, isStepTerminal, isTerminalRun, nagi, optional, outputOf, foldRun as projectRunState, resolvedOf, runStatusOf, sha256Canonical, stepStateOf, stepStatusOf, unwrap };