@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
@@ -1364,6 +1364,7 @@ class JournalProjection {
1364
1364
  return;
1365
1365
  rec.released += rec.checkpoints.size;
1366
1366
  rec.checkpoints.clear();
1367
+ rec.sortedCheckpoints = undefined;
1367
1368
  rec.toolByHash.clear();
1368
1369
  rec.uiByHash.clear();
1369
1370
  rec.stageOutputByReplayKey.clear();
@@ -1379,6 +1380,7 @@ class JournalProjection {
1379
1380
  if (checkpoint === undefined)
1380
1381
  continue;
1381
1382
  rec.checkpoints.delete(key);
1383
+ rec.sortedCheckpoints = undefined;
1382
1384
  rec.released++;
1383
1385
  if (checkpoint.kind === "tool")
1384
1386
  rec.toolByHash.delete(checkpoint.argsHash);
@@ -1401,6 +1403,7 @@ class JournalProjection {
1401
1403
  if (rec.checkpoints.has(key))
1402
1404
  return;
1403
1405
  rec.checkpoints.set(key, currentCheckpoint);
1406
+ rec.sortedCheckpoints = undefined;
1404
1407
  rec.attempt = Math.max(rec.attempt, workflowAttemptOf(currentCheckpoint) ?? 0);
1405
1408
  rec.nestedSnapshotVersion.record(currentCheckpoint);
1406
1409
  if (currentCheckpoint.kind === "tool") {
@@ -1448,11 +1451,20 @@ class JournalProjection {
1448
1451
  ...checkpoint.attempt !== undefined ? { attempt: checkpoint.attempt } : {}
1449
1452
  };
1450
1453
  }
1454
+ recordedCheckpoints(workflowId) {
1455
+ const rec = this.workflows.get(workflowId);
1456
+ if (rec === undefined || rec.released > 0)
1457
+ return;
1458
+ return [...rec.checkpoints.values()];
1459
+ }
1451
1460
  listCheckpoints(workflowId) {
1452
1461
  const rec = this.workflows.get(workflowId);
1453
1462
  if (!rec)
1454
1463
  return [];
1455
- return [...rec.checkpoints.values()].sort((a, b) => a.completedAt - b.completedAt);
1464
+ if (rec.sortedCheckpoints === undefined) {
1465
+ rec.sortedCheckpoints = Object.freeze([...rec.checkpoints.values()].sort((a, b) => a.completedAt - b.completedAt));
1466
+ }
1467
+ return rec.sortedCheckpoints;
1456
1468
  }
1457
1469
  getStoredCheckpoint(checkpoint) {
1458
1470
  return this.workflows.get(checkpoint.workflowId)?.checkpoints.get(checkpointKey(checkpoint));
@@ -3401,6 +3413,12 @@ class JournalDurableBackend {
3401
3413
  listCheckpoints(runId) {
3402
3414
  return this.projection.listCheckpoints(runId);
3403
3415
  }
3416
+ async readCheckpointSequence(runId) {
3417
+ if (this.projection.getWorkflow(runId) === undefined || this.summarized.has(runId) || this.lacksChildCheckpoints(runId) || this.checkpointSelections.has(runId))
3418
+ return;
3419
+ await this.catchUpWorkflow(runId);
3420
+ return this.projection.recordedCheckpoints(runId);
3421
+ }
3404
3422
  getStageCheckpoint(runId, checkpointId) {
3405
3423
  return this.projection.getStageCheckpoint(runId, checkpointId);
3406
3424
  }
@@ -4414,6 +4432,7 @@ class SqlRunJournal {
4414
4432
  })
4415
4433
  } : {},
4416
4434
  read: (body) => this.operation(() => this.readSnapshot((executor) => body(this.versionChecked(executor)))),
4435
+ peek: (body) => this.operation(() => this.readSnapshot(body)),
4417
4436
  withAppendGuard: (guard, action) => this.appendGuard.run(guard, action),
4418
4437
  tables: this.tables,
4419
4438
  olderBuildLive: (executor) => olderBuildLive(executor, this.dialect, this.tables),
@@ -6937,7 +6956,7 @@ var init_fork_errors = __esm(() => {
6937
6956
  code: "target-not-found",
6938
6957
  what: "Fork target not found",
6939
6958
  subject: `stage "${input.fromStage}" in run ${input.runId}`,
6940
- 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.`,
6959
+ 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.`,
6941
6960
  retryable: false,
6942
6961
  fields: { runId: input.runId, fromStage: input.fromStage, validStagePaths, totalValidStagePaths }
6943
6962
  });
@@ -10974,6 +10993,96 @@ function flattenTruncatedString(value2) {
10974
10993
  return value2.split("").join("");
10975
10994
  }
10976
10995
 
10996
+ // dist/builtin/workflows/src/shared/inspection-payload.ts
10997
+ function boxedKind(value2) {
10998
+ try {
10999
+ const prototype = Object.getPrototypeOf(value2);
11000
+ if (prototype === Object.prototype || prototype === null || Array.isArray(value2))
11001
+ return;
11002
+ } catch {
11003
+ return;
11004
+ }
11005
+ try {
11006
+ Number.prototype.valueOf.call(value2);
11007
+ return "number";
11008
+ } catch {}
11009
+ try {
11010
+ String.prototype.valueOf.call(value2);
11011
+ return "string";
11012
+ } catch {}
11013
+ try {
11014
+ Boolean.prototype.valueOf.call(value2);
11015
+ return "boolean";
11016
+ } catch {}
11017
+ try {
11018
+ BigInt.prototype.valueOf.call(value2);
11019
+ return "bigint";
11020
+ } catch {}
11021
+ return;
11022
+ }
11023
+ function cloneValue(source, key, ancestors) {
11024
+ let value2 = source;
11025
+ if (value2 !== null && (typeof value2 === "object" || typeof value2 === "function") || typeof value2 === "bigint") {
11026
+ const convert = value2.toJSON;
11027
+ if (typeof convert === "function")
11028
+ value2 = convert.call(value2, key);
11029
+ }
11030
+ if (value2 !== null && typeof value2 === "object") {
11031
+ const kind = boxedKind(value2);
11032
+ if (kind === "number")
11033
+ value2 = Number(value2);
11034
+ else if (kind === "string")
11035
+ value2 = String(value2);
11036
+ else if (kind === "boolean")
11037
+ value2 = Boolean.prototype.valueOf.call(value2);
11038
+ else if (kind === "bigint")
11039
+ throw new TypeError("BigInt cannot be serialized");
11040
+ }
11041
+ if (value2 === null)
11042
+ return null;
11043
+ const json = JSON;
11044
+ if (typeof value2 === "object" && json.isRawJSON?.(value2) === true) {
11045
+ return JSON.parse(value2.rawJSON);
11046
+ }
11047
+ switch (typeof value2) {
11048
+ case "string":
11049
+ case "boolean":
11050
+ return value2;
11051
+ case "number":
11052
+ return Number.isFinite(value2) ? Object.is(value2, -0) ? 0 : value2 : null;
11053
+ case "bigint":
11054
+ throw new TypeError("BigInt cannot be serialized");
11055
+ case "undefined":
11056
+ case "function":
11057
+ case "symbol":
11058
+ return;
11059
+ }
11060
+ if (ancestors.has(value2))
11061
+ throw new TypeError("Circular snapshot value cannot be serialized");
11062
+ ancestors.add(value2);
11063
+ try {
11064
+ if (Array.isArray(value2)) {
11065
+ return Array.from({ length: value2.length }, (_, index) => cloneValue(value2[index], String(index), ancestors) ?? null);
11066
+ }
11067
+ const result = {};
11068
+ for (const name of Object.keys(value2)) {
11069
+ const item = cloneValue(value2[name], name, ancestors);
11070
+ if (item === undefined)
11071
+ continue;
11072
+ if (name === "__proto__")
11073
+ Object.defineProperty(result, name, { value: item, enumerable: true, configurable: true, writable: true });
11074
+ else
11075
+ result[name] = item;
11076
+ }
11077
+ return result;
11078
+ } finally {
11079
+ ancestors.delete(value2);
11080
+ }
11081
+ }
11082
+ function cloneInspectionPayload(value2) {
11083
+ return cloneValue(value2, "", new Set);
11084
+ }
11085
+
10977
11086
  // dist/builtin/workflows/src/shared/run-stage-index.ts
10978
11087
  function asksForInput(stage) {
10979
11088
  return stage.pendingPrompt !== undefined || stage.inputRequest !== undefined || stage.status === "awaiting_input" || stage.awaitingInputSince !== undefined;
@@ -11135,7 +11244,7 @@ function cloneObjectLike(state, value2) {
11135
11244
  items.push(null);
11136
11245
  continue;
11137
11246
  }
11138
- items.push(cloneValue(state, item));
11247
+ items.push(cloneValue2(state, item));
11139
11248
  }
11140
11249
  return items;
11141
11250
  }
@@ -11146,7 +11255,7 @@ function cloneObjectLike(state, value2) {
11146
11255
  const child = safeProperty(value2, key);
11147
11256
  if (isOmittedJsonValue(child))
11148
11257
  continue;
11149
- cloned[key] = cloneValue(state, child);
11258
+ cloned[key] = cloneValue2(state, child);
11150
11259
  }
11151
11260
  if (scan.stoppedByLimit())
11152
11261
  addTruncationMarker(cloned);
@@ -11156,7 +11265,7 @@ function cloneObjectLike(state, value2) {
11156
11265
  state.seen.delete(value2);
11157
11266
  }
11158
11267
  }
11159
- function cloneValue(state, value2) {
11268
+ function cloneValue2(state, value2) {
11160
11269
  const resolved = resolveJsonValue(value2);
11161
11270
  if (resolved === null) {
11162
11271
  state.remaining -= NULL_COST;
@@ -11182,7 +11291,7 @@ function cloneValue(state, value2) {
11182
11291
  }
11183
11292
  }
11184
11293
  function boundedToolPayload(value2, limit = TOOL_PAYLOAD_VALUE_LIMIT) {
11185
- return cloneValue({ remaining: Math.max(1, limit), depth: 0, keysRemaining: TOOL_PAYLOAD_MAX_KEYS, seen: new Set }, value2);
11294
+ return cloneValue2({ remaining: Math.max(1, limit), depth: 0, keysRemaining: TOOL_PAYLOAD_MAX_KEYS, seen: new Set }, value2);
11186
11295
  }
11187
11296
  function boundedToolPayloadRecord(value2, limit = TOOL_PAYLOAD_VALUE_LIMIT) {
11188
11297
  const record = {};
@@ -11200,7 +11309,7 @@ function boundedToolPayloadRecord(value2, limit = TOOL_PAYLOAD_VALUE_LIMIT) {
11200
11309
  const child = safeProperty(value2, key);
11201
11310
  if (isOmittedJsonValue(child))
11202
11311
  continue;
11203
- record[key] = cloneValue(state, child);
11312
+ record[key] = cloneValue2(state, child);
11204
11313
  }
11205
11314
  if (scan.stoppedByLimit())
11206
11315
  addTruncationMarker(record);
@@ -11339,7 +11448,11 @@ function compactToolNode(node) {
11339
11448
  ...node.source !== undefined ? { source: boundedToolText(node.source) } : {}
11340
11449
  };
11341
11450
  }
11342
- function compactRun(run, stages = run.stages.map(compactStage), toolNodes = run.toolNodes.map(compactToolNode)) {
11451
+ function compactRun(run, stages = run.stages.map(compactStage), toolNodes = run.toolNodes.map(compactToolNode), full = false) {
11452
+ if (full) {
11453
+ const copy = cloneInspectionPayload({ ...run, stages: [], toolNodes: [] });
11454
+ return { ...copy, stages, toolNodes };
11455
+ }
11343
11456
  const {
11344
11457
  inputs: _inputs,
11345
11458
  result: sourceResult,
@@ -11374,8 +11487,8 @@ function sameSourceShape(value2, shape) {
11374
11487
  function isSettledStage(stage) {
11375
11488
  return stage.status === "completed" || stage.status === "failed" || stage.status === "skipped";
11376
11489
  }
11377
- function projectStage(stage) {
11378
- const compact = compactStage(stage);
11490
+ function projectStage(stage, full = false) {
11491
+ const compact = full ? cloneInspectionPayload(stage) : compactStage(stage);
11379
11492
  deepFreezeGraphValue(compact);
11380
11493
  return {
11381
11494
  shape: sourceShape(stage),
@@ -11390,15 +11503,19 @@ function projectStage(stage) {
11390
11503
  function stageUnchanged(stage, projected) {
11391
11504
  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;
11392
11505
  }
11393
- function projectToolNode(node) {
11394
- const compact = compactToolNode(node);
11506
+ function projectToolNode(node, full = false) {
11507
+ const compact = full ? cloneInspectionPayload(node) : compactToolNode(node);
11395
11508
  deepFreezeGraphValue(compact);
11396
11509
  return { shape: sourceShape(node), parentCount: node.parentIds.length, compact };
11397
11510
  }
11398
11511
  function toolNodeUnchanged(node, projected) {
11399
11512
  return sameSourceShape(node, projected.shape) && node.parentIds.length === projected.parentCount;
11400
11513
  }
11401
- function freezeCompactRun(run) {
11514
+ function freezeCompactRun(run, full = false) {
11515
+ if (full) {
11516
+ Object.freeze(run.stages);
11517
+ Object.freeze(run.toolNodes);
11518
+ }
11402
11519
  for (const [key, value2] of Object.entries(run)) {
11403
11520
  if (key === "stages" || key === "toolNodes")
11404
11521
  markPublishedSnapshotArray(value2);
@@ -11407,18 +11524,23 @@ function freezeCompactRun(run) {
11407
11524
  }
11408
11525
  Object.freeze(run);
11409
11526
  }
11527
+ function graphSnapshotLineage(snapshot) {
11528
+ return snapshotLineages.get(snapshot);
11529
+ }
11410
11530
 
11411
11531
  class GraphStoreSnapshotBuilder {
11532
+ full;
11533
+ constructor(options = {}) {
11534
+ this.full = options.fullPayloads ?? false;
11535
+ }
11412
11536
  projected = new Map;
11537
+ recheckSettledStages = false;
11413
11538
  changedRuns = new Set;
11414
11539
  changedStages = new Map;
11415
11540
  changedToolNodes = new Map;
11416
11541
  markChanged(change) {
11417
11542
  if (change === undefined) {
11418
- this.projected.clear();
11419
- this.changedRuns.clear();
11420
- this.changedStages.clear();
11421
- this.changedToolNodes.clear();
11543
+ this.recheckSettledStages = true;
11422
11544
  return;
11423
11545
  }
11424
11546
  if (change.stageId === undefined && change.toolNodeId === undefined) {
@@ -11430,6 +11552,22 @@ class GraphStoreSnapshotBuilder {
11430
11552
  if (change.toolNodeId !== undefined)
11431
11553
  addScoped(this.changedToolNodes, change.runId, change.toolNodeId);
11432
11554
  }
11555
+ hasRun(run) {
11556
+ return this.projected.get(run.id)?.source === run;
11557
+ }
11558
+ removeRun(runId) {
11559
+ this.projected.delete(runId);
11560
+ this.changedRuns.delete(runId);
11561
+ this.changedStages.delete(runId);
11562
+ this.changedToolNodes.delete(runId);
11563
+ }
11564
+ clear() {
11565
+ this.projected.clear();
11566
+ this.recheckSettledStages = false;
11567
+ this.changedRuns.clear();
11568
+ this.changedStages.clear();
11569
+ this.changedToolNodes.clear();
11570
+ }
11433
11571
  build(runs, notices, version) {
11434
11572
  const previous = this.projected;
11435
11573
  const next = new Map;
@@ -11440,16 +11578,16 @@ class GraphStoreSnapshotBuilder {
11440
11578
  compactRuns.push(projected.compact);
11441
11579
  }
11442
11580
  this.projected = next;
11581
+ this.recheckSettledStages = false;
11443
11582
  this.changedRuns.clear();
11444
11583
  this.changedStages.clear();
11445
11584
  this.changedToolNodes.clear();
11446
11585
  const compactNotices = notices.map((notice) => ({ ...notice }));
11447
11586
  deepFreezeGraphValue(compactNotices);
11448
- const snapshot = Object.freeze({
11449
- runs: Object.freeze(compactRuns),
11450
- notices: compactNotices,
11451
- version
11452
- });
11587
+ return this.publish(compactRuns, compactNotices, version);
11588
+ }
11589
+ publish(runs, notices, version) {
11590
+ const snapshot = Object.freeze({ runs: Object.freeze(runs), notices, version });
11453
11591
  snapshotLineages.set(snapshot, this);
11454
11592
  return snapshot;
11455
11593
  }
@@ -11500,7 +11638,8 @@ class GraphStoreSnapshotBuilder {
11500
11638
  changed.add(position);
11501
11639
  }
11502
11640
  }
11503
- for (const position of projected.unsettled)
11641
+ const positions = this.recheckSettledStages ? sources.keys() : projected.unsettled;
11642
+ for (const position of positions)
11504
11643
  if (!changed.has(position) && !stageUnchanged(sources[position], projected.stages[position]))
11505
11644
  changed.add(position);
11506
11645
  if (changed.size === 0 && run.stages.length === sources.length)
@@ -11509,7 +11648,7 @@ class GraphStoreSnapshotBuilder {
11509
11648
  const appendedFrom = sources.length;
11510
11649
  const compactStages = previous.stages.slice();
11511
11650
  for (const position of changed) {
11512
- const stage = projectStage(sources[position]);
11651
+ const stage = projectStage(sources[position], this.full);
11513
11652
  projected.stages[position] = stage;
11514
11653
  compactStages[position] = stage.compact;
11515
11654
  if (stage.settled)
@@ -11519,7 +11658,7 @@ class GraphStoreSnapshotBuilder {
11519
11658
  }
11520
11659
  for (let position = sources.length;position < run.stages.length; position++) {
11521
11660
  const source = run.stages[position];
11522
- const stage = projectStage(source);
11661
+ const stage = projectStage(source, this.full);
11523
11662
  sources.push(source);
11524
11663
  projected.stages.push(stage);
11525
11664
  compactStages.push(stage.compact);
@@ -11531,7 +11670,7 @@ class GraphStoreSnapshotBuilder {
11531
11670
  projected.stagePositions.set(source.id, position);
11532
11671
  }
11533
11672
  const compact = { ...previous, stages: compactStages };
11534
- freezeCompactRun(compact);
11673
+ freezeCompactRun(compact, this.full);
11535
11674
  indexRunFrom(compact, previous, changed, appendedFrom);
11536
11675
  projected.compact = compact;
11537
11676
  return projected;
@@ -11551,7 +11690,7 @@ class GraphStoreSnapshotBuilder {
11551
11690
  for (const stage of run.stages) {
11552
11691
  let projected = previousStages.get(stage);
11553
11692
  if (projected === undefined || changedStages?.has(stage.id) === true || !stageUnchanged(stage, projected))
11554
- projected = projectStage(stage);
11693
+ projected = projectStage(stage, this.full);
11555
11694
  previousStages.set(stage, projected);
11556
11695
  const position = stages.length;
11557
11696
  stageSources.push(stage);
@@ -11570,12 +11709,12 @@ class GraphStoreSnapshotBuilder {
11570
11709
  for (const node of run.toolNodes) {
11571
11710
  let projected = toolNodes.get(node) ?? previous?.toolNodes.get(node);
11572
11711
  if (projected === undefined || changedToolNodes?.has(node.id) === true || !toolNodeUnchanged(node, projected))
11573
- projected = projectToolNode(node);
11712
+ projected = projectToolNode(node, this.full);
11574
11713
  toolNodes.set(node, projected);
11575
11714
  compactToolNodes.push(projected.compact);
11576
11715
  }
11577
- const compact = compactRun(run, compactStages, compactToolNodes);
11578
- freezeCompactRun(compact);
11716
+ const compact = compactRun(run, compactStages, compactToolNodes, this.full);
11717
+ freezeCompactRun(compact, this.full);
11579
11718
  return {
11580
11719
  source: run,
11581
11720
  shape: sourceShape(run),
@@ -11619,10 +11758,366 @@ var init_graph_store_snapshot = __esm(() => {
11619
11758
  });
11620
11759
 
11621
11760
  // dist/builtin/workflows/src/shared/expanded-workflow-graph.ts
11622
- var leafExpansions, snapshotExpansions, settledStageCounts, expandedStageLists, chainExpansions;
11761
+ function toolNodesFor(run) {
11762
+ if (run.toolNodes === undefined)
11763
+ throw new MissingWorkflowToolNodesError(run.id);
11764
+ return run.toolNodes;
11765
+ }
11766
+ function virtualNodeId(runId, nodeId, isRootRun) {
11767
+ return isRootRun ? nodeId : `${runId}:${nodeId}`;
11768
+ }
11769
+ function localItems(run) {
11770
+ const stages = run.stages.map((stage, sourceIndex) => ({ kind: "stage", stage, sourceIndex }));
11771
+ const tools = toolNodesFor(run).map((tool, sourceIndex) => ({ kind: "tool", tool, sourceIndex }));
11772
+ return [...stages, ...tools].sort((left, right) => {
11773
+ const leftOrder = left.kind === "stage" ? left.stage.executionOrder : left.tool.executionOrder;
11774
+ const rightOrder = right.kind === "stage" ? right.stage.executionOrder : right.tool.executionOrder;
11775
+ if (leftOrder !== undefined || rightOrder !== undefined)
11776
+ return (leftOrder ?? Number.MAX_SAFE_INTEGER) - (rightOrder ?? Number.MAX_SAFE_INTEGER);
11777
+ if (left.kind !== right.kind)
11778
+ return left.kind === "stage" ? -1 : 1;
11779
+ return left.sourceIndex - right.sourceIndex;
11780
+ });
11781
+ }
11782
+ function itemId(item) {
11783
+ return item.kind === "stage" ? item.stage.id : item.tool.id;
11784
+ }
11785
+ function itemParents(item) {
11786
+ return item.kind === "stage" ? item.stage.parentIds : item.tool.parentIds;
11787
+ }
11788
+ function localTerminalIds(items) {
11789
+ const parents = new Set(items.flatMap((item) => [...itemParents(item)]));
11790
+ const terminals = items.map(itemId).filter((id) => !parents.has(id));
11791
+ return terminals.length > 0 ? terminals : items.map(itemId);
11792
+ }
11793
+ function projectedToolStatus(tool) {
11794
+ if (tool.status === "cached")
11795
+ return "completed";
11796
+ if (tool.status === "cancelled")
11797
+ return "skipped";
11798
+ return tool.status;
11799
+ }
11800
+ function isLeafRun(run) {
11801
+ return run.stages.every((stage) => authoritativeWorkflowChildRunId(stage) === undefined);
11802
+ }
11803
+ function expandWorkflowGraph(snapshot, rootRunId) {
11804
+ return createWorkflowGraphExpander(snapshot)(rootRunId);
11805
+ }
11806
+ function isSettledStage2(stage) {
11807
+ return stage.status === "completed" || stage.status === "failed" || stage.status === "skipped";
11808
+ }
11809
+ function executionOrderKey(stage) {
11810
+ return stage.executionOrder ?? Number.MAX_SAFE_INTEGER;
11811
+ }
11812
+ function chainStage(stage) {
11813
+ return stage.nodeKind !== "tool" && authoritativeWorkflowChildRunId(stage) === undefined;
11814
+ }
11815
+ function isChainRun(run) {
11816
+ if (toolNodesFor(run).length > 0)
11817
+ return false;
11818
+ let order = Number.NEGATIVE_INFINITY;
11819
+ for (const stage of run.stages) {
11820
+ const next = executionOrderKey(stage);
11821
+ if (next < order || !chainStage(stage))
11822
+ return false;
11823
+ order = next;
11824
+ }
11825
+ return true;
11826
+ }
11827
+ function expandChainFrom(run, previous) {
11828
+ const before = previous.run.stages;
11829
+ if (run.id !== previous.run.id || run.name !== previous.run.name || toolNodesFor(run).length > 0)
11830
+ return;
11831
+ if (run.stages.length < before.length)
11832
+ return;
11833
+ const replaced = [];
11834
+ for (let index = 0;index < before.length; index++) {
11835
+ const stage = run.stages[index];
11836
+ const earlier = before[index];
11837
+ if (stage === earlier)
11838
+ continue;
11839
+ if (stage.id !== earlier.id || stage.executionOrder !== earlier.executionOrder || !sameIds(stage.parentIds, earlier.parentIds) || !chainStage(stage))
11840
+ return;
11841
+ replaced.push(index);
11842
+ }
11843
+ let order = before.length === 0 ? Number.NEGATIVE_INFINITY : executionOrderKey(before[before.length - 1]);
11844
+ for (let index = before.length;index < run.stages.length; index++) {
11845
+ const stage = run.stages[index];
11846
+ const next = executionOrderKey(stage);
11847
+ if (next < order || !chainStage(stage))
11848
+ return;
11849
+ order = next;
11850
+ }
11851
+ const graph = previous.graph;
11852
+ if (replaced.length === 0 && run.stages.length === before.length)
11853
+ return graph;
11854
+ const stages = graph.stages.slice();
11855
+ const nodes = graph.nodes.slice();
11856
+ for (const index of replaced) {
11857
+ const earlier = graph.stages[index];
11858
+ const stage = {
11859
+ ...run.stages[index],
11860
+ id: earlier.id,
11861
+ parentIds: earlier.parentIds,
11862
+ workflowGraphTarget: earlier.workflowGraphTarget
11863
+ };
11864
+ stages[index] = stage;
11865
+ nodes[index] = { kind: "stage", stage };
11866
+ }
11867
+ let settled = settledStageCounts.get(graph.stages);
11868
+ if (settled !== undefined)
11869
+ for (const index of replaced)
11870
+ settled += Number(isSettledStage2(stages[index])) - Number(isSettledStage2(graph.stages[index]));
11871
+ let targets = graph.targets;
11872
+ if (run.stages.length > before.length) {
11873
+ const extended = new Map(graph.targets);
11874
+ for (let index = before.length;index < run.stages.length; index++) {
11875
+ const source = run.stages[index];
11876
+ const target = { runId: run.id, stageId: source.id, runName: run.name, depth: 0 };
11877
+ extended.set(source.id, target);
11878
+ const stage = {
11879
+ ...source,
11880
+ id: source.id,
11881
+ parentIds: Object.freeze([...source.parentIds]),
11882
+ workflowGraphTarget: target
11883
+ };
11884
+ stages.push(stage);
11885
+ nodes.push({ kind: "stage", stage });
11886
+ if (settled !== undefined)
11887
+ settled += Number(isSettledStage2(stage));
11888
+ }
11889
+ targets = extended;
11890
+ }
11891
+ expandedStageLists.add(stages);
11892
+ if (settled !== undefined)
11893
+ settledStageCounts.set(stages, settled);
11894
+ return { stages, renderStages: stages, tools: graph.tools, nodes, targets };
11895
+ }
11896
+ function rememberChainExpansion(memo, runById, run, graph, patched) {
11897
+ if (patched || isChainRun(run))
11898
+ memo.set(run.id, { run, graph });
11899
+ else
11900
+ memo.delete(run.id);
11901
+ for (const runId of memo.keys())
11902
+ if (!runById.has(runId))
11903
+ memo.delete(runId);
11904
+ }
11905
+ function createWorkflowGraphExpander(snapshot) {
11906
+ let runById;
11907
+ let expansions;
11908
+ let chains;
11909
+ if (Object.isFrozen(snapshot)) {
11910
+ expansions = snapshotExpansions.get(snapshot);
11911
+ if (expansions === undefined) {
11912
+ expansions = new Map;
11913
+ snapshotExpansions.set(snapshot, expansions);
11914
+ }
11915
+ const lineage = graphSnapshotLineage(snapshot);
11916
+ if (lineage !== undefined) {
11917
+ chains = chainExpansions.get(lineage);
11918
+ if (chains === undefined) {
11919
+ chains = new Map;
11920
+ chainExpansions.set(lineage, chains);
11921
+ }
11922
+ }
11923
+ }
11924
+ return (rootRunId) => {
11925
+ const known = expansions?.get(rootRunId);
11926
+ if (known !== undefined)
11927
+ return known;
11928
+ runById ??= new Map(snapshot.runs.map((run) => [run.id, run]));
11929
+ const root = runById.get(rootRunId);
11930
+ const previous = root === undefined ? undefined : chains?.get(rootRunId);
11931
+ const patched = root === undefined || previous === undefined ? undefined : expandChainFrom(root, previous);
11932
+ const graph = patched ?? expandIndexedWorkflowGraph(runById, rootRunId);
11933
+ expansions?.set(rootRunId, graph);
11934
+ if (chains !== undefined && root !== undefined)
11935
+ rememberChainExpansion(chains, runById, root, graph, patched !== undefined);
11936
+ return graph;
11937
+ };
11938
+ }
11939
+ function expandIndexedWorkflowGraph(runById, rootRunId) {
11940
+ const root = runById.get(rootRunId);
11941
+ if (!root)
11942
+ return { stages: [], renderStages: [], tools: [], nodes: [], targets: new Map };
11943
+ const targets = new Map;
11944
+ const rootOwnerByRunId = new Map;
11945
+ const rootOwnerFor = (runId) => {
11946
+ if (rootOwnerByRunId.has(runId))
11947
+ return rootOwnerByRunId.get(runId);
11948
+ const owner = reciprocalWorkflowRootRunId(runById, runId);
11949
+ rootOwnerByRunId.set(runId, owner);
11950
+ return owner;
11951
+ };
11952
+ const visiting = new Set;
11953
+ const expandedChildren = new Set;
11954
+ const expandRun = (run, depth, incomingParentIds) => {
11955
+ if (visiting.has(run.id))
11956
+ return { stages: [], tools: [], nodes: [], terminalIds: [] };
11957
+ const isRootRun = run.id === rootRunId;
11958
+ const memoizable = !isRootRun && Object.isFrozen(run) && isLeafRun(run);
11959
+ if (memoizable) {
11960
+ const known = leafExpansions.get(run);
11961
+ if (known !== undefined && known.depth === depth && sameIds(known.incomingParentIds, incomingParentIds)) {
11962
+ for (const [id, target] of known.targets)
11963
+ targets.set(id, target);
11964
+ return known.result;
11965
+ }
11966
+ }
11967
+ const runTargets = [];
11968
+ visiting.add(run.id);
11969
+ const items = localItems(run);
11970
+ const stages = [];
11971
+ const tools = [];
11972
+ const nodes = [];
11973
+ const stageById = new Map(run.stages.map((stage) => [stage.id, stage]));
11974
+ const boundaryExpansions = new Map;
11975
+ const validChildRunFor = (stage) => {
11976
+ const childRunId = authoritativeWorkflowChildRunId(stage);
11977
+ if (childRunId === undefined)
11978
+ return;
11979
+ const childRun = runById.get(childRunId);
11980
+ const runRoot = rootOwnerFor(run.id);
11981
+ 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) {
11982
+ return;
11983
+ }
11984
+ return childRun;
11985
+ };
11986
+ const resolvedParentIdsFor = (item) => {
11987
+ const parentIds = itemParents(item);
11988
+ if (parentIds.length === 0)
11989
+ return [...incomingParentIds];
11990
+ return parentIds.flatMap((parentId) => {
11991
+ const parentStage = stageById.get(parentId);
11992
+ const parentExpansion = parentStage === undefined ? undefined : boundaryExpansionFor(parentStage);
11993
+ return parentExpansion?.terminalIds.length ? [...parentExpansion.terminalIds] : [virtualNodeId(run.id, parentId, isRootRun)];
11994
+ });
11995
+ };
11996
+ const boundaryExpansionFor = (stage) => {
11997
+ const cached = boundaryExpansions.get(stage.id);
11998
+ if (cached !== undefined)
11999
+ return cached ?? undefined;
12000
+ const childRun = validChildRunFor(stage);
12001
+ if (childRun === undefined)
12002
+ return;
12003
+ boundaryExpansions.set(stage.id, null);
12004
+ expandedChildren.add(childRun.id);
12005
+ const stageItem = { kind: "stage", stage, sourceIndex: 0 };
12006
+ const childExpanded = expandRun(childRun, depth + 1, resolvedParentIdsFor(stageItem));
12007
+ if (childExpanded.stages.length === 0 || childExpanded.terminalIds.length === 0)
12008
+ return;
12009
+ boundaryExpansions.set(stage.id, childExpanded);
12010
+ return childExpanded;
12011
+ };
12012
+ for (const item of items) {
12013
+ const sourceId = itemId(item);
12014
+ const id = virtualNodeId(run.id, sourceId, isRootRun);
12015
+ const resolvedParentIds = resolvedParentIdsFor(item);
12016
+ if (item.kind === "tool") {
12017
+ const tool = {
12018
+ ...item.tool,
12019
+ id,
12020
+ parentIds: Object.freeze(resolvedParentIds),
12021
+ runId: run.id,
12022
+ runName: run.name,
12023
+ depth
12024
+ };
12025
+ const projectionTarget = {
12026
+ runId: run.id,
12027
+ stageId: item.tool.id,
12028
+ runName: run.name,
12029
+ depth
12030
+ };
12031
+ const projection = {
12032
+ id,
12033
+ name: item.tool.name,
12034
+ status: projectedToolStatus(item.tool),
12035
+ parentIds: Object.freeze(resolvedParentIds),
12036
+ executionOrder: item.tool.executionOrder,
12037
+ nodeKind: "tool",
12038
+ toolStatus: item.tool.status,
12039
+ startedAt: item.tool.startedAt,
12040
+ endedAt: item.tool.endedAt,
12041
+ result: item.tool.resultSummary,
12042
+ error: item.tool.error,
12043
+ toolEvents: [],
12044
+ attachable: false,
12045
+ workflowGraphTarget: projectionTarget
12046
+ };
12047
+ targets.set(id, projectionTarget);
12048
+ runTargets.push([id, projectionTarget]);
12049
+ tools.push(tool);
12050
+ stages.push(projection);
12051
+ nodes.push({ kind: "tool", tool });
12052
+ continue;
12053
+ }
12054
+ const childExpanded = boundaryExpansionFor(item.stage);
12055
+ if (childExpanded !== undefined) {
12056
+ stages.push(...childExpanded.stages);
12057
+ tools.push(...childExpanded.tools);
12058
+ nodes.push(...childExpanded.nodes);
12059
+ continue;
12060
+ }
12061
+ const target = {
12062
+ runId: run.id,
12063
+ stageId: item.stage.id,
12064
+ runName: run.name,
12065
+ depth
12066
+ };
12067
+ targets.set(id, target);
12068
+ runTargets.push([id, target]);
12069
+ const stage = {
12070
+ ...item.stage,
12071
+ id,
12072
+ parentIds: Object.freeze(resolvedParentIds),
12073
+ workflowGraphTarget: target
12074
+ };
12075
+ stages.push(stage);
12076
+ nodes.push({ kind: "stage", stage });
12077
+ }
12078
+ const terminalIds = localTerminalIds(items).flatMap((sourceId) => {
12079
+ const stage = stageById.get(sourceId);
12080
+ const replacement = stage === undefined ? undefined : boundaryExpansionFor(stage);
12081
+ return replacement?.terminalIds.length ? [...replacement.terminalIds] : [virtualNodeId(run.id, sourceId, isRootRun)];
12082
+ });
12083
+ visiting.delete(run.id);
12084
+ const result = { stages, tools, nodes, terminalIds };
12085
+ if (memoizable)
12086
+ leafExpansions.set(run, { depth, incomingParentIds: [...incomingParentIds], result, targets: runTargets });
12087
+ return result;
12088
+ };
12089
+ const expanded = expandRun(root, 0, []);
12090
+ const stages = expanded.stages.filter((stage) => stage.nodeKind !== "tool");
12091
+ expandedStageLists.add(stages);
12092
+ return {
12093
+ stages,
12094
+ renderStages: expanded.stages,
12095
+ tools: expanded.tools,
12096
+ nodes: expanded.nodes,
12097
+ targets
12098
+ };
12099
+ }
12100
+ function sameIds(left, right) {
12101
+ if (left.length !== right.length)
12102
+ return false;
12103
+ for (let index = 0;index < left.length; index++) {
12104
+ if (left[index] !== right[index])
12105
+ return false;
12106
+ }
12107
+ return true;
12108
+ }
12109
+ var MissingWorkflowToolNodesError, leafExpansions, snapshotExpansions, settledStageCounts, expandedStageLists, chainExpansions;
11623
12110
  var init_expanded_workflow_graph = __esm(() => {
11624
12111
  init_graph_store_snapshot();
11625
12112
  init_workflow_run_ownership();
12113
+ MissingWorkflowToolNodesError = class MissingWorkflowToolNodesError extends Error {
12114
+ runId;
12115
+ constructor(runId) {
12116
+ super(`atomic-workflows: run ${runId} has no tool node collection`);
12117
+ this.name = "MissingWorkflowToolNodesError";
12118
+ this.runId = runId;
12119
+ }
12120
+ };
11626
12121
  leafExpansions = new WeakMap;
11627
12122
  snapshotExpansions = new WeakMap;
11628
12123
  settledStageCounts = new WeakMap;
@@ -11630,6 +12125,16 @@ var init_expanded_workflow_graph = __esm(() => {
11630
12125
  chainExpansions = new WeakMap;
11631
12126
  });
11632
12127
 
12128
+ // dist/builtin/workflows/src/shared/inspection-store-snapshot.ts
12129
+ var prepareInspectionSnapshotKey, expandedRuns, inspectionExpanders;
12130
+ var init_inspection_store_snapshot = __esm(() => {
12131
+ init_expanded_workflow_graph();
12132
+ init_workflow_run_ownership();
12133
+ prepareInspectionSnapshotKey = Symbol("workflow.prepare-inspection-snapshot");
12134
+ expandedRuns = new WeakMap;
12135
+ inspectionExpanders = new WeakMap;
12136
+ });
12137
+
11633
12138
  // dist/builtin/workflows/src/shared/workflow-activity.ts
11634
12139
  function workflowActivityNodeKey(runId, nodeId) {
11635
12140
  return `${runId}:${nodeId}`;
@@ -12046,10 +12551,67 @@ function createStoreContext(state = createStoreState()) {
12046
12551
  let cachedGraphVersion = -1;
12047
12552
  let cachedGraphSnapshot;
12048
12553
  const graphBuilder = new GraphStoreSnapshotBuilder;
12554
+ let inspectionBuilder;
12555
+ let inspectionVersion = -1;
12556
+ let inspectionView;
12557
+ let inspectionTargets = new WeakMap;
12049
12558
  const observation = new WorkflowObservationRuntime({ all: () => state.runs, find: findRun, position: (runId) => runPosition(state, runId) }, bumpAndNotify);
12050
12559
  function snapshot() {
12051
12560
  return JSON.parse(JSON.stringify({ runs: state.runs, notices: state.notices, version: state.version }));
12052
12561
  }
12562
+ async function prepareInspectionSnapshot() {
12563
+ let prepared = 0;
12564
+ for (;; ) {
12565
+ inspectionBuilder ??= new GraphStoreSnapshotBuilder({ fullPayloads: true });
12566
+ const builder = inspectionBuilder;
12567
+ const unhandled = state.runs.filter((run) => !builder.hasRun(run) || !graphBuilder.hasRun(run));
12568
+ if (unhandled.length === 0)
12569
+ return;
12570
+ for (const run of unhandled) {
12571
+ if (builder.hasRun(run) && graphBuilder.hasRun(run))
12572
+ continue;
12573
+ if (prepared >= 16) {
12574
+ prepared = 0;
12575
+ await new Promise((resolve) => setImmediate(resolve));
12576
+ if (inspectionBuilder !== builder)
12577
+ break;
12578
+ }
12579
+ if (findRun(run.id) === run) {
12580
+ if (!builder.hasRun(run))
12581
+ builder.buildRun(run);
12582
+ if (!graphBuilder.hasRun(run))
12583
+ graphBuilder.buildRun(run);
12584
+ prepared++;
12585
+ }
12586
+ }
12587
+ }
12588
+ }
12589
+ function inspectionSnapshot(runId) {
12590
+ if (inspectionView !== undefined && inspectionVersion === state.version)
12591
+ return inspectionView;
12592
+ inspectionBuilder ??= new GraphStoreSnapshotBuilder({ fullPayloads: true });
12593
+ const builder = inspectionBuilder;
12594
+ if (runId === undefined) {
12595
+ inspectionView = builder.build(state.runs, state.notices, state.version);
12596
+ inspectionVersion = state.version;
12597
+ return inspectionView;
12598
+ }
12599
+ const compact = graphSnapshot();
12600
+ let targets = inspectionTargets.get(compact);
12601
+ const known = targets?.get(runId);
12602
+ if (known !== undefined)
12603
+ return known;
12604
+ const graph = expandWorkflowGraph(compact, runId);
12605
+ const fullRunIds = new Set([runId, ...Array.from(graph.targets.values(), (target) => target.runId)]);
12606
+ const runs = compact.runs.map((run) => fullRunIds.has(run.id) ? builder.buildRun(findRun(run.id)) : run);
12607
+ const view = builder.publish(runs, compact.notices, state.version);
12608
+ if (targets === undefined) {
12609
+ targets = new Map;
12610
+ inspectionTargets.set(compact, targets);
12611
+ }
12612
+ targets.set(runId, view);
12613
+ return view;
12614
+ }
12053
12615
  function graphSnapshot() {
12054
12616
  if (cachedGraphSnapshot === undefined || cachedGraphVersion !== state.version) {
12055
12617
  cachedGraphSnapshot = graphBuilder.build(state.runs, state.notices, state.version);
@@ -12068,6 +12630,7 @@ function createStoreContext(state = createStoreState()) {
12068
12630
  let batchedChanges = [];
12069
12631
  function notify(change) {
12070
12632
  graphBuilder.markChanged(change);
12633
+ inspectionBuilder?.markChanged(change);
12071
12634
  if (batchDepth > 0) {
12072
12635
  batchedNotification = true;
12073
12636
  if (change === undefined)
@@ -12134,11 +12697,22 @@ function createStoreContext(state = createStoreState()) {
12134
12697
  if (removed === undefined)
12135
12698
  return;
12136
12699
  state.runPositions.delete(removed.id);
12700
+ graphBuilder.removeRun(removed.id);
12701
+ inspectionBuilder?.removeRun(removed.id);
12702
+ inspectionView = undefined;
12703
+ inspectionTargets = new WeakMap;
12137
12704
  unindexChildRun(state, removed.id);
12138
12705
  for (let index = position;index < state.runs.length; index++)
12139
12706
  state.runPositions.set(state.runs[index].id, index);
12140
12707
  }
12141
12708
  function clearRuns() {
12709
+ graphBuilder.clear();
12710
+ cachedGraphSnapshot = undefined;
12711
+ cachedGraphVersion = -1;
12712
+ inspectionBuilder = undefined;
12713
+ inspectionTargets = new WeakMap;
12714
+ inspectionView = undefined;
12715
+ inspectionVersion = -1;
12142
12716
  state.runs.length = 0;
12143
12717
  state.runPositions.clear();
12144
12718
  state.childRunIds.clear();
@@ -12206,6 +12780,8 @@ function createStoreContext(state = createStoreState()) {
12206
12780
  observation,
12207
12781
  snapshot,
12208
12782
  graphSnapshot,
12783
+ inspectionSnapshot,
12784
+ prepareInspectionSnapshot,
12209
12785
  graphRun,
12210
12786
  notify,
12211
12787
  batch,
@@ -12228,6 +12804,7 @@ function createStoreContext(state = createStoreState()) {
12228
12804
  }
12229
12805
  var TERMINAL_STATUSES;
12230
12806
  var init_store_internal = __esm(() => {
12807
+ init_expanded_workflow_graph();
12231
12808
  init_graph_store_snapshot();
12232
12809
  init_workflow_observation_runtime();
12233
12810
  init_workflow_run_ownership();
@@ -13661,6 +14238,9 @@ function createRunStoreMethods(context) {
13661
14238
  graphSnapshot() {
13662
14239
  return context.graphSnapshot();
13663
14240
  },
14241
+ inspectionSnapshot(runId) {
14242
+ return context.inspectionSnapshot(runId);
14243
+ },
13664
14244
  graphRun(runId) {
13665
14245
  return context.graphRun(runId);
13666
14246
  },
@@ -14155,6 +14735,7 @@ function createStore() {
14155
14735
  context.backend = getDurableBackendProcessOwner().injectedBackend;
14156
14736
  const created = {
14157
14737
  [workflowObservationRuntimeKey]: context.observation,
14738
+ [prepareInspectionSnapshotKey]: context.prepareInspectionSnapshot,
14158
14739
  [workflowStoreBackendOverride]: context.backend,
14159
14740
  get [workflowStoreBackend]() {
14160
14741
  return context.backend;
@@ -14180,6 +14761,7 @@ var SESSION_KEY = "workflows:store:v1", singleton, store;
14180
14761
  var init_store_factory = __esm(() => {
14181
14762
  init_backend_process_owner();
14182
14763
  init_store_backend();
14764
+ init_inspection_store_snapshot();
14183
14765
  init_session_scoped_singleton();
14184
14766
  init_store_internal();
14185
14767
  init_store_pending_stage_delivery_methods();
@@ -28733,6 +29315,12 @@ class SqlPoolQueue {
28733
29315
  await ensureStorageSchema2(tx, dialect, { ledger, domain: "pool-outbox", revision: 1 }, () => tx.exec(schema.outbox));
28734
29316
  pool.outboxPending = await tx.get(`SELECT 1 AS held FROM ${pool.outbox} LIMIT 1`) !== undefined;
28735
29317
  }
29318
+ if (!pool.rowLocks) {
29319
+ await ensureStorageSchema2(tx, dialect, { ledger, domain: "pool-ready", revision: POOL_READY_SCHEMA_REVISION }, async () => {
29320
+ for (const statement of schema.ready)
29321
+ await tx.exec(statement);
29322
+ });
29323
+ }
28736
29324
  await ensureStorageSchema2(tx, dialect, { ledger, domain: "pool-ship", revision: 1 }, () => tx.exec(schema.ship));
28737
29325
  });
28738
29326
  return pool;
@@ -28810,7 +29398,19 @@ class SqlPoolQueue {
28810
29398
  generation ${int} NOT NULL, operation TEXT NOT NULL, request TEXT NOT NULL,
28811
29399
  event_key TEXT NOT NULL, payload TEXT NOT NULL, last_seq ${int},
28812
29400
  PRIMARY KEY(work, generation, operation)${dialect.rowOrderColumn}
28813
- )`
29401
+ )`,
29402
+ ready: [
29403
+ `CREATE TABLE IF NOT EXISTS ${this.roots}_ready(
29404
+ root TEXT PRIMARY KEY REFERENCES ${this.roots}(root) ON DELETE CASCADE,
29405
+ revision ${int} NOT NULL DEFAULT 0
29406
+ )`,
29407
+ ...["INSERT", "UPDATE"].map((event) => `CREATE TRIGGER IF NOT EXISTS ${this.roots}_ready_${event.toLowerCase()} AFTER ${event} ON ${this.work}
29408
+ WHEN NEW.state = 'ready'
29409
+ BEGIN
29410
+ INSERT INTO ${this.roots}_ready(root, revision) VALUES (NEW.root, 1)
29411
+ ON CONFLICT(root) DO UPDATE SET revision = revision + 1;
29412
+ END`)
29413
+ ]
28814
29414
  };
28815
29415
  }
28816
29416
  async openedWithoutLock(schema) {
@@ -28820,7 +29420,8 @@ class SqlPoolQueue {
28820
29420
  ...schema.tables,
28821
29421
  schema.chunks,
28822
29422
  schema.ship,
28823
- ...this.remote ? [schema.outbox] : []
29423
+ ...this.remote ? [schema.outbox] : [],
29424
+ ...this.rowLocks ? [] : schema.ready
28824
29425
  ];
28825
29426
  const columns = [
28826
29427
  [this.work, "inputs_chunks"],
@@ -29066,6 +29667,8 @@ class SqlPoolQueue {
29066
29667
  await tx.run(`INSERT INTO ${this.roots}_control(root, state, revision) VALUES (?, ?, 1)
29067
29668
  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);
29068
29669
  const row = await tx.get(`SELECT revision FROM ${this.roots}_control WHERE root = ?`, lease.runId);
29670
+ if (state === "running")
29671
+ await this.notifyReady(tx, lease.runId);
29069
29672
  return { state, revision: Number(row.revision) };
29070
29673
  });
29071
29674
  }
@@ -29352,13 +29955,24 @@ class SqlPoolQueue {
29352
29955
  await this.writeInputChunks(tx, previous.id, stored.chunks);
29353
29956
  return { ...previous, descriptor: stored.descriptor, fingerprint, inputs_chunks: stored.chunks.length };
29354
29957
  }
29355
- async claim(lease, worker, definitions, durationMs, placement) {
29958
+ async claim(lease, worker, definitions, durationMs, placement, outboxBlocked) {
29356
29959
  positive(durationMs);
29357
29960
  lease = snapshotLease(lease);
29358
29961
  const compatibleDefinitions = definitions.flatMap((d) => [d.definition, d.digest]);
29359
29962
  validateText("holderId", worker);
29360
29963
  const compatible = compatibleClause(this.dialect, definitions.length);
29361
29964
  if (this.remote) {
29965
+ try {
29966
+ while (this.outboxPending || this.draining !== undefined)
29967
+ await this.drainOutbox(lease);
29968
+ } catch (error) {
29969
+ if (error instanceof StaleLeaseError) {
29970
+ await this.remote.fresh(lease);
29971
+ throw error;
29972
+ }
29973
+ outboxBlocked?.(error);
29974
+ return;
29975
+ }
29362
29976
  await this.remote.fresh(lease);
29363
29977
  try {
29364
29978
  while (this.outboxPending || this.draining !== undefined)
@@ -29366,6 +29980,7 @@ class SqlPoolQueue {
29366
29980
  } catch (error) {
29367
29981
  if (error instanceof StaleLeaseError)
29368
29982
  throw error;
29983
+ outboxBlocked?.(error);
29369
29984
  return;
29370
29985
  }
29371
29986
  }
@@ -29448,6 +30063,31 @@ class SqlPoolQueue {
29448
30063
  ...row.workspace === null ? {} : { workspace: JSON.parse(String(row.workspace)) }
29449
30064
  }));
29450
30065
  }
30066
+ async acceptsClaim(lease, host) {
30067
+ lease = snapshotLease(lease);
30068
+ const requested = { ...host };
30069
+ await this.remote?.fresh(lease);
30070
+ return this.storage.read(async (read) => {
30071
+ 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))`);
30072
+ const row = await read.get(`SELECT l.*, r.status, p.timeout, ${this.now} AS now,
30073
+ (SELECT state FROM ${this.roots}_control WHERE root = l.run_id) AS control,
30074
+ ${available} AS host_available
30075
+ FROM ${this.journal.leases} l JOIN ${this.journal.runs} r ON r.run_id = l.run_id
30076
+ LEFT JOIN ${this.roots} p ON p.root = l.run_id WHERE l.run_id = ?`, requested.id, requested.providerId ?? null, lease.runId);
30077
+ const { status } = this.authorityOf(row, lease);
30078
+ if (status !== "running" || row.control !== null && row.control !== "running")
30079
+ return "control";
30080
+ return Number(row.host_available) === 1 ? "accepted" : "drain";
30081
+ });
30082
+ }
30083
+ async readyMark(root) {
30084
+ const readiness = this.rowLocks ? "bit_xor(hash_record_extended(ROW(xmin, ctid), 0))" : `(SELECT revision FROM ${this.roots}_ready WHERE root = ?)`;
30085
+ const row = await (this.storage.peek ?? this.storage.read)((executor) => executor.get(`SELECT COUNT(*) AS ready, MAX(ready_at) AS latest,
30086
+ ${readiness} AS readiness,
30087
+ (SELECT revision FROM ${this.roots}_control WHERE root = ?) AS revision
30088
+ FROM ${this.work} WHERE root = ? AND state = 'ready' AND ready_at <= (SELECT ${this.now})`, ...this.rowLocks ? [] : [root], root, root));
30089
+ return row === undefined || Number(row.ready) === 0 ? undefined : `${row.ready}:${row.latest}:${row.readiness ?? 0}:${row.revision ?? 0}`;
30090
+ }
29451
30091
  async failUnclaimed(lease, token) {
29452
30092
  lease = snapshotLease(lease);
29453
30093
  return this.transaction(async (tx) => {
@@ -30386,7 +31026,7 @@ function openSqlPoolQueue(journal, remote) {
30386
31026
  return Promise.reject(new Error("Worker pool requires a SQL run journal"));
30387
31027
  return SqlPoolQueue.open(storage, remote);
30388
31028
  }
30389
- 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";
31029
+ 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";
30390
31030
  var init_sql_pool_queue = __esm(() => {
30391
31031
  init_serializable();
30392
31032
  init_worker_pool_errors();
@@ -83403,29 +84043,164 @@ var UNATTRIBUTED_WRITE = "other";
83403
84043
  var init_pool_coordination_stats = () => {};
83404
84044
 
83405
84045
  // dist/builtin/workflows/src/workers/pool-wake-ups.ts
83406
- class IdleClaimPauses {
83407
- pauseMs;
83408
- waiting = new Set;
83409
- constructor(pauseMs) {
83410
- this.pauseMs = pauseMs;
84046
+ class IdleClaimBackoff {
84047
+ random;
84048
+ step = 0;
84049
+ carriedWake;
84050
+ constructor(random = Math.random) {
84051
+ this.random = random;
84052
+ }
84053
+ next() {
84054
+ const base = IDLE_CLAIM_FIRST_PAUSE_MS * 2 ** Math.min(this.step, 16);
84055
+ this.step++;
84056
+ return Math.min(IDLE_CLAIM_FALLBACK_MS, base * (1 + this.random()));
84057
+ }
84058
+ reset() {
84059
+ this.step = 0;
84060
+ }
84061
+ takeWake() {
84062
+ const carried = this.carriedWake;
84063
+ if (carried === undefined)
84064
+ return false;
84065
+ carried.signal?.removeEventListener("abort", carried.release);
84066
+ this.carriedWake = undefined;
84067
+ return true;
84068
+ }
84069
+ carryWake(signal, wake) {
84070
+ const release = () => {
84071
+ if (this.takeWake())
84072
+ wake();
84073
+ };
84074
+ this.carriedWake = { signal, release };
84075
+ signal?.addEventListener("abort", release, { once: true });
84076
+ if (signal?.aborted)
84077
+ release();
84078
+ }
84079
+ }
84080
+
84081
+ class IdleClaimTicket {
84082
+ woken = false;
84083
+ end;
84084
+ get pausing() {
84085
+ return this.end !== undefined;
84086
+ }
84087
+ wake() {
84088
+ this.woken = true;
84089
+ this.end?.();
83411
84090
  }
83412
- pause() {
84091
+ pause(ms, signal) {
84092
+ if (this.woken || signal?.aborted === true)
84093
+ return Promise.resolve();
83413
84094
  return new Promise((resolve) => {
83414
- const end = () => {
84095
+ const timer = setTimeout(() => this.end?.(), ms);
84096
+ const abort = () => this.end?.();
84097
+ signal?.addEventListener("abort", abort, { once: true });
84098
+ this.end = () => {
83415
84099
  clearTimeout(timer);
83416
- this.waiting.delete(end);
84100
+ signal?.removeEventListener("abort", abort);
84101
+ this.end = undefined;
83417
84102
  resolve();
83418
84103
  };
83419
- const timer = setTimeout(end, this.pauseMs);
83420
- this.waiting.add(end);
83421
84104
  });
83422
84105
  }
84106
+ }
84107
+
84108
+ class IdleClaimWaits {
84109
+ tickets = new Set;
84110
+ async claim(backoff, check, signal) {
84111
+ const ticket = new IdleClaimTicket;
84112
+ this.tickets.add(ticket);
84113
+ let carried = backoff.takeWake();
84114
+ const found = () => {
84115
+ backoff.reset();
84116
+ const passWake = ticket.woken || carried;
84117
+ carried = false;
84118
+ ticket.woken = false;
84119
+ if (this.tickets.delete(ticket) && passWake)
84120
+ this.wakeOne();
84121
+ };
84122
+ const abort = () => {
84123
+ if (this.tickets.delete(ticket) && (ticket.woken || carried))
84124
+ this.wakeOne();
84125
+ };
84126
+ signal?.addEventListener("abort", abort, { once: true });
84127
+ if (signal?.aborted)
84128
+ abort();
84129
+ try {
84130
+ const claimed = await check(found);
84131
+ if (claimed !== undefined) {
84132
+ found();
84133
+ return claimed;
84134
+ }
84135
+ if (!signal?.aborted)
84136
+ this.tickets.add(ticket);
84137
+ await ticket.pause(backoff.next(), signal);
84138
+ if (!signal?.aborted && (ticket.woken || carried))
84139
+ backoff.carryWake(signal, () => this.wakeOne());
84140
+ return;
84141
+ } catch (error) {
84142
+ if (this.tickets.delete(ticket) && (ticket.woken || carried))
84143
+ this.wakeOne();
84144
+ throw error;
84145
+ } finally {
84146
+ signal?.removeEventListener("abort", abort);
84147
+ this.tickets.delete(ticket);
84148
+ }
84149
+ }
84150
+ get pausing() {
84151
+ for (const ticket of this.tickets)
84152
+ if (ticket.pausing && !ticket.woken)
84153
+ return true;
84154
+ return false;
84155
+ }
83423
84156
  wake(woken, root) {
83424
84157
  if (woken === undefined)
83425
- for (const end of [...this.waiting])
83426
- end();
84158
+ this.wakeAll();
83427
84159
  else if (woken === root)
83428
- this.waiting.values().next().value?.();
84160
+ this.wakeOne();
84161
+ }
84162
+ wakeOne() {
84163
+ let checking;
84164
+ for (const ticket of this.tickets) {
84165
+ if (ticket.woken)
84166
+ continue;
84167
+ if (ticket.pausing) {
84168
+ ticket.wake();
84169
+ return;
84170
+ }
84171
+ checking ??= ticket;
84172
+ }
84173
+ checking?.wake();
84174
+ }
84175
+ wakeAll() {
84176
+ for (const ticket of [...this.tickets])
84177
+ ticket.wake();
84178
+ }
84179
+ }
84180
+
84181
+ class IdleReadyProbe {
84182
+ target;
84183
+ last;
84184
+ reading = false;
84185
+ constructor(target) {
84186
+ this.target = target;
84187
+ }
84188
+ async tick() {
84189
+ if (this.reading || !this.target.waits.pausing)
84190
+ return;
84191
+ this.reading = true;
84192
+ try {
84193
+ if (await this.target.notified().catch(() => false)) {
84194
+ this.last = undefined;
84195
+ return;
84196
+ }
84197
+ const mark = await this.target.mark().catch(() => this.last);
84198
+ if (mark !== undefined && mark !== this.last)
84199
+ this.target.waits.wakeOne();
84200
+ this.last = mark;
84201
+ } finally {
84202
+ this.reading = false;
84203
+ }
83429
84204
  }
83430
84205
  }
83431
84206
  function coordinatorWakeUps(target) {
@@ -83453,6 +84228,7 @@ function hostWakeUps(serves, poll, minIntervalMs, now = () => performance.now())
83453
84228
  poll();
83454
84229
  };
83455
84230
  }
84231
+ var IDLE_CLAIM_FIRST_PAUSE_MS = 25, IDLE_CLAIM_FALLBACK_MS = 2000, IDLE_READY_PROBE_MS = 250;
83456
84232
 
83457
84233
  // dist/builtin/workflows/src/workers/pooled-watch-trace.ts
83458
84234
  import { dirname as dirname21, join as join35, resolve as resolve17 } from "node:path";
@@ -83691,8 +84467,11 @@ class RestoreBackoff {
83691
84467
  this.policy = policy;
83692
84468
  }
83693
84469
  waiting(key) {
83694
- const failing = this.failing.get(key);
83695
- return failing !== undefined && this.now() < failing.until;
84470
+ return this.remaining(key) > 0;
84471
+ }
84472
+ remaining(key) {
84473
+ const until = this.failing.get(key)?.until;
84474
+ return until === undefined ? 0 : Math.max(0, until - this.now());
83696
84475
  }
83697
84476
  failed(key) {
83698
84477
  const failures = (this.failing.get(key)?.failures ?? 0) + 1;
@@ -84516,8 +85295,13 @@ class PoolCoordinator {
84516
85295
  statsTimer;
84517
85296
  committedControl;
84518
85297
  recoveryTimer;
85298
+ readyProbeTimer;
85299
+ claimRetryTimer;
85300
+ claimRetryAt = Number.POSITIVE_INFINITY;
84519
85301
  poolReady;
84520
- idlePauses = new IdleClaimPauses(SHARED_IDLE_CLAIM_MS);
85302
+ idleClaims = new IdleClaimWaits;
85303
+ claimsGated = false;
85304
+ lagGated = false;
84521
85305
  flushTimer;
84522
85306
  lastFlushAt = 0;
84523
85307
  batchSequence = 0;
@@ -84545,6 +85329,7 @@ class PoolCoordinator {
84545
85329
  starting;
84546
85330
  recovering;
84547
85331
  nextRecoveryAt = 0;
85332
+ hasPendingHandoff = false;
84548
85333
  cleanupFailure;
84549
85334
  held = new Set;
84550
85335
  unreaped = [];
@@ -84876,6 +85661,9 @@ class PoolCoordinator {
84876
85661
  if (this.committedControl !== undefined && control.revision <= this.committedControl.revision)
84877
85662
  return;
84878
85663
  this.committedControl = control;
85664
+ for (const slot of this.slots)
85665
+ slot.idle.reset();
85666
+ this.idleClaims.wakeAll();
84879
85667
  const message = { kind: "pool-control", control };
84880
85668
  for (const slot of this.slots)
84881
85669
  if (this.readyWorkers.has(slot.worker) && slot.child.connected)
@@ -84918,6 +85706,8 @@ class PoolCoordinator {
84918
85706
  }
84919
85707
  noteBudget(blocked) {
84920
85708
  this.budgetBlocked = blocked;
85709
+ if (!blocked)
85710
+ this.gateOpened();
84921
85711
  const shared = this.sharedPool;
84922
85712
  if (shared === undefined || this.satellite !== undefined || this.queue === undefined || this.lease === undefined)
84923
85713
  return;
@@ -84974,9 +85764,28 @@ class PoolCoordinator {
84974
85764
  }
84975
85765
  followBudget(blocked) {
84976
85766
  this.budgetBlocked = blocked;
85767
+ if (!blocked)
85768
+ this.gateOpened();
85769
+ }
85770
+ gateOpened() {
85771
+ this.lagGated = false;
85772
+ if (!this.claimsGated)
85773
+ return;
85774
+ this.claimsGated = false;
85775
+ this.idleClaims.wakeAll();
85776
+ }
85777
+ retireWaiting() {
85778
+ const options = this.options;
85779
+ if (options === undefined || this.waitingReserve.size <= Math.min(this.places.waiting, options.workers))
85780
+ return;
85781
+ this.idleClaims.wakeAll();
84977
85782
  }
84978
85783
  startRecovery() {
84979
85784
  const recover = () => {
85785
+ if (this.lagGated && !this.budgetBlocked && this.shipping?.lagging() !== true)
85786
+ this.gateOpened();
85787
+ if (this.hasPendingHandoff)
85788
+ this.nextRecoveryAt = 0;
84980
85789
  this.counters.enter("recovery");
84981
85790
  this.recoverExpired().catch(async (error) => {
84982
85791
  if (this.queue && isStaleLeaseError(error) && await this.rootRenewal(this.queue).catch(() => false))
@@ -84987,12 +85796,13 @@ class PoolCoordinator {
84987
85796
  });
84988
85797
  };
84989
85798
  this.recoveryTimer = setInterval(recover, RECOVERY_INTERVAL_MS).unref();
85799
+ this.startReadyProbe();
84990
85800
  if (this.options?.shared === undefined)
84991
85801
  return;
84992
85802
  this.poolReady = listenPoolReady(this.journal, coordinatorWakeUps({
84993
85803
  root: () => this.root,
84994
85804
  satellite: this.satellite !== undefined,
84995
- pauses: this.idlePauses,
85805
+ pauses: this.idleClaims,
84996
85806
  recovering: () => this.recovering,
84997
85807
  recover: () => {
84998
85808
  this.nextRecoveryAt = 0;
@@ -85000,6 +85810,22 @@ class PoolCoordinator {
85000
85810
  }
85001
85811
  }));
85002
85812
  }
85813
+ startReadyProbe() {
85814
+ const notifications = sqlPoolStorage(this.journal)?.notifications;
85815
+ const probe = new IdleReadyProbe({
85816
+ waits: this.idleClaims,
85817
+ notified: async () => this.poolReady !== undefined && notifications !== undefined && (await notifications.state()).status === "listening",
85818
+ mark: async () => {
85819
+ const queue = this.queue;
85820
+ const root = this.root;
85821
+ return queue === undefined || root === undefined || this.closed ? undefined : queue.readyMark(root);
85822
+ }
85823
+ });
85824
+ this.readyProbeTimer = setInterval(() => {
85825
+ this.counters.enter("ready-probe");
85826
+ probe.tick();
85827
+ }, IDLE_READY_PROBE_MS).unref();
85828
+ }
85003
85829
  async publishSharedConfig(sources) {
85004
85830
  const options = this.options;
85005
85831
  const shared = this.sharedPool;
@@ -85106,6 +85932,7 @@ class PoolCoordinator {
85106
85932
  }
85107
85933
  releasePlace(slot) {
85108
85934
  this.places.release(slot);
85935
+ this.gateOpened();
85109
85936
  if (this.closed || this.satellite !== undefined)
85110
85937
  return;
85111
85938
  const reserve = this.waitingReserve;
@@ -85130,6 +85957,7 @@ class PoolCoordinator {
85130
85957
  async drain() {
85131
85958
  this.draining = true;
85132
85959
  this.placingSignal.abort();
85960
+ this.idleClaims.wakeAll();
85133
85961
  while (!this.closed && [...this.slots].some(holding))
85134
85962
  await delay5(RECOVERY_INTERVAL_MS);
85135
85963
  this.closing ??= this.close();
@@ -85300,6 +86128,8 @@ class PoolCoordinator {
85300
86128
  });
85301
86129
  if (!this.attemptBase.has(work.id))
85302
86130
  this.attemptBase.set(work.id, work.state === "ready" || work.state === "leased" && work.epoch < lease.epoch ? work.generation : 0);
86131
+ if (work.state === "ready")
86132
+ this.idleClaims.wakeOne();
85303
86133
  const result = await this.queue.result(this.root, work.id);
85304
86134
  return { work, ...result === undefined ? {} : { result } };
85305
86135
  }
@@ -85855,6 +86685,7 @@ class PoolCoordinator {
85855
86685
  deliveries: new Map,
85856
86686
  runs: new Set,
85857
86687
  stageCommands: new Map,
86688
+ idle: new IdleClaimBackoff,
85858
86689
  exited: new AbortController
85859
86690
  };
85860
86691
  this.slots.add(slot);
@@ -85917,6 +86748,8 @@ class PoolCoordinator {
85917
86748
  this.awaiting.delete(worker);
85918
86749
  this.slots.delete(slot);
85919
86750
  this.places.end(slot);
86751
+ this.gateOpened();
86752
+ this.retireWaiting();
85920
86753
  this.endStageWatches((watch) => watch.slot === slot, "worker_exited");
85921
86754
  for (const settle of slot.stageCommands.values())
85922
86755
  settle(undefined);
@@ -86049,6 +86882,9 @@ class PoolCoordinator {
86049
86882
  const limits = this.rateLimits.current();
86050
86883
  if (limits.length > 0)
86051
86884
  child.send({ kind: "rate-limits", observations: limits }, replied);
86885
+ const control = this.committedControl;
86886
+ if (control !== undefined)
86887
+ child.send({ kind: "pool-control", control }, replied);
86052
86888
  this.readyWorkers.add(worker);
86053
86889
  clearTimeout(startup);
86054
86890
  resolve();
@@ -86087,6 +86923,8 @@ class PoolCoordinator {
86087
86923
  slot.work = undefined;
86088
86924
  slot.worktree = undefined;
86089
86925
  this.places.end(slot);
86926
+ this.gateOpened();
86927
+ this.retireWaiting();
86090
86928
  };
86091
86929
  if (fenced !== undefined)
86092
86930
  await this.shipping?.release(fenced);
@@ -86096,9 +86934,10 @@ class PoolCoordinator {
86096
86934
  const handoffs = this.handoffs(current);
86097
86935
  if (message.handoff === true && handoffs < MAX_CHILD_HANDOFFS)
86098
86936
  await leased(() => queue.releaseExited(lease, fenced, { delayMs: handoffDelayMs(handoffs) }));
86099
- else if (this.satellite !== undefined || this.attempts(current) < MAX_CHILD_ATTEMPTS)
86937
+ else if (this.satellite !== undefined || this.attempts(current) < MAX_CHILD_ATTEMPTS) {
86100
86938
  await leased(() => queue.releaseExited(lease, fenced));
86101
- else if (await leased(() => queue.failExited(lease, fenced))) {
86939
+ this.idleClaims.wakeOne();
86940
+ } else if (await leased(() => queue.failExited(lease, fenced))) {
86102
86941
  const fault = message.fault === undefined ? undefined : rehydrateError(message.fault);
86103
86942
  this.failWork(fenced, this.retryLimit(current, fault === undefined ? "refused-stale" : "pool-fault", fault));
86104
86943
  }
@@ -86135,34 +86974,42 @@ class PoolCoordinator {
86135
86974
  throw new Error("Worker already holds an attempt");
86136
86975
  if (this.retiresIdle(slot))
86137
86976
  return;
86138
- let claimed;
86139
- const lagging = this.shipping?.lagging() === true;
86140
- if (lagging)
86141
- this.shipping?.flushAll().catch(() => {});
86142
- if (!this.budgetBlocked && !this.draining && !lagging) {
86143
- if (!this.places.claim(slot))
86977
+ const claimed = await this.idleClaims.claim(slot.idle, async (found) => {
86978
+ if (this.draining)
86144
86979
  return;
86980
+ const shipping = this.shipping;
86981
+ const lagging = shipping?.lagging() === true;
86982
+ if (lagging) {
86983
+ this.lagGated = true;
86984
+ shipping?.flushAll().then(() => {
86985
+ if (!shipping.lagging())
86986
+ this.gateOpened();
86987
+ }).catch(() => {});
86988
+ }
86989
+ if (this.budgetBlocked || lagging || !this.places.claim(slot)) {
86990
+ this.claimsGated = true;
86991
+ return;
86992
+ }
86993
+ let taken;
86145
86994
  slot.claiming = true;
86146
86995
  try {
86147
- claimed = await leased(async () => {
86996
+ taken = await leased(async () => {
86148
86997
  await this.recoverExpired();
86149
86998
  slot.runs.clear();
86150
- return this.claimFor(queue, lease, worker, options.leaseMs, slot);
86999
+ return this.claimFor(queue, lease, worker, options.leaseMs, slot, found);
86151
87000
  });
86152
87001
  } finally {
86153
87002
  slot.claiming = false;
86154
87003
  slot.claimed = undefined;
86155
- if (claimed === undefined)
87004
+ if (taken === undefined) {
86156
87005
  this.places.end(slot);
87006
+ this.gateOpened();
87007
+ }
86157
87008
  }
86158
- }
86159
- if (this.closed)
87009
+ return taken;
87010
+ }, slot.exited.signal);
87011
+ if (this.closed || claimed === undefined)
86160
87012
  return;
86161
- if (claimed === undefined) {
86162
- if (options.shared !== undefined)
86163
- await this.idlePauses.pause();
86164
- return;
86165
- }
86166
87013
  slot.work = claimed.work;
86167
87014
  slot.worktree = claimed.worktree;
86168
87015
  await this.holdShipping(slot, claimed.work, options.leaseMs);
@@ -86178,8 +87025,13 @@ class PoolCoordinator {
86178
87025
  const held = slot.work;
86179
87026
  if (!held)
86180
87027
  throw new Error("Worker has no active attempt");
86181
- if (message.kind === "place")
86182
- return message.op === "release" ? this.releasePlace(slot) : this.places.reacquire(slot);
87028
+ if (message.kind === "place") {
87029
+ if (message.op === "release")
87030
+ return this.releasePlace(slot);
87031
+ const granted = await this.places.reacquire(slot);
87032
+ this.retireWaiting();
87033
+ return granted;
87034
+ }
86183
87035
  if (message.kind === "heartbeat") {
86184
87036
  const record = this.usageLedger.recording(lease, held, message.reports);
86185
87037
  const beat = await leased(() => queue.heartbeat(lease, held, options.leaseMs, record));
@@ -86295,6 +87147,8 @@ class PoolCoordinator {
86295
87147
  slot.work = undefined;
86296
87148
  slot.worktree = undefined;
86297
87149
  this.places.end(slot);
87150
+ this.gateOpened();
87151
+ this.retireWaiting();
86298
87152
  await this.sendResult(work.id);
86299
87153
  };
86300
87154
  const handled = this.counters.within(message.kind, () => lanes.run(WORKER_REQUEST_LANES[message.kind], answer));
@@ -86326,7 +87180,7 @@ class PoolCoordinator {
86326
87180
  });
86327
87181
  });
86328
87182
  }
86329
- async claimFor(queue, lease, worker, leaseMs, slot) {
87183
+ async claimFor(queue, lease, worker, leaseMs, slot, found) {
86330
87184
  const definitions = this.sources.map((source) => ({
86331
87185
  definition: `${source.path}#${source.exportName}`,
86332
87186
  digest: source.digest
@@ -86334,23 +87188,67 @@ class PoolCoordinator {
86334
87188
  const satellite = this.satellite;
86335
87189
  if (satellite === undefined) {
86336
87190
  const shared = this.options?.shared !== undefined;
86337
- const work = await queue.claim(lease, worker, definitions, leaseMs, shared ? { kind: "unbound" } : undefined);
87191
+ const work = await queue.claim(lease, worker, definitions, leaseMs, shared ? { kind: "unbound" } : undefined, (error) => {
87192
+ if (infrastructureFaultOf(error) === "storage_unavailable")
87193
+ throw error;
87194
+ slot.idle.reset();
87195
+ });
87196
+ if (work !== undefined)
87197
+ found();
86338
87198
  const blobs = this.remote === undefined ? undefined : this.durable?.snapshotBlobs;
86339
87199
  return work === undefined ? undefined : { work: await claimedWithStoredSnapshot(queue, work, blobs) };
86340
87200
  }
86341
87201
  const backoff = satellite.restoreBackoff ?? this.restoreBackoff;
86342
- 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)));
86343
- if (chosen === undefined || this.draining || this.closed)
87202
+ let chosen;
87203
+ let work;
87204
+ let refused;
87205
+ const attempted = new Map;
87206
+ for (let remaining = PLACEMENT_CANDIDATES;remaining > 0; remaining--) {
87207
+ const ready = await queue.readyCandidates(lease, definitions, PLACEMENT_CANDIDATES);
87208
+ const previous = refused;
87209
+ if (previous !== undefined && ready.some((candidate) => candidate.id === previous.id && candidate.generation === previous.generation)) {
87210
+ const admission = await queue.acceptsClaim(lease, {
87211
+ id: satellite.host,
87212
+ providerId: satellite.providerId
87213
+ });
87214
+ if (admission === "drain") {
87215
+ this.scheduleClaimRetry(SHARED_POLL_MS);
87216
+ this.scheduleCandidateRetries(satellite, backoff, ready);
87217
+ }
87218
+ if (admission !== "accepted")
87219
+ return;
87220
+ slot.idle.reset();
87221
+ }
87222
+ const candidates = ready.filter((candidate) => attempted.get(candidate.id) !== candidate.generation);
87223
+ chosen = await choosePlacement(candidates, (binding) => this.warmWorktree(satellite, binding, slot.exited.signal), (binding) => {
87224
+ if (satellite.restore === undefined)
87225
+ return false;
87226
+ const waitMs = backoff.remaining(workspaceAffinityKey(binding));
87227
+ if (waitMs > 0)
87228
+ this.scheduleClaimRetry(waitMs);
87229
+ return waitMs === 0;
87230
+ });
87231
+ if (this.draining || this.closed || slot.exited.signal.aborted)
87232
+ return;
87233
+ if (chosen === undefined) {
87234
+ this.scheduleCandidateRetries(satellite, backoff, candidates);
87235
+ return;
87236
+ }
87237
+ work = await queue.claim(lease, worker, definitions, leaseMs, {
87238
+ kind: "work",
87239
+ id: chosen.candidate.id,
87240
+ generation: chosen.candidate.generation,
87241
+ host: { id: satellite.host, providerId: satellite.providerId }
87242
+ });
87243
+ if (work !== undefined)
87244
+ break;
87245
+ refused = chosen.candidate;
87246
+ attempted.set(refused.id, refused.generation);
87247
+ }
87248
+ if (work === undefined || chosen === undefined)
86344
87249
  return;
87250
+ found();
86345
87251
  const { candidate, worktree } = chosen;
86346
- const work = await queue.claim(lease, worker, definitions, leaseMs, {
86347
- kind: "work",
86348
- id: candidate.id,
86349
- generation: candidate.generation,
86350
- host: { id: satellite.host, providerId: satellite.providerId }
86351
- });
86352
- if (work === undefined)
86353
- return;
86354
87252
  if (this.closed) {
86355
87253
  await this.releaseHeld(work);
86356
87254
  return;
@@ -86388,15 +87286,43 @@ class PoolCoordinator {
86388
87286
  await this.restoreFailed(satellite, backoff, binding, restored.error);
86389
87287
  return;
86390
87288
  }
87289
+ scheduleCandidateRetries(satellite, backoff, candidates) {
87290
+ if (satellite.restore === undefined)
87291
+ return;
87292
+ for (const candidate of candidates) {
87293
+ if (candidate.workspace === undefined)
87294
+ continue;
87295
+ const waitMs = backoff.remaining(workspaceAffinityKey(candidate.workspace));
87296
+ if (waitMs > 0)
87297
+ this.scheduleClaimRetry(waitMs);
87298
+ }
87299
+ }
87300
+ scheduleClaimRetry(waitMs) {
87301
+ if (this.closed)
87302
+ return;
87303
+ const at = performance.now() + waitMs;
87304
+ if (at >= this.claimRetryAt)
87305
+ return;
87306
+ clearTimeout(this.claimRetryTimer);
87307
+ this.claimRetryAt = at;
87308
+ this.claimRetryTimer = setTimeout(() => {
87309
+ this.claimRetryTimer = undefined;
87310
+ this.claimRetryAt = Number.POSITIVE_INFINITY;
87311
+ if (!this.closed)
87312
+ this.idleClaims.wakeOne();
87313
+ }, Math.ceil(waitMs)).unref();
87314
+ }
86391
87315
  async restoreFailed(satellite, backoff, binding, error) {
86392
87316
  const key = workspaceAffinityKey(binding);
86393
87317
  const waitMs = backoff.failed(key);
86394
87318
  await this.sharedPool.recordRestoreBackoff(satellite.host, key, waitMs, serializeError(error)).catch((recording) => satellite.placementFailed(recording));
87319
+ this.scheduleClaimRetry(backoff.remaining(key));
86395
87320
  }
86396
87321
  async restoreSucceeded(satellite, backoff, binding) {
86397
87322
  const key = workspaceAffinityKey(binding);
86398
87323
  if (!backoff.succeeded(key))
86399
87324
  return;
87325
+ this.idleClaims.wakeOne();
86400
87326
  await this.sharedPool.clearRestoreBackoff(satellite.host, key).catch((clearing) => satellite.placementFailed(clearing));
86401
87327
  }
86402
87328
  async warmWorktree(satellite, binding, workerExited) {
@@ -86500,6 +87426,7 @@ class PoolCoordinator {
86500
87426
  await this.admission?.reconcile();
86501
87427
  const expiredBefore = Date.now();
86502
87428
  const rows = await queue.inspect(root);
87429
+ this.hasPendingHandoff = rows.some((work) => work.state === "ready" && work.epoch === lease.epoch && this.handoffs(work) > 0);
86503
87430
  const expired = rows.filter((work) => work.state === "leased" && work.expiresAt < expiredBefore);
86504
87431
  if (expired.length > 0 && await queue.rootLease(lease, COORDINATOR_LEASE_MS) === "late") {
86505
87432
  this.rootRenewal(queue).catch(() => {});
@@ -86537,6 +87464,8 @@ class PoolCoordinator {
86537
87464
  await this.shipping?.release(work);
86538
87465
  }
86539
87466
  }
87467
+ if (expired.length > 0 || this.hasPendingHandoff)
87468
+ this.idleClaims.wakeOne();
86540
87469
  if (this.satellite === undefined && this.sharedPool !== undefined)
86541
87470
  await this.settleShared(queue, lease, this.sharedPool, rows);
86542
87471
  })().finally(() => {
@@ -86703,10 +87632,13 @@ class PoolCoordinator {
86703
87632
  }
86704
87633
  async close() {
86705
87634
  this.closed = true;
87635
+ this.idleClaims.wakeAll();
86706
87636
  this.closedSignal.abort();
86707
87637
  this.placingSignal.abort();
86708
87638
  clearInterval(this.ticker);
86709
87639
  clearInterval(this.recoveryTimer);
87640
+ clearInterval(this.readyProbeTimer);
87641
+ clearTimeout(this.claimRetryTimer);
86710
87642
  this.poolReady?.close();
86711
87643
  clearInterval(this.mirrorTimer);
86712
87644
  clearInterval(this.statsTimer);
@@ -86833,7 +87765,7 @@ function runPoolCoordinator() {
86833
87765
  function handoffDelayMs(handoffs) {
86834
87766
  return Math.random() * Math.min(HANDOFF_DELAY_MAX_MS, HANDOFF_DELAY_BASE_MS * 2 ** Math.min(handoffs, 16));
86835
87767
  }
86836
- 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;
87768
+ 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;
86837
87769
  var init_pool_coordinator = __esm(() => {
86838
87770
  init_internal();
86839
87771
  init_pool_remote_journal();
@@ -98689,6 +99621,57 @@ function forkPointRecords(checkpoints, rootRunId) {
98689
99621
  }
98690
99622
  return records;
98691
99623
  }
99624
+ function unfinishedForkTargetRecords(checkpoints, rootRunId, completed) {
99625
+ const all = checkpoints.map((event) => event.checkpoint);
99626
+ const reached = attemptReachedCheckpoints(all, rootRunId, { rootReach: true });
99627
+ const visible = reached === all ? undefined : new Set(reached);
99628
+ const boundaries = new Map;
99629
+ const finished = new Set;
99630
+ const first = new Map;
99631
+ const last = new Map;
99632
+ for (const { seq, checkpoint } of checkpoints) {
99633
+ if (checkpoint.kind !== "stage")
99634
+ continue;
99635
+ if (checkpoint.topology?.boundary !== undefined && !boundaries.has(checkpoint.replayKey))
99636
+ boundaries.set(checkpoint.replayKey, checkpoint.name);
99637
+ if (checkpoint.output !== undefined)
99638
+ finished.add(checkpoint.replayKey);
99639
+ if (checkpoint.topology?.occurrenceKey !== undefined || visible?.has(checkpoint) === false)
99640
+ continue;
99641
+ const key = JSON.stringify([checkpoint.replayKey, checkpointAttempt(checkpoint)]);
99642
+ if (!first.has(key))
99643
+ first.set(key, { seq, checkpoint });
99644
+ last.set(checkpoint.replayKey, checkpoint);
99645
+ }
99646
+ const enclosing = (replayKey) => [...boundaries.keys()].filter((boundary) => replayKey.startsWith(`${boundary}:`)).sort((a, b) => a.length - b.length).map((boundary) => boundaries.get(boundary));
99647
+ const taken = new Set(completed.map((record) => record.stagePath));
99648
+ const records = [];
99649
+ for (const [replayKey, checkpoint] of last) {
99650
+ const status = checkpoint.topology?.status;
99651
+ if (finished.has(replayKey) || status === undefined || !UNFINISHED_FORK_TARGET_STATUSES.has(status))
99652
+ continue;
99653
+ const base = [...enclosing(replayKey), checkpoint.name].join(STAGE_PATH_SEPARATOR);
99654
+ let occurrence = 0;
99655
+ let stagePath;
99656
+ do {
99657
+ occurrence++;
99658
+ stagePath = occurrence === 1 ? base : `${base}#${occurrence}`;
99659
+ } while (taken.has(stagePath));
99660
+ taken.add(stagePath);
99661
+ records.push({
99662
+ stagePath,
99663
+ replayKey,
99664
+ sessionId: stageSessionId(checkpoint),
99665
+ completedAt: checkpoint.completedAt,
99666
+ ...firstEvent(first.get(JSON.stringify([replayKey, checkpointAttempt(checkpoint)])))
99667
+ });
99668
+ }
99669
+ return records;
99670
+ }
99671
+ function forkTargetRecords(checkpoints, rootRunId) {
99672
+ const completed = forkPointRecords(checkpoints, rootRunId);
99673
+ return { completed, unfinished: unfinishedForkTargetRecords(checkpoints, rootRunId, completed) };
99674
+ }
98692
99675
  function firstEvent(event) {
98693
99676
  return { firstSeq: event.seq, firstTopology: event.checkpoint.topology };
98694
99677
  }
@@ -98977,15 +99960,17 @@ async function resolveForkDefinition(request, handle) {
98977
99960
  }
98978
99961
  }
98979
99962
  function selectForkEvents(source, request) {
98980
- const records = forkPointRecords(source.checkpoints, source.runId);
98981
- const target = records.find((record) => record.stagePath === request.fromStage);
98982
- if (request.fromStage !== undefined && target === undefined)
99963
+ const { completed: records, unfinished } = forkTargetRecords(source.checkpoints, source.runId);
99964
+ const target = records.find((record) => record.stagePath === request.fromStage) ?? unfinished.find((record) => record.stagePath === request.fromStage);
99965
+ if (request.fromStage !== undefined && (target === undefined || request.expectedStageId !== undefined && target.firstTopology?.stageId !== request.expectedStageId)) {
99966
+ const validTargets = [...records, ...unfinished];
98983
99967
  throw new ForkTargetNotFoundError({
98984
99968
  runId: source.runId,
98985
99969
  fromStage: request.fromStage,
98986
- validStagePaths: records.map((record) => record.stagePath),
98987
- totalValidStagePaths: records.length
99970
+ validStagePaths: validTargets.map((record) => record.stagePath),
99971
+ totalValidStagePaths: validTargets.length
98988
99972
  });
99973
+ }
98989
99974
  const cut = target?.firstSeq ?? Number.POSITIVE_INFINITY;
98990
99975
  const carryAll = request.carryMessages === "all";
98991
99976
  const prefix = source.checkpoints.filter((event) => event.seq < cut);
@@ -99522,7 +100507,7 @@ async function copySessions(source, sessions, ids, request, cleanup, claim) {
99522
100507
  throw new ForkCopyFailedError({ runId: source.runId, forkRunId: ids.forkRunId, phase: "sessions" }, { cause: error });
99523
100508
  }
99524
100509
  }
99525
- var STAGE_PATH_SEPARATOR = ".", LOCAL_ONLY_ADAPTERS, SOURCE_CLAIM_RENEW_MS;
100510
+ var STAGE_PATH_SEPARATOR = ".", LOCAL_ONLY_ADAPTERS, UNFINISHED_FORK_TARGET_STATUSES, SOURCE_CLAIM_RENEW_MS;
99526
100511
  var init_fork_run = __esm(() => {
99527
100512
  init_executor_child_helpers();
99528
100513
  init_executor_inputs();
@@ -99543,6 +100528,7 @@ var init_fork_run = __esm(() => {
99543
100528
  init_stage_topology();
99544
100529
  init_stage_topology_validation();
99545
100530
  LOCAL_ONLY_ADAPTERS = new Set(["memory", "node-sqlite", "jsonl"]);
100531
+ UNFINISHED_FORK_TARGET_STATUSES = new Set(["failed", "blocked", "paused", "suspended"]);
99546
100532
  SOURCE_CLAIM_RENEW_MS = FOREIGN_LIVE_WORKFLOW_WINDOW_MS / 4;
99547
100533
  });
99548
100534
 
@@ -112190,26 +113176,35 @@ async function runWorker(start) {
112190
113176
  prompts: () => prompts,
112191
113177
  inbox: () => remoteInbox
112192
113178
  });
113179
+ let controlChanged;
112193
113180
  const offerControl = (next) => void control.offer(next).catch((error) => {
112194
113181
  if (activeController)
112195
113182
  activeController.abort(error);
112196
113183
  else
112197
113184
  controlFailure ??= error;
112198
- });
113185
+ }).finally(() => controlChanged?.());
112199
113186
  receiveControl = offerControl;
112200
113187
  const observeControl = async () => control.offer(await request({ kind: "control" }));
113188
+ const controlPushed = start.shared === undefined || start.shared.routes;
112201
113189
  await request({ kind: "ready" });
112202
113190
  for (;; ) {
112203
113191
  if (controlFailure)
112204
113192
  throw controlFailure;
112205
113193
  let work;
112206
113194
  try {
112207
- await observeControl();
112208
- if (control.state !== "running") {
112209
- await delay7(25);
112210
- continue;
113195
+ if (controlPushed && control.state !== "running") {
113196
+ const waited = await new Promise((resolve) => {
113197
+ const timer = setTimeout(() => resolve(true), IDLE_CLAIM_FALLBACK_MS);
113198
+ controlChanged = () => {
113199
+ clearTimeout(timer);
113200
+ resolve(false);
113201
+ };
113202
+ });
113203
+ controlChanged = undefined;
113204
+ if (!waited)
113205
+ continue;
113206
+ await observeControl();
112211
113207
  }
112212
- await reader.catchUpWorkflow(start.root);
112213
113208
  work = await request({ kind: "claim" });
112214
113209
  } catch (error) {
112215
113210
  if (infrastructureFaultOf(error) !== "storage_unavailable")
@@ -112223,7 +113218,6 @@ async function runWorker(start) {
112223
113218
  if (!work) {
112224
113219
  if (replies.retired)
112225
113220
  break;
112226
- await delay7(25 + Math.random() * 25);
112227
113221
  continue;
112228
113222
  }
112229
113223
  const index = start.definitions.findIndex((source) => `${source.path}#${source.exportName}` === work.definition && source.digest === work.digest);