@tangle-network/agent-runtime 9.0.16 → 10.0.0

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 (93) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/dist/{activation-y6NAn3sW.d.ts → activation-CDlOqX5a.d.ts} +7 -8
  3. package/dist/{activation-DgT20fzX.js → activation-CEGkyzEG.js} +2 -2
  4. package/dist/{activation-DgT20fzX.js.map → activation-CEGkyzEG.js.map} +1 -1
  5. package/dist/agent.d.ts +1 -1
  6. package/dist/agent.js +3 -3
  7. package/dist/candidate-execution/index.d.ts +3 -0
  8. package/dist/candidate-execution/index.js +10 -3
  9. package/dist/candidate-execution/index.js.map +1 -1
  10. package/dist/{delegate-Cmu5OF3M.js → delegate-V2Nz8GgO.js} +2 -2
  11. package/dist/{delegate-Cmu5OF3M.js.map → delegate-V2Nz8GgO.js.map} +1 -1
  12. package/dist/{coordination-manager-CFtnSLPw.js → driver-control-acknowledgers-CJDYLJmW.js} +1042 -1042
  13. package/dist/driver-control-acknowledgers-CJDYLJmW.js.map +1 -0
  14. package/dist/durable.d.ts +5 -5
  15. package/dist/durable.js +13 -13
  16. package/dist/durable.js.map +1 -1
  17. package/dist/{failure-cause-WifbY42M.js → failure-cause-BI7cfDWx.js} +14 -2
  18. package/dist/failure-cause-BI7cfDWx.js.map +1 -0
  19. package/dist/{graph-registry-B_1C7qye.js → graph-registry-DxhlgHdA.js} +1 -1
  20. package/dist/{graph-registry-BbZN5deo.js → graph-registry-j9t9J0KT.js} +11 -12
  21. package/dist/{graph-registry-BbZN5deo.js.map → graph-registry-j9t9J0KT.js.map} +1 -1
  22. package/dist/{graph-DqtIiS94.js → graph-wJOMQ1kC.js} +8 -8
  23. package/dist/{graph-DqtIiS94.js.map → graph-wJOMQ1kC.js.map} +1 -1
  24. package/dist/{improve-B0vNv6e7.js → improve-DOjywiPq.js} +42 -26
  25. package/dist/{improve-B0vNv6e7.js.map → improve-DOjywiPq.js.map} +1 -1
  26. package/dist/index.d.ts +38 -6
  27. package/dist/index.js +59 -20
  28. package/dist/index.js.map +1 -1
  29. package/dist/intelligence.d.ts +93 -63
  30. package/dist/intelligence.js +166 -73
  31. package/dist/intelligence.js.map +1 -1
  32. package/dist/kernel.d.ts +3 -3
  33. package/dist/kernel.js +16 -15
  34. package/dist/{loop-runner-BvVdDdZC.js → loop-runner-CPTOzSol.js} +2 -2
  35. package/dist/{loop-runner-BvVdDdZC.js.map → loop-runner-CPTOzSol.js.map} +1 -1
  36. package/dist/{loop-runner-CfMOsISJ.d.ts → loop-runner-DwxZbYW5.d.ts} +2 -2
  37. package/dist/loop-runner-bin.d.ts +1 -1
  38. package/dist/loop-runner-bin.js +1 -1
  39. package/dist/mcp/bin.js +3 -3
  40. package/dist/mcp/index.d.ts +1 -1
  41. package/dist/mcp/index.js +7 -7
  42. package/dist/mcp/memory-bin.js +1 -1
  43. package/dist/{model-policy-CZwhXp8O.js → model-policy-CqDuBTq-.js} +12 -2
  44. package/dist/model-policy-CqDuBTq-.js.map +1 -0
  45. package/dist/{prepare-Cw4ZaN01.js → prepare-DT-ibRsm.js} +2 -2
  46. package/dist/{prepare-Cw4ZaN01.js.map → prepare-DT-ibRsm.js.map} +1 -1
  47. package/dist/profiles.d.ts +1 -1
  48. package/dist/profiles.js +1 -1
  49. package/dist/{provision-supervisor-BjKluSKl.js → provision-supervisor-B1_Kow9m.js} +6 -6
  50. package/dist/{provision-supervisor-BjKluSKl.js.map → provision-supervisor-B1_Kow9m.js.map} +1 -1
  51. package/dist/{run-cancellation-BvGEEwRG.js → run-cancellation-D5m6JHPH.js} +2 -2
  52. package/dist/{run-cancellation-BvGEEwRG.js.map → run-cancellation-D5m6JHPH.js.map} +1 -1
  53. package/dist/{run-state-Dd_AjWd6.js → run-state-DKOXe08H.js} +5 -5
  54. package/dist/{run-state-Dd_AjWd6.js.map → run-state-DKOXe08H.js.map} +1 -1
  55. package/dist/{runtime-7VEM9muH.js → runtime-C5cWSMqU.js} +191 -24
  56. package/dist/runtime-C5cWSMqU.js.map +1 -0
  57. package/dist/{search-executor-Dqtm1fOC.js → search-executor-CA6fTYWz.js} +5 -5
  58. package/dist/{search-executor-Dqtm1fOC.js.map → search-executor-CA6fTYWz.js.map} +1 -1
  59. package/dist/{server-B8Kmit_v.js → server-C8Z3vYdI.js} +4 -4
  60. package/dist/{server-B8Kmit_v.js.map → server-C8Z3vYdI.js.map} +1 -1
  61. package/dist/{settle-record-BvH2-Ao5.js → settle-record-BDxPAO4m.js} +2 -2
  62. package/dist/{settle-record-BvH2-Ao5.js.map → settle-record-BDxPAO4m.js.map} +1 -1
  63. package/dist/{structural-rollout-CYc8PE2N.js → structural-rollout-B0HPcP9G.js} +5 -5
  64. package/dist/{structural-rollout-CYc8PE2N.js.map → structural-rollout-B0HPcP9G.js.map} +1 -1
  65. package/dist/{supervise-BayNu7qZ.js → supervise-Dvj-8S6D.js} +2341 -2283
  66. package/dist/supervise-Dvj-8S6D.js.map +1 -0
  67. package/dist/{supervision-discovery-Ca4QO4rG.js → supervision-discovery-CbrwcgJy.js} +3 -3
  68. package/dist/{supervision-discovery-Ca4QO4rG.js.map → supervision-discovery-CbrwcgJy.js.map} +1 -1
  69. package/dist/{supervisor-Bx21Hy27.js → supervisor-DwdeUC2l.js} +218 -47
  70. package/dist/supervisor-DwdeUC2l.js.map +1 -0
  71. package/dist/{supervisor-accounting-StDNW1YT.js → supervisor-accounting-C48Yo9QC.js} +507 -341
  72. package/dist/supervisor-accounting-C48Yo9QC.js.map +1 -0
  73. package/dist/testing.d.ts +1 -1
  74. package/dist/testing.js +11 -11
  75. package/dist/{tool-server-CirrqFlr.js → tool-server-DsCeBr-C.js} +2 -2
  76. package/dist/{tool-server-CirrqFlr.js.map → tool-server-DsCeBr-C.js.map} +1 -1
  77. package/dist/{top-web-Cg7ywIkF.js → top-web-CTOq4psb.js} +6 -6
  78. package/dist/{top-web-Cg7ywIkF.js.map → top-web-CTOq4psb.js.map} +1 -1
  79. package/dist/tui/bin.js +3 -3
  80. package/dist/tui/index.d.ts +1 -1
  81. package/dist/tui/index.js +2 -2
  82. package/dist/{types-_j53efrk.d.ts → types-lnF0wIJW.d.ts} +8245 -8153
  83. package/dist/{workspace-streams-BakRr-Pl.js → workspace-streams-C7PGLAUd.js} +3 -3
  84. package/dist/workspace-streams-C7PGLAUd.js.map +1 -0
  85. package/package.json +5 -4
  86. package/dist/coordination-manager-CFtnSLPw.js.map +0 -1
  87. package/dist/failure-cause-WifbY42M.js.map +0 -1
  88. package/dist/model-policy-CZwhXp8O.js.map +0 -1
  89. package/dist/runtime-7VEM9muH.js.map +0 -1
  90. package/dist/supervise-BayNu7qZ.js.map +0 -1
  91. package/dist/supervisor-Bx21Hy27.js.map +0 -1
  92. package/dist/supervisor-accounting-StDNW1YT.js.map +0 -1
  93. package/dist/workspace-streams-BakRr-Pl.js.map +0 -1
@@ -2,10 +2,10 @@ import { c as RetainedInteractiveAdmissionError, d as RetainedRunDispatchBinding
2
2
  import { a as readCommittedJsonLines, c as appendCommittedJsonLine, f as deadlineSignal, h as signalAbortError, l as sha256, m as runAbortable, r as prepareJsonlAppend, s as withJsonlFileLock, t as isNoEntError, u as RunCancellationReason } from "./jsonl-file-BhuxeejY.js";
3
3
  import { c as checkInIdleMs, d as teardownExecutor, n as CHILD_DEADLINE_REASON, o as armDeadlineTimer, s as boundedChildDeadlineAt, u as singleFlightTeardown } from "./deadline-CySmJ_0S.js";
4
4
  import { A as withBudgetResources, C as unreportedSpend, D as addResourceSpend, T as zeroSpend, a as cloneSpend, c as errorMessage, f as isAsyncIterable, i as chargedTokens, k as resourceTelemetry, n as addSpend, o as cloneTokenUsage, t as abortError, v as sleep } from "./util-qsH5cC9S.js";
5
- import { Et as recordValue, F as executorFailure, G as budgetLeaseUpdates, I as executorFailureInfra, J as completedLeafBacking, K as budgetLeases, L as executorFailureReason, M as traceRootWriter, N as contentAddress, Q as newUsageTotals, W as BudgetReconcileFault, X as refreshBudgetLease, Y as createBudgetPool, Z as meterUsageEvent, dt as extractTransportEventIdentity, et as spendFromUsageTotals, f as executorEvidenceWriter, ft as parseCanonicalTransportEvent, g as prepareRetainedExecutor, h as leafContinuationExecutionId, n as runtimeFailureCause, nt as assertValidSpend, o as settlementFailureCause, q as budgetRecoverySeeds, s as BUDGET_CONTINUATION_TASK, t as reportedFailureCause, tt as assertValidBudget, u as RetainedExecutionPendingError, y as retainedExecutorSeamKey } from "./failure-cause-WifbY42M.js";
6
- import { a as errMessage, f as resolveRedactor, l as errorText, n as detachedSnapshot, r as shareParsedStrings, u as defaultRedactor } from "./snapshot-BKI_w3JD.js";
7
- import { p as canonicalObservedModelParts, t as assertExecutableAgentProfile } from "./model-policy-CZwhXp8O.js";
8
- import { h as workspaceLimits, i as readAgentCandidateWorkspaceArtifactFiles, m as safeArchivePath, y as verifiedArtifactChunks } from "./workspace-streams-BakRr-Pl.js";
5
+ import { Dt as recordValue, F as executorFailure, G as budgetLeaseUpdates, I as executorFailureInfra, J as completedLeafBacking, K as budgetLeases, L as executorFailureReason, M as traceRootWriter, N as contentAddress, Q as newUsageTotals, W as BudgetReconcileFault, X as refreshBudgetLease, Y as createBudgetPool, Z as meterUsageEvent, dt as extractTransportEventIdentity, et as spendFromUsageTotals, f as executorEvidenceWriter, ft as parseCanonicalTransportEvent, g as prepareRetainedExecutor, h as leafContinuationExecutionId, n as runtimeFailureCause, nt as assertValidSpend, o as settlementFailureCause, q as budgetRecoverySeeds, s as BUDGET_CONTINUATION_TASK, t as reportedFailureCause, tt as assertValidBudget, u as RetainedExecutionPendingError, y as retainedExecutorSeamKey } from "./failure-cause-BI7cfDWx.js";
6
+ import { a as errMessage, f as resolveRedactor, i as causeChain, l as errorText, n as detachedSnapshot, r as shareParsedStrings, u as defaultRedactor } from "./snapshot-BKI_w3JD.js";
7
+ import { p as canonicalObservedModelParts, t as assertExecutableAgentProfile } from "./model-policy-CqDuBTq-.js";
8
+ import { b as verifiedArtifactChunks, g as workspaceLimits, h as safeArchivePath, i as readAgentCandidateWorkspaceArtifactFiles } from "./workspace-streams-C7PGLAUd.js";
9
9
  import { a as writeAtomicDurableFile, n as assertNoSymlinkDescendant, o as captureRunWriteContext, r as publishExclusiveDurableFile, s as fenceRunWrite, t as appendDurableFile } from "./durable-file-DstVeHcj.js";
10
10
  import { b as sha256Bytes$1, g as deepFreezeCandidate } from "./output-artifacts-AqkZ8lO2.js";
11
11
  import { a as withPursuitContext, i as notifyRuntimeHookEvent } from "./runtime-hooks-CsW2pfFk.js";
@@ -20,6 +20,7 @@ import { createHash, randomUUID } from "node:crypto";
20
20
  import { appendFileSync, closeSync, constants, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, statSync, unlinkSync, writeSync } from "node:fs";
21
21
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
22
22
  import { mkdir, open, realpath, stat } from "node:fs/promises";
23
+ import { BOUND_HARNESS_SESSION_READ_LIMITS, HARNESS_TRANSCRIPT_DENY, readBoundHarnessSessions } from "@tangle-network/harness-sessions";
23
24
  import { decodeOtlpAttributes, msToUnixNano, otlpTraceExport, readOtlpPartialSuccess, toOtlpAttributes } from "@tangle-network/agent-trace-contract/otlp";
24
25
  import { lockHolderVerdict, lockIdentity, parseLockHolderRecord, readLockHolderIdentity } from "@tangle-network/agent-eval/lock-holder";
25
26
  // src/runtime/turn-input.ts
@@ -1176,6 +1177,7 @@ const sourceSchema = z.object({
1176
1177
  profileDigest: digest,
1177
1178
  providerSessionId: text.nullable(),
1178
1179
  nativeSessionId: text.nullable(),
1180
+ nativeSessionIds: z.array(text).min(1).max(1e3).optional(),
1179
1181
  coverageComplete: z.boolean(),
1180
1182
  incompleteReason: z.string().optional()
1181
1183
  });
@@ -1195,6 +1197,17 @@ const skippedSchema = z.object({
1195
1197
  path: text,
1196
1198
  reason: text
1197
1199
  });
1200
+ const omittedSchema = z.object({
1201
+ path: text,
1202
+ reason: z.enum([
1203
+ "harness-install",
1204
+ "harness-cache",
1205
+ "credential"
1206
+ ]),
1207
+ bytes: count.optional(),
1208
+ sha256: digest.optional(),
1209
+ attribution: attributionSchema
1210
+ });
1198
1211
  const retainedSchema = z.object({
1199
1212
  kind: z.literal("retained-harness-transcript"),
1200
1213
  schemaVersion: z.literal(1),
@@ -1210,13 +1223,12 @@ const retainedSchema = z.object({
1210
1223
  }),
1211
1224
  files: z.array(fileSchema),
1212
1225
  skipped: z.array(skippedSchema),
1226
+ omitted: z.array(omittedSchema).optional(),
1213
1227
  missing: z.array(z.string())
1214
1228
  });
1215
1229
  /** One native capture/read bound per child; replay resolves references rather than copying bytes. */
1216
1230
  const HARNESS_TRANSCRIPT_READ_LIMITS = Object.freeze({
1217
- maxFileBytes: 2097152,
1218
- maxTotalBytes: 16777216,
1219
- maxFiles: 1e3,
1231
+ ...BOUND_HARNESS_SESSION_READ_LIMITS,
1220
1232
  maxManifestBytes: 16777216
1221
1233
  });
1222
1234
  /** Validate persisted descriptors before trusting their identity, locators, or inventory. */
@@ -1224,11 +1236,17 @@ function parseRetainedHarnessTranscript(value) {
1224
1236
  const parsed = retainedSchema.safeParse(value);
1225
1237
  if (!parsed.success) throw new ValidationError(`Invalid retained harness transcript: ${parsed.error.message}`);
1226
1238
  const paths = /* @__PURE__ */ new Set();
1239
+ const ids = parsed.data.source.nativeSessionIds;
1240
+ if (ids && (new Set(ids).size !== ids.length || !ids.includes(parsed.data.source.nativeSessionId ?? ""))) throw new ValidationError("Retained transcript native identities are ambiguous");
1227
1241
  for (const file of parsed.data.files) {
1228
1242
  if (paths.has(file.path)) throw new ValidationError(`Retained transcript repeats native identity: ${file.path}`);
1229
1243
  paths.add(file.path);
1230
1244
  if (file.path !== nativeIdentity(file.attribution)) throw new ValidationError(`Retained transcript native identity does not match its attribution: ${file.path}`);
1231
1245
  }
1246
+ for (const file of parsed.data.omitted ?? []) {
1247
+ if (paths.has(file.path) || file.path !== nativeIdentity(file.attribution)) throw new ValidationError("Retained transcript omission conflicts with its native inventory");
1248
+ paths.add(file.path);
1249
+ }
1232
1250
  return deepFreezeCandidate(parsed.data);
1233
1251
  }
1234
1252
  function nativeIdentity(attribution) {
@@ -1253,10 +1271,23 @@ function retainHarnessTranscript(receipt, harness) {
1253
1271
  function nativeDigest(value) {
1254
1272
  return typeof value === "string" && /^[0-9a-f]{64}$/.test(value) ? `sha256:${value}` : value;
1255
1273
  }
1274
+ /** Every native conversation observed across this exact execution's attempts, in order. */
1275
+ function retainedNativeSessionIds(receipt) {
1276
+ const observedIds = [...new Set((receipt.provenance.attempts ?? []).filter((attempt) => attempt.executionId === (receipt.controlRef?.executionId ?? receipt.executionId)).flatMap((attempt) => attempt.nativeSessionIds))];
1277
+ const nativeSessionIds = receipt.nativeSessionIds ?? (observedIds.length > 0 ? [.../* @__PURE__ */ new Set([...observedIds, ...receipt.nativeSessionId ? [receipt.nativeSessionId] : []])] : void 0);
1278
+ if (nativeSessionIds && observedIds.some((id) => !nativeSessionIds.includes(id))) throw new ValidationError("Retained transcript omits an observed native execution attempt");
1279
+ return nativeSessionIds;
1280
+ }
1256
1281
  function retainedCapture(receipt, harness) {
1257
- const { snapshot, provenance, ...source } = receipt;
1282
+ const { snapshot, provenance, ...originalSource } = receipt;
1283
+ const nativeSessionIds = retainedNativeSessionIds(receipt);
1284
+ const source = {
1285
+ ...originalSource,
1286
+ ...nativeSessionIds ? { nativeSessionIds } : {}
1287
+ };
1258
1288
  const files = [];
1259
1289
  const skipped = [];
1290
+ const omitted = [];
1260
1291
  const missing = [...provenance.missing];
1261
1292
  for (const session of provenance.sessions ?? []) {
1262
1293
  if (session.executionId !== receipt.executionId || session.backendType !== harness) throw new ValidationError("Retained transcript session has a different execution or harness");
@@ -1273,6 +1304,16 @@ function retainedCapture(receipt, harness) {
1273
1304
  rootScope: entry.rootScope,
1274
1305
  nativePath: entry.path
1275
1306
  };
1307
+ if (entry.contentOmitted !== void 0) {
1308
+ omitted.push(omittedSchema.parse({
1309
+ path: nativeIdentity(attribution),
1310
+ reason: entry.contentOmitted,
1311
+ bytes: entry.sizeBytes,
1312
+ ...nativeDigest(entry.sha256) === null ? {} : { sha256: nativeDigest(entry.sha256) },
1313
+ attribution
1314
+ }));
1315
+ continue;
1316
+ }
1276
1317
  const parsed = fileSchema.safeParse({
1277
1318
  path: nativeIdentity(attribution),
1278
1319
  bytes: entry.sizeBytes,
@@ -1289,15 +1330,20 @@ function retainedCapture(receipt, harness) {
1289
1330
  missing.push(`${nativeIdentity(attribution)}: ${reason}`);
1290
1331
  }
1291
1332
  }
1292
- for (const entry of session.nativeStore.excludedPaths) skipped.push({
1293
- path: nativeIdentity({
1333
+ for (const entry of session.nativeStore.excludedPaths) {
1334
+ const attribution = {
1294
1335
  providerSessionId: session.id,
1295
1336
  ...entry.sourceId === void 0 ? {} : { sourceId: entry.sourceId },
1296
1337
  rootScope: entry.rootScope,
1297
1338
  nativePath: entry.path
1298
- }),
1299
- reason: entry.reason
1300
- });
1339
+ };
1340
+ omitted.push({
1341
+ path: nativeIdentity(attribution),
1342
+ reason: entry.reason,
1343
+ bytes: entry.sizeBytes,
1344
+ attribution
1345
+ });
1346
+ }
1301
1347
  }
1302
1348
  if (files.length === 0) missing.push("No native files declared by provider capture");
1303
1349
  const descriptor = parseRetainedHarnessTranscript({
@@ -1315,6 +1361,7 @@ function retainedCapture(receipt, harness) {
1315
1361
  },
1316
1362
  files,
1317
1363
  skipped,
1364
+ ...omitted.length ? { omitted } : {},
1318
1365
  missing
1319
1366
  });
1320
1367
  if (files.length === 0) return deepFreezeCandidate({
@@ -1422,7 +1469,8 @@ async function resolveHarnessTranscriptCapture(capture, options = {}) {
1422
1469
  files.push({
1423
1470
  path: file.path,
1424
1471
  bytes: file.bytes,
1425
- content
1472
+ content,
1473
+ attribution: file.attribution
1426
1474
  });
1427
1475
  } catch {
1428
1476
  skipped.push({
@@ -1436,69 +1484,23 @@ async function resolveHarnessTranscriptCapture(capture, options = {}) {
1436
1484
  harness: descriptor.harness,
1437
1485
  source: descriptor.source,
1438
1486
  files,
1439
- skipped
1487
+ skipped,
1488
+ ...descriptor.omitted ? { omitted: descriptor.omitted } : {}
1440
1489
  });
1441
1490
  }
1442
- /** Credential-shaped paths are refused even when a producer lists them. */
1443
- const HARNESS_TRANSCRIPT_DENY = /(^|\/)(auth\.json|\.credentials\.json|credentials|\.netrc|\.env(\..*)?|secrets?(\.|$)|.*\.(pem|key|p12|pfx)|id_[a-z0-9_]+)$/iu;
1444
- /** Verify a bound native family without owning a store, filesystem layout or native parser. */
1445
- async function readBoundHarnessSessions(input) {
1446
- const files = [];
1447
- const sessions = /* @__PURE__ */ new Map();
1448
- const parents = /* @__PURE__ */ new Map();
1449
- const paths = /* @__PURE__ */ new Set();
1450
- const pathBytes = workspaceLimits(void 0).maxPathBytes;
1451
- const pending = [input.nativeSessionId];
1452
- let total = 0;
1453
- while (pending.length) {
1454
- const id = pending.shift();
1455
- if (sessions.has(id)) continue;
1456
- const candidates = input.files.filter((file) => file.nativeSessionId === id);
1457
- if (!candidates.length) throw new ValidationError("The exact native session or a recorded child was not retained");
1458
- for (const file of candidates) {
1459
- input.signal?.throwIfAborted();
1460
- if (files.length >= HARNESS_TRANSCRIPT_READ_LIMITS.maxFiles) throw new ValidationError("Native file count exceeds the capture bound");
1461
- safeArchivePath(file.path, pathBytes);
1462
- if (HARNESS_TRANSCRIPT_DENY.test(file.path) || paths.has(file.path)) throw new ValidationError("Native file path is denied or repeated");
1463
- paths.add(file.path);
1464
- const read = () => input.read(file, input.signal);
1465
- const bytes = input.signal ? await runAbortable(read, input.signal, "Native source read stopped") : await read();
1466
- total += bytes.byteLength;
1467
- if (bytes.byteLength > HARNESS_TRANSCRIPT_READ_LIMITS.maxFileBytes || total > HARNESS_TRANSCRIPT_READ_LIMITS.maxTotalBytes) throw new ValidationError("Native bytes exceed the capture bound");
1468
- const actual = sha256Bytes$1(bytes);
1469
- if (file.sha256 && file.sha256.replace(/^sha256:/, "") !== actual.slice(7) || file.byteLength !== void 0 && file.byteLength !== bytes.byteLength) throw new ValidationError("Captured native session bytes changed");
1470
- const session = input.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes), file);
1471
- if (session.nativeSessionId !== id || session.integrity.truncated || session.integrity.unparsedRecords || session.integrity.gaps.length) throw new ValidationError("Native session identity or integrity did not match its binding");
1472
- if (session.parentNativeSessionId && parents.has(id) && session.parentNativeSessionId !== parents.get(id)) throw new ValidationError("Native child has a different recorded parent");
1473
- const prior = files.find((value) => value.nativeSessionId === id);
1474
- if (prior && prior.sha256 !== actual) throw new ValidationError("Native session copies are ambiguous");
1475
- files.push({
1476
- path: file.path,
1477
- nativeSessionId: id,
1478
- sha256: actual,
1479
- byteLength: bytes.byteLength
1480
- });
1481
- if (!prior) sessions.set(id, session);
1482
- }
1483
- for (const child of sessions.get(id).children) {
1484
- if (parents.has(child.nativeSessionId) && parents.get(child.nativeSessionId) !== id) throw new ValidationError("Native child has ambiguous recorded parents");
1485
- parents.set(child.nativeSessionId, id);
1486
- if (!sessions.has(child.nativeSessionId)) pending.push(child.nativeSessionId);
1487
- }
1488
- }
1489
- return {
1490
- files,
1491
- sessions: [...sessions.values()]
1492
- };
1491
+ /** Compatibility entry. The shared reader owns native-family integrity; Runtime
1492
+ * retains its archive path policy, abort behavior and public error identity. */
1493
+ async function readBoundHarnessSessions$1(input) {
1494
+ return readBoundHarnessSessions({
1495
+ ...input,
1496
+ validatePath: (path) => {
1497
+ safeArchivePath(path, workspaceLimits(void 0).maxPathBytes);
1498
+ },
1499
+ failure: (message) => new ValidationError(message),
1500
+ read: (file, signal) => signal ? runAbortable(() => input.read(file, signal), signal, "Native source read stopped") : input.read(file)
1501
+ });
1493
1502
  }
1494
1503
  // src/runtime/harness-transcript.ts
1495
- /**
1496
- * Persist a harness transcript receipt beside the supervisor tool trace.
1497
- * Provider workspace retention supplies an attributed descriptor whose bytes stay in the
1498
- * original verified archive. Environments without retention use the bounded read/exec
1499
- * fallback below. Neither path embeds transcript content in settlement events.
1500
- * Readers request metadata without archive I/O, or explicitly resolve bounded text content.
1501
- */
1502
1504
  const { maxFileBytes: MAX_FILE_BYTES, maxTotalBytes: MAX_TOTAL_BYTES, maxFiles: MAX_FILES } = HARNESS_TRANSCRIPT_READ_LIMITS;
1503
1505
  /** Where each harness keeps the session files that hold the conversation. */
1504
1506
  const HARNESS_ROOTS = Object.freeze({
@@ -1946,9 +1948,9 @@ function capturedTranscript(artifact, coverageComplete) {
1946
1948
  }
1947
1949
  /** Local native bytes enter the same artifact/settlement path as every other transcript. */
1948
1950
  async function captureBoundHarnessTranscript(input) {
1949
- if (input.binding.nativeSessionId !== input.nativeSessionId || !input.binding.sessionId || !/^sha256:[a-f0-9]{64}$/.test(input.binding.profileDigest) || !input.binding.runs.length || input.binding.runs.some((run) => !run.runId || !/^sha256:[a-f0-9]{64}$/.test(run.requestDigest))) throw new ValidationError("Native capture binding is incomplete");
1951
+ if (input.binding.nativeSessionId !== input.nativeSessionId || JSON.stringify(input.binding.nativeSessionIds ?? [input.binding.nativeSessionId]) !== JSON.stringify(input.nativeSessionIds ?? [input.nativeSessionId]) || !input.binding.sessionId || !/^sha256:[a-f0-9]{64}$/.test(input.binding.profileDigest) || !input.binding.runs.length || input.binding.runs.some((run) => !run.runId || !/^sha256:[a-f0-9]{64}$/.test(run.requestDigest))) throw new ValidationError("Native capture binding is incomplete");
1950
1952
  const files = [];
1951
- await readBoundHarnessSessions({
1953
+ await readBoundHarnessSessions$1({
1952
1954
  ...input,
1953
1955
  read: async (file, signal) => {
1954
1956
  const bytes = await input.read(file, signal);
@@ -4920,7 +4922,7 @@ var SpawnEventIndex = class {
4920
4922
  if (event.kind === "admission-granted" && node.grantClock && (event.deadlineArmedAt !== node.grantClock.deadlineArmedAt || event.deadlineAt !== node.grantClock.deadlineAt)) throw new Error(`spawn journal corrupted: admission deadline changed for '${event.id}'`);
4921
4923
  }
4922
4924
  if (event.kind === "execution-evidence") {
4923
- if (!node?.spawned || !/^sha256:[0-9a-f]{64}$/.test(event.outRef)) throw new Error("spawn journal corrupted: executor evidence has no spawned node or valid content reference");
4925
+ if (!node?.spawned || !/^sha256:[0-9a-f]{64}$/.test(event.outRef) || event.attemptId !== void 0 && (typeof event.attemptId !== "string" || !event.attemptId)) throw new Error("spawn journal corrupted: executor evidence has no spawned node, valid content reference or attempt");
4924
4926
  }
4925
4927
  if (event.kind === "materialized") {
4926
4928
  if (node?.materialized) throw new Error(`spawn journal corrupted: duplicate materialization receipt for node '${event.id}' in tree '${this.root}'`);
@@ -5455,6 +5457,81 @@ function ownedTreeRootSpawn(spawn) {
5455
5457
  const { parent: _parent, ownedTreeRoot: _ownedTreeRoot, ...root } = spawn;
5456
5458
  return root;
5457
5459
  }
5460
+ // src/runtime/supervise/retained-owner-state.ts
5461
+ const owners = /* @__PURE__ */ new WeakMap();
5462
+ /** Bound native custody, read from its canonical receipts without probing another provider. */
5463
+ function scopeOwnerLiabilities(scope, events) {
5464
+ const state = owners.get(scope);
5465
+ if (!state) return {
5466
+ environmentHeld: false,
5467
+ invocationUnsettled: false,
5468
+ measuredResources: /* @__PURE__ */ new Map()
5469
+ };
5470
+ const held = /* @__PURE__ */ new Set();
5471
+ const destroyed = /* @__PURE__ */ new Set();
5472
+ const forks = /* @__PURE__ */ new Set();
5473
+ const key = (provider, id) => JSON.stringify([provider, id]);
5474
+ const forkKey = (provider, id, environmentId) => JSON.stringify([
5475
+ provider,
5476
+ id,
5477
+ environmentId ?? null
5478
+ ]);
5479
+ let invocationUnsettled = false;
5480
+ let environment;
5481
+ const measurements = /* @__PURE__ */ new Map();
5482
+ for (const event of events) {
5483
+ if (event.id !== state.args.nodeId) continue;
5484
+ if (event.kind === "execution-admitted") {
5485
+ invocationUnsettled = true;
5486
+ if (event.admission.phase === "environment") {
5487
+ environment = key(event.admission.provider, event.admission.environmentId);
5488
+ held.add(environment);
5489
+ destroyed.delete(environment);
5490
+ measurements.delete(environment);
5491
+ }
5492
+ } else if (event.kind === "execution-result") {
5493
+ invocationUnsettled = false;
5494
+ if (environment !== void 0) measurements.set(environment, new Map(Object.entries(event.spent.resources ?? {}).flatMap(([name, value]) => value.known ? [[name, value.unit]] : [])));
5495
+ } else if (event.kind === "environment-teardown" && event.destroyed) {
5496
+ held.delete(key(event.provider, event.environmentId));
5497
+ destroyed.add(key(event.provider, event.environmentId));
5498
+ } else if (event.kind === "workspace-checkpoint-fork-requested") forks.add(forkKey(event.provider, event.idempotencyKey));
5499
+ else if (event.kind === "workspace-checkpoint-fork-ready") {
5500
+ forks.delete(forkKey(event.provider, event.fork.idempotencyKey));
5501
+ forks.add(forkKey(event.provider, event.fork.idempotencyKey, event.fork.environmentId));
5502
+ } else if (event.kind === "workspace-checkpoint-fork-teardown" && event.destroyed) {
5503
+ forks.delete(forkKey(event.provider, event.fork.idempotencyKey));
5504
+ forks.delete(forkKey(event.provider, event.fork.idempotencyKey, event.fork.environmentId));
5505
+ }
5506
+ }
5507
+ const live = state.liveEnvironmentId?.();
5508
+ if (live !== void 0 && (state.provider === void 0 || !destroyed.has(key(state.provider.name, live)))) held.add(key(state.provider?.name ?? "", live));
5509
+ const measuredResources = new Map(measurements.get([...held][0] ?? "") ?? []);
5510
+ for (const reference of held) for (const [name, unit] of measuredResources) if (measurements.get(reference)?.get(name) !== unit) measuredResources.delete(name);
5511
+ if (forks.size > 0 || invocationUnsettled) measuredResources.clear();
5512
+ return {
5513
+ environmentHeld: held.size > 0 || forks.size > 0,
5514
+ invocationUnsettled,
5515
+ measuredResources
5516
+ };
5517
+ }
5518
+ function scopeRetainedOwnerContext(scope) {
5519
+ return owners.get(scope)?.context;
5520
+ }
5521
+ /** The journal tree that owns this manager turn, including nested driver children. */
5522
+ function scopeRetainedOwnerJournalRoot(scope) {
5523
+ return owners.get(scope)?.args.rootId;
5524
+ }
5525
+ /** Bind the provider that owns native stop, checkpoint and environment acknowledgements. */
5526
+ function bindScopeRetainedOwnerProvider(scope, provider) {
5527
+ const state = owners.get(scope);
5528
+ if (state) state.provider = provider;
5529
+ }
5530
+ /** Bind the resolver for the owner's current environment id. Admissions alone miss a provider that never writes an environment admission. */
5531
+ function bindScopeRetainedOwnerEnvironmentId(scope, liveEnvironmentId) {
5532
+ const state = owners.get(scope);
5533
+ if (state) state.liveEnvironmentId = liveEnvironmentId;
5534
+ }
5458
5535
  // src/runtime/supervise/retained-owner-checkpoint-requests.ts
5459
5536
  /** Reconstruct authority for this source only; a replacement cannot own its snapshots. */
5460
5537
  async function checkpointHandle(state, sourceEnvironmentId, signal) {
@@ -5670,81 +5747,6 @@ async function settleCaptureForks(state, parent) {
5670
5747
  }
5671
5748
  return unresolved;
5672
5749
  }
5673
- // src/runtime/supervise/retained-owner-state.ts
5674
- const owners = /* @__PURE__ */ new WeakMap();
5675
- /** Bound native custody, read from its canonical receipts without probing another provider. */
5676
- function scopeOwnerLiabilities(scope, events) {
5677
- const state = owners.get(scope);
5678
- if (!state) return {
5679
- environmentHeld: false,
5680
- invocationUnsettled: false,
5681
- measuredResources: /* @__PURE__ */ new Map()
5682
- };
5683
- const held = /* @__PURE__ */ new Set();
5684
- const destroyed = /* @__PURE__ */ new Set();
5685
- const forks = /* @__PURE__ */ new Set();
5686
- const key = (provider, id) => JSON.stringify([provider, id]);
5687
- const forkKey = (provider, id, environmentId) => JSON.stringify([
5688
- provider,
5689
- id,
5690
- environmentId ?? null
5691
- ]);
5692
- let invocationUnsettled = false;
5693
- let environment;
5694
- const measurements = /* @__PURE__ */ new Map();
5695
- for (const event of events) {
5696
- if (event.id !== state.args.nodeId) continue;
5697
- if (event.kind === "execution-admitted") {
5698
- invocationUnsettled = true;
5699
- if (event.admission.phase === "environment") {
5700
- environment = key(event.admission.provider, event.admission.environmentId);
5701
- held.add(environment);
5702
- destroyed.delete(environment);
5703
- measurements.delete(environment);
5704
- }
5705
- } else if (event.kind === "execution-result") {
5706
- invocationUnsettled = false;
5707
- if (environment !== void 0) measurements.set(environment, new Map(Object.entries(event.spent.resources ?? {}).flatMap(([name, value]) => value.known ? [[name, value.unit]] : [])));
5708
- } else if (event.kind === "environment-teardown" && event.destroyed) {
5709
- held.delete(key(event.provider, event.environmentId));
5710
- destroyed.add(key(event.provider, event.environmentId));
5711
- } else if (event.kind === "workspace-checkpoint-fork-requested") forks.add(forkKey(event.provider, event.idempotencyKey));
5712
- else if (event.kind === "workspace-checkpoint-fork-ready") {
5713
- forks.delete(forkKey(event.provider, event.fork.idempotencyKey));
5714
- forks.add(forkKey(event.provider, event.fork.idempotencyKey, event.fork.environmentId));
5715
- } else if (event.kind === "workspace-checkpoint-fork-teardown" && event.destroyed) {
5716
- forks.delete(forkKey(event.provider, event.fork.idempotencyKey));
5717
- forks.delete(forkKey(event.provider, event.fork.idempotencyKey, event.fork.environmentId));
5718
- }
5719
- }
5720
- const live = state.liveEnvironmentId?.();
5721
- if (live !== void 0 && (state.provider === void 0 || !destroyed.has(key(state.provider.name, live)))) held.add(key(state.provider?.name ?? "", live));
5722
- const measuredResources = new Map(measurements.get([...held][0] ?? "") ?? []);
5723
- for (const reference of held) for (const [name, unit] of measuredResources) if (measurements.get(reference)?.get(name) !== unit) measuredResources.delete(name);
5724
- if (forks.size > 0 || invocationUnsettled) measuredResources.clear();
5725
- return {
5726
- environmentHeld: held.size > 0 || forks.size > 0,
5727
- invocationUnsettled,
5728
- measuredResources
5729
- };
5730
- }
5731
- function scopeRetainedOwnerContext(scope) {
5732
- return owners.get(scope)?.context;
5733
- }
5734
- /** The journal tree that owns this manager turn, including nested driver children. */
5735
- function scopeRetainedOwnerJournalRoot(scope) {
5736
- return owners.get(scope)?.args.rootId;
5737
- }
5738
- /** Bind the provider that owns native stop, checkpoint and environment acknowledgements. */
5739
- function bindScopeRetainedOwnerProvider(scope, provider) {
5740
- const state = owners.get(scope);
5741
- if (state) state.provider = provider;
5742
- }
5743
- /** Bind the resolver for the owner's current environment id. Admissions alone miss a provider that never writes an environment admission. */
5744
- function bindScopeRetainedOwnerEnvironmentId(scope, liveEnvironmentId) {
5745
- const state = owners.get(scope);
5746
- if (state) state.liveEnvironmentId = liveEnvironmentId;
5747
- }
5748
5750
  // src/runtime/supervise/retained-owner-checkpoint-rotation.ts
5749
5751
  /** Checkpoint after a coordination call once the last one is older than {@link WORKSPACE_CHECKPOINT_MIN_INTERVAL_MS}. It never delays the call, and a failure leaves the previous restore point. */
5750
5752
  function noteScopeRetainedOwnerCoordination(scope) {
@@ -6341,6 +6343,35 @@ async function scopeRetainedOwnerSettled(scope) {
6341
6343
  await scopeRetainedOwnerTurnEnded(scope);
6342
6344
  await state.releasing?.catch(() => void 0);
6343
6345
  }
6346
+ // src/runtime/supervise/harness-transcript-evidence.ts
6347
+ /**
6348
+ * Bind one capture to the input and output of the exact attempt that produced it. The record holds
6349
+ * content only; the attempt id names the journal row that cites it, so equal evidence keeps one
6350
+ * content address across runs.
6351
+ */
6352
+ async function recordHarnessTranscriptEvidence(args) {
6353
+ const task = detachedSnapshot(args.task, "execution transcript input");
6354
+ const taskRef = contentAddress(task);
6355
+ await args.blobs.put(taskRef, task);
6356
+ const { attemptId, ...node } = args.node;
6357
+ const evidence = {
6358
+ kind: "harness-transcript",
6359
+ schemaVersion: 1,
6360
+ node,
6361
+ taskRef,
6362
+ ...args.outRef === void 0 ? {} : { outRef: args.outRef },
6363
+ harnessTranscript: args.harnessTranscript
6364
+ };
6365
+ for (const rootId of new Set(args.roots)) await executorEvidenceWriter({
6366
+ journal: args.journal,
6367
+ blobs: args.blobs,
6368
+ rootId,
6369
+ nodeId: args.node.nodeId,
6370
+ attemptId,
6371
+ nextSequence: () => 0,
6372
+ now: args.now
6373
+ })(evidence);
6374
+ }
6344
6375
  // src/runtime/supervise/provider-visible-profile.ts
6345
6376
  /** Runtime-owned coordination is mounted under this MCP alias. */
6346
6377
  const coordinationMcpAlias = "agent-runtime-coordination";
@@ -6529,6 +6560,49 @@ function scopeOwnerExecutorNodeContext(scope) {
6529
6560
  attemptId: state.attemptId
6530
6561
  });
6531
6562
  }
6563
+ /**
6564
+ * @internal Hold this scope's settlement until a driver attempt's transcript record finishes. A
6565
+ * cancelled run settles without waiting for its root driver; the hold keeps that record from
6566
+ * landing after the run has returned. Call the returned release once the attempt is done.
6567
+ */
6568
+ function holdScopeOwnerTranscript(scope) {
6569
+ const state = ownerMaterializationStates.get(scope);
6570
+ if (state === void 0) return () => {};
6571
+ let release;
6572
+ const hold = new Promise((resolve) => {
6573
+ release = resolve;
6574
+ });
6575
+ state.transcriptHolds ??= /* @__PURE__ */ new Set();
6576
+ const holds = state.transcriptHolds;
6577
+ holds.add(hold);
6578
+ return () => {
6579
+ holds.delete(hold);
6580
+ release();
6581
+ };
6582
+ }
6583
+ /** Retain every manager attempt's native evidence without accepting another execution result. */
6584
+ async function recordScopeOwnerHarnessTranscript(scope, task, capture, result) {
6585
+ const state = ownerMaterializationState(scope);
6586
+ const node = scopeOwnerExecutorNodeContext(scope);
6587
+ const input = detachedSnapshot(task, "manager execution input");
6588
+ await serializedOwnerWrite(state, async () => {
6589
+ const output = result?.out === void 0 ? void 0 : detachedSnapshot(result.out, "manager execution output");
6590
+ const outRef = output === void 0 ? void 0 : contentAddress(output);
6591
+ if (outRef !== void 0) await state.blobs.put(outRef, output);
6592
+ const harnessTranscript = await persistHarnessTranscript(capture, state.blobs);
6593
+ await recordHarnessTranscriptEvidence({
6594
+ node,
6595
+ task: input,
6596
+ ...outRef === void 0 ? {} : { outRef },
6597
+ harnessTranscript,
6598
+ journal: state.journal,
6599
+ roots: [state.root, state.retainedRoot],
6600
+ blobs: state.blobs,
6601
+ now: state.now
6602
+ });
6603
+ if (harnessTranscript.status === "unavailable" && capture.status !== "unavailable") throw new ValidationError("manager transcript capture could not be persisted");
6604
+ });
6605
+ }
6532
6606
  /** Reuse a committed owner invocation without inventing another provider attempt. @internal */
6533
6607
  async function restoreScopeOwnerAcceptedExecution(scope) {
6534
6608
  const state = ownerMaterializationState(scope);
@@ -6557,6 +6631,8 @@ async function restoreScopeOwnerAcceptedExecution(scope) {
6557
6631
  async function finalizeScopeOwnerMaterialization(scope) {
6558
6632
  const state = ownerMaterializationStates.get(scope);
6559
6633
  if (state === void 0) return;
6634
+ const holds = state.transcriptHolds;
6635
+ if (holds?.size) await settleHarnessTranscript({ harnessTranscriptSettled: () => Promise.all(holds).then(() => void 0) });
6560
6636
  await serializedOwnerWrite(state, () => finalizeOwnerMaterialization(state));
6561
6637
  }
6562
6638
  async function finalizeOwnerMaterialization(state) {
@@ -6802,6 +6878,10 @@ function registerScopeRetainedOwner(scope, args) {
6802
6878
  now: args.now,
6803
6879
  traceRoots
6804
6880
  }),
6881
+ onHarnessTranscript: async (task, capture, result) => {
6882
+ if (!ownerMaterializationStates.has(scope)) return;
6883
+ await recordScopeOwnerHarnessTranscript(scope, task, capture, result);
6884
+ },
6805
6885
  onEndOfTurnWork: (work) => {
6806
6886
  preemptRotationCaptures(state);
6807
6887
  const prior = state.turnEnd;
@@ -7046,8 +7126,9 @@ function retainedOwnerReleaseRetriable(scope) {
7046
7126
  /** One budget for every checkpoint lookup, delete and fork cleanup this release starts. Work cut short keeps its checkpoint and source. */
7047
7127
  const RELEASE_CHECKPOINT_CAPTURES_MS = 9e5;
7048
7128
  /** A release's wait for its destroys; a delete grows with the retained workspace it seals (Sandbox
7049
- * 2026-11-11: 2-4 s at 1 MB, 30 s at 300 MB, 72 s at 1 GB). A later release joins the rest. */
7050
- const RELEASE_DESTROY_MS = 3e5;
7129
+ * 2026-11-11: 2-4 s at 1 MB, 30 s at 300 MB, 72 s at 1 GB). A later release joins the rest. A
7130
+ * settling run's whole teardown fits in one such wait, so a cancel settles in about this long. */
7131
+ const RELEASE_DESTROY_MS = 9e4;
7051
7132
  /**
7052
7133
  * Release the owner's environment once no turn of it will run again. A second call joins the one
7053
7134
  * in flight. The end-of-turn capture finishes before destroy. `capturesMs` bounds checkpoint work.
@@ -7098,9 +7179,18 @@ async function releaseOwnerEnvironment(state, provider, capturesMs, destroyMs) {
7098
7179
  }
7099
7180
  const forksUnresolved = await settleCaptureForks(state, captures.signal);
7100
7181
  for (const { event } of checkpointFailures) pendingSources.add(event.environmentId);
7101
- const destroyDeadline = AbortSignal.timeout(destroyMs);
7102
- const destroys = new Map([...environments].filter((id) => !released.has(id) && !retentionFailures.has(id) && !pendingSources.has(id)).map((id) => {
7103
- const wait = runAbortable(() => ownerEnvironmentDestroy(state, provider, id), destroyDeadline, () => /* @__PURE__ */ new Error(`destroy still running after ${destroyMs} ms`));
7182
+ const held = state.held ??= /* @__PURE__ */ new Map();
7183
+ const asking = [...environments].filter((id) => !released.has(id) && !retentionFailures.has(id) && !pendingSources.has(id) && !held.has(id));
7184
+ const clock = state.releaseClock;
7185
+ if (clock !== void 0 && asking.length > 0) {
7186
+ clock.startedAt ??= Date.now();
7187
+ state.releaseDestroysAt ??= Date.now();
7188
+ }
7189
+ const left = clock?.startedAt === void 0 ? Number.POSITIVE_INFINITY : Math.max(clock.startedAt + clock.windowMs, (state.releaseDestroysAt ?? Date.now()) + destroyMs) - Date.now();
7190
+ const waitMs = Math.max(0, Math.min(destroyMs, left));
7191
+ const destroyDeadline = AbortSignal.timeout(waitMs);
7192
+ const destroys = new Map(asking.map((id) => {
7193
+ const wait = runAbortable(() => ownerEnvironmentDestroy(state, provider, id), destroyDeadline, () => /* @__PURE__ */ new Error(`destroy still running after ${waitMs} ms`));
7104
7194
  wait.catch(() => void 0);
7105
7195
  return [id, wait];
7106
7196
  }));
@@ -7108,24 +7198,33 @@ async function releaseOwnerEnvironment(state, provider, capturesMs, destroyMs) {
7108
7198
  if (released.has(environmentId)) continue;
7109
7199
  let destroyed = false;
7110
7200
  let detail;
7111
- const retentionReason = retentionFailures.get(environmentId);
7201
+ const asked = destroys.get(environmentId);
7202
+ const heldBefore = asked === void 0 ? held.get(environmentId) : void 0;
7203
+ const retentionReason = retentionFailures.get(environmentId) ?? heldBefore;
7112
7204
  const nativeHold = retentionReason?.startsWith("native session copy incomplete:") === true;
7113
7205
  if (retentionReason !== void 0 || pendingSources.has(environmentId)) {
7114
7206
  detail = !nativeHold && pendingSources.has(environmentId) ? "checkpoint cleanup unresolved: source preserved for exact lookup and cleanup" : retentionReason;
7115
7207
  preserved.push(environmentId);
7116
7208
  lastDetail = detail;
7117
7209
  } else try {
7118
- await destroys.get(environmentId);
7210
+ await asked;
7119
7211
  destroyed = true;
7120
7212
  } catch (error) {
7121
- detail = `retained owner environment cleanup was not confirmed: ${errMessage(error).slice(0, 500)}`;
7122
- unconfirmed.push(environmentId);
7213
+ detail = held.get(environmentId) ?? `retained owner environment cleanup was not confirmed: ${errMessage(error).slice(0, 500)}`;
7123
7214
  lastDetail = detail;
7124
- if (!(error instanceof PermanentReleaseRefusal)) retriable = true;
7215
+ if (held.has(environmentId)) preserved.push(environmentId);
7216
+ else {
7217
+ unconfirmed.push(environmentId);
7218
+ if (!(error instanceof PermanentReleaseRefusal)) retriable = true;
7219
+ }
7125
7220
  }
7126
7221
  if (!destroyed && !state.destroys?.has(environmentId)) {
7127
7222
  const runs = unsettledOwnerRuns(events, args.nodeId, environmentId);
7128
- if (runs.length > 0) {
7223
+ if (runs.length > 0 && held.has(environmentId)) {
7224
+ const stops = runs.map((run) => `native execution ${run.executionId} ${HELD_STOP}; ${NATIVE_STOP_UNCONFIRMED}`);
7225
+ detail = `${detail}; ${stops.join("; ")}`;
7226
+ lastDetail = detail;
7227
+ } else if (runs.length > 0) {
7129
7228
  const stops = await Promise.all(runs.map((controlRef) => stopRetainedNativeExecution({
7130
7229
  provider,
7131
7230
  controlRef,
@@ -7189,6 +7288,15 @@ async function releaseOwnerEnvironment(state, provider, capturesMs, destroyMs) {
7189
7288
  }, ...checkpointTeardowns] : checkpointTeardowns;
7190
7289
  }
7191
7290
  var PermanentReleaseRefusal = class extends Error {};
7291
+ const HELD_STOP = "stop not attempted: its provider holds the environment under a retention hold and a reconnect would wake it";
7292
+ /**
7293
+ * A provider that keeps an environment under a retention hold refuses its delete until the hold is
7294
+ * released: 409 `RETENTION_HOLD`, or a refusal whose message names the hold. The holder, not this
7295
+ * release, decides when the environment goes.
7296
+ */
7297
+ function retentionHoldRefusal(error) {
7298
+ return causeChain(error).some((cause) => Reflect.get(cause, "code") === "RETENTION_HOLD") || /\bunder retention hold\b/iu.test(errMessage(error));
7299
+ }
7192
7300
  /** A destroy in flight this long is presumed lost, and the next release asks the provider again. */
7193
7301
  const RELEASE_DESTROY_ABANDONED_MS = 9e5;
7194
7302
  /**
@@ -7213,8 +7321,9 @@ function ownerEnvironmentDestroy(state, provider, environmentId) {
7213
7321
  since: Date.now()
7214
7322
  };
7215
7323
  destroys.set(environmentId, entry);
7216
- destroy.catch(() => {
7324
+ destroy.catch((error) => {
7217
7325
  if (destroys.get(environmentId) === entry) destroys.delete(environmentId);
7326
+ if (retentionHoldRefusal(error)) (state.held ??= /* @__PURE__ */ new Map()).set(environmentId, `environment kept: its provider refuses deletion under a retention hold (${errMessage(error).slice(0, 500)})`);
7218
7327
  });
7219
7328
  return destroy;
7220
7329
  }
@@ -7745,17 +7854,34 @@ async function startScopeRecoveries(scope) {
7745
7854
  * root is live, and never on a resumable interruption, since the open slot and the live
7746
7855
  * environment are exactly what a resume recovers. One `environment-teardown` receipt is journaled
7747
7856
  * per environment, on this scope's own tree; a nested manager reaches its children through
7748
- * `Executor.releaseRetained`, and its nested scope journals theirs.
7857
+ * `Executor.releaseRetained`, and its nested scope journals theirs. The children, the nested
7858
+ * managers and this scope's own owner release at once, so a tree waits one destroy wait, not one
7859
+ * per level.
7749
7860
  */
7750
7861
  async function releaseRetainedEnvironments(scope) {
7751
7862
  releasingScopes.add(scope);
7752
- const release = retainedReleasers.get(scope);
7753
- if (release) await release();
7754
- await releaseNestedManagerEnvironments(scope);
7755
- ownerUnconfirmedByScope.set(scope, await releaseScopeRetainedOwnerEnvironment(scope));
7756
- await scopeSeatAccountingUpdates.get(scope)?.();
7863
+ await releaseScope(scope, true);
7757
7864
  return unconfirmedTeardowns(scope);
7758
7865
  }
7866
+ /** Release a scope's retained children and its own owner, and with `nested` its nested managers'
7867
+ * trees, all at once. */
7868
+ async function releaseScope(scope, nested) {
7869
+ await Promise.all([
7870
+ retainedReleasers.get(scope)?.(),
7871
+ nested && releaseNestedManagerEnvironments(scope),
7872
+ releaseScopeRetainedOwnerEnvironment(scope).then((unconfirmed) => {
7873
+ ownerUnconfirmedByScope.set(scope, unconfirmed);
7874
+ })
7875
+ ]);
7876
+ await scopeSeatAccountingUpdates.get(scope)?.();
7877
+ }
7878
+ /** @internal Bound every owner release in this scope's tree by the settling run's one teardown
7879
+ * clock, so no destroy wait at any level outlasts it. */
7880
+ function boundRetainedReleases(scope, clock) {
7881
+ const owner = owners.get(scope);
7882
+ if (owner !== void 0) owner.releaseClock = clock;
7883
+ for (const nested of nestedManagerScopes(scope)) boundRetainedReleases(nested, clock);
7884
+ }
7759
7885
  /** The manager scopes this scope's children own, read live. */
7760
7886
  function nestedManagerScopes(scope) {
7761
7887
  return nestedManagerScopeReaders.get(scope)?.() ?? [];
@@ -7775,15 +7901,8 @@ async function releaseNestedManagerEnvironments(scope) {
7775
7901
  * last end-of-turn capture, so it runs beside the settlement; later calls join it.
7776
7902
  */
7777
7903
  function releaseManagerEnvironment(scope) {
7778
- let release = managerEnvironmentReleases.get(scope);
7779
- if (release === void 0) {
7780
- release = Promise.all([retainedReleasers.get(scope)?.(), releaseScopeRetainedOwnerEnvironment(scope).then((unconfirmed) => {
7781
- ownerUnconfirmedByScope.set(scope, unconfirmed);
7782
- })]).then(async () => {
7783
- await scopeSeatAccountingUpdates.get(scope)?.();
7784
- });
7785
- managerEnvironmentReleases.set(scope, release);
7786
- }
7904
+ const release = managerEnvironmentReleases.get(scope) ?? releaseScope(scope, false);
7905
+ managerEnvironmentReleases.set(scope, release);
7787
7906
  return release;
7788
7907
  }
7789
7908
  /**
@@ -8875,156 +8994,12 @@ async function appendNodeMaterialization(args, id, seq, receipt, binding, now) {
8875
8994
  at
8876
8995
  });
8877
8996
  }
8878
- // src/runtime/supervise/scope-child-retention.ts
8879
- /** Own the retained child invocation and its durable writes. */
8880
- function createChildRetention({ args, controller, id, ordinal, attemptId, identity, recovery, opts, now, traceRoots, markRecoveryReady, admission, readLive, completeEvidence }) {
8881
- const retainedWrites = /* @__PURE__ */ new Set();
8882
- let retainedWritesClosed = false;
8883
- const retainedWrite = (write) => {
8884
- controller.signal.throwIfAborted();
8885
- if (retainedWritesClosed) throw new ValidationError("retained child writer is closed");
8886
- const pending = write();
8887
- retainedWrites.add(pending);
8888
- pending.then(() => retainedWrites.delete(pending), () => retainedWrites.delete(pending));
8889
- return pending;
8890
- };
8891
- const closeRetainedWrites = async () => {
8892
- retainedWritesClosed = true;
8893
- await Promise.allSettled([...retainedWrites]);
8894
- };
8895
- let admissions = [...recovery?.admissions ?? []];
8896
- let inputSeq = recovery?.continuation?.inputSeq ?? ordinal;
8897
- let pauseSeq = 0;
8898
- const onAdmission = (admission) => retainedWrite(async () => {
8899
- controller.signal.throwIfAborted();
8900
- const existing = admissions.find((record) => record.phase === admission.phase);
8901
- if (existing) {
8902
- if (contentAddress(existing) !== contentAddress(admission)) throw new ValidationError("scope retained admission conflicts with its committed phase");
8903
- return;
8904
- }
8905
- if (identity?.taskDigest === void 0) throw new ValidationError("retained execution requires a canonical task identity");
8906
- await args.journal.appendEvent(args.root, {
8907
- kind: "execution-admitted",
8908
- id,
8909
- admission: detachedSnapshot(admission, "retained admission"),
8910
- seq: ordinal,
8911
- at: new Date(now()).toISOString()
8912
- });
8913
- admissions.push(detachedSnapshot(admission, "retained admission"));
8914
- notifyExecutionAdmitted(args.hooks, args.root, id, admission, now, attemptId);
8915
- readLive().recoveryPending = true;
8916
- controller.signal.throwIfAborted();
8917
- });
8918
- const onResult = (result) => retainedWrite(async () => {
8919
- controller.signal.throwIfAborted();
8920
- assertValidSpend(result.spent, "retained executor result");
8921
- executorFailureReason(result);
8922
- await completeEvidence();
8923
- const outRef = contentAddress(result.out);
8924
- await args.blobs.put(outRef, result.out);
8925
- controller.signal.throwIfAborted();
8926
- const traceRoot = await traceRoots.write(outRef, result);
8927
- await args.journal.appendEvent(args.root, {
8928
- kind: "execution-result",
8929
- id,
8930
- outRef,
8931
- ...traceRoot === void 0 ? {} : { traceRoot },
8932
- spent: result.spent,
8933
- ...result.verdict ? { verdict: result.verdict } : {},
8934
- ...result.outcome ? { outcome: result.outcome } : {},
8935
- ...result.outputFormat === void 0 ? {} : { outputFormat: result.outputFormat },
8936
- seq: ordinal,
8937
- at: new Date(now()).toISOString()
8938
- });
8939
- readLive().acceptedResult = detachedSnapshot({
8940
- ...result,
8941
- outRef
8942
- }, "accepted retained child result");
8943
- readLive().recoveryPending = false;
8944
- });
8945
- const onPause = (pause) => retainedWrite(async () => {
8946
- await args.journal.appendEvent(args.root, {
8947
- kind: "paused",
8948
- id,
8949
- ...pause,
8950
- seq: pauseSeq++,
8951
- at: new Date(now()).toISOString()
8952
- });
8953
- });
8954
- const holdMs = args.budgetStopHoldMs ?? 6e5;
8955
- const holdOnSettle = opts.key !== void 0 && holdMs > 0 ? (spent) => overBudget(opts.budget, spent) || admission.deadlineAtMs !== void 0 && now() > admission.deadlineAtMs : void 0;
8956
- const retainedContext = (continuing) => ({
8957
- ...continuing === void 0 ? {} : {
8958
- executionId: continuing.executionId,
8959
- priorSession: continuing.priorSession,
8960
- ...continuing.priorSpent === void 0 ? {} : { priorSpent: continuing.priorSpent }
8961
- },
8962
- admissions,
8963
- ...holdOnSettle === void 0 ? {} : { holdOnSettle },
8964
- ...markRecoveryReady && continuing === void 0 ? { onReady: markRecoveryReady } : {},
8965
- onAdmission,
8966
- onResult,
8967
- onEvidence: executorEvidenceWriter({
8968
- journal: args.journal,
8969
- blobs: args.blobs,
8970
- rootId: args.root,
8971
- nodeId: id,
8972
- nextSequence: () => ordinal,
8973
- now,
8974
- traceRoots
8975
- }),
8976
- onPause,
8977
- continueInvocation: async (nextTask) => {
8978
- controller.signal.throwIfAborted();
8979
- const live = readLive();
8980
- if (live.acceptedResult === void 0) throw new ValidationError("scope: a retained child continues only after its invocation committed a result");
8981
- const environment = admissions.find((record) => record.phase === "environment");
8982
- if (environment?.phase !== "environment") throw new ValidationError("scope: a retained child continues only in an environment it was admitted to");
8983
- const snapshot = detachedSnapshot(nextTask, "retained child continuation");
8984
- const taskRef = contentAddress(snapshot);
8985
- const nextSeq = inputSeq + 1;
8986
- await retainedWrite(async () => {
8987
- await args.blobs.put(taskRef, snapshot);
8988
- controller.signal.throwIfAborted();
8989
- await args.journal.appendEvent(args.root, {
8990
- kind: "execution-input",
8991
- id,
8992
- taskRef,
8993
- seq: nextSeq,
8994
- at: new Date(now()).toISOString()
8995
- });
8996
- });
8997
- inputSeq = nextSeq;
8998
- admissions = [];
8999
- const priorSpent = live.acceptedResult.spent;
9000
- live.acceptedResult = void 0;
9001
- return retainedContext({
9002
- executionId: leafContinuationExecutionId(id, nextSeq),
9003
- priorSession: environment,
9004
- priorSpent
9005
- });
9006
- }
9007
- });
9008
- return {
9009
- retainedContext,
9010
- closeRetainedWrites,
9011
- holdMs,
9012
- readEnvironmentAdmission: () => {
9013
- const admission = admissions.find((record) => record.phase === "environment");
9014
- return admission?.phase === "environment" ? admission : void 0;
9015
- }
9016
- };
9017
- }
9018
- /** Whether a settled spend exceeds the budget it was given, by the channels the pool reconciles. */
9019
- function overBudget(budget, spent) {
9020
- return budget.maxTokens !== void 0 && chargedTokens(spent.tokens) > budget.maxTokens || budget.maxIterations !== void 0 && spent.iterations > budget.maxIterations || budget.maxUsd !== void 0 && spent.usdKnown !== false && spent.usd > budget.maxUsd;
9021
- }
9022
- // src/durable/spawn-journal/record-events.ts
9023
- /** Decode historical envelopes; readers own event validation. @internal */
9024
- function spawnJournalRecordEvents(record, invalid = "throw") {
9025
- const corrupt = (reason) => {
9026
- if (invalid === "skip") return [];
9027
- throw new Error(`spawn journal corrupted: ${reason}`);
8997
+ // src/durable/spawn-journal/record-events.ts
8998
+ /** Decode historical envelopes; readers own event validation. @internal */
8999
+ function spawnJournalRecordEvents(record, invalid = "throw") {
9000
+ const corrupt = (reason) => {
9001
+ if (invalid === "skip") return [];
9002
+ throw new Error(`spawn journal corrupted: ${reason}`);
9028
9003
  };
9029
9004
  if (!isRecord(record)) return corrupt("record must be an object");
9030
9005
  if (record.kind === "begin") return [];
@@ -10148,6 +10123,10 @@ var ChildExecutionAttempt = class {
10148
10123
  }
10149
10124
  async persistTranscript() {
10150
10125
  this.transcriptEvidence ??= await persistHarnessTranscript(readHarnessTranscript(this.executor), this.blobs);
10126
+ if (!this.live.transcriptEvidenceRecorded) {
10127
+ await this.live.recordTranscriptEvidence?.(this.transcriptEvidence, this.retainedOutputRef);
10128
+ this.live.transcriptEvidenceRecorded = true;
10129
+ }
10151
10130
  return this.transcriptEvidence;
10152
10131
  }
10153
10132
  async teardown(grace) {
@@ -12346,12 +12325,23 @@ var WorkerEvents = class {
12346
12325
  * row, its spawn journal record and hook, and the settlement chain that closes it. `scope-spawn`
12347
12326
  * sequences them; each builder here owns one record.
12348
12327
  */
12328
+ /** The child's node coordinates, shared by its executor context and its transcript evidence. */
12329
+ function childNode(args, child) {
12330
+ return {
12331
+ rootId: args.root,
12332
+ parentId: args.parentId,
12333
+ nodeId: child.id,
12334
+ depth: args.depth + 1,
12335
+ attemptId: child.attemptId,
12336
+ ...child.identity ? { identity: child.identity } : {}
12337
+ };
12338
+ }
12349
12339
  /**
12350
12340
  * Seed THIS scope's keystone deps into the child's `ExecutorContext.seams`, so a DRIVER child can
12351
12341
  * mount a nested `Scope` at `depth+1` over a pool backed by THIS reservation. Leaves ignore it.
12352
12342
  */
12353
12343
  function childExecutorContext(args, child, controller, seams) {
12354
- const { id, identity, recovery, continuing, opts } = child;
12344
+ const { id, recovery, continuing, opts } = child;
12355
12345
  const interactiveBindingDir = args.interactiveBindingDir;
12356
12346
  const observation = createExecutorObservation(args.hooks, {
12357
12347
  rootId: args.root,
@@ -12361,14 +12351,7 @@ function childExecutorContext(args, child, controller, seams) {
12361
12351
  }, seams.onProgress);
12362
12352
  return {
12363
12353
  signal: controller.signal,
12364
- node: {
12365
- rootId: args.root,
12366
- parentId: args.parentId,
12367
- nodeId: id,
12368
- depth: args.depth + 1,
12369
- attemptId: child.attemptId,
12370
- ...identity ? { identity } : {}
12371
- },
12354
+ node: childNode(args, child),
12372
12355
  seams: {
12373
12356
  ...args.seams,
12374
12357
  [executorObservationSeamKey]: observation,
@@ -12436,9 +12419,20 @@ function liveChildRecord(args, child, executor, start) {
12436
12419
  attemptId: child.attemptId
12437
12420
  }, () => {}))),
12438
12421
  id,
12422
+ executionTask: child.task,
12439
12423
  status: start.granted ? "acquiring" : "queued",
12440
12424
  runtime: executor.runtime,
12441
12425
  ...ownedTreeRoot === void 0 ? {} : { ownedTreeRoot },
12426
+ ...ownedTreeRoot === void 0 && executor.harnessTranscript ? { recordTranscriptEvidence: (harnessTranscript, outRef) => recordHarnessTranscriptEvidence({
12427
+ node: childNode(args, child),
12428
+ task: live.executionTask,
12429
+ harnessTranscript,
12430
+ ...outRef === void 0 ? {} : { outRef },
12431
+ journal: args.journal,
12432
+ roots: [args.root],
12433
+ blobs: args.blobs,
12434
+ now
12435
+ }) } : {},
12442
12436
  ...identity ? { identity } : {},
12443
12437
  ...modelSubstitution === void 0 ? {} : { modelSubstitution },
12444
12438
  budget: opts.budget,
@@ -12621,6 +12615,171 @@ async function resolveChildSettlement(live, ran, interactiveBindingCommitted, ho
12621
12615
  }
12622
12616
  return resolution;
12623
12617
  }
12618
+ // src/runtime/supervise/scope-child-retention.ts
12619
+ /** Own the retained child invocation and its durable writes. */
12620
+ function createChildRetention({ args, controller, id, ordinal, attemptId, identity, recovery, opts, now, traceRoots, markRecoveryReady, admission, readLive, completeEvidence }) {
12621
+ const retainedWrites = /* @__PURE__ */ new Set();
12622
+ let retainedWritesClosed = false;
12623
+ const retainedWrite = (write) => {
12624
+ controller.signal.throwIfAborted();
12625
+ if (retainedWritesClosed) throw new ValidationError("retained child writer is closed");
12626
+ const pending = write();
12627
+ retainedWrites.add(pending);
12628
+ pending.then(() => retainedWrites.delete(pending), () => retainedWrites.delete(pending));
12629
+ return pending;
12630
+ };
12631
+ const closeRetainedWrites = async () => {
12632
+ retainedWritesClosed = true;
12633
+ await Promise.allSettled([...retainedWrites]);
12634
+ };
12635
+ let admissions = [...recovery?.admissions ?? []];
12636
+ let inputSeq = recovery?.continuation?.inputSeq ?? ordinal;
12637
+ let pauseSeq = 0;
12638
+ const onAdmission = (admission) => retainedWrite(async () => {
12639
+ controller.signal.throwIfAborted();
12640
+ const existing = admissions.find((record) => record.phase === admission.phase);
12641
+ if (existing) {
12642
+ if (contentAddress(existing) !== contentAddress(admission)) throw new ValidationError("scope retained admission conflicts with its committed phase");
12643
+ return;
12644
+ }
12645
+ if (identity?.taskDigest === void 0) throw new ValidationError("retained execution requires a canonical task identity");
12646
+ await args.journal.appendEvent(args.root, {
12647
+ kind: "execution-admitted",
12648
+ id,
12649
+ admission: detachedSnapshot(admission, "retained admission"),
12650
+ seq: ordinal,
12651
+ at: new Date(now()).toISOString()
12652
+ });
12653
+ admissions.push(detachedSnapshot(admission, "retained admission"));
12654
+ notifyExecutionAdmitted(args.hooks, args.root, id, admission, now, attemptId);
12655
+ readLive().recoveryPending = true;
12656
+ controller.signal.throwIfAborted();
12657
+ });
12658
+ const onResult = (result) => retainedWrite(async () => {
12659
+ controller.signal.throwIfAborted();
12660
+ assertValidSpend(result.spent, "retained executor result");
12661
+ executorFailureReason(result);
12662
+ await completeEvidence();
12663
+ const outRef = contentAddress(result.out);
12664
+ await args.blobs.put(outRef, result.out);
12665
+ controller.signal.throwIfAborted();
12666
+ const traceRoot = await traceRoots.write(outRef, result);
12667
+ await args.journal.appendEvent(args.root, {
12668
+ kind: "execution-result",
12669
+ id,
12670
+ outRef,
12671
+ ...traceRoot === void 0 ? {} : { traceRoot },
12672
+ spent: result.spent,
12673
+ ...result.verdict ? { verdict: result.verdict } : {},
12674
+ ...result.outcome ? { outcome: result.outcome } : {},
12675
+ ...result.outputFormat === void 0 ? {} : { outputFormat: result.outputFormat },
12676
+ seq: ordinal,
12677
+ at: new Date(now()).toISOString()
12678
+ });
12679
+ readLive().acceptedResult = detachedSnapshot({
12680
+ ...result,
12681
+ outRef
12682
+ }, "accepted retained child result");
12683
+ readLive().recoveryPending = false;
12684
+ });
12685
+ const onPause = (pause) => retainedWrite(async () => {
12686
+ await args.journal.appendEvent(args.root, {
12687
+ kind: "paused",
12688
+ id,
12689
+ ...pause,
12690
+ seq: pauseSeq++,
12691
+ at: new Date(now()).toISOString()
12692
+ });
12693
+ });
12694
+ const holdMs = args.budgetStopHoldMs ?? 6e5;
12695
+ const holdOnSettle = opts.key !== void 0 && holdMs > 0 ? (spent) => overBudget(opts.budget, spent) || admission.deadlineAtMs !== void 0 && now() > admission.deadlineAtMs : void 0;
12696
+ const retainedContext = (continuing) => ({
12697
+ ...continuing === void 0 ? {} : {
12698
+ executionId: continuing.executionId,
12699
+ priorSession: continuing.priorSession,
12700
+ ...continuing.priorSpent === void 0 ? {} : { priorSpent: continuing.priorSpent }
12701
+ },
12702
+ admissions,
12703
+ ...holdOnSettle === void 0 ? {} : { holdOnSettle },
12704
+ ...markRecoveryReady && continuing === void 0 ? { onReady: markRecoveryReady } : {},
12705
+ onAdmission,
12706
+ onResult,
12707
+ onEvidence: executorEvidenceWriter({
12708
+ journal: args.journal,
12709
+ blobs: args.blobs,
12710
+ rootId: args.root,
12711
+ nodeId: id,
12712
+ nextSequence: () => ordinal,
12713
+ now,
12714
+ traceRoots
12715
+ }),
12716
+ onHarnessTranscript: async (task, capture, result) => {
12717
+ const harnessTranscript = await persistHarnessTranscript(capture, args.blobs);
12718
+ await recordHarnessTranscriptEvidence({
12719
+ node: childNode(args, {
12720
+ id,
12721
+ attemptId,
12722
+ identity
12723
+ }),
12724
+ task,
12725
+ ...result?.out === void 0 ? {} : { outRef: contentAddress(result.out) },
12726
+ harnessTranscript,
12727
+ journal: args.journal,
12728
+ roots: [args.root],
12729
+ blobs: args.blobs,
12730
+ now
12731
+ });
12732
+ if (harnessTranscript.status === "unavailable" && capture.status !== "unavailable") throw new ValidationError("provider transcript capture could not be persisted");
12733
+ readLive().transcriptEvidenceRecorded = true;
12734
+ },
12735
+ onPause,
12736
+ continueInvocation: async (nextTask) => {
12737
+ controller.signal.throwIfAborted();
12738
+ const live = readLive();
12739
+ if (live.acceptedResult === void 0) throw new ValidationError("scope: a retained child continues only after its invocation committed a result");
12740
+ const environment = admissions.find((record) => record.phase === "environment");
12741
+ if (environment?.phase !== "environment") throw new ValidationError("scope: a retained child continues only in an environment it was admitted to");
12742
+ const snapshot = detachedSnapshot(nextTask, "retained child continuation");
12743
+ const taskRef = contentAddress(snapshot);
12744
+ const nextSeq = inputSeq + 1;
12745
+ await retainedWrite(async () => {
12746
+ await args.blobs.put(taskRef, snapshot);
12747
+ controller.signal.throwIfAborted();
12748
+ await args.journal.appendEvent(args.root, {
12749
+ kind: "execution-input",
12750
+ id,
12751
+ taskRef,
12752
+ seq: nextSeq,
12753
+ at: new Date(now()).toISOString()
12754
+ });
12755
+ });
12756
+ inputSeq = nextSeq;
12757
+ live.executionTask = snapshot;
12758
+ live.transcriptEvidenceRecorded = false;
12759
+ admissions = [];
12760
+ const priorSpent = live.acceptedResult.spent;
12761
+ live.acceptedResult = void 0;
12762
+ return retainedContext({
12763
+ executionId: leafContinuationExecutionId(id, nextSeq),
12764
+ priorSession: environment,
12765
+ priorSpent
12766
+ });
12767
+ }
12768
+ });
12769
+ return {
12770
+ retainedContext,
12771
+ closeRetainedWrites,
12772
+ holdMs,
12773
+ readEnvironmentAdmission: () => {
12774
+ const admission = admissions.find((record) => record.phase === "environment");
12775
+ return admission?.phase === "environment" ? admission : void 0;
12776
+ }
12777
+ };
12778
+ }
12779
+ /** Whether a settled spend exceeds the budget it was given, by the channels the pool reconciles. */
12780
+ function overBudget(budget, spent) {
12781
+ return budget.maxTokens !== void 0 && chargedTokens(spent.tokens) > budget.maxTokens || budget.maxIterations !== void 0 && spent.iterations > budget.maxIterations || budget.maxUsd !== void 0 && spent.usdKnown !== false && spent.usd > budget.maxUsd;
12782
+ }
12624
12783
  // src/runtime/supervise/scope-key-registry.ts
12625
12784
  /**
12626
12785
  * The semantic-key registry (`SpawnOpts.key`), seeded from the journal on resume and updated as
@@ -13201,7 +13360,14 @@ function bindChildTeardown(scope, args, children, now) {
13201
13360
  return child.teardownRetry;
13202
13361
  }));
13203
13362
  });
13204
- retainedReleasers.set(scope, async () => {
13363
+ let sweeping;
13364
+ retainedReleasers.set(scope, () => {
13365
+ sweeping ??= sweepRetained().finally(() => {
13366
+ sweeping = void 0;
13367
+ });
13368
+ return sweeping;
13369
+ });
13370
+ async function sweepRetained() {
13205
13371
  const held = retainedHeld();
13206
13372
  const released = await Promise.all(held.map(async (child) => {
13207
13373
  child.cleanupConfirmed = false;
@@ -13236,7 +13402,7 @@ function bindChildTeardown(scope, args, children, now) {
13236
13402
  await child.admission.prepareAccounting?.();
13237
13403
  if (child.cleanupConfirmed) await closeRetainedSlot(child, "released", prior);
13238
13404
  }
13239
- });
13405
+ }
13240
13406
  const closeRetainedSlot = async (child, state, prior) => {
13241
13407
  if (child.recoveryPending !== true || child.resolved?.kind !== "down" || child.settledSeq === void 0 || child.settledAt === void 0 || child.retainedExecution === "released" || child.retainedExecution === "release-unconfirmed" || prior.some((event) => event.id === child.id && closesCursorSlot(event))) return;
13242
13408
  child.budgetViolation = child.retainedViolation;
@@ -13979,6 +14145,6 @@ function unknownChannels(spend) {
13979
14145
  function isNonEmptySpend(s) {
13980
14146
  return s.iterations > 0 || s.tokens.input > 0 || s.tokens.output > 0 || s.usd > 0 || s.ms > 0 || s.tokensKnown === false || s.usdKnown === false || Object.values(s.resources ?? {}).some((resource) => resource.amount > 0 || !resource.known);
13981
14147
  }
13982
- export { queueOf as $, captureHarnessTranscript as $n, RetainedRunProviderContractError as $r, loadSpawnForest as $t, openSlotGroup as A, verifyObserverRecords as An, knownMaterializationReceipt as Ar, noteScopeOwnerPlannedExecution as At, readWorkerInteractiveBinding as B, buildLoopSpanNodes as Bn, runtimeOwnedExecutorMaterialization as Br, scopeRetainedOwnerSettled as Bt, workerCancellationsDir as C, retainedCreateMaterial as Cn, attestRuntimeOwnedPendingExecutor as Cr, abandonScopeRetainedOwnerInvocation as Ct, writeWorkerSteer as D, FileObserverJournal as Dn, finalizeRuntimeOwnedPendingExecutor as Dr, scopeRetainedOwnerResult as Dt, writeWorkerCancellation as E, prepareInteractiveDelegation as En, authoredProfileDigest as Er, scopeRetainedOwnerPriorSpend as Et, parseWorkerToolTraceArtifact as F, workerTraceHeaders as Fn, recordRuntimeOwnedProviderDispatchNotStarted as Fr, coordinationMcpAlias as Ft, appendSpawnEvents as G, generateSpanId as Gn, unknownExecutionBindingReceipt as Gr, noteScopeRetainedOwnerCoordination as Gt, recoverRetainedInteractiveRun as H, createOpenInferenceFileExporter as Hn, runtimeOwnedPendingExecutorMaterialization as Hr, assertRetainedOwnerCoordinationRekey as Ht, workerTraceAnalysisStore as I, createPropagatingTraceEmitter as In, recordRuntimeOwnedProviderIdentityConflict as Ir, coordinationProfileToolPrefix as It, reenteredWorkers as J, createRuntimeStreamEventCollector as Jn, executableAgentSpecSnapshot as Jr, bindScopeRetainedOwnerProvider as Jt, spawnJournalRecordEvents as K, loopEventToOtelSpan as Kn, unknownMaterializationReceipt as Kr, scopeRetainedOwnerCheckpointing as Kt, nestedScopeSeamKey as L, mergeTraceEnv as Ln, recordRuntimeOwnedProviderModel as Lr, providerVisibleProfile as Lt, prepareScopeResume as M, environmentGone as Mn, providerAttemptEvidence as Mr, restoreScopeOwnerAcceptedExecution as Mt, replaySpawnTree as N, WORKER_TRACE_PROPAGATION as Nn, recordRuntimeOwnedDriveHarnessProviderEvidence as Nr, scopeOwnerExecutionObservation as Nt, writeWorkerSteerAcknowledgement as O, createFileObserverHooks as On, inheritRuntimeOwnedExecutorAttestation as Or, beginScopeOwnerAttempt as Ot, isTraceAnalysisStore as P, workerTraceEnv as Pn, recordRuntimeOwnedProviderAttemptStart as Pr, scopeOwnerExecutorNodeContext as Pt, freeSlots as Q, captureBoundHarnessTranscript as Qn, runtimeFlowBrain as Qr, scopeRetainedOwnerJournalRoot as Qt, interactiveAdmissionSeamKey as R, readTraceContextFromEnv as Rn, runtimeOwnedDriveHarnessProviderEvidence as Rr, runtimeGraphMetadataKey as Rt, workerCancelRequestsFile as S, startRetainedRunInEnvironment as Sn, attestRuntimeOwnedExecutor as Sr, resolveSpawnResourcePaths as St, workerSteerRequestsDir as T, offerInteractiveControl as Tn, authoredAgentIdentity as Tr, prepareScopeRetainedOwnerTask as Tt, startRetainedInteractiveRun as U, createOtelExporter as Un, runtimeOwnedScopeOwnerControl as Ur, reconcileScopeRetainedOwnerEnvironment as Ut, reconnectRetainedInteractiveRun as V, buildRuntimeEventOtelSpans as Vn, runtimeOwnedExecutorProviderEvidence as Vr, scopeRetainedOwnerTurnEnded as Vt, FileSpawnJournal as W, flatOtelSpan as Wn, runtimeOwnedScopeOwnerRuntime as Wr, scopeRetainedOwnerRestorePoint as Wt, assertRecursiveReservationPolicy as X, sanitizeRuntimeStreamEvent as Xn, runtimeCheckFactory as Xr, scopeOwnerLiabilities as Xt, settledToIteration as Y, sanitizeKnowledgeReadinessReport as Yn, isRuntimeFlowBrain as Yr, owners as Yt, deriveNodeExecutionIdentity as Z, HARNESS_TRANSCRIPT_SETTLE_TIMEOUT_MS as Zn, runtimeFlowAgent as Zr, scopeRetainedOwnerContext as Zt, readWorkerSteerAcknowledgement as _, assertRetainedRunReplayMaterial as _n, SeatPauseError as _r, waitForScopeChildren as _t, createRootStreamSink as a, sameControlCoordinates as ai, FileResultBlobStore as an, HARNESS_TRANSCRIPT_READ_LIMITS as ar, meterRuntimeOwnedProviderAttempt as at, supervisorRunDir as b, recoverRetainedRun as bn, subscriptionUsageLimitSignal as br, scopeRetainedOwnerResourceReader as bt, readRootStreamReceipt as c, providerMessageText as ci, insideCursorNamespace as cn, retainHarnessTranscript as cr, recordScopeOwnerDriverAttempt as ct, claimWorkerSteerDelivery as d, observeModelRequest as dn, describeToolArgs as dr, releaseHeldEnvironments as dt, assertEventBinding as ei, ownedTreeRootSpawn as en, harnessTranscriptArtifact as er, rollingDispatch as et, fileEscalateQuestion as f, NATIVE_STOP_UNCONFIRMED as fn, readWorkerProgress as fr, releaseRetainedEnvironments as ft, readWorkerCancellation as g, RetainedMaterializationTimeoutError as gn, SeatChain as gr, unconfirmedTeardowns as gt, readWorkerCancelRequests as h, verifyWorkspaceMarker as hn, SEAT_RECHECK_MS as hr, startScopeRecoveries as ht, ROOT_STREAM_FILE as i, retainedSessionReplaced as ii, nestedDriverTreeRoot as in, readHarnessTranscript as ir, meterRuntimeOwnedAccounting as it, resolveWorkerSlots as j, destroyInteractiveEnvironment as jn, newExecutionAttemptId as jr, recordScopeOwnerMaterialization as jt, createWorkerSlots as k, observerRecordDigest as kn, knownExecutionBindingReceipt as kr, finalizeScopeOwnerMaterialization as kt, appendWorkerControlEvent as l, executorObservation as ln, DEFAULT_STALL_AFTER_MS as lr, recordScopeOwnerPause as lt, legacySupervisorRunsRoot as m, stopRetainedNativeExecution as mn, isTerminalNodeStatus as mr, settleManagerWork as mt, terminalAccounting as n, exactSession as ni, attestNestedDriverTreeOwner as nn, harnessTranscriptUnavailable as nr, closeScopeAdmission as nt, nodeStreamFile as o, promptFromAgentTurnInput as oi, encodeResultBlob as on, readBoundHarnessSessions as or, pauseScopeSeatAdmission as ot, legacySupervisorRunDir as p, describeRetainedNativeStops as pn, isLiveNodeStatus as pr, retryUnconfirmedTeardowns as pt, appendTeardownConfirmation as q, createRuntimeEventCollector as qn, executableAgentProfileSnapshot as qr, bindScopeRetainedOwnerEnvironmentId as qt, createScope as r, freezeControlRef as ri, driverRuntime as rn, persistHarnessTranscript as rr, hasRetriableTeardowns as rt, readRootStream as s, promptOptionsFromAgentTurnInput as si, SpawnEventIndex as sn, resolveHarnessTranscriptCapture as sr, recordScopeOwnerBarrenPause as st, isNonEmptySpend as t, awaitAbortable$1 as ti, materializeTreeView as tn, harnessTranscriptFromLines as tr, closeRetainedSlots as tt, cancelWorker as u, executorObservationSeamKey as un, createActivityLog as ur, registerNestedTeardownScope as ut, readWorkerSteerRequests as v, mintRetainedIdentity as vn, authoredSeatStages as vr, prepareScopeRetainedOwnerSeatSwitch as vt, workerInboxFileFromEventDir as w, acceptedInteractiveControl as wn, attestRuntimeOwnedScopeOwner as wr, consumeScopeRetainedOwnerResult as wt, supervisorRunsRoot as x, startRetainedRun as xn, attestRuntimeOwnedDeferredExecutor as xr, environmentReader as xt, safeWorkerFile as y, reconnectRetainedRun as yn, seatExecutionProfile as yr, releaseScopeRetainedOwnerForSeatPause as yt, attachWorker as z, buildLoopOtelSpans as zn, runtimeOwnedExecutorExecutionBinding as zr, beginScopeRetainedOwnerDrive as zt };
14148
+ export { queueOf as $, sanitizeKnowledgeReadinessReport as $n, executableAgentSpecSnapshot as $r, owners as $t, openSlotGroup as A, prepareInteractiveDelegation as An, authoredAgentIdentity as Ar, beginScopeOwnerAttempt as At, readWorkerInteractiveBinding as B, createPropagatingTraceEmitter as Bn, recordRuntimeOwnedProviderDispatchNotStarted as Br, coordinationProfileToolPrefix as Bt, workerCancellationsDir as C, reconnectRetainedRun as Cn, authoredSeatStages as Cr, resolveSpawnResourcePaths as Ct, writeWorkerSteer as D, retainedCreateMaterial as Dn, attestRuntimeOwnedExecutor as Dr, prepareScopeRetainedOwnerTask as Dt, writeWorkerCancellation as E, startRetainedRunInEnvironment as En, attestRuntimeOwnedDeferredExecutor as Er, consumeScopeRetainedOwnerResult as Et, parseWorkerToolTraceArtifact as F, destroyInteractiveEnvironment as Fn, knownMaterializationReceipt as Fr, recordScopeOwnerMaterialization as Ft, appendSpawnEvents as G, buildRuntimeEventOtelSpans as Gn, runtimeOwnedExecutorMaterialization as Gr, scopeRetainedOwnerTurnEnded as Gt, recoverRetainedInteractiveRun as H, readTraceContextFromEnv as Hn, recordRuntimeOwnedProviderModel as Hr, runtimeGraphMetadataKey as Ht, workerTraceAnalysisStore as I, environmentGone as In, newExecutionAttemptId as Ir, restoreScopeOwnerAcceptedExecution as It, reenteredWorkers as J, flatOtelSpan as Jn, runtimeOwnedScopeOwnerControl as Jr, scopeRetainedOwnerRestorePoint as Jt, spawnJournalRecordEvents as K, createOpenInferenceFileExporter as Kn, runtimeOwnedExecutorProviderEvidence as Kr, assertRetainedOwnerCoordinationRekey as Kt, nestedScopeSeamKey as L, WORKER_TRACE_PROPAGATION as Ln, providerAttemptEvidence as Lr, scopeOwnerExecutionObservation as Lt, prepareScopeResume as M, createFileObserverHooks as Mn, finalizeRuntimeOwnedPendingExecutor as Mr, holdScopeOwnerTranscript as Mt, replaySpawnTree as N, observerRecordDigest as Nn, inheritRuntimeOwnedExecutorAttestation as Nr, noteScopeOwnerPlannedExecution as Nt, writeWorkerSteerAcknowledgement as O, acceptedInteractiveControl as On, attestRuntimeOwnedPendingExecutor as Or, scopeRetainedOwnerPriorSpend as Ot, isTraceAnalysisStore as P, verifyObserverRecords as Pn, knownExecutionBindingReceipt as Pr, recordScopeOwnerHarnessTranscript as Pt, freeSlots as Q, createRuntimeStreamEventCollector as Qn, executableAgentProfileSnapshot as Qr, bindScopeRetainedOwnerProvider as Qt, interactiveAdmissionSeamKey as R, workerTraceEnv as Rn, recordRuntimeOwnedDriveHarnessProviderEvidence as Rr, scopeOwnerExecutorNodeContext as Rt, workerCancelRequestsFile as S, mintRetainedIdentity as Sn, SeatPauseError as Sr, environmentReader as St, workerSteerRequestsDir as T, startRetainedRun as Tn, subscriptionUsageLimitSignal as Tr, abandonScopeRetainedOwnerInvocation as Tt, startRetainedInteractiveRun as U, buildLoopOtelSpans as Un, runtimeOwnedDriveHarnessProviderEvidence as Ur, beginScopeRetainedOwnerDrive as Ut, reconnectRetainedInteractiveRun as V, mergeTraceEnv as Vn, recordRuntimeOwnedProviderIdentityConflict as Vr, providerVisibleProfile as Vt, FileSpawnJournal as W, buildLoopSpanNodes as Wn, runtimeOwnedExecutorExecutionBinding as Wr, scopeRetainedOwnerSettled as Wt, assertRecursiveReservationPolicy as X, loopEventToOtelSpan as Xn, unknownExecutionBindingReceipt as Xr, scopeRetainedOwnerCheckpointing as Xt, settledToIteration as Y, generateSpanId as Yn, runtimeOwnedScopeOwnerRuntime as Yr, noteScopeRetainedOwnerCoordination as Yt, deriveNodeExecutionIdentity as Z, createRuntimeEventCollector as Zn, unknownMaterializationReceipt as Zr, bindScopeRetainedOwnerEnvironmentId as Zt, readWorkerSteerAcknowledgement as _, describeRetainedNativeStops as _n, readWorkerProgress as _r, unconfirmedTeardowns as _t, createRootStreamSink as a, assertEventBinding as ai, materializeTreeView as an, harnessTranscriptFromLines as ar, meterRuntimeOwnedAccounting as at, supervisorRunDir as b, RetainedMaterializationTimeoutError as bn, SEAT_RECHECK_MS as br, releaseScopeRetainedOwnerForSeatPause as bt, readRootStreamReceipt as c, freezeControlRef as ci, nestedDriverTreeRoot as cn, readHarnessTranscript as cr, recordScopeOwnerBarrenPause as ct, claimWorkerSteerDelivery as d, promptFromAgentTurnInput as di, SpawnEventIndex as dn, readBoundHarnessSessions$1 as dr, registerNestedTeardownScope as dt, isRuntimeFlowBrain as ei, scopeOwnerLiabilities as en, sanitizeRuntimeStreamEvent as er, rollingDispatch as et, fileEscalateQuestion as f, promptOptionsFromAgentTurnInput as fi, insideCursorNamespace as fn, resolveHarnessTranscriptCapture as fr, releaseHeldEnvironments as ft, readWorkerCancellation as g, NATIVE_STOP_UNCONFIRMED as gn, describeToolArgs as gr, startScopeRecoveries as gt, readWorkerCancelRequests as h, observeModelRequest as hn, createActivityLog as hr, settleManagerWork as ht, ROOT_STREAM_FILE as i, RetainedRunProviderContractError as ii, ownedTreeRootSpawn as in, harnessTranscriptArtifact as ir, hasRetriableTeardowns as it, resolveWorkerSlots as j, FileObserverJournal as jn, authoredProfileDigest as jr, finalizeScopeOwnerMaterialization as jt, createWorkerSlots as k, offerInteractiveControl as kn, attestRuntimeOwnedScopeOwner as kr, scopeRetainedOwnerResult as kt, appendWorkerControlEvent as l, retainedSessionReplaced as li, FileResultBlobStore as ln, settleHarnessTranscript as lr, recordScopeOwnerDriverAttempt as lt, legacySupervisorRunsRoot as m, executorObservationSeamKey as mn, DEFAULT_STALL_AFTER_MS as mr, retryUnconfirmedTeardowns as mt, terminalAccounting as n, runtimeFlowAgent as ni, scopeRetainedOwnerJournalRoot as nn, captureBoundHarnessTranscript as nr, closeRetainedSlots as nt, nodeStreamFile as o, awaitAbortable$1 as oi, attestNestedDriverTreeOwner as on, harnessTranscriptUnavailable as or, meterRuntimeOwnedProviderAttempt as ot, legacySupervisorRunDir as p, providerMessageText as pi, executorObservation as pn, retainHarnessTranscript as pr, releaseRetainedEnvironments as pt, appendTeardownConfirmation as q, createOtelExporter as qn, runtimeOwnedPendingExecutorMaterialization as qr, reconcileScopeRetainedOwnerEnvironment as qt, createScope as r, runtimeFlowBrain as ri, loadSpawnForest as rn, captureHarnessTranscript as rr, closeScopeAdmission as rt, readRootStream as s, exactSession as si, driverRuntime as sn, persistHarnessTranscript as sr, pauseScopeSeatAdmission as st, isNonEmptySpend as t, runtimeCheckFactory as ti, scopeRetainedOwnerContext as tn, HARNESS_TRANSCRIPT_SETTLE_TIMEOUT_MS as tr, boundRetainedReleases as tt, cancelWorker as u, sameControlCoordinates as ui, encodeResultBlob as un, HARNESS_TRANSCRIPT_READ_LIMITS as ur, recordScopeOwnerPause as ut, readWorkerSteerRequests as v, stopRetainedNativeExecution as vn, isLiveNodeStatus as vr, waitForScopeChildren as vt, workerInboxFileFromEventDir as w, recoverRetainedRun as wn, seatExecutionProfile as wr, RELEASE_DESTROY_MS as wt, supervisorRunsRoot as x, assertRetainedRunReplayMaterial as xn, SeatChain as xr, scopeRetainedOwnerResourceReader as xt, safeWorkerFile as y, verifyWorkspaceMarker as yn, isTerminalNodeStatus as yr, prepareScopeRetainedOwnerSeatSwitch as yt, attachWorker as z, workerTraceHeaders as zn, recordRuntimeOwnedProviderAttemptStart as zr, coordinationMcpAlias as zt };
13983
14149
 
13984
- //# sourceMappingURL=supervisor-accounting-StDNW1YT.js.map
14150
+ //# sourceMappingURL=supervisor-accounting-C48Yo9QC.js.map