@tangle-network/agent-runtime 0.298.1 → 0.299.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 (53) hide show
  1. package/dist/{activation-CYHA4rRC.js → activation-hR2jeUaw.js} +2 -2
  2. package/dist/{activation-CYHA4rRC.js.map → activation-hR2jeUaw.js.map} +1 -1
  3. package/dist/{activation-BplOD2nI.d.ts → activation-tUsWG3uJ.d.ts} +3 -3
  4. package/dist/agent.d.ts +2 -2
  5. package/dist/agent.js +2 -2
  6. package/dist/{coordination-driver-zPyluAvO.js → coordination-driver-DQqNlHNU.js} +2 -2
  7. package/dist/{coordination-driver-zPyluAvO.js.map → coordination-driver-DQqNlHNU.js.map} +1 -1
  8. package/dist/{delegate-BQBHhLst.js → delegate-B2ux581r.js} +2 -2
  9. package/dist/{delegate-BQBHhLst.js.map → delegate-B2ux581r.js.map} +1 -1
  10. package/dist/durable.d.ts +2 -2
  11. package/dist/durable.js +2 -2
  12. package/dist/{graph-B5GC0B7N.js → graph-CrK93Avw.js} +4 -4
  13. package/dist/{graph-B5GC0B7N.js.map → graph-CrK93Avw.js.map} +1 -1
  14. package/dist/{improvement-cycle-DB1d3Hay.js → improvement-cycle-oKjGSbFV.js} +3 -3
  15. package/dist/{improvement-cycle-DB1d3Hay.js.map → improvement-cycle-oKjGSbFV.js.map} +1 -1
  16. package/dist/{index-DNc4puC0.d.ts → index-BXzfhVpx.d.ts} +26 -6
  17. package/dist/index.d.ts +6 -6
  18. package/dist/index.js +7 -7
  19. package/dist/intelligence.d.ts +3 -3
  20. package/dist/intelligence.js +4 -4
  21. package/dist/kernel.d.ts +4 -4
  22. package/dist/kernel.js +8 -8
  23. package/dist/{loop-runner-bin-BYv3D9Uu.d.ts → loop-runner-bin-Cs0G7h8L.d.ts} +3 -3
  24. package/dist/{loop-runner-bin-DMMgy4n7.js → loop-runner-bin-Du_SBPxW.js} +3 -3
  25. package/dist/{loop-runner-bin-DMMgy4n7.js.map → loop-runner-bin-Du_SBPxW.js.map} +1 -1
  26. package/dist/loop-runner-bin.d.ts +1 -1
  27. package/dist/loop-runner-bin.js +1 -1
  28. package/dist/mcp/bin.js +3 -3
  29. package/dist/mcp/index.d.ts +5 -5
  30. package/dist/mcp/index.js +4 -4
  31. package/dist/{openai-tools-CrfETZkV.d.ts → openai-tools-JmKXlSR4.d.ts} +2 -2
  32. package/dist/profiles.d.ts +2 -2
  33. package/dist/{provision-supervisor-SoJlaXXm.js → provision-supervisor-vDXQxYFy.js} +3 -3
  34. package/dist/{provision-supervisor-SoJlaXXm.js.map → provision-supervisor-vDXQxYFy.js.map} +1 -1
  35. package/dist/{runtime-CXz6E34n.js → runtime-CyQ8CLJf.js} +43 -8
  36. package/dist/{runtime-CXz6E34n.js.map → runtime-CyQ8CLJf.js.map} +1 -1
  37. package/dist/{search-method-D3KpsvEs.js → search-method-BIhLTuQB.js} +2 -2
  38. package/dist/{search-method-D3KpsvEs.js.map → search-method-BIhLTuQB.js.map} +1 -1
  39. package/dist/{server-DFWQoBYk.js → server-BO0N9O7o.js} +3 -3
  40. package/dist/{server-DFWQoBYk.js.map → server-BO0N9O7o.js.map} +1 -1
  41. package/dist/{stream-agent-turn-D-JUSWnD.d.ts → stream-agent-turn-B9RXK3fv.d.ts} +2 -2
  42. package/dist/{substrate-Bd4FFbim.d.ts → substrate-CLCPNwHP.d.ts} +2 -2
  43. package/dist/{supervise-D-H4-BbE.js → supervise-CvPBOHpa.js} +3 -3
  44. package/dist/{supervise-D-H4-BbE.js.map → supervise-CvPBOHpa.js.map} +1 -1
  45. package/dist/{supervisor-Iea8J235.js → supervisor-DPXXMNZK.js} +168 -18
  46. package/dist/supervisor-DPXXMNZK.js.map +1 -0
  47. package/dist/testing.d.ts +2 -2
  48. package/dist/testing.js +12 -12
  49. package/dist/tui/index.d.ts +1 -1
  50. package/dist/tui/index.js +1 -1
  51. package/dist/{types-CwGpKzG1.d.ts → types-DLM0wytK.d.ts} +31 -4
  52. package/package.json +1 -1
  53. package/dist/supervisor-Iea8J235.js.map +0 -1
@@ -105,6 +105,14 @@ function promptPartFromInputPart(part) {
105
105
  //#region src/runtime/supervise/deadline.ts
106
106
  const MAX_TIMER_DELAY_MS = 2147483647;
107
107
  const DEFAULT_SUCCESSFUL_SHUTDOWN_MS = 5e3;
108
+ /** The abort reason a child's own deadline carries. */
109
+ const CHILD_DEADLINE_REASON = "child deadline exceeded";
110
+ /** The abort reason the root's budget deadline cascades to every node. */
111
+ const ROOT_DEADLINE_REASON = "root budget deadline exceeded";
112
+ /** Whether an abort reason is a deadline: the child's own or the root budget's. */
113
+ function isDeadlineAbortReason(reason) {
114
+ return reason === "child deadline exceeded" || reason === "root budget deadline exceeded";
115
+ }
108
116
  const TEARDOWN_ACKNOWLEDGEMENT_MS = 250;
109
117
  /** Arm a finite wall-clock deadline in safe chunks. Resource deadlines unref by default;
110
118
  * a standalone wait opts into keeping the process alive until it settles or is cancelled. */
@@ -7284,16 +7292,28 @@ function normalizeWorkerSlotBound(value) {
7284
7292
  if (!Number.isSafeInteger(value)) throw new ValidationError$1(`workerSlots must be a positive safe integer, or 0 or less for no bound, got ${String(value)}`);
7285
7293
  return value;
7286
7294
  }
7287
- //#endregion
7288
- //#region src/runtime/provider-workspace-retention.ts
7289
7295
  /** Validate the executable retention port at the create boundary. */
7290
7296
  function assertProviderWorkspaceRetentionPort(port, context) {
7291
7297
  if (!Number.isSafeInteger(port.timeoutMs) || port.timeoutMs <= 0) throw new ValidationError$1(`${context}: workspaceRetention.timeoutMs must be a positive safe integer`);
7292
7298
  if (port.maxConcurrentCaptures !== void 0 && (!Number.isSafeInteger(port.maxConcurrentCaptures) || port.maxConcurrentCaptures <= 0)) throw new ValidationError$1(`${context}: workspaceRetention.maxConcurrentCaptures must be a positive safe integer`);
7293
7299
  if (port.artifacts === null || typeof port.artifacts?.read !== "function") throw new ValidationError$1(`${context}: workspaceRetention.artifacts.read is required`);
7294
7300
  if (typeof port.capture !== "function") throw new ValidationError$1(`${context}: workspaceRetention.capture is required`);
7301
+ if (port.captureNative !== void 0 && typeof port.captureNative !== "function") throw new ValidationError$1(`${context}: workspaceRetention.captureNative must be a function`);
7302
+ for (const key of ["nativeIntervalMs", "nativeTimeoutMs"]) {
7303
+ const value = port[key];
7304
+ if (value !== void 0 && (!Number.isSafeInteger(value) || value <= 0)) throw new ValidationError$1(`${context}: workspaceRetention.${key} must be a positive safe integer`);
7305
+ }
7295
7306
  }
7296
7307
  const captureGroups = /* @__PURE__ */ new WeakMap();
7308
+ const nativeSlotKeys = /* @__PURE__ */ new WeakMap();
7309
+ function nativeSlots(port) {
7310
+ let key = nativeSlotKeys.get(port);
7311
+ if (key === void 0) {
7312
+ key = Object.freeze({ maxConcurrentCaptures: port.maxConcurrentCaptures });
7313
+ nativeSlotKeys.set(port, key);
7314
+ }
7315
+ return key;
7316
+ }
7297
7317
  async function withCaptureSlot(port, signal, capture) {
7298
7318
  if (port.maxConcurrentCaptures === void 0) return capture();
7299
7319
  let group = captureGroups.get(port);
@@ -7310,20 +7330,28 @@ async function withCaptureSlot(port, signal, capture) {
7310
7330
  permit.release();
7311
7331
  }
7312
7332
  }
7313
- /** Capture, require durable refs, and verify every returned manifest/archive byte. */
7314
- async function captureProviderWorkspaceSnapshot(port, context) {
7333
+ /**
7334
+ * Capture, require durable refs, and verify every returned manifest/archive byte.
7335
+ * `native` calls {@link ProviderWorkspaceRetentionPort.captureNative} under its own queue and
7336
+ * bound, and judges coverage by the sessions alone.
7337
+ */
7338
+ async function captureProviderWorkspaceSnapshot(port, context, scope = "environment") {
7315
7339
  assertProviderWorkspaceRetentionPort(port, "provider workspace retention");
7340
+ const native = scope === "native";
7341
+ if (native && port.captureNative === void 0) throw new ValidationError$1("provider workspace retention: the port has no captureNative");
7342
+ const timeoutMs = native ? port.nativeTimeoutMs ?? 12e4 : port.timeoutMs;
7316
7343
  const controlRef = context.controlRef === void 0 ? void 0 : AgentExactRunControlRefSchema.parse(context.controlRef);
7317
7344
  if (controlRef !== void 0 && (controlRef.environmentId !== context.environment.id || controlRef.provider !== context.environment.provider || context.providerSessionId != null && controlRef.sessionId !== context.providerSessionId)) throw new Error("provider workspace retention control reference names another environment or session");
7318
7345
  const controller = new AbortController();
7319
- const clearDeadline = armDeadlineTimer(port.timeoutMs, () => controller.abort(/* @__PURE__ */ new Error(`provider workspace retention timed out after ${port.timeoutMs}ms`)), true);
7346
+ const clearDeadline = armDeadlineTimer(timeoutMs, () => controller.abort(/* @__PURE__ */ new Error(`provider workspace retention timed out after ${timeoutMs}ms`)), true);
7320
7347
  try {
7321
- return await runAbortable(() => withCaptureSlot(port, controller.signal, async () => {
7322
- const result = detachedSnapshot(await port.capture({
7348
+ return await runAbortable(() => withCaptureSlot(native ? nativeSlots(port) : port, controller.signal, async () => {
7349
+ const input = {
7323
7350
  ...context,
7324
7351
  ...controlRef === void 0 ? {} : { controlRef: Object.freeze({ ...controlRef }) },
7325
7352
  signal: controller.signal
7326
- }), "provider workspace retention snapshot");
7353
+ };
7354
+ const result = detachedSnapshot(native ? await port.captureNative(input) : await port.capture(input), "provider workspace retention snapshot");
7327
7355
  const snapshot = "snapshot" in result ? result.snapshot : result;
7328
7356
  const provenance = "snapshot" in result ? detachedSnapshot(result.provenance, "provider workspace retention provenance") : {
7329
7357
  status: "unavailable",
@@ -7340,7 +7368,9 @@ async function captureProviderWorkspaceSnapshot(port, context) {
7340
7368
  }
7341
7369
  if (provenance.status !== "reported") coverageGaps.push("Coverage metadata unavailable");
7342
7370
  if (provenance.executionId !== context.executionId) coverageGaps.push("Exact execution identity missing");
7343
- if (provenance.workspace?.complete !== true) coverageGaps.push("Workspace inventory incomplete");
7371
+ if (native) {
7372
+ if (provenance.workspaceScope !== "none") coverageGaps.push("Native capture did not report a native-only scope");
7373
+ } else if (provenance.workspace?.complete !== true) coverageGaps.push("Workspace inventory incomplete");
7344
7374
  if (provenance.sessions === void 0) coverageGaps.push("Session inventory missing");
7345
7375
  if (context.providerSessionId != null && !provenance.sessions?.some((session) => session.id === context.providerSessionId && session.executionId === context.executionId)) coverageGaps.push(`Provider session ${context.providerSessionId} missing from capture`);
7346
7376
  for (const session of provenance.sessions ?? []) {
@@ -7378,7 +7408,7 @@ async function captureProviderWorkspaceSnapshot(port, context) {
7378
7408
  coverageComplete,
7379
7409
  ...coverageComplete ? {} : { incompleteReason: `provider workspace retention coverage incomplete: ${coverageGaps.join("; ")}` }
7380
7410
  };
7381
- }), controller.signal, `provider workspace retention timed out after ${port.timeoutMs}ms`);
7411
+ }), controller.signal, `provider workspace retention timed out after ${timeoutMs}ms`);
7382
7412
  } finally {
7383
7413
  clearDeadline();
7384
7414
  }
@@ -11236,6 +11266,7 @@ function createProviderExecutor(provider, profile, ctx, options, placement) {
11236
11266
  let workspaceCleanupPromise;
11237
11267
  let retainedReleasePromise;
11238
11268
  let releaseReadTried = false;
11269
+ let releaseNativeTried = false;
11239
11270
  let workspaceOutcome;
11240
11271
  let workspacePreservationRequired = false;
11241
11272
  let workspaceRunActive = false;
@@ -11300,7 +11331,9 @@ function createProviderExecutor(provider, profile, ctx, options, placement) {
11300
11331
  if (workspaceSnapshot !== void 0) return workspaceSnapshot;
11301
11332
  if (workspaceCapturePromise === void 0) {
11302
11333
  workspaceOutcome = outcome;
11303
- workspaceCapturePromise = captureProviderWorkspaceSnapshot(workspaceRetention, {
11334
+ if (nativeTimer !== void 0) clearTimeout(nativeTimer);
11335
+ nativeTimer = void 0;
11336
+ const captureContext = {
11304
11337
  environment: next,
11305
11338
  executionId: workspaceExecutionId,
11306
11339
  ...workspaceControlRef === void 0 ? {} : { controlRef: workspaceControlRef },
@@ -11309,7 +11342,8 @@ function createProviderExecutor(provider, profile, ctx, options, placement) {
11309
11342
  nativeSessionId: null,
11310
11343
  profile: createProfile,
11311
11344
  ...outcome === void 0 ? {} : { outcome }
11312
- }).then(({ snapshot, provenance, coverageComplete, incompleteReason }) => {
11345
+ };
11346
+ workspaceCapturePromise = (nativeInFlight ?? Promise.resolve()).then(() => captureProviderWorkspaceSnapshot(workspaceRetention, captureContext)).then(({ snapshot, provenance, coverageComplete, incompleteReason }) => {
11313
11347
  workspaceSnapshot = snapshot;
11314
11348
  workspaceProvenance = provenance;
11315
11349
  workspaceCoverageComplete = coverageComplete ?? false;
@@ -11326,8 +11360,9 @@ function createProviderExecutor(provider, profile, ctx, options, placement) {
11326
11360
  incompleteReason
11327
11361
  })
11328
11362
  }, next, snapshot, providerSessionId), createProfile.harness);
11363
+ nativeHoldsTranscript = false;
11329
11364
  } catch (error) {
11330
- harnessTranscript = {
11365
+ if (!nativeHoldsTranscript) harnessTranscript = {
11331
11366
  status: "unavailable",
11332
11367
  reason: "retained-projection-failed",
11333
11368
  skipped: [{
@@ -11349,6 +11384,74 @@ function createProviderExecutor(provider, profile, ctx, options, placement) {
11349
11384
  const reason = workspaceCaptureFailure instanceof Error ? workspaceCaptureFailure.message : String(workspaceCaptureFailure ?? "capture was not accepted");
11350
11385
  return `providerAsExecutor(${provider.name}): workspace retention failed — ${reason}; source environment preserved`;
11351
11386
  };
11387
+ const nativePort = options.workspaceRetention?.captureNative === void 0 ? void 0 : options.workspaceRetention;
11388
+ let nativeInFlight;
11389
+ let nativeTimer;
11390
+ let nativeHoldsTranscript = false;
11391
+ const stopNativeMirror = async () => {
11392
+ if (nativeTimer !== void 0) clearTimeout(nativeTimer);
11393
+ nativeTimer = void 0;
11394
+ await nativeInFlight;
11395
+ };
11396
+ const captureNative = (next, phase, admitted) => {
11397
+ if (nativePort === void 0 || createProfile.harness === void 0) return Promise.resolve();
11398
+ const harness = createProfile.harness;
11399
+ const tracked = (nativeInFlight ?? Promise.resolve()).then(async () => {
11400
+ const controlRef = workspaceControlRef ?? admitted;
11401
+ const sessionId = providerSessionId ?? admitted?.sessionId ?? null;
11402
+ if (workspaceSnapshot !== void 0 && !nativeHoldsTranscript) return;
11403
+ const invocationId = workspaceExecutionId;
11404
+ try {
11405
+ const captured = await captureProviderWorkspaceSnapshot(nativePort, {
11406
+ environment: next,
11407
+ executionId: invocationId,
11408
+ ...controlRef === void 0 ? {} : { controlRef },
11409
+ ...node === void 0 ? {} : { node },
11410
+ providerSessionId: sessionId,
11411
+ nativeSessionId: null,
11412
+ profile: createProfile,
11413
+ phase
11414
+ }, "native");
11415
+ if (workspaceSnapshot !== void 0 && !nativeHoldsTranscript) return;
11416
+ const copy = retainHarnessTranscript(providerWorkspaceCaptureReceipt({
11417
+ executionId: invocationId,
11418
+ profile: createProfile,
11419
+ ...node === void 0 ? {} : { node },
11420
+ workspaceControlRef: () => controlRef,
11421
+ workspaceProvenance: () => captured.provenance,
11422
+ workspaceCoverage: () => ({
11423
+ complete: captured.coverageComplete ?? false,
11424
+ incompleteReason: captured.incompleteReason
11425
+ })
11426
+ }, next, captured.snapshot, sessionId), harness);
11427
+ if (nativeHoldsTranscript && !(copy.status === "retained" && copy.fileCount > 0)) return;
11428
+ harnessTranscript = copy;
11429
+ nativeHoldsTranscript = true;
11430
+ } catch {}
11431
+ }).finally(() => {
11432
+ if (nativeInFlight === tracked) nativeInFlight = void 0;
11433
+ });
11434
+ nativeInFlight = tracked;
11435
+ return tracked;
11436
+ };
11437
+ const startNativeMirror = (next) => {
11438
+ if (nativePort === void 0) return;
11439
+ if (nativeTimer !== void 0) clearTimeout(nativeTimer);
11440
+ const interval = nativePort.nativeIntervalMs ?? 12e4;
11441
+ const schedule = () => {
11442
+ nativeTimer = setTimeout(() => {
11443
+ if (nativeInFlight === void 0) captureNative(next, "running");
11444
+ schedule();
11445
+ }, interval);
11446
+ nativeTimer.unref?.();
11447
+ };
11448
+ schedule();
11449
+ };
11450
+ const finishNativeMirror = async (next, phase) => {
11451
+ await stopNativeMirror();
11452
+ if (workspaceSnapshot !== void 0 && !nativeHoldsTranscript) return;
11453
+ await captureNative(next, phase);
11454
+ };
11352
11455
  const destroyEnvironment = async (cleanupSignal) => {
11353
11456
  if (workspaceCleanupPromise !== void 0) return await workspaceCleanupPromise;
11354
11457
  const cleanupPromise = (async () => {
@@ -11428,6 +11531,17 @@ function createProviderExecutor(provider, profile, ctx, options, placement) {
11428
11531
  return stopping;
11429
11532
  };
11430
11533
  /**
11534
+ * A turn that its deadline or an explicit cancellation ended stops its harness, and waits within
11535
+ * the stop's bound for the provider to report it stopped, before the turn's final native copy.
11536
+ * Nothing else stops a retained execution before teardown, so that copy read a session the
11537
+ * harness was still writing and was stored partial (2026-10-04 trace proof:
11538
+ * `native_snapshot_live`, `events_not_settled`), and the harness spent past its deadline.
11539
+ */
11540
+ const stopEndedHarness = async (signal) => {
11541
+ if (!isDeadlineAbortReason(signal.reason) && !cancelledExplicitly()) return;
11542
+ await stopNativeExecution();
11543
+ };
11544
+ /**
11431
11545
  * A release that keeps an environment keeps its files, never its running harness. The root has
11432
11546
  * settled and no process will reconcile this execution, so its native process stops before the
11433
11547
  * release records what it kept.
@@ -11577,6 +11691,9 @@ function createProviderExecutor(provider, profile, ctx, options, placement) {
11577
11691
  if (continued && snapshot !== void 0 && (!options.workspaceRetention?.requireCompleteProvenance || workspaceCoverageComplete)) workspacePreservationRequired = false;
11578
11692
  },
11579
11693
  captureWorkspace,
11694
+ startNativeMirror,
11695
+ stopEndedHarness,
11696
+ finishNativeMirror,
11580
11697
  workspaceControlRef: () => workspaceControlRef,
11581
11698
  workspaceProvenance: () => workspaceProvenance,
11582
11699
  workspaceCoverage: () => ({
@@ -11703,6 +11820,11 @@ function createProviderExecutor(provider, profile, ctx, options, placement) {
11703
11820
  const capture = await captureHarnessTranscript(target, profile.harness, signal);
11704
11821
  if (capture.status === "captured") harnessTranscript = capture;
11705
11822
  }
11823
+ if (nativePort !== void 0 && harnessTranscript.status !== "retained" && !releaseNativeTried) {
11824
+ releaseNativeTried = true;
11825
+ const admitted = retained?.controlRef ?? admittedControlRef(retention);
11826
+ await awaitAbortable$1(captureNative(target, "interrupted", admitted === void 0 ? void 0 : freezeControlRef(admitted)), signal).catch(() => void 0);
11827
+ }
11706
11828
  const result = await destroyEnvironment(signal);
11707
11829
  if (!result.destroyed) return [receipt(false, result.detail, result.permanent)];
11708
11830
  pending = false;
@@ -11780,6 +11902,7 @@ async function* streamProviderExecutor(args) {
11780
11902
  const source = await providerExecutionSource(args, turn, linked);
11781
11903
  const environment = source.environment;
11782
11904
  args.onEnvironment(environment);
11905
+ args.startNativeMirror(environment);
11783
11906
  const archive = createTurnEventArchive();
11784
11907
  const seenTraceCalls = /* @__PURE__ */ new Set();
11785
11908
  let tokens = zeroTokenUsage();
@@ -11803,6 +11926,12 @@ async function* streamProviderExecutor(args) {
11803
11926
  let failure;
11804
11927
  let failed = false;
11805
11928
  let unavailable;
11929
+ let harnessStop;
11930
+ const stopEndedHarness = () => {
11931
+ if (settled !== void 0 || !linked.aborted) return Promise.resolve();
11932
+ harnessStop ??= args.stopEndedHarness(linked);
11933
+ return harnessStop;
11934
+ };
11806
11935
  try {
11807
11936
  const toolParts = createSandboxToolPartState();
11808
11937
  for await (const event of source.events) {
@@ -11928,6 +12057,7 @@ async function* streamProviderExecutor(args) {
11928
12057
  error: error instanceof Error ? error.message : String(error),
11929
12058
  ...linked.aborted ? { errorCode: "cancelled" } : {}
11930
12059
  };
12060
+ await stopEndedHarness();
11931
12061
  try {
11932
12062
  const retainedWorkspace = await args.captureWorkspace(environment, failureOutcome);
11933
12063
  if (retainedWorkspace !== void 0 && args.retention?.onEvidence !== void 0) await args.retention.onEvidence({
@@ -11942,6 +12072,8 @@ async function* streamProviderExecutor(args) {
11942
12072
  }
11943
12073
  if (args.options.workspaceRetention === void 0) args.onHarnessTranscript(await captureHarnessTranscript(environment, args.profile.harness, linked));
11944
12074
  } finally {
12075
+ await stopEndedHarness();
12076
+ await args.finishNativeMirror(environment, failed ? "failed" : settled !== void 0 ? "settled" : "interrupted");
11945
12077
  if ((!source.retained || settled !== void 0 && !failed) && !(source.retained && args.retention?.preserveEnvironment) && !(unavailable !== void 0 && !failed) && (args.options.destroyOnSettle ?? true)) {
11946
12078
  const cleanup = await args.destroyEnvironment();
11947
12079
  if (!cleanup.destroyed) {
@@ -24441,7 +24573,7 @@ function createScope(args) {
24441
24573
  cascadeAbort = () => controller.abort(args.signal.reason);
24442
24574
  if (args.signal.aborted) controller.abort(args.signal.reason);
24443
24575
  else args.signal.addEventListener("abort", cascadeAbort, { once: true });
24444
- if (childDeadlineAtMs !== void 0) clearChildDeadline = armDeadlineTimer(Math.max(0, childDeadlineAtMs - now()), () => controller.abort("child deadline exceeded"));
24576
+ if (childDeadlineAtMs !== void 0) clearChildDeadline = armDeadlineTimer(Math.max(0, childDeadlineAtMs - now()), () => controller.abort(CHILD_DEADLINE_REASON));
24445
24577
  const deferredOwner = {};
24446
24578
  const workerTrace = args.workerTrace?.(args.parentId);
24447
24579
  let markRecoveryReady;
@@ -25445,12 +25577,26 @@ function meterRuntimeOwnedAccounting(scope, spend, detail) {
25445
25577
  }
25446
25578
  const ownerMaterializationStates = /* @__PURE__ */ new WeakMap();
25447
25579
  /**
25580
+ * One owner materialization write at a time. A cancelled run settles without waiting for its root
25581
+ * driver, so the driver's late receipt and the settlement's finalization could each read no
25582
+ * receipt before the other's journal append returned, and both appended one: the journal then
25583
+ * refused the run as corrupted (duplicate materialization receipt).
25584
+ */
25585
+ function serializedOwnerWrite(state, write) {
25586
+ const next = (state.writes ?? Promise.resolve()).then(write, write);
25587
+ state.writes = next.catch(() => void 0);
25588
+ return next;
25589
+ }
25590
+ /**
25448
25591
  * @internal Publish exact root-manager materialization from a runtime-owned adapter after dynamic
25449
25592
  * attachments exist and before its executor starts. This is deliberately a module function backed
25450
25593
  * by a private WeakMap, not a Scope method an Agent can call.
25451
25594
  */
25452
25595
  async function recordScopeOwnerMaterialization(scope, runtime, declaration, bindingInput) {
25453
25596
  const state = ownerMaterializationState(scope);
25597
+ await serializedOwnerWrite(state, () => publishOwnerMaterialization(state, runtime, declaration, bindingInput));
25598
+ }
25599
+ async function publishOwnerMaterialization(state, runtime, declaration, bindingInput) {
25454
25600
  if (runtime !== state.runtime) {
25455
25601
  await rejectOwnerMaterialization(state);
25456
25602
  throw new ValidationError$1(`scope owner materialization runtime ${JSON.stringify(runtime)} does not match ${JSON.stringify(state.runtime)}`);
@@ -25563,7 +25709,11 @@ async function restoreScopeOwnerAcceptedExecution(scope) {
25563
25709
  /** @internal Ensure a deferred root that never published evidence remains visibly unknown. */
25564
25710
  async function finalizeScopeOwnerMaterialization(scope) {
25565
25711
  const state = ownerMaterializationStates.get(scope);
25566
- if (state === void 0 || state.publishedThisProcess || state.bindingPublished) return;
25712
+ if (state === void 0) return;
25713
+ await serializedOwnerWrite(state, () => finalizeOwnerMaterialization(state));
25714
+ }
25715
+ async function finalizeOwnerMaterialization(state) {
25716
+ if (state.publishedThisProcess || state.bindingPublished) return;
25567
25717
  if (state.prior !== void 0) {
25568
25718
  await appendUnknownOwnerBinding(state, state.prior, "root-agent-did-not-report");
25569
25719
  throw new ValidationError$1("resumed scope owner did not re-attest its prior materialization before execution");
@@ -28474,9 +28624,9 @@ function createSupervisor() {
28474
28624
  });
28475
28625
  let deadlineExceeded = false;
28476
28626
  const rootDeadlineAtMs = pool.readout().deadlineMs;
28477
- if (rootDeadlineAtMs > 0 && now() >= rootDeadlineAtMs) deadlineExceeded = cascadeAbort("root budget deadline exceeded");
28627
+ if (rootDeadlineAtMs > 0 && now() >= rootDeadlineAtMs) deadlineExceeded = cascadeAbort(ROOT_DEADLINE_REASON);
28478
28628
  const clearRootDeadline = opts.budget.deadlineMs === void 0 ? void 0 : armDeadlineTimer(Math.max(0, rootDeadlineAtMs - now()), () => {
28479
- deadlineExceeded = cascadeAbort("root budget deadline exceeded");
28629
+ deadlineExceeded = cascadeAbort(ROOT_DEADLINE_REASON);
28480
28630
  });
28481
28631
  let actOutcome = {
28482
28632
  ok: false,
@@ -29080,4 +29230,4 @@ function isNonEmptySpend(s) {
29080
29230
  //#endregion
29081
29231
  export { bindScopeRetainedOwnerProvider as $, detachedFrozen as $i, parseWorkerToolTraceArtifact as $n, sanitizeRuntimeStreamEvent as $r, isPeerMailEnvelope as $t, driverExecutorFactory as A, addResourceSpend as Aa, prepareJsonlAppend as Ai, resolveAgentEnvironmentProvider as An, contentAddress as Ar, createExecutor as At, recordScopeOwnerDriverAttempt as B, promptFromAgentTurnInput as Ba, newExecutionAttemptId as Bi, InMemoryResultBlobStore as Bn, buildRuntimeEventOtelSpans as Br, workerTraceEnv as Bt, createContinuationKeeper as C, sleep as Ca, renderProfileMaterializationIssues as Ci, readPromptOptions as Cn, runAbortable as Cr, freeSlots as Ct, passedItems as D, unmeteredSpend as Da, validateProfileMaterialization as Di, createAgentEnvironmentProviderRegistry as Dn, readHarnessTranscript as Dr, captureReusableExecutorConfig as Dt, failedItems as E, throwIfAborted as Ea, unsupportedProfileDimensions as Ei, LEAF_CONTINUATION_TASK as En, persistHarnessTranscript as Er, bindReusableExecutorExecutionId as Et, beginScopeOwnerAttempt as F, awaitAbortable$1 as Fa, authoredProfileDigest as Fi, sandboxSessionTraceSource as Fn, defaultRedactor as Fr, createSteerableSandboxSession as Ft, settledToIteration as G, runtimeOwnedExecutorMaterialization as Gi, insideCursorNamespace as Gn, loopEventToOtelSpan as Gr, createActivityLog as Gt, recordScopeOwnerPause as H, providerMessageText as Ha, recordRuntimeOwnedDriveHarnessProviderEvidence as Hi, SpawnEventIndex as Hn, createOtelExporter as Hr, workerTraceSeamKey as Ht, createScope as I, DEFAULT_SUCCESSFUL_SHUTDOWN_MS as Ia, finalizeRuntimeOwnedPendingExecutor as Ii, registerRetainedExecutorPreparation as In, defaultRedactorIdentityMaterial as Ir, createRouterTranscript as It, pollFor as J, runtimeOwnedScopeOwnerRuntime as Ji, pendingWaits as Jn, toOtelAttributes as Jr, AUTHORITY_MARKERS as Jt, createWaitProbes as K, runtimeOwnedExecutorProviderEvidence as Ki, loadSpawnForest as Kn, padSpanId as Kr, readWorkerProgress as Kt, deriveNodeExecutionIdentity as L, armDeadlineTimer as La, inheritRuntimeOwnedExecutorAttestation as Li, retainedExecutorSeamKey as Ln, resolveRedactor as Lr, createInPlaceCliExecutor as Lt, withDriverExecutor as M, withBudgetResources as Ma, writeAllBytes as Mi, unavailableSignalOfFailure as Mn, mergeTraceEnv as Mr, snapshotExecutorConfig as Mt, SUBTREE_RESULT_LIMIT as N, decodeHarnessUsage as Na, attestRuntimeOwnedPendingExecutor as Ni, createPushTraceSource as Nn, readTraceContextFromEnv as Nr, createWorktreeCliExecutor as Nt, verdictFromJudgeScore as O, withTimeout as Oa, worktreeCliProfileMaterialization as Oi, providerAsExecutor as On, resolveHarnessTranscriptCapture as Or, cliInPlaceExecutor as Ot, assertRecursiveReservationPolicy as P, abortError$2 as Pa, attestRuntimeOwnedScopeOwner as Pi, decodeToolPart as Pn, traceContextToEnv as Pr, DEFAULT_SANDBOX_STEERING_MAX_TURNS as Pt, bindScopeRetainedOwnerEnvironmentId as Q, executableAgentSpecSnapshot as Qi, isTraceAnalysisStore as Qn, sanitizeKnowledgeReadinessReport as Qr, createPeerMailbox as Qt, meterRuntimeOwnedAccounting as R, teardownExecutor as Ra, knownExecutionBindingReceipt as Ri, FileResultBlobStore as Rn, buildLoopOtelSpans as Rr, WORKER_TRACE_PROPAGATION as Rt, composeContinuationNote as S, randomSuffix as Sa, promptResourceProfileMaterialization as Si, assertBoxlessPromptOptions as Sn, linkAbort as Sr, startRetainedInteractiveRun as St, expandQuestions as T, throwAbort as Ta, sandboxActProfileMaterialization as Ti, runBrainLoop as Tn, harnessTranscriptArtifact as Tr, rollingDispatch as Tt, restoreScopeOwnerAcceptedExecution as U, runtimeOwnedDriveHarnessProviderEvidence as Ui, assertContentAddress as Un, flatOtelSpan as Ur, taskToPrompt as Ut, recordScopeOwnerMaterialization as V, promptOptionsFromAgentTurnInput as Va, providerAttemptEvidence as Vi, InMemorySpawnJournal as Vn, createOpenInferenceFileExporter as Vr, workerTraceHeaders as Vt, scopeOwnerExecutorNodeContext as W, runtimeOwnedExecutorExecutionBinding as Wi, encodeResultBlob as Wn, generateSpanId as Wr, DEFAULT_STALL_AFTER_MS as Wt, validateWaitSpec as X, unknownMaterializationReceipt as Xi, WORKER_TOOL_TRACE_SCHEMA_VERSION as Xn, createRuntimeStreamEventCollector as Xr, PEER_MAIL_WIRE_KEY as Xt, timerAt as Y, unknownExecutionBindingReceipt as Yi, replaySpawnTree as Yn, createRuntimeEventCollector as Yr, DEFAULT_PEER_MAIL_LIMITS as Yt, waitUntil as Z, executableAgentProfileSnapshot as Zi, captureWorkerTraceEvidence as Zn, sanitizeAgentRuntimeEvent as Zr, claimsAuthority as Zt, CheckUnavailableError as _, cloneSpend as _a, fullProfileMaterialization as _i, createSandboxLineage as _n, environmentGone as _r, readWorkerInteractiveBinding as _t, collectDelivered as a, createSandboxToolPartState as aa, DEFAULT_LOCAL_HARNESS as ai, bridgeModelRouteRefusal as an, createBudgetPool as ar, scopeRetainedOwnerPriorSpend as at, bestComposite as b, isAbortError$2 as ba, promptModelProfileMaterialization as bi, SandboxEvidenceRetentionError as bn, RunCancellationReason as br, reconnectRetainedInteractiveRun as bt, runTree as c, isSandboxTerminalEvent as ca, harnessSupportsReasoningEffort as ci, harnessUsageIsEmpty as cn, spendFromUsageEvents as cr, scopeRetainedOwnerResult as ct, classifyDriverFailure as d, notifySandboxEventObserver as da, CodexExecutionDiagnosticError as di, bridgeStopSignalKey as dn, reconnectRetainedRun as dr, hostDirectoryReader as dt, detachedSnapshot as ea, runSettledCommand as ei, peerMailTools as en, workerTraceAnalysisStore as er, consumeScopeRetainedOwnerResult as et, runDriverWithRetry as f, sandboxEventServedBackend as fa, terminateProcessTreeAndConfirm as fi, TERMINAL_DECISIONS as fn, recoverRetainedRun as fr, resolveSpawnResourcePaths as ft, CONTINUATION_FACTS as g, chargedTokens as ga, defineProfileMaterializationContract as gi, runAgentRounds as gn, destroyInteractiveEnvironment as gr, attachWorker as gt, CONTINUATIONS_DIR as h, addSpend as ha, controlProfileMaterialization as hi, isTerminalDecision as hn, retainedCreateMaterial as hr, workerInteractiveAdmissionFile as ht, bestDelivered as i, canonicalStreamEventFromSandboxEvent as ia, removeWorktree as ii, bridgeAdmissionRefusal as in, assertValidBudget as ir, scopeRetainedOwnerContext as it, isDriverSpec as j, resourceTelemetry as ja, readCommittedJsonLines as ji, unavailablePauseMs as jn, createPropagatingTraceEmitter as jr, createExecutorRegistry as jt, driverChild as k, zeroSpend as ka, isNoEntError as ki, providerAsSandboxClient as kn, retainHarnessTranscript as kr, cliWorktreeExecutor as kt, DriverAttemptsExhaustedError as l, mapSandboxEvent as la, localHarnessExecutable as li, readCodexRolloutSession as ln, spendFromUsageTotals as lr, SPAWN_RESOURCE_PATH_MAX_BYTES as lt, upstreamUnavailableSignal as m, sumSandboxUsage as ma, assertProfileMaterialization as mi, defaultSelectWinner as mn, startRetainedRunInEnvironment as mr, readWorkerInteractiveAdmissions as mt, createRootHandle as n, readSandboxOutcome as na, captureWorktreeDiff as ni, isLiveNodeStatus as nn, BudgetReconcileFault as nr, prepareScopeRetainedOwnerTask as nt, pickBestDelivered as o, createSandboxUsageLedger as oa, LOCAL_HARNESSES as oi, addHarnessUsage as on, meterUsageEvent as or, scopeRetainedOwnerResourceReader as ot, summarizeDriverAttempts as p, sandboxProgressEvents as pa, AGENT_PROFILE_MATERIALIZATION_AXES as pi, createSandboxForSpec as pn, startRetainedRun as pr, interactiveAdmissionSeamKey as pt, isWaitOutcome as q, runtimeOwnedPendingExecutorMaterialization as qi, materializeTreeView as qn, padTraceId as qr, createInbox as qt, createSupervisor as r, assertSandboxServedModel as ra, createWorktree as ri, isTerminalNodeStatus as rn, ReservationWaitRefused as rr, reconcileScopeRetainedOwnerEnvironment as rt, runFinalizer as s, extractLlmCallEvent as sa, harnessInvocation as si, createCodexRolloutStoreReader as sn, newUsageTotals as sr, scopeRetainedOwnerRestorePoint as st, DEFAULT_MAX_DEPTH as t, projectSandboxOutcome as ta, runWorktreeHarness as ti, peerMailVerbNames as tn, executorFailure as tr, noteScopeRetainedOwnerCoordination as tt, HarnessTurnFailedError as u, mapSandboxToolEvent as ua, parseCodexTokenUsage as ui, bridgeRuntimeAttachmentsKey as un, errMessage as ur, environmentReader as ut, admitContinuationPolicy as v, deleteBoxSafe as va, profileMaterializationAxes$1 as vi, probeSandboxCapabilities as vn, createWorkerSlots as vr, workerInteractiveBindingFile as vt, distillFindings as w, stringifySafe as wa, renderUnsupported as wi, routerBrain as wn, captureHarnessTranscript as wr, queueOf as wt, checkVerdictOf as x, promptCacheTokenClasses as xa, promptOnlyProfileMaterialization as xi, captureBeforeDestroy as xn, abortError as xr, recoverRetainedInteractiveRun as xt, admitFinding as y, hasCompleteCacheBreakdown as ya, promptControlProfileMaterialization as yi, acquireSandbox as yn, openSlotGroup as yr, workerInteractiveBindingsDir as yt, meterRuntimeOwnedProviderAttempt as z, teardownSurfaces as za, knownMaterializationReceipt as zi, FileSpawnJournal as zn, buildLoopSpanNodes as zr, readWorkerTraceContext as zt };
29082
29232
 
29083
- //# sourceMappingURL=supervisor-Iea8J235.js.map
29233
+ //# sourceMappingURL=supervisor-DPXXMNZK.js.map