@nagi-js/core 0.1.1-rc.12 → 0.1.1-rc.14

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.js CHANGED
@@ -81,6 +81,7 @@ function startTarget(stepKind, attempt) {
81
81
  case "subflow":
82
82
  return { tag: "awaitingChild", attempt };
83
83
  case "task":
84
+ case "activity":
84
85
  case "streaming":
85
86
  case "match":
86
87
  return { tag: "running", attempt };
@@ -292,7 +293,7 @@ function peekDef(step) {
292
293
  return step[DEF];
293
294
  }
294
295
  function handlerDef(def) {
295
- return def.kind === "task" || def.kind === "streaming" ? def : void 0;
296
+ return def.kind === "task" || def.kind === "activity" || def.kind === "streaming" ? def : void 0;
296
297
  }
297
298
  function needsStepIds(def) {
298
299
  return Object.values(def.needs).map((ref) => ref.step.id);
@@ -337,6 +338,23 @@ function makeBuilder() {
337
338
  };
338
339
  return attachDef({ kind: "task", id: "" }, def);
339
340
  }
341
+ function activity(config) {
342
+ const def = {
343
+ kind: "activity",
344
+ needs: normalizeNeeds(config.needs),
345
+ run: config.run,
346
+ ...compact({
347
+ retry: config.retry,
348
+ timeoutMs: config.timeoutMs,
349
+ when: config.when,
350
+ onStart: config.onStart,
351
+ onComplete: config.onComplete,
352
+ onError: config.onError,
353
+ onRetry: config.onRetry
354
+ })
355
+ };
356
+ return attachDef({ kind: "activity", id: "" }, def);
357
+ }
340
358
  function streamingTask(config) {
341
359
  const def = {
342
360
  kind: "streaming",
@@ -398,6 +416,7 @@ function makeBuilder() {
398
416
  }
399
417
  return {
400
418
  task,
419
+ activity,
401
420
  streamingTask,
402
421
  signal,
403
422
  subflow,
@@ -585,7 +604,7 @@ async function canonicalize(flow2) {
585
604
  async function canonicalizeStep(id, def) {
586
605
  const needs = [...needsStepIds(def)].sort();
587
606
  const base = { id, kind: def.kind, needs };
588
- if (def.kind === "task" || def.kind === "streaming")
607
+ if (def.kind === "task" || def.kind === "activity" || def.kind === "streaming")
589
608
  return canonicalizeTask(base, def);
590
609
  if (def.kind === "signal") return canonicalizeSignal(base, def);
591
610
  if (def.kind === "subflow") return canonicalizeSubflow(base, def);
@@ -837,6 +856,45 @@ var NagiCanceledError = class extends Error {
837
856
  };
838
857
  }
839
858
  };
859
+ var NagiFlowSnapshotGoneError = class extends Error {
860
+ runId;
861
+ flowId;
862
+ pinnedHash;
863
+ currentHash;
864
+ constructor({
865
+ runId,
866
+ flowId,
867
+ pinnedHash,
868
+ currentHash
869
+ }) {
870
+ super(
871
+ currentHash === null ? `Run ${runId} is pinned to flow "${flowId}" hash ${pinnedHash.slice(0, 12)}\u2026, but flow "${flowId}" is not registered with the current nagi(). Pin a worker on the prior code version or migrate the run.` : `Run ${runId} is pinned to flow "${flowId}" hash ${pinnedHash.slice(0, 12)}\u2026, but the current registry has hash ${currentHash.slice(0, 12)}\u2026. Pin a worker on the prior code version or migrate the run.`
872
+ );
873
+ this.name = "NagiFlowSnapshotGoneError";
874
+ this.runId = runId;
875
+ this.flowId = flowId;
876
+ this.pinnedHash = pinnedHash;
877
+ this.currentHash = currentHash;
878
+ }
879
+ };
880
+ var NagiConcurrencyConflictError = class extends Error {
881
+ runId;
882
+ flowId;
883
+ concurrencyKey;
884
+ constructor({
885
+ runId,
886
+ flowId,
887
+ concurrencyKey
888
+ }) {
889
+ super(
890
+ `Run ${runId}: concurrent start lost the race on flow "${flowId}" concurrency key "${concurrencyKey}" \u2014 retry the caller transaction.`
891
+ );
892
+ this.name = "NagiConcurrencyConflictError";
893
+ this.runId = runId;
894
+ this.flowId = flowId;
895
+ this.concurrencyKey = concurrencyKey;
896
+ }
897
+ };
840
898
  var NagiSnapshotDriftError = class extends Error {
841
899
  runId;
842
900
  expected;
@@ -866,6 +924,23 @@ function serializeError(err) {
866
924
  return { name: "Error", message: String(err) };
867
925
  }
868
926
 
927
+ // src/lease-reaper.ts
928
+ function decideExpiredLeaseAction(args) {
929
+ const { lease, stepStatus, now } = args;
930
+ if (stepStatus === "completed" || stepStatus === "failed" || stepStatus === "canceled" || stepStatus === "skipped") {
931
+ return { tag: "skip", reason: "terminal" };
932
+ }
933
+ if (lease.expiresAt > now) {
934
+ return { tag: "skip", reason: "still-live" };
935
+ }
936
+ return {
937
+ tag: "reap",
938
+ nextAttempt: lease.attempt + 1,
939
+ backoffMs: 0
940
+ };
941
+ }
942
+ var DEFAULT_REAPER_INTERVAL_MS = 3e4;
943
+
869
944
  // src/facts.ts
870
945
  var Facts = {
871
946
  flowStarted(a) {
@@ -988,6 +1063,17 @@ var Facts = {
988
1063
  ...compact({ signalName: a.signalName })
989
1064
  };
990
1065
  },
1066
+ leaseReaped(a) {
1067
+ return {
1068
+ kind: "lease.reaped",
1069
+ runId: a.runId,
1070
+ stepId: a.stepId,
1071
+ attempt: a.attempt,
1072
+ at: a.at,
1073
+ reapedAt: a.reapedAt,
1074
+ reason: "expired"
1075
+ };
1076
+ },
991
1077
  flowRefUpdated(a) {
992
1078
  return {
993
1079
  kind: "flow_ref.updated",
@@ -1390,6 +1476,12 @@ var InMemoryStore = class {
1390
1476
  }
1391
1477
  return { started: true, canceled };
1392
1478
  }
1479
+ // In-memory has no real tx; we share the underlying maps with tryStartRun,
1480
+ // so the implementation is intentionally a straight delegate. The `tx`
1481
+ // parameter is accepted for shape-compat with the Store contract.
1482
+ async tryStartRunOnTx(_tx, runId, fact, concurrency) {
1483
+ return this.tryStartRun(runId, fact, concurrency);
1484
+ }
1393
1485
  async listChildren(parentRunId) {
1394
1486
  const set = this.childrenByParent.get(parentRunId);
1395
1487
  if (set === void 0) return [];
@@ -1409,6 +1501,72 @@ var InMemoryStore = class {
1409
1501
  this.leases.set(key, { token, expiresAt: now + this.leaseMs });
1410
1502
  return token;
1411
1503
  }
1504
+ async extendLease(runId, stepId, attempt, leaseMs) {
1505
+ const key = `${runId}::${stepId}::${attempt}`;
1506
+ const existing = this.leases.get(key);
1507
+ if (existing === void 0) return;
1508
+ this.leases.set(key, {
1509
+ token: existing.token,
1510
+ expiresAt: Date.now() + leaseMs
1511
+ });
1512
+ }
1513
+ async sweepLeases(args) {
1514
+ const { now, queue, limit = 100 } = args;
1515
+ const reaped = [];
1516
+ const candidates = [];
1517
+ for (const [key, lease] of this.leases) {
1518
+ if (candidates.length >= limit) break;
1519
+ const parts = key.split("::");
1520
+ if (parts.length !== 3) continue;
1521
+ const [runId, stepId, attemptStr] = parts;
1522
+ candidates.push({
1523
+ key,
1524
+ runId,
1525
+ stepId,
1526
+ attempt: Number(attemptStr),
1527
+ expiresAt: new Date(lease.expiresAt)
1528
+ });
1529
+ }
1530
+ for (const c of candidates) {
1531
+ const factList = this.facts.get(c.runId);
1532
+ const state = factList ? foldRun(c.runId, factList) : null;
1533
+ const ss = state ? stepStateOf(state, c.stepId) : null;
1534
+ const stepStatus = ss === null ? "pending" : stepStatusOf(ss);
1535
+ const decision = decideExpiredLeaseAction({
1536
+ lease: {
1537
+ runId: c.runId,
1538
+ stepId: c.stepId,
1539
+ attempt: c.attempt,
1540
+ expiresAt: c.expiresAt
1541
+ },
1542
+ stepStatus,
1543
+ now
1544
+ });
1545
+ if (decision.tag === "skip") continue;
1546
+ this.leases.delete(c.key);
1547
+ await this.appendFact(
1548
+ c.runId,
1549
+ Facts.leaseReaped({
1550
+ runId: c.runId,
1551
+ stepId: c.stepId,
1552
+ attempt: c.attempt,
1553
+ at: now,
1554
+ reapedAt: now
1555
+ })
1556
+ );
1557
+ await queue.enqueue(c.runId, c.stepId, {
1558
+ attempt: decision.nextAttempt,
1559
+ delayMs: decision.backoffMs
1560
+ });
1561
+ reaped.push({
1562
+ runId: c.runId,
1563
+ stepId: c.stepId,
1564
+ attempt: c.attempt,
1565
+ nextAttempt: decision.nextAttempt
1566
+ });
1567
+ }
1568
+ return reaped;
1569
+ }
1412
1570
  async settleStep(runId, _stepId, fact) {
1413
1571
  await this.appendFact(runId, fact);
1414
1572
  }
@@ -1494,6 +1652,117 @@ var InMemoryStore = class {
1494
1652
  const cursor = hasMore && last !== void 0 ? encodeCursor({ t: last.startedAt.getTime(), r: last.runId }) : null;
1495
1653
  return { runs: page, cursor };
1496
1654
  }
1655
+ async describe(runId) {
1656
+ const factList = this.facts.get(runId);
1657
+ if (factList === void 0 || factList.length === 0) return null;
1658
+ const first = factList[0];
1659
+ if (first === void 0 || first.kind !== "flow.started") return null;
1660
+ const state = foldRun(runId, factList);
1661
+ const status = runStatusOf(state);
1662
+ let completedAt;
1663
+ let output;
1664
+ let error;
1665
+ let canceledByRunId;
1666
+ let concurrencyKey;
1667
+ for (let i = factList.length - 1; i >= 0; i--) {
1668
+ const f = factList[i];
1669
+ if (f === void 0) continue;
1670
+ if (f.kind === "flow.completed") {
1671
+ completedAt = f.at;
1672
+ output = f.output;
1673
+ break;
1674
+ }
1675
+ if (f.kind === "flow.failed") {
1676
+ completedAt = f.at;
1677
+ error = f.error;
1678
+ break;
1679
+ }
1680
+ if (f.kind === "flow.canceled") {
1681
+ completedAt = f.at;
1682
+ if (f.cause === "concurrency") {
1683
+ canceledByRunId = f.canceledByRunId;
1684
+ }
1685
+ break;
1686
+ }
1687
+ }
1688
+ const slot = this.keyByActiveRun.get(runId);
1689
+ if (slot !== void 0) {
1690
+ const sep = slot.indexOf("::");
1691
+ if (sep >= 0) concurrencyKey = slot.slice(sep + 2);
1692
+ }
1693
+ if (concurrencyKey === void 0) {
1694
+ for (const f of factList) {
1695
+ if (f.kind === "flow.canceled" && f.cause === "concurrency") {
1696
+ concurrencyKey = f.concurrencyKey;
1697
+ break;
1698
+ }
1699
+ }
1700
+ }
1701
+ const childSet = this.childrenByParent.get(runId);
1702
+ const children = childSet ? Array.from(childSet) : [];
1703
+ const parent = first.parent;
1704
+ const run = {
1705
+ runId,
1706
+ flowId: first.flowId,
1707
+ flowHash: first.flowHash ?? "",
1708
+ status,
1709
+ startedAt: first.at,
1710
+ input: first.input,
1711
+ children,
1712
+ ...completedAt !== void 0 ? { completedAt } : {},
1713
+ ...output !== void 0 ? { output } : {},
1714
+ ...error !== void 0 ? { error } : {},
1715
+ ...canceledByRunId !== void 0 ? { canceledByRunId } : {},
1716
+ ...concurrencyKey !== void 0 ? { concurrencyKey } : {},
1717
+ ...parent !== void 0 ? { parent } : {}
1718
+ };
1719
+ const steps = [];
1720
+ const startedAtByStep = /* @__PURE__ */ new Map();
1721
+ const completedAtByStep = /* @__PURE__ */ new Map();
1722
+ for (const f of factList) {
1723
+ if (f.kind === "step.started" && !startedAtByStep.has(f.stepId)) {
1724
+ startedAtByStep.set(f.stepId, f.at);
1725
+ }
1726
+ if ((f.kind === "step.completed" || f.kind === "step.failed" || f.kind === "step.canceled" || f.kind === "step.skipped") && !completedAtByStep.has(f.stepId)) {
1727
+ completedAtByStep.set(f.stepId, f.at);
1728
+ }
1729
+ }
1730
+ const now = Date.now();
1731
+ for (const [stepId, stepState] of Object.entries(state.steps)) {
1732
+ const status2 = stepStatusOf(stepState);
1733
+ const attempt = attemptOf(stepState);
1734
+ const out = outputOf(stepState);
1735
+ const err = errorOf(stepState);
1736
+ const startedAt = startedAtByStep.get(stepId);
1737
+ const completedAt2 = completedAtByStep.get(stepId);
1738
+ let lease;
1739
+ const leasePrefix = `${runId}::${stepId}::`;
1740
+ let bestExpiry = 0;
1741
+ for (const [key, l] of this.leases) {
1742
+ if (!key.startsWith(leasePrefix)) continue;
1743
+ if (l.expiresAt > now && l.expiresAt > bestExpiry)
1744
+ bestExpiry = l.expiresAt;
1745
+ }
1746
+ if (bestExpiry > 0) lease = { expiresAt: new Date(bestExpiry) };
1747
+ steps.push({
1748
+ stepId,
1749
+ attempt,
1750
+ status: status2,
1751
+ ...startedAt !== void 0 ? { startedAt } : {},
1752
+ ...completedAt2 !== void 0 ? { completedAt: completedAt2 } : {},
1753
+ ...out !== null ? { output: out } : {},
1754
+ ...err !== void 0 ? { error: err } : {},
1755
+ ...lease !== void 0 ? { lease } : {}
1756
+ });
1757
+ }
1758
+ steps.sort((a, b) => {
1759
+ const ta = a.startedAt?.getTime() ?? Number.POSITIVE_INFINITY;
1760
+ const tb = b.startedAt?.getTime() ?? Number.POSITIVE_INFINITY;
1761
+ if (ta !== tb) return ta - tb;
1762
+ return a.stepId < b.stepId ? -1 : a.stepId > b.stepId ? 1 : 0;
1763
+ });
1764
+ return { run, steps };
1765
+ }
1497
1766
  async pruneFacts(opts) {
1498
1767
  const olderThanMs = opts.olderThan.getTime();
1499
1768
  const statusSet = new Set(opts.statuses);
@@ -1738,6 +2007,26 @@ var InMemoryTrigger = class {
1738
2007
  }
1739
2008
  };
1740
2009
 
2010
+ // src/run-id.ts
2011
+ var RunId = {
2012
+ parse(s) {
2013
+ if (typeof s !== "string" || s.length === 0) {
2014
+ throw validationError("RunId.parse: must be a non-empty string", [
2015
+ "runId"
2016
+ ]);
2017
+ }
2018
+ if (/\s/.test(s)) {
2019
+ throw validationError("RunId.parse: must not contain whitespace", [
2020
+ "runId"
2021
+ ]);
2022
+ }
2023
+ return s;
2024
+ },
2025
+ fromTrusted(s) {
2026
+ return s;
2027
+ }
2028
+ };
2029
+
1741
2030
  // src/exec/hooks.ts
1742
2031
  function makeHooks(deps) {
1743
2032
  async function fireHook(hook, event, hookName) {
@@ -1977,14 +2266,14 @@ var DEFAULT_RETRY2 = {
1977
2266
  var CANCEL_POLL_INTERVAL_MS = 250;
1978
2267
  var NagiAbortError = class extends Error {
1979
2268
  runId;
1980
- scope;
1981
- constructor(runId, scope) {
2269
+ kind;
2270
+ constructor(runId, kind) {
1982
2271
  super(
1983
- scope === "run" ? `Run ${runId} was canceled \u2014 ctx.signal aborted.` : `Step in run ${runId} was aborted by operator.retry() \u2014 ctx.signal aborted.`
2272
+ kind === "run" ? `Run ${runId} was canceled \u2014 ctx.signal aborted.` : `Step in run ${runId} was aborted by operator.retry() \u2014 ctx.signal aborted.`
1984
2273
  );
1985
- this.name = "NagiAbortError";
2274
+ this.name = "AbortError";
1986
2275
  this.runId = runId;
1987
- this.scope = scope;
2276
+ this.kind = kind;
1988
2277
  }
1989
2278
  };
1990
2279
  function resolveExecutionFact(args) {
@@ -2033,6 +2322,56 @@ function startCancelWatcher(args) {
2033
2322
  }
2034
2323
  };
2035
2324
  }
2325
+ var DEFAULT_HEARTBEAT_LEASE_MS = 12e4;
2326
+ var DEFAULT_HEARTBEAT_INTERVAL_MS = 4e4;
2327
+ function startHeartbeat(args) {
2328
+ const {
2329
+ queue,
2330
+ store,
2331
+ runId,
2332
+ stepId,
2333
+ attempt,
2334
+ receipt,
2335
+ intervalMs,
2336
+ leaseMs,
2337
+ emitLog
2338
+ } = args;
2339
+ let stopped = false;
2340
+ let timer;
2341
+ const schedule = () => {
2342
+ timer = setTimeout(() => {
2343
+ void (async () => {
2344
+ await Promise.all([
2345
+ queue.extend(receipt, leaseMs).catch((err) => {
2346
+ emitLog({
2347
+ level: "warn",
2348
+ msg: "heartbeat: failed to extend message visibility",
2349
+ attrs: { receipt, error: String(err) }
2350
+ });
2351
+ }),
2352
+ store.extendLease(runId, stepId, attempt, leaseMs).catch((err) => {
2353
+ emitLog({
2354
+ level: "warn",
2355
+ msg: "heartbeat: failed to extend store lease",
2356
+ attrs: { runId, stepId, attempt, error: String(err) }
2357
+ });
2358
+ })
2359
+ ]);
2360
+ if (!stopped) schedule();
2361
+ })();
2362
+ }, intervalMs);
2363
+ };
2364
+ schedule();
2365
+ return {
2366
+ // Clear the pending timer so a settled step strands nothing on the event
2367
+ // loop — without this every fast step would leak a timer for up to
2368
+ // intervalMs, keeping the process alive and delaying clean shutdown.
2369
+ stop: () => {
2370
+ stopped = true;
2371
+ if (timer !== void 0) clearTimeout(timer);
2372
+ }
2373
+ };
2374
+ }
2036
2375
  function classifyFailure(args) {
2037
2376
  const { attempt, policy, err, runIsCanceled, stepAborted } = args;
2038
2377
  if (runIsCanceled || stepAborted) {
@@ -2043,11 +2382,29 @@ function classifyFailure(args) {
2043
2382
  includeError: isAbort
2044
2383
  };
2045
2384
  }
2385
+ const cancel = findNagiCanceledError(err);
2386
+ if (cancel !== void 0) {
2387
+ return {
2388
+ tag: "flowCanceled",
2389
+ canceledByRunId: cancel.canceledByRunId,
2390
+ concurrencyKey: cancel.concurrencyKey
2391
+ };
2392
+ }
2046
2393
  if (attempt < policy.maxAttempts && retryAllows(policy, err)) {
2047
2394
  return { tag: "retry", delayMs: computeBackoff(policy, attempt) };
2048
2395
  }
2049
2396
  return { tag: "failed" };
2050
2397
  }
2398
+ function findNagiCanceledError(err) {
2399
+ let cursor = err;
2400
+ const seen = /* @__PURE__ */ new Set();
2401
+ while (cursor instanceof Error && !seen.has(cursor)) {
2402
+ if (cursor instanceof NagiCanceledError) return cursor;
2403
+ seen.add(cursor);
2404
+ cursor = cursor.cause;
2405
+ }
2406
+ return void 0;
2407
+ }
2051
2408
  function computeBackoff(policy, attempt) {
2052
2409
  const initial = policy.initialDelayMs ?? 1e3;
2053
2410
  const max = policy.maxDelayMs ?? 6e4;
@@ -2064,8 +2421,8 @@ function retryAllows(policy, err) {
2064
2421
  if (!policy.retryOn) return true;
2065
2422
  return policy.retryOn(err);
2066
2423
  }
2067
- function makeStepCtx(args) {
2068
- const { runId, stepId, attempt, input, store, clock, tx, signal, emitLog } = args;
2424
+ function makeBaseCtx(args) {
2425
+ const { runId, stepId, attempt, input, store, clock, signal, emitLog } = args;
2069
2426
  const log = (level) => (msg, attrs) => emitLog({ level, msg, attrs: { ...attrs, runId, stepId, attempt } });
2070
2427
  const logger = {
2071
2428
  debug: log("debug"),
@@ -2080,12 +2437,25 @@ function makeStepCtx(args) {
2080
2437
  attempt,
2081
2438
  signal,
2082
2439
  now: () => clock.now(),
2083
- tx,
2084
2440
  logger,
2085
2441
  once: makeOnce({ runId, stepId, store }),
2086
2442
  idempotencyKey: makeIdempotencyKey(runId, stepId)
2087
2443
  };
2088
2444
  }
2445
+ function makeStepCtx(args) {
2446
+ const { tx, ...base } = args;
2447
+ return { ...makeBaseCtx(base), tx };
2448
+ }
2449
+ function makeActivityCtx(args) {
2450
+ return {
2451
+ ...makeBaseCtx(args),
2452
+ get tx() {
2453
+ throw new Error(
2454
+ "nagi: activity steps have no ctx.tx \u2014 they run outside the durable transaction. Write idempotently via your own client, or use a task."
2455
+ );
2456
+ }
2457
+ };
2458
+ }
2089
2459
 
2090
2460
  // src/exec/message.ts
2091
2461
  function makeMessage(deps, hooks, progression) {
@@ -2102,11 +2472,24 @@ function makeMessage(deps, hooks, progression) {
2102
2472
  const { def, state } = admission;
2103
2473
  await recordStarted({ flow: flow2, message, def, state });
2104
2474
  const startedAt = Date.now();
2475
+ const heartbeat = startHeartbeat({
2476
+ queue,
2477
+ store: deps.store,
2478
+ runId: message.runId,
2479
+ stepId: message.stepId,
2480
+ attempt: message.attempt,
2481
+ receipt: message.receipt,
2482
+ intervalMs: deps.heartbeat.intervalMs,
2483
+ leaseMs: deps.heartbeat.leaseMs,
2484
+ emitLog: deps.emitLog
2485
+ });
2105
2486
  let outcome;
2106
2487
  try {
2107
2488
  outcome = await execute({ flow: flow2, message, def, state });
2108
2489
  } catch (err) {
2109
2490
  outcome = await handleStepError({ flow: flow2, message, def, err });
2491
+ } finally {
2492
+ heartbeat.stop();
2110
2493
  }
2111
2494
  await queue.ack(message.receipt);
2112
2495
  await interpret({ flow: flow2, message, def, startedAt, outcome });
@@ -2142,7 +2525,7 @@ function makeMessage(deps, hooks, progression) {
2142
2525
  runId,
2143
2526
  Facts.stepStarted(runId, stepId, attempt, def.kind, clock.now())
2144
2527
  );
2145
- const startCarriesInput = def.kind === "task" || def.kind === "streaming" || def.kind === "subflow";
2528
+ const startCarriesInput = def.kind === "task" || def.kind === "activity" || def.kind === "streaming" || def.kind === "subflow";
2146
2529
  const input = startCarriesInput ? state.input : null;
2147
2530
  await fireStepLifecycle(
2148
2531
  handler?.onStart,
@@ -2174,6 +2557,16 @@ function makeMessage(deps, hooks, progression) {
2174
2557
  });
2175
2558
  return skipAdvance ? { tag: "parked" } : { tag: "completed", output };
2176
2559
  }
2560
+ case "activity": {
2561
+ const { output, skipAdvance } = await executeActivity({
2562
+ def,
2563
+ runId,
2564
+ stepId,
2565
+ attempt,
2566
+ state
2567
+ });
2568
+ return skipAdvance ? { tag: "parked" } : { tag: "completed", output };
2569
+ }
2177
2570
  case "signal": {
2178
2571
  const settled = await deps.store.settleSignal({
2179
2572
  runId,
@@ -2315,6 +2708,56 @@ function makeMessage(deps, hooks, progression) {
2315
2708
  watcher.stop();
2316
2709
  }
2317
2710
  }
2711
+ async function executeActivity(args) {
2712
+ const { def, runId, stepId, attempt, state } = args;
2713
+ const { store, clock } = deps;
2714
+ const input = state.input;
2715
+ const needs = resolveNeeds(def, (id) => resolvedOf(stepStateOf(state, id)));
2716
+ const ac = new AbortController();
2717
+ const watcher = startCancelWatcher({
2718
+ store,
2719
+ runId,
2720
+ stepId,
2721
+ attempt,
2722
+ ac,
2723
+ intervalMs: deps.cancelPollIntervalMs ?? CANCEL_POLL_INTERVAL_MS
2724
+ });
2725
+ try {
2726
+ const ctx = makeActivityCtx({
2727
+ runId,
2728
+ stepId,
2729
+ attempt,
2730
+ input,
2731
+ store,
2732
+ clock,
2733
+ signal: ac.signal,
2734
+ emitLog: deps.emitLog
2735
+ });
2736
+ const out = await runHandler(def, { input, needs, ctx, runId, stepId });
2737
+ let stepAbortedHere = false;
2738
+ const output = await store.runStep(
2739
+ runId,
2740
+ stepId,
2741
+ attempt,
2742
+ async () => {
2743
+ const postState = await store.loadRunState(runId);
2744
+ const { fact, abortedHere } = resolveExecutionFact({
2745
+ postState,
2746
+ runId,
2747
+ stepId,
2748
+ attempt,
2749
+ output: out,
2750
+ at: clock.now()
2751
+ });
2752
+ stepAbortedHere = abortedHere;
2753
+ return { output: out, fact };
2754
+ }
2755
+ );
2756
+ return { output, skipAdvance: stepAbortedHere };
2757
+ } finally {
2758
+ watcher.stop();
2759
+ }
2760
+ }
2318
2761
  async function executeSubflow(args) {
2319
2762
  const { def, runId, stepId, attempt, state } = args;
2320
2763
  const child = deps.lookupFlow(def.childFlowId);
@@ -2407,6 +2850,23 @@ function makeMessage(deps, hooks, progression) {
2407
2850
  );
2408
2851
  return { tag: "advance" };
2409
2852
  }
2853
+ case "flowCanceled": {
2854
+ const at = clock.now();
2855
+ await store.appendFact(
2856
+ runId,
2857
+ Facts.stepCanceled(runId, stepId, attempt, at, error)
2858
+ );
2859
+ await store.appendFact(
2860
+ runId,
2861
+ Facts.flowCanceledByConcurrency({
2862
+ runId,
2863
+ at,
2864
+ canceledByRunId: outcome.canceledByRunId,
2865
+ concurrencyKey: outcome.concurrencyKey
2866
+ })
2867
+ );
2868
+ return { tag: "parked" };
2869
+ }
2410
2870
  }
2411
2871
  }
2412
2872
  return { dispatchMessage };
@@ -2622,8 +3082,20 @@ function makeFlowRegistry(flows) {
2622
3082
  }
2623
3083
  return flow2;
2624
3084
  },
2625
- requireForRun(flowId, runId) {
3085
+ requireForRun(flowId, runId, pinnedHash, currentHashOf) {
2626
3086
  const flow2 = byId.get(flowId);
3087
+ if (pinnedHash !== void 0) {
3088
+ const currentHash = flow2 === void 0 ? null : currentHashOf?.(flowId) ?? null;
3089
+ if (flow2 === void 0 || currentHash !== pinnedHash) {
3090
+ throw new NagiFlowSnapshotGoneError({
3091
+ runId,
3092
+ flowId,
3093
+ pinnedHash,
3094
+ currentHash
3095
+ });
3096
+ }
3097
+ return flow2;
3098
+ }
2627
3099
  if (!flow2) {
2628
3100
  throw new NagiRuntimeError(
2629
3101
  `Run ${runId} references flow "${flowId}" which is not registered with nagi().`
@@ -2947,6 +3419,23 @@ var WorkerImpl = class {
2947
3419
  try {
2948
3420
  await this.dispatcher.dispatchMessage(msg);
2949
3421
  } catch (err) {
3422
+ if (err instanceof NagiFlowSnapshotGoneError) {
3423
+ this.deps.emitLog({
3424
+ level: "warn",
3425
+ msg: "worker.dispatch: flow snapshot gone \u2014 nacking",
3426
+ attrs: {
3427
+ runId: err.runId,
3428
+ flowId: err.flowId,
3429
+ pinnedHash: err.pinnedHash,
3430
+ currentHash: err.currentHash
3431
+ }
3432
+ });
3433
+ try {
3434
+ await this.deps.queue.nack(msg.receipt);
3435
+ } catch {
3436
+ }
3437
+ return;
3438
+ }
2950
3439
  this.deps.emitLog({
2951
3440
  level: "error",
2952
3441
  msg: "worker.dispatch threw uncaught",
@@ -3017,7 +3506,12 @@ async function nagiImpl(config) {
3017
3506
  const codeVersion = config.codeVersion ?? await fingerprintFlows(config.flows);
3018
3507
  async function flowFor(runId) {
3019
3508
  const runState = await config.store.loadRunState(runId);
3020
- return registry.requireForRun(runState.flowId, runId);
3509
+ return registry.requireForRun(
3510
+ runState.flowId,
3511
+ runId,
3512
+ runState.flowHash,
3513
+ (id) => flowHashById.get(id)
3514
+ );
3021
3515
  }
3022
3516
  function lookupFlow(flowId) {
3023
3517
  return registry.get(flowId);
@@ -3175,6 +3669,12 @@ async function nagiImpl(config) {
3175
3669
  queue: config.queue,
3176
3670
  clock,
3177
3671
  emitLog,
3672
+ // The one fork point for heartbeat tuning: collapse the public optionals to
3673
+ // a single required config here so the dispatch internals never re-check it.
3674
+ heartbeat: {
3675
+ intervalMs: config.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS,
3676
+ leaseMs: config.heartbeatLeaseMs ?? DEFAULT_HEARTBEAT_LEASE_MS
3677
+ },
3178
3678
  ...compact({
3179
3679
  hooks: config.hooks,
3180
3680
  defaultRetry: config.defaultRetry,
@@ -3218,6 +3718,121 @@ async function nagiImpl(config) {
3218
3718
  await startRunInternal({ flow: flow2, validatedInput: validated, runId });
3219
3719
  return runId;
3220
3720
  },
3721
+ async startStaged(flow2, input, opts) {
3722
+ return wf.startStagedById(flow2.id, input, opts);
3723
+ },
3724
+ async startStagedById(flowId, input, opts) {
3725
+ if (opts === void 0 || opts.tx === void 0) {
3726
+ throw validationError(
3727
+ "startStaged: opts.tx is required (the caller-supplied transaction the run row, flow.started fact, and initial enqueue commit on).",
3728
+ ["tx"]
3729
+ );
3730
+ }
3731
+ const flow2 = registry.require(flowId);
3732
+ let runId;
3733
+ if (opts.runId !== void 0) {
3734
+ if (typeof opts.runId !== "string" || opts.runId.length === 0) {
3735
+ throw validationError("opts.runId must be a non-empty string", [
3736
+ "runId"
3737
+ ]);
3738
+ }
3739
+ runId = opts.runId;
3740
+ } else {
3741
+ runId = mintRunId();
3742
+ }
3743
+ const validated = await validate(flow2.input, input);
3744
+ const startedAt = clock.now();
3745
+ const flowHash = flowHashById.get(flow2.id);
3746
+ const fact = Facts.flowStarted({
3747
+ runId,
3748
+ flowId: flow2.id,
3749
+ input: validated,
3750
+ at: startedAt,
3751
+ codeVersion,
3752
+ ...compact({ flowHash })
3753
+ });
3754
+ let concurrencyArg;
3755
+ if (flow2.concurrency !== void 0) {
3756
+ const derived = flow2.concurrency.keyFn(validated);
3757
+ if (typeof derived !== "string" || derived.length === 0) {
3758
+ throw validationError(
3759
+ `flow.concurrency.keyFn must return a non-empty string (got ${typeof derived === "string" ? '""' : typeof derived})`,
3760
+ ["concurrency", "keyFn"]
3761
+ );
3762
+ }
3763
+ concurrencyArg = { key: derived, mode: flow2.concurrency.mode };
3764
+ }
3765
+ const { started, canceled } = await config.store.tryStartRunOnTx(
3766
+ opts.tx,
3767
+ runId,
3768
+ fact,
3769
+ concurrencyArg
3770
+ );
3771
+ if (started) {
3772
+ const seedState = foldRun(runId, [fact]);
3773
+ const transition = nextTransition(flow2, seedState);
3774
+ if (transition.kind === "dispatch") {
3775
+ const txQueue = bindQueueToTx(config.queue, opts.tx);
3776
+ for (const stepId of transition.runnable) {
3777
+ await txQueue.enqueue(runId, stepId);
3778
+ }
3779
+ }
3780
+ }
3781
+ let fired = false;
3782
+ const applyOnCommit = async () => {
3783
+ if (fired) return;
3784
+ fired = true;
3785
+ if (!started) return;
3786
+ for (const c of canceled) {
3787
+ const cancelError = new NagiCanceledError({
3788
+ runId: c.runId,
3789
+ canceledByRunId: runId,
3790
+ concurrencyKey: c.fact.concurrencyKey
3791
+ });
3792
+ const serialized = {
3793
+ ...serializeError(cancelError),
3794
+ cause: {
3795
+ canceledByRunId: runId,
3796
+ concurrencyKey: c.fact.concurrencyKey
3797
+ }
3798
+ };
3799
+ const errorEvent = {
3800
+ runId: c.runId,
3801
+ flowId: flow2.id,
3802
+ error: serialized,
3803
+ at: c.fact.at
3804
+ };
3805
+ await hooks.fireHook(flow2.onError, errorEvent, "flow.onError");
3806
+ await hooks.fireHook(
3807
+ config.hooks?.onFlowError,
3808
+ errorEvent,
3809
+ "onFlowError"
3810
+ );
3811
+ await dispatcher.propagateToParent(c.runId, {
3812
+ kind: "canceled",
3813
+ error: serialized
3814
+ });
3815
+ }
3816
+ const startEvent = {
3817
+ runId,
3818
+ flowId: flow2.id,
3819
+ input: validated,
3820
+ at: startedAt
3821
+ };
3822
+ await hooks.fireHook(flow2.onStart, startEvent, "flow.onStart");
3823
+ await hooks.fireHook(
3824
+ config.hooks?.onFlowStart,
3825
+ startEvent,
3826
+ "onFlowStart"
3827
+ );
3828
+ };
3829
+ return {
3830
+ runId,
3831
+ started,
3832
+ canceled: canceled.map((c) => c.runId),
3833
+ applyOnCommit
3834
+ };
3835
+ },
3221
3836
  signal: signals.signal,
3222
3837
  async cancel(runId, opts) {
3223
3838
  await cancelRunRecursive(runId, {
@@ -3244,6 +3859,9 @@ async function nagiImpl(config) {
3244
3859
  return makeWorker({ ...dispatchDeps, clock }, workerConfig);
3245
3860
  },
3246
3861
  replay: replayer.replay,
3862
+ async describe(runId) {
3863
+ return config.store.describe(runId);
3864
+ },
3247
3865
  async queryRuns(opts = {}) {
3248
3866
  if (opts.latest === true) {
3249
3867
  if (opts.limit !== void 0 || opts.cursor !== void 0) {
@@ -3314,6 +3932,7 @@ async function nagiRun(config) {
3314
3932
  const signal = config.signal ? AbortSignal.any([internal.signal, config.signal]) : internal.signal;
3315
3933
  const worker = wf.worker({ ...config.worker, signal });
3316
3934
  const emitLog = makeEmit(config.onLog);
3935
+ const clock = config.clock ?? new InMemoryClock();
3317
3936
  const loop = worker.run();
3318
3937
  loop.catch((err) => {
3319
3938
  if (signal.aborted) return;
@@ -3323,6 +3942,31 @@ async function nagiRun(config) {
3323
3942
  attrs: { error: String(err) }
3324
3943
  });
3325
3944
  });
3945
+ const reaperIntervalMs = config.reaperIntervalMs ?? DEFAULT_REAPER_INTERVAL_MS;
3946
+ const reaper = reaperIntervalMs > 0 ? (async () => {
3947
+ while (!signal.aborted) {
3948
+ try {
3949
+ await clock.sleep(reaperIntervalMs, signal);
3950
+ } catch {
3951
+ return;
3952
+ }
3953
+ if (signal.aborted) return;
3954
+ try {
3955
+ await config.store.sweepLeases({
3956
+ now: clock.now(),
3957
+ queue: config.queue
3958
+ });
3959
+ } catch (err) {
3960
+ emitLog({
3961
+ level: "warn",
3962
+ msg: "nagi.run: lease reaper sweep failed",
3963
+ attrs: { error: String(err) }
3964
+ });
3965
+ }
3966
+ }
3967
+ })() : Promise.resolve();
3968
+ reaper.catch(() => {
3969
+ });
3326
3970
  let stopping;
3327
3971
  const stop = () => {
3328
3972
  stopping ??= (async () => {
@@ -3331,6 +3975,10 @@ async function nagiRun(config) {
3331
3975
  await loop;
3332
3976
  } catch {
3333
3977
  }
3978
+ try {
3979
+ await reaper;
3980
+ } catch {
3981
+ }
3334
3982
  })();
3335
3983
  return stopping;
3336
3984
  };
@@ -3347,7 +3995,12 @@ function asStreamTransport(store) {
3347
3995
  const s = store;
3348
3996
  return typeof s.subscribeStream === "function" && typeof s.publishChunk === "function" ? s : void 0;
3349
3997
  }
3998
+ function bindQueueToTx(queue, tx) {
3999
+ const q = queue;
4000
+ if (typeof q.withTx === "function") return q.withTx(tx);
4001
+ return queue;
4002
+ }
3350
4003
 
3351
- export { InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiCanceledError, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, attemptOf, canonicalize, decideSignal, diffSnapshots, errorOf, fingerprintFlows, flow, isStepTerminal, isTerminalRun, nagi, optional, outputOf, foldRun as projectRunState, resolvedOf, runStatusOf, sha256Canonical, stepStateOf, stepStatusOf, unwrap };
4004
+ export { DEFAULT_REAPER_INTERVAL_MS, InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiAbortError, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, RunId, attemptOf, canonicalize, decideExpiredLeaseAction, decideSignal, diffSnapshots, errorOf, fingerprintFlows, flow, isStepTerminal, isTerminalRun, nagi, optional, outputOf, foldRun as projectRunState, resolvedOf, runStatusOf, sha256Canonical, stepStateOf, stepStatusOf, unwrap };
3352
4005
  //# sourceMappingURL=index.js.map
3353
4006
  //# sourceMappingURL=index.js.map