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

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
@@ -113,6 +113,20 @@ interface TaskConfig<Input, N extends NeedsMap, Output> extends StepConfigBase<I
113
113
  readonly needs: NoInfer<NeedsOutputs<N>>;
114
114
  readonly ctx: StepCtx<NoInfer<Input>>;
115
115
  }) => Promise<Output>;
116
+ /**
117
+ * Lifecycle hooks colocated with this step. Fire *before* the cross-cutting
118
+ * `FlowHooks` callbacks (deterministic ordering). A throwing hook is logged
119
+ * via the runtime's `Logger` and swallowed — hooks cannot fail the run.
120
+ *
121
+ * `onComplete`'s event is typed against this step's `Output` — no `Json`
122
+ * narrowing required at the call site.
123
+ */
124
+ readonly onStart?: (event: StepStartEvent) => void | Promise<void>;
125
+ readonly onComplete?: (event: StepCompleteEvent & {
126
+ readonly output: NoInfer<Output>;
127
+ }) => void | Promise<void>;
128
+ readonly onError?: (event: StepErrorEvent) => void | Promise<void>;
129
+ readonly onRetry?: (event: StepRetryEvent) => void | Promise<void>;
116
130
  }
117
131
  interface SignalConfig<Input, N extends NeedsMap, Schema extends StandardSchemaV1> extends StepConfigBase<Input, N> {
118
132
  readonly schema: Schema;
@@ -202,6 +216,13 @@ interface StepEntryConfig<Input, A extends Record<string, unknown>, Needs extend
202
216
  };
203
217
  readonly ctx: StepCtx<NoInfer<Input>>;
204
218
  }) => Promise<Output>;
219
+ /** See {@link TaskConfig} for hook semantics. */
220
+ readonly onStart?: (event: StepStartEvent) => void | Promise<void>;
221
+ readonly onComplete?: (event: StepCompleteEvent & {
222
+ readonly output: NoInfer<Output>;
223
+ }) => void | Promise<void>;
224
+ readonly onError?: (event: StepErrorEvent) => void | Promise<void>;
225
+ readonly onRetry?: (event: StepRetryEvent) => void | Promise<void>;
205
226
  }
206
227
  /**
207
228
  * `b` inside `flow({ build: (b) => ... })`.
@@ -296,12 +317,36 @@ interface FlowConfig<Id extends string, InputSchema extends StandardSchemaV1, R,
296
317
  * the type claims otherwise (consistent with the "skip is transitive" lock).
297
318
  */
298
319
  output?(steps: NeedsOutputs<AsStepMap<R>>): Output;
320
+ /**
321
+ * Flow-level lifecycle hooks. Like step-local hooks (see {@link TaskConfig}),
322
+ * these fire *before* the cross-cutting `FlowHooks` callbacks, and a thrown
323
+ * hook is swallowed + logged rather than failing the run.
324
+ *
325
+ * `onComplete`'s event is typed against this flow's `Output` (whatever the
326
+ * `output()` resolver returns).
327
+ */
328
+ readonly onStart?: (event: FlowStartEvent) => void | Promise<void>;
329
+ readonly onComplete?: (event: FlowCompleteEvent & {
330
+ readonly output: NoInfer<Output>;
331
+ }) => void | Promise<void>;
332
+ readonly onError?: (event: FlowErrorEvent) => void | Promise<void>;
299
333
  }
300
334
  interface Flow<Id extends string = string, InputSchema extends StandardSchemaV1 = StandardSchemaV1, M extends StepMap = StepMap, Output = unknown> {
301
335
  readonly id: Id;
302
336
  readonly input: InputSchema;
303
337
  readonly steps: M;
304
338
  output?(steps: NeedsOutputs<M>): Output;
339
+ /**
340
+ * Forwarded from {@link FlowConfig}; surfaced for the dispatcher.
341
+ *
342
+ * Note these use the plain (non-Output-augmented) event types — the typed
343
+ * narrowing lives on {@link FlowConfig}'s callbacks at build time, while
344
+ * the runtime form is variance-friendly so a concrete `Flow<...{x: number}>`
345
+ * stays assignable to `Flow<...unknown>` (the dispatcher's view).
346
+ */
347
+ readonly onStart?: (event: FlowStartEvent) => void | Promise<void>;
348
+ readonly onComplete?: (event: FlowCompleteEvent) => void | Promise<void>;
349
+ readonly onError?: (event: FlowErrorEvent) => void | Promise<void>;
305
350
  }
306
351
  type FlowInput<F> = F extends Flow<string, infer S, StepMap, unknown> ? InferSchemaOutput<S> : never;
307
352
  type FlowOutput<F> = F extends Flow<string, StandardSchemaV1, StepMap, infer O> ? O : never;
@@ -681,6 +726,15 @@ interface ReplayOpts {
681
726
  * When false (default), drift throws `NagiSnapshotDriftError`.
682
727
  */
683
728
  readonly allowDrift?: boolean;
729
+ /**
730
+ * Whether step / flow lifecycle hooks (both the step-local ones on
731
+ * `TaskConfig` / `FlowConfig` and the cross-cutting `FlowHooks`) fire during
732
+ * replay. Defaults to `true` — replay re-executes steps via the idempotent
733
+ * dispatcher and emits the same observable lifecycle. Set to `false` for
734
+ * backfills or inspection-style replays where re-emitting webhooks would
735
+ * dual-publish.
736
+ */
737
+ readonly fireHooks?: boolean;
684
738
  }
685
739
 
686
740
  /**
package/dist/index.js CHANGED
@@ -89,7 +89,13 @@ function makeBuilder() {
89
89
  ...config.when !== void 0 ? {
90
90
  when: config.when
91
91
  } : {},
92
- run: config.run
92
+ run: config.run,
93
+ ...config.onStart !== void 0 ? { onStart: config.onStart } : {},
94
+ ...config.onComplete !== void 0 ? {
95
+ onComplete: config.onComplete
96
+ } : {},
97
+ ...config.onError !== void 0 ? { onError: config.onError } : {},
98
+ ...config.onRetry !== void 0 ? { onRetry: config.onRetry } : {}
93
99
  };
94
100
  return attachDef({ kind: "task", id: "" }, def);
95
101
  }
@@ -175,7 +181,13 @@ function makeBuilder() {
175
181
  ...config.when !== void 0 ? {
176
182
  when: config.when
177
183
  } : {},
178
- run: config.run
184
+ run: config.run,
185
+ ...config.onStart !== void 0 ? { onStart: config.onStart } : {},
186
+ ...config.onComplete !== void 0 ? {
187
+ onComplete: config.onComplete
188
+ } : {},
189
+ ...config.onError !== void 0 ? { onError: config.onError } : {},
190
+ ...config.onRetry !== void 0 ? { onRetry: config.onRetry } : {}
179
191
  };
180
192
  attachDefMut(shell, def);
181
193
  chainSteps.set(key, shell);
@@ -219,7 +231,12 @@ function flow(config) {
219
231
  id: config.id,
220
232
  input: config.input,
221
233
  steps: finalSteps,
222
- ...config.output !== void 0 ? { output: config.output } : {}
234
+ ...config.output !== void 0 ? { output: config.output } : {},
235
+ ...config.onStart !== void 0 ? { onStart: config.onStart } : {},
236
+ ...config.onComplete !== void 0 ? {
237
+ onComplete: config.onComplete
238
+ } : {},
239
+ ...config.onError !== void 0 ? { onError: config.onError } : {}
223
240
  };
224
241
  }
225
242
  function collectIds(map, prefix, idByIdentity) {
@@ -930,6 +947,19 @@ function extractInput(runState) {
930
947
  }
931
948
 
932
949
  // src/dispatch.ts
950
+ async function fireHook(hook, event, hookName, deps) {
951
+ if (deps.fireHooks === false) return;
952
+ if (hook === void 0) return;
953
+ try {
954
+ await hook(event);
955
+ } catch (err) {
956
+ const { message, stack } = serializeError(err);
957
+ deps.logger?.error(`nagi hook "${hookName}" threw \u2014 swallowed`, {
958
+ error: message,
959
+ ...stack !== void 0 ? { stack } : {}
960
+ });
961
+ }
962
+ }
933
963
  var DEFAULT_RETRY2 = {
934
964
  maxAttempts: 3,
935
965
  backoff: "exponential",
@@ -968,7 +998,7 @@ async function dispatchMessage(deps, message) {
968
998
  at: clock.now()
969
999
  });
970
1000
  const startEventInput = def.kind === "task" ? extractInput(await store.loadRunState(runId)) : null;
971
- await deps.hooks?.onStepStart?.({
1001
+ const startEvent = {
972
1002
  runId,
973
1003
  flowId: flow2.id,
974
1004
  stepId,
@@ -976,7 +1006,10 @@ async function dispatchMessage(deps, message) {
976
1006
  kind: def.kind,
977
1007
  input: startEventInput,
978
1008
  at: clock.now()
979
- });
1009
+ };
1010
+ const stepOnStart = def.kind === "task" ? def.onStart : void 0;
1011
+ await fireHook(stepOnStart, startEvent, "step.onStart", deps);
1012
+ await fireHook(deps.hooks?.onStepStart, startEvent, "onStepStart", deps);
980
1013
  const startedAt = Date.now();
981
1014
  try {
982
1015
  if (def.kind === "task") {
@@ -988,7 +1021,7 @@ async function dispatchMessage(deps, message) {
988
1021
  stepId,
989
1022
  attempt
990
1023
  });
991
- await deps.hooks?.onStepComplete?.({
1024
+ const completeEvent = {
992
1025
  runId,
993
1026
  flowId: flow2.id,
994
1027
  stepId,
@@ -997,7 +1030,14 @@ async function dispatchMessage(deps, message) {
997
1030
  output,
998
1031
  durationMs: Date.now() - startedAt,
999
1032
  at: clock.now()
1000
- });
1033
+ };
1034
+ await fireHook(def.onComplete, completeEvent, "step.onComplete", deps);
1035
+ await fireHook(
1036
+ deps.hooks?.onStepComplete,
1037
+ completeEvent,
1038
+ "onStepComplete",
1039
+ deps
1040
+ );
1001
1041
  await advance(deps, runId);
1002
1042
  } else if (def.kind === "signal") {
1003
1043
  await queue.ack(message.receipt);
@@ -1090,7 +1130,7 @@ async function handleStepError(args) {
1090
1130
  nextAttemptAt: new Date(Date.now() + delayMs),
1091
1131
  at: clock.now()
1092
1132
  });
1093
- await deps.hooks?.onStepRetry?.({
1133
+ const retryEvent = {
1094
1134
  runId,
1095
1135
  flowId: flow2.id,
1096
1136
  stepId,
@@ -1099,7 +1139,10 @@ async function handleStepError(args) {
1099
1139
  error,
1100
1140
  nextAttemptAt: new Date(Date.now() + delayMs),
1101
1141
  at: clock.now()
1102
- });
1142
+ };
1143
+ const stepOnRetry = def.kind === "task" ? def.onRetry : void 0;
1144
+ await fireHook(stepOnRetry, retryEvent, "step.onRetry", deps);
1145
+ await fireHook(deps.hooks?.onStepRetry, retryEvent, "onStepRetry", deps);
1103
1146
  await queue.enqueue(runId, stepId, { attempt: attempt + 1, delayMs });
1104
1147
  await queue.ack(message.receipt);
1105
1148
  return;
@@ -1113,7 +1156,7 @@ async function handleStepError(args) {
1113
1156
  at: clock.now()
1114
1157
  };
1115
1158
  await store.failStep(runId, stepId, error, fact);
1116
- await deps.hooks?.onStepError?.({
1159
+ const errorEvent = {
1117
1160
  runId,
1118
1161
  flowId: flow2.id,
1119
1162
  stepId,
@@ -1121,7 +1164,10 @@ async function handleStepError(args) {
1121
1164
  kind: def.kind,
1122
1165
  error,
1123
1166
  at: clock.now()
1124
- });
1167
+ };
1168
+ const stepOnError = def.kind === "task" ? def.onError : void 0;
1169
+ await fireHook(stepOnError, errorEvent, "step.onError", deps);
1170
+ await fireHook(deps.hooks?.onStepError, errorEvent, "onStepError", deps);
1125
1171
  await queue.ack(message.receipt);
1126
1172
  await advance(deps, runId);
1127
1173
  }
@@ -1135,53 +1181,18 @@ async function advance(deps, runId) {
1135
1181
  if (promoted) continue;
1136
1182
  const termination = flowTermination(flow2, runState);
1137
1183
  if (termination.done) {
1138
- const last2 = runState.facts[runState.facts.length - 1];
1139
- const flowAlreadyTerminal = last2 !== void 0 && (last2.kind === "flow.completed" || last2.kind === "flow.failed");
1140
- if (!flowAlreadyTerminal) {
1141
- if (termination.failed) {
1142
- const failedStep = Object.values(runState.steps).find(
1143
- (s) => s.status === "failed"
1144
- );
1145
- await store.appendFact(runId, {
1146
- kind: "flow.failed",
1147
- runId,
1148
- error: failedStep?.error ?? {
1149
- name: "Error",
1150
- message: "step failed"
1151
- },
1152
- at: clock.now()
1153
- });
1154
- await deps.hooks?.onFlowError?.({
1155
- runId,
1156
- flowId: flow2.id,
1157
- error: failedStep?.error ?? {
1158
- name: "Error",
1159
- message: "step failed"
1160
- },
1161
- at: clock.now()
1162
- });
1163
- } else {
1164
- let flowOutput = null;
1165
- if (flow2.output !== void 0) {
1166
- const stepOutputs = {};
1167
- for (const [sid, sstate] of Object.entries(runState.steps)) {
1168
- if (sstate.output !== void 0) stepOutputs[sid] = sstate.output;
1169
- }
1170
- flowOutput = flow2.output(stepOutputs);
1171
- }
1172
- await store.appendFact(runId, {
1173
- kind: "flow.completed",
1174
- runId,
1175
- output: flowOutput,
1176
- at: clock.now()
1177
- });
1178
- await deps.hooks?.onFlowComplete?.({
1179
- runId,
1180
- flowId: flow2.id,
1181
- output: flowOutput,
1182
- at: clock.now()
1183
- });
1184
- }
1184
+ if (isFlowTerminal(runState.facts)) return;
1185
+ if (termination.failed) {
1186
+ const failedStep = Object.values(runState.steps).find(
1187
+ (s) => s.status === "failed"
1188
+ );
1189
+ const flowError = failedStep?.error ?? {
1190
+ name: "Error",
1191
+ message: "step failed"
1192
+ };
1193
+ await finalizeFlowFailure({ deps, flow: flow2, runId, error: flowError });
1194
+ } else {
1195
+ await finalizeFlowCompletion({ deps, flow: flow2, runId, runState });
1185
1196
  }
1186
1197
  return;
1187
1198
  }
@@ -1208,21 +1219,9 @@ async function advance(deps, runId) {
1208
1219
  name: "NagiCycleError",
1209
1220
  message: `advance exceeded ${MAX_ADVANCE_ITERS} iterations \u2014 likely a cycle or infinite skip loop in flow "${flow2.id}"`
1210
1221
  };
1211
- const last = (await store.loadRunState(runId)).facts.slice(-1)[0];
1212
- const alreadyTerminal = last !== void 0 && (last.kind === "flow.completed" || last.kind === "flow.failed");
1213
- if (!alreadyTerminal) {
1214
- await store.appendFact(runId, {
1215
- kind: "flow.failed",
1216
- runId,
1217
- error: cycleError,
1218
- at: clock.now()
1219
- });
1220
- await deps.hooks?.onFlowError?.({
1221
- runId,
1222
- flowId: flow2.id,
1223
- error: cycleError,
1224
- at: clock.now()
1225
- });
1222
+ const facts = (await store.loadRunState(runId)).facts;
1223
+ if (!isFlowTerminal(facts)) {
1224
+ await finalizeFlowFailure({ deps, flow: flow2, runId, error: cycleError });
1226
1225
  }
1227
1226
  }
1228
1227
  async function promoteMatches(args) {
@@ -1252,15 +1251,20 @@ async function promoteMatches(args) {
1252
1251
  at: clock.now()
1253
1252
  };
1254
1253
  await store.failStep(runState.runId, matchId, error, fact2);
1255
- await deps.hooks?.onStepError?.({
1256
- runId: runState.runId,
1257
- flowId: flow2.id,
1258
- stepId: matchId,
1259
- attempt,
1260
- kind: "match",
1261
- error,
1262
- at: clock.now()
1263
- });
1254
+ await fireHook(
1255
+ deps.hooks?.onStepError,
1256
+ {
1257
+ runId: runState.runId,
1258
+ flowId: flow2.id,
1259
+ stepId: matchId,
1260
+ attempt,
1261
+ kind: "match",
1262
+ error,
1263
+ at: clock.now()
1264
+ },
1265
+ "onStepError",
1266
+ deps
1267
+ );
1264
1268
  promoted = true;
1265
1269
  continue;
1266
1270
  }
@@ -1273,16 +1277,21 @@ async function promoteMatches(args) {
1273
1277
  at: clock.now()
1274
1278
  };
1275
1279
  await store.completeStep(runState.runId, matchId, agg.output, fact);
1276
- await deps.hooks?.onStepComplete?.({
1277
- runId: runState.runId,
1278
- flowId: flow2.id,
1279
- stepId: matchId,
1280
- attempt,
1281
- kind: "match",
1282
- output: agg.output,
1283
- durationMs: 0,
1284
- at: clock.now()
1285
- });
1280
+ await fireHook(
1281
+ deps.hooks?.onStepComplete,
1282
+ {
1283
+ runId: runState.runId,
1284
+ flowId: flow2.id,
1285
+ stepId: matchId,
1286
+ attempt,
1287
+ kind: "match",
1288
+ output: agg.output,
1289
+ durationMs: 0,
1290
+ at: clock.now()
1291
+ },
1292
+ "onStepComplete",
1293
+ deps
1294
+ );
1286
1295
  promoted = true;
1287
1296
  }
1288
1297
  return promoted;
@@ -1332,6 +1341,45 @@ function retryAllows(policy, err) {
1332
1341
  if (!policy.retryOn) return true;
1333
1342
  return policy.retryOn(err);
1334
1343
  }
1344
+ function isFlowTerminal(facts) {
1345
+ const last = facts[facts.length - 1];
1346
+ return last !== void 0 && (last.kind === "flow.completed" || last.kind === "flow.failed");
1347
+ }
1348
+ async function finalizeFlowFailure(args) {
1349
+ const { deps, flow: flow2, runId, error } = args;
1350
+ const { store, clock } = deps;
1351
+ await store.appendFact(runId, {
1352
+ kind: "flow.failed",
1353
+ runId,
1354
+ error,
1355
+ at: clock.now()
1356
+ });
1357
+ const event = { runId, flowId: flow2.id, error, at: clock.now() };
1358
+ await fireHook(flow2.onError, event, "flow.onError", deps);
1359
+ await fireHook(deps.hooks?.onFlowError, event, "onFlowError", deps);
1360
+ }
1361
+ async function finalizeFlowCompletion(args) {
1362
+ const { deps, flow: flow2, runId, runState } = args;
1363
+ const { store, clock } = deps;
1364
+ const output = computeFlowOutput(flow2, runState);
1365
+ await store.appendFact(runId, {
1366
+ kind: "flow.completed",
1367
+ runId,
1368
+ output,
1369
+ at: clock.now()
1370
+ });
1371
+ const event = { runId, flowId: flow2.id, output, at: clock.now() };
1372
+ await fireHook(flow2.onComplete, event, "flow.onComplete", deps);
1373
+ await fireHook(deps.hooks?.onFlowComplete, event, "onFlowComplete", deps);
1374
+ }
1375
+ function computeFlowOutput(flow2, runState) {
1376
+ if (flow2.output === void 0) return null;
1377
+ const stepOutputs = {};
1378
+ for (const [sid, sstate] of Object.entries(runState.steps)) {
1379
+ if (sstate.output !== void 0) stepOutputs[sid] = sstate.output;
1380
+ }
1381
+ return flow2.output(stepOutputs);
1382
+ }
1335
1383
  function serializeError(err) {
1336
1384
  if (err instanceof Error) {
1337
1385
  return {
@@ -1557,12 +1605,24 @@ async function nagi(config) {
1557
1605
  if (!started) {
1558
1606
  return runId;
1559
1607
  }
1560
- await config.hooks?.onFlowStart?.({
1608
+ const startEvent = {
1561
1609
  runId,
1562
1610
  flowId: flow2.id,
1563
1611
  input: validated,
1564
1612
  at: startedAt
1565
- });
1613
+ };
1614
+ await fireHook(
1615
+ flow2.onStart,
1616
+ startEvent,
1617
+ "flow.onStart",
1618
+ dispatchDeps
1619
+ );
1620
+ await fireHook(
1621
+ config.hooks?.onFlowStart,
1622
+ startEvent,
1623
+ "onFlowStart",
1624
+ dispatchDeps
1625
+ );
1566
1626
  await advance(dispatchDeps, runId);
1567
1627
  return runId;
1568
1628
  },
@@ -1615,15 +1675,20 @@ async function nagi(config) {
1615
1675
  validated,
1616
1676
  completedFact
1617
1677
  );
1618
- await config.hooks?.onSignalReceived?.({
1619
- runId,
1620
- flowId: flow2.id,
1621
- stepId: stepName,
1622
- attempt,
1623
- kind: "signal",
1624
- payload: validated,
1625
- at: clock.now()
1626
- });
1678
+ await fireHook(
1679
+ config.hooks?.onSignalReceived,
1680
+ {
1681
+ runId,
1682
+ flowId: flow2.id,
1683
+ stepId: stepName,
1684
+ attempt,
1685
+ kind: "signal",
1686
+ payload: validated,
1687
+ at: clock.now()
1688
+ },
1689
+ "onSignalReceived",
1690
+ dispatchDeps
1691
+ );
1627
1692
  await advance(dispatchDeps, runId);
1628
1693
  },
1629
1694
  worker(workerConfig) {
@@ -1643,6 +1708,9 @@ async function nagi(config) {
1643
1708
  );
1644
1709
  }
1645
1710
  if (opts.mode === "inspect") return;
1711
+ const fireHooks = opts.fireHooks !== false;
1712
+ const baseDeps = fireHooks ? dispatchDeps : { ...dispatchDeps, fireHooks: false };
1713
+ let replayDeps = baseDeps;
1646
1714
  const pinned = runState.flowHash;
1647
1715
  if (pinned !== void 0) {
1648
1716
  const liveHash = flowHashById.get(liveFlow.id);
@@ -1664,21 +1732,25 @@ async function nagi(config) {
1664
1732
  snapshot.dag,
1665
1733
  liveFlow
1666
1734
  );
1667
- const driftDeps = {
1668
- ...dispatchDeps,
1669
- flowFor: async () => synthesized
1670
- };
1671
- await advance(driftDeps, runId);
1672
- return;
1735
+ replayDeps = { ...baseDeps, flowFor: async () => synthesized };
1673
1736
  }
1674
1737
  }
1675
- await advance(dispatchDeps, runId);
1738
+ await advance(replayDeps, runId);
1739
+ if (!fireHooks) await drainInline(replayDeps);
1676
1740
  }
1677
1741
  };
1678
1742
  }
1679
1743
  function mintRunId() {
1680
1744
  return `run-${crypto.randomUUID()}`;
1681
1745
  }
1746
+ var MAX_REPLAY_DISPATCHES = 4096;
1747
+ async function drainInline(deps) {
1748
+ for (let i = 0; i < MAX_REPLAY_DISPATCHES; i++) {
1749
+ const messages = await deps.queue.dequeue({ count: 1 });
1750
+ if (messages.length === 0) return;
1751
+ for (const msg of messages) await dispatchMessage(deps, msg);
1752
+ }
1753
+ }
1682
1754
  async function validate(schema, value) {
1683
1755
  const result = await schema["~standard"].validate(value);
1684
1756
  if ("issues" in result && result.issues !== void 0) {