@tangle-network/agent-runtime 8.0.1 → 9.0.1

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 (85) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/{activation-8AdN-3r4.js → activation-BrBDs0Yj.js} +3 -3
  3. package/dist/{activation-8AdN-3r4.js.map → activation-BrBDs0Yj.js.map} +1 -1
  4. package/dist/{activation-xxvLF1-1.d.ts → activation-Cvw_7nrn.d.ts} +2 -2
  5. package/dist/agent.d.ts +3 -3
  6. package/dist/agent.js +2 -2
  7. package/dist/agent.js.map +1 -1
  8. package/dist/candidate-execution/index.js +2 -2
  9. package/dist/{continuation-CIyKnS1Q.js → continuation-DDPfLw2w.js} +2 -2
  10. package/dist/{continuation-CIyKnS1Q.js.map → continuation-DDPfLw2w.js.map} +1 -1
  11. package/dist/{coordination-manager-DAGPerJy.js → coordination-manager-DKmQGzBB.js} +9 -10
  12. package/dist/coordination-manager-DKmQGzBB.js.map +1 -0
  13. package/dist/{delegate-CoaNr0hO.js → delegate-eayHBLHB.js} +2 -2
  14. package/dist/{delegate-CoaNr0hO.js.map → delegate-eayHBLHB.js.map} +1 -1
  15. package/dist/durable.d.ts +33 -2
  16. package/dist/durable.js +75 -14
  17. package/dist/durable.js.map +1 -1
  18. package/dist/{graph-pFTeNZ-G.js → graph-Cdhyxi8E.js} +10 -10
  19. package/dist/graph-Cdhyxi8E.js.map +1 -0
  20. package/dist/{graph-registry-czAwYwNj.js → graph-registry-D3cY0BJU.js} +3 -3
  21. package/dist/{graph-registry-czAwYwNj.js.map → graph-registry-D3cY0BJU.js.map} +1 -1
  22. package/dist/{graph-registry-uTIyyy7A.js → graph-registry-DTeb6qhB.js} +1 -1
  23. package/dist/{improve-I43jex8v.js → improve-CnTEGkF6.js} +6 -6
  24. package/dist/{improve-I43jex8v.js.map → improve-CnTEGkF6.js.map} +1 -1
  25. package/dist/index.d.ts +5 -5
  26. package/dist/index.js +12 -12
  27. package/dist/intelligence.d.ts +4 -4
  28. package/dist/intelligence.js +6 -6
  29. package/dist/kernel.d.ts +2 -2
  30. package/dist/kernel.js +15 -15
  31. package/dist/{loop-runner-BGwhcn1p.d.ts → loop-runner-Bd9Ieh5w.d.ts} +2 -2
  32. package/dist/{loop-runner-BN4KozR0.js → loop-runner-CGt9nTw7.js} +3 -3
  33. package/dist/{loop-runner-BN4KozR0.js.map → loop-runner-CGt9nTw7.js.map} +1 -1
  34. package/dist/loop-runner-bin.d.ts +1 -1
  35. package/dist/loop-runner-bin.js +1 -1
  36. package/dist/mcp/bin.js +3 -3
  37. package/dist/mcp/index.d.ts +1 -1
  38. package/dist/mcp/index.js +6 -6
  39. package/dist/{prepare-BnF8nGIg.js → prepare-D7WwIddG.js} +2 -2
  40. package/dist/{prepare-BnF8nGIg.js.map → prepare-D7WwIddG.js.map} +1 -1
  41. package/dist/{profile-CD25rTJF.js → profile-BT0X-dm5.js} +2 -2
  42. package/dist/{profile-CD25rTJF.js.map → profile-BT0X-dm5.js.map} +1 -1
  43. package/dist/profiles.d.ts +1 -1
  44. package/dist/{provision-supervisor-DvzayGpe.js → provision-supervisor-B-ULubUf.js} +6 -6
  45. package/dist/{provision-supervisor-DvzayGpe.js.map → provision-supervisor-B-ULubUf.js.map} +1 -1
  46. package/dist/{run-cancellation-C5__aBKW.js → run-cancellation-DZn4OSl8.js} +2 -2
  47. package/dist/{run-cancellation-C5__aBKW.js.map → run-cancellation-DZn4OSl8.js.map} +1 -1
  48. package/dist/{run-state-CJAaxqfp.js → run-state-nbF5NNGy.js} +6 -6
  49. package/dist/{run-state-CJAaxqfp.js.map → run-state-nbF5NNGy.js.map} +1 -1
  50. package/dist/{runtime-CuwHe8_K.js → runtime-CPL2lhgf.js} +98 -30
  51. package/dist/runtime-CPL2lhgf.js.map +1 -0
  52. package/dist/{search-executor-DAjm-NlG.js → search-executor-2xqDTDNO.js} +3 -3
  53. package/dist/{search-executor-DAjm-NlG.js.map → search-executor-2xqDTDNO.js.map} +1 -1
  54. package/dist/{server-BUpNUn5D.js → server-DHZq2AG7.js} +3 -3
  55. package/dist/{server-BUpNUn5D.js.map → server-DHZq2AG7.js.map} +1 -1
  56. package/dist/{settle-record-CeBdBuxP.js → settle-record-B95oiypS.js} +3 -3
  57. package/dist/{settle-record-CeBdBuxP.js.map → settle-record-B95oiypS.js.map} +1 -1
  58. package/dist/{structural-rollout-CqxBKxKY.js → structural-rollout-BHNqBUV0.js} +8 -5
  59. package/dist/structural-rollout-BHNqBUV0.js.map +1 -0
  60. package/dist/{supervise-Cdqj_oe4.js → supervise-DkhIZyD_.js} +16 -16
  61. package/dist/supervise-DkhIZyD_.js.map +1 -0
  62. package/dist/{supervision-discovery-CW-ildZ-.js → supervision-discovery-DUpm_6nQ.js} +2 -2
  63. package/dist/{supervision-discovery-CW-ildZ-.js.map → supervision-discovery-DUpm_6nQ.js.map} +1 -1
  64. package/dist/{supervisor-D-eT-6Tu.js → supervisor-BhcXPxAk.js} +180 -95
  65. package/dist/supervisor-BhcXPxAk.js.map +1 -0
  66. package/dist/{supervisor-accounting-Ow6CChpB.js → supervisor-accounting-BB22j3hu.js} +46 -31
  67. package/dist/supervisor-accounting-BB22j3hu.js.map +1 -0
  68. package/dist/testing.d.ts +1 -1
  69. package/dist/testing.js +12 -12
  70. package/dist/{top-web-BuYMkJN4.js → top-web-DsFGyUlS.js} +5 -5
  71. package/dist/{top-web-BuYMkJN4.js.map → top-web-DsFGyUlS.js.map} +1 -1
  72. package/dist/tui/bin.js +3 -3
  73. package/dist/tui/index.d.ts +1 -1
  74. package/dist/tui/index.js +2 -2
  75. package/dist/{types-C_qbnw9N.d.ts → types-CwGD-823.d.ts} +43 -32
  76. package/dist/viewer/styles.css +29 -237
  77. package/dist/viewer/workspace-viewer.js +2 -2
  78. package/package.json +11 -11
  79. package/dist/coordination-manager-DAGPerJy.js.map +0 -1
  80. package/dist/graph-pFTeNZ-G.js.map +0 -1
  81. package/dist/runtime-CuwHe8_K.js.map +0 -1
  82. package/dist/structural-rollout-CqxBKxKY.js.map +0 -1
  83. package/dist/supervise-Cdqj_oe4.js.map +0 -1
  84. package/dist/supervisor-D-eT-6Tu.js.map +0 -1
  85. package/dist/supervisor-accounting-Ow6CChpB.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { $n as harnessTranscriptFromLines, $r as awaitAbortable, $t as ownedTreeRootSpawn, An as environmentGone, Bt as scopeRetainedOwnerSettled, Dr as knownExecutionBindingReceipt, Er as inheritRuntimeOwnedExecutorAttestation, Fn as mergeTraceEnv, Fr as recordRuntimeOwnedProviderModel, G as appendSpawnEvents, Gr as executableAgentProfileSnapshot, Hr as runtimeOwnedScopeOwnerRuntime, J as reenteredWorkers, Jt as bindScopeRetainedOwnerProvider, Kr as executableAgentSpecSnapshot, Kt as scopeRetainedOwnerCheckpointing, L as nestedScopeSeamKey, Lr as runtimeOwnedExecutorExecutionBinding, M as prepareScopeResume, Mn as workerTraceEnv, Mr as recordRuntimeOwnedProviderAttemptStart, Nn as workerTraceHeaders, Nr as recordRuntimeOwnedProviderDispatchNotStarted, Or as knownMaterializationReceipt, Pr as recordRuntimeOwnedProviderIdentityConflict, Qr as assertEventBinding, Qt as loadSpawnForest, Rr as runtimeOwnedExecutorMaterialization, Tr as finalizeRuntimeOwnedPendingExecutor, Ur as unknownExecutionBindingReceipt, Vr as runtimeOwnedScopeOwnerControl, Wr as unknownMaterializationReceipt, X as assertRecursiveReservationPolicy, Yn as HARNESS_TRANSCRIPT_SETTLE_TIMEOUT_MS, Zn as captureHarnessTranscript, Zr as RetainedRunProviderContractError, _n as reconnectRetainedRun, _t as waitForScopeChildren, ai as abortReason, an as encodeResultBlob, br as attestRuntimeOwnedExecutor, cn as executorObservation, cr as createActivityLog, dn as describeRetainedNativeStops, dr as isLiveNodeStatus, dt as releaseHeldEnvironments, ei as exactSession, er as harnessTranscriptUnavailable, fn as stopRetainedNativeExecution, ft as releaseRetainedEnvironments, gn as mintRetainedIdentity, gt as unconfirmedTeardowns, hn as assertRetainedRunReplayMaterial, ht as startScopeRecoveries, ii as RunCancellationReason, j as resolveWorkerSlots, jn as WORKER_TRACE_PROPAGATION, kr as newExecutionAttemptId, kt as finalizeScopeOwnerMaterialization, lr as describeToolArgs, mn as RetainedMaterializationTimeoutError, mt as settleManagerWork, n as terminalAccounting, ni as retainedSessionReplaced, nn as driverRuntime, nt as closeScopeAdmission, oi as linkAbort, on as SpawnEventIndex, pn as verifyWorkspaceMarker, pt as retryUnconfirmedTeardowns, q as appendTeardownConfirmation, r as createScope, ri as sameControlCoordinates, rn as nestedDriverTreeRoot, rt as hasRetriableTeardowns, si as runAbortable, t as isNonEmptySpend, ti as freezeControlRef, tn as attestNestedDriverTreeOwner, tt as closeRetainedSlots, ui as promptOptionsFromAgentTurnInput, un as observeModelRequest, ut as registerNestedTeardownScope, vn as recoverRetainedRun, vr as subscriptionUsageLimitSignal, xr as attestRuntimeOwnedPendingExecutor, yn as startRetainedRun, yr as attestRuntimeOwnedDeferredExecutor } from "./supervisor-accounting-Ow6CChpB.js";
1
+ import { $r as assertEventBinding, $t as loadSpawnForest, Ar as newExecutionAttemptId, Bt as scopeRetainedOwnerSettled, Dr as inheritRuntimeOwnedExecutorAttestation, Er as finalizeRuntimeOwnedPendingExecutor, Fr as recordRuntimeOwnedProviderIdentityConflict, G as appendSpawnEvents, Gr as unknownMaterializationReceipt, Hr as runtimeOwnedScopeOwnerControl, In as mergeTraceEnv, Ir as recordRuntimeOwnedProviderModel, J as reenteredWorkers, Jt as bindScopeRetainedOwnerProvider, Kr as executableAgentProfileSnapshot, Kt as scopeRetainedOwnerCheckpointing, L as nestedScopeSeamKey, M as prepareScopeResume, Mn as WORKER_TRACE_PROPAGATION, Nn as workerTraceEnv, Nr as recordRuntimeOwnedProviderAttemptStart, Or as knownExecutionBindingReceipt, Pn as workerTraceHeaders, Pr as recordRuntimeOwnedProviderDispatchNotStarted, Qn as captureHarnessTranscript, Qr as RetainedRunProviderContractError, Rr as runtimeOwnedExecutorExecutionBinding, Sr as attestRuntimeOwnedPendingExecutor, Ur as runtimeOwnedScopeOwnerRuntime, Wr as unknownExecutionBindingReceipt, X as assertRecursiveReservationPolicy, Xn as HARNESS_TRANSCRIPT_SETTLE_TIMEOUT_MS, Xt as scopeOwnerLiabilities, Yt as owners, _n as mintRetainedIdentity, _t as waitForScopeChildren, ai as RunCancellationReason, bn as startRetainedRun, br as attestRuntimeOwnedDeferredExecutor, ci as runAbortable, di as promptOptionsFromAgentTurnInput, dn as observeModelRequest, dt as releaseHeldEnvironments, ei as awaitAbortable, en as ownedTreeRootSpawn, er as harnessTranscriptFromLines, fn as describeRetainedNativeStops, fr as isLiveNodeStatus, ft as releaseRetainedEnvironments, gn as assertRetainedRunReplayMaterial, gt as unconfirmedTeardowns, hn as RetainedMaterializationTimeoutError, ht as startScopeRecoveries, ii as sameControlCoordinates, in as nestedDriverTreeRoot, j as resolveWorkerSlots, jn as environmentGone, kr as knownMaterializationReceipt, kt as finalizeScopeOwnerMaterialization, ln as executorObservation, lr as createActivityLog, mn as verifyWorkspaceMarker, mt as settleManagerWork, n as terminalAccounting, ni as freezeControlRef, nn as attestNestedDriverTreeOwner, nt as closeScopeAdmission, oi as abortReason, on as encodeResultBlob, pn as stopRetainedNativeExecution, pt as retryUnconfirmedTeardowns, q as appendTeardownConfirmation, qr as executableAgentSpecSnapshot, r as createScope, ri as retainedSessionReplaced, rn as driverRuntime, rt as hasRetriableTeardowns, si as linkAbort, sn as SpawnEventIndex, t as isNonEmptySpend, ti as exactSession, tr as harnessTranscriptUnavailable, tt as closeRetainedSlots, ur as describeToolArgs, ut as registerNestedTeardownScope, vn as reconnectRetainedRun, xr as attestRuntimeOwnedExecutor, yn as recoverRetainedRun, yr as subscriptionUsageLimitSignal, zr as runtimeOwnedExecutorMaterialization } from "./supervisor-accounting-BB22j3hu.js";
2
2
  import { f as RuntimeRunStateError, i as ConfigError, m as ValidationError$1, r as BackendTransportError, t as AgentEvalError } from "./errors-DG8yufqX.js";
3
3
  import { C as unreportedSpend, D as addResourceSpend, E as zeroTokenUsage, F as ROOT_DEADLINE_REASON, H as teardownSurfaces, I as armDeadlineTimer, S as unmeteredSpend, T as zeroSpend, _ as roundBoxMinutes, b as throwAbort, c as errorMessage, d as isAbortError, f as isAsyncIterable, g as randomUuid, h as randomSuffix, j as ACCEPTED_RESULT_GRACE_MS, m as promptCacheTokenClasses, n as addSpend, o as cloneTokenUsage, p as mapWithConcurrency, r as addTokenUsage, s as deleteBoxSafe, v as sleep, w as withTimeout, x as throwIfAborted, y as stringifySafe, z as isDeadlineAbortReason } from "./util-fcckrkKp.js";
4
4
  import { t as runTaskQueue } from "./task-queue-DbpZAp6C.js";
@@ -8,7 +8,7 @@ import { _ as agentHarness, a as concreteProfileModel, c as profileModelExecutio
8
8
  import { r as nativeSystemPrompt, t as assertSandboxProfileCompatibility } from "./sandbox-profile-compat-l-SLQnGb.js";
9
9
  import { l as sha256 } from "./jsonl-file-DsxVI0E_.js";
10
10
  import { V as hasControlCharacter } from "./workspace-streams-DA9R3j-p.js";
11
- import { i as checkVerdictOf, s as isFiniteNumber } from "./continuation-CIyKnS1Q.js";
11
+ import { i as checkVerdictOf, s as isFiniteNumber } from "./continuation-DDPfLw2w.js";
12
12
  import { a as writeAtomicDurableFile, s as fenceRunWrite } from "./durable-file-DstVeHcj.js";
13
13
  import { t as PROTOCOL_VERSION } from "./tool-server-DYwRbi0I.js";
14
14
  import { i as notifyRuntimeHookEvent } from "./runtime-hooks-CsW2pfFk.js";
@@ -6959,14 +6959,8 @@ function createInPlaceCliExecutor(options) {
6959
6959
  });
6960
6960
  const result = await running;
6961
6961
  const spent = {
6962
- iterations: 1,
6963
- tokens: {
6964
- input: 0,
6965
- output: 0
6966
- },
6967
- tokensKnown: false,
6968
- usd: 0,
6969
- ms: Date.now() - started
6962
+ ...unmeteredSpend(Date.now() - started),
6963
+ iterations: 1
6970
6964
  };
6971
6965
  const exit = result.harness;
6972
6966
  const failed = exit.exitCode !== 0 || exit.timedOut;
@@ -7145,7 +7139,7 @@ function createWorktreeCliExecutor(options) {
7145
7139
  },
7146
7140
  ...usage ? {} : { tokensKnown: false },
7147
7141
  usd: 0,
7148
- ...usage ? { usdKnown: false } : {},
7142
+ usdKnown: false,
7149
7143
  ms: Date.now() - started
7150
7144
  };
7151
7145
  artifact = {
@@ -7498,13 +7492,6 @@ async function captureBeforeDestroy(scope, target, signal) {
7498
7492
  if (capture.status === "captured") state.harnessTranscript = capture;
7499
7493
  }
7500
7494
  }
7501
- // src/runtime/environment-provider/provider-validation-error.ts
7502
- var ValidationError = class extends Error {
7503
- constructor(message, options) {
7504
- super(message, options);
7505
- this.name = "ValidationError";
7506
- }
7507
- };
7508
7495
  // src/runtime/environment-provider/provider-event-projection.ts
7509
7496
  function sandboxEventFromEnvironmentEvent(event) {
7510
7497
  const normalized = event.normalized;
@@ -7751,28 +7738,41 @@ function resultFromEvents(events, fallbackText) {
7751
7738
  events
7752
7739
  };
7753
7740
  }
7754
- /** Decode only the final assistant message, keeping the unmodified stream as evidence. */
7741
+ /** A non-JSON final message settles the fenced block ending it; trailing text keeps it refused. */
7742
+ function finalJsonValue(text) {
7743
+ if (text === void 0) return "";
7744
+ try {
7745
+ JSON.parse(text);
7746
+ return text;
7747
+ } catch {}
7748
+ return /```(?:json)?[ \t]*\r?\n((?:(?!```)[\s\S])*)```\s*$/i.exec(text)?.[1] ?? text;
7749
+ }
7750
+ /** Decode only the final assistant message, keeping the stream as evidence. A stream not wholly
7751
+ * read is refused, not left pending: no later read completes an ended turn's stream. */
7755
7752
  function jsonResultFromEvents(events) {
7756
- if (events.some((event) => event.type === "result" && event.data.eventStreamComplete === false)) throw new ValidationError("provider JSON output: complete native event observation is required");
7753
+ if (events.some((event) => event.type === "result" && event.data.eventStreamComplete === false)) return refusedJson("complete native event observation is required");
7757
7754
  const projected = events.map(sandboxEventFromEnvironmentEvent);
7758
7755
  const text = collectAgentFinalMessageText(projected) ?? (projected.some(isToolBearingEvent) ? void 0 : collectAgentResponseText(projected));
7759
7756
  try {
7760
- return { out: JSON.parse(text ?? "", (_key, value) => {
7757
+ return { out: JSON.parse(finalJsonValue(text), (_key, value) => {
7761
7758
  if (typeof value === "number" && !Number.isFinite(value)) throw new SyntaxError("JSON number is not finite");
7762
7759
  return value;
7763
7760
  }) };
7764
7761
  } catch (error) {
7765
7762
  if (!(error instanceof SyntaxError)) throw error;
7766
- return {
7767
- out: null,
7768
- outcome: {
7769
- success: false,
7770
- error: `provider JSON output: ${text === void 0 ? "missing final assistant message" : "invalid final assistant JSON"}; return only a JSON value after tool use`,
7771
- errorCode: "RUNTIME_OUTPUT_FORMAT_INVALID"
7772
- }
7773
- };
7763
+ return refusedJson(`${text === void 0 ? "missing final assistant message" : "invalid final assistant JSON"}; return only a JSON value after tool use`);
7774
7764
  }
7775
7765
  }
7766
+ function refusedJson(reason) {
7767
+ return {
7768
+ out: null,
7769
+ outcome: {
7770
+ success: false,
7771
+ error: `provider JSON output: ${reason}`,
7772
+ errorCode: "RUNTIME_OUTPUT_FORMAT_INVALID"
7773
+ }
7774
+ };
7775
+ }
7776
7776
  function textFromEnvironmentEvent(event) {
7777
7777
  if (event.normalized?.type === "message.part.updated") return typeof event.normalized.delta === "string" ? event.normalized.delta : "";
7778
7778
  const data = event.data;
@@ -8120,6 +8120,13 @@ var RetainedObservation = class {
8120
8120
  }
8121
8121
  }
8122
8122
  };
8123
+ // src/runtime/environment-provider/provider-validation-error.ts
8124
+ var ValidationError = class extends Error {
8125
+ constructor(message, options) {
8126
+ super(message, options);
8127
+ this.name = "ValidationError";
8128
+ }
8129
+ };
8123
8130
  // src/runtime/environment-provider/provider-turn-input.ts
8124
8131
  /**
8125
8132
  * Lower the seam's prompt options onto turn fields, through the one mapper this module already
@@ -14985,9 +14992,11 @@ var RunParkedError = class extends Error {
14985
14992
  }
14986
14993
  };
14987
14994
  const DEFAULT_PARK_AFTER_MS = 6e4;
14995
+ /** A seat reset nearer than this is slept through in place; requeueing costs more than it frees. */
14996
+ const SEAT_PARK_MIN_MS = 3e5;
14988
14997
  const parkingContext = new AsyncLocalStorage();
14989
14998
  const parkingDrains = /* @__PURE__ */ new WeakMap();
14990
- /** Drain committed child work through the existing manager ledger before testing root idleness. */
14999
+ /** Drain committed child work through the existing manager ledger before testing idleness. */
14991
15000
  function bindScopeParkingDrain(scope, drain, idle) {
14992
15001
  parkingDrains.set(scope, {
14993
15002
  drain,
@@ -14997,96 +15006,168 @@ function bindScopeParkingDrain(scope, drain, idle) {
14997
15006
  /** Validate at intake, before any execution or ownership acquisition. */
14998
15007
  function assertRunParking(policy, durable) {
14999
15008
  if (policy === void 0) return;
15000
- if (!durable) throw new ValidationError$1("supervise: parking requires runDir");
15009
+ if (!durable) throw new ValidationError$1("supervise: parking requires runDir or a SQL runContext");
15001
15010
  if (policy === null || typeof policy !== "object" || policy.afterMs !== void 0 && (!Number.isFinite(policy.afterMs) || policy.afterMs < 0)) throw new ValidationError$1("supervise: parking.afterMs must be a nonnegative finite number");
15002
15011
  }
15003
- /** Scope the handoff to one execution, preserving the original wake time on an early re-entry. */
15012
+ /** Whether this error is the current run's own park, which every scope of the run propagates. */
15013
+ function isRunParked(error, scope) {
15014
+ return error instanceof RunParkedError && (error.runId === scope.view.root || error.runId === parkingContext.getStore()?.runId);
15015
+ }
15016
+ /**
15017
+ * Scope the handoff to one execution, preserving the original wake time on an early re-entry.
15018
+ * The journal's `run-parked` event is the durable record; `parking.json` is its runDir projection.
15019
+ */
15004
15020
  async function withRunParking(policy, runDir, runId, journal, now, signal, run) {
15005
- if (policy === void 0 || runDir === void 0) return run();
15021
+ if (policy === void 0) return parkingContext.exit(run);
15006
15022
  const events = await journal.loadTree(runId) ?? [];
15007
15023
  const previous = [...events].reverse().find((event) => event.kind === "run-parked");
15008
15024
  const transition = [...events].reverse().find((event) => event.id === runId && (event.kind === "run-parked" || event.kind === "root-reentered" || event.kind === "reopened"));
15009
15025
  const current = transition?.kind === "run-parked" ? transition : void 0;
15010
15026
  if (current !== void 0 && Date.parse(current.wakeAt) > now() && !signal?.aborted) {
15011
- await writeParkingProjection(runDir, runId, current);
15027
+ if (runDir !== void 0) await writeParkingProjection(runDir, runId, current);
15012
15028
  throw new RunParkedError(runId, parkingRecordOf(current));
15013
15029
  }
15014
- if (previous !== void 0) await writeAtomicDurableFile(resolve(runDir, "parking.json"), JSON.stringify({
15015
- status: "resuming",
15016
- runId,
15017
- ...parkingRecordOf(previous),
15018
- resumedAt: new Date(now()).toISOString()
15019
- }));
15030
+ if (previous !== void 0 && runDir !== void 0) await writeParkingProjection(runDir, runId, previous, now());
15031
+ let park;
15032
+ const parked = new Promise((_, reject) => {
15033
+ park = reject;
15034
+ });
15035
+ parked.catch(() => void 0);
15020
15036
  return parkingContext.run({
15021
15037
  runDir,
15022
15038
  runId,
15023
15039
  journal,
15024
15040
  now,
15025
- afterMs: policy.afterMs ?? DEFAULT_PARK_AFTER_MS
15041
+ afterMs: policy.afterMs ?? DEFAULT_PARK_AFTER_MS,
15042
+ waits: /* @__PURE__ */ new Map(),
15043
+ parked,
15044
+ park,
15045
+ handingOff: false
15026
15046
  }, run);
15027
15047
  }
15048
+ /** Run the root execution so a park decided by any of the run's waits rejects it at once. */
15049
+ function raceRunParking(runId, scope, seal, run) {
15050
+ const context = parkingContext.getStore();
15051
+ if (context === void 0 || context.runId !== runId) return run();
15052
+ context.root = {
15053
+ scope,
15054
+ seal
15055
+ };
15056
+ const running = run();
15057
+ running.catch(() => void 0);
15058
+ return Promise.race([running, context.parked]);
15059
+ }
15028
15060
  /**
15029
- * Sleep through the existing wait path. A root with no live descendants may hand off after its
15030
- * idle threshold; children and roots with active work keep their normal wait. No timer survives
15031
- * the handoff, and no provider work is cancelled or terminal settlement written for parking.
15061
+ * Sleep through the existing wait path. The run may hand off once every live node is waiting
15062
+ * here: the root on its own wait, any node on a seat reset at least SEAT_PARK_MIN_MS away. A run
15063
+ * with other active work keeps its normal wait. No timer survives the handoff, and no provider
15064
+ * work is cancelled or terminal settlement written for parking.
15032
15065
  */
15033
15066
  async function sleepScopeWait(scope, ms, signal, reason) {
15034
15067
  if (ms <= 0 || signal.aborted) return;
15035
15068
  const context = parkingContext.getStore();
15036
- const onlyRootWait = () => context !== void 0 && scope.view.root === context.runId && parkingDrains.get(scope)?.idle() !== false && scope.workerCapacity.unconfirmed.length === 0 && !(scope.observeTree?.() ?? scope.view).nodes.some((node) => node.id !== context.runId && isLiveNodeStatus(node.status));
15037
- if (context === void 0 || scope.view.root !== context.runId || ms <= context.afterMs) return sleep(ms, signal, false);
15069
+ const node = scope.view.root;
15070
+ if (context === void 0 || node !== context.runId && reason !== "seat-wait") return sleep(ms, signal, false);
15071
+ const floor = reason === "seat-wait" ? Math.max(context.afterMs, SEAT_PARK_MIN_MS) : context.afterMs;
15038
15072
  const since = context.now();
15039
- const deadline = scope.budget.deadlineMs;
15040
- const wakeAt = Math.min(since + ms, deadline > 0 ? deadline : Number.POSITIVE_INFINITY);
15041
- if (wakeAt - since <= context.afterMs) return sleep(ms, signal, false);
15042
- let idleSince = onlyRootWait() ? since : void 0;
15043
- for (;;) {
15044
- const remaining = Math.max(0, wakeAt - context.now());
15045
- if (remaining <= context.afterMs) return sleep(remaining, signal, false);
15046
- const checkMs = context.afterMs || (idleSince === void 0 ? DEFAULT_PARK_AFTER_MS : 0);
15047
- await sleep(Math.min(checkMs, remaining), signal, false);
15048
- if (signal.aborted) return;
15049
- await parkingDrains.get(scope)?.drain();
15050
- if (!onlyRootWait()) {
15051
- idleSince = void 0;
15052
- continue;
15053
- }
15054
- if (idleSince === void 0) {
15055
- idleSince = context.now();
15056
- continue;
15057
- }
15058
- if (context.now() - idleSince < context.afterMs) continue;
15059
- const events = await context.journal.loadTree(context.runId) ?? [];
15060
- if (signal.aborted) return;
15061
- const ownerEvents = events.filter((event) => event.id === context.runId);
15062
- const input = [...ownerEvents].reverse().find((event) => event.kind === "execution-input");
15063
- const invocation = input === void 0 ? [] : ownerEvents.slice(ownerEvents.indexOf(input));
15064
- if (invocation.some((event) => event.kind === "execution-admitted") && !invocation.some((event) => event.kind === "execution-result" || event.kind === "execution-abandoned" && event.outcome === "stopped") || !onlyRootWait()) {
15065
- idleSince = void 0;
15066
- continue;
15073
+ const deadline = Math.min(deadlineOf(scope), context.root ? deadlineOf(context.root.scope) : Number.POSITIVE_INFINITY);
15074
+ const wakeAt = Math.min(since + ms, deadline);
15075
+ if (wakeAt - since <= floor) return sleep(ms, signal, false);
15076
+ context.waits.set(node, {
15077
+ scope,
15078
+ wakeAt,
15079
+ floor,
15080
+ reason: wakeAt === deadline && wakeAt < since + ms ? "deadline" : reason
15081
+ });
15082
+ try {
15083
+ let idleSince = runIdle(context) ? since : void 0;
15084
+ for (;;) {
15085
+ const remaining = Math.max(0, wakeAt - context.now());
15086
+ if (remaining <= floor) return await Promise.race([sleep(remaining, signal, false), context.parked]);
15087
+ const checkMs = context.afterMs || (idleSince === void 0 ? DEFAULT_PARK_AFTER_MS : 0);
15088
+ await Promise.race([sleep(Math.min(checkMs, remaining), signal, false), context.parked]);
15089
+ if (signal.aborted) return;
15090
+ for (const held of heldScopes(context)) await parkingDrains.get(held)?.drain();
15091
+ if (!runIdle(context)) {
15092
+ idleSince = void 0;
15093
+ continue;
15094
+ }
15095
+ if (idleSince === void 0) {
15096
+ idleSince = context.now();
15097
+ continue;
15098
+ }
15099
+ if (context.now() - idleSince < context.afterMs) continue;
15100
+ const events = await context.journal.loadTree(context.runId) ?? [];
15101
+ if (signal.aborted) return;
15102
+ if (await invocationUnresolved(context, events) || !runIdle(context)) {
15103
+ idleSince = void 0;
15104
+ continue;
15105
+ }
15106
+ const at = context.now();
15107
+ const waits = [...context.waits.values()];
15108
+ if (waits.some((wait) => wait.wakeAt - at <= wait.floor)) continue;
15109
+ await parkRun(context, waits, idleSince, events);
15067
15110
  }
15068
- const parking = {
15069
- reason: deadline > 0 && wakeAt === deadline ? "deadline" : reason,
15070
- since: new Date(idleSince).toISOString(),
15071
- wakeAt: new Date(wakeAt).toISOString()
15072
- };
15073
- closeScopeAdmission(scope);
15074
- await context.journal.appendEvent(context.runId, {
15075
- kind: "run-parked",
15076
- id: context.runId,
15077
- ...parking,
15078
- seq: events.filter((event) => event.kind === "run-parked").length,
15079
- at: new Date(context.now()).toISOString()
15080
- });
15081
- await writeParkingProjection(context.runDir, context.runId, parking);
15082
- throw new RunParkedError(context.runId, parking);
15111
+ } finally {
15112
+ context.waits.delete(node);
15113
+ }
15114
+ }
15115
+ async function parkRun(context, waits, idleSince, events) {
15116
+ if (context.handingOff) return context.parked;
15117
+ context.handingOff = true;
15118
+ const root = context.root;
15119
+ const earliest = waits.reduce((first, wait) => wait.wakeAt < first.wakeAt ? wait : first);
15120
+ const parking = {
15121
+ reason: earliest.reason,
15122
+ since: new Date(idleSince).toISOString(),
15123
+ wakeAt: new Date(earliest.wakeAt).toISOString()
15124
+ };
15125
+ for (const held of heldScopes(context)) closeScopeAdmission(held);
15126
+ await context.journal.appendEvent(context.runId, {
15127
+ kind: "run-parked",
15128
+ id: context.runId,
15129
+ ...parking,
15130
+ seq: events.filter((event) => event.kind === "run-parked").length,
15131
+ at: new Date(context.now()).toISOString()
15132
+ });
15133
+ if (context.runDir !== void 0) await writeParkingProjection(context.runDir, context.runId, parking);
15134
+ const error = new RunParkedError(context.runId, parking);
15135
+ if (waits.some((wait) => wait.scope !== root.scope)) root.seal(error);
15136
+ context.park(error);
15137
+ throw error;
15138
+ }
15139
+ function heldScopes(context) {
15140
+ const scopes = new Set([...context.waits.values()].map((wait) => wait.scope));
15141
+ if (context.root) scopes.add(context.root.scope);
15142
+ return [...scopes];
15143
+ }
15144
+ /** Every live node is in a parkable wait, and no scope holds open work or unconfirmed capacity. */
15145
+ function runIdle(context) {
15146
+ const root = context.root;
15147
+ if (root === void 0) return false;
15148
+ if (heldScopes(context).some((held) => parkingDrains.get(held)?.idle() === false || held.workerCapacity.unconfirmed.length > 0)) return false;
15149
+ return !(root.scope.observeTree?.() ?? root.scope.view).nodes.some((node) => node.id !== context.runId && isLiveNodeStatus(node.status) && !context.waits.has(node.id));
15150
+ }
15151
+ /** The owners' own receipts decide: an admitted invocation without its result may still compute. */
15152
+ async function invocationUnresolved(context, rootEvents) {
15153
+ for (const held of heldScopes(context)) {
15154
+ const rootId = owners.get(held)?.args.rootId;
15155
+ if (rootId === void 0) continue;
15156
+ const events = rootId === context.runId ? rootEvents : await context.journal.loadTree(rootId);
15157
+ if (scopeOwnerLiabilities(held, events ?? []).invocationUnsettled) return true;
15083
15158
  }
15159
+ return false;
15160
+ }
15161
+ function deadlineOf(scope) {
15162
+ const deadline = scope.budget.deadlineMs;
15163
+ return deadline > 0 ? deadline : Number.POSITIVE_INFINITY;
15084
15164
  }
15085
- async function writeParkingProjection(runDir, runId, parking) {
15165
+ async function writeParkingProjection(runDir, runId, parking, resumedAt) {
15086
15166
  await writeAtomicDurableFile(resolve(runDir, "parking.json"), JSON.stringify({
15087
- status: "parked",
15167
+ status: resumedAt === void 0 ? "parked" : "resuming",
15088
15168
  runId,
15089
- ...parkingRecordOf(parking)
15169
+ ...parkingRecordOf(parking),
15170
+ ...resumedAt === void 0 ? {} : { resumedAt: new Date(resumedAt).toISOString() }
15090
15171
  }));
15091
15172
  }
15092
15173
  function parkingRecordOf(record) {
@@ -15524,6 +15605,10 @@ function guardRunPersistence(journal, blobs, interrupt) {
15524
15605
  },
15525
15606
  assertAvailable() {
15526
15607
  if (failure !== void 0) throw failure;
15608
+ },
15609
+ /** Refuse every later write with `error`, without interrupting the retained executions. */
15610
+ seal(error) {
15611
+ failure ??= error;
15527
15612
  }
15528
15613
  };
15529
15614
  }
@@ -16003,7 +16088,7 @@ async function executeRoot(root) {
16003
16088
  ok: true,
16004
16089
  out: await runAbortable(() => {
16005
16090
  rootStarted = true;
16006
- return root.run();
16091
+ return raceRunParking(opts.runId, scope, persistence.seal, root.run);
16007
16092
  }, controller.signal, "supervisor aborted")
16008
16093
  };
16009
16094
  } catch (error) {
@@ -16136,6 +16221,6 @@ async function noWinner(settled, rejection) {
16136
16221
  reason: "no-result-selected"
16137
16222
  };
16138
16223
  }
16139
- export { DEFAULT_PEER_MAIL_LIMITS as $, createSandboxForSpec as A, bridgeRuntimeAttachmentsKey as At, createRouterTranscript as B, controlProfileMaterialization as Bt, createExecutor as C, priceTokens as Ct, runAgentRounds as D, harnessUsageIsEmpty as Dt, createSteerableSandboxSession as E, createCodexRolloutStoreReader as Et, codeModeArguments as F, LOCAL_HARNESSES as Ft, LEAF_CONTINUATION_TASK as G, promptModelProfileMaterialization as Gt, createAgentEnvironmentProviderRegistry as H, fullProfileMaterialization as Ht, codeModeModelOutput as I, harnessInvocation as It, createInPlaceCliExecutor as J, sandboxProfileMaterialization as Jt, providerAsSandboxClient as K, renderUnsupported as Kt, createCodeModeTools as L, terminateProcessTreeAndConfirm as Lt, acquireSandbox as M, defaultRunCommand as Mt, TERMINAL_DECISIONS as N, runSettledCommand as Nt, assertBoxlessPromptOptions as O, readCodexRolloutSession as Ot, defaultSelectWinner as P, runWorktreeHarness as Pt, AUTHORITY_MARKERS as Q, readSandboxOutcome as Qt, runCodeMode as R, assertProfileMaterialization as Rt, captureReusableExecutorConfig as S, bridgeModelRouteRefusal as St, DEFAULT_SANDBOX_STEERING_MAX_TURNS as T, addHarnessUsage as Tt, resolveAgentEnvironmentProvider as U, profileMaterializationAxes$1 as Ut, routerBrain as V, defineProfileMaterializationContract as Vt, providerAsExecutor as W, promptControlProfileMaterialization as Wt, createInbox as X, worktreeCliProfileMaterialization as Xt, INBOX_RECEIPT_KEY as Y, unsupportedProfileDimensions as Yt, failPendingAfter as Z, projectSandboxOutcome as Zt, withDriverExecutor as _, gateFactoryOnDeliverable as _t, assertRunParking as a, peerMailVerbNames as at, createExecutorRegistry as b, verdictFromJudgeScore as bt, sleepScopeWait as c, HarnessTurnFailedError as ct, runFinalizer as d, summarizeDriverAttempts as dt, PEER_MAIL_WIRE_KEY as et, runTree as f, transientFailureKind as ft, isDriverSpec as g, CheckUnavailableError as gt, driverExecutorFactory as h, preflightPublicCoordination as ht, RunParkedError as i, peerMailTools as it, createSandboxLineage as j, bridgeStopSignalKey as jt, readPromptOptions as k, createPushTraceSource as kt, withRunParking as l, abandonablePending as lt, driverChild as m, upstreamUnavailableSignal as mt, createSupervisor as n, createPeerMailbox as nt, bindScopeParkingDrain as o, taskToPrompt$1 as ot, createRootHandle as p, undispatchedCredentialExit as pt, createWorktreeCliExecutor as q, sandboxActProfileMaterialization as qt, assertResumeLimits as r, isPeerMailEnvelope as rt, readRunParking as s, DriverAttemptsExhaustedError as st, DEFAULT_MAX_DEPTH as t, claimsAuthority as tt, bestDelivered as u, classifyDriverFailure as ut, InMemoryResultBlobStore as v, gateOnDeliverable as vt, snapshotExecutorConfig as w, ROUTER_PRICE_SOURCE as wt, bindReusableExecutorExecutionId as x, bridgeAdmissionRefusal as xt, InMemorySpawnJournal as y, mapExecutorResult as yt, toolResultText as z, assertProfileMaterializes as zt };
16224
+ export { AUTHORITY_MARKERS as $, readSandboxOutcome as $t, readPromptOptions as A, createPushTraceSource as At, toolResultText as B, assertProfileMaterializes as Bt, captureReusableExecutorConfig as C, bridgeModelRouteRefusal as Ct, createSteerableSandboxSession as D, createCodexRolloutStoreReader as Dt, DEFAULT_SANDBOX_STEERING_MAX_TURNS as E, addHarnessUsage as Et, defaultSelectWinner as F, runWorktreeHarness as Ft, providerAsExecutor as G, promptControlProfileMaterialization as Gt, routerBrain as H, defineProfileMaterializationContract as Ht, codeModeArguments as I, LOCAL_HARNESSES as It, createWorktreeCliExecutor as J, sandboxActProfileMaterialization as Jt, LEAF_CONTINUATION_TASK as K, promptModelProfileMaterialization as Kt, codeModeModelOutput as L, harnessInvocation as Lt, createSandboxLineage as M, bridgeStopSignalKey as Mt, acquireSandbox as N, defaultRunCommand as Nt, runAgentRounds as O, harnessUsageIsEmpty as Ot, TERMINAL_DECISIONS as P, runSettledCommand as Pt, failPendingAfter as Q, projectSandboxOutcome as Qt, createCodeModeTools as R, terminateProcessTreeAndConfirm as Rt, bindReusableExecutorExecutionId as S, bridgeAdmissionRefusal as St, snapshotExecutorConfig as T, ROUTER_PRICE_SOURCE as Tt, createAgentEnvironmentProviderRegistry as U, fullProfileMaterialization as Ut, createRouterTranscript as V, controlProfileMaterialization as Vt, resolveAgentEnvironmentProvider as W, profileMaterializationAxes$1 as Wt, INBOX_RECEIPT_KEY as X, unsupportedProfileDimensions as Xt, createInPlaceCliExecutor as Y, sandboxProfileMaterialization as Yt, createInbox as Z, worktreeCliProfileMaterialization as Zt, isDriverSpec as _, CheckUnavailableError as _t, assertRunParking as a, peerMailTools as at, InMemorySpawnJournal as b, mapExecutorResult as bt, readRunParking as c, DriverAttemptsExhaustedError as ct, bestDelivered as d, classifyDriverFailure as dt, DEFAULT_PEER_MAIL_LIMITS as et, runFinalizer as f, summarizeDriverAttempts as ft, driverExecutorFactory as g, preflightPublicCoordination as gt, driverChild as h, upstreamUnavailableSignal as ht, RunParkedError as i, isPeerMailEnvelope as it, createSandboxForSpec as j, bridgeRuntimeAttachmentsKey as jt, assertBoxlessPromptOptions as k, readCodexRolloutSession as kt, sleepScopeWait as l, HarnessTurnFailedError as lt, createRootHandle as m, undispatchedCredentialExit as mt, createSupervisor as n, claimsAuthority as nt, bindScopeParkingDrain as o, peerMailVerbNames as ot, runTree as p, transientFailureKind as pt, providerAsSandboxClient as q, renderUnsupported as qt, assertResumeLimits as r, createPeerMailbox as rt, isRunParked as s, taskToPrompt$1 as st, DEFAULT_MAX_DEPTH as t, PEER_MAIL_WIRE_KEY as tt, withRunParking as u, abandonablePending as ut, withDriverExecutor as v, gateFactoryOnDeliverable as vt, createExecutor as w, priceTokens as wt, createExecutorRegistry as x, verdictFromJudgeScore as xt, InMemoryResultBlobStore as y, gateOnDeliverable as yt, runCodeMode as z, assertProfileMaterialization as zt };
16140
16225
 
16141
- //# sourceMappingURL=supervisor-D-eT-6Tu.js.map
16226
+ //# sourceMappingURL=supervisor-BhcXPxAk.js.map