@bastani/atomic 0.9.88-alpha.1 → 0.9.88

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.
Files changed (55) hide show
  1. package/CHANGELOG.md +287 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +57 -0
  3. package/dist/builtin/intercom/index.bundle.mjs +62 -38
  4. package/dist/builtin/intercom/package.json +1 -1
  5. package/dist/builtin/intercom/session-target.ts +15 -3
  6. package/dist/builtin/mcp/package.json +1 -1
  7. package/dist/builtin/subagents/CHANGELOG.md +50 -0
  8. package/dist/builtin/subagents/package.json +1 -1
  9. package/dist/builtin/web-access/CHANGELOG.md +10 -0
  10. package/dist/builtin/web-access/package.json +1 -1
  11. package/dist/builtin/workflows/CHANGELOG.md +117 -0
  12. package/dist/builtin/workflows/README.md +2 -2
  13. package/dist/builtin/workflows/builtin/{chunk-r9xfx5d0.js → chunk-4h4nh4f1.js} +1 -1
  14. package/dist/builtin/workflows/builtin/{chunk-cryf7s3r.js → chunk-jm7redy5.js} +648 -91
  15. package/dist/builtin/workflows/builtin/{chunk-c7bc4ppx.js → chunk-t661k7hd.js} +1 -1
  16. package/dist/builtin/workflows/builtin/goal.js +2 -2
  17. package/dist/builtin/workflows/builtin/index.js +3 -3
  18. package/dist/builtin/workflows/builtin/ralph.js +2 -2
  19. package/dist/builtin/workflows/package.json +1 -1
  20. package/dist/builtin/workflows/src/durable/fork-errors.d.ts +0 -1
  21. package/dist/builtin/workflows/src/durable/journal/internal.d.ts +1 -0
  22. package/dist/builtin/workflows/src/extension/index.bundle.mjs +2515 -1091
  23. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +1092 -98
  24. package/dist/builtin/workflows/src/index.js +1077 -91
  25. package/dist/builtin/workflows/src/local-worker-entry.mjs +1092 -98
  26. package/dist/core/storage/session/session-resume.d.ts +8 -1
  27. package/dist/core/storage/session/session-resume.d.ts.map +1 -1
  28. package/dist/core/storage/session/session-resume.js +22 -3
  29. package/dist/core/storage/session/session-resume.js.map +1 -1
  30. package/dist/core/worktree-snapshot/restore.d.ts +2 -0
  31. package/dist/core/worktree-snapshot/restore.d.ts.map +1 -1
  32. package/dist/core/worktree-snapshot/restore.js +41 -5
  33. package/dist/core/worktree-snapshot/restore.js.map +1 -1
  34. package/dist/modes/interactive/components/jump-to-latest.d.ts +0 -5
  35. package/dist/modes/interactive/components/jump-to-latest.d.ts.map +1 -1
  36. package/dist/modes/interactive/components/jump-to-latest.js +0 -5
  37. package/dist/modes/interactive/components/jump-to-latest.js.map +1 -1
  38. package/dist/modes/interactive/interactive-mode-base.d.ts +1 -0
  39. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  40. package/dist/modes/interactive/interactive-mode-base.js +13 -2
  41. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  42. package/dist/modes/interactive/interactive-render-chat.d.ts +0 -4
  43. package/dist/modes/interactive/interactive-render-chat.d.ts.map +1 -1
  44. package/dist/modes/interactive/interactive-render-chat.js +19 -45
  45. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  46. package/dist/modes/interactive/interactive-startup-chat-container.d.ts +9 -1
  47. package/dist/modes/interactive/interactive-startup-chat-container.d.ts.map +1 -1
  48. package/dist/modes/interactive/interactive-startup-chat-container.js +38 -0
  49. package/dist/modes/interactive/interactive-startup-chat-container.js.map +1 -1
  50. package/docs/keybindings.md +1 -1
  51. package/docs/storage.md +1 -1
  52. package/docs/workflows/api-reference.md +3 -2
  53. package/docs/workflows/operations.md +11 -9
  54. package/npm-shrinkwrap.json +49 -49
  55. package/package.json +6 -6
@@ -599,7 +599,7 @@ var init_fork_errors = __esm(() => {
599
599
  code: "target-not-found",
600
600
  what: "Fork target not found",
601
601
  subject: `stage "${input.fromStage}" in run ${input.runId}`,
602
- hint: validStagePaths.length === 0 ? `The run has no completed stage to fork from yet; listForkPoints("${input.runId}") lists stages once they complete.` : `Pass one of: ${listedPaths(validStagePaths, totalValidStagePaths)}; listForkPoints("${input.runId}") lists them all.`,
602
+ hint: validStagePaths.length === 0 ? `The run has no eligible stage to fork from yet; listForkPoints("${input.runId}") lists completed stages.` : `Pass one of: ${listedPaths(validStagePaths, totalValidStagePaths)}; listForkPoints("${input.runId}") lists completed stages.`,
603
603
  retryable: false,
604
604
  fields: { runId: input.runId, fromStage: input.fromStage, validStagePaths, totalValidStagePaths }
605
605
  });
@@ -2687,6 +2687,7 @@ class SqlRunJournal {
2687
2687
  })
2688
2688
  } : {},
2689
2689
  read: (body) => this.operation(() => this.readSnapshot((executor) => body(this.versionChecked(executor)))),
2690
+ peek: (body) => this.operation(() => this.readSnapshot(body)),
2690
2691
  withAppendGuard: (guard, action) => this.appendGuard.run(guard, action),
2691
2692
  tables: this.tables,
2692
2693
  olderBuildLive: (executor) => olderBuildLive(executor, this.dialect, this.tables),
@@ -7016,6 +7017,96 @@ function flattenTruncatedString(value2) {
7016
7017
  return value2.split("").join("");
7017
7018
  }
7018
7019
 
7020
+ // dist/builtin/workflows/src/shared/inspection-payload.ts
7021
+ function boxedKind(value2) {
7022
+ try {
7023
+ const prototype = Object.getPrototypeOf(value2);
7024
+ if (prototype === Object.prototype || prototype === null || Array.isArray(value2))
7025
+ return;
7026
+ } catch {
7027
+ return;
7028
+ }
7029
+ try {
7030
+ Number.prototype.valueOf.call(value2);
7031
+ return "number";
7032
+ } catch {}
7033
+ try {
7034
+ String.prototype.valueOf.call(value2);
7035
+ return "string";
7036
+ } catch {}
7037
+ try {
7038
+ Boolean.prototype.valueOf.call(value2);
7039
+ return "boolean";
7040
+ } catch {}
7041
+ try {
7042
+ BigInt.prototype.valueOf.call(value2);
7043
+ return "bigint";
7044
+ } catch {}
7045
+ return;
7046
+ }
7047
+ function cloneValue(source, key, ancestors) {
7048
+ let value2 = source;
7049
+ if (value2 !== null && (typeof value2 === "object" || typeof value2 === "function") || typeof value2 === "bigint") {
7050
+ const convert = value2.toJSON;
7051
+ if (typeof convert === "function")
7052
+ value2 = convert.call(value2, key);
7053
+ }
7054
+ if (value2 !== null && typeof value2 === "object") {
7055
+ const kind = boxedKind(value2);
7056
+ if (kind === "number")
7057
+ value2 = Number(value2);
7058
+ else if (kind === "string")
7059
+ value2 = String(value2);
7060
+ else if (kind === "boolean")
7061
+ value2 = Boolean.prototype.valueOf.call(value2);
7062
+ else if (kind === "bigint")
7063
+ throw new TypeError("BigInt cannot be serialized");
7064
+ }
7065
+ if (value2 === null)
7066
+ return null;
7067
+ const json = JSON;
7068
+ if (typeof value2 === "object" && json.isRawJSON?.(value2) === true) {
7069
+ return JSON.parse(value2.rawJSON);
7070
+ }
7071
+ switch (typeof value2) {
7072
+ case "string":
7073
+ case "boolean":
7074
+ return value2;
7075
+ case "number":
7076
+ return Number.isFinite(value2) ? Object.is(value2, -0) ? 0 : value2 : null;
7077
+ case "bigint":
7078
+ throw new TypeError("BigInt cannot be serialized");
7079
+ case "undefined":
7080
+ case "function":
7081
+ case "symbol":
7082
+ return;
7083
+ }
7084
+ if (ancestors.has(value2))
7085
+ throw new TypeError("Circular snapshot value cannot be serialized");
7086
+ ancestors.add(value2);
7087
+ try {
7088
+ if (Array.isArray(value2)) {
7089
+ return Array.from({ length: value2.length }, (_, index) => cloneValue(value2[index], String(index), ancestors) ?? null);
7090
+ }
7091
+ const result = {};
7092
+ for (const name of Object.keys(value2)) {
7093
+ const item = cloneValue(value2[name], name, ancestors);
7094
+ if (item === undefined)
7095
+ continue;
7096
+ if (name === "__proto__")
7097
+ Object.defineProperty(result, name, { value: item, enumerable: true, configurable: true, writable: true });
7098
+ else
7099
+ result[name] = item;
7100
+ }
7101
+ return result;
7102
+ } finally {
7103
+ ancestors.delete(value2);
7104
+ }
7105
+ }
7106
+ function cloneInspectionPayload(value2) {
7107
+ return cloneValue(value2, "", new Set);
7108
+ }
7109
+
7019
7110
  // dist/builtin/workflows/src/shared/run-stage-index.ts
7020
7111
  function asksForInput(stage) {
7021
7112
  return stage.pendingPrompt !== undefined || stage.inputRequest !== undefined || stage.status === "awaiting_input" || stage.awaitingInputSince !== undefined;
@@ -7177,7 +7268,7 @@ function cloneObjectLike(state, value2) {
7177
7268
  items.push(null);
7178
7269
  continue;
7179
7270
  }
7180
- items.push(cloneValue(state, item));
7271
+ items.push(cloneValue2(state, item));
7181
7272
  }
7182
7273
  return items;
7183
7274
  }
@@ -7188,7 +7279,7 @@ function cloneObjectLike(state, value2) {
7188
7279
  const child = safeProperty(value2, key);
7189
7280
  if (isOmittedJsonValue(child))
7190
7281
  continue;
7191
- cloned[key] = cloneValue(state, child);
7282
+ cloned[key] = cloneValue2(state, child);
7192
7283
  }
7193
7284
  if (scan.stoppedByLimit())
7194
7285
  addTruncationMarker(cloned);
@@ -7198,7 +7289,7 @@ function cloneObjectLike(state, value2) {
7198
7289
  state.seen.delete(value2);
7199
7290
  }
7200
7291
  }
7201
- function cloneValue(state, value2) {
7292
+ function cloneValue2(state, value2) {
7202
7293
  const resolved = resolveJsonValue(value2);
7203
7294
  if (resolved === null) {
7204
7295
  state.remaining -= NULL_COST;
@@ -7224,7 +7315,7 @@ function cloneValue(state, value2) {
7224
7315
  }
7225
7316
  }
7226
7317
  function boundedToolPayload(value2, limit = TOOL_PAYLOAD_VALUE_LIMIT) {
7227
- return cloneValue({ remaining: Math.max(1, limit), depth: 0, keysRemaining: TOOL_PAYLOAD_MAX_KEYS, seen: new Set }, value2);
7318
+ return cloneValue2({ remaining: Math.max(1, limit), depth: 0, keysRemaining: TOOL_PAYLOAD_MAX_KEYS, seen: new Set }, value2);
7228
7319
  }
7229
7320
  function boundedToolPayloadRecord(value2, limit = TOOL_PAYLOAD_VALUE_LIMIT) {
7230
7321
  const record = {};
@@ -7242,7 +7333,7 @@ function boundedToolPayloadRecord(value2, limit = TOOL_PAYLOAD_VALUE_LIMIT) {
7242
7333
  const child = safeProperty(value2, key);
7243
7334
  if (isOmittedJsonValue(child))
7244
7335
  continue;
7245
- record[key] = cloneValue(state, child);
7336
+ record[key] = cloneValue2(state, child);
7246
7337
  }
7247
7338
  if (scan.stoppedByLimit())
7248
7339
  addTruncationMarker(record);
@@ -7381,7 +7472,11 @@ function compactToolNode(node) {
7381
7472
  ...node.source !== undefined ? { source: boundedToolText(node.source) } : {}
7382
7473
  };
7383
7474
  }
7384
- function compactRun(run, stages = run.stages.map(compactStage), toolNodes = run.toolNodes.map(compactToolNode)) {
7475
+ function compactRun(run, stages = run.stages.map(compactStage), toolNodes = run.toolNodes.map(compactToolNode), full = false) {
7476
+ if (full) {
7477
+ const copy = cloneInspectionPayload({ ...run, stages: [], toolNodes: [] });
7478
+ return { ...copy, stages, toolNodes };
7479
+ }
7385
7480
  const {
7386
7481
  inputs: _inputs,
7387
7482
  result: sourceResult,
@@ -7416,8 +7511,8 @@ function sameSourceShape(value2, shape) {
7416
7511
  function isSettledStage(stage) {
7417
7512
  return stage.status === "completed" || stage.status === "failed" || stage.status === "skipped";
7418
7513
  }
7419
- function projectStage(stage) {
7420
- const compact = compactStage(stage);
7514
+ function projectStage(stage, full = false) {
7515
+ const compact = full ? cloneInspectionPayload(stage) : compactStage(stage);
7421
7516
  deepFreezeGraphValue(compact);
7422
7517
  return {
7423
7518
  shape: sourceShape(stage),
@@ -7432,15 +7527,19 @@ function projectStage(stage) {
7432
7527
  function stageUnchanged(stage, projected) {
7433
7528
  return sameSourceShape(stage, projected.shape) && stage.parentIds.length === projected.parentCount && stage.toolEvents.length === projected.toolEventCount && stage.toolEvents.at(-1) === projected.lastToolEvent && stage.notices?.length === projected.noticeCount;
7434
7529
  }
7435
- function projectToolNode(node) {
7436
- const compact = compactToolNode(node);
7530
+ function projectToolNode(node, full = false) {
7531
+ const compact = full ? cloneInspectionPayload(node) : compactToolNode(node);
7437
7532
  deepFreezeGraphValue(compact);
7438
7533
  return { shape: sourceShape(node), parentCount: node.parentIds.length, compact };
7439
7534
  }
7440
7535
  function toolNodeUnchanged(node, projected) {
7441
7536
  return sameSourceShape(node, projected.shape) && node.parentIds.length === projected.parentCount;
7442
7537
  }
7443
- function freezeCompactRun(run) {
7538
+ function freezeCompactRun(run, full = false) {
7539
+ if (full) {
7540
+ Object.freeze(run.stages);
7541
+ Object.freeze(run.toolNodes);
7542
+ }
7444
7543
  for (const [key, value2] of Object.entries(run)) {
7445
7544
  if (key === "stages" || key === "toolNodes")
7446
7545
  markPublishedSnapshotArray(value2);
@@ -7449,18 +7548,23 @@ function freezeCompactRun(run) {
7449
7548
  }
7450
7549
  Object.freeze(run);
7451
7550
  }
7551
+ function graphSnapshotLineage(snapshot) {
7552
+ return snapshotLineages.get(snapshot);
7553
+ }
7452
7554
 
7453
7555
  class GraphStoreSnapshotBuilder {
7556
+ full;
7557
+ constructor(options = {}) {
7558
+ this.full = options.fullPayloads ?? false;
7559
+ }
7454
7560
  projected = new Map;
7561
+ recheckSettledStages = false;
7455
7562
  changedRuns = new Set;
7456
7563
  changedStages = new Map;
7457
7564
  changedToolNodes = new Map;
7458
7565
  markChanged(change) {
7459
7566
  if (change === undefined) {
7460
- this.projected.clear();
7461
- this.changedRuns.clear();
7462
- this.changedStages.clear();
7463
- this.changedToolNodes.clear();
7567
+ this.recheckSettledStages = true;
7464
7568
  return;
7465
7569
  }
7466
7570
  if (change.stageId === undefined && change.toolNodeId === undefined) {
@@ -7472,6 +7576,22 @@ class GraphStoreSnapshotBuilder {
7472
7576
  if (change.toolNodeId !== undefined)
7473
7577
  addScoped(this.changedToolNodes, change.runId, change.toolNodeId);
7474
7578
  }
7579
+ hasRun(run) {
7580
+ return this.projected.get(run.id)?.source === run;
7581
+ }
7582
+ removeRun(runId) {
7583
+ this.projected.delete(runId);
7584
+ this.changedRuns.delete(runId);
7585
+ this.changedStages.delete(runId);
7586
+ this.changedToolNodes.delete(runId);
7587
+ }
7588
+ clear() {
7589
+ this.projected.clear();
7590
+ this.recheckSettledStages = false;
7591
+ this.changedRuns.clear();
7592
+ this.changedStages.clear();
7593
+ this.changedToolNodes.clear();
7594
+ }
7475
7595
  build(runs, notices, version) {
7476
7596
  const previous = this.projected;
7477
7597
  const next = new Map;
@@ -7482,16 +7602,16 @@ class GraphStoreSnapshotBuilder {
7482
7602
  compactRuns.push(projected.compact);
7483
7603
  }
7484
7604
  this.projected = next;
7605
+ this.recheckSettledStages = false;
7485
7606
  this.changedRuns.clear();
7486
7607
  this.changedStages.clear();
7487
7608
  this.changedToolNodes.clear();
7488
7609
  const compactNotices = notices.map((notice) => ({ ...notice }));
7489
7610
  deepFreezeGraphValue(compactNotices);
7490
- const snapshot = Object.freeze({
7491
- runs: Object.freeze(compactRuns),
7492
- notices: compactNotices,
7493
- version
7494
- });
7611
+ return this.publish(compactRuns, compactNotices, version);
7612
+ }
7613
+ publish(runs, notices, version) {
7614
+ const snapshot = Object.freeze({ runs: Object.freeze(runs), notices, version });
7495
7615
  snapshotLineages.set(snapshot, this);
7496
7616
  return snapshot;
7497
7617
  }
@@ -7542,7 +7662,8 @@ class GraphStoreSnapshotBuilder {
7542
7662
  changed.add(position);
7543
7663
  }
7544
7664
  }
7545
- for (const position of projected.unsettled)
7665
+ const positions = this.recheckSettledStages ? sources.keys() : projected.unsettled;
7666
+ for (const position of positions)
7546
7667
  if (!changed.has(position) && !stageUnchanged(sources[position], projected.stages[position]))
7547
7668
  changed.add(position);
7548
7669
  if (changed.size === 0 && run.stages.length === sources.length)
@@ -7551,7 +7672,7 @@ class GraphStoreSnapshotBuilder {
7551
7672
  const appendedFrom = sources.length;
7552
7673
  const compactStages = previous.stages.slice();
7553
7674
  for (const position of changed) {
7554
- const stage = projectStage(sources[position]);
7675
+ const stage = projectStage(sources[position], this.full);
7555
7676
  projected.stages[position] = stage;
7556
7677
  compactStages[position] = stage.compact;
7557
7678
  if (stage.settled)
@@ -7561,7 +7682,7 @@ class GraphStoreSnapshotBuilder {
7561
7682
  }
7562
7683
  for (let position = sources.length;position < run.stages.length; position++) {
7563
7684
  const source = run.stages[position];
7564
- const stage = projectStage(source);
7685
+ const stage = projectStage(source, this.full);
7565
7686
  sources.push(source);
7566
7687
  projected.stages.push(stage);
7567
7688
  compactStages.push(stage.compact);
@@ -7573,7 +7694,7 @@ class GraphStoreSnapshotBuilder {
7573
7694
  projected.stagePositions.set(source.id, position);
7574
7695
  }
7575
7696
  const compact = { ...previous, stages: compactStages };
7576
- freezeCompactRun(compact);
7697
+ freezeCompactRun(compact, this.full);
7577
7698
  indexRunFrom(compact, previous, changed, appendedFrom);
7578
7699
  projected.compact = compact;
7579
7700
  return projected;
@@ -7593,7 +7714,7 @@ class GraphStoreSnapshotBuilder {
7593
7714
  for (const stage of run.stages) {
7594
7715
  let projected = previousStages.get(stage);
7595
7716
  if (projected === undefined || changedStages?.has(stage.id) === true || !stageUnchanged(stage, projected))
7596
- projected = projectStage(stage);
7717
+ projected = projectStage(stage, this.full);
7597
7718
  previousStages.set(stage, projected);
7598
7719
  const position = stages.length;
7599
7720
  stageSources.push(stage);
@@ -7612,12 +7733,12 @@ class GraphStoreSnapshotBuilder {
7612
7733
  for (const node of run.toolNodes) {
7613
7734
  let projected = toolNodes.get(node) ?? previous?.toolNodes.get(node);
7614
7735
  if (projected === undefined || changedToolNodes?.has(node.id) === true || !toolNodeUnchanged(node, projected))
7615
- projected = projectToolNode(node);
7736
+ projected = projectToolNode(node, this.full);
7616
7737
  toolNodes.set(node, projected);
7617
7738
  compactToolNodes.push(projected.compact);
7618
7739
  }
7619
- const compact = compactRun(run, compactStages, compactToolNodes);
7620
- freezeCompactRun(compact);
7740
+ const compact = compactRun(run, compactStages, compactToolNodes, this.full);
7741
+ freezeCompactRun(compact, this.full);
7621
7742
  return {
7622
7743
  source: run,
7623
7744
  shape: sourceShape(run),
@@ -7661,10 +7782,366 @@ var init_graph_store_snapshot = __esm(() => {
7661
7782
  });
7662
7783
 
7663
7784
  // dist/builtin/workflows/src/shared/expanded-workflow-graph.ts
7664
- var leafExpansions, snapshotExpansions, settledStageCounts, expandedStageLists, chainExpansions;
7785
+ function toolNodesFor(run) {
7786
+ if (run.toolNodes === undefined)
7787
+ throw new MissingWorkflowToolNodesError(run.id);
7788
+ return run.toolNodes;
7789
+ }
7790
+ function virtualNodeId(runId, nodeId, isRootRun) {
7791
+ return isRootRun ? nodeId : `${runId}:${nodeId}`;
7792
+ }
7793
+ function localItems(run) {
7794
+ const stages = run.stages.map((stage, sourceIndex) => ({ kind: "stage", stage, sourceIndex }));
7795
+ const tools = toolNodesFor(run).map((tool, sourceIndex) => ({ kind: "tool", tool, sourceIndex }));
7796
+ return [...stages, ...tools].sort((left, right) => {
7797
+ const leftOrder = left.kind === "stage" ? left.stage.executionOrder : left.tool.executionOrder;
7798
+ const rightOrder = right.kind === "stage" ? right.stage.executionOrder : right.tool.executionOrder;
7799
+ if (leftOrder !== undefined || rightOrder !== undefined)
7800
+ return (leftOrder ?? Number.MAX_SAFE_INTEGER) - (rightOrder ?? Number.MAX_SAFE_INTEGER);
7801
+ if (left.kind !== right.kind)
7802
+ return left.kind === "stage" ? -1 : 1;
7803
+ return left.sourceIndex - right.sourceIndex;
7804
+ });
7805
+ }
7806
+ function itemId(item) {
7807
+ return item.kind === "stage" ? item.stage.id : item.tool.id;
7808
+ }
7809
+ function itemParents(item) {
7810
+ return item.kind === "stage" ? item.stage.parentIds : item.tool.parentIds;
7811
+ }
7812
+ function localTerminalIds(items) {
7813
+ const parents = new Set(items.flatMap((item) => [...itemParents(item)]));
7814
+ const terminals = items.map(itemId).filter((id) => !parents.has(id));
7815
+ return terminals.length > 0 ? terminals : items.map(itemId);
7816
+ }
7817
+ function projectedToolStatus(tool) {
7818
+ if (tool.status === "cached")
7819
+ return "completed";
7820
+ if (tool.status === "cancelled")
7821
+ return "skipped";
7822
+ return tool.status;
7823
+ }
7824
+ function isLeafRun(run) {
7825
+ return run.stages.every((stage) => authoritativeWorkflowChildRunId(stage) === undefined);
7826
+ }
7827
+ function expandWorkflowGraph(snapshot, rootRunId) {
7828
+ return createWorkflowGraphExpander(snapshot)(rootRunId);
7829
+ }
7830
+ function isSettledStage2(stage) {
7831
+ return stage.status === "completed" || stage.status === "failed" || stage.status === "skipped";
7832
+ }
7833
+ function executionOrderKey(stage) {
7834
+ return stage.executionOrder ?? Number.MAX_SAFE_INTEGER;
7835
+ }
7836
+ function chainStage(stage) {
7837
+ return stage.nodeKind !== "tool" && authoritativeWorkflowChildRunId(stage) === undefined;
7838
+ }
7839
+ function isChainRun(run) {
7840
+ if (toolNodesFor(run).length > 0)
7841
+ return false;
7842
+ let order = Number.NEGATIVE_INFINITY;
7843
+ for (const stage of run.stages) {
7844
+ const next = executionOrderKey(stage);
7845
+ if (next < order || !chainStage(stage))
7846
+ return false;
7847
+ order = next;
7848
+ }
7849
+ return true;
7850
+ }
7851
+ function expandChainFrom(run, previous) {
7852
+ const before = previous.run.stages;
7853
+ if (run.id !== previous.run.id || run.name !== previous.run.name || toolNodesFor(run).length > 0)
7854
+ return;
7855
+ if (run.stages.length < before.length)
7856
+ return;
7857
+ const replaced = [];
7858
+ for (let index = 0;index < before.length; index++) {
7859
+ const stage = run.stages[index];
7860
+ const earlier = before[index];
7861
+ if (stage === earlier)
7862
+ continue;
7863
+ if (stage.id !== earlier.id || stage.executionOrder !== earlier.executionOrder || !sameIds(stage.parentIds, earlier.parentIds) || !chainStage(stage))
7864
+ return;
7865
+ replaced.push(index);
7866
+ }
7867
+ let order = before.length === 0 ? Number.NEGATIVE_INFINITY : executionOrderKey(before[before.length - 1]);
7868
+ for (let index = before.length;index < run.stages.length; index++) {
7869
+ const stage = run.stages[index];
7870
+ const next = executionOrderKey(stage);
7871
+ if (next < order || !chainStage(stage))
7872
+ return;
7873
+ order = next;
7874
+ }
7875
+ const graph = previous.graph;
7876
+ if (replaced.length === 0 && run.stages.length === before.length)
7877
+ return graph;
7878
+ const stages = graph.stages.slice();
7879
+ const nodes = graph.nodes.slice();
7880
+ for (const index of replaced) {
7881
+ const earlier = graph.stages[index];
7882
+ const stage = {
7883
+ ...run.stages[index],
7884
+ id: earlier.id,
7885
+ parentIds: earlier.parentIds,
7886
+ workflowGraphTarget: earlier.workflowGraphTarget
7887
+ };
7888
+ stages[index] = stage;
7889
+ nodes[index] = { kind: "stage", stage };
7890
+ }
7891
+ let settled = settledStageCounts.get(graph.stages);
7892
+ if (settled !== undefined)
7893
+ for (const index of replaced)
7894
+ settled += Number(isSettledStage2(stages[index])) - Number(isSettledStage2(graph.stages[index]));
7895
+ let targets = graph.targets;
7896
+ if (run.stages.length > before.length) {
7897
+ const extended = new Map(graph.targets);
7898
+ for (let index = before.length;index < run.stages.length; index++) {
7899
+ const source = run.stages[index];
7900
+ const target = { runId: run.id, stageId: source.id, runName: run.name, depth: 0 };
7901
+ extended.set(source.id, target);
7902
+ const stage = {
7903
+ ...source,
7904
+ id: source.id,
7905
+ parentIds: Object.freeze([...source.parentIds]),
7906
+ workflowGraphTarget: target
7907
+ };
7908
+ stages.push(stage);
7909
+ nodes.push({ kind: "stage", stage });
7910
+ if (settled !== undefined)
7911
+ settled += Number(isSettledStage2(stage));
7912
+ }
7913
+ targets = extended;
7914
+ }
7915
+ expandedStageLists.add(stages);
7916
+ if (settled !== undefined)
7917
+ settledStageCounts.set(stages, settled);
7918
+ return { stages, renderStages: stages, tools: graph.tools, nodes, targets };
7919
+ }
7920
+ function rememberChainExpansion(memo, runById, run, graph, patched) {
7921
+ if (patched || isChainRun(run))
7922
+ memo.set(run.id, { run, graph });
7923
+ else
7924
+ memo.delete(run.id);
7925
+ for (const runId of memo.keys())
7926
+ if (!runById.has(runId))
7927
+ memo.delete(runId);
7928
+ }
7929
+ function createWorkflowGraphExpander(snapshot) {
7930
+ let runById;
7931
+ let expansions;
7932
+ let chains;
7933
+ if (Object.isFrozen(snapshot)) {
7934
+ expansions = snapshotExpansions.get(snapshot);
7935
+ if (expansions === undefined) {
7936
+ expansions = new Map;
7937
+ snapshotExpansions.set(snapshot, expansions);
7938
+ }
7939
+ const lineage = graphSnapshotLineage(snapshot);
7940
+ if (lineage !== undefined) {
7941
+ chains = chainExpansions.get(lineage);
7942
+ if (chains === undefined) {
7943
+ chains = new Map;
7944
+ chainExpansions.set(lineage, chains);
7945
+ }
7946
+ }
7947
+ }
7948
+ return (rootRunId) => {
7949
+ const known = expansions?.get(rootRunId);
7950
+ if (known !== undefined)
7951
+ return known;
7952
+ runById ??= new Map(snapshot.runs.map((run) => [run.id, run]));
7953
+ const root = runById.get(rootRunId);
7954
+ const previous = root === undefined ? undefined : chains?.get(rootRunId);
7955
+ const patched = root === undefined || previous === undefined ? undefined : expandChainFrom(root, previous);
7956
+ const graph = patched ?? expandIndexedWorkflowGraph(runById, rootRunId);
7957
+ expansions?.set(rootRunId, graph);
7958
+ if (chains !== undefined && root !== undefined)
7959
+ rememberChainExpansion(chains, runById, root, graph, patched !== undefined);
7960
+ return graph;
7961
+ };
7962
+ }
7963
+ function expandIndexedWorkflowGraph(runById, rootRunId) {
7964
+ const root = runById.get(rootRunId);
7965
+ if (!root)
7966
+ return { stages: [], renderStages: [], tools: [], nodes: [], targets: new Map };
7967
+ const targets = new Map;
7968
+ const rootOwnerByRunId = new Map;
7969
+ const rootOwnerFor = (runId) => {
7970
+ if (rootOwnerByRunId.has(runId))
7971
+ return rootOwnerByRunId.get(runId);
7972
+ const owner = reciprocalWorkflowRootRunId(runById, runId);
7973
+ rootOwnerByRunId.set(runId, owner);
7974
+ return owner;
7975
+ };
7976
+ const visiting = new Set;
7977
+ const expandedChildren = new Set;
7978
+ const expandRun = (run, depth, incomingParentIds) => {
7979
+ if (visiting.has(run.id))
7980
+ return { stages: [], tools: [], nodes: [], terminalIds: [] };
7981
+ const isRootRun = run.id === rootRunId;
7982
+ const memoizable = !isRootRun && Object.isFrozen(run) && isLeafRun(run);
7983
+ if (memoizable) {
7984
+ const known = leafExpansions.get(run);
7985
+ if (known !== undefined && known.depth === depth && sameIds(known.incomingParentIds, incomingParentIds)) {
7986
+ for (const [id, target] of known.targets)
7987
+ targets.set(id, target);
7988
+ return known.result;
7989
+ }
7990
+ }
7991
+ const runTargets = [];
7992
+ visiting.add(run.id);
7993
+ const items = localItems(run);
7994
+ const stages = [];
7995
+ const tools = [];
7996
+ const nodes = [];
7997
+ const stageById = new Map(run.stages.map((stage) => [stage.id, stage]));
7998
+ const boundaryExpansions = new Map;
7999
+ const validChildRunFor = (stage) => {
8000
+ const childRunId = authoritativeWorkflowChildRunId(stage);
8001
+ if (childRunId === undefined)
8002
+ return;
8003
+ const childRun = runById.get(childRunId);
8004
+ const runRoot = rootOwnerFor(run.id);
8005
+ if (childRun === undefined || expandedChildren.has(childRun.id) || childRun.stages.length + toolNodesFor(childRun).length === 0 || childRun.parentRunId !== run.id || childRun.parentStageId !== stage.id || runRoot === undefined || rootOwnerFor(childRun.id) !== runRoot) {
8006
+ return;
8007
+ }
8008
+ return childRun;
8009
+ };
8010
+ const resolvedParentIdsFor = (item) => {
8011
+ const parentIds = itemParents(item);
8012
+ if (parentIds.length === 0)
8013
+ return [...incomingParentIds];
8014
+ return parentIds.flatMap((parentId) => {
8015
+ const parentStage = stageById.get(parentId);
8016
+ const parentExpansion = parentStage === undefined ? undefined : boundaryExpansionFor(parentStage);
8017
+ return parentExpansion?.terminalIds.length ? [...parentExpansion.terminalIds] : [virtualNodeId(run.id, parentId, isRootRun)];
8018
+ });
8019
+ };
8020
+ const boundaryExpansionFor = (stage) => {
8021
+ const cached = boundaryExpansions.get(stage.id);
8022
+ if (cached !== undefined)
8023
+ return cached ?? undefined;
8024
+ const childRun = validChildRunFor(stage);
8025
+ if (childRun === undefined)
8026
+ return;
8027
+ boundaryExpansions.set(stage.id, null);
8028
+ expandedChildren.add(childRun.id);
8029
+ const stageItem = { kind: "stage", stage, sourceIndex: 0 };
8030
+ const childExpanded = expandRun(childRun, depth + 1, resolvedParentIdsFor(stageItem));
8031
+ if (childExpanded.stages.length === 0 || childExpanded.terminalIds.length === 0)
8032
+ return;
8033
+ boundaryExpansions.set(stage.id, childExpanded);
8034
+ return childExpanded;
8035
+ };
8036
+ for (const item of items) {
8037
+ const sourceId = itemId(item);
8038
+ const id = virtualNodeId(run.id, sourceId, isRootRun);
8039
+ const resolvedParentIds = resolvedParentIdsFor(item);
8040
+ if (item.kind === "tool") {
8041
+ const tool = {
8042
+ ...item.tool,
8043
+ id,
8044
+ parentIds: Object.freeze(resolvedParentIds),
8045
+ runId: run.id,
8046
+ runName: run.name,
8047
+ depth
8048
+ };
8049
+ const projectionTarget = {
8050
+ runId: run.id,
8051
+ stageId: item.tool.id,
8052
+ runName: run.name,
8053
+ depth
8054
+ };
8055
+ const projection = {
8056
+ id,
8057
+ name: item.tool.name,
8058
+ status: projectedToolStatus(item.tool),
8059
+ parentIds: Object.freeze(resolvedParentIds),
8060
+ executionOrder: item.tool.executionOrder,
8061
+ nodeKind: "tool",
8062
+ toolStatus: item.tool.status,
8063
+ startedAt: item.tool.startedAt,
8064
+ endedAt: item.tool.endedAt,
8065
+ result: item.tool.resultSummary,
8066
+ error: item.tool.error,
8067
+ toolEvents: [],
8068
+ attachable: false,
8069
+ workflowGraphTarget: projectionTarget
8070
+ };
8071
+ targets.set(id, projectionTarget);
8072
+ runTargets.push([id, projectionTarget]);
8073
+ tools.push(tool);
8074
+ stages.push(projection);
8075
+ nodes.push({ kind: "tool", tool });
8076
+ continue;
8077
+ }
8078
+ const childExpanded = boundaryExpansionFor(item.stage);
8079
+ if (childExpanded !== undefined) {
8080
+ stages.push(...childExpanded.stages);
8081
+ tools.push(...childExpanded.tools);
8082
+ nodes.push(...childExpanded.nodes);
8083
+ continue;
8084
+ }
8085
+ const target = {
8086
+ runId: run.id,
8087
+ stageId: item.stage.id,
8088
+ runName: run.name,
8089
+ depth
8090
+ };
8091
+ targets.set(id, target);
8092
+ runTargets.push([id, target]);
8093
+ const stage = {
8094
+ ...item.stage,
8095
+ id,
8096
+ parentIds: Object.freeze(resolvedParentIds),
8097
+ workflowGraphTarget: target
8098
+ };
8099
+ stages.push(stage);
8100
+ nodes.push({ kind: "stage", stage });
8101
+ }
8102
+ const terminalIds = localTerminalIds(items).flatMap((sourceId) => {
8103
+ const stage = stageById.get(sourceId);
8104
+ const replacement = stage === undefined ? undefined : boundaryExpansionFor(stage);
8105
+ return replacement?.terminalIds.length ? [...replacement.terminalIds] : [virtualNodeId(run.id, sourceId, isRootRun)];
8106
+ });
8107
+ visiting.delete(run.id);
8108
+ const result = { stages, tools, nodes, terminalIds };
8109
+ if (memoizable)
8110
+ leafExpansions.set(run, { depth, incomingParentIds: [...incomingParentIds], result, targets: runTargets });
8111
+ return result;
8112
+ };
8113
+ const expanded = expandRun(root, 0, []);
8114
+ const stages = expanded.stages.filter((stage) => stage.nodeKind !== "tool");
8115
+ expandedStageLists.add(stages);
8116
+ return {
8117
+ stages,
8118
+ renderStages: expanded.stages,
8119
+ tools: expanded.tools,
8120
+ nodes: expanded.nodes,
8121
+ targets
8122
+ };
8123
+ }
8124
+ function sameIds(left, right) {
8125
+ if (left.length !== right.length)
8126
+ return false;
8127
+ for (let index = 0;index < left.length; index++) {
8128
+ if (left[index] !== right[index])
8129
+ return false;
8130
+ }
8131
+ return true;
8132
+ }
8133
+ var MissingWorkflowToolNodesError, leafExpansions, snapshotExpansions, settledStageCounts, expandedStageLists, chainExpansions;
7665
8134
  var init_expanded_workflow_graph = __esm(() => {
7666
8135
  init_graph_store_snapshot();
7667
8136
  init_workflow_run_ownership();
8137
+ MissingWorkflowToolNodesError = class MissingWorkflowToolNodesError extends Error {
8138
+ runId;
8139
+ constructor(runId) {
8140
+ super(`atomic-workflows: run ${runId} has no tool node collection`);
8141
+ this.name = "MissingWorkflowToolNodesError";
8142
+ this.runId = runId;
8143
+ }
8144
+ };
7668
8145
  leafExpansions = new WeakMap;
7669
8146
  snapshotExpansions = new WeakMap;
7670
8147
  settledStageCounts = new WeakMap;
@@ -7672,6 +8149,16 @@ var init_expanded_workflow_graph = __esm(() => {
7672
8149
  chainExpansions = new WeakMap;
7673
8150
  });
7674
8151
 
8152
+ // dist/builtin/workflows/src/shared/inspection-store-snapshot.ts
8153
+ var prepareInspectionSnapshotKey, expandedRuns, inspectionExpanders;
8154
+ var init_inspection_store_snapshot = __esm(() => {
8155
+ init_expanded_workflow_graph();
8156
+ init_workflow_run_ownership();
8157
+ prepareInspectionSnapshotKey = Symbol("workflow.prepare-inspection-snapshot");
8158
+ expandedRuns = new WeakMap;
8159
+ inspectionExpanders = new WeakMap;
8160
+ });
8161
+
7675
8162
  // dist/builtin/workflows/src/shared/workflow-activity.ts
7676
8163
  function workflowActivityNodeKey(runId, nodeId) {
7677
8164
  return `${runId}:${nodeId}`;
@@ -8088,10 +8575,67 @@ function createStoreContext(state = createStoreState()) {
8088
8575
  let cachedGraphVersion = -1;
8089
8576
  let cachedGraphSnapshot;
8090
8577
  const graphBuilder = new GraphStoreSnapshotBuilder;
8578
+ let inspectionBuilder;
8579
+ let inspectionVersion = -1;
8580
+ let inspectionView;
8581
+ let inspectionTargets = new WeakMap;
8091
8582
  const observation = new WorkflowObservationRuntime({ all: () => state.runs, find: findRun, position: (runId) => runPosition(state, runId) }, bumpAndNotify);
8092
8583
  function snapshot() {
8093
8584
  return JSON.parse(JSON.stringify({ runs: state.runs, notices: state.notices, version: state.version }));
8094
8585
  }
8586
+ async function prepareInspectionSnapshot() {
8587
+ let prepared = 0;
8588
+ for (;; ) {
8589
+ inspectionBuilder ??= new GraphStoreSnapshotBuilder({ fullPayloads: true });
8590
+ const builder = inspectionBuilder;
8591
+ const unhandled = state.runs.filter((run) => !builder.hasRun(run) || !graphBuilder.hasRun(run));
8592
+ if (unhandled.length === 0)
8593
+ return;
8594
+ for (const run of unhandled) {
8595
+ if (builder.hasRun(run) && graphBuilder.hasRun(run))
8596
+ continue;
8597
+ if (prepared >= 16) {
8598
+ prepared = 0;
8599
+ await new Promise((resolve) => setImmediate(resolve));
8600
+ if (inspectionBuilder !== builder)
8601
+ break;
8602
+ }
8603
+ if (findRun(run.id) === run) {
8604
+ if (!builder.hasRun(run))
8605
+ builder.buildRun(run);
8606
+ if (!graphBuilder.hasRun(run))
8607
+ graphBuilder.buildRun(run);
8608
+ prepared++;
8609
+ }
8610
+ }
8611
+ }
8612
+ }
8613
+ function inspectionSnapshot(runId) {
8614
+ if (inspectionView !== undefined && inspectionVersion === state.version)
8615
+ return inspectionView;
8616
+ inspectionBuilder ??= new GraphStoreSnapshotBuilder({ fullPayloads: true });
8617
+ const builder = inspectionBuilder;
8618
+ if (runId === undefined) {
8619
+ inspectionView = builder.build(state.runs, state.notices, state.version);
8620
+ inspectionVersion = state.version;
8621
+ return inspectionView;
8622
+ }
8623
+ const compact = graphSnapshot();
8624
+ let targets = inspectionTargets.get(compact);
8625
+ const known = targets?.get(runId);
8626
+ if (known !== undefined)
8627
+ return known;
8628
+ const graph = expandWorkflowGraph(compact, runId);
8629
+ const fullRunIds = new Set([runId, ...Array.from(graph.targets.values(), (target) => target.runId)]);
8630
+ const runs = compact.runs.map((run) => fullRunIds.has(run.id) ? builder.buildRun(findRun(run.id)) : run);
8631
+ const view = builder.publish(runs, compact.notices, state.version);
8632
+ if (targets === undefined) {
8633
+ targets = new Map;
8634
+ inspectionTargets.set(compact, targets);
8635
+ }
8636
+ targets.set(runId, view);
8637
+ return view;
8638
+ }
8095
8639
  function graphSnapshot() {
8096
8640
  if (cachedGraphSnapshot === undefined || cachedGraphVersion !== state.version) {
8097
8641
  cachedGraphSnapshot = graphBuilder.build(state.runs, state.notices, state.version);
@@ -8110,6 +8654,7 @@ function createStoreContext(state = createStoreState()) {
8110
8654
  let batchedChanges = [];
8111
8655
  function notify(change) {
8112
8656
  graphBuilder.markChanged(change);
8657
+ inspectionBuilder?.markChanged(change);
8113
8658
  if (batchDepth > 0) {
8114
8659
  batchedNotification = true;
8115
8660
  if (change === undefined)
@@ -8176,11 +8721,22 @@ function createStoreContext(state = createStoreState()) {
8176
8721
  if (removed === undefined)
8177
8722
  return;
8178
8723
  state.runPositions.delete(removed.id);
8724
+ graphBuilder.removeRun(removed.id);
8725
+ inspectionBuilder?.removeRun(removed.id);
8726
+ inspectionView = undefined;
8727
+ inspectionTargets = new WeakMap;
8179
8728
  unindexChildRun(state, removed.id);
8180
8729
  for (let index = position;index < state.runs.length; index++)
8181
8730
  state.runPositions.set(state.runs[index].id, index);
8182
8731
  }
8183
8732
  function clearRuns() {
8733
+ graphBuilder.clear();
8734
+ cachedGraphSnapshot = undefined;
8735
+ cachedGraphVersion = -1;
8736
+ inspectionBuilder = undefined;
8737
+ inspectionTargets = new WeakMap;
8738
+ inspectionView = undefined;
8739
+ inspectionVersion = -1;
8184
8740
  state.runs.length = 0;
8185
8741
  state.runPositions.clear();
8186
8742
  state.childRunIds.clear();
@@ -8248,6 +8804,8 @@ function createStoreContext(state = createStoreState()) {
8248
8804
  observation,
8249
8805
  snapshot,
8250
8806
  graphSnapshot,
8807
+ inspectionSnapshot,
8808
+ prepareInspectionSnapshot,
8251
8809
  graphRun,
8252
8810
  notify,
8253
8811
  batch,
@@ -8270,6 +8828,7 @@ function createStoreContext(state = createStoreState()) {
8270
8828
  }
8271
8829
  var TERMINAL_STATUSES;
8272
8830
  var init_store_internal = __esm(() => {
8831
+ init_expanded_workflow_graph();
8273
8832
  init_graph_store_snapshot();
8274
8833
  init_workflow_observation_runtime();
8275
8834
  init_workflow_run_ownership();
@@ -9703,6 +10262,9 @@ function createRunStoreMethods(context) {
9703
10262
  graphSnapshot() {
9704
10263
  return context.graphSnapshot();
9705
10264
  },
10265
+ inspectionSnapshot(runId) {
10266
+ return context.inspectionSnapshot(runId);
10267
+ },
9706
10268
  graphRun(runId) {
9707
10269
  return context.graphRun(runId);
9708
10270
  },
@@ -10197,6 +10759,7 @@ function createStore() {
10197
10759
  context.backend = getDurableBackendProcessOwner().injectedBackend;
10198
10760
  const created = {
10199
10761
  [workflowObservationRuntimeKey]: context.observation,
10762
+ [prepareInspectionSnapshotKey]: context.prepareInspectionSnapshot,
10200
10763
  [workflowStoreBackendOverride]: context.backend,
10201
10764
  get [workflowStoreBackend]() {
10202
10765
  return context.backend;
@@ -10222,6 +10785,7 @@ var SESSION_KEY = "workflows:store:v1", singleton, store;
10222
10785
  var init_store_factory = __esm(() => {
10223
10786
  init_backend_process_owner();
10224
10787
  init_store_backend();
10788
+ init_inspection_store_snapshot();
10225
10789
  init_session_scoped_singleton();
10226
10790
  init_store_internal();
10227
10791
  init_store_pending_stage_delivery_methods();
@@ -13333,6 +13897,7 @@ class JournalProjection {
13333
13897
  return;
13334
13898
  rec.released += rec.checkpoints.size;
13335
13899
  rec.checkpoints.clear();
13900
+ rec.sortedCheckpoints = undefined;
13336
13901
  rec.toolByHash.clear();
13337
13902
  rec.uiByHash.clear();
13338
13903
  rec.stageOutputByReplayKey.clear();
@@ -13348,6 +13913,7 @@ class JournalProjection {
13348
13913
  if (checkpoint === undefined)
13349
13914
  continue;
13350
13915
  rec.checkpoints.delete(key);
13916
+ rec.sortedCheckpoints = undefined;
13351
13917
  rec.released++;
13352
13918
  if (checkpoint.kind === "tool")
13353
13919
  rec.toolByHash.delete(checkpoint.argsHash);
@@ -13370,6 +13936,7 @@ class JournalProjection {
13370
13936
  if (rec.checkpoints.has(key))
13371
13937
  return;
13372
13938
  rec.checkpoints.set(key, currentCheckpoint);
13939
+ rec.sortedCheckpoints = undefined;
13373
13940
  rec.attempt = Math.max(rec.attempt, workflowAttemptOf(currentCheckpoint) ?? 0);
13374
13941
  rec.nestedSnapshotVersion.record(currentCheckpoint);
13375
13942
  if (currentCheckpoint.kind === "tool") {
@@ -13417,11 +13984,20 @@ class JournalProjection {
13417
13984
  ...checkpoint.attempt !== undefined ? { attempt: checkpoint.attempt } : {}
13418
13985
  };
13419
13986
  }
13987
+ recordedCheckpoints(workflowId) {
13988
+ const rec = this.workflows.get(workflowId);
13989
+ if (rec === undefined || rec.released > 0)
13990
+ return;
13991
+ return [...rec.checkpoints.values()];
13992
+ }
13420
13993
  listCheckpoints(workflowId) {
13421
13994
  const rec = this.workflows.get(workflowId);
13422
13995
  if (!rec)
13423
13996
  return [];
13424
- return [...rec.checkpoints.values()].sort((a, b) => a.completedAt - b.completedAt);
13997
+ if (rec.sortedCheckpoints === undefined) {
13998
+ rec.sortedCheckpoints = Object.freeze([...rec.checkpoints.values()].sort((a, b) => a.completedAt - b.completedAt));
13999
+ }
14000
+ return rec.sortedCheckpoints;
13425
14001
  }
13426
14002
  getStoredCheckpoint(checkpoint) {
13427
14003
  return this.workflows.get(checkpoint.workflowId)?.checkpoints.get(checkpointKey(checkpoint));
@@ -17275,6 +17851,12 @@ class JournalDurableBackend {
17275
17851
  listCheckpoints(runId) {
17276
17852
  return this.projection.listCheckpoints(runId);
17277
17853
  }
17854
+ async readCheckpointSequence(runId) {
17855
+ if (this.projection.getWorkflow(runId) === undefined || this.summarized.has(runId) || this.lacksChildCheckpoints(runId) || this.checkpointSelections.has(runId))
17856
+ return;
17857
+ await this.catchUpWorkflow(runId);
17858
+ return this.projection.recordedCheckpoints(runId);
17859
+ }
17278
17860
  getStageCheckpoint(runId, checkpointId) {
17279
17861
  return this.projection.getStageCheckpoint(runId, checkpointId);
17280
17862
  }
@@ -28910,6 +29492,12 @@ class SqlPoolQueue {
28910
29492
  await ensureStorageSchema2(tx, dialect, { ledger, domain: "pool-outbox", revision: 1 }, () => tx.exec(schema.outbox));
28911
29493
  pool.outboxPending = await tx.get(`SELECT 1 AS held FROM ${pool.outbox} LIMIT 1`) !== undefined;
28912
29494
  }
29495
+ if (!pool.rowLocks) {
29496
+ await ensureStorageSchema2(tx, dialect, { ledger, domain: "pool-ready", revision: POOL_READY_SCHEMA_REVISION }, async () => {
29497
+ for (const statement of schema.ready)
29498
+ await tx.exec(statement);
29499
+ });
29500
+ }
28913
29501
  await ensureStorageSchema2(tx, dialect, { ledger, domain: "pool-ship", revision: 1 }, () => tx.exec(schema.ship));
28914
29502
  });
28915
29503
  return pool;
@@ -28987,7 +29575,19 @@ class SqlPoolQueue {
28987
29575
  generation ${int} NOT NULL, operation TEXT NOT NULL, request TEXT NOT NULL,
28988
29576
  event_key TEXT NOT NULL, payload TEXT NOT NULL, last_seq ${int},
28989
29577
  PRIMARY KEY(work, generation, operation)${dialect.rowOrderColumn}
28990
- )`
29578
+ )`,
29579
+ ready: [
29580
+ `CREATE TABLE IF NOT EXISTS ${this.roots}_ready(
29581
+ root TEXT PRIMARY KEY REFERENCES ${this.roots}(root) ON DELETE CASCADE,
29582
+ revision ${int} NOT NULL DEFAULT 0
29583
+ )`,
29584
+ ...["INSERT", "UPDATE"].map((event) => `CREATE TRIGGER IF NOT EXISTS ${this.roots}_ready_${event.toLowerCase()} AFTER ${event} ON ${this.work}
29585
+ WHEN NEW.state = 'ready'
29586
+ BEGIN
29587
+ INSERT INTO ${this.roots}_ready(root, revision) VALUES (NEW.root, 1)
29588
+ ON CONFLICT(root) DO UPDATE SET revision = revision + 1;
29589
+ END`)
29590
+ ]
28991
29591
  };
28992
29592
  }
28993
29593
  async openedWithoutLock(schema) {
@@ -28997,7 +29597,8 @@ class SqlPoolQueue {
28997
29597
  ...schema.tables,
28998
29598
  schema.chunks,
28999
29599
  schema.ship,
29000
- ...this.remote ? [schema.outbox] : []
29600
+ ...this.remote ? [schema.outbox] : [],
29601
+ ...this.rowLocks ? [] : schema.ready
29001
29602
  ];
29002
29603
  const columns = [
29003
29604
  [this.work, "inputs_chunks"],
@@ -29243,6 +29844,8 @@ class SqlPoolQueue {
29243
29844
  await tx.run(`INSERT INTO ${this.roots}_control(root, state, revision) VALUES (?, ?, 1)
29244
29845
  ON CONFLICT(root) DO UPDATE SET state = excluded.state, revision = ${this.roots}_control.revision + (${this.dialect.flag(`${this.roots}_control.state != excluded.state`)})`, lease.runId, state);
29245
29846
  const row = await tx.get(`SELECT revision FROM ${this.roots}_control WHERE root = ?`, lease.runId);
29847
+ if (state === "running")
29848
+ await this.notifyReady(tx, lease.runId);
29246
29849
  return { state, revision: Number(row.revision) };
29247
29850
  });
29248
29851
  }
@@ -29529,13 +30132,24 @@ class SqlPoolQueue {
29529
30132
  await this.writeInputChunks(tx, previous.id, stored.chunks);
29530
30133
  return { ...previous, descriptor: stored.descriptor, fingerprint, inputs_chunks: stored.chunks.length };
29531
30134
  }
29532
- async claim(lease, worker, definitions, durationMs, placement) {
30135
+ async claim(lease, worker, definitions, durationMs, placement, outboxBlocked) {
29533
30136
  positive(durationMs);
29534
30137
  lease = snapshotLease(lease);
29535
30138
  const compatibleDefinitions = definitions.flatMap((d) => [d.definition, d.digest]);
29536
30139
  validateText("holderId", worker);
29537
30140
  const compatible = compatibleClause(this.dialect, definitions.length);
29538
30141
  if (this.remote) {
30142
+ try {
30143
+ while (this.outboxPending || this.draining !== undefined)
30144
+ await this.drainOutbox(lease);
30145
+ } catch (error) {
30146
+ if (error instanceof StaleLeaseError) {
30147
+ await this.remote.fresh(lease);
30148
+ throw error;
30149
+ }
30150
+ outboxBlocked?.(error);
30151
+ return;
30152
+ }
29539
30153
  await this.remote.fresh(lease);
29540
30154
  try {
29541
30155
  while (this.outboxPending || this.draining !== undefined)
@@ -29543,6 +30157,7 @@ class SqlPoolQueue {
29543
30157
  } catch (error) {
29544
30158
  if (error instanceof StaleLeaseError)
29545
30159
  throw error;
30160
+ outboxBlocked?.(error);
29546
30161
  return;
29547
30162
  }
29548
30163
  }
@@ -29625,6 +30240,31 @@ class SqlPoolQueue {
29625
30240
  ...row.workspace === null ? {} : { workspace: JSON.parse(String(row.workspace)) }
29626
30241
  }));
29627
30242
  }
30243
+ async acceptsClaim(lease, host) {
30244
+ lease = snapshotLease(lease);
30245
+ const requested = { ...host };
30246
+ await this.remote?.fresh(lease);
30247
+ return this.storage.read(async (read) => {
30248
+ const available = this.dialect.flag(`NOT EXISTS (SELECT 1 FROM ${this.journal.runs}_fleet_drains WHERE host = CAST(? AS TEXT) OR provider_id = CAST(? AS TEXT))`);
30249
+ const row = await read.get(`SELECT l.*, r.status, p.timeout, ${this.now} AS now,
30250
+ (SELECT state FROM ${this.roots}_control WHERE root = l.run_id) AS control,
30251
+ ${available} AS host_available
30252
+ FROM ${this.journal.leases} l JOIN ${this.journal.runs} r ON r.run_id = l.run_id
30253
+ LEFT JOIN ${this.roots} p ON p.root = l.run_id WHERE l.run_id = ?`, requested.id, requested.providerId ?? null, lease.runId);
30254
+ const { status } = this.authorityOf(row, lease);
30255
+ if (status !== "running" || row.control !== null && row.control !== "running")
30256
+ return "control";
30257
+ return Number(row.host_available) === 1 ? "accepted" : "drain";
30258
+ });
30259
+ }
30260
+ async readyMark(root) {
30261
+ const readiness = this.rowLocks ? "bit_xor(hash_record_extended(ROW(xmin, ctid), 0))" : `(SELECT revision FROM ${this.roots}_ready WHERE root = ?)`;
30262
+ const row = await (this.storage.peek ?? this.storage.read)((executor) => executor.get(`SELECT COUNT(*) AS ready, MAX(ready_at) AS latest,
30263
+ ${readiness} AS readiness,
30264
+ (SELECT revision FROM ${this.roots}_control WHERE root = ?) AS revision
30265
+ FROM ${this.work} WHERE root = ? AND state = 'ready' AND ready_at <= (SELECT ${this.now})`, ...this.rowLocks ? [] : [root], root, root));
30266
+ return row === undefined || Number(row.ready) === 0 ? undefined : `${row.ready}:${row.latest}:${row.readiness ?? 0}:${row.revision ?? 0}`;
30267
+ }
29628
30268
  async failUnclaimed(lease, token) {
29629
30269
  lease = snapshotLease(lease);
29630
30270
  return this.transaction(async (tx) => {
@@ -30563,7 +31203,7 @@ function openSqlPoolQueue(journal, remote) {
30563
31203
  return Promise.reject(new Error("Worker pool requires a SQL run journal"));
30564
31204
  return SqlPoolQueue.open(storage, remote);
30565
31205
  }
30566
- var MAX_WORKER_CLOCK_SKEW_MS = 1000, POOL_SCHEMA_VERSION = 3, POOL_SCHEMA_VERSION_UNCHUNKED = 2, POOL_SCHEMA_REVISION = 1, chunkedInputs, OPERATION_COLUMNS, CLAIM, HEARTBEAT, COMMIT, COMPLETE, HANDOFF_OPERATION = "pool-handoff", CONFIRMED_OPERATION = "pool-confirmed";
31206
+ var MAX_WORKER_CLOCK_SKEW_MS = 1000, POOL_SCHEMA_VERSION = 3, POOL_SCHEMA_VERSION_UNCHUNKED = 2, POOL_SCHEMA_REVISION = 1, POOL_READY_SCHEMA_REVISION = 2, chunkedInputs, OPERATION_COLUMNS, CLAIM, HEARTBEAT, COMMIT, COMPLETE, HANDOFF_OPERATION = "pool-handoff", CONFIRMED_OPERATION = "pool-confirmed";
30567
31207
  var init_sql_pool_queue = __esm(() => {
30568
31208
  init_serializable();
30569
31209
  init_worker_pool_errors();
@@ -83547,29 +84187,164 @@ var UNATTRIBUTED_WRITE = "other";
83547
84187
  var init_pool_coordination_stats = () => {};
83548
84188
 
83549
84189
  // dist/builtin/workflows/src/workers/pool-wake-ups.ts
83550
- class IdleClaimPauses {
83551
- pauseMs;
83552
- waiting = new Set;
83553
- constructor(pauseMs) {
83554
- this.pauseMs = pauseMs;
84190
+ class IdleClaimBackoff {
84191
+ random;
84192
+ step = 0;
84193
+ carriedWake;
84194
+ constructor(random = Math.random) {
84195
+ this.random = random;
84196
+ }
84197
+ next() {
84198
+ const base = IDLE_CLAIM_FIRST_PAUSE_MS * 2 ** Math.min(this.step, 16);
84199
+ this.step++;
84200
+ return Math.min(IDLE_CLAIM_FALLBACK_MS, base * (1 + this.random()));
84201
+ }
84202
+ reset() {
84203
+ this.step = 0;
84204
+ }
84205
+ takeWake() {
84206
+ const carried = this.carriedWake;
84207
+ if (carried === undefined)
84208
+ return false;
84209
+ carried.signal?.removeEventListener("abort", carried.release);
84210
+ this.carriedWake = undefined;
84211
+ return true;
84212
+ }
84213
+ carryWake(signal, wake) {
84214
+ const release = () => {
84215
+ if (this.takeWake())
84216
+ wake();
84217
+ };
84218
+ this.carriedWake = { signal, release };
84219
+ signal?.addEventListener("abort", release, { once: true });
84220
+ if (signal?.aborted)
84221
+ release();
83555
84222
  }
83556
- pause() {
84223
+ }
84224
+
84225
+ class IdleClaimTicket {
84226
+ woken = false;
84227
+ end;
84228
+ get pausing() {
84229
+ return this.end !== undefined;
84230
+ }
84231
+ wake() {
84232
+ this.woken = true;
84233
+ this.end?.();
84234
+ }
84235
+ pause(ms, signal) {
84236
+ if (this.woken || signal?.aborted === true)
84237
+ return Promise.resolve();
83557
84238
  return new Promise((resolve) => {
83558
- const end = () => {
84239
+ const timer = setTimeout(() => this.end?.(), ms);
84240
+ const abort = () => this.end?.();
84241
+ signal?.addEventListener("abort", abort, { once: true });
84242
+ this.end = () => {
83559
84243
  clearTimeout(timer);
83560
- this.waiting.delete(end);
84244
+ signal?.removeEventListener("abort", abort);
84245
+ this.end = undefined;
83561
84246
  resolve();
83562
84247
  };
83563
- const timer = setTimeout(end, this.pauseMs);
83564
- this.waiting.add(end);
83565
84248
  });
83566
84249
  }
84250
+ }
84251
+
84252
+ class IdleClaimWaits {
84253
+ tickets = new Set;
84254
+ async claim(backoff, check, signal) {
84255
+ const ticket = new IdleClaimTicket;
84256
+ this.tickets.add(ticket);
84257
+ let carried = backoff.takeWake();
84258
+ const found = () => {
84259
+ backoff.reset();
84260
+ const passWake = ticket.woken || carried;
84261
+ carried = false;
84262
+ ticket.woken = false;
84263
+ if (this.tickets.delete(ticket) && passWake)
84264
+ this.wakeOne();
84265
+ };
84266
+ const abort = () => {
84267
+ if (this.tickets.delete(ticket) && (ticket.woken || carried))
84268
+ this.wakeOne();
84269
+ };
84270
+ signal?.addEventListener("abort", abort, { once: true });
84271
+ if (signal?.aborted)
84272
+ abort();
84273
+ try {
84274
+ const claimed = await check(found);
84275
+ if (claimed !== undefined) {
84276
+ found();
84277
+ return claimed;
84278
+ }
84279
+ if (!signal?.aborted)
84280
+ this.tickets.add(ticket);
84281
+ await ticket.pause(backoff.next(), signal);
84282
+ if (!signal?.aborted && (ticket.woken || carried))
84283
+ backoff.carryWake(signal, () => this.wakeOne());
84284
+ return;
84285
+ } catch (error) {
84286
+ if (this.tickets.delete(ticket) && (ticket.woken || carried))
84287
+ this.wakeOne();
84288
+ throw error;
84289
+ } finally {
84290
+ signal?.removeEventListener("abort", abort);
84291
+ this.tickets.delete(ticket);
84292
+ }
84293
+ }
84294
+ get pausing() {
84295
+ for (const ticket of this.tickets)
84296
+ if (ticket.pausing && !ticket.woken)
84297
+ return true;
84298
+ return false;
84299
+ }
83567
84300
  wake(woken, root) {
83568
84301
  if (woken === undefined)
83569
- for (const end of [...this.waiting])
83570
- end();
84302
+ this.wakeAll();
83571
84303
  else if (woken === root)
83572
- this.waiting.values().next().value?.();
84304
+ this.wakeOne();
84305
+ }
84306
+ wakeOne() {
84307
+ let checking;
84308
+ for (const ticket of this.tickets) {
84309
+ if (ticket.woken)
84310
+ continue;
84311
+ if (ticket.pausing) {
84312
+ ticket.wake();
84313
+ return;
84314
+ }
84315
+ checking ??= ticket;
84316
+ }
84317
+ checking?.wake();
84318
+ }
84319
+ wakeAll() {
84320
+ for (const ticket of [...this.tickets])
84321
+ ticket.wake();
84322
+ }
84323
+ }
84324
+
84325
+ class IdleReadyProbe {
84326
+ target;
84327
+ last;
84328
+ reading = false;
84329
+ constructor(target) {
84330
+ this.target = target;
84331
+ }
84332
+ async tick() {
84333
+ if (this.reading || !this.target.waits.pausing)
84334
+ return;
84335
+ this.reading = true;
84336
+ try {
84337
+ if (await this.target.notified().catch(() => false)) {
84338
+ this.last = undefined;
84339
+ return;
84340
+ }
84341
+ const mark = await this.target.mark().catch(() => this.last);
84342
+ if (mark !== undefined && mark !== this.last)
84343
+ this.target.waits.wakeOne();
84344
+ this.last = mark;
84345
+ } finally {
84346
+ this.reading = false;
84347
+ }
83573
84348
  }
83574
84349
  }
83575
84350
  function coordinatorWakeUps(target) {
@@ -83597,6 +84372,7 @@ function hostWakeUps(serves, poll, minIntervalMs, now = () => performance.now())
83597
84372
  poll();
83598
84373
  };
83599
84374
  }
84375
+ var IDLE_CLAIM_FIRST_PAUSE_MS = 25, IDLE_CLAIM_FALLBACK_MS = 2000, IDLE_READY_PROBE_MS = 250;
83600
84376
 
83601
84377
  // dist/builtin/workflows/src/workers/pooled-watch-trace.ts
83602
84378
  import { dirname as dirname22, join as join36, resolve as resolve18 } from "node:path";
@@ -83835,8 +84611,11 @@ class RestoreBackoff {
83835
84611
  this.policy = policy;
83836
84612
  }
83837
84613
  waiting(key) {
83838
- const failing = this.failing.get(key);
83839
- return failing !== undefined && this.now() < failing.until;
84614
+ return this.remaining(key) > 0;
84615
+ }
84616
+ remaining(key) {
84617
+ const until = this.failing.get(key)?.until;
84618
+ return until === undefined ? 0 : Math.max(0, until - this.now());
83840
84619
  }
83841
84620
  failed(key) {
83842
84621
  const failures = (this.failing.get(key)?.failures ?? 0) + 1;
@@ -84599,8 +85378,13 @@ class PoolCoordinator {
84599
85378
  statsTimer;
84600
85379
  committedControl;
84601
85380
  recoveryTimer;
85381
+ readyProbeTimer;
85382
+ claimRetryTimer;
85383
+ claimRetryAt = Number.POSITIVE_INFINITY;
84602
85384
  poolReady;
84603
- idlePauses = new IdleClaimPauses(SHARED_IDLE_CLAIM_MS);
85385
+ idleClaims = new IdleClaimWaits;
85386
+ claimsGated = false;
85387
+ lagGated = false;
84604
85388
  flushTimer;
84605
85389
  lastFlushAt = 0;
84606
85390
  batchSequence = 0;
@@ -84628,6 +85412,7 @@ class PoolCoordinator {
84628
85412
  starting;
84629
85413
  recovering;
84630
85414
  nextRecoveryAt = 0;
85415
+ hasPendingHandoff = false;
84631
85416
  cleanupFailure;
84632
85417
  held = new Set;
84633
85418
  unreaped = [];
@@ -84959,6 +85744,9 @@ class PoolCoordinator {
84959
85744
  if (this.committedControl !== undefined && control.revision <= this.committedControl.revision)
84960
85745
  return;
84961
85746
  this.committedControl = control;
85747
+ for (const slot of this.slots)
85748
+ slot.idle.reset();
85749
+ this.idleClaims.wakeAll();
84962
85750
  const message = { kind: "pool-control", control };
84963
85751
  for (const slot of this.slots)
84964
85752
  if (this.readyWorkers.has(slot.worker) && slot.child.connected)
@@ -85001,6 +85789,8 @@ class PoolCoordinator {
85001
85789
  }
85002
85790
  noteBudget(blocked) {
85003
85791
  this.budgetBlocked = blocked;
85792
+ if (!blocked)
85793
+ this.gateOpened();
85004
85794
  const shared = this.sharedPool;
85005
85795
  if (shared === undefined || this.satellite !== undefined || this.queue === undefined || this.lease === undefined)
85006
85796
  return;
@@ -85057,9 +85847,28 @@ class PoolCoordinator {
85057
85847
  }
85058
85848
  followBudget(blocked) {
85059
85849
  this.budgetBlocked = blocked;
85850
+ if (!blocked)
85851
+ this.gateOpened();
85852
+ }
85853
+ gateOpened() {
85854
+ this.lagGated = false;
85855
+ if (!this.claimsGated)
85856
+ return;
85857
+ this.claimsGated = false;
85858
+ this.idleClaims.wakeAll();
85859
+ }
85860
+ retireWaiting() {
85861
+ const options = this.options;
85862
+ if (options === undefined || this.waitingReserve.size <= Math.min(this.places.waiting, options.workers))
85863
+ return;
85864
+ this.idleClaims.wakeAll();
85060
85865
  }
85061
85866
  startRecovery() {
85062
85867
  const recover = () => {
85868
+ if (this.lagGated && !this.budgetBlocked && this.shipping?.lagging() !== true)
85869
+ this.gateOpened();
85870
+ if (this.hasPendingHandoff)
85871
+ this.nextRecoveryAt = 0;
85063
85872
  this.counters.enter("recovery");
85064
85873
  this.recoverExpired().catch(async (error) => {
85065
85874
  if (this.queue && isStaleLeaseError(error) && await this.rootRenewal(this.queue).catch(() => false))
@@ -85070,12 +85879,13 @@ class PoolCoordinator {
85070
85879
  });
85071
85880
  };
85072
85881
  this.recoveryTimer = setInterval(recover, RECOVERY_INTERVAL_MS).unref();
85882
+ this.startReadyProbe();
85073
85883
  if (this.options?.shared === undefined)
85074
85884
  return;
85075
85885
  this.poolReady = listenPoolReady(this.journal, coordinatorWakeUps({
85076
85886
  root: () => this.root,
85077
85887
  satellite: this.satellite !== undefined,
85078
- pauses: this.idlePauses,
85888
+ pauses: this.idleClaims,
85079
85889
  recovering: () => this.recovering,
85080
85890
  recover: () => {
85081
85891
  this.nextRecoveryAt = 0;
@@ -85083,6 +85893,22 @@ class PoolCoordinator {
85083
85893
  }
85084
85894
  }));
85085
85895
  }
85896
+ startReadyProbe() {
85897
+ const notifications = sqlPoolStorage(this.journal)?.notifications;
85898
+ const probe = new IdleReadyProbe({
85899
+ waits: this.idleClaims,
85900
+ notified: async () => this.poolReady !== undefined && notifications !== undefined && (await notifications.state()).status === "listening",
85901
+ mark: async () => {
85902
+ const queue = this.queue;
85903
+ const root = this.root;
85904
+ return queue === undefined || root === undefined || this.closed ? undefined : queue.readyMark(root);
85905
+ }
85906
+ });
85907
+ this.readyProbeTimer = setInterval(() => {
85908
+ this.counters.enter("ready-probe");
85909
+ probe.tick();
85910
+ }, IDLE_READY_PROBE_MS).unref();
85911
+ }
85086
85912
  async publishSharedConfig(sources) {
85087
85913
  const options = this.options;
85088
85914
  const shared = this.sharedPool;
@@ -85189,6 +86015,7 @@ class PoolCoordinator {
85189
86015
  }
85190
86016
  releasePlace(slot) {
85191
86017
  this.places.release(slot);
86018
+ this.gateOpened();
85192
86019
  if (this.closed || this.satellite !== undefined)
85193
86020
  return;
85194
86021
  const reserve = this.waitingReserve;
@@ -85213,6 +86040,7 @@ class PoolCoordinator {
85213
86040
  async drain() {
85214
86041
  this.draining = true;
85215
86042
  this.placingSignal.abort();
86043
+ this.idleClaims.wakeAll();
85216
86044
  while (!this.closed && [...this.slots].some(holding))
85217
86045
  await delay5(RECOVERY_INTERVAL_MS);
85218
86046
  this.closing ??= this.close();
@@ -85383,6 +86211,8 @@ class PoolCoordinator {
85383
86211
  });
85384
86212
  if (!this.attemptBase.has(work.id))
85385
86213
  this.attemptBase.set(work.id, work.state === "ready" || work.state === "leased" && work.epoch < lease.epoch ? work.generation : 0);
86214
+ if (work.state === "ready")
86215
+ this.idleClaims.wakeOne();
85386
86216
  const result = await this.queue.result(this.root, work.id);
85387
86217
  return { work, ...result === undefined ? {} : { result } };
85388
86218
  }
@@ -85938,6 +86768,7 @@ class PoolCoordinator {
85938
86768
  deliveries: new Map,
85939
86769
  runs: new Set,
85940
86770
  stageCommands: new Map,
86771
+ idle: new IdleClaimBackoff,
85941
86772
  exited: new AbortController
85942
86773
  };
85943
86774
  this.slots.add(slot);
@@ -86000,6 +86831,8 @@ class PoolCoordinator {
86000
86831
  this.awaiting.delete(worker);
86001
86832
  this.slots.delete(slot);
86002
86833
  this.places.end(slot);
86834
+ this.gateOpened();
86835
+ this.retireWaiting();
86003
86836
  this.endStageWatches((watch) => watch.slot === slot, "worker_exited");
86004
86837
  for (const settle of slot.stageCommands.values())
86005
86838
  settle(undefined);
@@ -86132,6 +86965,9 @@ class PoolCoordinator {
86132
86965
  const limits = this.rateLimits.current();
86133
86966
  if (limits.length > 0)
86134
86967
  child.send({ kind: "rate-limits", observations: limits }, replied);
86968
+ const control = this.committedControl;
86969
+ if (control !== undefined)
86970
+ child.send({ kind: "pool-control", control }, replied);
86135
86971
  this.readyWorkers.add(worker);
86136
86972
  clearTimeout(startup);
86137
86973
  resolve();
@@ -86170,6 +87006,8 @@ class PoolCoordinator {
86170
87006
  slot.work = undefined;
86171
87007
  slot.worktree = undefined;
86172
87008
  this.places.end(slot);
87009
+ this.gateOpened();
87010
+ this.retireWaiting();
86173
87011
  };
86174
87012
  if (fenced !== undefined)
86175
87013
  await this.shipping?.release(fenced);
@@ -86179,9 +87017,10 @@ class PoolCoordinator {
86179
87017
  const handoffs = this.handoffs(current);
86180
87018
  if (message.handoff === true && handoffs < MAX_CHILD_HANDOFFS)
86181
87019
  await leased(() => queue.releaseExited(lease, fenced, { delayMs: handoffDelayMs(handoffs) }));
86182
- else if (this.satellite !== undefined || this.attempts(current) < MAX_CHILD_ATTEMPTS)
87020
+ else if (this.satellite !== undefined || this.attempts(current) < MAX_CHILD_ATTEMPTS) {
86183
87021
  await leased(() => queue.releaseExited(lease, fenced));
86184
- else if (await leased(() => queue.failExited(lease, fenced))) {
87022
+ this.idleClaims.wakeOne();
87023
+ } else if (await leased(() => queue.failExited(lease, fenced))) {
86185
87024
  const fault = message.fault === undefined ? undefined : rehydrateError(message.fault);
86186
87025
  this.failWork(fenced, this.retryLimit(current, fault === undefined ? "refused-stale" : "pool-fault", fault));
86187
87026
  }
@@ -86218,34 +87057,42 @@ class PoolCoordinator {
86218
87057
  throw new Error("Worker already holds an attempt");
86219
87058
  if (this.retiresIdle(slot))
86220
87059
  return;
86221
- let claimed;
86222
- const lagging = this.shipping?.lagging() === true;
86223
- if (lagging)
86224
- this.shipping?.flushAll().catch(() => {});
86225
- if (!this.budgetBlocked && !this.draining && !lagging) {
86226
- if (!this.places.claim(slot))
87060
+ const claimed = await this.idleClaims.claim(slot.idle, async (found) => {
87061
+ if (this.draining)
86227
87062
  return;
87063
+ const shipping = this.shipping;
87064
+ const lagging = shipping?.lagging() === true;
87065
+ if (lagging) {
87066
+ this.lagGated = true;
87067
+ shipping?.flushAll().then(() => {
87068
+ if (!shipping.lagging())
87069
+ this.gateOpened();
87070
+ }).catch(() => {});
87071
+ }
87072
+ if (this.budgetBlocked || lagging || !this.places.claim(slot)) {
87073
+ this.claimsGated = true;
87074
+ return;
87075
+ }
87076
+ let taken;
86228
87077
  slot.claiming = true;
86229
87078
  try {
86230
- claimed = await leased(async () => {
87079
+ taken = await leased(async () => {
86231
87080
  await this.recoverExpired();
86232
87081
  slot.runs.clear();
86233
- return this.claimFor(queue, lease, worker, options.leaseMs, slot);
87082
+ return this.claimFor(queue, lease, worker, options.leaseMs, slot, found);
86234
87083
  });
86235
87084
  } finally {
86236
87085
  slot.claiming = false;
86237
87086
  slot.claimed = undefined;
86238
- if (claimed === undefined)
87087
+ if (taken === undefined) {
86239
87088
  this.places.end(slot);
87089
+ this.gateOpened();
87090
+ }
86240
87091
  }
86241
- }
86242
- if (this.closed)
87092
+ return taken;
87093
+ }, slot.exited.signal);
87094
+ if (this.closed || claimed === undefined)
86243
87095
  return;
86244
- if (claimed === undefined) {
86245
- if (options.shared !== undefined)
86246
- await this.idlePauses.pause();
86247
- return;
86248
- }
86249
87096
  slot.work = claimed.work;
86250
87097
  slot.worktree = claimed.worktree;
86251
87098
  await this.holdShipping(slot, claimed.work, options.leaseMs);
@@ -86261,8 +87108,13 @@ class PoolCoordinator {
86261
87108
  const held = slot.work;
86262
87109
  if (!held)
86263
87110
  throw new Error("Worker has no active attempt");
86264
- if (message.kind === "place")
86265
- return message.op === "release" ? this.releasePlace(slot) : this.places.reacquire(slot);
87111
+ if (message.kind === "place") {
87112
+ if (message.op === "release")
87113
+ return this.releasePlace(slot);
87114
+ const granted = await this.places.reacquire(slot);
87115
+ this.retireWaiting();
87116
+ return granted;
87117
+ }
86266
87118
  if (message.kind === "heartbeat") {
86267
87119
  const record = this.usageLedger.recording(lease, held, message.reports);
86268
87120
  const beat = await leased(() => queue.heartbeat(lease, held, options.leaseMs, record));
@@ -86378,6 +87230,8 @@ class PoolCoordinator {
86378
87230
  slot.work = undefined;
86379
87231
  slot.worktree = undefined;
86380
87232
  this.places.end(slot);
87233
+ this.gateOpened();
87234
+ this.retireWaiting();
86381
87235
  await this.sendResult(work.id);
86382
87236
  };
86383
87237
  const handled = this.counters.within(message.kind, () => lanes.run(WORKER_REQUEST_LANES[message.kind], answer));
@@ -86409,7 +87263,7 @@ class PoolCoordinator {
86409
87263
  });
86410
87264
  });
86411
87265
  }
86412
- async claimFor(queue, lease, worker, leaseMs, slot) {
87266
+ async claimFor(queue, lease, worker, leaseMs, slot, found) {
86413
87267
  const definitions = this.sources.map((source) => ({
86414
87268
  definition: `${source.path}#${source.exportName}`,
86415
87269
  digest: source.digest
@@ -86417,23 +87271,67 @@ class PoolCoordinator {
86417
87271
  const satellite = this.satellite;
86418
87272
  if (satellite === undefined) {
86419
87273
  const shared = this.options?.shared !== undefined;
86420
- const work = await queue.claim(lease, worker, definitions, leaseMs, shared ? { kind: "unbound" } : undefined);
87274
+ const work = await queue.claim(lease, worker, definitions, leaseMs, shared ? { kind: "unbound" } : undefined, (error) => {
87275
+ if (infrastructureFaultOf(error) === "storage_unavailable")
87276
+ throw error;
87277
+ slot.idle.reset();
87278
+ });
87279
+ if (work !== undefined)
87280
+ found();
86421
87281
  const blobs = this.remote === undefined ? undefined : this.durable?.snapshotBlobs;
86422
87282
  return work === undefined ? undefined : { work: await claimedWithStoredSnapshot(queue, work, blobs) };
86423
87283
  }
86424
87284
  const backoff = satellite.restoreBackoff ?? this.restoreBackoff;
86425
- const chosen = await choosePlacement(await queue.readyCandidates(lease, definitions, PLACEMENT_CANDIDATES), (binding) => this.warmWorktree(satellite, binding, slot.exited.signal), (binding) => satellite.restore !== undefined && !backoff.waiting(workspaceAffinityKey(binding)));
86426
- if (chosen === undefined || this.draining || this.closed)
87285
+ let chosen;
87286
+ let work;
87287
+ let refused;
87288
+ const attempted = new Map;
87289
+ for (let remaining = PLACEMENT_CANDIDATES;remaining > 0; remaining--) {
87290
+ const ready = await queue.readyCandidates(lease, definitions, PLACEMENT_CANDIDATES);
87291
+ const previous = refused;
87292
+ if (previous !== undefined && ready.some((candidate) => candidate.id === previous.id && candidate.generation === previous.generation)) {
87293
+ const admission = await queue.acceptsClaim(lease, {
87294
+ id: satellite.host,
87295
+ providerId: satellite.providerId
87296
+ });
87297
+ if (admission === "drain") {
87298
+ this.scheduleClaimRetry(SHARED_POLL_MS);
87299
+ this.scheduleCandidateRetries(satellite, backoff, ready);
87300
+ }
87301
+ if (admission !== "accepted")
87302
+ return;
87303
+ slot.idle.reset();
87304
+ }
87305
+ const candidates = ready.filter((candidate) => attempted.get(candidate.id) !== candidate.generation);
87306
+ chosen = await choosePlacement(candidates, (binding) => this.warmWorktree(satellite, binding, slot.exited.signal), (binding) => {
87307
+ if (satellite.restore === undefined)
87308
+ return false;
87309
+ const waitMs = backoff.remaining(workspaceAffinityKey(binding));
87310
+ if (waitMs > 0)
87311
+ this.scheduleClaimRetry(waitMs);
87312
+ return waitMs === 0;
87313
+ });
87314
+ if (this.draining || this.closed || slot.exited.signal.aborted)
87315
+ return;
87316
+ if (chosen === undefined) {
87317
+ this.scheduleCandidateRetries(satellite, backoff, candidates);
87318
+ return;
87319
+ }
87320
+ work = await queue.claim(lease, worker, definitions, leaseMs, {
87321
+ kind: "work",
87322
+ id: chosen.candidate.id,
87323
+ generation: chosen.candidate.generation,
87324
+ host: { id: satellite.host, providerId: satellite.providerId }
87325
+ });
87326
+ if (work !== undefined)
87327
+ break;
87328
+ refused = chosen.candidate;
87329
+ attempted.set(refused.id, refused.generation);
87330
+ }
87331
+ if (work === undefined || chosen === undefined)
86427
87332
  return;
87333
+ found();
86428
87334
  const { candidate, worktree } = chosen;
86429
- const work = await queue.claim(lease, worker, definitions, leaseMs, {
86430
- kind: "work",
86431
- id: candidate.id,
86432
- generation: candidate.generation,
86433
- host: { id: satellite.host, providerId: satellite.providerId }
86434
- });
86435
- if (work === undefined)
86436
- return;
86437
87335
  if (this.closed) {
86438
87336
  await this.releaseHeld(work);
86439
87337
  return;
@@ -86471,15 +87369,43 @@ class PoolCoordinator {
86471
87369
  await this.restoreFailed(satellite, backoff, binding, restored.error);
86472
87370
  return;
86473
87371
  }
87372
+ scheduleCandidateRetries(satellite, backoff, candidates) {
87373
+ if (satellite.restore === undefined)
87374
+ return;
87375
+ for (const candidate of candidates) {
87376
+ if (candidate.workspace === undefined)
87377
+ continue;
87378
+ const waitMs = backoff.remaining(workspaceAffinityKey(candidate.workspace));
87379
+ if (waitMs > 0)
87380
+ this.scheduleClaimRetry(waitMs);
87381
+ }
87382
+ }
87383
+ scheduleClaimRetry(waitMs) {
87384
+ if (this.closed)
87385
+ return;
87386
+ const at = performance.now() + waitMs;
87387
+ if (at >= this.claimRetryAt)
87388
+ return;
87389
+ clearTimeout(this.claimRetryTimer);
87390
+ this.claimRetryAt = at;
87391
+ this.claimRetryTimer = setTimeout(() => {
87392
+ this.claimRetryTimer = undefined;
87393
+ this.claimRetryAt = Number.POSITIVE_INFINITY;
87394
+ if (!this.closed)
87395
+ this.idleClaims.wakeOne();
87396
+ }, Math.ceil(waitMs)).unref();
87397
+ }
86474
87398
  async restoreFailed(satellite, backoff, binding, error) {
86475
87399
  const key = workspaceAffinityKey(binding);
86476
87400
  const waitMs = backoff.failed(key);
86477
87401
  await this.sharedPool.recordRestoreBackoff(satellite.host, key, waitMs, serializeError(error)).catch((recording) => satellite.placementFailed(recording));
87402
+ this.scheduleClaimRetry(backoff.remaining(key));
86478
87403
  }
86479
87404
  async restoreSucceeded(satellite, backoff, binding) {
86480
87405
  const key = workspaceAffinityKey(binding);
86481
87406
  if (!backoff.succeeded(key))
86482
87407
  return;
87408
+ this.idleClaims.wakeOne();
86483
87409
  await this.sharedPool.clearRestoreBackoff(satellite.host, key).catch((clearing) => satellite.placementFailed(clearing));
86484
87410
  }
86485
87411
  async warmWorktree(satellite, binding, workerExited) {
@@ -86583,6 +87509,7 @@ class PoolCoordinator {
86583
87509
  await this.admission?.reconcile();
86584
87510
  const expiredBefore = Date.now();
86585
87511
  const rows = await queue.inspect(root);
87512
+ this.hasPendingHandoff = rows.some((work) => work.state === "ready" && work.epoch === lease.epoch && this.handoffs(work) > 0);
86586
87513
  const expired = rows.filter((work) => work.state === "leased" && work.expiresAt < expiredBefore);
86587
87514
  if (expired.length > 0 && await queue.rootLease(lease, COORDINATOR_LEASE_MS) === "late") {
86588
87515
  this.rootRenewal(queue).catch(() => {});
@@ -86620,6 +87547,8 @@ class PoolCoordinator {
86620
87547
  await this.shipping?.release(work);
86621
87548
  }
86622
87549
  }
87550
+ if (expired.length > 0 || this.hasPendingHandoff)
87551
+ this.idleClaims.wakeOne();
86623
87552
  if (this.satellite === undefined && this.sharedPool !== undefined)
86624
87553
  await this.settleShared(queue, lease, this.sharedPool, rows);
86625
87554
  })().finally(() => {
@@ -86786,10 +87715,13 @@ class PoolCoordinator {
86786
87715
  }
86787
87716
  async close() {
86788
87717
  this.closed = true;
87718
+ this.idleClaims.wakeAll();
86789
87719
  this.closedSignal.abort();
86790
87720
  this.placingSignal.abort();
86791
87721
  clearInterval(this.ticker);
86792
87722
  clearInterval(this.recoveryTimer);
87723
+ clearInterval(this.readyProbeTimer);
87724
+ clearTimeout(this.claimRetryTimer);
86793
87725
  this.poolReady?.close();
86794
87726
  clearInterval(this.mirrorTimer);
86795
87727
  clearInterval(this.statsTimer);
@@ -86890,7 +87822,7 @@ function withHostGit(env, git) {
86890
87822
  function handoffDelayMs(handoffs) {
86891
87823
  return Math.random() * Math.min(HANDOFF_DELAY_MAX_MS, HANDOFF_DELAY_BASE_MS * 2 ** Math.min(handoffs, 16));
86892
87824
  }
86893
- var CONTROL_ACKNOWLEDGEMENT_STALL_MS = 5000, RECOVERY_INTERVAL_MS = 500, TICK_INTERVAL_MS = 100, STALL_THRESHOLD_MS = 500, COORDINATOR_LEASE_MS, LATE_ROOT_POLL_MS, MIRROR_INTERVAL_MS = 1e4, STDERR_DRAIN_GRACE_MS = 1000, WORKER_EXIT_CONFIRMATION_MS = 5000, WORKER_EXIT_POLL_MS = 50, MAX_CHILD_ATTEMPTS = 3, MAX_CHILD_HANDOFFS = 20, HANDOFF_DELAY_BASE_MS = 500, HANDOFF_DELAY_MAX_MS = 30000, PLACEMENT_CANDIDATES = 32, PREFERENCE_CACHE_MS = 1000, PREFERENCE_CACHE_ENTRIES = 256, SHARED_POLL_MS = 500, SHARED_IDLE_CLAIM_MS = 500, STAGE_INPUT_LEASE_MS = 30000, STAGE_INPUT_RECEIPT_TIMEOUT_MS = 60000, STAGE_INPUT_RETRY_MAX_MS = 4000, MAX_WORKER_REPLACEMENTS = 3, ROUTE_REGISTRATION_WAIT_MS = 120000, STAGE_WATCH_BACKLOG_EVENTS = 2000, STAGE_WATCH_BACKLOG_BYTES, PENDING_STAGE_MESSAGE_EVENT2 = "atomic:workflow-pending-stage-message", STICKY_LIVE_DELIVERED_EVENT2 = "atomic:workflow-sticky-live-delivered", PENDING_STAGE_UNDELIVERABLE_EVENT2 = "atomic:workflow-pending-stage-undeliverable", ENDED_WATCHES_REMEMBERED = 1024;
87825
+ var CONTROL_ACKNOWLEDGEMENT_STALL_MS = 5000, RECOVERY_INTERVAL_MS = 500, TICK_INTERVAL_MS = 100, STALL_THRESHOLD_MS = 500, COORDINATOR_LEASE_MS, LATE_ROOT_POLL_MS, MIRROR_INTERVAL_MS = 1e4, STDERR_DRAIN_GRACE_MS = 1000, WORKER_EXIT_CONFIRMATION_MS = 5000, WORKER_EXIT_POLL_MS = 50, MAX_CHILD_ATTEMPTS = 3, MAX_CHILD_HANDOFFS = 20, HANDOFF_DELAY_BASE_MS = 500, HANDOFF_DELAY_MAX_MS = 30000, PLACEMENT_CANDIDATES = 32, PREFERENCE_CACHE_MS = 1000, PREFERENCE_CACHE_ENTRIES = 256, SHARED_POLL_MS = 500, STAGE_INPUT_LEASE_MS = 30000, STAGE_INPUT_RECEIPT_TIMEOUT_MS = 60000, STAGE_INPUT_RETRY_MAX_MS = 4000, MAX_WORKER_REPLACEMENTS = 3, ROUTE_REGISTRATION_WAIT_MS = 120000, STAGE_WATCH_BACKLOG_EVENTS = 2000, STAGE_WATCH_BACKLOG_BYTES, PENDING_STAGE_MESSAGE_EVENT2 = "atomic:workflow-pending-stage-message", STICKY_LIVE_DELIVERED_EVENT2 = "atomic:workflow-sticky-live-delivered", PENDING_STAGE_UNDELIVERABLE_EVENT2 = "atomic:workflow-pending-stage-undeliverable", ENDED_WATCHES_REMEMBERED = 1024;
86894
87826
  var init_pool_coordinator = __esm(() => {
86895
87827
  init_internal();
86896
87828
  init_pool_remote_journal();
@@ -98746,6 +99678,57 @@ function forkPointRecords(checkpoints, rootRunId) {
98746
99678
  }
98747
99679
  return records;
98748
99680
  }
99681
+ function unfinishedForkTargetRecords(checkpoints, rootRunId, completed) {
99682
+ const all = checkpoints.map((event) => event.checkpoint);
99683
+ const reached = attemptReachedCheckpoints(all, rootRunId, { rootReach: true });
99684
+ const visible = reached === all ? undefined : new Set(reached);
99685
+ const boundaries = new Map;
99686
+ const finished = new Set;
99687
+ const first = new Map;
99688
+ const last = new Map;
99689
+ for (const { seq, checkpoint } of checkpoints) {
99690
+ if (checkpoint.kind !== "stage")
99691
+ continue;
99692
+ if (checkpoint.topology?.boundary !== undefined && !boundaries.has(checkpoint.replayKey))
99693
+ boundaries.set(checkpoint.replayKey, checkpoint.name);
99694
+ if (checkpoint.output !== undefined)
99695
+ finished.add(checkpoint.replayKey);
99696
+ if (checkpoint.topology?.occurrenceKey !== undefined || visible?.has(checkpoint) === false)
99697
+ continue;
99698
+ const key = JSON.stringify([checkpoint.replayKey, checkpointAttempt(checkpoint)]);
99699
+ if (!first.has(key))
99700
+ first.set(key, { seq, checkpoint });
99701
+ last.set(checkpoint.replayKey, checkpoint);
99702
+ }
99703
+ const enclosing = (replayKey) => [...boundaries.keys()].filter((boundary) => replayKey.startsWith(`${boundary}:`)).sort((a, b) => a.length - b.length).map((boundary) => boundaries.get(boundary));
99704
+ const taken = new Set(completed.map((record) => record.stagePath));
99705
+ const records = [];
99706
+ for (const [replayKey, checkpoint] of last) {
99707
+ const status = checkpoint.topology?.status;
99708
+ if (finished.has(replayKey) || status === undefined || !UNFINISHED_FORK_TARGET_STATUSES.has(status))
99709
+ continue;
99710
+ const base = [...enclosing(replayKey), checkpoint.name].join(STAGE_PATH_SEPARATOR);
99711
+ let occurrence = 0;
99712
+ let stagePath;
99713
+ do {
99714
+ occurrence++;
99715
+ stagePath = occurrence === 1 ? base : `${base}#${occurrence}`;
99716
+ } while (taken.has(stagePath));
99717
+ taken.add(stagePath);
99718
+ records.push({
99719
+ stagePath,
99720
+ replayKey,
99721
+ sessionId: stageSessionId(checkpoint),
99722
+ completedAt: checkpoint.completedAt,
99723
+ ...firstEvent(first.get(JSON.stringify([replayKey, checkpointAttempt(checkpoint)])))
99724
+ });
99725
+ }
99726
+ return records;
99727
+ }
99728
+ function forkTargetRecords(checkpoints, rootRunId) {
99729
+ const completed = forkPointRecords(checkpoints, rootRunId);
99730
+ return { completed, unfinished: unfinishedForkTargetRecords(checkpoints, rootRunId, completed) };
99731
+ }
98749
99732
  function firstEvent(event) {
98750
99733
  return { firstSeq: event.seq, firstTopology: event.checkpoint.topology };
98751
99734
  }
@@ -99034,15 +100017,17 @@ async function resolveForkDefinition(request, handle) {
99034
100017
  }
99035
100018
  }
99036
100019
  function selectForkEvents(source, request) {
99037
- const records = forkPointRecords(source.checkpoints, source.runId);
99038
- const target = records.find((record) => record.stagePath === request.fromStage);
99039
- if (request.fromStage !== undefined && target === undefined)
100020
+ const { completed: records, unfinished } = forkTargetRecords(source.checkpoints, source.runId);
100021
+ const target = records.find((record) => record.stagePath === request.fromStage) ?? unfinished.find((record) => record.stagePath === request.fromStage);
100022
+ if (request.fromStage !== undefined && (target === undefined || request.expectedStageId !== undefined && target.firstTopology?.stageId !== request.expectedStageId)) {
100023
+ const validTargets = [...records, ...unfinished];
99040
100024
  throw new ForkTargetNotFoundError({
99041
100025
  runId: source.runId,
99042
100026
  fromStage: request.fromStage,
99043
- validStagePaths: records.map((record) => record.stagePath),
99044
- totalValidStagePaths: records.length
100027
+ validStagePaths: validTargets.map((record) => record.stagePath),
100028
+ totalValidStagePaths: validTargets.length
99045
100029
  });
100030
+ }
99046
100031
  const cut = target?.firstSeq ?? Number.POSITIVE_INFINITY;
99047
100032
  const carryAll = request.carryMessages === "all";
99048
100033
  const prefix = source.checkpoints.filter((event) => event.seq < cut);
@@ -99579,7 +100564,7 @@ async function copySessions(source, sessions, ids, request, cleanup, claim) {
99579
100564
  throw new ForkCopyFailedError({ runId: source.runId, forkRunId: ids.forkRunId, phase: "sessions" }, { cause: error });
99580
100565
  }
99581
100566
  }
99582
- var STAGE_PATH_SEPARATOR = ".", LOCAL_ONLY_ADAPTERS, SOURCE_CLAIM_RENEW_MS;
100567
+ var STAGE_PATH_SEPARATOR = ".", LOCAL_ONLY_ADAPTERS, UNFINISHED_FORK_TARGET_STATUSES, SOURCE_CLAIM_RENEW_MS;
99583
100568
  var init_fork_run = __esm(() => {
99584
100569
  init_executor_child_helpers();
99585
100570
  init_executor_inputs();
@@ -99600,6 +100585,7 @@ var init_fork_run = __esm(() => {
99600
100585
  init_stage_topology();
99601
100586
  init_stage_topology_validation();
99602
100587
  LOCAL_ONLY_ADAPTERS = new Set(["memory", "node-sqlite", "jsonl"]);
100588
+ UNFINISHED_FORK_TARGET_STATUSES = new Set(["failed", "blocked", "paused", "suspended"]);
99603
100589
  SOURCE_CLAIM_RENEW_MS = FOREIGN_LIVE_WORKFLOW_WINDOW_MS / 4;
99604
100590
  });
99605
100591