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

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
@@ -36,7 +36,7 @@ type RunDescription = {
36
36
 
37
37
  type ReaperDecision = {
38
38
  readonly tag: "skip";
39
- readonly reason: "terminal" | "still-live";
39
+ readonly reason: "terminal" | "still-live" | "child-active";
40
40
  } | {
41
41
  readonly tag: "reap";
42
42
  readonly nextAttempt: AttemptNumber;
@@ -50,6 +50,7 @@ declare function decideExpiredLeaseAction(args: {
50
50
  readonly expiresAt: Date;
51
51
  };
52
52
  readonly stepStatus: StepRunStatus;
53
+ readonly childActive: boolean;
53
54
  readonly now: Date;
54
55
  }): ReaperDecision;
55
56
  interface ReapedLease {
@@ -965,6 +966,7 @@ declare class InMemoryStore implements Store, StreamTransport {
965
966
  }>;
966
967
  }>;
967
968
  listChildren(parentRunId: RunId$1): Promise<ReadonlyArray<RunId$1>>;
969
+ private hasActiveChild;
968
970
  loadRunState(runId: RunId$1): Promise<RunState>;
969
971
  claimStep(runId: RunId$1, stepId: StepId, attempt: AttemptNumber): Promise<ClaimToken | null>;
970
972
  extendLease(runId: RunId$1, stepId: StepId, attempt: AttemptNumber, leaseMs: Millis): Promise<void>;
package/dist/index.js CHANGED
@@ -926,10 +926,13 @@ function serializeError(err) {
926
926
 
927
927
  // src/lease-reaper.ts
928
928
  function decideExpiredLeaseAction(args) {
929
- const { lease, stepStatus, now } = args;
929
+ const { lease, stepStatus, childActive, now } = args;
930
930
  if (stepStatus === "completed" || stepStatus === "failed" || stepStatus === "canceled" || stepStatus === "skipped") {
931
931
  return { tag: "skip", reason: "terminal" };
932
932
  }
933
+ if (childActive) {
934
+ return { tag: "skip", reason: "child-active" };
935
+ }
933
936
  if (lease.expiresAt > now) {
934
937
  return { tag: "skip", reason: "still-live" };
935
938
  }
@@ -1487,6 +1490,23 @@ var InMemoryStore = class {
1487
1490
  if (set === void 0) return [];
1488
1491
  return Array.from(set);
1489
1492
  }
1493
+ // Does a non-terminal child exist for this (parentRunId, stepId)? Used by the
1494
+ // reaper to leave a subflow step parked while its child still runs (instead
1495
+ // of re-dispatching it at attempt+1). childrenByParent is keyed by parent run
1496
+ // only, so filter on the child's parent.stepId.
1497
+ hasActiveChild(parentRunId, parentStepId) {
1498
+ const childIds = this.childrenByParent.get(parentRunId);
1499
+ if (childIds === void 0) return false;
1500
+ for (const childId of childIds) {
1501
+ const factList = this.facts.get(childId);
1502
+ if (factList === void 0) continue;
1503
+ const child = foldRun(childId, factList);
1504
+ if (child.parent?.stepId === parentStepId && !isTerminalRun(child)) {
1505
+ return true;
1506
+ }
1507
+ }
1508
+ return false;
1509
+ }
1490
1510
  async loadRunState(runId) {
1491
1511
  return foldRun(runId, this.facts.get(runId) ?? []);
1492
1512
  }
@@ -1540,6 +1560,7 @@ var InMemoryStore = class {
1540
1560
  expiresAt: c.expiresAt
1541
1561
  },
1542
1562
  stepStatus,
1563
+ childActive: this.hasActiveChild(c.runId, c.stepId),
1543
1564
  now
1544
1565
  });
1545
1566
  if (decision.tag === "skip") continue;
@@ -2026,6 +2047,21 @@ var RunId = {
2026
2047
  return s;
2027
2048
  }
2028
2049
  };
2050
+ async function deriveChildRunId(key) {
2051
+ const seed = `nagi:subflow:${key.runId}:${key.stepId}:gen${key.generation}`;
2052
+ const digest = await crypto.subtle.digest(
2053
+ "SHA-256",
2054
+ new TextEncoder().encode(seed)
2055
+ );
2056
+ const bytes = new Uint8Array(digest).subarray(0, 16);
2057
+ bytes[6] = (bytes[6] ?? 0) & 15 | 80;
2058
+ bytes[8] = (bytes[8] ?? 0) & 63 | 128;
2059
+ const hex2 = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(
2060
+ ""
2061
+ );
2062
+ const uuid = `${hex2.slice(0, 8)}-${hex2.slice(8, 12)}-${hex2.slice(12, 16)}-${hex2.slice(16, 20)}-${hex2.slice(20, 32)}`;
2063
+ return `run-${uuid}`;
2064
+ }
2029
2065
 
2030
2066
  // src/exec/hooks.ts
2031
2067
  function makeHooks(deps) {
@@ -2458,6 +2494,13 @@ function makeActivityCtx(args) {
2458
2494
  }
2459
2495
 
2460
2496
  // src/exec/message.ts
2497
+ function subflowGeneration(state, stepId) {
2498
+ let n = 0;
2499
+ for (const f of state.facts) {
2500
+ if (f.kind === "step.reset" && f.stepId === stepId) n++;
2501
+ }
2502
+ return n;
2503
+ }
2461
2504
  function makeMessage(deps, hooks, progression) {
2462
2505
  const { fireHook, fireStepLifecycle } = hooks;
2463
2506
  const { advance } = progression;
@@ -2595,8 +2638,7 @@ function makeMessage(deps, hooks, progression) {
2595
2638
  await executeMatch({ def, runId, stepId, state });
2596
2639
  return { tag: "advance" };
2597
2640
  case "subflow":
2598
- await executeSubflow({ def, runId, stepId, attempt, state });
2599
- return { tag: "parked" };
2641
+ return await executeSubflow({ def, runId, stepId, attempt, state });
2600
2642
  }
2601
2643
  }
2602
2644
  async function interpret(args) {
@@ -2766,14 +2808,23 @@ function makeMessage(deps, hooks, progression) {
2766
2808
  `Subflow step "${stepId}" references child flow "${def.childFlowId}" which is not registered with nagi(). Pass it to flows[].`
2767
2809
  );
2768
2810
  }
2811
+ const generation = subflowGeneration(state, stepId);
2812
+ const childRunId = await deriveChildRunId({ runId, stepId, generation });
2813
+ const childState = await deps.store.loadRunState(childRunId);
2814
+ if (isTerminalRun(childState)) {
2815
+ await progression.wakeParentFromChild(childRunId);
2816
+ return { tag: "parked" };
2817
+ }
2769
2818
  const parentInput = state.input;
2770
2819
  const needs = resolveNeeds(def, (id) => resolvedOf(stepStateOf(state, id)));
2771
2820
  const childInput = def.buildInput({ input: parentInput, needs });
2772
2821
  await deps.startChildRun({
2773
2822
  child,
2774
2823
  childInput,
2775
- parent: { runId, stepId, attempt }
2824
+ parent: { runId, stepId, attempt },
2825
+ generation
2776
2826
  });
2827
+ return { tag: "parked" };
2777
2828
  }
2778
2829
  async function executeMatch(args) {
2779
2830
  const { def, runId, stepId, state } = args;
@@ -2874,6 +2925,44 @@ function makeMessage(deps, hooks, progression) {
2874
2925
 
2875
2926
  // src/exec/progression.ts
2876
2927
  var MAX_ADVANCE_ITERS = 1024;
2928
+ function subflowOutcomeOf(childRunId, child) {
2929
+ switch (child.phase.tag) {
2930
+ case "completed":
2931
+ return { kind: "completed", output: child.phase.output };
2932
+ case "failed":
2933
+ return { kind: "failed", error: child.phase.error };
2934
+ case "canceled":
2935
+ return {
2936
+ kind: "canceled",
2937
+ error: cancelCauseToError(childRunId, child.phase.cause)
2938
+ };
2939
+ default:
2940
+ return void 0;
2941
+ }
2942
+ }
2943
+ function cancelCauseToError(runId, cause) {
2944
+ switch (cause.kind) {
2945
+ case "concurrency":
2946
+ return {
2947
+ name: "NagiCanceledError",
2948
+ message: `Run ${runId} was canceled (superseded by ${cause.canceledByRunId})`,
2949
+ cause: {
2950
+ canceledByRunId: cause.canceledByRunId,
2951
+ concurrencyKey: cause.concurrencyKey
2952
+ }
2953
+ };
2954
+ case "explicit":
2955
+ return {
2956
+ name: "NagiCanceledError",
2957
+ message: `Run ${runId} was canceled: ${cause.reason}`
2958
+ };
2959
+ case "operator":
2960
+ return {
2961
+ name: "NagiCanceledError",
2962
+ message: `Run ${runId} was canceled by ${cause.actor}: ${cause.reason}`
2963
+ };
2964
+ }
2965
+ }
2877
2966
  function makeProgression(deps, hooks) {
2878
2967
  const { fireHook } = hooks;
2879
2968
  async function advance(runId) {
@@ -3037,7 +3126,13 @@ function makeProgression(deps, hooks) {
3037
3126
  });
3038
3127
  await advance(parentRunId);
3039
3128
  }
3040
- return { advance, propagateToParent };
3129
+ async function wakeParentFromChild(childRunId) {
3130
+ const child = await deps.store.loadRunState(childRunId);
3131
+ const outcome = subflowOutcomeOf(childRunId, child);
3132
+ if (outcome === void 0) return;
3133
+ await propagateToParent(childRunId, outcome);
3134
+ }
3135
+ return { advance, propagateToParent, wakeParentFromChild };
3041
3136
  }
3042
3137
 
3043
3138
  // src/dispatch.ts
@@ -3600,25 +3695,24 @@ async function nagiImpl(config) {
3600
3695
  return { started: true };
3601
3696
  }
3602
3697
  async function startChildRun(args) {
3603
- const { child, childInput, parent } = args;
3698
+ const { child, childInput, parent, generation } = args;
3604
3699
  if (!registry.has(child.id)) {
3605
3700
  throw new NagiRuntimeError(
3606
3701
  `Subflow child "${child.id}" not registered with nagi(). Pass it to flows[].`
3607
3702
  );
3608
3703
  }
3609
3704
  const validated = await validate(child.input, childInput);
3610
- const childRunId = mintRunId();
3611
- const { started } = await startRunInternal({
3705
+ const childRunId = await deriveChildRunId({
3706
+ runId: parent.runId,
3707
+ stepId: parent.stepId,
3708
+ generation
3709
+ });
3710
+ await startRunInternal({
3612
3711
  flow: child,
3613
3712
  validatedInput: validated,
3614
3713
  runId: childRunId,
3615
3714
  parent
3616
3715
  });
3617
- if (!started) {
3618
- throw new NagiRuntimeError(
3619
- `startChildRun: minted child runId collided with an existing run (${childRunId})`
3620
- );
3621
- }
3622
3716
  return childRunId;
3623
3717
  }
3624
3718
  async function cancelRunRecursive(runId, args) {