@nagi-js/core 0.1.1-rc.19 → 0.1.1-rc.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { aC as StandardSchemaV1, aP as StepMap, n as FlowConfig, f as Flow, aD as Step, Z as Optional, aN as StepId, aO as StepKind, B as BackoffStrategy, S as Millis, an as RunId$1, c as Clock, a6 as Queue, a8 as QueueEnqueueOpts, a7 as QueueDequeueOpts, aa as QueueMessage, a9 as QueueInspectEntry, a$ as Store, F as Fact, x as FlowStartedFact, d as ConcurrencyMode, g as FlowCanceledByConcurrencyFact, b9 as Tx, ap as RunState, A as AttemptNumber, b as ClaimToken, ab as ReapedLease, aI as StepCompletedFact, aM as StepFailedFact, J as Json, au as SettleSignalResult, b8 as TimedOutSignal, aG as StepCanceledFact, G as GlobalFact, a3 as QueryRunsOpts, a4 as QueryRunsResult, am as RunDescription, a1 as PruneOpts, a2 as PruneResult, b1 as StreamTransport, aB as SnapshotGonePolicy, r as FlowHooks, z as LogEntry, aj as RetryPolicy, bb as WorkerConfig, t as FlowInput, ba as Worker, af as ReplayOpts, s as FlowIdOf, b0 as StreamEvent, X as Operator, av as SignalBufferedFact, ay as SignalReceivedFact, aq as RunStatus, a0 as PrunableStatus } from './types-DfxwD2MH.js';
2
- export { a as Builder, C as CancelArgs, D as DEFAULT_REAPER_INTERVAL_MS, e as FactKind, h as FlowCanceledByOperatorFact, i as FlowCanceledExplicitlyFact, j as FlowCanceledFact, k as FlowCompleteEvent, l as FlowCompletedFact, m as FlowConcurrency, o as FlowErrorEvent, p as FlowEvent, q as FlowFailedFact, u as FlowOutput, v as FlowRefUpdatedFact, w as FlowStartEvent, I as InferSchemaInput, y as InferSchemaOutput, L as LeaseReapedFact, E as LogLevel, H as Logger, M as MatchArm, K as MatchArmGuard, N as MatchArmOtherwise, O as MatchArmOutput, P as MatchArmSelectedFact, Q as MatchArmShape, R as MatchGuardConfig, T as NeedRef, U as NeedsMap, V as NeedsOutputs, W as OnceRecordedFact, Y as OperatorAuditOpts, _ as ParentLink, $ as ParentRef, a5 as QueryRunsWhere, ac as ReaperDecision, ad as Register, ae as ReplayMode, ag as Resolved, ah as ResolvedConcurrency, ai as ResolvedNeeds, ak as RowDelta, al as RunCancelCause, ao as RunPhase, ar as RunSummary, as as RunView, at as SerializedError, aw as SignalConfig, ax as SignalReceivedEvent, az as SkipReason, aA as SnapshotGoneDisposition, aE as StepAbortRequestedFact, aF as StepCancelCause, aH as StepCompleteEvent, aJ as StepCtx, aK as StepErrorEvent, aL as StepEvent, aQ as StepOutput, aR as StepResetFact, aS as StepRetriedFact, aT as StepRetryEvent, aU as StepRunStatus, aV as StepSkippedFact, aW as StepStartEvent, aX as StepStartedFact, aY as StepState, aZ as StepStatus, a_ as StepView, b2 as StreamingStepCtx, b3 as StreamingTaskConfig, b4 as StringKeyOf, b5 as SubflowConfig, b6 as SubflowStepOutput, b7 as TaskConfig, bc as WorkerRunOnceOpts, bd as WorkerRunResult, be as WorkerRunUntilEmptyOpts, bf as attemptOf, bg as decideExpiredLeaseAction, bh as errorOf, bj as isStepTerminal, bk as isTerminalRun, bl as outputOf, bi as projectRunState, bm as resolvedOf, bn as rowDeltaOf, bo as runStatusOf, bp as stepStateOf, bq as stepStatusOf, br as unwrap } from './types-DfxwD2MH.js';
1
+ import { aD as StandardSchemaV1, aQ as StepMap, o as FlowConfig, g as Flow, aE as Step, _ as Optional, aO as StepId, aP as StepKind, B as BackoffStrategy, T as Millis, ao as RunId$1, c as Clock, a7 as Queue, a9 as QueueEnqueueOpts, a8 as QueueDequeueOpts, ab as QueueMessage, aa as QueueInspectEntry, b0 as Store, F as Fact, y as FlowStartedFact, d as ConcurrencyMode, h as FlowCanceledByConcurrencyFact, ba as Tx, aq as RunState, A as AttemptNumber, b as ClaimToken, ac as ReapedLease, aJ as StepCompletedFact, aN as StepFailedFact, J as Json, av as SettleSignalResult, b9 as TimedOutSignal, aH as StepCanceledFact, G as GlobalFact, a4 as QueryRunsOpts, a5 as QueryRunsResult, an as RunDescription, a2 as PruneOpts, a3 as PruneResult, b2 as StreamTransport, aC as SnapshotGonePolicy, s as FlowHooks, E as LogEntry, ak as RetryPolicy, e as DriftPolicy, bc as WorkerConfig, u as FlowInput, bb as Worker, ag as ReplayOpts, t as FlowIdOf, b1 as StreamEvent, Y as Operator, aw as SignalBufferedFact, az as SignalReceivedFact, ar as RunStatus, a1 as PrunableStatus } from './types-DFSYjJE3.js';
2
+ export { a as Builder, C as CancelArgs, D as DEFAULT_REAPER_INTERVAL_MS, f as FactKind, i as FlowCanceledByOperatorFact, j as FlowCanceledExplicitlyFact, k as FlowCanceledFact, l as FlowCompleteEvent, m as FlowCompletedFact, n as FlowConcurrency, p as FlowErrorEvent, q as FlowEvent, r as FlowFailedFact, v as FlowOutput, w as FlowRefUpdatedFact, x as FlowStartEvent, I as InferSchemaInput, z as InferSchemaOutput, L as LeaseReapedFact, H as LogLevel, K as Logger, M as MatchArm, N as MatchArmGuard, O as MatchArmOtherwise, P as MatchArmOutput, Q as MatchArmSelectedFact, R as MatchArmShape, S as MatchGuardConfig, U as NeedRef, V as NeedsMap, W as NeedsOutputs, X as OnceRecordedFact, Z as OperatorAuditOpts, $ as ParentLink, a0 as ParentRef, a6 as QueryRunsWhere, ad as ReaperDecision, ae as Register, af as ReplayMode, ah as Resolved, ai as ResolvedConcurrency, aj as ResolvedNeeds, al as RowDelta, am as RunCancelCause, ap as RunPhase, as as RunSummary, at as RunView, au as SerializedError, ax as SignalConfig, ay as SignalReceivedEvent, aA as SkipReason, aB as SnapshotGoneDisposition, aF as StepAbortRequestedFact, aG as StepCancelCause, aI as StepCompleteEvent, aK as StepCtx, aL as StepErrorEvent, aM as StepEvent, aR as StepOutput, aS as StepResetFact, aT as StepRetriedFact, aU as StepRetryEvent, aV as StepRunStatus, aW as StepSkippedFact, aX as StepStartEvent, aY as StepStartedFact, aZ as StepState, a_ as StepStatus, a$ as StepView, b3 as StreamingStepCtx, b4 as StreamingTaskConfig, b5 as StringKeyOf, b6 as SubflowConfig, b7 as SubflowStepOutput, b8 as TaskConfig, bd as WorkerRunOnceOpts, be as WorkerRunResult, bf as WorkerRunUntilEmptyOpts, bg as attemptOf, bh as decideExpiredLeaseAction, bi as errorOf, bk as isStepTerminal, bl as isTerminalRun, bm as outputOf, bj as projectRunState, bn as resolvedOf, bo as rowDeltaOf, bp as runStatusOf, bq as stepStateOf, br as stepStatusOf, bs as unwrap } from './types-DFSYjJE3.js';
3
3
 
4
4
  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>;
5
5
  declare function optional<S extends Step>(step: S): Optional<S>;
@@ -259,6 +259,7 @@ interface NagiConfig {
259
259
  readonly onLog?: (entry: LogEntry) => void;
260
260
  readonly defaultRetry?: RetryPolicy;
261
261
  readonly codeVersion?: string;
262
+ readonly driftPolicy?: DriftPolicy;
262
263
  readonly heartbeatIntervalMs?: Millis;
263
264
  readonly heartbeatLeaseMs?: Millis;
264
265
  readonly leaseHoldWarnMs?: Millis;
@@ -401,4 +402,4 @@ type FactEffects = {
401
402
  };
402
403
  declare function factEffects(fact: Fact): FactEffects;
403
404
 
404
- export { AttemptNumber, BackoffStrategy, type CanonicalDag, type CanonicalMatchArm, type CanonicalRetryPolicy, type CanonicalSchema, type CanonicalStep, ClaimToken, Clock, ConcurrencyMode, DEFAULT_SWEEP_LIMIT, Fact, type FactEffects, Flow, FlowCanceledByConcurrencyFact, FlowConfig, FlowHooks, FlowIdOf, FlowInput, FlowStartedFact, GlobalFact, InMemoryClock, InMemoryQueue, InMemoryStore, Json, LogEntry, Millis, NagiAbortError, NagiCanceledError, NagiConcurrencyConflictError, type NagiConfig, NagiFlowSnapshotGoneError, NagiNonRetryableError, type NagiRunConfig, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiValidationError, Operator, Optional, PrunableStatus, type PruneCandidate, PruneOpts, PruneResult, QUERY_RUNS_DEFAULT_LIMIT, QUERY_RUNS_MAX_LIMIT, QueryRunsOpts, QueryRunsResult, Queue, QueueDequeueOpts, QueueEnqueueOpts, QueueInspectEntry, QueueMessage, ReapedLease, ReplayOpts, RetryPolicy, type RunCursor, RunDescription, RunId, RunState, RunStatus, type RuntimeHandle, SettleSignalResult, SignalBufferedFact, type SignalDecision, SignalReceivedFact, type SnapshotChangedEdge, type SnapshotChangedField, type SnapshotDiff, SnapshotGonePolicy, StandardSchemaV1, type StartOpts, type StartStagedOpts, type StartStagedResult, Step, StepCanceledFact, StepCompletedFact, StepFailedFact, StepId, StepKind, StepMap, Store, StreamEvent, StreamTransport, TimedOutSignal, type TimeoutDecision, Tx, type Wf, Worker, WorkerConfig, canonicalize, clampQueryLimit, compareRunOrder, decideSignal, decideTimeout, decodeRunCursor, defaultSnapshotGonePolicy, diffSnapshots, encodeRunCursor, factEffects, fingerprintFlows, flow, isPastCursor, jsonContains, nagi, optional, selectExpired, selectPruneBatch, sha256Canonical };
405
+ export { AttemptNumber, BackoffStrategy, type CanonicalDag, type CanonicalMatchArm, type CanonicalRetryPolicy, type CanonicalSchema, type CanonicalStep, ClaimToken, Clock, ConcurrencyMode, DEFAULT_SWEEP_LIMIT, DriftPolicy, Fact, type FactEffects, Flow, FlowCanceledByConcurrencyFact, FlowConfig, FlowHooks, FlowIdOf, FlowInput, FlowStartedFact, GlobalFact, InMemoryClock, InMemoryQueue, InMemoryStore, Json, LogEntry, Millis, NagiAbortError, NagiCanceledError, NagiConcurrencyConflictError, type NagiConfig, NagiFlowSnapshotGoneError, NagiNonRetryableError, type NagiRunConfig, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiValidationError, Operator, Optional, PrunableStatus, type PruneCandidate, PruneOpts, PruneResult, QUERY_RUNS_DEFAULT_LIMIT, QUERY_RUNS_MAX_LIMIT, QueryRunsOpts, QueryRunsResult, Queue, QueueDequeueOpts, QueueEnqueueOpts, QueueInspectEntry, QueueMessage, ReapedLease, ReplayOpts, RetryPolicy, type RunCursor, RunDescription, RunId, RunState, RunStatus, type RuntimeHandle, SettleSignalResult, SignalBufferedFact, type SignalDecision, SignalReceivedFact, type SnapshotChangedEdge, type SnapshotChangedField, type SnapshotDiff, SnapshotGonePolicy, StandardSchemaV1, type StartOpts, type StartStagedOpts, type StartStagedResult, Step, StepCanceledFact, StepCompletedFact, StepFailedFact, StepId, StepKind, StepMap, Store, StreamEvent, StreamTransport, TimedOutSignal, type TimeoutDecision, Tx, type Wf, Worker, WorkerConfig, canonicalize, clampQueryLimit, compareRunOrder, decideSignal, decideTimeout, decodeRunCursor, defaultSnapshotGonePolicy, diffSnapshots, encodeRunCursor, factEffects, fingerprintFlows, flow, isPastCursor, jsonContains, nagi, optional, selectExpired, selectPruneBatch, sha256Canonical };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { InMemoryClock, makeEmit, asStepMapWithDefs, getDef, NagiRuntimeError, compact, makeSignals, DEFAULT_REAPER_INTERVAL_MS, Facts, validationError, NagiFlowSnapshotGoneError, isTerminalRun, runStatusOf, validate, foldRun, needsStepIds, attachDef, setDef, stepStateOf, serializeError, NagiCanceledError, NagiSignalTimeoutError, dequeueBackoff, defaultSnapshotGonePolicy, isStepTerminal, stepStatusOf, NagiSnapshotDriftError, attemptOf, DEFAULT_RETRY, outputOf, resolveNeeds, resolvedOf, handlerDef, resolveRetry, isAbortRequested, selectArm, stepBackoff, peekDef, NagiNonRetryableError, normalizeNeeds } from './chunk-VQTYTI6X.js';
1
+ import { InMemoryClock, makeEmit, asStepMapWithDefs, getDef, NagiRuntimeError, compact, makeSignals, DEFAULT_REAPER_INTERVAL_MS, Facts, validationError, NagiFlowSnapshotGoneError, isTerminalRun, runStatusOf, validate, foldRun, needsStepIds, stepStateOf, serializeError, NagiCanceledError, NagiSignalTimeoutError, dequeueBackoff, defaultSnapshotGonePolicy, isStepTerminal, stepStatusOf, NagiSnapshotDriftError, attachDef, setDef, attemptOf, DEFAULT_RETRY, outputOf, resolveNeeds, resolvedOf, handlerDef, resolveRetry, isAbortRequested, selectArm, stepBackoff, peekDef, NagiNonRetryableError, normalizeNeeds } from './chunk-VQTYTI6X.js';
2
2
  export { DEFAULT_REAPER_INTERVAL_MS, DEFAULT_SWEEP_LIMIT, InMemoryClock, InMemoryQueue, InMemoryStore, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiNonRetryableError, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiValidationError, QUERY_RUNS_DEFAULT_LIMIT, QUERY_RUNS_MAX_LIMIT, attemptOf, clampQueryLimit, compareRunOrder, decideExpiredLeaseAction, decideSignal, decideTimeout, decodeRunCursor, defaultSnapshotGonePolicy, encodeRunCursor, errorOf, factEffects, isPastCursor, isStepTerminal, isTerminalRun, jsonContains, outputOf, foldRun as projectRunState, resolvedOf, rowDeltaOf, runStatusOf, selectExpired, selectPruneBatch, stepStateOf, stepStatusOf, unwrap } from './chunk-VQTYTI6X.js';
3
3
 
4
4
  // src/builder.ts
@@ -1503,7 +1503,17 @@ async function registerFlows(deps) {
1503
1503
  });
1504
1504
  return isTerminalRun(state) ? { kind: "gone-terminal", error, live } : { kind: "gone-live", error, live };
1505
1505
  }
1506
- async function synthesize(gone) {
1506
+ const synthesizedByHash = /* @__PURE__ */ new Map();
1507
+ function synthesize(gone) {
1508
+ const { pinnedHash } = gone.error;
1509
+ const cached = synthesizedByHash.get(pinnedHash);
1510
+ if (cached !== void 0) return cached;
1511
+ const pending = synthesizeUncached(gone);
1512
+ synthesizedByHash.set(pinnedHash, pending);
1513
+ pending.catch(() => synthesizedByHash.delete(pinnedHash));
1514
+ return pending;
1515
+ }
1516
+ async function synthesizeUncached(gone) {
1507
1517
  const { runId, flowId, pinnedHash } = gone.error;
1508
1518
  if (gone.live === void 0) {
1509
1519
  throw new NagiRuntimeError(
@@ -1513,7 +1523,7 @@ async function registerFlows(deps) {
1513
1523
  const snapshot = await store.loadSnapshot(pinnedHash);
1514
1524
  if (snapshot === null) {
1515
1525
  throw new NagiRuntimeError(
1516
- `Run ${runId} pinned to flow hash ${pinnedHash.slice(0, 12)}\u2026 but no snapshot with that hash was found. Cannot replay with allowDrift.`
1526
+ `Run ${runId} pinned to flow hash ${pinnedHash.slice(0, 12)}\u2026 but no snapshot with that hash was found. Nothing can resume it.`
1517
1527
  );
1518
1528
  }
1519
1529
  return synthesizeReplayFlow(
@@ -1955,7 +1965,7 @@ function makeOperator(o) {
1955
1965
 
1956
1966
  // src/replay.ts
1957
1967
  function makeReplay(deps) {
1958
- const { registry, store, queue, clock } = deps;
1968
+ const { registry, store, queue, clock, driftPolicy } = deps;
1959
1969
  async function replay(runId, opts = { mode: "continue" }) {
1960
1970
  const runState = await store.loadRunState(runId);
1961
1971
  const resolution = registry.resolve(runState);
@@ -1976,7 +1986,7 @@ function makeReplay(deps) {
1976
1986
  let replayDeps = baseDeps;
1977
1987
  let effectiveFlow = liveFlow;
1978
1988
  if (resolution.kind !== "current") {
1979
- if (!opts.allowDrift) {
1989
+ if (!opts.allowDrift && driftPolicy === "freeze") {
1980
1990
  throw new NagiSnapshotDriftError({
1981
1991
  runId,
1982
1992
  expected: resolution.error.pinnedHash,
@@ -2525,8 +2535,28 @@ async function nagiImpl(config) {
2525
2535
  clock
2526
2536
  });
2527
2537
  const codeVersion = config.codeVersion ?? await fingerprintFlows(config.flows);
2538
+ const driftPolicy = config.driftPolicy ?? "freeze";
2528
2539
  async function resolveFlow(runId) {
2529
- return registry.resolve(await config.store.loadRunState(runId));
2540
+ const resolution = registry.resolve(await config.store.loadRunState(runId));
2541
+ if (resolution.kind !== "gone-live" || driftPolicy === "freeze") {
2542
+ return resolution;
2543
+ }
2544
+ try {
2545
+ return { kind: "current", flow: await registry.synthesize(resolution) };
2546
+ } catch (err) {
2547
+ if (!(err instanceof NagiRuntimeError)) throw err;
2548
+ emitLog({
2549
+ level: "warn",
2550
+ msg: "resolveFlow: drift synthesis failed \u2014 treating run as snapshot-gone",
2551
+ attrs: {
2552
+ runId: resolution.error.runId,
2553
+ flowId: resolution.error.flowId,
2554
+ pinnedHash: resolution.error.pinnedHash,
2555
+ error: err.message
2556
+ }
2557
+ });
2558
+ return resolution;
2559
+ }
2530
2560
  }
2531
2561
  function lookupFlow(flowId) {
2532
2562
  return registry.get(flowId);
@@ -2575,7 +2605,7 @@ async function nagiImpl(config) {
2575
2605
  emitLog,
2576
2606
  ...compact({ flowHooks: config.hooks })
2577
2607
  });
2578
- const replayer = makeReplay({ ...dispatchDeps, registry });
2608
+ const replayer = makeReplay({ ...dispatchDeps, registry, driftPolicy });
2579
2609
  const wf = {
2580
2610
  async start(flow2, input, opts) {
2581
2611
  return wf.startById(flow2.id, input, opts);