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

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
@@ -44,7 +44,7 @@ interface Register {
44
44
  type Tx = Register extends {
45
45
  tx: infer T;
46
46
  } ? T : unknown;
47
- type StepKind = "task" | "signal" | "match";
47
+ type StepKind = "task" | "signal" | "match" | "subflow";
48
48
  interface Step<Output = unknown> {
49
49
  readonly kind: StepKind;
50
50
  readonly id: StepId;
@@ -71,17 +71,7 @@ interface StepCtx<Input = unknown> {
71
71
  readonly signal: AbortSignal;
72
72
  readonly now: () => Date;
73
73
  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
74
  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
75
  idempotencyKey(scope: string): string;
86
76
  }
87
77
  type BackoffStrategy = "exponential" | "linear" | "fixed";
@@ -94,12 +84,6 @@ interface RetryPolicy {
94
84
  }
95
85
  interface StepConfigBase<Input, N extends NeedsMap> {
96
86
  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
87
  readonly when?: (args: {
104
88
  readonly input: NoInfer<Input>;
105
89
  readonly needs: NoInfer<NeedsOutputs<N>>;
@@ -113,14 +97,6 @@ interface TaskConfig<Input, N extends NeedsMap, Output> extends StepConfigBase<I
113
97
  readonly needs: NoInfer<NeedsOutputs<N>>;
114
98
  readonly ctx: StepCtx<NoInfer<Input>>;
115
99
  }) => 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
- */
124
100
  readonly onStart?: (event: StepStartEvent) => void | Promise<void>;
125
101
  readonly onComplete?: (event: StepCompleteEvent & {
126
102
  readonly output: NoInfer<Output>;
@@ -130,21 +106,7 @@ interface TaskConfig<Input, N extends NeedsMap, Output> extends StepConfigBase<I
130
106
  }
131
107
  interface SignalConfig<Input, N extends NeedsMap, Schema extends StandardSchemaV1> extends StepConfigBase<Input, N> {
132
108
  readonly schema: Schema;
133
- }
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: {
142
- 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
- };
109
+ readonly names?: readonly [string, ...string[]];
148
110
  }
149
111
  interface MatchArmGuard<Input, N extends NeedsMap, M extends StepMap> {
150
112
  readonly when: (args: {
@@ -152,179 +114,70 @@ interface MatchArmGuard<Input, N extends NeedsMap, M extends StepMap> {
152
114
  readonly needs: NoInfer<NeedsOutputs<N>>;
153
115
  }) => boolean;
154
116
  readonly otherwise?: never;
155
- readonly build: (b: Builder<Input>) => BuildResult<Input, M>;
117
+ readonly build: (b: Builder<Input>) => M;
156
118
  }
157
119
  interface MatchArmOtherwise<Input, M extends StepMap> {
158
120
  readonly otherwise: true;
159
121
  readonly when?: never;
160
- readonly build: (b: Builder<Input>) => BuildResult<Input, M>;
122
+ readonly build: (b: Builder<Input>) => M;
161
123
  }
162
124
  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
125
  type MatchArmShape<Input, N extends NeedsMap> = {
170
126
  readonly when: (args: {
171
127
  readonly input: NoInfer<Input>;
172
128
  readonly needs: NoInfer<NeedsOutputs<N>>;
173
129
  }) => boolean;
174
130
  readonly otherwise?: never;
175
- readonly build: (b: Builder<Input>) => BuildResult<Input, StepMap>;
131
+ readonly build: (b: Builder<Input>) => StepMap;
176
132
  } | {
177
133
  readonly otherwise: true;
178
134
  readonly when?: never;
179
- readonly build: (b: Builder<Input>) => BuildResult<Input, StepMap>;
135
+ readonly build: (b: Builder<Input>) => StepMap;
180
136
  };
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
137
  interface MatchGuardConfig<Input, N extends NeedsMap, M extends StepMap> {
187
138
  readonly needs?: N;
188
139
  readonly arms: ReadonlyArray<MatchArm<Input, N, M>>;
189
140
  }
190
- /** The output of a match step is a record of each step in the chosen arm. */
191
141
  type MatchArmOutput<M extends StepMap> = {
192
142
  readonly [K in keyof M]: StepOutput<M[K]>;
193
143
  };
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: {
144
+ interface SubflowConfig<Input, N extends NeedsMap, Child extends Flow> extends StepConfigBase<Input, N> {
145
+ readonly input: (args: {
213
146
  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>;
147
+ readonly needs: NoInfer<NeedsOutputs<N>>;
148
+ }) => FlowInput<Child>;
226
149
  }
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>> {
150
+ interface SubflowStepOutput<ChildOutput> {
151
+ readonly childRunId: RunId;
152
+ readonly output: ChildOutput;
153
+ }
154
+ interface Builder<Input = unknown> {
248
155
  task<N extends NeedsMap, Output>(config: TaskConfig<Input, N, Output>): Step<Output>;
249
156
  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]>;
157
+ subflow<N extends NeedsMap, Child extends Flow>(child: Child, config: SubflowConfig<Input, N, Child>): Step<SubflowStepOutput<FlowOutput<Child>>>;
262
158
  match<N extends NeedsMap, Arms extends ReadonlyArray<MatchArmShape<Input, N>>>(config: {
263
159
  readonly needs?: N;
264
160
  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;
161
+ }): Step<MatchArmOutput<ReturnType<Arms[number]["build"]>>>;
162
+ }
163
+ type ConcurrencyMode = "cancel-in-progress";
164
+ type StringKeyOf<Input> = {
165
+ [K in keyof Input]-?: Input[K] extends string ? K : never;
166
+ }[keyof Input];
167
+ type FlowConcurrency<Input = Json> = StringKeyOf<Input> | {
168
+ readonly keyFn: (input: Input) => string;
169
+ readonly mode?: ConcurrencyMode;
298
170
  };
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). */
171
+ interface ResolvedConcurrency {
172
+ readonly keyFn: (input: Json) => string;
173
+ readonly mode: ConcurrencyMode;
174
+ }
175
+ interface FlowConfig<Id extends string, InputSchema extends StandardSchemaV1, R extends StepMap, Output = unknown> {
305
176
  readonly id: Id;
306
177
  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
178
  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
- */
179
+ output?(steps: NeedsOutputs<R>): Output;
180
+ readonly concurrency?: FlowConcurrency<InferSchemaOutput<InputSchema>>;
328
181
  readonly onStart?: (event: FlowStartEvent) => void | Promise<void>;
329
182
  readonly onComplete?: (event: FlowCompleteEvent & {
330
183
  readonly output: NoInfer<Output>;
@@ -336,20 +189,30 @@ interface Flow<Id extends string = string, InputSchema extends StandardSchemaV1
336
189
  readonly input: InputSchema;
337
190
  readonly steps: M;
338
191
  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
192
  readonly onStart?: (event: FlowStartEvent) => void | Promise<void>;
348
193
  readonly onComplete?: (event: FlowCompleteEvent) => void | Promise<void>;
349
194
  readonly onError?: (event: FlowErrorEvent) => void | Promise<void>;
195
+ readonly concurrency?: ResolvedConcurrency;
350
196
  }
351
197
  type FlowInput<F> = F extends Flow<string, infer S, StepMap, unknown> ? InferSchemaOutput<S> : never;
352
198
  type FlowOutput<F> = F extends Flow<string, StandardSchemaV1, StepMap, infer O> ? O : never;
199
+ 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
+ interface ParentLink {
205
+ readonly runId: RunId;
206
+ readonly stepId: StepId;
207
+ }
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
+ interface ParentRef extends ParentLink {
214
+ readonly attempt: AttemptNumber;
215
+ }
353
216
  interface FlowEvent {
354
217
  readonly runId: RunId;
355
218
  readonly flowId: string;
@@ -357,6 +220,12 @@ interface FlowEvent {
357
220
  }
358
221
  interface FlowStartEvent extends FlowEvent {
359
222
  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
+ readonly parent?: ParentRef;
360
229
  }
361
230
  interface FlowCompleteEvent extends FlowEvent {
362
231
  readonly output: Json;
@@ -370,13 +239,6 @@ interface StepEvent extends FlowEvent {
370
239
  readonly kind: StepKind;
371
240
  }
372
241
  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
242
  readonly input: Json;
381
243
  }
382
244
  interface StepCompleteEvent extends StepEvent {
@@ -410,25 +272,20 @@ interface FlowHooks {
410
272
  interface WorkerConfig {
411
273
  readonly concurrency?: number;
412
274
  readonly pollIntervalMs?: Millis;
413
- /** AbortSignal drives graceful drain on SIGTERM/SIGINT. */
414
275
  readonly signal?: AbortSignal;
415
276
  }
416
277
  interface WorkerRunOnceOpts {
417
278
  readonly maxSteps?: number;
418
279
  }
419
280
  interface WorkerRunUntilEmptyOpts {
420
- /** Wall-clock deadline in `Date.now()` units. Edge runtimes have CPU/wall-time budgets. */
421
281
  readonly deadline?: number;
422
282
  }
423
283
  interface WorkerRunResult {
424
284
  readonly processed: number;
425
285
  }
426
286
  interface Worker {
427
- /** Long-running fleet (Cloud Run service, ECS, dedicated VM). Blocks until `signal` aborts. */
428
287
  run(): Promise<void>;
429
- /** HTTP server alongside requests. Returns after up to `maxSteps` are processed. */
430
288
  runOnce(opts?: WorkerRunOnceOpts): Promise<WorkerRunResult>;
431
- /** Serverless / edge. Drains everything available within the deadline and exits. */
432
289
  runUntilEmpty(opts?: WorkerRunUntilEmptyOpts): Promise<WorkerRunResult>;
433
290
  }
434
291
  type ClaimToken = string & {
@@ -440,116 +297,83 @@ interface SerializedError {
440
297
  readonly stack?: string;
441
298
  readonly cause?: Json;
442
299
  }
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
- */
453
300
  interface Store {
454
301
  appendFact(runId: RunId, fact: Fact): Promise<void>;
455
302
  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<{
303
+ tryStartRun(runId: RunId, fact: FlowStartedFact, concurrency?: {
304
+ readonly key: string;
305
+ readonly mode: ConcurrencyMode;
306
+ }): Promise<{
471
307
  readonly started: boolean;
308
+ readonly canceled: ReadonlyArray<{
309
+ readonly runId: RunId;
310
+ readonly fact: FlowCanceledByConcurrencyFact;
311
+ }>;
472
312
  }>;
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
313
  claimStep(runId: RunId, stepId: StepId, attempt: AttemptNumber): Promise<ClaimToken | null>;
478
314
  completeStep(runId: RunId, stepId: StepId, output: Json, fact: Fact): Promise<void>;
479
315
  failStep(runId: RunId, stepId: StepId, error: SerializedError, fact: Fact): Promise<void>;
480
- /** Memoization read — returns the persisted output of a previously completed step. */
481
316
  getStepOutput(runId: RunId, stepId: StepId): Promise<Json | null>;
482
- /** `ctx.once` durable record. */
483
317
  recordOnce(runId: RunId, stepId: StepId, scope: string, value: Json): Promise<void>;
484
318
  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
319
  runStep<T extends Json>(runId: RunId, stepId: StepId, attempt: AttemptNumber, body: (tx: Tx) => Promise<{
508
320
  readonly output: T;
509
- readonly fact: StepCompletedFact | StepFailedFact;
321
+ readonly fact: StepCompletedFact | StepFailedFact | StepCanceledFact;
510
322
  }>): 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
323
  upsertSnapshot(args: {
521
324
  readonly flowHash: string;
522
325
  readonly flowId: string;
523
326
  readonly dag: Json;
524
327
  }): 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
328
  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
329
  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
330
  loadSnapshot(flowHash: string): Promise<{
545
331
  readonly flowId: string;
546
332
  readonly dag: Json;
547
333
  } | 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
334
  appendGlobalFact(fact: GlobalFact): Promise<void>;
335
+ queryRuns(opts: QueryRunsOpts): Promise<QueryRunsResult>;
336
+ listChildren(parentRunId: RunId): Promise<ReadonlyArray<RunId>>;
337
+ pruneFacts(opts: Required<PruneOpts>): Promise<PruneResult>;
338
+ }
339
+ interface QueryRunsWhere<FlowId extends string = string> {
340
+ readonly flowId?: FlowId;
341
+ readonly status?: RunStatus | ReadonlyArray<RunStatus>;
342
+ readonly input?: Record<string, Json>;
343
+ }
344
+ type QueryRunsOpts<FlowId extends string = string> = {
345
+ readonly where?: QueryRunsWhere<FlowId>;
346
+ readonly latest: true;
347
+ readonly limit?: never;
348
+ readonly cursor?: never;
349
+ } | {
350
+ readonly where?: QueryRunsWhere<FlowId>;
351
+ readonly latest?: false;
352
+ readonly limit?: number;
353
+ readonly cursor?: string;
354
+ };
355
+ interface RunSummary<FlowId extends string = string> {
356
+ readonly runId: RunId;
357
+ readonly flowId: FlowId;
358
+ readonly status: RunStatus;
359
+ readonly startedAt: Date;
360
+ readonly completedAt: Date | null;
361
+ readonly input: Json;
362
+ }
363
+ interface QueryRunsResult<FlowId extends string = string> {
364
+ readonly runs: ReadonlyArray<RunSummary<FlowId>>;
365
+ readonly cursor: string | null;
366
+ }
367
+ type PrunableStatus = Extract<RunStatus, "completed" | "failed" | "canceled">;
368
+ interface PruneOpts {
369
+ readonly olderThan: Date;
370
+ readonly statuses?: ReadonlyArray<PrunableStatus>;
371
+ readonly batchSize?: number;
372
+ readonly keepSummary?: boolean;
373
+ }
374
+ interface PruneResult {
375
+ readonly runsPruned: number;
376
+ readonly factsPruned: number;
553
377
  }
554
378
  interface QueueMessage {
555
379
  readonly receipt: string;
@@ -562,11 +386,8 @@ interface QueueDequeueOpts {
562
386
  readonly count: number;
563
387
  }
564
388
  interface QueueEnqueueOpts {
565
- /** Attempt number to publish. Defaults to 1. The dispatcher controls increments. */
566
389
  readonly attempt?: AttemptNumber;
567
- /** Visibility delay — the message becomes dequeueable after `delayMs`. */
568
390
  readonly delayMs?: Millis;
569
- /** Adapter-specific extra data. Core never reads this. */
570
391
  readonly payload?: Json;
571
392
  }
572
393
  interface Queue {
@@ -577,24 +398,23 @@ interface Queue {
577
398
  delayMs?: Millis;
578
399
  }): Promise<void>;
579
400
  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
+ ensureSchema?(): Promise<void>;
580
408
  }
581
409
  interface Clock {
582
410
  now(): Date;
583
- /** Resolves when `ms` has elapsed or `signal` aborts. */
584
411
  sleep(ms: Millis, signal?: AbortSignal): Promise<void>;
585
- /** Persistent timer — wakes the scheduler at `at` for `(runId, stepId)`. */
586
412
  schedule(at: Date, runId: RunId, stepId: StepId): Promise<void>;
587
413
  }
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
414
  interface Trigger {
595
415
  subscribe(handler: (runId: RunId) => void): () => void;
596
416
  }
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";
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";
598
418
  interface FactBase {
599
419
  readonly runId: RunId;
600
420
  readonly at: Date;
@@ -603,34 +423,14 @@ interface FlowStartedFact extends FactBase {
603
423
  readonly kind: "flow.started";
604
424
  readonly flowId: string;
605
425
  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
426
  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
427
  readonly codeVersion?: string;
428
+ /** Present when this run was started as a subflow child; absent for roots. */
429
+ readonly parent?: ParentLink;
620
430
  }
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
431
  interface FlowRefUpdatedFact {
631
432
  readonly kind: "flow_ref.updated";
632
433
  readonly flowId: string;
633
- /** Previous hash, or null when this is the first publish of `flowId`. */
634
434
  readonly from: string | null;
635
435
  readonly to: string;
636
436
  readonly at: Date;
@@ -644,6 +444,26 @@ interface FlowFailedFact extends FactBase {
644
444
  readonly kind: "flow.failed";
645
445
  readonly error: SerializedError;
646
446
  }
447
+ interface FlowCanceledByConcurrencyFact extends FactBase {
448
+ readonly kind: "flow.canceled";
449
+ readonly cause: "concurrency";
450
+ readonly canceledByRunId: RunId;
451
+ readonly concurrencyKey: string;
452
+ }
453
+ interface FlowCanceledExplicitlyFact extends FactBase {
454
+ readonly kind: "flow.canceled";
455
+ readonly cause: "explicit";
456
+ readonly reason: string;
457
+ readonly note?: string;
458
+ }
459
+ interface FlowCanceledByOperatorFact extends FactBase {
460
+ readonly kind: "flow.canceled";
461
+ readonly cause: "operator";
462
+ readonly actor: string;
463
+ readonly reason: string;
464
+ readonly note?: string;
465
+ }
466
+ type FlowCanceledFact = FlowCanceledByConcurrencyFact | FlowCanceledExplicitlyFact | FlowCanceledByOperatorFact;
647
467
  interface StepStartedFact extends FactBase {
648
468
  readonly kind: "step.started";
649
469
  readonly stepId: StepId;
@@ -661,6 +481,12 @@ interface StepFailedFact extends FactBase {
661
481
  readonly attempt: AttemptNumber;
662
482
  readonly error: SerializedError;
663
483
  }
484
+ interface StepCanceledFact extends FactBase {
485
+ readonly kind: "step.canceled";
486
+ readonly stepId: StepId;
487
+ readonly attempt: AttemptNumber;
488
+ readonly error?: SerializedError;
489
+ }
664
490
  interface StepRetriedFact extends FactBase {
665
491
  readonly kind: "step.retried";
666
492
  readonly stepId: StepId;
@@ -670,7 +496,10 @@ interface StepRetriedFact extends FactBase {
670
496
  interface StepSkippedFact extends FactBase {
671
497
  readonly kind: "step.skipped";
672
498
  readonly stepId: StepId;
673
- readonly reason: "when-false" | "transitive";
499
+ readonly reason: "when-false" | "transitive" | "manual";
500
+ readonly actor?: string;
501
+ readonly note?: string;
502
+ readonly cascade?: "skip" | "continue";
674
503
  }
675
504
  interface SignalSentFact extends FactBase {
676
505
  readonly kind: "signal.sent";
@@ -681,6 +510,7 @@ interface SignalReceivedFact extends FactBase {
681
510
  readonly kind: "signal.received";
682
511
  readonly stepId: StepId;
683
512
  readonly payload: Json;
513
+ readonly signalName?: string;
684
514
  }
685
515
  interface OnceRecordedFact extends FactBase {
686
516
  readonly kind: "once.recorded";
@@ -693,9 +523,23 @@ interface MatchArmSelectedFact extends FactBase {
693
523
  readonly stepId: StepId;
694
524
  readonly arm: string;
695
525
  }
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";
526
+ interface StepResetFact extends FactBase {
527
+ readonly kind: "step.reset";
528
+ readonly stepId: StepId;
529
+ readonly cascadedFrom?: StepId;
530
+ readonly actor?: string;
531
+ readonly note?: string;
532
+ }
533
+ interface StepAbortRequestedFact extends FactBase {
534
+ readonly kind: "step.abort-requested";
535
+ readonly stepId: StepId;
536
+ readonly attempt: AttemptNumber;
537
+ readonly actor: string;
538
+ readonly note?: string;
539
+ }
540
+ type Fact = FlowStartedFact | FlowCompletedFact | FlowFailedFact | FlowCanceledFact | StepStartedFact | StepCompletedFact | StepFailedFact | StepCanceledFact | StepRetriedFact | StepSkippedFact | StepResetFact | StepAbortRequestedFact | SignalSentFact | SignalReceivedFact | OnceRecordedFact | MatchArmSelectedFact;
541
+ type RunStatus = "pending" | "running" | "completed" | "failed" | "canceled";
542
+ type StepStatus = "pending" | "running" | "completed" | "failed" | "canceled" | "skipped";
699
543
  interface StepState {
700
544
  readonly stepId: StepId;
701
545
  readonly status: StepStatus;
@@ -709,68 +553,37 @@ interface RunState {
709
553
  readonly status: RunStatus;
710
554
  readonly steps: Readonly<Record<StepId, StepState>>;
711
555
  readonly facts: ReadonlyArray<Fact>;
712
- /** Content hash of the canonical flow DAG this run is pinned to. */
713
556
  readonly flowHash?: string;
714
- /** Handler-code identifier (typically a git SHA) recorded at run start. */
715
557
  readonly codeVersion?: string;
716
558
  }
717
559
  type ReplayMode = "inspect" | "continue";
718
560
  interface ReplayOpts {
719
561
  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
562
  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
563
  readonly fireHooks?: boolean;
564
+ readonly from?: StepId;
565
+ }
566
+ interface OperatorAuditOpts {
567
+ readonly actor: string;
568
+ readonly note?: string;
569
+ }
570
+ interface OperatorSkipOpts extends OperatorAuditOpts {
571
+ readonly cascade?: "skip" | "continue";
572
+ }
573
+ interface Operator {
574
+ skip(runId: RunId, stepId: StepId, opts: OperatorSkipOpts): Promise<void>;
575
+ retry(runId: RunId, stepId: StepId, opts: OperatorAuditOpts): Promise<void>;
576
+ abort(runId: RunId, opts: OperatorAuditOpts): Promise<void>;
738
577
  }
739
578
 
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>;
579
+ 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>;
757
580
 
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
581
  interface CanonicalRetryPolicy {
764
582
  readonly maxAttempts: number;
765
583
  readonly backoff: BackoffStrategy;
766
584
  readonly initialDelayMs: Millis;
767
585
  readonly maxDelayMs: Millis;
768
586
  }
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
587
  interface CanonicalSchema {
775
588
  readonly vendor: string;
776
589
  readonly version: number;
@@ -780,55 +593,31 @@ interface CanonicalMatchArm {
780
593
  readonly id: string;
781
594
  readonly otherwise?: true;
782
595
  readonly whenHash?: string;
783
- /** Namespaced IDs of nested steps for this arm, sorted lexicographically. */
784
596
  readonly stepIds: readonly StepId[];
785
597
  }
786
598
  interface CanonicalStep {
787
599
  readonly id: StepId;
788
600
  readonly kind: StepKind;
789
- /** Upstream step ids the step depends on, sorted lexicographically. */
790
601
  readonly needs: readonly StepId[];
791
602
  readonly whenHash?: string;
792
603
  readonly retry?: CanonicalRetryPolicy;
793
604
  readonly timeoutMs?: Millis;
794
605
  readonly signalSchema?: CanonicalSchema;
795
- readonly matchMode?: "discriminator" | "guard";
796
- readonly matchOnHash?: string;
606
+ readonly signalNames?: readonly string[];
797
607
  readonly matchArms?: readonly CanonicalMatchArm[];
608
+ readonly childFlowId?: string;
609
+ readonly subflowInputHash?: string;
798
610
  }
799
611
  interface CanonicalDag {
800
612
  readonly flowId: string;
801
613
  readonly inputSchema: CanonicalSchema;
802
- /** Steps sorted by `id` lexicographically — insertion order is ignored. */
803
614
  readonly steps: readonly CanonicalStep[];
804
615
  }
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
616
  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
617
  declare function sha256Canonical(dag: CanonicalDag): Promise<string>;
618
+ declare function fingerprintFlows(flows: ReadonlyArray<Flow>): Promise<string>;
829
619
 
830
- /** Fields on a step whose hash-relevant value can change between snapshots. */
831
- type SnapshotChangedField = "kind" | "when" | "retry" | "timeoutMs" | "signalSchema" | "matchMode" | "matchOn" | "matchArms";
620
+ type SnapshotChangedField = "kind" | "when" | "retry" | "timeoutMs" | "signalSchema" | "matchArms";
832
621
  interface SnapshotChangedEdge {
833
622
  readonly from: StepId;
834
623
  readonly to: StepId;
@@ -839,22 +628,6 @@ interface SnapshotChangedField_ {
839
628
  readonly stepId: StepId;
840
629
  readonly field: SnapshotChangedField;
841
630
  }
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
631
  interface SnapshotDiff {
859
632
  readonly addedSteps: readonly StepId[];
860
633
  readonly removedSteps: readonly StepId[];
@@ -874,12 +647,24 @@ declare class InMemoryStore implements Store {
874
647
  private readonly snapshots;
875
648
  private readonly refs;
876
649
  private readonly globalFacts;
650
+ private readonly activeByKey;
651
+ private readonly keyByActiveRun;
652
+ private readonly childrenByParent;
653
+ private readonly summaries;
877
654
  private readonly leaseMs;
878
655
  constructor(opts?: InMemoryStoreOpts);
879
656
  appendFact(runId: RunId, fact: Fact): Promise<void>;
880
- tryStartRun(runId: RunId, fact: FlowStartedFact): Promise<{
657
+ tryStartRun(runId: RunId, fact: FlowStartedFact, concurrency?: {
658
+ readonly key: string;
659
+ readonly mode: ConcurrencyMode;
660
+ }): Promise<{
881
661
  readonly started: boolean;
662
+ readonly canceled: ReadonlyArray<{
663
+ readonly runId: RunId;
664
+ readonly fact: FlowCanceledByConcurrencyFact;
665
+ }>;
882
666
  }>;
667
+ listChildren(parentRunId: RunId): Promise<ReadonlyArray<RunId>>;
883
668
  loadRunState(runId: RunId): Promise<RunState>;
884
669
  claimStep(runId: RunId, stepId: StepId, attempt: AttemptNumber): Promise<ClaimToken | null>;
885
670
  completeStep(runId: RunId, stepId: StepId, output: Json, fact: Fact): Promise<void>;
@@ -889,7 +674,7 @@ declare class InMemoryStore implements Store {
889
674
  getOnce(runId: RunId, stepId: StepId, scope: string): Promise<Json | null>;
890
675
  runStep<T extends Json>(runId: RunId, stepId: StepId, _attempt: AttemptNumber, body: (tx: Tx) => Promise<{
891
676
  readonly output: T;
892
- readonly fact: StepCompletedFact | StepFailedFact;
677
+ readonly fact: StepCompletedFact | StepFailedFact | StepCanceledFact;
893
678
  }>): Promise<T>;
894
679
  upsertSnapshot(args: {
895
680
  readonly flowHash: string;
@@ -903,14 +688,10 @@ declare class InMemoryStore implements Store {
903
688
  readonly dag: Json;
904
689
  } | null>;
905
690
  appendGlobalFact(fact: GlobalFact): Promise<void>;
906
- /** Test-only: peek at the in-memory global fact log. */
907
691
  readGlobalFacts(): ReadonlyArray<GlobalFact>;
692
+ queryRuns(opts: QueryRunsOpts): Promise<QueryRunsResult>;
693
+ pruneFacts(opts: Required<PruneOpts>): Promise<PruneResult>;
908
694
  }
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
695
  declare function projectRunState(runId: RunId, facts: readonly Fact[]): RunState;
915
696
  interface InMemoryQueueOpts {
916
697
  readonly leaseMs?: Millis;
@@ -929,13 +710,6 @@ declare class InMemoryQueue implements Queue {
929
710
  extend(receipt: string, leaseMs: Millis): Promise<void>;
930
711
  }
931
712
  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
713
  readonly trigger?: InMemoryTrigger;
940
714
  }
941
715
  declare class InMemoryClock implements Clock {
@@ -945,16 +719,11 @@ declare class InMemoryClock implements Clock {
945
719
  now(): Date;
946
720
  sleep(ms: Millis, signal?: AbortSignal): Promise<void>;
947
721
  schedule(at: Date, runId: RunId, stepId: StepId): Promise<void>;
948
- /** Clear any pending scheduled timers. Call from test teardown. */
949
722
  dispose(): void;
950
723
  }
951
724
  declare class InMemoryTrigger implements Trigger {
952
725
  private handlers;
953
726
  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
727
  fire(runId: RunId): void;
959
728
  }
960
729
 
@@ -967,42 +736,36 @@ interface NagiConfig {
967
736
  readonly hooks?: FlowHooks;
968
737
  readonly logger?: Logger;
969
738
  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
739
  readonly codeVersion?: string;
978
740
  }
979
741
  interface StartOpts {
742
+ readonly runId?: RunId;
743
+ }
744
+ interface CancelOpts {
745
+ readonly reason?: string;
746
+ }
747
+ interface Wf<TFlows extends ReadonlyArray<Flow> = ReadonlyArray<Flow>> {
748
+ start<F extends TFlows[number]>(flow: F, input: FlowInput<F>, opts?: StartOpts): Promise<RunId>;
980
749
  /**
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).
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.
986
756
  *
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.
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.
991
760
  */
992
- readonly runId?: RunId;
993
- }
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. */
761
+ startById(flowId: string, input: unknown, opts?: StartOpts): Promise<RunId>;
998
762
  signal(runId: RunId, stepName: string, payload: unknown): Promise<void>;
999
- /** Construct a worker; call `run` / `runOnce` / `runUntilEmpty` on it. */
763
+ cancel(runId: RunId, opts?: CancelOpts): Promise<void>;
1000
764
  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
765
  replay(runId: RunId, opts?: ReplayOpts): Promise<void>;
766
+ queryRuns(opts?: QueryRunsOpts<FlowIdOf<TFlows>>): Promise<QueryRunsResult<FlowIdOf<TFlows>>>;
767
+ operator(): Operator;
768
+ pruneFacts(opts: PruneOpts): Promise<PruneResult>;
1006
769
  }
1007
770
  declare class NagiValidationError extends Error {
1008
771
  readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
@@ -1011,12 +774,16 @@ declare class NagiValidationError extends Error {
1011
774
  declare class NagiRuntimeError extends Error {
1012
775
  constructor(message: string);
1013
776
  }
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
- */
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
+ }
1020
787
  declare class NagiSnapshotDriftError extends Error {
1021
788
  readonly runId: RunId;
1022
789
  readonly expected: string;
@@ -1027,6 +794,37 @@ declare class NagiSnapshotDriftError extends Error {
1027
794
  readonly actual: string;
1028
795
  });
1029
796
  }
1030
- declare function nagi(config: NagiConfig): Promise<Wf>;
797
+ declare function nagiImpl<const TFlows extends ReadonlyArray<Flow>>(config: NagiConfig & {
798
+ flows: TFlows;
799
+ }): 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
+ interface NagiRunConfig extends NagiConfig {
806
+ readonly worker?: Omit<WorkerConfig, "signal">;
807
+ readonly signal?: AbortSignal;
808
+ }
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
+ interface RuntimeHandle<TFlows extends ReadonlyArray<Flow> = ReadonlyArray<Flow>> {
816
+ readonly wf: Wf<TFlows>;
817
+ stop(): Promise<void>;
818
+ }
819
+ declare function nagiRun<const TFlows extends ReadonlyArray<Flow>>(config: NagiRunConfig & {
820
+ flows: TFlows;
821
+ }): 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
+ declare const nagi: typeof nagiImpl & {
827
+ run: typeof nagiRun;
828
+ };
1031
829
 
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 };
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 };