@nagi-js/core 0.1.1-rc.1 → 0.1.1-rc.12

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";
157
+ type StepKind = "task" | "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;
@@ -71,19 +194,25 @@ interface StepCtx<Input = unknown> {
71
194
  readonly signal: AbortSignal;
72
195
  readonly now: () => Date;
73
196
  readonly logger: Logger;
74
- /**
75
- * Durable per-effect memoization. The first successful call for `(runId, stepId, scope)`
76
- * persists its return value; subsequent calls (including post-crash retries) return the
77
- * cached value without re-invoking `fn`.
78
- */
79
197
  once<T extends Json>(scope: string, fn: () => Promise<T>): Promise<T>;
80
- /**
81
- * Stable idempotency key for external APIs (Stripe, Mux, etc.).
82
- * Returns `hash(runId + stepId + scope)` — identical across retries of the same attempt,
83
- * different across runs.
84
- */
85
198
  idempotencyKey(scope: string): string;
86
199
  }
200
+ type StreamEvent<C = Json> = {
201
+ readonly kind: "chunk";
202
+ readonly chunk: C;
203
+ } | {
204
+ readonly kind: "dropped";
205
+ readonly count: number;
206
+ } | {
207
+ readonly kind: "retry";
208
+ readonly attempt: AttemptNumber;
209
+ } | {
210
+ readonly kind: "error";
211
+ readonly error: SerializedError;
212
+ };
213
+ interface StreamingStepCtx<Input = unknown, Chunk = Json> extends StepCtx<Input> {
214
+ readonly emit: (chunk: Chunk) => Promise<void>;
215
+ }
87
216
  type BackoffStrategy = "exponential" | "linear" | "fixed";
88
217
  interface RetryPolicy {
89
218
  readonly maxAttempts: number;
@@ -94,33 +223,13 @@ interface RetryPolicy {
94
223
  }
95
224
  interface StepConfigBase<Input, N extends NeedsMap> {
96
225
  readonly needs?: N;
97
- /**
98
- * Skip this step when the predicate returns false. Locked semantic:
99
- * downstream steps that need a skipped step are also skipped (transitive).
100
- * Therefore at the type level, `needs.x` is the unconditional `Output` —
101
- * not `Output | undefined`.
102
- */
103
226
  readonly when?: (args: {
104
227
  readonly input: NoInfer<Input>;
105
- readonly needs: NoInfer<NeedsOutputs<N>>;
228
+ readonly needs: NoInfer<ResolvedNeeds<N>>;
106
229
  }) => boolean;
107
230
  readonly timeoutMs?: Millis;
108
231
  }
109
- interface TaskConfig<Input, N extends NeedsMap, Output> extends StepConfigBase<Input, N> {
110
- readonly retry?: RetryPolicy;
111
- readonly run: (args: {
112
- readonly input: NoInfer<Input>;
113
- readonly needs: NoInfer<NeedsOutputs<N>>;
114
- readonly ctx: StepCtx<NoInfer<Input>>;
115
- }) => Promise<Output>;
116
- /**
117
- * Lifecycle hooks colocated with this step. Fire *before* the cross-cutting
118
- * `FlowHooks` callbacks (deterministic ordering). A throwing hook is logged
119
- * via the runtime's `Logger` and swallowed — hooks cannot fail the run.
120
- *
121
- * `onComplete`'s event is typed against this step's `Output` — no `Json`
122
- * narrowing required at the call site.
123
- */
232
+ interface StepLifecycleHooks<Output> {
124
233
  readonly onStart?: (event: StepStartEvent) => void | Promise<void>;
125
234
  readonly onComplete?: (event: StepCompleteEvent & {
126
235
  readonly output: NoInfer<Output>;
@@ -128,203 +237,97 @@ interface TaskConfig<Input, N extends NeedsMap, Output> extends StepConfigBase<I
128
237
  readonly onError?: (event: StepErrorEvent) => void | Promise<void>;
129
238
  readonly onRetry?: (event: StepRetryEvent) => void | Promise<void>;
130
239
  }
131
- interface SignalConfig<Input, N extends NeedsMap, Schema extends StandardSchemaV1> extends StepConfigBase<Input, N> {
132
- readonly schema: Schema;
240
+ interface TaskConfig<Input, N extends NeedsMap, Output> extends StepConfigBase<Input, N>, StepLifecycleHooks<Output> {
241
+ readonly retry?: RetryPolicy;
242
+ readonly run: (args: {
243
+ readonly input: NoInfer<Input>;
244
+ readonly needs: NoInfer<ResolvedNeeds<N>>;
245
+ readonly ctx: StepCtx<NoInfer<Input>>;
246
+ }) => Promise<Output>;
133
247
  }
134
- /**
135
- * Discriminator mode — exhaustive at compile time. `cases` must cover every
136
- * value in the discriminant union; adding a new value to the discriminant
137
- * is a type error until the case is handled.
138
- */
139
- interface MatchDiscriminatorConfig<Input, N extends NeedsMap, D extends string, M extends Record<D, StepMap>> {
140
- readonly needs?: N;
141
- readonly on: (args: {
248
+ interface StreamingTaskConfig<Input, N extends NeedsMap, Output, Chunk> extends StepConfigBase<Input, N>, StepLifecycleHooks<Output> {
249
+ readonly retry?: RetryPolicy;
250
+ readonly run: (args: {
142
251
  readonly input: NoInfer<Input>;
143
- readonly needs: NoInfer<NeedsOutputs<N>>;
144
- }) => D;
145
- readonly cases: {
146
- readonly [K in D]: (b: Builder<Input>) => BuildResult<Input, M[K]>;
147
- };
252
+ readonly needs: NoInfer<ResolvedNeeds<N>>;
253
+ readonly ctx: StreamingStepCtx<NoInfer<Input>, Chunk>;
254
+ }) => Promise<Output>;
255
+ }
256
+ interface SignalConfig<Input, N extends NeedsMap, Schema extends StandardSchemaV1> extends StepConfigBase<Input, N> {
257
+ readonly schema: Schema;
258
+ readonly names?: readonly [string, ...string[]];
148
259
  }
149
260
  interface MatchArmGuard<Input, N extends NeedsMap, M extends StepMap> {
150
261
  readonly when: (args: {
151
262
  readonly input: NoInfer<Input>;
152
- readonly needs: NoInfer<NeedsOutputs<N>>;
263
+ readonly needs: NoInfer<ResolvedNeeds<N>>;
153
264
  }) => boolean;
154
265
  readonly otherwise?: never;
155
- readonly build: (b: Builder<Input>) => BuildResult<Input, M>;
266
+ readonly build: (b: Builder<Input>) => M;
156
267
  }
157
268
  interface MatchArmOtherwise<Input, M extends StepMap> {
158
269
  readonly otherwise: true;
159
270
  readonly when?: never;
160
- readonly build: (b: Builder<Input>) => BuildResult<Input, M>;
271
+ readonly build: (b: Builder<Input>) => M;
161
272
  }
162
273
  type MatchArm<Input, N extends NeedsMap, M extends StepMap> = MatchArmGuard<Input, N, M> | MatchArmOtherwise<Input, M>;
163
- /**
164
- * Inference-friendly arm shape: M is not bound, so each arm in an `arms:` tuple
165
- * keeps its own StepMap (and per-step Output) through inference. The `arms`
166
- * overload of `Builder.match` uses this; user-facing arms still satisfy
167
- * `MatchArm<Input, N, M>` for any concrete M they construct.
168
- */
169
274
  type MatchArmShape<Input, N extends NeedsMap> = {
170
275
  readonly when: (args: {
171
276
  readonly input: NoInfer<Input>;
172
- readonly needs: NoInfer<NeedsOutputs<N>>;
277
+ readonly needs: NoInfer<ResolvedNeeds<N>>;
173
278
  }) => boolean;
174
279
  readonly otherwise?: never;
175
- readonly build: (b: Builder<Input>) => BuildResult<Input, StepMap>;
280
+ readonly build: (b: Builder<Input>) => StepMap;
176
281
  } | {
177
282
  readonly otherwise: true;
178
283
  readonly when?: never;
179
- readonly build: (b: Builder<Input>) => BuildResult<Input, StepMap>;
284
+ readonly build: (b: Builder<Input>) => StepMap;
180
285
  };
181
- /**
182
- * Guard mode — Rust-style `match { x if guard => ... }`. Top-to-bottom,
183
- * first match wins. The terminal `{ otherwise: true }` arm is required so
184
- * guard mode can never silently fall through.
185
- */
186
286
  interface MatchGuardConfig<Input, N extends NeedsMap, M extends StepMap> {
187
287
  readonly needs?: N;
188
288
  readonly arms: ReadonlyArray<MatchArm<Input, N, M>>;
189
289
  }
190
- /** The output of a match step is a record of each step in the chosen arm. */
191
290
  type MatchArmOutput<M extends StepMap> = {
192
291
  readonly [K in keyof M]: StepOutput<M[K]>;
193
292
  };
194
- /** Across all cases of a discriminator match — the union of arm outputs. */
195
- type MatchDiscriminatorOutput<D extends string, M extends Record<D, StepMap>> = {
196
- [K in D]: MatchArmOutput<M[K]>;
197
- }[D];
198
- /**
199
- * Per-entry config for `b.step(key, config)`. `Needs` is a const tuple of
200
- * sibling keys that resolve against the chain's accumulator `A`.
201
- */
202
- interface StepEntryConfig<Input, A extends Record<string, unknown>, Needs extends ReadonlyArray<keyof A & string>, Output> {
203
- readonly needs?: Needs;
204
- readonly retry?: RetryPolicy;
205
- readonly timeoutMs?: Millis;
206
- readonly when?: (args: {
207
- readonly input: NoInfer<Input>;
208
- readonly needs: {
209
- readonly [P in Needs[number]]: A[P];
210
- };
211
- }) => boolean;
212
- readonly run: (args: {
293
+ interface SubflowConfig<Input, N extends NeedsMap, Child extends Flow> extends StepConfigBase<Input, N> {
294
+ readonly input: (args: {
213
295
  readonly input: NoInfer<Input>;
214
- readonly needs: {
215
- readonly [P in Needs[number]]: A[P];
216
- };
217
- readonly ctx: StepCtx<NoInfer<Input>>;
218
- }) => Promise<Output>;
219
- /** See {@link TaskConfig} for hook semantics. */
220
- readonly onStart?: (event: StepStartEvent) => void | Promise<void>;
221
- readonly onComplete?: (event: StepCompleteEvent & {
222
- readonly output: NoInfer<Output>;
223
- }) => void | Promise<void>;
224
- readonly onError?: (event: StepErrorEvent) => void | Promise<void>;
225
- readonly onRetry?: (event: StepRetryEvent) => void | Promise<void>;
296
+ readonly needs: NoInfer<ResolvedNeeds<N>>;
297
+ }) => FlowInput<Child>;
298
+ }
299
+ interface SubflowStepOutput<ChildOutput> {
300
+ readonly childRunId: RunId;
301
+ readonly output: ChildOutput;
226
302
  }
227
- /**
228
- * `b` inside `flow({ build: (b) => ... })`.
229
- *
230
- * Two complementary authoring styles:
231
- *
232
- * 1. **Standalone constructors** — `b.task`, `b.signal`, `b.match` each
233
- * return a `Step<Output>` value the user can assign and reference. The
234
- * build callback returns a `StepMap` of those values.
235
- *
236
- * 2. **Chain (key-first)** — `b.step(key, config)` is keyed and chainable.
237
- * Each call extends the builder's accumulator `A` with `{ [Key]: Output }`,
238
- * and subsequent `.step()` calls type `needs: ["sibling"]` against `A`.
239
- * `b.include(key, prebuiltStep)` brings a `Step<O>` (from `b.task` /
240
- * `b.signal` / `b.match`) into the chain under a key. The chain itself
241
- * is returned from the build callback; `flow()` extracts the accumulator.
242
- *
243
- * Both styles compose in the same build callback — the chain end is the
244
- * canonical result; pre-built standalone steps enter the chain via
245
- * `.include(key, step)`.
246
- */
247
- interface Builder<Input = unknown, A extends Record<string, unknown> = Record<never, never>> {
303
+ interface Builder<Input = unknown> {
248
304
  task<N extends NeedsMap, Output>(config: TaskConfig<Input, N, Output>): Step<Output>;
305
+ streamingTask<N extends NeedsMap, O, C = Json>(config: StreamingTaskConfig<Input, N, O, C>): Step<O>;
249
306
  signal<N extends NeedsMap, S extends StandardSchemaV1>(config: SignalConfig<Input, N, S>): Step<InferSchemaOutput<S>>;
250
- match<N extends NeedsMap, D extends string, Cases extends {
251
- readonly [K in D]: (b: Builder<Input>) => BuildResult<Input, StepMap>;
252
- }>(config: {
253
- readonly needs?: N;
254
- readonly on: (args: {
255
- readonly input: NoInfer<Input>;
256
- readonly needs: NoInfer<NeedsOutputs<N>>;
257
- }) => D;
258
- readonly cases: Cases;
259
- }): Step<{
260
- readonly [K in keyof Cases]: MatchArmOutput<AsStepMap<ReturnType<Cases[K]>>>;
261
- }[keyof Cases]>;
307
+ subflow<N extends NeedsMap, Child extends Flow>(child: Child, config: SubflowConfig<Input, N, Child>): Step<SubflowStepOutput<FlowOutput<Child>>>;
262
308
  match<N extends NeedsMap, Arms extends ReadonlyArray<MatchArmShape<Input, N>>>(config: {
263
309
  readonly needs?: N;
264
310
  readonly arms: Arms;
265
- }): Step<MatchArmOutput<AsStepMap<ReturnType<Arms[number]["build"]>>>>;
266
- /**
267
- * Chainable task definition. The first arg is the persisted step id; the
268
- * config follows the standalone `task` shape plus a `needs: ["sibling"]`
269
- * tuple of accumulator keys. Returns the same builder typed with the new
270
- * entry appended to `A`.
271
- *
272
- * b.step('fetchRecording', { run: async () => ({ url: '…' }) })
273
- * .step('transcribe', {
274
- * needs: ['fetchRecording'],
275
- * run: async ({ needs }) => ({ text: needs.fetchRecording.url + '…' }),
276
- * })
277
- */
278
- step<const Key extends string, const Needs extends ReadonlyArray<keyof A & string>, Output>(key: Exclude<Key, keyof A>, config: StepEntryConfig<Input, A, Needs, Output>): Builder<Input, A & {
279
- readonly [K in Key]: Output;
280
- }>;
281
- /**
282
- * Include a pre-built `Step<O>` (from `b.task` / `b.signal` / `b.match`)
283
- * into the chain under a key. The included step's output joins `A`.
284
- */
285
- include<const Key extends string, S extends Step<unknown>>(key: Exclude<Key, keyof A>, step: S): Builder<Input, A & {
286
- readonly [K in Key]: S extends Step<infer O> ? O : never;
287
- }>;
288
- }
289
- /**
290
- * Acceptable shape for a build callback's return. Either a plain `StepMap`
291
- * (record-literal style) or a `Builder<Input, A>` whose accumulator is
292
- * extracted by `flow()`.
293
- */
294
- type BuildResult<Input, M extends StepMap> = M | Builder<Input, BuilderAccumulator<M>>;
295
- /** Convert a `StepMap` back to its accumulator shape `{ [K]: Output }`. */
296
- type BuilderAccumulator<M extends StepMap> = {
297
- readonly [K in keyof M]: M[K] extends Step<infer O> ? O : never;
311
+ }): Step<MatchArmOutput<ReturnType<Arms[number]["build"]>>>;
312
+ }
313
+ type ConcurrencyMode = "cancel-in-progress";
314
+ type StringKeyOf<Input> = {
315
+ [K in keyof Input]-?: Input[K] extends string ? K : never;
316
+ }[keyof Input];
317
+ type FlowConcurrency<Input = Json> = StringKeyOf<Input> | {
318
+ readonly keyFn: (input: Input) => string;
319
+ readonly mode?: ConcurrencyMode;
298
320
  };
299
- /** Extract a `StepMap` from either a plain map or a `Builder` chain result. */
300
- type AsStepMap<R> = R extends Builder<unknown, infer A> ? {
301
- readonly [K in keyof A]: Step<A[K]>;
302
- } : R extends StepMap ? R : never;
303
- interface FlowConfig<Id extends string, InputSchema extends StandardSchemaV1, R, Output = unknown> {
304
- /** Stable persistence handle. TanStack-key shaped (kebab or snake). */
321
+ interface ResolvedConcurrency {
322
+ readonly keyFn: (input: Json) => string;
323
+ readonly mode: ConcurrencyMode;
324
+ }
325
+ interface FlowConfig<Id extends string, InputSchema extends StandardSchemaV1, R extends StepMap, Output = unknown> {
305
326
  readonly id: Id;
306
327
  readonly input: InputSchema;
307
- /**
308
- * Returns either a `StepMap` (record-literal style with `b.task` / `b.signal`
309
- * / `b.match`) or a chained `Builder<Input, A>` (Express-style with `b.step`
310
- * / `b.include`). `flow()` extracts the assembled `StepMap` either way.
311
- */
312
328
  readonly build: (b: Builder<InferSchemaOutput<InputSchema>>) => R;
313
- /**
314
- * Compute the flow's terminal output from its step outputs. Fired once at
315
- * `flow.completed` and persisted on the fact + `onFlowComplete` event.
316
- * Skipped steps land as `null` in the input record at runtime even though
317
- * the type claims otherwise (consistent with the "skip is transitive" lock).
318
- */
319
- output?(steps: NeedsOutputs<AsStepMap<R>>): Output;
320
- /**
321
- * Flow-level lifecycle hooks. Like step-local hooks (see {@link TaskConfig}),
322
- * these fire *before* the cross-cutting `FlowHooks` callbacks, and a thrown
323
- * hook is swallowed + logged rather than failing the run.
324
- *
325
- * `onComplete`'s event is typed against this flow's `Output` (whatever the
326
- * `output()` resolver returns).
327
- */
329
+ output?(steps: NeedsOutputs<R>): Output;
330
+ readonly concurrency?: FlowConcurrency<InferSchemaOutput<InputSchema>>;
328
331
  readonly onStart?: (event: FlowStartEvent) => void | Promise<void>;
329
332
  readonly onComplete?: (event: FlowCompleteEvent & {
330
333
  readonly output: NoInfer<Output>;
@@ -336,20 +339,21 @@ interface Flow<Id extends string = string, InputSchema extends StandardSchemaV1
336
339
  readonly input: InputSchema;
337
340
  readonly steps: M;
338
341
  output?(steps: NeedsOutputs<M>): Output;
339
- /**
340
- * Forwarded from {@link FlowConfig}; surfaced for the dispatcher.
341
- *
342
- * Note these use the plain (non-Output-augmented) event types — the typed
343
- * narrowing lives on {@link FlowConfig}'s callbacks at build time, while
344
- * the runtime form is variance-friendly so a concrete `Flow<...{x: number}>`
345
- * stays assignable to `Flow<...unknown>` (the dispatcher's view).
346
- */
347
342
  readonly onStart?: (event: FlowStartEvent) => void | Promise<void>;
348
343
  readonly onComplete?: (event: FlowCompleteEvent) => void | Promise<void>;
349
344
  readonly onError?: (event: FlowErrorEvent) => void | Promise<void>;
345
+ readonly concurrency?: ResolvedConcurrency;
350
346
  }
351
347
  type FlowInput<F> = F extends Flow<string, infer S, StepMap, unknown> ? InferSchemaOutput<S> : never;
352
348
  type FlowOutput<F> = F extends Flow<string, StandardSchemaV1, StepMap, infer O> ? O : never;
349
+ type FlowIdOf<T extends ReadonlyArray<Flow>> = T[number] extends Flow<infer Id> ? Id : never;
350
+ interface ParentLink {
351
+ readonly runId: RunId;
352
+ readonly stepId: StepId;
353
+ }
354
+ interface ParentRef extends ParentLink {
355
+ readonly attempt: AttemptNumber;
356
+ }
353
357
  interface FlowEvent {
354
358
  readonly runId: RunId;
355
359
  readonly flowId: string;
@@ -357,6 +361,7 @@ interface FlowEvent {
357
361
  }
358
362
  interface FlowStartEvent extends FlowEvent {
359
363
  readonly input: Json;
364
+ readonly parent?: ParentRef;
360
365
  }
361
366
  interface FlowCompleteEvent extends FlowEvent {
362
367
  readonly output: Json;
@@ -370,18 +375,11 @@ interface StepEvent extends FlowEvent {
370
375
  readonly kind: StepKind;
371
376
  }
372
377
  interface StepStartEvent extends StepEvent {
373
- /**
374
- * The resolved input for this step at the moment it starts.
375
- * - Task: the value passed to `run({ input, needs, ctx })`.
376
- * - Signal: `null` (signals await an external payload — no pre-execution input).
377
- * - Match: `null` (the discriminator value is computed inside the match
378
- * handler; the start event fires before that resolves).
379
- */
380
378
  readonly input: Json;
381
379
  }
382
380
  interface StepCompleteEvent extends StepEvent {
383
381
  readonly output: Json;
384
- readonly durationMs: Millis;
382
+ readonly durationMs?: Millis;
385
383
  }
386
384
  interface StepErrorEvent extends StepEvent {
387
385
  readonly error: SerializedError;
@@ -410,25 +408,20 @@ interface FlowHooks {
410
408
  interface WorkerConfig {
411
409
  readonly concurrency?: number;
412
410
  readonly pollIntervalMs?: Millis;
413
- /** AbortSignal drives graceful drain on SIGTERM/SIGINT. */
414
411
  readonly signal?: AbortSignal;
415
412
  }
416
413
  interface WorkerRunOnceOpts {
417
414
  readonly maxSteps?: number;
418
415
  }
419
416
  interface WorkerRunUntilEmptyOpts {
420
- /** Wall-clock deadline in `Date.now()` units. Edge runtimes have CPU/wall-time budgets. */
421
417
  readonly deadline?: number;
422
418
  }
423
419
  interface WorkerRunResult {
424
420
  readonly processed: number;
425
421
  }
426
422
  interface Worker {
427
- /** Long-running fleet (Cloud Run service, ECS, dedicated VM). Blocks until `signal` aborts. */
428
423
  run(): Promise<void>;
429
- /** HTTP server alongside requests. Returns after up to `maxSteps` are processed. */
430
424
  runOnce(opts?: WorkerRunOnceOpts): Promise<WorkerRunResult>;
431
- /** Serverless / edge. Drains everything available within the deadline and exits. */
432
425
  runUntilEmpty(opts?: WorkerRunUntilEmptyOpts): Promise<WorkerRunResult>;
433
426
  }
434
427
  type ClaimToken = string & {
@@ -440,116 +433,106 @@ interface SerializedError {
440
433
  readonly stack?: string;
441
434
  readonly cause?: Json;
442
435
  }
443
- /**
444
- * Fact-ordering invariant (must hold for every Store implementation):
445
- * facts persisted via `appendFact` / `completeStep` / `failStep` MUST be
446
- * visible to the next `loadRunState` call. The scheduler decides what to run
447
- * by projecting `RunState.steps` from the fact log, then calls `nextRunnable`
448
- * — if a `step.completed` write isn't reflected in a subsequent read, the
449
- * scheduler will re-enqueue or skip steps incorrectly. Adapters with read
450
- * replicas must route `loadRunState` to the primary or wait for replication
451
- * within a single `advance` cycle.
452
- */
436
+ type SettleSignalResult = {
437
+ readonly tag: "delivered";
438
+ readonly attempt: AttemptNumber;
439
+ readonly payload: Json;
440
+ readonly signalName?: string;
441
+ } | {
442
+ readonly tag: "buffered";
443
+ } | {
444
+ readonly tag: "noop";
445
+ };
453
446
  interface Store {
454
447
  appendFact(runId: RunId, fact: Fact): Promise<void>;
455
448
  loadRunState(runId: RunId): Promise<RunState>;
456
- /**
457
- * Atomically begin a run. Inserts the `flow.started` fact and any
458
- * materialized run row keyed by `runId` IFF no run with this `runId` already
459
- * exists. Returns `{ started: true }` if this call created the run,
460
- * `{ started: false }` if the run already exists.
461
- *
462
- * Two concurrent `tryStartRun(runId, ...)` calls with the same `runId` must
463
- * result in exactly one `flow.started` fact. Adapters enforce this at the
464
- * durability layer (e.g. Postgres `INSERT ... ON CONFLICT DO NOTHING` keyed
465
- * by `run_id`), NOT via app-level check-then-insert.
466
- *
467
- * The runtime calls this exactly once at `wf.start()`. Subsequent facts go
468
- * through `appendFact` as usual.
469
- */
470
- tryStartRun(runId: RunId, fact: FlowStartedFact): Promise<{
449
+ settleSignal(args: {
450
+ readonly runId: RunId;
451
+ readonly stepId: StepId;
452
+ readonly at: Date;
453
+ readonly incoming?: {
454
+ readonly payload: Json;
455
+ readonly signalName?: string;
456
+ };
457
+ }): Promise<SettleSignalResult>;
458
+ tryStartRun(runId: RunId, fact: FlowStartedFact, concurrency?: {
459
+ readonly key: string;
460
+ readonly mode: ConcurrencyMode;
461
+ }): Promise<{
471
462
  readonly started: boolean;
463
+ readonly canceled: ReadonlyArray<{
464
+ readonly runId: RunId;
465
+ readonly fact: FlowCanceledByConcurrencyFact;
466
+ }>;
472
467
  }>;
473
- /**
474
- * Returns null if the step is already claimed under a live lease. Lease
475
- * duration is owned by the Store implementation; configure it on the adapter.
476
- */
477
468
  claimStep(runId: RunId, stepId: StepId, attempt: AttemptNumber): Promise<ClaimToken | null>;
478
- completeStep(runId: RunId, stepId: StepId, output: Json, fact: Fact): Promise<void>;
479
- failStep(runId: RunId, stepId: StepId, error: SerializedError, fact: Fact): Promise<void>;
480
- /** Memoization read — returns the persisted output of a previously completed step. */
481
- getStepOutput(runId: RunId, stepId: StepId): Promise<Json | null>;
482
- /** `ctx.once` durable record. */
469
+ settleStep(runId: RunId, stepId: StepId, fact: StepCompletedFact | StepFailedFact): Promise<void>;
483
470
  recordOnce(runId: RunId, stepId: StepId, scope: string, value: Json): Promise<void>;
484
471
  getOnce(runId: RunId, stepId: StepId, scope: string): Promise<Json | null>;
485
- /**
486
- * Run a task step's handler inside an adapter-owned transaction.
487
- *
488
- * Implementations open a transaction (or equivalent atomic scope), invoke
489
- * `body(tx)`, and on a successful return persist the returned fact
490
- * atomically with any writes the handler made via `ctx.tx`. The output is
491
- * returned to the caller; for `step.failed` facts the output is ignored
492
- * (callers should still return the placeholder shape the type requires).
493
- *
494
- * Contract:
495
- * - If `body` throws, the transaction is rolled back and the error
496
- * propagates. The caller (dispatcher) is responsible for recording the
497
- * failure via `failStep` in a separate scope so the failure survives
498
- * even when domain writes do not.
499
- * - On a returned `step.completed` fact, the same atomic scope must also
500
- * record the step output (such that `getStepOutput` reflects it) and
501
- * release any worker lease held for `(runId, stepId, attempt)`.
502
- *
503
- * For adapters with no real transaction (in-memory, sqlite without WAL),
504
- * `tx` is passed as `undefined as Tx` and the write is non-atomic — those
505
- * adapters are not used with `ctx.tx` writes.
506
- */
507
472
  runStep<T extends Json>(runId: RunId, stepId: StepId, attempt: AttemptNumber, body: (tx: Tx) => Promise<{
508
473
  readonly output: T;
509
- readonly fact: StepCompletedFact | StepFailedFact;
474
+ readonly fact: StepCompletedFact | StepFailedFact | StepCanceledFact;
510
475
  }>): Promise<T>;
511
- /**
512
- * Deduped store of canonical flow DAGs, keyed by content hash. Inserts are
513
- * idempotent — the same `(flowHash, dag)` may be written by many concurrent
514
- * boots; only the first physical row survives. Subsequent writes are
515
- * no-ops.
516
- *
517
- * Adapters MUST enforce this at the durability layer (e.g. Postgres
518
- * `INSERT ... ON CONFLICT (flow_hash) DO NOTHING`).
519
- */
520
476
  upsertSnapshot(args: {
521
477
  readonly flowHash: string;
522
478
  readonly flowId: string;
523
479
  readonly dag: Json;
524
480
  }): Promise<void>;
525
- /**
526
- * Read the currently-published hash for a flow id. Returns `null` if no
527
- * `flow_ref` row exists yet — first boot of a never-published flow.
528
- */
529
481
  getRef(flowId: string): Promise<string | null>;
530
- /**
531
- * Atomically set the published hash for a flow id. Last writer wins; the
532
- * audit trail of ref changes lives in {@link appendGlobalFact} as
533
- * `flow_ref.updated`.
534
- *
535
- * Adapters MUST enforce atomicity at the durability layer (e.g. Postgres
536
- * `INSERT ... ON CONFLICT (flow_id) DO UPDATE`).
537
- */
538
482
  setRef(flowId: string, flowHash: string): Promise<void>;
539
- /**
540
- * Load a snapshot by its content hash. Returns `null` if no snapshot with
541
- * this hash has been recorded — e.g., the deployment is replaying a run
542
- * whose pinned topology was never seen by this store.
543
- */
544
483
  loadSnapshot(flowHash: string): Promise<{
545
484
  readonly flowId: string;
546
485
  readonly dag: Json;
547
486
  } | null>;
548
- /**
549
- * Append a non-run-scoped fact. See {@link GlobalFact} for the union.
550
- * Currently only `flow_ref.updated` events flow through this method.
551
- */
552
487
  appendGlobalFact(fact: GlobalFact): Promise<void>;
488
+ queryRuns(opts: QueryRunsOpts): Promise<QueryRunsResult>;
489
+ listChildren(parentRunId: RunId): Promise<ReadonlyArray<RunId>>;
490
+ pruneFacts(opts: Required<PruneOpts>): Promise<PruneResult>;
491
+ }
492
+ interface StreamTransport {
493
+ subscribeStream(runId: RunId, stepId: StepId, opts?: {
494
+ readonly replayBuffered?: boolean;
495
+ }): AsyncIterable<StreamEvent<Json>>;
496
+ publishChunk(runId: RunId, stepId: StepId, chunk: Json): void;
497
+ }
498
+ interface QueryRunsWhere<FlowId extends string = string> {
499
+ readonly flowId?: FlowId;
500
+ readonly status?: ReadonlyArray<RunStatus>;
501
+ readonly input?: Record<string, Json>;
502
+ }
503
+ type QueryRunsOpts<FlowId extends string = string> = {
504
+ readonly where?: QueryRunsWhere<FlowId>;
505
+ readonly latest: true;
506
+ readonly limit?: never;
507
+ readonly cursor?: never;
508
+ } | {
509
+ readonly where?: QueryRunsWhere<FlowId>;
510
+ readonly latest?: false;
511
+ readonly limit?: number;
512
+ readonly cursor?: string;
513
+ };
514
+ interface RunSummary<FlowId extends string = string> {
515
+ readonly runId: RunId;
516
+ readonly flowId: FlowId;
517
+ readonly status: RunStatus;
518
+ readonly startedAt: Date;
519
+ readonly completedAt: Date | null;
520
+ readonly input: Json;
521
+ }
522
+ interface QueryRunsResult<FlowId extends string = string> {
523
+ readonly runs: ReadonlyArray<RunSummary<FlowId>>;
524
+ readonly cursor: string | null;
525
+ }
526
+ type PrunableStatus = Extract<RunStatus, "completed" | "failed" | "canceled">;
527
+ interface PruneOpts {
528
+ readonly olderThan: Date;
529
+ readonly statuses?: ReadonlyArray<PrunableStatus>;
530
+ readonly batchSize?: number;
531
+ readonly keepSummary?: boolean;
532
+ }
533
+ interface PruneResult {
534
+ readonly runsPruned: number;
535
+ readonly factsPruned: number;
553
536
  }
554
537
  interface QueueMessage {
555
538
  readonly receipt: string;
@@ -562,11 +545,8 @@ interface QueueDequeueOpts {
562
545
  readonly count: number;
563
546
  }
564
547
  interface QueueEnqueueOpts {
565
- /** Attempt number to publish. Defaults to 1. The dispatcher controls increments. */
566
548
  readonly attempt?: AttemptNumber;
567
- /** Visibility delay — the message becomes dequeueable after `delayMs`. */
568
549
  readonly delayMs?: Millis;
569
- /** Adapter-specific extra data. Core never reads this. */
570
550
  readonly payload?: Json;
571
551
  }
572
552
  interface Queue {
@@ -577,24 +557,17 @@ interface Queue {
577
557
  delayMs?: Millis;
578
558
  }): Promise<void>;
579
559
  extend(receipt: string, leaseMs: Millis): Promise<void>;
560
+ ensureSchema?(): Promise<void>;
580
561
  }
581
562
  interface Clock {
582
563
  now(): Date;
583
- /** Resolves when `ms` has elapsed or `signal` aborts. */
584
564
  sleep(ms: Millis, signal?: AbortSignal): Promise<void>;
585
- /** Persistent timer — wakes the scheduler at `at` for `(runId, stepId)`. */
586
565
  schedule(at: Date, runId: RunId, stepId: StepId): Promise<void>;
587
566
  }
588
- /**
589
- * Wakes the scheduler when there's work to do. Default impl polls via the
590
- * Queue plugin; Postgres adapter offers a NOTIFY/LISTEN variant.
591
- * Per the sharding-safety lock: the handler receives a `runId` — there is no
592
- * global tick.
593
- */
594
567
  interface Trigger {
595
568
  subscribe(handler: (runId: RunId) => void): () => void;
596
569
  }
597
- type FactKind = "flow.started" | "flow.completed" | "flow.failed" | "step.started" | "step.completed" | "step.failed" | "step.retried" | "step.skipped" | "signal.sent" | "signal.received" | "once.recorded" | "match.arm-selected";
570
+ 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";
598
571
  interface FactBase {
599
572
  readonly runId: RunId;
600
573
  readonly at: Date;
@@ -603,34 +576,13 @@ interface FlowStartedFact extends FactBase {
603
576
  readonly kind: "flow.started";
604
577
  readonly flowId: string;
605
578
  readonly input: Json;
606
- /**
607
- * Content hash of the canonical flow DAG at the moment this run started.
608
- * Pins the run to a specific topology; `wf.replay()` reads this to detect
609
- * snapshot drift. Optional in v0 — legacy runs from before the snapshot
610
- * store landed have `undefined`. After a soak period it becomes required.
611
- */
612
579
  readonly flowHash?: string;
613
- /**
614
- * Free-form handler-code identifier, typically a git SHA. Sourced from
615
- * `nagi({ codeVersion })`. Captures handler-source drift orthogonally to
616
- * `flowHash` (which only captures topology). See RFC 0001
617
- * "Topology vs handler code."
618
- */
619
580
  readonly codeVersion?: string;
581
+ readonly parent?: ParentLink;
620
582
  }
621
- /**
622
- * A non-run-scoped event, recorded as a side effect of nagi runtime activity
623
- * that has no specific `runId`. Lives in the `nagi.global_fact` table.
624
- *
625
- * Per RFC 0001: when nagi boots and a flow's canonical hash differs from the
626
- * currently-published one, the runtime updates `flow_ref` and appends a
627
- * `flow_ref.updated` global fact. The audit trail of ref changes is queryable
628
- * independently of any single run.
629
- */
630
583
  interface FlowRefUpdatedFact {
631
584
  readonly kind: "flow_ref.updated";
632
585
  readonly flowId: string;
633
- /** Previous hash, or null when this is the first publish of `flowId`. */
634
586
  readonly from: string | null;
635
587
  readonly to: string;
636
588
  readonly at: Date;
@@ -644,10 +596,33 @@ interface FlowFailedFact extends FactBase {
644
596
  readonly kind: "flow.failed";
645
597
  readonly error: SerializedError;
646
598
  }
599
+ interface FlowCanceledByConcurrencyFact extends FactBase {
600
+ readonly kind: "flow.canceled";
601
+ readonly cause: "concurrency";
602
+ readonly canceledByRunId: RunId;
603
+ readonly concurrencyKey: string;
604
+ }
605
+ interface FlowCanceledExplicitlyFact extends FactBase {
606
+ readonly kind: "flow.canceled";
607
+ readonly cause: "explicit";
608
+ readonly reason: string;
609
+ readonly note?: string;
610
+ }
611
+ interface FlowCanceledByOperatorFact extends FactBase {
612
+ readonly kind: "flow.canceled";
613
+ readonly cause: "operator";
614
+ readonly actor: string;
615
+ readonly reason: string;
616
+ readonly note?: string;
617
+ }
618
+ type FlowCanceledFact = FlowCanceledByConcurrencyFact | FlowCanceledExplicitlyFact | FlowCanceledByOperatorFact;
619
+ type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
620
+ type CancelArgs = DistributiveOmit<FlowCanceledExplicitlyFact | FlowCanceledByOperatorFact, "kind" | "runId" | "at">;
647
621
  interface StepStartedFact extends FactBase {
648
622
  readonly kind: "step.started";
649
623
  readonly stepId: StepId;
650
624
  readonly attempt: AttemptNumber;
625
+ readonly stepKind: StepKind;
651
626
  }
652
627
  interface StepCompletedFact extends FactBase {
653
628
  readonly kind: "step.completed";
@@ -661,16 +636,25 @@ interface StepFailedFact extends FactBase {
661
636
  readonly attempt: AttemptNumber;
662
637
  readonly error: SerializedError;
663
638
  }
639
+ interface StepCanceledFact extends FactBase {
640
+ readonly kind: "step.canceled";
641
+ readonly stepId: StepId;
642
+ readonly attempt: AttemptNumber;
643
+ readonly error?: SerializedError;
644
+ }
664
645
  interface StepRetriedFact extends FactBase {
665
646
  readonly kind: "step.retried";
666
647
  readonly stepId: StepId;
667
648
  readonly attempt: AttemptNumber;
668
649
  readonly nextAttemptAt: Date;
650
+ readonly error: SerializedError;
669
651
  }
670
652
  interface StepSkippedFact extends FactBase {
671
653
  readonly kind: "step.skipped";
672
654
  readonly stepId: StepId;
673
- readonly reason: "when-false" | "transitive";
655
+ readonly reason: "when-false" | "transitive" | "manual";
656
+ readonly actor?: string;
657
+ readonly note?: string;
674
658
  }
675
659
  interface SignalSentFact extends FactBase {
676
660
  readonly kind: "signal.sent";
@@ -681,6 +665,13 @@ interface SignalReceivedFact extends FactBase {
681
665
  readonly kind: "signal.received";
682
666
  readonly stepId: StepId;
683
667
  readonly payload: Json;
668
+ readonly signalName?: string;
669
+ }
670
+ interface SignalBufferedFact extends FactBase {
671
+ readonly kind: "signal.buffered";
672
+ readonly stepId: StepId;
673
+ readonly payload: Json;
674
+ readonly signalName?: string;
684
675
  }
685
676
  interface OnceRecordedFact extends FactBase {
686
677
  readonly kind: "once.recorded";
@@ -693,84 +684,50 @@ interface MatchArmSelectedFact extends FactBase {
693
684
  readonly stepId: StepId;
694
685
  readonly arm: string;
695
686
  }
696
- type Fact = FlowStartedFact | FlowCompletedFact | FlowFailedFact | StepStartedFact | StepCompletedFact | StepFailedFact | StepRetriedFact | StepSkippedFact | SignalSentFact | SignalReceivedFact | OnceRecordedFact | MatchArmSelectedFact;
697
- type RunStatus = "pending" | "running" | "completed" | "failed";
698
- type StepStatus = "pending" | "running" | "completed" | "failed" | "skipped";
699
- interface StepState {
687
+ interface StepResetFact extends FactBase {
688
+ readonly kind: "step.reset";
700
689
  readonly stepId: StepId;
701
- readonly status: StepStatus;
702
- readonly attempts: AttemptNumber;
703
- readonly output?: Json;
704
- readonly error?: SerializedError;
690
+ readonly cascadedFrom?: StepId;
691
+ readonly actor?: string;
692
+ readonly note?: string;
705
693
  }
706
- interface RunState {
707
- readonly runId: RunId;
708
- readonly flowId: string;
709
- readonly status: RunStatus;
710
- readonly steps: Readonly<Record<StepId, StepState>>;
711
- readonly facts: ReadonlyArray<Fact>;
712
- /** Content hash of the canonical flow DAG this run is pinned to. */
713
- readonly flowHash?: string;
714
- /** Handler-code identifier (typically a git SHA) recorded at run start. */
715
- readonly codeVersion?: string;
694
+ interface StepAbortRequestedFact extends FactBase {
695
+ readonly kind: "step.abort-requested";
696
+ readonly stepId: StepId;
697
+ readonly attempt: AttemptNumber;
698
+ readonly actor: string;
699
+ readonly note?: string;
716
700
  }
701
+ type Fact = FlowStartedFact | FlowCompletedFact | FlowFailedFact | FlowCanceledFact | StepStartedFact | StepCompletedFact | StepFailedFact | StepCanceledFact | StepRetriedFact | StepSkippedFact | StepResetFact | StepAbortRequestedFact | SignalSentFact | SignalReceivedFact | SignalBufferedFact | OnceRecordedFact | MatchArmSelectedFact;
702
+ type RunStatus = "pending" | "running" | "completed" | "failed" | "canceled";
703
+ type StepStatus = "pending" | "running" | "completed" | "failed" | "canceled" | "skipped";
704
+
717
705
  type ReplayMode = "inspect" | "continue";
718
706
  interface ReplayOpts {
719
707
  readonly mode: ReplayMode;
720
- /**
721
- * When true, allow replays to proceed even if the live flow's canonical
722
- * hash differs from the snapshot pinned to the run. Scheduling decisions
723
- * come from the pinned snapshot; handler bodies are resolved from the
724
- * currently-registered flow by step id (best-effort).
725
- *
726
- * When false (default), drift throws `NagiSnapshotDriftError`.
727
- */
728
708
  readonly allowDrift?: boolean;
729
- /**
730
- * Whether step / flow lifecycle hooks (both the step-local ones on
731
- * `TaskConfig` / `FlowConfig` and the cross-cutting `FlowHooks`) fire during
732
- * replay. Defaults to `true` — replay re-executes steps via the idempotent
733
- * dispatcher and emits the same observable lifecycle. Set to `false` for
734
- * backfills or inspection-style replays where re-emitting webhooks would
735
- * dual-publish.
736
- */
737
709
  readonly fireHooks?: boolean;
710
+ readonly from?: StepId;
711
+ }
712
+ interface OperatorAuditOpts {
713
+ readonly actor: string;
714
+ readonly note?: string;
715
+ }
716
+ interface Operator {
717
+ skip(runId: RunId, stepId: StepId, opts: OperatorAuditOpts): Promise<void>;
718
+ retry(runId: RunId, stepId: StepId, opts: OperatorAuditOpts): Promise<void>;
719
+ abort(runId: RunId, opts: OperatorAuditOpts): Promise<void>;
738
720
  }
739
721
 
740
- /**
741
- * Construct a flow.
742
- *
743
- * 1. Run `build(b)` to collect the user's StepMap. Each call to `b.task` /
744
- * `b.signal` / `b.match` produced a Step with `id: ""` and a captured def
745
- * (which may reference upstream Step values from earlier in the closure).
746
- * Match defs additionally hold their arms' nested StepMaps on `_nested`.
747
- * 2. Walk the returned map *recursively*, descending into match arms. Each
748
- * step gets an id derived from its position: top-level keys verbatim,
749
- * nested arm steps namespaced as `<matchKey>.<armId>.<stepKey>`.
750
- * 3. Rewrite every def's `needs` so each upstream Step value carries its
751
- * assigned id. Nested-arm step defs additionally get a `parentMatch`
752
- * annotation so the scheduler can gate them on arm selection.
753
- * 4. Promote `MatchArmDef._nested` → `MatchArmDef.stepIds` (the namespaced
754
- * IDs of the arm's nested steps), then drop `_nested`.
755
- */
756
- declare function flow<const Id extends string, InputSchema extends StandardSchemaV1, R, Output = unknown>(config: FlowConfig<Id, InputSchema, R, Output>): Flow<Id, InputSchema, AsStepMap<R>, Output>;
722
+ 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>;
723
+ declare function optional<S extends Step>(step: S): Optional<S>;
757
724
 
758
- /**
759
- * Canonical retry shape. Defaults are materialized explicitly so equivalent
760
- * retry configs hash identically regardless of source-side omission style.
761
- * `retryOn` is dropped — it's a function, not serializable.
762
- */
763
725
  interface CanonicalRetryPolicy {
764
726
  readonly maxAttempts: number;
765
727
  readonly backoff: BackoffStrategy;
766
728
  readonly initialDelayMs: Millis;
767
729
  readonly maxDelayMs: Millis;
768
730
  }
769
- /**
770
- * Canonical schema fingerprint. v0 hashes `validate.toString()` alongside
771
- * runtime-stable `vendor` + `version` — best-effort, breaks under minification.
772
- * Documented as a known limit in RFC 0001.
773
- */
774
731
  interface CanonicalSchema {
775
732
  readonly vendor: string;
776
733
  readonly version: number;
@@ -780,116 +737,123 @@ interface CanonicalMatchArm {
780
737
  readonly id: string;
781
738
  readonly otherwise?: true;
782
739
  readonly whenHash?: string;
783
- /** Namespaced IDs of nested steps for this arm, sorted lexicographically. */
784
740
  readonly stepIds: readonly StepId[];
785
741
  }
786
742
  interface CanonicalStep {
787
743
  readonly id: StepId;
788
744
  readonly kind: StepKind;
789
- /** Upstream step ids the step depends on, sorted lexicographically. */
790
745
  readonly needs: readonly StepId[];
791
746
  readonly whenHash?: string;
792
747
  readonly retry?: CanonicalRetryPolicy;
793
748
  readonly timeoutMs?: Millis;
794
749
  readonly signalSchema?: CanonicalSchema;
795
- readonly matchMode?: "discriminator" | "guard";
796
- readonly matchOnHash?: string;
750
+ readonly signalNames?: readonly string[];
797
751
  readonly matchArms?: readonly CanonicalMatchArm[];
752
+ readonly childFlowId?: string;
753
+ readonly subflowInputHash?: string;
798
754
  }
799
755
  interface CanonicalDag {
800
756
  readonly flowId: string;
801
757
  readonly inputSchema: CanonicalSchema;
802
- /** Steps sorted by `id` lexicographically — insertion order is ignored. */
803
758
  readonly steps: readonly CanonicalStep[];
804
759
  }
805
- /**
806
- * Build the canonical DAG for a flow.
807
- *
808
- * Stable across cosmetic source changes (step-key reorder, needs-key reorder)
809
- * and different across topology changes (added/removed steps, edge changes,
810
- * `when` flips, retry edits, timeout edits).
811
- *
812
- * Handler `run` bodies are intentionally NOT part of the hash — see RFC 0001
813
- * "Topology vs handler code." Use `nagi({ codeVersion })` (typically a git
814
- * SHA) to capture handler-code drift orthogonally.
815
- *
816
- * Async because predicate/schema source bodies are sha256'd via
817
- * `crypto.subtle` so the stored `dag` JSON stays compact.
818
- */
819
760
  declare function canonicalize(flow: Flow): Promise<CanonicalDag>;
820
- /**
821
- * Compute the sha256 hex digest of a canonical DAG. Uses Web Crypto
822
- * (`crypto.subtle.digest`) which is available in Node ≥ 19, modern browsers,
823
- * Cloudflare Workers, Deno, and Bun.
824
- *
825
- * The DAG is serialized via {@link stableStringify} so object-key order is
826
- * deterministic. Two equivalent DAGs produce byte-identical input bytes.
827
- */
828
761
  declare function sha256Canonical(dag: CanonicalDag): Promise<string>;
762
+ declare function fingerprintFlows(flows: ReadonlyArray<Flow>): Promise<string>;
829
763
 
830
- /** Fields on a step whose hash-relevant value can change between snapshots. */
831
- type SnapshotChangedField = "kind" | "when" | "retry" | "timeoutMs" | "signalSchema" | "matchMode" | "matchOn" | "matchArms";
764
+ type SnapshotChangedField = "kind" | "when" | "retry" | "timeoutMs" | "signalSchema" | "matchArms";
832
765
  interface SnapshotChangedEdge {
833
766
  readonly from: StepId;
834
767
  readonly to: StepId;
835
768
  readonly before: "needed" | "absent";
836
769
  readonly after: "needed" | "absent";
837
770
  }
838
- interface SnapshotChangedField_ {
771
+ interface SnapshotChangedPredicate {
839
772
  readonly stepId: StepId;
840
773
  readonly field: SnapshotChangedField;
841
774
  }
842
- /**
843
- * Structural delta between two snapshots — added/removed steps, added/removed
844
- * edges, per-field topology changes on shared steps.
845
- *
846
- * Pure function over canonical DAGs. The output mirrors the RFC 0001 shape:
847
- *
848
- * {
849
- * addedSteps,
850
- * removedSteps,
851
- * changedEdges, // append-or-remove edges between shared steps
852
- * changedPredicates // when / retry / timeoutMs / schema / match changes
853
- * }
854
- *
855
- * "Changed" means the canonical hash-relevant value differs. For predicates
856
- * this is best-effort under the same source-hash limit as canonicalize.
857
- */
858
775
  interface SnapshotDiff {
859
776
  readonly addedSteps: readonly StepId[];
860
777
  readonly removedSteps: readonly StepId[];
861
778
  readonly changedEdges: readonly SnapshotChangedEdge[];
862
- readonly changedPredicates: readonly SnapshotChangedField_[];
779
+ readonly changedPredicates: readonly SnapshotChangedPredicate[];
863
780
  }
864
781
  declare function diffSnapshots(before: CanonicalDag, after: CanonicalDag): SnapshotDiff;
865
782
 
783
+ declare class NagiValidationError extends Error {
784
+ readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
785
+ constructor(issues: ReadonlyArray<StandardSchemaV1.Issue>);
786
+ }
787
+ declare class NagiRuntimeError extends Error {
788
+ constructor(message: string);
789
+ }
790
+ declare class NagiCanceledError extends Error {
791
+ readonly runId: RunId;
792
+ readonly canceledByRunId: RunId;
793
+ readonly concurrencyKey: string;
794
+ constructor({ runId, canceledByRunId, concurrencyKey, }: {
795
+ readonly runId: RunId;
796
+ readonly canceledByRunId: RunId;
797
+ readonly concurrencyKey: string;
798
+ });
799
+ }
800
+ declare class NagiSnapshotDriftError extends Error {
801
+ readonly runId: RunId;
802
+ readonly expected: string;
803
+ readonly actual: string;
804
+ constructor({ runId, expected, actual, }: {
805
+ readonly runId: RunId;
806
+ readonly expected: string;
807
+ readonly actual: string;
808
+ });
809
+ }
810
+
866
811
  interface InMemoryStoreOpts {
867
812
  readonly leaseMs?: Millis;
868
813
  }
869
- declare class InMemoryStore implements Store {
814
+ declare class InMemoryStore implements Store, StreamTransport {
870
815
  private readonly facts;
871
- private readonly outputs;
872
816
  private readonly onces;
873
817
  private readonly leases;
874
818
  private readonly snapshots;
875
819
  private readonly refs;
876
820
  private readonly globalFacts;
821
+ private readonly activeByKey;
822
+ private readonly keyByActiveRun;
823
+ private readonly childrenByParent;
824
+ private readonly summaries;
825
+ private readonly streamHub;
877
826
  private readonly leaseMs;
878
827
  constructor(opts?: InMemoryStoreOpts);
879
828
  appendFact(runId: RunId, fact: Fact): Promise<void>;
880
- tryStartRun(runId: RunId, fact: FlowStartedFact): Promise<{
829
+ tryStartRun(runId: RunId, fact: FlowStartedFact, concurrency?: {
830
+ readonly key: string;
831
+ readonly mode: ConcurrencyMode;
832
+ }): Promise<{
881
833
  readonly started: boolean;
834
+ readonly canceled: ReadonlyArray<{
835
+ readonly runId: RunId;
836
+ readonly fact: FlowCanceledByConcurrencyFact;
837
+ }>;
882
838
  }>;
839
+ listChildren(parentRunId: RunId): Promise<ReadonlyArray<RunId>>;
883
840
  loadRunState(runId: RunId): Promise<RunState>;
884
841
  claimStep(runId: RunId, stepId: StepId, attempt: AttemptNumber): Promise<ClaimToken | null>;
885
- completeStep(runId: RunId, stepId: StepId, output: Json, fact: Fact): Promise<void>;
886
- failStep(runId: RunId, _stepId: StepId, _error: SerializedError, fact: Fact): Promise<void>;
887
- getStepOutput(runId: RunId, stepId: StepId): Promise<Json | null>;
842
+ settleStep(runId: RunId, _stepId: StepId, fact: StepCompletedFact | StepFailedFact): Promise<void>;
843
+ settleSignal(args: {
844
+ readonly runId: RunId;
845
+ readonly stepId: StepId;
846
+ readonly at: Date;
847
+ readonly incoming?: {
848
+ readonly payload: Json;
849
+ readonly signalName?: string;
850
+ };
851
+ }): Promise<SettleSignalResult>;
888
852
  recordOnce(runId: RunId, stepId: StepId, scope: string, value: Json): Promise<void>;
889
853
  getOnce(runId: RunId, stepId: StepId, scope: string): Promise<Json | null>;
890
- runStep<T extends Json>(runId: RunId, stepId: StepId, _attempt: AttemptNumber, body: (tx: Tx) => Promise<{
854
+ runStep<T extends Json>(runId: RunId, _stepId: StepId, _attempt: AttemptNumber, body: (tx: Tx) => Promise<{
891
855
  readonly output: T;
892
- readonly fact: StepCompletedFact | StepFailedFact;
856
+ readonly fact: StepCompletedFact | StepFailedFact | StepCanceledFact;
893
857
  }>): Promise<T>;
894
858
  upsertSnapshot(args: {
895
859
  readonly flowHash: string;
@@ -903,15 +867,15 @@ declare class InMemoryStore implements Store {
903
867
  readonly dag: Json;
904
868
  } | null>;
905
869
  appendGlobalFact(fact: GlobalFact): Promise<void>;
906
- /** Test-only: peek at the in-memory global fact log. */
907
870
  readGlobalFacts(): ReadonlyArray<GlobalFact>;
871
+ queryRuns(opts: QueryRunsOpts): Promise<QueryRunsResult>;
872
+ pruneFacts(opts: Required<PruneOpts>): Promise<PruneResult>;
873
+ subscribeStream(runId: RunId, stepId: StepId, opts?: {
874
+ readonly replayBuffered?: boolean;
875
+ }): AsyncIterable<StreamEvent<Json>>;
876
+ publishChunk(runId: RunId, stepId: StepId, chunk: Json): void;
908
877
  }
909
- /**
910
- * Project an append-only fact stream into a `RunState`. Public so adapters
911
- * (e.g. `@nagi-js/postgres`) can re-use the same projection rules — keeping
912
- * one canonical definition of "what does the fact log mean".
913
- */
914
- declare function projectRunState(runId: RunId, facts: readonly Fact[]): RunState;
878
+
915
879
  interface InMemoryQueueOpts {
916
880
  readonly leaseMs?: Millis;
917
881
  }
@@ -929,13 +893,6 @@ declare class InMemoryQueue implements Queue {
929
893
  extend(receipt: string, leaseMs: Millis): Promise<void>;
930
894
  }
931
895
  interface InMemoryClockOpts {
932
- /**
933
- * Wires `schedule()` wake-ups to a trigger. When the persistent timer fires,
934
- * the clock calls `trigger.fire(runId)` so scheduler subscribers can resume
935
- * the run. Without this, `schedule()` is a no-op on the worker loop and any
936
- * step that depends on it (time-based gates, long-delayed retries) will
937
- * stall in tests.
938
- */
939
896
  readonly trigger?: InMemoryTrigger;
940
897
  }
941
898
  declare class InMemoryClock implements Clock {
@@ -945,88 +902,86 @@ declare class InMemoryClock implements Clock {
945
902
  now(): Date;
946
903
  sleep(ms: Millis, signal?: AbortSignal): Promise<void>;
947
904
  schedule(at: Date, runId: RunId, stepId: StepId): Promise<void>;
948
- /** Clear any pending scheduled timers. Call from test teardown. */
949
905
  dispose(): void;
950
906
  }
951
907
  declare class InMemoryTrigger implements Trigger {
952
908
  private handlers;
953
909
  subscribe(handler: (runId: RunId) => void): () => void;
954
- /**
955
- * Test-only: synchronously dispatch a wake-up to all subscribers.
956
- * Real triggers fire from a Store change (NOTIFY/LISTEN, polling, etc.).
957
- */
958
910
  fire(runId: RunId): void;
959
911
  }
960
912
 
961
913
  interface NagiConfig {
962
914
  readonly flows: ReadonlyArray<Flow>;
963
915
  readonly store: Store;
916
+ readonly streamTransport?: StreamTransport;
964
917
  readonly queue: Queue;
965
918
  readonly clock?: Clock;
966
919
  readonly trigger?: Trigger;
967
920
  readonly hooks?: FlowHooks;
968
- readonly logger?: Logger;
921
+ readonly onLog?: (entry: LogEntry) => void;
969
922
  readonly defaultRetry?: RetryPolicy;
970
- /**
971
- * Handler-code identifier — typically a git SHA from `process.env.GIT_SHA`
972
- * or your build's bundle hash. Persisted on `workflow_run.code_version` and
973
- * on every `flow.started` fact for runs started by this process. Captures
974
- * handler-body drift orthogonally to the topology hash. See RFC 0001
975
- * "Topology vs handler code."
976
- */
977
923
  readonly codeVersion?: string;
978
924
  }
979
925
  interface StartOpts {
980
- /**
981
- * Caller-supplied runId for idempotent kickoff. If provided and a run with
982
- * this ID already exists, `start()` is a no-op and returns the same ID
983
- * without re-appending `flow.started`, re-dispatching, or re-validating the
984
- * input. Two concurrent `start()` calls with the same `runId` produce
985
- * exactly one run (enforced at the Store layer).
986
- *
987
- * If omitted, the runtime mints a fresh ID via `crypto.randomUUID()`.
988
- *
989
- * Typical usage: a content hash of the input, so callers de-duplicate
990
- * kickoffs without coordinating.
991
- */
992
926
  readonly runId?: RunId;
993
927
  }
994
- interface Wf {
995
- /** Begin a new run. Returns the runId. */
996
- start<F extends Flow>(flow: F, input: FlowInput<F>, opts?: StartOpts): Promise<RunId>;
997
- /** Resolve a `b.signal()` step waiting on external input. */
928
+ interface CancelOpts {
929
+ readonly reason?: string;
930
+ }
931
+ interface Wf<TFlows extends ReadonlyArray<Flow> = ReadonlyArray<Flow>> {
932
+ start<F extends TFlows[number]>(flow: F, input: FlowInput<F>, opts?: StartOpts): Promise<RunId>;
933
+ startById(flowId: string, input: unknown, opts?: StartOpts): Promise<RunId>;
998
934
  signal(runId: RunId, stepName: string, payload: unknown): Promise<void>;
999
- /** Construct a worker; call `run` / `runOnce` / `runUntilEmpty` on it. */
935
+ cancel(runId: RunId, opts?: CancelOpts): Promise<void>;
1000
936
  worker(config?: WorkerConfig): Worker;
1001
- /**
1002
- * Re-dispatch from the first incomplete step. `mode: "continue"` runs side
1003
- * effects (idempotency protects); `mode: "inspect"` is a no-op probe.
1004
- */
1005
937
  replay(runId: RunId, opts?: ReplayOpts): Promise<void>;
938
+ queryRuns(opts?: QueryRunsOpts<FlowIdOf<TFlows>>): Promise<QueryRunsResult<FlowIdOf<TFlows>>>;
939
+ subscribe<C = Json>(runId: RunId, stepId: StepId, opts?: {
940
+ readonly replayBuffered?: boolean;
941
+ }): AsyncIterable<StreamEvent<C>>;
942
+ operator(): Operator;
943
+ pruneFacts(opts: PruneOpts): Promise<PruneResult>;
944
+ }
945
+ declare function nagiImpl<const TFlows extends ReadonlyArray<Flow>>(config: NagiConfig & {
946
+ flows: TFlows;
947
+ }): Promise<Wf<TFlows>>;
948
+ interface NagiRunConfig extends NagiConfig {
949
+ readonly worker?: Omit<WorkerConfig, "signal">;
950
+ readonly signal?: AbortSignal;
1006
951
  }
1007
- declare class NagiValidationError extends Error {
1008
- readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
1009
- constructor(issues: ReadonlyArray<StandardSchemaV1.Issue>);
1010
- }
1011
- declare class NagiRuntimeError extends Error {
1012
- constructor(message: string);
952
+ interface RuntimeHandle<TFlows extends ReadonlyArray<Flow> = ReadonlyArray<Flow>> {
953
+ readonly wf: Wf<TFlows>;
954
+ stop(): Promise<void>;
1013
955
  }
1014
- /**
1015
- * Thrown by `wf.replay(runId)` when the live flow's canonical hash differs
1016
- * from the snapshot the run was pinned to. The default replay behavior is
1017
- * fail-loud — pass `replayOpts.allowDrift = true` to proceed using a
1018
- * synthesized flow (topology from snapshot, handlers/predicates from live).
1019
- */
1020
- declare class NagiSnapshotDriftError extends Error {
1021
- readonly runId: RunId;
1022
- readonly expected: string;
1023
- readonly actual: string;
1024
- constructor(args: {
1025
- readonly runId: RunId;
1026
- readonly expected: string;
1027
- readonly actual: string;
1028
- });
1029
- }
1030
- declare function nagi(config: NagiConfig): Promise<Wf>;
956
+ declare function nagiRun<const TFlows extends ReadonlyArray<Flow>>(config: NagiRunConfig & {
957
+ flows: TFlows;
958
+ }): Promise<RuntimeHandle<TFlows>>;
959
+ declare const nagi: typeof nagiImpl & {
960
+ run: typeof nagiRun;
961
+ };
962
+
963
+ type SignalDecision = {
964
+ readonly kind: "noop";
965
+ readonly result: SettleSignalResult;
966
+ } | {
967
+ readonly kind: "buffer";
968
+ readonly fact: SignalBufferedFact | null;
969
+ readonly result: SettleSignalResult;
970
+ } | {
971
+ readonly kind: "deliver";
972
+ readonly attempt: AttemptNumber;
973
+ readonly received: SignalReceivedFact;
974
+ readonly completed: StepCompletedFact;
975
+ readonly result: SettleSignalResult;
976
+ };
977
+ declare function decideSignal(args: {
978
+ readonly runState: RunState;
979
+ readonly stepId: StepId;
980
+ readonly at: Date;
981
+ readonly incoming?: {
982
+ readonly payload: Json;
983
+ readonly signalName?: string;
984
+ } | undefined;
985
+ }): SignalDecision;
1031
986
 
1032
- export { type AsStepMap, type AttemptNumber, type BackoffStrategy, type BuildResult, type Builder, type BuilderAccumulator, type CanonicalDag, type CanonicalMatchArm, type CanonicalRetryPolicy, type CanonicalSchema, type CanonicalStep, type ClaimToken, type Clock, type Fact, type FactKind, type Flow, type FlowCompleteEvent, type FlowCompletedFact, type FlowConfig, type FlowErrorEvent, type FlowEvent, type FlowFailedFact, type FlowHooks, 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 MatchDiscriminatorConfig, type MatchDiscriminatorOutput, type MatchGuardConfig, type Millis, type NagiConfig, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, type NeedsMap, type NeedsOutputs, type OnceRecordedFact, type Queue, type QueueDequeueOpts, type QueueEnqueueOpts, type QueueMessage, type Register, type ReplayMode, type ReplayOpts, type RetryPolicy, type RunId, type RunState, type RunStatus, type SerializedError, type SignalConfig, type SignalReceivedEvent, type SignalReceivedFact, type SignalSentEvent, type SignalSentFact, type SnapshotChangedEdge, type SnapshotChangedField, type SnapshotDiff, StandardSchemaV1, type StartOpts, type Step, type StepCompleteEvent, type StepCompletedFact, type StepCtx, type StepEntryConfig, type StepErrorEvent, type StepEvent, type StepFailedFact, type StepId, type StepKind, type StepMap, type StepOutput, type StepRetriedFact, type StepRetryEvent, type StepSkippedFact, type StepStartEvent, type StepStartedFact, type StepState, type StepStatus, type Store, type TaskConfig, type Trigger, type Tx, type Wf, type Worker, type WorkerConfig, type WorkerRunOnceOpts, type WorkerRunResult, type WorkerRunUntilEmptyOpts, canonicalize, diffSnapshots, flow, nagi, projectRunState, sha256Canonical };
987
+ 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 };