@nagi-js/core 0.1.1-rc.6 → 0.1.1-rc.9
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 +125 -628
- package/dist/index.js +967 -433
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
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>;
|
|
@@ -128,246 +104,73 @@ interface TaskConfig<Input, N extends NeedsMap, Output> extends StepConfigBase<I
|
|
|
128
104
|
readonly onError?: (event: StepErrorEvent) => void | Promise<void>;
|
|
129
105
|
readonly onRetry?: (event: StepRetryEvent) => void | Promise<void>;
|
|
130
106
|
}
|
|
131
|
-
/**
|
|
132
|
-
* One signal step accepts one or more external signal names. Omitting
|
|
133
|
-
* `names` defaults to `[stepId]` (back-compat behavior). Passing `names:
|
|
134
|
-
* [...]` accepts any listed name; first arrival wins, late losers are a
|
|
135
|
-
* no-op + logged. Non-empty tuple type so `names: []` is a compile error.
|
|
136
|
-
*/
|
|
137
107
|
interface SignalConfig<Input, N extends NeedsMap, Schema extends StandardSchemaV1> extends StepConfigBase<Input, N> {
|
|
138
108
|
readonly schema: Schema;
|
|
139
109
|
readonly names?: readonly [string, ...string[]];
|
|
140
110
|
}
|
|
141
|
-
/**
|
|
142
|
-
* Discriminator mode — exhaustive at compile time. `cases` must cover every
|
|
143
|
-
* value in the discriminant union; adding a new value to the discriminant
|
|
144
|
-
* is a type error until the case is handled.
|
|
145
|
-
*/
|
|
146
|
-
interface MatchDiscriminatorConfig<Input, N extends NeedsMap, D extends string, M extends Record<D, StepMap>> {
|
|
147
|
-
readonly needs?: N;
|
|
148
|
-
readonly on: (args: {
|
|
149
|
-
readonly input: NoInfer<Input>;
|
|
150
|
-
readonly needs: NoInfer<NeedsOutputs<N>>;
|
|
151
|
-
}) => D;
|
|
152
|
-
readonly cases: {
|
|
153
|
-
readonly [K in D]: (b: Builder<Input>) => BuildResult<Input, M[K]>;
|
|
154
|
-
};
|
|
155
|
-
}
|
|
156
111
|
interface MatchArmGuard<Input, N extends NeedsMap, M extends StepMap> {
|
|
157
112
|
readonly when: (args: {
|
|
158
113
|
readonly input: NoInfer<Input>;
|
|
159
114
|
readonly needs: NoInfer<NeedsOutputs<N>>;
|
|
160
115
|
}) => boolean;
|
|
161
116
|
readonly otherwise?: never;
|
|
162
|
-
readonly build: (b: Builder<Input>) =>
|
|
117
|
+
readonly build: (b: Builder<Input>) => M;
|
|
163
118
|
}
|
|
164
119
|
interface MatchArmOtherwise<Input, M extends StepMap> {
|
|
165
120
|
readonly otherwise: true;
|
|
166
121
|
readonly when?: never;
|
|
167
|
-
readonly build: (b: Builder<Input>) =>
|
|
122
|
+
readonly build: (b: Builder<Input>) => M;
|
|
168
123
|
}
|
|
169
124
|
type MatchArm<Input, N extends NeedsMap, M extends StepMap> = MatchArmGuard<Input, N, M> | MatchArmOtherwise<Input, M>;
|
|
170
|
-
/**
|
|
171
|
-
* Inference-friendly arm shape: M is not bound, so each arm in an `arms:` tuple
|
|
172
|
-
* keeps its own StepMap (and per-step Output) through inference. The `arms`
|
|
173
|
-
* overload of `Builder.match` uses this; user-facing arms still satisfy
|
|
174
|
-
* `MatchArm<Input, N, M>` for any concrete M they construct.
|
|
175
|
-
*/
|
|
176
125
|
type MatchArmShape<Input, N extends NeedsMap> = {
|
|
177
126
|
readonly when: (args: {
|
|
178
127
|
readonly input: NoInfer<Input>;
|
|
179
128
|
readonly needs: NoInfer<NeedsOutputs<N>>;
|
|
180
129
|
}) => boolean;
|
|
181
130
|
readonly otherwise?: never;
|
|
182
|
-
readonly build: (b: Builder<Input>) =>
|
|
131
|
+
readonly build: (b: Builder<Input>) => StepMap;
|
|
183
132
|
} | {
|
|
184
133
|
readonly otherwise: true;
|
|
185
134
|
readonly when?: never;
|
|
186
|
-
readonly build: (b: Builder<Input>) =>
|
|
135
|
+
readonly build: (b: Builder<Input>) => StepMap;
|
|
187
136
|
};
|
|
188
|
-
/**
|
|
189
|
-
* Guard mode — Rust-style `match { x if guard => ... }`. Top-to-bottom,
|
|
190
|
-
* first match wins. The terminal `{ otherwise: true }` arm is required so
|
|
191
|
-
* guard mode can never silently fall through.
|
|
192
|
-
*/
|
|
193
137
|
interface MatchGuardConfig<Input, N extends NeedsMap, M extends StepMap> {
|
|
194
138
|
readonly needs?: N;
|
|
195
139
|
readonly arms: ReadonlyArray<MatchArm<Input, N, M>>;
|
|
196
140
|
}
|
|
197
|
-
/** The output of a match step is a record of each step in the chosen arm. */
|
|
198
141
|
type MatchArmOutput<M extends StepMap> = {
|
|
199
142
|
readonly [K in keyof M]: StepOutput<M[K]>;
|
|
200
143
|
};
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
[K in D]: MatchArmOutput<M[K]>;
|
|
204
|
-
}[D];
|
|
205
|
-
/**
|
|
206
|
-
* Per-entry config for `b.step(key, config)`. `Needs` is a const tuple of
|
|
207
|
-
* sibling keys that resolve against the chain's accumulator `A`.
|
|
208
|
-
*/
|
|
209
|
-
interface StepEntryConfig<Input, A extends Record<string, unknown>, Needs extends ReadonlyArray<keyof A & string>, Output> {
|
|
210
|
-
readonly needs?: Needs;
|
|
211
|
-
readonly retry?: RetryPolicy;
|
|
212
|
-
readonly timeoutMs?: Millis;
|
|
213
|
-
readonly when?: (args: {
|
|
214
|
-
readonly input: NoInfer<Input>;
|
|
215
|
-
readonly needs: {
|
|
216
|
-
readonly [P in Needs[number]]: A[P];
|
|
217
|
-
};
|
|
218
|
-
}) => boolean;
|
|
219
|
-
readonly run: (args: {
|
|
144
|
+
interface SubflowConfig<Input, N extends NeedsMap, Child extends Flow> extends StepConfigBase<Input, N> {
|
|
145
|
+
readonly input: (args: {
|
|
220
146
|
readonly input: NoInfer<Input>;
|
|
221
|
-
readonly needs:
|
|
222
|
-
|
|
223
|
-
};
|
|
224
|
-
readonly ctx: StepCtx<NoInfer<Input>>;
|
|
225
|
-
}) => Promise<Output>;
|
|
226
|
-
/** See {@link TaskConfig} for hook semantics. */
|
|
227
|
-
readonly onStart?: (event: StepStartEvent) => void | Promise<void>;
|
|
228
|
-
readonly onComplete?: (event: StepCompleteEvent & {
|
|
229
|
-
readonly output: NoInfer<Output>;
|
|
230
|
-
}) => void | Promise<void>;
|
|
231
|
-
readonly onError?: (event: StepErrorEvent) => void | Promise<void>;
|
|
232
|
-
readonly onRetry?: (event: StepRetryEvent) => void | Promise<void>;
|
|
147
|
+
readonly needs: NoInfer<NeedsOutputs<N>>;
|
|
148
|
+
}) => FlowInput<Child>;
|
|
233
149
|
}
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
* 1. **Standalone constructors** — `b.task`, `b.signal`, `b.match` each
|
|
240
|
-
* return a `Step<Output>` value the user can assign and reference. The
|
|
241
|
-
* build callback returns a `StepMap` of those values.
|
|
242
|
-
*
|
|
243
|
-
* 2. **Chain (key-first)** — `b.step(key, config)` is keyed and chainable.
|
|
244
|
-
* Each call extends the builder's accumulator `A` with `{ [Key]: Output }`,
|
|
245
|
-
* and subsequent `.step()` calls type `needs: ["sibling"]` against `A`.
|
|
246
|
-
* `b.include(key, prebuiltStep)` brings a `Step<O>` (from `b.task` /
|
|
247
|
-
* `b.signal` / `b.match`) into the chain under a key. The chain itself
|
|
248
|
-
* is returned from the build callback; `flow()` extracts the accumulator.
|
|
249
|
-
*
|
|
250
|
-
* Both styles compose in the same build callback — the chain end is the
|
|
251
|
-
* canonical result; pre-built standalone steps enter the chain via
|
|
252
|
-
* `.include(key, step)`.
|
|
253
|
-
*/
|
|
254
|
-
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> {
|
|
255
155
|
task<N extends NeedsMap, Output>(config: TaskConfig<Input, N, Output>): Step<Output>;
|
|
256
156
|
signal<N extends NeedsMap, S extends StandardSchemaV1>(config: SignalConfig<Input, N, S>): Step<InferSchemaOutput<S>>;
|
|
257
|
-
|
|
258
|
-
readonly [K in D]: (b: Builder<Input>) => BuildResult<Input, StepMap>;
|
|
259
|
-
}>(config: {
|
|
260
|
-
readonly needs?: N;
|
|
261
|
-
readonly on: (args: {
|
|
262
|
-
readonly input: NoInfer<Input>;
|
|
263
|
-
readonly needs: NoInfer<NeedsOutputs<N>>;
|
|
264
|
-
}) => D;
|
|
265
|
-
readonly cases: Cases;
|
|
266
|
-
}): Step<{
|
|
267
|
-
readonly [K in keyof Cases]: MatchArmOutput<AsStepMap<ReturnType<Cases[K]>>>;
|
|
268
|
-
}[keyof Cases]>;
|
|
157
|
+
subflow<N extends NeedsMap, Child extends Flow>(child: Child, config: SubflowConfig<Input, N, Child>): Step<SubflowStepOutput<FlowOutput<Child>>>;
|
|
269
158
|
match<N extends NeedsMap, Arms extends ReadonlyArray<MatchArmShape<Input, N>>>(config: {
|
|
270
159
|
readonly needs?: N;
|
|
271
160
|
readonly arms: Arms;
|
|
272
|
-
}): Step<MatchArmOutput<
|
|
273
|
-
/**
|
|
274
|
-
* Chainable task definition. The first arg is the persisted step id; the
|
|
275
|
-
* config follows the standalone `task` shape plus a `needs: ["sibling"]`
|
|
276
|
-
* tuple of accumulator keys. Returns the same builder typed with the new
|
|
277
|
-
* entry appended to `A`.
|
|
278
|
-
*
|
|
279
|
-
* b.step('fetchRecording', { run: async () => ({ url: '…' }) })
|
|
280
|
-
* .step('transcribe', {
|
|
281
|
-
* needs: ['fetchRecording'],
|
|
282
|
-
* run: async ({ needs }) => ({ text: needs.fetchRecording.url + '…' }),
|
|
283
|
-
* })
|
|
284
|
-
*/
|
|
285
|
-
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 & {
|
|
286
|
-
readonly [K in Key]: Output;
|
|
287
|
-
}>;
|
|
288
|
-
/**
|
|
289
|
-
* Include a pre-built `Step<O>` (from `b.task` / `b.signal` / `b.match`)
|
|
290
|
-
* into the chain under a key. The included step's output joins `A`.
|
|
291
|
-
*/
|
|
292
|
-
include<const Key extends string, S extends Step<unknown>>(key: Exclude<Key, keyof A>, step: S): Builder<Input, A & {
|
|
293
|
-
readonly [K in Key]: S extends Step<infer O> ? O : never;
|
|
294
|
-
}>;
|
|
161
|
+
}): Step<MatchArmOutput<ReturnType<Arms[number]["build"]>>>;
|
|
295
162
|
}
|
|
296
|
-
/**
|
|
297
|
-
* Acceptable shape for a build callback's return. Either a plain `StepMap`
|
|
298
|
-
* (record-literal style) or a `Builder<Input, A>` whose accumulator is
|
|
299
|
-
* extracted by `flow()`.
|
|
300
|
-
*/
|
|
301
|
-
type BuildResult<Input, M extends StepMap> = M | Builder<Input, BuilderAccumulator<M>>;
|
|
302
|
-
/** Convert a `StepMap` back to its accumulator shape `{ [K]: Output }`. */
|
|
303
|
-
type BuilderAccumulator<M extends StepMap> = {
|
|
304
|
-
readonly [K in keyof M]: M[K] extends Step<infer O> ? O : never;
|
|
305
|
-
};
|
|
306
|
-
/** Extract a `StepMap` from either a plain map or a `Builder` chain result. */
|
|
307
|
-
type AsStepMap<R> = R extends Builder<unknown, infer A> ? {
|
|
308
|
-
readonly [K in keyof A]: Step<A[K]>;
|
|
309
|
-
} : R extends StepMap ? R : never;
|
|
310
|
-
/**
|
|
311
|
-
* Modes for `FlowConcurrency`. v1 implements only `cancel-in-progress`; the
|
|
312
|
-
* union is a single literal so adding `queue` / `reject` later is a
|
|
313
|
-
* non-breaking widening rather than a new discriminator.
|
|
314
|
-
*/
|
|
315
163
|
type ConcurrencyMode = "cancel-in-progress";
|
|
316
|
-
/**
|
|
317
|
-
* Per-flow concurrency control. When set, `wf.start()` derives a group key
|
|
318
|
-
* from the validated input and applies the configured `mode` against any
|
|
319
|
-
* prior run sharing the same `(flowId, key)` pair.
|
|
320
|
-
*
|
|
321
|
-
* `cancel-in-progress`: any active prior run with the same key transitions
|
|
322
|
-
* to the `canceled` terminal state before the new run is inserted. In-flight
|
|
323
|
-
* steps on the canceled run run to completion (their facts persist), but the
|
|
324
|
-
* dispatcher stops scheduling further steps for it.
|
|
325
|
-
*/
|
|
326
164
|
interface FlowConcurrency<Input = Json> {
|
|
327
|
-
/**
|
|
328
|
-
* Derive the concurrency group key from the validated flow input.
|
|
329
|
-
* Synchronous + pure. Returning a non-string or an empty string throws
|
|
330
|
-
* `NagiValidationError` at `wf.start()` time.
|
|
331
|
-
*/
|
|
332
165
|
readonly keyFn: (input: Input) => string;
|
|
333
166
|
readonly mode: ConcurrencyMode;
|
|
334
167
|
}
|
|
335
|
-
interface FlowConfig<Id extends string, InputSchema extends StandardSchemaV1, R, Output = unknown> {
|
|
336
|
-
/** Stable persistence handle. TanStack-key shaped (kebab or snake). */
|
|
168
|
+
interface FlowConfig<Id extends string, InputSchema extends StandardSchemaV1, R extends StepMap, Output = unknown> {
|
|
337
169
|
readonly id: Id;
|
|
338
170
|
readonly input: InputSchema;
|
|
339
|
-
/**
|
|
340
|
-
* Returns either a `StepMap` (record-literal style with `b.task` / `b.signal`
|
|
341
|
-
* / `b.match`) or a chained `Builder<Input, A>` (Express-style with `b.step`
|
|
342
|
-
* / `b.include`). `flow()` extracts the assembled `StepMap` either way.
|
|
343
|
-
*/
|
|
344
171
|
readonly build: (b: Builder<InferSchemaOutput<InputSchema>>) => R;
|
|
345
|
-
|
|
346
|
-
* Compute the flow's terminal output from its step outputs. Fired once at
|
|
347
|
-
* `flow.completed` and persisted on the fact + `onFlowComplete` event.
|
|
348
|
-
* Skipped steps land as `null` in the input record at runtime even though
|
|
349
|
-
* the type claims otherwise (consistent with the "skip is transitive" lock).
|
|
350
|
-
*/
|
|
351
|
-
output?(steps: NeedsOutputs<AsStepMap<R>>): Output;
|
|
352
|
-
/**
|
|
353
|
-
* Concurrency group config. See {@link FlowConcurrency}. `keyFn` is typed
|
|
354
|
-
* against the schema's parsed output — what `b.task`'s `run({ input })`
|
|
355
|
-
* receives — so refactors to the input schema break the key derivation
|
|
356
|
-
* at compile time.
|
|
357
|
-
*/
|
|
172
|
+
output?(steps: NeedsOutputs<R>): Output;
|
|
358
173
|
readonly concurrency?: FlowConcurrency<InferSchemaOutput<InputSchema>>;
|
|
359
|
-
/**
|
|
360
|
-
* Flow-level lifecycle hooks. Like step-local hooks (see {@link TaskConfig}),
|
|
361
|
-
* these fire *before* the cross-cutting `FlowHooks` callbacks, and a thrown
|
|
362
|
-
* hook is swallowed + logged rather than failing the run.
|
|
363
|
-
*
|
|
364
|
-
* `onComplete`'s event is typed against this flow's `Output` (whatever the
|
|
365
|
-
* `output()` resolver returns).
|
|
366
|
-
*
|
|
367
|
-
* `onError` also fires when a run is canceled by a concurrency-group
|
|
368
|
-
* supersede; the event's `error.name` is `"NagiCanceledError"` and
|
|
369
|
-
* `error.cause` carries `{ canceledByRunId, concurrencyKey }`.
|
|
370
|
-
*/
|
|
371
174
|
readonly onStart?: (event: FlowStartEvent) => void | Promise<void>;
|
|
372
175
|
readonly onComplete?: (event: FlowCompleteEvent & {
|
|
373
176
|
readonly output: NoInfer<Output>;
|
|
@@ -379,22 +182,9 @@ interface Flow<Id extends string = string, InputSchema extends StandardSchemaV1
|
|
|
379
182
|
readonly input: InputSchema;
|
|
380
183
|
readonly steps: M;
|
|
381
184
|
output?(steps: NeedsOutputs<M>): Output;
|
|
382
|
-
/**
|
|
383
|
-
* Forwarded from {@link FlowConfig}; surfaced for the dispatcher.
|
|
384
|
-
*
|
|
385
|
-
* Note these use the plain (non-Output-augmented) event types — the typed
|
|
386
|
-
* narrowing lives on {@link FlowConfig}'s callbacks at build time, while
|
|
387
|
-
* the runtime form is variance-friendly so a concrete `Flow<...{x: number}>`
|
|
388
|
-
* stays assignable to `Flow<...unknown>` (the dispatcher's view).
|
|
389
|
-
*/
|
|
390
185
|
readonly onStart?: (event: FlowStartEvent) => void | Promise<void>;
|
|
391
186
|
readonly onComplete?: (event: FlowCompleteEvent) => void | Promise<void>;
|
|
392
187
|
readonly onError?: (event: FlowErrorEvent) => void | Promise<void>;
|
|
393
|
-
/**
|
|
394
|
-
* Forwarded from {@link FlowConfig.concurrency}. The runtime form widens
|
|
395
|
-
* `Input` to `Json` so a concrete `Flow<...{x: number}>` is assignable to
|
|
396
|
-
* `Flow<...unknown>` (the dispatcher's view).
|
|
397
|
-
*/
|
|
398
188
|
readonly concurrency?: FlowConcurrency<Json>;
|
|
399
189
|
}
|
|
400
190
|
type FlowInput<F> = F extends Flow<string, infer S, StepMap, unknown> ? InferSchemaOutput<S> : never;
|
|
@@ -406,6 +196,16 @@ interface FlowEvent {
|
|
|
406
196
|
}
|
|
407
197
|
interface FlowStartEvent extends FlowEvent {
|
|
408
198
|
readonly input: Json;
|
|
199
|
+
/**
|
|
200
|
+
* Set when this run was started as a subflow child. Undefined for
|
|
201
|
+
* top-level runs (start / startById). Carried in-process only — for
|
|
202
|
+
* durable linkage see FlowStartedFact.parentRunId / parentStepId.
|
|
203
|
+
*/
|
|
204
|
+
readonly parent?: {
|
|
205
|
+
readonly runId: RunId;
|
|
206
|
+
readonly stepId: StepId;
|
|
207
|
+
readonly attempt: AttemptNumber;
|
|
208
|
+
};
|
|
409
209
|
}
|
|
410
210
|
interface FlowCompleteEvent extends FlowEvent {
|
|
411
211
|
readonly output: Json;
|
|
@@ -419,13 +219,6 @@ interface StepEvent extends FlowEvent {
|
|
|
419
219
|
readonly kind: StepKind;
|
|
420
220
|
}
|
|
421
221
|
interface StepStartEvent extends StepEvent {
|
|
422
|
-
/**
|
|
423
|
-
* The resolved input for this step at the moment it starts.
|
|
424
|
-
* - Task: the value passed to `run({ input, needs, ctx })`.
|
|
425
|
-
* - Signal: `null` (signals await an external payload — no pre-execution input).
|
|
426
|
-
* - Match: `null` (the discriminator value is computed inside the match
|
|
427
|
-
* handler; the start event fires before that resolves).
|
|
428
|
-
*/
|
|
429
222
|
readonly input: Json;
|
|
430
223
|
}
|
|
431
224
|
interface StepCompleteEvent extends StepEvent {
|
|
@@ -459,25 +252,20 @@ interface FlowHooks {
|
|
|
459
252
|
interface WorkerConfig {
|
|
460
253
|
readonly concurrency?: number;
|
|
461
254
|
readonly pollIntervalMs?: Millis;
|
|
462
|
-
/** AbortSignal drives graceful drain on SIGTERM/SIGINT. */
|
|
463
255
|
readonly signal?: AbortSignal;
|
|
464
256
|
}
|
|
465
257
|
interface WorkerRunOnceOpts {
|
|
466
258
|
readonly maxSteps?: number;
|
|
467
259
|
}
|
|
468
260
|
interface WorkerRunUntilEmptyOpts {
|
|
469
|
-
/** Wall-clock deadline in `Date.now()` units. Edge runtimes have CPU/wall-time budgets. */
|
|
470
261
|
readonly deadline?: number;
|
|
471
262
|
}
|
|
472
263
|
interface WorkerRunResult {
|
|
473
264
|
readonly processed: number;
|
|
474
265
|
}
|
|
475
266
|
interface Worker {
|
|
476
|
-
/** Long-running fleet (Cloud Run service, ECS, dedicated VM). Blocks until `signal` aborts. */
|
|
477
267
|
run(): Promise<void>;
|
|
478
|
-
/** HTTP server alongside requests. Returns after up to `maxSteps` are processed. */
|
|
479
268
|
runOnce(opts?: WorkerRunOnceOpts): Promise<WorkerRunResult>;
|
|
480
|
-
/** Serverless / edge. Drains everything available within the deadline and exits. */
|
|
481
269
|
runUntilEmpty(opts?: WorkerRunUntilEmptyOpts): Promise<WorkerRunResult>;
|
|
482
270
|
}
|
|
483
271
|
type ClaimToken = string & {
|
|
@@ -489,44 +277,9 @@ interface SerializedError {
|
|
|
489
277
|
readonly stack?: string;
|
|
490
278
|
readonly cause?: Json;
|
|
491
279
|
}
|
|
492
|
-
/**
|
|
493
|
-
* Fact-ordering invariant (must hold for every Store implementation):
|
|
494
|
-
* facts persisted via `appendFact` / `completeStep` / `failStep` MUST be
|
|
495
|
-
* visible to the next `loadRunState` call. The scheduler decides what to run
|
|
496
|
-
* by projecting `RunState.steps` from the fact log, then calls `nextRunnable`
|
|
497
|
-
* — if a `step.completed` write isn't reflected in a subsequent read, the
|
|
498
|
-
* scheduler will re-enqueue or skip steps incorrectly. Adapters with read
|
|
499
|
-
* replicas must route `loadRunState` to the primary or wait for replication
|
|
500
|
-
* within a single `advance` cycle.
|
|
501
|
-
*/
|
|
502
280
|
interface Store {
|
|
503
281
|
appendFact(runId: RunId, fact: Fact): Promise<void>;
|
|
504
282
|
loadRunState(runId: RunId): Promise<RunState>;
|
|
505
|
-
/**
|
|
506
|
-
* Atomically begin a run. Inserts the `flow.started` fact and any
|
|
507
|
-
* materialized run row keyed by `runId` IFF no run with this `runId` already
|
|
508
|
-
* exists. Returns `{ started: true, canceled: [...] }` if this call created
|
|
509
|
-
* the run, `{ started: false, canceled: [] }` if the run already exists.
|
|
510
|
-
*
|
|
511
|
-
* Two concurrent `tryStartRun(runId, ...)` calls with the same `runId` must
|
|
512
|
-
* result in exactly one `flow.started` fact. Adapters enforce this at the
|
|
513
|
-
* durability layer (e.g. Postgres `INSERT ... ON CONFLICT DO NOTHING` keyed
|
|
514
|
-
* by `run_id`), NOT via app-level check-then-insert.
|
|
515
|
-
*
|
|
516
|
-
* When `concurrency` is supplied, the adapter ALSO atomically cancels any
|
|
517
|
-
* prior runs whose `(flowId, concurrency.key)` matches and whose status is
|
|
518
|
-
* still `pending` / `running`. Each canceled run gets a `flow.canceled`
|
|
519
|
-
* fact appended to its log and its materialized status updated to
|
|
520
|
-
* `canceled`. The returned `canceled` array carries the fact for each
|
|
521
|
-
* canceled run so the runtime can fire `onFlowError` post-commit.
|
|
522
|
-
*
|
|
523
|
-
* Adapters MUST serialize concurrent starts for the same
|
|
524
|
-
* `(flowId, concurrency.key)` (e.g. Postgres advisory-lock keyed on the
|
|
525
|
-
* pair) so the partial unique index on active runs is never violated.
|
|
526
|
-
*
|
|
527
|
-
* The runtime calls this exactly once at `wf.start()`. Subsequent facts go
|
|
528
|
-
* through `appendFact` as usual.
|
|
529
|
-
*/
|
|
530
283
|
tryStartRun(runId: RunId, fact: FlowStartedFact, concurrency?: {
|
|
531
284
|
readonly key: string;
|
|
532
285
|
readonly mode: ConcurrencyMode;
|
|
@@ -534,133 +287,49 @@ interface Store {
|
|
|
534
287
|
readonly started: boolean;
|
|
535
288
|
readonly canceled: ReadonlyArray<{
|
|
536
289
|
readonly runId: RunId;
|
|
537
|
-
readonly fact:
|
|
290
|
+
readonly fact: FlowCanceledByConcurrencyFact;
|
|
538
291
|
}>;
|
|
539
292
|
}>;
|
|
540
|
-
/**
|
|
541
|
-
* Returns null if the step is already claimed under a live lease. Lease
|
|
542
|
-
* duration is owned by the Store implementation; configure it on the adapter.
|
|
543
|
-
*/
|
|
544
293
|
claimStep(runId: RunId, stepId: StepId, attempt: AttemptNumber): Promise<ClaimToken | null>;
|
|
545
294
|
completeStep(runId: RunId, stepId: StepId, output: Json, fact: Fact): Promise<void>;
|
|
546
295
|
failStep(runId: RunId, stepId: StepId, error: SerializedError, fact: Fact): Promise<void>;
|
|
547
|
-
/** Memoization read — returns the persisted output of a previously completed step. */
|
|
548
296
|
getStepOutput(runId: RunId, stepId: StepId): Promise<Json | null>;
|
|
549
|
-
/** `ctx.once` durable record. */
|
|
550
297
|
recordOnce(runId: RunId, stepId: StepId, scope: string, value: Json): Promise<void>;
|
|
551
298
|
getOnce(runId: RunId, stepId: StepId, scope: string): Promise<Json | null>;
|
|
552
|
-
/**
|
|
553
|
-
* Run a task step's handler inside an adapter-owned transaction.
|
|
554
|
-
*
|
|
555
|
-
* Implementations open a transaction (or equivalent atomic scope), invoke
|
|
556
|
-
* `body(tx)`, and on a successful return persist the returned fact
|
|
557
|
-
* atomically with any writes the handler made via `ctx.tx`. The output is
|
|
558
|
-
* returned to the caller; for `step.failed` facts the output is ignored
|
|
559
|
-
* (callers should still return the placeholder shape the type requires).
|
|
560
|
-
*
|
|
561
|
-
* Contract:
|
|
562
|
-
* - If `body` throws, the transaction is rolled back and the error
|
|
563
|
-
* propagates. The caller (dispatcher) is responsible for recording the
|
|
564
|
-
* failure via `failStep` in a separate scope so the failure survives
|
|
565
|
-
* even when domain writes do not.
|
|
566
|
-
* - On a returned `step.completed` fact, the same atomic scope must also
|
|
567
|
-
* record the step output (such that `getStepOutput` reflects it) and
|
|
568
|
-
* release any worker lease held for `(runId, stepId, attempt)`.
|
|
569
|
-
*
|
|
570
|
-
* For adapters with no real transaction (in-memory, sqlite without WAL),
|
|
571
|
-
* `tx` is passed as `undefined as Tx` and the write is non-atomic — those
|
|
572
|
-
* adapters are not used with `ctx.tx` writes.
|
|
573
|
-
*/
|
|
574
299
|
runStep<T extends Json>(runId: RunId, stepId: StepId, attempt: AttemptNumber, body: (tx: Tx) => Promise<{
|
|
575
300
|
readonly output: T;
|
|
576
|
-
readonly fact: StepCompletedFact | StepFailedFact;
|
|
301
|
+
readonly fact: StepCompletedFact | StepFailedFact | StepCanceledFact;
|
|
577
302
|
}>): Promise<T>;
|
|
578
|
-
/**
|
|
579
|
-
* Deduped store of canonical flow DAGs, keyed by content hash. Inserts are
|
|
580
|
-
* idempotent — the same `(flowHash, dag)` may be written by many concurrent
|
|
581
|
-
* boots; only the first physical row survives. Subsequent writes are
|
|
582
|
-
* no-ops.
|
|
583
|
-
*
|
|
584
|
-
* Adapters MUST enforce this at the durability layer (e.g. Postgres
|
|
585
|
-
* `INSERT ... ON CONFLICT (flow_hash) DO NOTHING`).
|
|
586
|
-
*/
|
|
587
303
|
upsertSnapshot(args: {
|
|
588
304
|
readonly flowHash: string;
|
|
589
305
|
readonly flowId: string;
|
|
590
306
|
readonly dag: Json;
|
|
591
307
|
}): Promise<void>;
|
|
592
|
-
/**
|
|
593
|
-
* Read the currently-published hash for a flow id. Returns `null` if no
|
|
594
|
-
* `flow_ref` row exists yet — first boot of a never-published flow.
|
|
595
|
-
*/
|
|
596
308
|
getRef(flowId: string): Promise<string | null>;
|
|
597
|
-
/**
|
|
598
|
-
* Atomically set the published hash for a flow id. Last writer wins; the
|
|
599
|
-
* audit trail of ref changes lives in {@link appendGlobalFact} as
|
|
600
|
-
* `flow_ref.updated`.
|
|
601
|
-
*
|
|
602
|
-
* Adapters MUST enforce atomicity at the durability layer (e.g. Postgres
|
|
603
|
-
* `INSERT ... ON CONFLICT (flow_id) DO UPDATE`).
|
|
604
|
-
*/
|
|
605
309
|
setRef(flowId: string, flowHash: string): Promise<void>;
|
|
606
|
-
/**
|
|
607
|
-
* Load a snapshot by its content hash. Returns `null` if no snapshot with
|
|
608
|
-
* this hash has been recorded — e.g., the deployment is replaying a run
|
|
609
|
-
* whose pinned topology was never seen by this store.
|
|
610
|
-
*/
|
|
611
310
|
loadSnapshot(flowHash: string): Promise<{
|
|
612
311
|
readonly flowId: string;
|
|
613
312
|
readonly dag: Json;
|
|
614
313
|
} | null>;
|
|
615
|
-
/**
|
|
616
|
-
* Append a non-run-scoped fact. See {@link GlobalFact} for the union.
|
|
617
|
-
* Currently only `flow_ref.updated` events flow through this method.
|
|
618
|
-
*/
|
|
619
314
|
appendGlobalFact(fact: GlobalFact): Promise<void>;
|
|
620
|
-
/**
|
|
621
|
-
* Discover runs by their input + flow + status. See {@link QueryRunsOpts}
|
|
622
|
-
* and {@link Wf.queryRuns} (in `runtime.ts`) for the public contract.
|
|
623
|
-
*
|
|
624
|
-
* Adapters MUST order results by `(startedAt DESC, runId DESC)` so cursor
|
|
625
|
-
* pagination is stable across calls. Adapters MUST treat
|
|
626
|
-
* `opts.where.input` as JSONB containment (Postgres `@>` semantics —
|
|
627
|
-
* the row's input is a superset of the filter object, recursively).
|
|
628
|
-
*/
|
|
629
315
|
queryRuns(opts: QueryRunsOpts): Promise<QueryRunsResult>;
|
|
316
|
+
listChildren(parentRunId: RunId): Promise<ReadonlyArray<RunId>>;
|
|
317
|
+
pruneFacts(opts: Required<PruneOpts>): Promise<PruneResult>;
|
|
630
318
|
}
|
|
631
319
|
interface QueryRunsWhere {
|
|
632
320
|
readonly flowId?: string;
|
|
633
321
|
readonly status?: RunStatus | ReadonlyArray<RunStatus>;
|
|
634
|
-
/**
|
|
635
|
-
* JSONB containment against `flow.started.input`. The stored input is a
|
|
636
|
-
* superset of this object — recursive on nested objects, exact on
|
|
637
|
-
* arrays/scalars. Example: `{ videoId: 'abc' }` matches
|
|
638
|
-
* `{ videoId: 'abc', userId: 7 }`.
|
|
639
|
-
*
|
|
640
|
-
* Containment only — no JSONPath, no operators. Combine keys for AND.
|
|
641
|
-
*/
|
|
642
322
|
readonly input?: Record<string, Json>;
|
|
643
323
|
}
|
|
644
|
-
/**
|
|
645
|
-
* Options for {@link Wf.queryRuns}.
|
|
646
|
-
*
|
|
647
|
-
* Encoded as a discriminated union on `latest` so the type system rejects
|
|
648
|
-
* `{ latest: true, limit, cursor }` at compile time — those fields are
|
|
649
|
-
* meaningless when only one row is requested. Adapters still validate at
|
|
650
|
-
* runtime as defense-in-depth.
|
|
651
|
-
*/
|
|
652
324
|
type QueryRunsOpts = {
|
|
653
325
|
readonly where?: QueryRunsWhere;
|
|
654
|
-
/** Return at most one run — the most recently started match. */
|
|
655
326
|
readonly latest: true;
|
|
656
327
|
readonly limit?: never;
|
|
657
328
|
readonly cursor?: never;
|
|
658
329
|
} | {
|
|
659
330
|
readonly where?: QueryRunsWhere;
|
|
660
331
|
readonly latest?: false;
|
|
661
|
-
/** Page size. Default 50, max 500. */
|
|
662
332
|
readonly limit?: number;
|
|
663
|
-
/** Opaque cursor from a previous `queryRuns` call. */
|
|
664
333
|
readonly cursor?: string;
|
|
665
334
|
};
|
|
666
335
|
interface RunSummary {
|
|
@@ -673,9 +342,19 @@ interface RunSummary {
|
|
|
673
342
|
}
|
|
674
343
|
interface QueryRunsResult {
|
|
675
344
|
readonly runs: ReadonlyArray<RunSummary>;
|
|
676
|
-
/** Pass to the next `queryRuns` to resume. `null` when no more rows. */
|
|
677
345
|
readonly cursor: string | null;
|
|
678
346
|
}
|
|
347
|
+
type PrunableStatus = Extract<RunStatus, "completed" | "failed" | "canceled">;
|
|
348
|
+
interface PruneOpts {
|
|
349
|
+
readonly olderThan: Date;
|
|
350
|
+
readonly statuses?: ReadonlyArray<PrunableStatus>;
|
|
351
|
+
readonly batchSize?: number;
|
|
352
|
+
readonly keepSummary?: boolean;
|
|
353
|
+
}
|
|
354
|
+
interface PruneResult {
|
|
355
|
+
readonly runsPruned: number;
|
|
356
|
+
readonly factsPruned: number;
|
|
357
|
+
}
|
|
679
358
|
interface QueueMessage {
|
|
680
359
|
readonly receipt: string;
|
|
681
360
|
readonly runId: RunId;
|
|
@@ -687,11 +366,8 @@ interface QueueDequeueOpts {
|
|
|
687
366
|
readonly count: number;
|
|
688
367
|
}
|
|
689
368
|
interface QueueEnqueueOpts {
|
|
690
|
-
/** Attempt number to publish. Defaults to 1. The dispatcher controls increments. */
|
|
691
369
|
readonly attempt?: AttemptNumber;
|
|
692
|
-
/** Visibility delay — the message becomes dequeueable after `delayMs`. */
|
|
693
370
|
readonly delayMs?: Millis;
|
|
694
|
-
/** Adapter-specific extra data. Core never reads this. */
|
|
695
371
|
readonly payload?: Json;
|
|
696
372
|
}
|
|
697
373
|
interface Queue {
|
|
@@ -705,21 +381,13 @@ interface Queue {
|
|
|
705
381
|
}
|
|
706
382
|
interface Clock {
|
|
707
383
|
now(): Date;
|
|
708
|
-
/** Resolves when `ms` has elapsed or `signal` aborts. */
|
|
709
384
|
sleep(ms: Millis, signal?: AbortSignal): Promise<void>;
|
|
710
|
-
/** Persistent timer — wakes the scheduler at `at` for `(runId, stepId)`. */
|
|
711
385
|
schedule(at: Date, runId: RunId, stepId: StepId): Promise<void>;
|
|
712
386
|
}
|
|
713
|
-
/**
|
|
714
|
-
* Wakes the scheduler when there's work to do. Default impl polls via the
|
|
715
|
-
* Queue plugin; Postgres adapter offers a NOTIFY/LISTEN variant.
|
|
716
|
-
* Per the sharding-safety lock: the handler receives a `runId` — there is no
|
|
717
|
-
* global tick.
|
|
718
|
-
*/
|
|
719
387
|
interface Trigger {
|
|
720
388
|
subscribe(handler: (runId: RunId) => void): () => void;
|
|
721
389
|
}
|
|
722
|
-
type FactKind = "flow.started" | "flow.completed" | "flow.failed" | "flow.canceled" | "step.started" | "step.completed" | "step.failed" | "step.retried" | "step.skipped" | "step.reset" | "signal.sent" | "signal.received" | "once.recorded" | "match.arm-selected";
|
|
390
|
+
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";
|
|
723
391
|
interface FactBase {
|
|
724
392
|
readonly runId: RunId;
|
|
725
393
|
readonly at: Date;
|
|
@@ -728,34 +396,14 @@ interface FlowStartedFact extends FactBase {
|
|
|
728
396
|
readonly kind: "flow.started";
|
|
729
397
|
readonly flowId: string;
|
|
730
398
|
readonly input: Json;
|
|
731
|
-
/**
|
|
732
|
-
* Content hash of the canonical flow DAG at the moment this run started.
|
|
733
|
-
* Pins the run to a specific topology; `wf.replay()` reads this to detect
|
|
734
|
-
* snapshot drift. Optional in v0 — legacy runs from before the snapshot
|
|
735
|
-
* store landed have `undefined`. After a soak period it becomes required.
|
|
736
|
-
*/
|
|
737
399
|
readonly flowHash?: string;
|
|
738
|
-
/**
|
|
739
|
-
* Free-form handler-code identifier, typically a git SHA. Sourced from
|
|
740
|
-
* `nagi({ codeVersion })`. Captures handler-source drift orthogonally to
|
|
741
|
-
* `flowHash` (which only captures topology). See RFC 0001
|
|
742
|
-
* "Topology vs handler code."
|
|
743
|
-
*/
|
|
744
400
|
readonly codeVersion?: string;
|
|
401
|
+
readonly parentRunId?: RunId;
|
|
402
|
+
readonly parentStepId?: StepId;
|
|
745
403
|
}
|
|
746
|
-
/**
|
|
747
|
-
* A non-run-scoped event, recorded as a side effect of nagi runtime activity
|
|
748
|
-
* that has no specific `runId`. Lives in the `nagi.global_fact` table.
|
|
749
|
-
*
|
|
750
|
-
* Per RFC 0001: when nagi boots and a flow's canonical hash differs from the
|
|
751
|
-
* currently-published one, the runtime updates `flow_ref` and appends a
|
|
752
|
-
* `flow_ref.updated` global fact. The audit trail of ref changes is queryable
|
|
753
|
-
* independently of any single run.
|
|
754
|
-
*/
|
|
755
404
|
interface FlowRefUpdatedFact {
|
|
756
405
|
readonly kind: "flow_ref.updated";
|
|
757
406
|
readonly flowId: string;
|
|
758
|
-
/** Previous hash, or null when this is the first publish of `flowId`. */
|
|
759
407
|
readonly from: string | null;
|
|
760
408
|
readonly to: string;
|
|
761
409
|
readonly at: Date;
|
|
@@ -769,19 +417,26 @@ interface FlowFailedFact extends FactBase {
|
|
|
769
417
|
readonly kind: "flow.failed";
|
|
770
418
|
readonly error: SerializedError;
|
|
771
419
|
}
|
|
772
|
-
|
|
773
|
-
* Recorded on a prior run when a new `wf.start()` with the same concurrency
|
|
774
|
-
* group supersedes it. The fact lives in the canceled run's fact log (not
|
|
775
|
-
* the new run's) — observers reading that run's history see exactly when and
|
|
776
|
-
* why it was canceled.
|
|
777
|
-
*/
|
|
778
|
-
interface FlowCanceledFact extends FactBase {
|
|
420
|
+
interface FlowCanceledByConcurrencyFact extends FactBase {
|
|
779
421
|
readonly kind: "flow.canceled";
|
|
780
|
-
|
|
422
|
+
readonly cause: "concurrency";
|
|
781
423
|
readonly canceledByRunId: RunId;
|
|
782
|
-
/** The shared concurrency key between this run and `canceledByRunId`. */
|
|
783
424
|
readonly concurrencyKey: string;
|
|
784
425
|
}
|
|
426
|
+
interface FlowCanceledExplicitlyFact extends FactBase {
|
|
427
|
+
readonly kind: "flow.canceled";
|
|
428
|
+
readonly cause: "explicit";
|
|
429
|
+
readonly reason: string;
|
|
430
|
+
readonly note?: string;
|
|
431
|
+
}
|
|
432
|
+
interface FlowCanceledByOperatorFact extends FactBase {
|
|
433
|
+
readonly kind: "flow.canceled";
|
|
434
|
+
readonly cause: "operator";
|
|
435
|
+
readonly actor: string;
|
|
436
|
+
readonly reason: string;
|
|
437
|
+
readonly note?: string;
|
|
438
|
+
}
|
|
439
|
+
type FlowCanceledFact = FlowCanceledByConcurrencyFact | FlowCanceledExplicitlyFact | FlowCanceledByOperatorFact;
|
|
785
440
|
interface StepStartedFact extends FactBase {
|
|
786
441
|
readonly kind: "step.started";
|
|
787
442
|
readonly stepId: StepId;
|
|
@@ -799,6 +454,12 @@ interface StepFailedFact extends FactBase {
|
|
|
799
454
|
readonly attempt: AttemptNumber;
|
|
800
455
|
readonly error: SerializedError;
|
|
801
456
|
}
|
|
457
|
+
interface StepCanceledFact extends FactBase {
|
|
458
|
+
readonly kind: "step.canceled";
|
|
459
|
+
readonly stepId: StepId;
|
|
460
|
+
readonly attempt: AttemptNumber;
|
|
461
|
+
readonly error?: SerializedError;
|
|
462
|
+
}
|
|
802
463
|
interface StepRetriedFact extends FactBase {
|
|
803
464
|
readonly kind: "step.retried";
|
|
804
465
|
readonly stepId: StepId;
|
|
@@ -808,7 +469,10 @@ interface StepRetriedFact extends FactBase {
|
|
|
808
469
|
interface StepSkippedFact extends FactBase {
|
|
809
470
|
readonly kind: "step.skipped";
|
|
810
471
|
readonly stepId: StepId;
|
|
811
|
-
readonly reason: "when-false" | "transitive";
|
|
472
|
+
readonly reason: "when-false" | "transitive" | "manual";
|
|
473
|
+
readonly actor?: string;
|
|
474
|
+
readonly note?: string;
|
|
475
|
+
readonly cascade?: "skip" | "continue";
|
|
812
476
|
}
|
|
813
477
|
interface SignalSentFact extends FactBase {
|
|
814
478
|
readonly kind: "signal.sent";
|
|
@@ -819,11 +483,6 @@ interface SignalReceivedFact extends FactBase {
|
|
|
819
483
|
readonly kind: "signal.received";
|
|
820
484
|
readonly stepId: StepId;
|
|
821
485
|
readonly payload: Json;
|
|
822
|
-
/**
|
|
823
|
-
* The alias the caller sent, when the resolved signal step accepts
|
|
824
|
-
* multiple names (or a single name != stepId). Absent when the incoming
|
|
825
|
-
* name equals the step id — the back-compat single-name case.
|
|
826
|
-
*/
|
|
827
486
|
readonly signalName?: string;
|
|
828
487
|
}
|
|
829
488
|
interface OnceRecordedFact extends FactBase {
|
|
@@ -837,23 +496,23 @@ interface MatchArmSelectedFact extends FactBase {
|
|
|
837
496
|
readonly stepId: StepId;
|
|
838
497
|
readonly arm: string;
|
|
839
498
|
}
|
|
840
|
-
/**
|
|
841
|
-
* Marks a step as cleared from the projected `RunState.steps` so the next
|
|
842
|
-
* `nextRunnable()` pass treats it (and any cascaded descendants) as runnable
|
|
843
|
-
* again. Emitted by `wf.replay(runId, { from })` — one fact per step that the
|
|
844
|
-
* runtime resolved as part of the cascade. The user-named step has
|
|
845
|
-
* `cascadedFrom === undefined`; transitively reset descendants record the
|
|
846
|
-
* originating step so read-side UIs can group them.
|
|
847
|
-
*/
|
|
848
499
|
interface StepResetFact extends FactBase {
|
|
849
500
|
readonly kind: "step.reset";
|
|
850
501
|
readonly stepId: StepId;
|
|
851
|
-
/** The user-named `from` step that caused this reset, when this fact is a cascaded descendant. */
|
|
852
502
|
readonly cascadedFrom?: StepId;
|
|
503
|
+
readonly actor?: string;
|
|
504
|
+
readonly note?: string;
|
|
505
|
+
}
|
|
506
|
+
interface StepAbortRequestedFact extends FactBase {
|
|
507
|
+
readonly kind: "step.abort-requested";
|
|
508
|
+
readonly stepId: StepId;
|
|
509
|
+
readonly attempt: AttemptNumber;
|
|
510
|
+
readonly actor: string;
|
|
511
|
+
readonly note?: string;
|
|
853
512
|
}
|
|
854
|
-
type Fact = FlowStartedFact | FlowCompletedFact | FlowFailedFact | FlowCanceledFact | StepStartedFact | StepCompletedFact | StepFailedFact | StepRetriedFact | StepSkippedFact | StepResetFact | SignalSentFact | SignalReceivedFact | OnceRecordedFact | MatchArmSelectedFact;
|
|
513
|
+
type Fact = FlowStartedFact | FlowCompletedFact | FlowFailedFact | FlowCanceledFact | StepStartedFact | StepCompletedFact | StepFailedFact | StepCanceledFact | StepRetriedFact | StepSkippedFact | StepResetFact | StepAbortRequestedFact | SignalSentFact | SignalReceivedFact | OnceRecordedFact | MatchArmSelectedFact;
|
|
855
514
|
type RunStatus = "pending" | "running" | "completed" | "failed" | "canceled";
|
|
856
|
-
type StepStatus = "pending" | "running" | "completed" | "failed" | "skipped";
|
|
515
|
+
type StepStatus = "pending" | "running" | "completed" | "failed" | "canceled" | "skipped";
|
|
857
516
|
interface StepState {
|
|
858
517
|
readonly stepId: StepId;
|
|
859
518
|
readonly status: StepStatus;
|
|
@@ -867,82 +526,37 @@ interface RunState {
|
|
|
867
526
|
readonly status: RunStatus;
|
|
868
527
|
readonly steps: Readonly<Record<StepId, StepState>>;
|
|
869
528
|
readonly facts: ReadonlyArray<Fact>;
|
|
870
|
-
/** Content hash of the canonical flow DAG this run is pinned to. */
|
|
871
529
|
readonly flowHash?: string;
|
|
872
|
-
/** Handler-code identifier (typically a git SHA) recorded at run start. */
|
|
873
530
|
readonly codeVersion?: string;
|
|
874
531
|
}
|
|
875
532
|
type ReplayMode = "inspect" | "continue";
|
|
876
533
|
interface ReplayOpts {
|
|
877
534
|
readonly mode: ReplayMode;
|
|
878
|
-
/**
|
|
879
|
-
* When true, allow replays to proceed even if the live flow's canonical
|
|
880
|
-
* hash differs from the snapshot pinned to the run. Scheduling decisions
|
|
881
|
-
* come from the pinned snapshot; handler bodies are resolved from the
|
|
882
|
-
* currently-registered flow by step id (best-effort).
|
|
883
|
-
*
|
|
884
|
-
* When false (default), drift throws `NagiSnapshotDriftError`.
|
|
885
|
-
*/
|
|
886
535
|
readonly allowDrift?: boolean;
|
|
887
|
-
/**
|
|
888
|
-
* Whether step / flow lifecycle hooks (both the step-local ones on
|
|
889
|
-
* `TaskConfig` / `FlowConfig` and the cross-cutting `FlowHooks`) fire during
|
|
890
|
-
* replay. Defaults to `true` — replay re-executes steps via the idempotent
|
|
891
|
-
* dispatcher and emits the same observable lifecycle. Set to `false` for
|
|
892
|
-
* backfills or inspection-style replays where re-emitting webhooks would
|
|
893
|
-
* dual-publish.
|
|
894
|
-
*/
|
|
895
536
|
readonly fireHooks?: boolean;
|
|
896
|
-
/**
|
|
897
|
-
* Replay starting from a specific step instead of the default "first
|
|
898
|
-
* incomplete" behavior. The runtime appends `step.reset` facts for `from`
|
|
899
|
-
* and every transitive descendant, then re-dispatches — completed steps
|
|
900
|
-
* downstream of `from` re-run, completed steps upstream are preserved.
|
|
901
|
-
*
|
|
902
|
-
* - Throws `NagiValidationError` if `from` is not a registered step in the
|
|
903
|
-
* effective flow (the snapshot topology under drift + `allowDrift`, else
|
|
904
|
-
* the live flow).
|
|
905
|
-
* - Throws `NagiRuntimeError` if the run is still `running` — resetting
|
|
906
|
-
* mid-flight races in-flight workers.
|
|
907
|
-
* - Ignored under `mode: "inspect"` (inspect remains side-effect-free).
|
|
908
|
-
*/
|
|
909
537
|
readonly from?: StepId;
|
|
910
538
|
}
|
|
539
|
+
interface OperatorAuditOpts {
|
|
540
|
+
readonly actor: string;
|
|
541
|
+
readonly note?: string;
|
|
542
|
+
}
|
|
543
|
+
interface OperatorSkipOpts extends OperatorAuditOpts {
|
|
544
|
+
readonly cascade?: "skip" | "continue";
|
|
545
|
+
}
|
|
546
|
+
interface Operator {
|
|
547
|
+
skip(runId: RunId, stepId: StepId, opts: OperatorSkipOpts): Promise<void>;
|
|
548
|
+
retry(runId: RunId, stepId: StepId, opts: OperatorAuditOpts): Promise<void>;
|
|
549
|
+
abort(runId: RunId, opts: OperatorAuditOpts): Promise<void>;
|
|
550
|
+
}
|
|
911
551
|
|
|
912
|
-
|
|
913
|
-
* Construct a flow.
|
|
914
|
-
*
|
|
915
|
-
* 1. Run `build(b)` to collect the user's StepMap. Each call to `b.task` /
|
|
916
|
-
* `b.signal` / `b.match` produced a Step with `id: ""` and a captured def
|
|
917
|
-
* (which may reference upstream Step values from earlier in the closure).
|
|
918
|
-
* Match defs additionally hold their arms' nested StepMaps on `_nested`.
|
|
919
|
-
* 2. Walk the returned map *recursively*, descending into match arms. Each
|
|
920
|
-
* step gets an id derived from its position: top-level keys verbatim,
|
|
921
|
-
* nested arm steps namespaced as `<matchKey>.<armId>.<stepKey>`.
|
|
922
|
-
* 3. Rewrite every def's `needs` so each upstream Step value carries its
|
|
923
|
-
* assigned id. Nested-arm step defs additionally get a `parentMatch`
|
|
924
|
-
* annotation so the scheduler can gate them on arm selection.
|
|
925
|
-
* 4. Promote `MatchArmDef._nested` → `MatchArmDef.stepIds` (the namespaced
|
|
926
|
-
* IDs of the arm's nested steps), then drop `_nested`.
|
|
927
|
-
*/
|
|
928
|
-
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>;
|
|
552
|
+
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>;
|
|
929
553
|
|
|
930
|
-
/**
|
|
931
|
-
* Canonical retry shape. Defaults are materialized explicitly so equivalent
|
|
932
|
-
* retry configs hash identically regardless of source-side omission style.
|
|
933
|
-
* `retryOn` is dropped — it's a function, not serializable.
|
|
934
|
-
*/
|
|
935
554
|
interface CanonicalRetryPolicy {
|
|
936
555
|
readonly maxAttempts: number;
|
|
937
556
|
readonly backoff: BackoffStrategy;
|
|
938
557
|
readonly initialDelayMs: Millis;
|
|
939
558
|
readonly maxDelayMs: Millis;
|
|
940
559
|
}
|
|
941
|
-
/**
|
|
942
|
-
* Canonical schema fingerprint. v0 hashes `validate.toString()` alongside
|
|
943
|
-
* runtime-stable `vendor` + `version` — best-effort, breaks under minification.
|
|
944
|
-
* Documented as a known limit in RFC 0001.
|
|
945
|
-
*/
|
|
946
560
|
interface CanonicalSchema {
|
|
947
561
|
readonly vendor: string;
|
|
948
562
|
readonly version: number;
|
|
@@ -952,73 +566,31 @@ interface CanonicalMatchArm {
|
|
|
952
566
|
readonly id: string;
|
|
953
567
|
readonly otherwise?: true;
|
|
954
568
|
readonly whenHash?: string;
|
|
955
|
-
/** Namespaced IDs of nested steps for this arm, sorted lexicographically. */
|
|
956
569
|
readonly stepIds: readonly StepId[];
|
|
957
570
|
}
|
|
958
571
|
interface CanonicalStep {
|
|
959
572
|
readonly id: StepId;
|
|
960
573
|
readonly kind: StepKind;
|
|
961
|
-
/** Upstream step ids the step depends on, sorted lexicographically. */
|
|
962
574
|
readonly needs: readonly StepId[];
|
|
963
575
|
readonly whenHash?: string;
|
|
964
576
|
readonly retry?: CanonicalRetryPolicy;
|
|
965
577
|
readonly timeoutMs?: Millis;
|
|
966
578
|
readonly signalSchema?: CanonicalSchema;
|
|
967
|
-
/**
|
|
968
|
-
* External signal names this step accepts, sorted lexicographically. Only
|
|
969
|
-
* present when the caller supplied `name` / `names` on `b.signal`; absent
|
|
970
|
-
* for the default "name == step id" case so pre-RFC-0004 flows hash
|
|
971
|
-
* byte-identically.
|
|
972
|
-
*/
|
|
973
579
|
readonly signalNames?: readonly string[];
|
|
974
|
-
readonly matchMode?: "discriminator" | "guard";
|
|
975
|
-
readonly matchOnHash?: string;
|
|
976
580
|
readonly matchArms?: readonly CanonicalMatchArm[];
|
|
581
|
+
readonly childFlowId?: string;
|
|
582
|
+
readonly subflowInputHash?: string;
|
|
977
583
|
}
|
|
978
584
|
interface CanonicalDag {
|
|
979
585
|
readonly flowId: string;
|
|
980
586
|
readonly inputSchema: CanonicalSchema;
|
|
981
|
-
/** Steps sorted by `id` lexicographically — insertion order is ignored. */
|
|
982
587
|
readonly steps: readonly CanonicalStep[];
|
|
983
588
|
}
|
|
984
|
-
/**
|
|
985
|
-
* Build the canonical DAG for a flow.
|
|
986
|
-
*
|
|
987
|
-
* Stable across cosmetic source changes (step-key reorder, needs-key reorder)
|
|
988
|
-
* and different across topology changes (added/removed steps, edge changes,
|
|
989
|
-
* `when` flips, retry edits, timeout edits).
|
|
990
|
-
*
|
|
991
|
-
* Handler `run` bodies are intentionally NOT part of the hash — see RFC 0001
|
|
992
|
-
* "Topology vs handler code." Use `nagi({ codeVersion })` (typically a git
|
|
993
|
-
* SHA) to capture handler-code drift orthogonally.
|
|
994
|
-
*
|
|
995
|
-
* Async because predicate/schema source bodies are sha256'd via
|
|
996
|
-
* `crypto.subtle` so the stored `dag` JSON stays compact.
|
|
997
|
-
*/
|
|
998
589
|
declare function canonicalize(flow: Flow): Promise<CanonicalDag>;
|
|
999
|
-
/**
|
|
1000
|
-
* Compute the sha256 hex digest of a canonical DAG. Uses Web Crypto
|
|
1001
|
-
* (`crypto.subtle.digest`) which is available in Node ≥ 19, modern browsers,
|
|
1002
|
-
* Cloudflare Workers, Deno, and Bun.
|
|
1003
|
-
*
|
|
1004
|
-
* The DAG is serialized via {@link stableStringify} so object-key order is
|
|
1005
|
-
* deterministic. Two equivalent DAGs produce byte-identical input bytes.
|
|
1006
|
-
*/
|
|
1007
590
|
declare function sha256Canonical(dag: CanonicalDag): Promise<string>;
|
|
1008
|
-
/**
|
|
1009
|
-
* Compute a structural fingerprint over a set of registered flows. Used as
|
|
1010
|
-
* the default value of `nagi({ codeVersion })` when the caller omits it.
|
|
1011
|
-
*
|
|
1012
|
-
* Per-flow projection reuses {@link canonicalize} unchanged — so this hash
|
|
1013
|
-
* and each flow's snapshot `flowHash` share one canonical definition and
|
|
1014
|
-
* cannot drift apart. Equivalent flow sets produce byte-identical hashes;
|
|
1015
|
-
* adding/removing a flow, renaming a flow id, or any structural step change
|
|
1016
|
-
* moves the result. `run`-body edits do not.
|
|
1017
|
-
*/
|
|
1018
591
|
declare function fingerprintFlows(flows: ReadonlyArray<Flow>): Promise<string>;
|
|
1019
592
|
|
|
1020
|
-
|
|
1021
|
-
type SnapshotChangedField = "kind" | "when" | "retry" | "timeoutMs" | "signalSchema" | "matchMode" | "matchOn" | "matchArms";
|
|
593
|
+
type SnapshotChangedField = "kind" | "when" | "retry" | "timeoutMs" | "signalSchema" | "matchArms";
|
|
1022
594
|
interface SnapshotChangedEdge {
|
|
1023
595
|
readonly from: StepId;
|
|
1024
596
|
readonly to: StepId;
|
|
@@ -1029,22 +601,6 @@ interface SnapshotChangedField_ {
|
|
|
1029
601
|
readonly stepId: StepId;
|
|
1030
602
|
readonly field: SnapshotChangedField;
|
|
1031
603
|
}
|
|
1032
|
-
/**
|
|
1033
|
-
* Structural delta between two snapshots — added/removed steps, added/removed
|
|
1034
|
-
* edges, per-field topology changes on shared steps.
|
|
1035
|
-
*
|
|
1036
|
-
* Pure function over canonical DAGs. The output mirrors the RFC 0001 shape:
|
|
1037
|
-
*
|
|
1038
|
-
* {
|
|
1039
|
-
* addedSteps,
|
|
1040
|
-
* removedSteps,
|
|
1041
|
-
* changedEdges, // append-or-remove edges between shared steps
|
|
1042
|
-
* changedPredicates // when / retry / timeoutMs / schema / match changes
|
|
1043
|
-
* }
|
|
1044
|
-
*
|
|
1045
|
-
* "Changed" means the canonical hash-relevant value differs. For predicates
|
|
1046
|
-
* this is best-effort under the same source-hash limit as canonicalize.
|
|
1047
|
-
*/
|
|
1048
604
|
interface SnapshotDiff {
|
|
1049
605
|
readonly addedSteps: readonly StepId[];
|
|
1050
606
|
readonly removedSteps: readonly StepId[];
|
|
@@ -1064,14 +620,10 @@ declare class InMemoryStore implements Store {
|
|
|
1064
620
|
private readonly snapshots;
|
|
1065
621
|
private readonly refs;
|
|
1066
622
|
private readonly globalFacts;
|
|
1067
|
-
/**
|
|
1068
|
-
* The runId currently holding the active slot for `flowId::concurrencyKey`.
|
|
1069
|
-
* Updated on `tryStartRun` (set when concurrency is supplied) and on
|
|
1070
|
-
* terminal facts (cleared via {@link keyByActiveRun}).
|
|
1071
|
-
*/
|
|
1072
623
|
private readonly activeByKey;
|
|
1073
|
-
/** Reverse lookup so terminal facts can free the slot in O(1). */
|
|
1074
624
|
private readonly keyByActiveRun;
|
|
625
|
+
private readonly childrenByParent;
|
|
626
|
+
private readonly summaries;
|
|
1075
627
|
private readonly leaseMs;
|
|
1076
628
|
constructor(opts?: InMemoryStoreOpts);
|
|
1077
629
|
appendFact(runId: RunId, fact: Fact): Promise<void>;
|
|
@@ -1082,9 +634,10 @@ declare class InMemoryStore implements Store {
|
|
|
1082
634
|
readonly started: boolean;
|
|
1083
635
|
readonly canceled: ReadonlyArray<{
|
|
1084
636
|
readonly runId: RunId;
|
|
1085
|
-
readonly fact:
|
|
637
|
+
readonly fact: FlowCanceledByConcurrencyFact;
|
|
1086
638
|
}>;
|
|
1087
639
|
}>;
|
|
640
|
+
listChildren(parentRunId: RunId): Promise<ReadonlyArray<RunId>>;
|
|
1088
641
|
loadRunState(runId: RunId): Promise<RunState>;
|
|
1089
642
|
claimStep(runId: RunId, stepId: StepId, attempt: AttemptNumber): Promise<ClaimToken | null>;
|
|
1090
643
|
completeStep(runId: RunId, stepId: StepId, output: Json, fact: Fact): Promise<void>;
|
|
@@ -1094,7 +647,7 @@ declare class InMemoryStore implements Store {
|
|
|
1094
647
|
getOnce(runId: RunId, stepId: StepId, scope: string): Promise<Json | null>;
|
|
1095
648
|
runStep<T extends Json>(runId: RunId, stepId: StepId, _attempt: AttemptNumber, body: (tx: Tx) => Promise<{
|
|
1096
649
|
readonly output: T;
|
|
1097
|
-
readonly fact: StepCompletedFact | StepFailedFact;
|
|
650
|
+
readonly fact: StepCompletedFact | StepFailedFact | StepCanceledFact;
|
|
1098
651
|
}>): Promise<T>;
|
|
1099
652
|
upsertSnapshot(args: {
|
|
1100
653
|
readonly flowHash: string;
|
|
@@ -1108,15 +661,10 @@ declare class InMemoryStore implements Store {
|
|
|
1108
661
|
readonly dag: Json;
|
|
1109
662
|
} | null>;
|
|
1110
663
|
appendGlobalFact(fact: GlobalFact): Promise<void>;
|
|
1111
|
-
/** Test-only: peek at the in-memory global fact log. */
|
|
1112
664
|
readGlobalFacts(): ReadonlyArray<GlobalFact>;
|
|
1113
665
|
queryRuns(opts: QueryRunsOpts): Promise<QueryRunsResult>;
|
|
666
|
+
pruneFacts(opts: Required<PruneOpts>): Promise<PruneResult>;
|
|
1114
667
|
}
|
|
1115
|
-
/**
|
|
1116
|
-
* Project an append-only fact stream into a `RunState`. Public so adapters
|
|
1117
|
-
* (e.g. `@nagi-js/postgres`) can re-use the same projection rules — keeping
|
|
1118
|
-
* one canonical definition of "what does the fact log mean".
|
|
1119
|
-
*/
|
|
1120
668
|
declare function projectRunState(runId: RunId, facts: readonly Fact[]): RunState;
|
|
1121
669
|
interface InMemoryQueueOpts {
|
|
1122
670
|
readonly leaseMs?: Millis;
|
|
@@ -1135,13 +683,6 @@ declare class InMemoryQueue implements Queue {
|
|
|
1135
683
|
extend(receipt: string, leaseMs: Millis): Promise<void>;
|
|
1136
684
|
}
|
|
1137
685
|
interface InMemoryClockOpts {
|
|
1138
|
-
/**
|
|
1139
|
-
* Wires `schedule()` wake-ups to a trigger. When the persistent timer fires,
|
|
1140
|
-
* the clock calls `trigger.fire(runId)` so scheduler subscribers can resume
|
|
1141
|
-
* the run. Without this, `schedule()` is a no-op on the worker loop and any
|
|
1142
|
-
* step that depends on it (time-based gates, long-delayed retries) will
|
|
1143
|
-
* stall in tests.
|
|
1144
|
-
*/
|
|
1145
686
|
readonly trigger?: InMemoryTrigger;
|
|
1146
687
|
}
|
|
1147
688
|
declare class InMemoryClock implements Clock {
|
|
@@ -1151,16 +692,11 @@ declare class InMemoryClock implements Clock {
|
|
|
1151
692
|
now(): Date;
|
|
1152
693
|
sleep(ms: Millis, signal?: AbortSignal): Promise<void>;
|
|
1153
694
|
schedule(at: Date, runId: RunId, stepId: StepId): Promise<void>;
|
|
1154
|
-
/** Clear any pending scheduled timers. Call from test teardown. */
|
|
1155
695
|
dispose(): void;
|
|
1156
696
|
}
|
|
1157
697
|
declare class InMemoryTrigger implements Trigger {
|
|
1158
698
|
private handlers;
|
|
1159
699
|
subscribe(handler: (runId: RunId) => void): () => void;
|
|
1160
|
-
/**
|
|
1161
|
-
* Test-only: synchronously dispatch a wake-up to all subscribers.
|
|
1162
|
-
* Real triggers fire from a Store change (NOTIFY/LISTEN, polling, etc.).
|
|
1163
|
-
*/
|
|
1164
700
|
fire(runId: RunId): void;
|
|
1165
701
|
}
|
|
1166
702
|
|
|
@@ -1173,62 +709,36 @@ interface NagiConfig {
|
|
|
1173
709
|
readonly hooks?: FlowHooks;
|
|
1174
710
|
readonly logger?: Logger;
|
|
1175
711
|
readonly defaultRetry?: RetryPolicy;
|
|
1176
|
-
/**
|
|
1177
|
-
* Process-wide identifier persisted on `workflow_run.code_version` and on
|
|
1178
|
-
* every `flow.started` fact for runs started by this process.
|
|
1179
|
-
*
|
|
1180
|
-
* When omitted (default), nagi computes a structural fingerprint over the
|
|
1181
|
-
* registered flows via {@link fingerprintFlows} and uses that — so the
|
|
1182
|
-
* audit field is meaningful by default and shifts only when flow topology
|
|
1183
|
-
* changes, not on every deploy. Supply an explicit string to override
|
|
1184
|
-
* (e.g. for a forced cutover: `"cutover-2026-05-15"`).
|
|
1185
|
-
*
|
|
1186
|
-
* Drift detection at replay uses each flow's per-flow `flowHash`, not this
|
|
1187
|
-
* value. See RFC 0001 "Topology vs handler code" and RFC 0003 "Auto-compute
|
|
1188
|
-
* codeVersion."
|
|
1189
|
-
*/
|
|
1190
712
|
readonly codeVersion?: string;
|
|
1191
713
|
}
|
|
1192
714
|
interface StartOpts {
|
|
1193
|
-
/**
|
|
1194
|
-
* Caller-supplied runId for idempotent kickoff. If provided and a run with
|
|
1195
|
-
* this ID already exists, `start()` is a no-op and returns the same ID
|
|
1196
|
-
* without re-appending `flow.started`, re-dispatching, or re-validating the
|
|
1197
|
-
* input. Two concurrent `start()` calls with the same `runId` produce
|
|
1198
|
-
* exactly one run (enforced at the Store layer).
|
|
1199
|
-
*
|
|
1200
|
-
* If omitted, the runtime mints a fresh ID via `crypto.randomUUID()`.
|
|
1201
|
-
*
|
|
1202
|
-
* Typical usage: a content hash of the input, so callers de-duplicate
|
|
1203
|
-
* kickoffs without coordinating.
|
|
1204
|
-
*/
|
|
1205
715
|
readonly runId?: RunId;
|
|
1206
716
|
}
|
|
717
|
+
interface CancelOpts {
|
|
718
|
+
readonly reason?: string;
|
|
719
|
+
}
|
|
1207
720
|
interface Wf {
|
|
1208
|
-
/** Begin a new run. Returns the runId. */
|
|
1209
721
|
start<F extends Flow>(flow: F, input: FlowInput<F>, opts?: StartOpts): Promise<RunId>;
|
|
1210
|
-
/** Resolve a `b.signal()` step waiting on external input. */
|
|
1211
|
-
signal(runId: RunId, stepName: string, payload: unknown): Promise<void>;
|
|
1212
|
-
/** Construct a worker; call `run` / `runOnce` / `runUntilEmpty` on it. */
|
|
1213
|
-
worker(config?: WorkerConfig): Worker;
|
|
1214
|
-
/**
|
|
1215
|
-
* Re-dispatch from the first incomplete step. `mode: "continue"` runs side
|
|
1216
|
-
* effects (idempotency protects); `mode: "inspect"` is a no-op probe.
|
|
1217
|
-
*/
|
|
1218
|
-
replay(runId: RunId, opts?: ReplayOpts): Promise<void>;
|
|
1219
722
|
/**
|
|
1220
|
-
*
|
|
1221
|
-
*
|
|
1222
|
-
*
|
|
723
|
+
* Start a flow by id with a runtime-typed input. Intended for callers
|
|
724
|
+
* holding a serialized payload (transactional-outbox reconcilers, queue
|
|
725
|
+
* consumers replaying DLQs, admin CLIs replaying a runId): the input
|
|
726
|
+
* is validated against the registered flow's schema before the run is
|
|
727
|
+
* created, mirroring `start`'s runtime contract without requiring a
|
|
728
|
+
* compile-time-typed input.
|
|
1223
729
|
*
|
|
1224
|
-
*
|
|
1225
|
-
*
|
|
1226
|
-
*
|
|
1227
|
-
* Pagination is keyset on `(startedAt, runId)` DESC. Pass the returned
|
|
1228
|
-
* `cursor` to the next call. `latest: true` returns at most one run and
|
|
1229
|
-
* forbids `limit` / `cursor` at the type level.
|
|
730
|
+
* Throws `NagiRuntimeError` when `flowId` is not registered with
|
|
731
|
+
* `nagi()`, and `NagiValidationError` when the input fails the flow's
|
|
732
|
+
* schema or when `opts.runId` is invalid.
|
|
1230
733
|
*/
|
|
734
|
+
startById(flowId: string, input: unknown, opts?: StartOpts): Promise<RunId>;
|
|
735
|
+
signal(runId: RunId, stepName: string, payload: unknown): Promise<void>;
|
|
736
|
+
cancel(runId: RunId, opts?: CancelOpts): Promise<void>;
|
|
737
|
+
worker(config?: WorkerConfig): Worker;
|
|
738
|
+
replay(runId: RunId, opts?: ReplayOpts): Promise<void>;
|
|
1231
739
|
queryRuns(opts?: QueryRunsOpts): Promise<QueryRunsResult>;
|
|
740
|
+
operator(): Operator;
|
|
741
|
+
pruneFacts(opts: PruneOpts): Promise<PruneResult>;
|
|
1232
742
|
}
|
|
1233
743
|
declare class NagiValidationError extends Error {
|
|
1234
744
|
readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
|
|
@@ -1237,13 +747,6 @@ declare class NagiValidationError extends Error {
|
|
|
1237
747
|
declare class NagiRuntimeError extends Error {
|
|
1238
748
|
constructor(message: string);
|
|
1239
749
|
}
|
|
1240
|
-
/**
|
|
1241
|
-
* Carried by `onFlowError` (both flow-local and cross-cutting) when a run is
|
|
1242
|
-
* canceled because a newer `wf.start()` for the same concurrency group
|
|
1243
|
-
* superseded it. The serialized form preserves `name` and a structured
|
|
1244
|
-
* `cause` so observers can discriminate via `error.name === "NagiCanceledError"`
|
|
1245
|
-
* and read `error.cause.canceledByRunId` / `error.cause.concurrencyKey`.
|
|
1246
|
-
*/
|
|
1247
750
|
declare class NagiCanceledError extends Error {
|
|
1248
751
|
readonly runId: RunId;
|
|
1249
752
|
readonly canceledByRunId: RunId;
|
|
@@ -1254,12 +757,6 @@ declare class NagiCanceledError extends Error {
|
|
|
1254
757
|
readonly concurrencyKey: string;
|
|
1255
758
|
});
|
|
1256
759
|
}
|
|
1257
|
-
/**
|
|
1258
|
-
* Thrown by `wf.replay(runId)` when the live flow's canonical hash differs
|
|
1259
|
-
* from the snapshot the run was pinned to. The default replay behavior is
|
|
1260
|
-
* fail-loud — pass `replayOpts.allowDrift = true` to proceed using a
|
|
1261
|
-
* synthesized flow (topology from snapshot, handlers/predicates from live).
|
|
1262
|
-
*/
|
|
1263
760
|
declare class NagiSnapshotDriftError extends Error {
|
|
1264
761
|
readonly runId: RunId;
|
|
1265
762
|
readonly expected: string;
|
|
@@ -1272,4 +769,4 @@ declare class NagiSnapshotDriftError extends Error {
|
|
|
1272
769
|
}
|
|
1273
770
|
declare function nagi(config: NagiConfig): Promise<Wf>;
|
|
1274
771
|
|
|
1275
|
-
export { type
|
|
772
|
+
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 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, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, type NeedsMap, type NeedsOutputs, type OnceRecordedFact, type Operator, type OperatorAuditOpts, type OperatorSkipOpts, 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 RetryPolicy, type RunId, type RunState, type RunStatus, type RunSummary, 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 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 };
|