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