@tangle-network/agent-runtime 0.189.0 → 0.191.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 (104) hide show
  1. package/dist/{activation-DuYIFVQm.js → activation-BpTEBhQR.js} +3 -3
  2. package/dist/{activation-DuYIFVQm.js.map → activation-BpTEBhQR.js.map} +1 -1
  3. package/dist/agent.d.ts +1 -1
  4. package/dist/agent.js +3 -3
  5. package/dist/{authoring-CIE6rF8N.js → authoring-DV0fkyxx.js} +7 -3
  6. package/dist/{authoring-CIE6rF8N.js.map → authoring-DV0fkyxx.js.map} +1 -1
  7. package/dist/candidate-execution/index.d.ts +3 -3
  8. package/dist/candidate-execution/index.js +5 -5
  9. package/dist/{candidate-execution-CQYU8E5a.js → candidate-execution-BSkZErxD.js} +255 -9
  10. package/dist/candidate-execution-BSkZErxD.js.map +1 -0
  11. package/dist/conversation.d.ts +1 -1
  12. package/dist/{coordination-driver-CtbyZv5d.js → coordination-driver-Bw0Prnim.js} +672 -39
  13. package/dist/coordination-driver-Bw0Prnim.js.map +1 -0
  14. package/dist/{durable-file-g3YdfEh4.js → durable-file-D24y9zg7.js} +2 -2
  15. package/dist/{durable-file-g3YdfEh4.js.map → durable-file-D24y9zg7.js.map} +1 -1
  16. package/dist/durable.d.ts +2 -2
  17. package/dist/durable.js +3 -3
  18. package/dist/{environment-provider-C4AQiUxj.d.ts → environment-provider-CJ43FJfJ.d.ts} +2 -2
  19. package/dist/{environment-provider-DZxuH3E4.js → environment-provider-DEwsolvi.js} +44 -7
  20. package/dist/environment-provider-DEwsolvi.js.map +1 -0
  21. package/dist/environment-provider.d.ts +1 -1
  22. package/dist/environment-provider.js +1 -1
  23. package/dist/{graph-DzkWh1BI.js → graph-BzsMtBYp.js} +6 -3
  24. package/dist/graph-BzsMtBYp.js.map +1 -0
  25. package/dist/graph.d.ts +3 -3
  26. package/dist/graph.js +5 -5
  27. package/dist/{redact-C9EWk1FT.d.ts → improve-Cbbt3jE6.d.ts} +4 -36
  28. package/dist/{improvement-cycle-DP9zf-IL.js → improvement-cycle-jC89uaRW.js} +7 -7
  29. package/dist/{improvement-cycle-DP9zf-IL.js.map → improvement-cycle-jC89uaRW.js.map} +1 -1
  30. package/dist/{index-k5bcID4t.d.ts → index-B2rVjcPT.d.ts} +417 -56
  31. package/dist/{index-DCqHTdmp.d.ts → index-CUosKU4N.d.ts} +144 -4
  32. package/dist/{index-DA9jKuJc.d.ts → index-OSRVFARy.d.ts} +2 -2
  33. package/dist/{index-tf6g2B27.d.ts → index-Y14IrBuB.d.ts} +4 -4
  34. package/dist/index.d.ts +11 -10
  35. package/dist/index.js +12 -13
  36. package/dist/index.js.map +1 -1
  37. package/dist/intelligence.d.ts +6 -5
  38. package/dist/intelligence.js +6 -7
  39. package/dist/intelligence.js.map +1 -1
  40. package/dist/kernel.d.ts +6 -6
  41. package/dist/kernel.js +12 -12
  42. package/dist/{knowledge-C5lODZQC.js → knowledge-BuXP5ynd.js} +5 -5
  43. package/dist/{knowledge-C5lODZQC.js.map → knowledge-BuXP5ynd.js.map} +1 -1
  44. package/dist/knowledge.d.ts +1 -1
  45. package/dist/knowledge.js +1 -1
  46. package/dist/{loop-runner-bin-BKsjoaVu.js → loop-runner-bin-B_Xh4jLi.js} +3 -3
  47. package/dist/{loop-runner-bin-BKsjoaVu.js.map → loop-runner-bin-B_Xh4jLi.js.map} +1 -1
  48. package/dist/{loop-runner-bin-ncN_8Msd.d.ts → loop-runner-bin-C2Yw-RBc.d.ts} +3 -3
  49. package/dist/loop-runner-bin.d.ts +1 -1
  50. package/dist/loop-runner-bin.js +1 -1
  51. package/dist/mcp/bin.js +3 -3
  52. package/dist/mcp/index.d.ts +4 -4
  53. package/dist/mcp/index.js +8 -8
  54. package/dist/mcp/memory-bin.js +1 -1
  55. package/dist/{memory-server-DsKOhzGf.js → memory-server-Crkevawz.js} +2 -2
  56. package/dist/{memory-server-DsKOhzGf.js.map → memory-server-Crkevawz.js.map} +1 -1
  57. package/dist/{openai-tools-x83CTnJM.js → openai-tools-Dqg8IhKd.js} +2 -2
  58. package/dist/{openai-tools-x83CTnJM.js.map → openai-tools-Dqg8IhKd.js.map} +1 -1
  59. package/dist/{prepare-BtXhV0qj.js → prepare-B5fJ7mLS.js} +239 -227
  60. package/dist/prepare-B5fJ7mLS.js.map +1 -0
  61. package/dist/primeintellect/index.d.ts +1 -1
  62. package/dist/primeintellect/index.js +1 -1
  63. package/dist/profiles.js +1 -1
  64. package/dist/{protected-model-port-DHrayPt4.js → protected-model-port-B0xFSAjt.js} +2 -2
  65. package/dist/{protected-model-port-DHrayPt4.js.map → protected-model-port-B0xFSAjt.js.map} +1 -1
  66. package/dist/{provision-supervisor-B-_4I1In.js → provision-supervisor-DAcTZDQG.js} +8 -8
  67. package/dist/{provision-supervisor-B-_4I1In.js.map → provision-supervisor-DAcTZDQG.js.map} +1 -1
  68. package/dist/{supervisor-BSNkaM2a.js → redact-BP8Xn2A3.js} +569 -12
  69. package/dist/redact-BP8Xn2A3.js.map +1 -0
  70. package/dist/{run-layout-Cd_l2XWV.js → run-layout-B8I_LXN-.js} +3 -3
  71. package/dist/{run-layout-Cd_l2XWV.js.map → run-layout-B8I_LXN-.js.map} +1 -1
  72. package/dist/{runtime-EQgE3942.d.ts → runtime-DI4mJNXI.d.ts} +202 -4
  73. package/dist/{runtime-C98JsP83.js → runtime-Dm63BrGY.js} +69 -25
  74. package/dist/{runtime-C98JsP83.js.map → runtime-Dm63BrGY.js.map} +1 -1
  75. package/dist/{spawn-journal-CxRa-NJ2.js → spawn-journal-B9eTmVAn.js} +2 -2
  76. package/dist/{spawn-journal-CxRa-NJ2.js.map → spawn-journal-B9eTmVAn.js.map} +1 -1
  77. package/dist/{stream-agent-turn-BomJ21AK.d.ts → stream-agent-turn-_GgUW49y.d.ts} +35 -3
  78. package/dist/{structural-rollout-C8sB6B4q.js → structural-rollout-ChpGSR0q.js} +3 -3
  79. package/dist/{structural-rollout-C8sB6B4q.js.map → structural-rollout-ChpGSR0q.js.map} +1 -1
  80. package/dist/{supervise-DSu4d0b6.js → supervise-B89x7rgF.js} +287 -23
  81. package/dist/supervise-B89x7rgF.js.map +1 -0
  82. package/dist/testing.d.ts +2 -2
  83. package/dist/testing.js +13 -13
  84. package/dist/{top-app-DIBApkt1.js → top-app-KgIFpD9H.js} +3 -3
  85. package/dist/{top-app-DIBApkt1.js.map → top-app-KgIFpD9H.js.map} +1 -1
  86. package/dist/tui/bin.js +1 -1
  87. package/dist/tui/index.d.ts +1 -1
  88. package/dist/tui/index.js +2 -2
  89. package/dist/{types-BbkiJR1D.d.ts → types-DKA_PDv0.d.ts} +62 -2
  90. package/dist/{util-BfoW6RU7.js → util-mCNUeboW.js} +21 -2
  91. package/dist/util-mCNUeboW.js.map +1 -0
  92. package/dist/{workspace-archive-SVeiWLNE.js → workspace-archive-yAPDklLV.js} +4 -4
  93. package/dist/{workspace-archive-SVeiWLNE.js.map → workspace-archive-yAPDklLV.js.map} +1 -1
  94. package/package.json +8 -8
  95. package/dist/candidate-execution-CQYU8E5a.js.map +0 -1
  96. package/dist/coordination-driver-CtbyZv5d.js.map +0 -1
  97. package/dist/environment-provider-DZxuH3E4.js.map +0 -1
  98. package/dist/graph-DzkWh1BI.js.map +0 -1
  99. package/dist/prepare-BtXhV0qj.js.map +0 -1
  100. package/dist/redact-D-u-rrcn.js +0 -82
  101. package/dist/redact-D-u-rrcn.js.map +0 -1
  102. package/dist/supervise-DSu4d0b6.js.map +0 -1
  103. package/dist/supervisor-BSNkaM2a.js.map +0 -1
  104. package/dist/util-BfoW6RU7.js.map +0 -1
@@ -1,21 +1,21 @@
1
1
  import { A as assertEventBinding, B as exactContinuedControlRef, C as runtimeOwnedScopeOwnerRuntime, D as abortError, E as RetainedRunProviderContractError, F as assertWaitDuration, G as freezeControlRef, H as exactSession, I as awaitAbortable$1, J as sameControlCoordinates, K as hasDurableCancel, L as cancellationRequest, M as assertResultBinding, N as assertSequence, O as assertBoundaryBinding, P as assertStableText, R as copyControlRef, S as runtimeOwnedPendingExecutorMaterialization, T as unknownMaterializationReceipt, U as exactSessionCancel, V as exactControlRef, W as exactSessionResult, Y as freshTurnInput, _ as runtimeOwnedDeferredExecutorRuntime, a as authoredProfileDigest, b as runtimeOwnedExecutorMaterialization, c as knownExecutionBindingReceipt, g as recordRuntimeOwnedProviderModel, h as recordRuntimeOwnedProviderIdentityConflict, j as assertInteractionBinding, k as assertCanonicalEventBinding, l as knownMaterializationReceipt, m as recordRuntimeOwnedProviderDispatchNotStarted, n as attestRuntimeOwnedExecutor, o as finalizeRuntimeOwnedPendingExecutor, p as recordRuntimeOwnedProviderAttemptStart, q as isTerminalSessionStatus, r as attestRuntimeOwnedPendingExecutor, s as inheritRuntimeOwnedExecutorAttestation, t as attestRuntimeOwnedDeferredExecutor, u as newExecutionAttemptId, w as unknownExecutionBindingReceipt, x as runtimeOwnedExecutorProviderEvidence, y as runtimeOwnedExecutorExecutionBinding, z as delay } from "./materialization-CekWK6OO.js";
2
2
  import { c as RetainedInteractiveAdmissionError, d as RetainedRunDispatchBindingError, f as RuntimeRunStateError, l as RetainedInteractiveBindingError, m as ValidationError, r as BackendTransportError, u as RetainedRunAdmissionError } from "./errors-CDZ8XsVj.js";
3
3
  import { n as detachedSnapshot } from "./snapshot-CTAf4uuA.js";
4
- import { _ as captureWorkerTraceEvidence, a as aggregateProviderModelEvidence, c as loadSpawnForest, d as replaySpawnTree, f as attestNestedDriverTreeOwner, h as runtimeOwnedNestedDriverTreeRoot, l as materializeTreeView, m as nestedDriverTreeRoot, n as FileSpawnJournal, o as closesCursorSlot, p as driverRuntime, u as pendingWaits, x as contentAddress } from "./spawn-journal-CxRa-NJ2.js";
5
- import { _ as throwIfAborted, a as cloneTokenUsage, b as zeroSpend, d as randomSuffix, f as randomUuid, g as throwAbort, h as stringifySafe, l as mapWithConcurrency, m as sleep, n as addTokenUsage, o as deleteBoxSafe, p as roundBoxMinutes, r as chargedTokens, s as hasCompleteCacheBreakdown, t as addSpend, u as promptCacheTokenClasses, v as unmeteredSpend, x as zeroTokenUsage, y as withTimeout } from "./util-BfoW6RU7.js";
4
+ import { _ as captureWorkerTraceEvidence, a as aggregateProviderModelEvidence, c as loadSpawnForest, d as replaySpawnTree, f as attestNestedDriverTreeOwner, h as runtimeOwnedNestedDriverTreeRoot, l as materializeTreeView, m as nestedDriverTreeRoot, n as FileSpawnJournal, o as closesCursorSlot, p as driverRuntime, u as pendingWaits, x as contentAddress } from "./spawn-journal-B9eTmVAn.js";
5
+ import { _ as throwIfAborted, a as cloneTokenUsage, b as zeroSpend, d as randomSuffix, f as randomUuid, g as throwAbort, h as stringifySafe, l as mapWithConcurrency, m as sleep, n as addTokenUsage, o as deleteBoxSafe, p as roundBoxMinutes, r as chargedTokens, s as hasCompleteCacheBreakdown, t as addSpend, u as promptCacheTokenClasses, v as unmeteredSpend, x as zeroTokenUsage, y as withTimeout } from "./util-mCNUeboW.js";
6
6
  import { _ as parseCodexUsageRecord, c as mapSandboxToolEvent, d as sandboxProgressEvents, h as parseCanonicalTransportEvent, i as createSandboxUsageLedger, l as notifySandboxEventObserver, m as extractTransportEventIdentity, r as createSandboxToolPartState, t as assertSandboxServedModel, u as sandboxEventServedBackend } from "./sandbox-events-DWeQRWxg.js";
7
7
  import { n as executableAgentSpecSnapshot, r as projectSandboxOutcome, t as executableAgentProfileSnapshot } from "./executable-spec-DxuiDFAU.js";
8
8
  import { a as concreteProfileModel, c as profileModelExecutionSettings, d as agentHarness, l as profileProviderModel, o as enforceTokenLimits, s as profileBridgeWireModel, t as assertExecutableAgentProfile, u as resolveRouterRetryPolicy } from "./model-policy-Wf2MxXJ9.js";
9
- import { c as linkAbort, i as resolveAgentEnvironmentProvider, l as runAbortable, n as providerAsExecutor, r as providerAsSandboxClient, s as abortError$1 } from "./environment-provider-DZxuH3E4.js";
9
+ import { c as linkAbort, i as resolveAgentEnvironmentProvider, l as runAbortable, n as providerAsExecutor, r as providerAsSandboxClient, s as abortError$1 } from "./environment-provider-DEwsolvi.js";
10
10
  import { i as notifyRuntimeHookEvent } from "./runtime-hooks-tXpAarhW.js";
11
- import { n as assertNoSymlinkDescendant, r as publishExclusiveDurableFile } from "./durable-file-g3YdfEh4.js";
11
+ import { n as assertNoSymlinkDescendant, r as publishExclusiveDurableFile } from "./durable-file-D24y9zg7.js";
12
12
  import { AGENT_PROFILE_MATERIALIZATION_AXES, AgentEnvironmentCapabilitiesSchema, AgentExactRunControlRefSchema, AgentInteractiveSessionControlClaimAcknowledgementSchema, AgentInteractiveSessionControlClaimSchema, AgentInteractiveSessionPromptAcknowledgementSchema, AgentInteractiveSessionRefSchema, AgentInteractiveSessionStatusSchema, AgentInteractiveSessionStopAcknowledgementSchema, AgentNativeContextContinuationResultSchema, AgentTurnInputSchema, AgentTurnResultSchema, ContextTransferRequestSchema, InteractionAcknowledgementSchema, InteractionResponseCommandSchema, NativeContextBoundaryProofSchema, NativeContextContinuationRequestSchema, REASONING_EFFORTS, RuntimeEventEnvelopeSchema, TerminalReplayWindowSchema, TerminalSessionRefSchema, agentInteractiveSessionControlClaimAcknowledgementMatchesRequest, agentInteractiveSessionControlClaimMatchesRef, agentInteractiveSessionPromptAcknowledgementMatchesCommand, agentInteractiveSessionRefMatchesStart, agentInteractiveSessionRunRef, agentInteractiveSessionStatusMatchesRef, agentInteractiveSessionStopAcknowledgementMatchesCommand, agentNativeContextContinuationResultMatchesRequest, agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, exactAgentInteractiveSessionStart, harnessTypeSchema, nativeContextContinuationTurnDigest, nativeReasoningControl, profileMaterializationAxes, profileMaterializationAxes as profileMaterializationAxes$1, renderInputPartsAsText, sha256DigestSchema } from "@tangle-network/agent-interface";
13
13
  import { estimateCost, isModelPriced } from "@tangle-network/agent-eval";
14
14
  import { createHash, randomBytes, randomUUID } from "node:crypto";
15
- import { basename, delimiter, dirname, isAbsolute, join, resolve, sep, win32 } from "node:path";
16
- import { applyWorkspacePlan, hashWorkspacePlan, materializeProfile, resolveAgentProfileResources } from "@tangle-network/agent-profile-materialize";
17
- import { access, chmod, copyFile, mkdir, mkdtemp, open, readFile, realpath, rm, rmdir, stat, symlink, writeFile } from "node:fs/promises";
18
15
  import { appendFileSync, constants, createReadStream, existsSync, mkdirSync, readFileSync } from "node:fs";
16
+ import { access, chmod, copyFile, mkdir, mkdtemp, open, readFile, readdir, realpath, rm, rmdir, stat, symlink, writeFile } from "node:fs/promises";
17
+ import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep, win32 } from "node:path";
18
+ import { applyWorkspacePlan, hashWorkspacePlan, materializeProfile, resolveAgentProfileResources } from "@tangle-network/agent-profile-materialize";
19
19
  import { spawn } from "node:child_process";
20
20
  import { homedir, tmpdir } from "node:os";
21
21
  import { stripVTControlCharacters } from "node:util";
@@ -3322,6 +3322,405 @@ function generateTraceId() {
3322
3322
  return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
3323
3323
  }
3324
3324
  //#endregion
3325
+ //#region src/runtime/codex-rollout-store.ts
3326
+ const zeroCounters = {
3327
+ input: 0,
3328
+ output: 0,
3329
+ cachedInput: 0,
3330
+ cacheWriteInput: 0,
3331
+ reasoningOutput: 0
3332
+ };
3333
+ const ROLLOUT_SUFFIX = ".jsonl";
3334
+ /** Rows this reader needs. Every other line is skipped without being parsed. */
3335
+ const INTERESTING = [
3336
+ "\"session_meta\"",
3337
+ "\"token_count\"",
3338
+ "\"task_started\""
3339
+ ];
3340
+ /**
3341
+ * Read one rollout's rows into a session record.
3342
+ *
3343
+ * `rows` is the file's JSON values in file order. Pass the whole file to read a completed session;
3344
+ * the store reader passes appended slices and carries the identity forward itself.
3345
+ */
3346
+ function readCodexRolloutSession(rows) {
3347
+ const state = createSessionState();
3348
+ for (const row of rows) consumeRow(state, row);
3349
+ return finishSession(state)?.session;
3350
+ }
3351
+ /**
3352
+ * Open an incremental reader over a codex store.
3353
+ *
3354
+ * Nothing is read until `read()` is called, and every read is bounded by the bytes appended since
3355
+ * the previous one, so a 695MB rollout is scanned once rather than once per turn.
3356
+ */
3357
+ function createCodexRolloutStoreReader(ref) {
3358
+ if (!isAbsolute(ref.root)) throw new ValidationError(`createCodexRolloutStoreReader: root must be an absolute path, received ${JSON.stringify(ref.root)}`);
3359
+ const root = resolve(ref.root);
3360
+ const workspaceRoot = ref.workspaceRoot === void 0 ? void 0 : resolve(ref.workspaceRoot);
3361
+ const files = /* @__PURE__ */ new Map();
3362
+ return { async read() {
3363
+ const sessions = [];
3364
+ for (const path of await listRollouts(root)) {
3365
+ const cursor = files.get(path) ?? newCursor();
3366
+ files.set(path, cursor);
3367
+ const size = await fileSize(path);
3368
+ if (size === void 0) continue;
3369
+ if (size < cursor.offset) {
3370
+ const fresh = newCursor();
3371
+ files.set(path, fresh);
3372
+ cursor.offset = fresh.offset;
3373
+ cursor.state = fresh.state;
3374
+ cursor.pending = fresh.pending;
3375
+ }
3376
+ if (size === cursor.offset) continue;
3377
+ await consumeAppendedBytes(path, cursor, size);
3378
+ const read = finishSession(cursor.state);
3379
+ if (read === void 0 || !includesWorkspace(read.session, workspaceRoot)) continue;
3380
+ const from = read.ownFrom === void 0 ? void 0 : laterCounters(read.ownFrom, cursor.credited);
3381
+ const incremental = from === void 0 ? void 0 : counterDelta(from, cursor.state.cumulative);
3382
+ cursor.credited = cursor.state.cumulative;
3383
+ sessions.push({
3384
+ session: read.session,
3385
+ ...incremental === void 0 ? {} : { incremental }
3386
+ });
3387
+ }
3388
+ return reduceDelta(sessions);
3389
+ } };
3390
+ }
3391
+ /** Sum two usage reports on every counter both of them state. */
3392
+ function addHarnessUsage(left, right) {
3393
+ return {
3394
+ harness: left.harness,
3395
+ input: left.input + right.input,
3396
+ output: left.output + right.output,
3397
+ ...sumOptional("cachedInput", left, right),
3398
+ ...sumOptional("cacheWriteInput", left, right),
3399
+ ...sumOptional("reasoningOutput", left, right)
3400
+ };
3401
+ }
3402
+ /** True when a report states any spend at all. */
3403
+ function harnessUsageIsEmpty(usage) {
3404
+ return usage.input === 0 && usage.output === 0;
3405
+ }
3406
+ function createSessionState() {
3407
+ return {
3408
+ cumulative: zeroCounters,
3409
+ marks: [],
3410
+ markEnds: [],
3411
+ beforeFirstMark: zeroCounters,
3412
+ sawAnyCount: false
3413
+ };
3414
+ }
3415
+ function consumeRow(state, row) {
3416
+ const record = plainRecord(row);
3417
+ if (record === void 0) return;
3418
+ if (record.type === "session_meta") {
3419
+ readIdentity(state, record);
3420
+ return;
3421
+ }
3422
+ if (record.type !== "event_msg") return;
3423
+ const payload = plainRecord(record.payload);
3424
+ if (payload === void 0) return;
3425
+ if (payload.type === "task_started") {
3426
+ const at = state.cumulative;
3427
+ state.marks.push({
3428
+ ...typeof payload.turn_id === "string" ? { turnId: payload.turn_id } : {},
3429
+ ...typeof payload.started_at === "number" ? { startedAtSeconds: payload.started_at } : {},
3430
+ at,
3431
+ ...typeof record.ordinal === "number" ? { ordinal: record.ordinal } : {}
3432
+ });
3433
+ state.markEnds.push(at);
3434
+ return;
3435
+ }
3436
+ if (payload.type !== "token_count") return;
3437
+ const total = readCumulative(plainRecord(payload.info)?.total_token_usage);
3438
+ if (total === void 0) return;
3439
+ if (sameCounters(total, state.cumulative)) return;
3440
+ state.cumulative = total;
3441
+ state.sawAnyCount = true;
3442
+ if (state.marks.length === 0) state.beforeFirstMark = total;
3443
+ else state.markEnds[state.marks.length - 1] = total;
3444
+ }
3445
+ function readIdentity(state, record) {
3446
+ const payload = plainRecord(record.payload);
3447
+ if (payload === void 0) return;
3448
+ const sessionId = typeof payload.id === "string" ? payload.id : void 0;
3449
+ if (sessionId === void 0) return;
3450
+ const spawn = plainRecord(plainRecord(plainRecord(payload.source)?.subagent)?.thread_spawn);
3451
+ const startedAtMs = Date.parse(typeof payload.timestamp === "string" ? payload.timestamp : String(record.timestamp ?? ""));
3452
+ state.identity = {
3453
+ sessionId,
3454
+ ...typeof payload.parent_thread_id === "string" ? { parentThreadId: payload.parent_thread_id } : {},
3455
+ ...typeof payload.forked_from_id === "string" ? { forkedFromId: payload.forked_from_id } : {},
3456
+ nativeChild: payload.thread_source === "subagent",
3457
+ ...typeof payload.agent_path === "string" ? { agentPath: payload.agent_path } : {},
3458
+ ...typeof payload.agent_nickname === "string" ? { agentNickname: payload.agent_nickname } : {},
3459
+ ...typeof spawn?.depth === "number" ? { depth: spawn.depth } : {},
3460
+ ...typeof payload.cwd === "string" ? { cwd: payload.cwd } : {},
3461
+ ...typeof payload.cli_version === "string" ? { cliVersion: payload.cli_version } : {},
3462
+ ...Number.isFinite(startedAtMs) ? { startedAtMs } : {}
3463
+ };
3464
+ if (typeof payload.subagent_history_start_ordinal === "number") state.historyStartOrdinal = payload.subagent_history_start_ordinal;
3465
+ }
3466
+ function finishSession(state) {
3467
+ const identity = state.identity;
3468
+ if (identity === void 0) return void 0;
3469
+ const boundary = resolveBoundary(state, identity);
3470
+ const base = {
3471
+ identity,
3472
+ boundary,
3473
+ fileCumulativeInput: state.cumulative.input,
3474
+ fileCumulativeOutput: state.cumulative.output
3475
+ };
3476
+ if (boundary.kind === "unresolved") return { session: {
3477
+ ...base,
3478
+ turns: []
3479
+ } };
3480
+ const firstOwn = boundary.kind === "whole-file" ? 0 : boundary.inheritedTurns;
3481
+ const turns = [];
3482
+ for (let index = firstOwn; index < state.marks.length; index += 1) {
3483
+ const mark = state.marks[index];
3484
+ const end = state.markEnds[index];
3485
+ if (mark === void 0 || end === void 0) continue;
3486
+ const usage = counterDelta(mark.at, end);
3487
+ if (usage === void 0) continue;
3488
+ turns.push({
3489
+ ...mark.turnId === void 0 ? {} : { turnId: mark.turnId },
3490
+ ...mark.startedAtSeconds === void 0 ? {} : { startedAtMs: mark.startedAtSeconds * 1e3 },
3491
+ usage
3492
+ });
3493
+ }
3494
+ const from = firstOwn === 0 ? state.marks.length === 0 ? zeroCounters : state.beforeFirstMark : state.marks[firstOwn]?.at ?? state.cumulative;
3495
+ const own = counterDelta(from, state.cumulative) ?? emptyUsage();
3496
+ return {
3497
+ session: {
3498
+ ...base,
3499
+ own,
3500
+ turns
3501
+ },
3502
+ ownFrom: from
3503
+ };
3504
+ }
3505
+ /**
3506
+ * Find the row where this session's OWN history begins.
3507
+ *
3508
+ * Four rules, most authoritative first. A build that states the boundary is believed over one that
3509
+ * must be inferred, and inference is refused rather than guessed when nothing distinguishes the
3510
+ * child's turns from the parent's.
3511
+ */
3512
+ function resolveBoundary(state, identity) {
3513
+ if (!(identity.forkedFromId !== void 0 || identity.nativeChild)) return { kind: "whole-file" };
3514
+ if (state.historyStartOrdinal !== void 0) {
3515
+ const at = state.marks.findIndex((mark) => mark.ordinal !== void 0 && mark.ordinal >= (state.historyStartOrdinal ?? 0));
3516
+ if (at >= 0) return {
3517
+ kind: "resolved",
3518
+ rule: "history-start-ordinal",
3519
+ ...state.marks[at]?.turnId === void 0 ? {} : { turnId: state.marks[at]?.turnId },
3520
+ inheritedTurns: at
3521
+ };
3522
+ }
3523
+ const exact = state.marks.findIndex((mark) => mark.turnId === identity.sessionId);
3524
+ if (exact >= 0) return {
3525
+ kind: "resolved",
3526
+ rule: "turn-is-session",
3527
+ turnId: identity.sessionId,
3528
+ inheritedTurns: exact
3529
+ };
3530
+ const sessionMintedAtMs = uuidV7TimestampMs(identity.sessionId);
3531
+ if (sessionMintedAtMs !== void 0) {
3532
+ const at = state.marks.findIndex((mark) => {
3533
+ const minted = uuidV7TimestampMs(mark.turnId);
3534
+ return minted !== void 0 && minted >= sessionMintedAtMs;
3535
+ });
3536
+ if (at >= 0) return {
3537
+ kind: "resolved",
3538
+ rule: "turn-uuid-v7",
3539
+ ...state.marks[at]?.turnId === void 0 ? {} : { turnId: state.marks[at]?.turnId },
3540
+ inheritedTurns: at
3541
+ };
3542
+ }
3543
+ if (identity.startedAtMs !== void 0) {
3544
+ const startedAtSeconds = Math.floor(identity.startedAtMs / 1e3);
3545
+ const matches = state.marks.map((mark, index) => ({
3546
+ mark,
3547
+ index
3548
+ })).filter(({ mark }) => mark.startedAtSeconds !== void 0 && Math.abs(mark.startedAtSeconds - startedAtSeconds) <= 2);
3549
+ if (matches.length === 1) {
3550
+ const only = matches[0];
3551
+ if (only !== void 0) return {
3552
+ kind: "resolved",
3553
+ rule: "turn-start-time",
3554
+ ...only.mark.turnId === void 0 ? {} : { turnId: only.mark.turnId },
3555
+ inheritedTurns: only.index
3556
+ };
3557
+ }
3558
+ if (matches.length > 1) return {
3559
+ kind: "unresolved",
3560
+ reason: `${matches.length} task_started rows start within 2s of the child session; its own turn cannot be isolated`
3561
+ };
3562
+ }
3563
+ return {
3564
+ kind: "unresolved",
3565
+ reason: "forked rollout carries no history-start ordinal, no turn matching the session id, no UUIDv7 turn at or after it, and no task_started at the session start time"
3566
+ };
3567
+ }
3568
+ function newCursor() {
3569
+ return {
3570
+ offset: 0,
3571
+ pending: "",
3572
+ state: createSessionState(),
3573
+ credited: zeroCounters
3574
+ };
3575
+ }
3576
+ async function listRollouts(root) {
3577
+ const found = [];
3578
+ const walk = async (dir) => {
3579
+ let entries;
3580
+ try {
3581
+ entries = await readdir(dir, { withFileTypes: true });
3582
+ } catch {
3583
+ return;
3584
+ }
3585
+ for (const entry of entries) {
3586
+ const path = join(dir, entry.name);
3587
+ if (entry.isDirectory()) await walk(path);
3588
+ else if (entry.isFile() && entry.name.endsWith(ROLLOUT_SUFFIX)) found.push(path);
3589
+ }
3590
+ };
3591
+ await walk(join(root, "sessions"));
3592
+ return found.sort();
3593
+ }
3594
+ async function fileSize(path) {
3595
+ try {
3596
+ return (await stat(path)).size;
3597
+ } catch {
3598
+ return;
3599
+ }
3600
+ }
3601
+ /** Read `[cursor.offset, size)` and fold every complete line into the cursor's session state. */
3602
+ async function consumeAppendedBytes(path, cursor, size) {
3603
+ const stream = createReadStream(path, {
3604
+ encoding: "utf8",
3605
+ start: cursor.offset,
3606
+ end: size - 1
3607
+ });
3608
+ try {
3609
+ for await (const chunk of stream) {
3610
+ cursor.pending += chunk;
3611
+ let start = 0;
3612
+ for (let at = cursor.pending.indexOf("\n"); at !== -1; at = cursor.pending.indexOf("\n", start)) {
3613
+ consumeLine(cursor.state, cursor.pending.slice(start, at));
3614
+ start = at + 1;
3615
+ }
3616
+ cursor.pending = cursor.pending.slice(start);
3617
+ }
3618
+ } finally {
3619
+ stream.destroy();
3620
+ }
3621
+ cursor.offset = size;
3622
+ }
3623
+ function consumeLine(state, line) {
3624
+ if (!INTERESTING.some((marker) => line.includes(marker))) return;
3625
+ try {
3626
+ consumeRow(state, JSON.parse(line));
3627
+ } catch {}
3628
+ }
3629
+ function includesWorkspace(session, workspaceRoot) {
3630
+ if (workspaceRoot === void 0) return true;
3631
+ const cwd = session.identity.cwd;
3632
+ if (cwd === void 0) return false;
3633
+ const rel = relative(workspaceRoot, resolve(cwd));
3634
+ return rel === "" || !rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel);
3635
+ }
3636
+ function reduceDelta(read) {
3637
+ let seat = emptyUsage();
3638
+ let native = emptyUsage();
3639
+ const unresolved = [];
3640
+ for (const { session, incremental } of read) {
3641
+ if (session.boundary.kind === "unresolved") {
3642
+ unresolved.push({
3643
+ sessionId: session.identity.sessionId,
3644
+ reason: session.boundary.reason
3645
+ });
3646
+ continue;
3647
+ }
3648
+ if (incremental === void 0) continue;
3649
+ if (session.identity.nativeChild) native = addHarnessUsage(native, incremental);
3650
+ else seat = addHarnessUsage(seat, incremental);
3651
+ }
3652
+ return {
3653
+ seat,
3654
+ native,
3655
+ unresolved,
3656
+ sessions: read.map((entry) => entry.session)
3657
+ };
3658
+ }
3659
+ /** The later of two cumulative marks. Every counter is monotonic within one session. */
3660
+ function laterCounters(left, right) {
3661
+ return left.input + left.output >= right.input + right.output ? left : right;
3662
+ }
3663
+ function emptyUsage() {
3664
+ return {
3665
+ harness: "codex",
3666
+ input: 0,
3667
+ output: 0
3668
+ };
3669
+ }
3670
+ function counterDelta(from, to) {
3671
+ const input = to.input - from.input;
3672
+ const output = to.output - from.output;
3673
+ if (input < 0 || output < 0) return void 0;
3674
+ const cachedInput = Math.max(0, to.cachedInput - from.cachedInput);
3675
+ const cacheWriteInput = Math.max(0, to.cacheWriteInput - from.cacheWriteInput);
3676
+ const reasoningOutput = Math.max(0, to.reasoningOutput - from.reasoningOutput);
3677
+ if (input === 0 && output === 0) return void 0;
3678
+ return {
3679
+ harness: "codex",
3680
+ input,
3681
+ output,
3682
+ cachedInput: Math.min(cachedInput, input),
3683
+ cacheWriteInput: Math.min(cacheWriteInput, Math.max(0, input - Math.min(cachedInput, input))),
3684
+ reasoningOutput: Math.min(reasoningOutput, output)
3685
+ };
3686
+ }
3687
+ function readCumulative(value) {
3688
+ const record = plainRecord(value);
3689
+ if (record === void 0) return void 0;
3690
+ const input = naturalNumber(record.input_tokens);
3691
+ const output = naturalNumber(record.output_tokens);
3692
+ if (input === void 0 || output === void 0) return void 0;
3693
+ return {
3694
+ input,
3695
+ output,
3696
+ cachedInput: naturalNumber(record.cached_input_tokens) ?? 0,
3697
+ cacheWriteInput: naturalNumber(record.cache_write_input_tokens) ?? 0,
3698
+ reasoningOutput: naturalNumber(record.reasoning_output_tokens) ?? 0
3699
+ };
3700
+ }
3701
+ function sameCounters(left, right) {
3702
+ return left.input === right.input && left.output === right.output && left.cachedInput === right.cachedInput && left.cacheWriteInput === right.cacheWriteInput && left.reasoningOutput === right.reasoningOutput;
3703
+ }
3704
+ function sumOptional(field, left, right) {
3705
+ const a = left[field];
3706
+ const b = right[field];
3707
+ if (a === void 0 && b === void 0) return {};
3708
+ return { [field]: (a ?? 0) + (b ?? 0) };
3709
+ }
3710
+ const UUID_V7 = /^([0-9a-f]{8})-([0-9a-f]{4})-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
3711
+ function uuidV7TimestampMs(value) {
3712
+ const match = value?.match(UUID_V7);
3713
+ if (!match) return void 0;
3714
+ const ms = Number.parseInt(`${match[1]}${match[2]}`, 16);
3715
+ return Number.isSafeInteger(ms) ? ms : void 0;
3716
+ }
3717
+ function plainRecord(value) {
3718
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3719
+ }
3720
+ function naturalNumber(value) {
3721
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
3722
+ }
3723
+ //#endregion
3325
3724
  //#region src/runtime/model-identity.ts
3326
3725
  const SNAPSHOT_TOKEN = /^[A-Za-z0-9._-]+$/u;
3327
3726
  /** Match equivalent bare and provider-qualified spellings without discarding observed identity. */
@@ -8651,6 +9050,12 @@ async function* streamBridgeSession(args) {
8651
9050
  let observedSystemFingerprint;
8652
9051
  const toolCalls = [];
8653
9052
  const promptCache = {};
9053
+ const harnessStore = openBridgeHarnessStore(seam.harnessStore);
9054
+ let tokensProvenance;
9055
+ const creditProvenance = (source) => {
9056
+ tokensProvenance = tokensProvenance === void 0 || tokensProvenance === source ? source : "mixed";
9057
+ };
9058
+ if (harnessStore) await readHarnessStoreDelta(harnessStore, observation);
8654
9059
  let nextPrompt = taskToPrompt(args.task);
8655
9060
  for (let t = 0; args.maxTurns === 0 || t < args.maxTurns; t += 1) {
8656
9061
  if (args.stopSignal?.aborted) {
@@ -8802,6 +9207,7 @@ async function* streamBridgeSession(args) {
8802
9207
  }
8803
9208
  if (chunk.usage) {
8804
9209
  sawTurnTokenUsage = true;
9210
+ creditProvenance("stream-receipt");
8805
9211
  if (!chunk.usage.known) turnTokensKnown = false;
8806
9212
  turnInputTokens += chunk.usage.input;
8807
9213
  turnOutputTokens += chunk.usage.output;
@@ -8877,6 +9283,7 @@ async function* streamBridgeSession(args) {
8877
9283
  const receipt = readBridgeReceiptTokens(activeRun.profileMaterialization?.inference?.observation?.usage);
8878
9284
  if ("event" in receipt) {
8879
9285
  sawTurnTokenUsage = true;
9286
+ creditProvenance("stream-receipt");
8880
9287
  turnInputTokens += receipt.event.input;
8881
9288
  turnOutputTokens += receipt.event.output;
8882
9289
  addTokenUsage(tokens, receipt.event);
@@ -8886,6 +9293,37 @@ async function* streamBridgeSession(args) {
8886
9293
  if (receipt.event.cacheWrite !== void 0) promptCache.writeTokens = (promptCache.writeTokens ?? 0) + receipt.event.cacheWrite;
8887
9294
  } else tokensUnknownReason ??= receipt.reason;
8888
9295
  }
9296
+ if (harnessStore) {
9297
+ const delta = await readHarnessStoreDelta(harnessStore, observation);
9298
+ if (delta) {
9299
+ const charged = sawTurnTokenUsage ? delta.native : addHarnessUsage(delta.seat, delta.native);
9300
+ if (!harnessUsageIsEmpty(charged)) {
9301
+ const event = {
9302
+ kind: "tokens",
9303
+ input: charged.input,
9304
+ output: charged.output,
9305
+ ...promptCacheTokenClasses(charged.input, {
9306
+ ...charged.cachedInput === void 0 ? {} : { readTokens: charged.cachedInput },
9307
+ ...charged.cacheWriteInput === void 0 ? {} : { writeTokens: charged.cacheWriteInput }
9308
+ }),
9309
+ provenance: "harness-store"
9310
+ };
9311
+ sawTurnTokenUsage = true;
9312
+ creditProvenance("harness-store");
9313
+ turnInputTokens += event.input;
9314
+ turnOutputTokens += event.output;
9315
+ addTokenUsage(tokens, event);
9316
+ if (event.freshInput !== void 0) promptCache.freshInput = (promptCache.freshInput ?? 0) + event.freshInput;
9317
+ if (event.cacheRead !== void 0) promptCache.readTokens = (promptCache.readTokens ?? 0) + event.cacheRead;
9318
+ if (event.cacheWrite !== void 0) promptCache.writeTokens = (promptCache.writeTokens ?? 0) + event.cacheWrite;
9319
+ yield event;
9320
+ }
9321
+ if (delta.unresolved.length > 0) {
9322
+ turnTokensKnown = false;
9323
+ tokensUnknownReason ??= `harness-store: ${delta.unresolved.length} forked rollout(s) could not be attributed to a turn; ${delta.unresolved[0]?.reason ?? "no reason recorded"}`;
9324
+ }
9325
+ }
9326
+ }
8889
9327
  if (!sawTurnTokenUsage || !turnTokensKnown) tokensKnown = false;
8890
9328
  if (!sawTurnCostStatus || !turnUsdKnown) usdKnown = false;
8891
9329
  if (!sawTurnCostStatus || !turnUsdKnown) {
@@ -8923,7 +9361,8 @@ async function* streamBridgeSession(args) {
8923
9361
  usd,
8924
9362
  ...usdKnown ? {} : { usdKnown: false },
8925
9363
  ...estimatedUsdCharged > 0 ? { usdEstimated: estimatedUsdCharged } : {},
8926
- ms: Date.now() - started
9364
+ ms: Date.now() - started,
9365
+ ...tokensProvenance === void 0 || tokensProvenance === "stream-receipt" ? {} : { tokensProvenance }
8927
9366
  };
8928
9367
  const out = {
8929
9368
  content: lastText,
@@ -8965,6 +9404,40 @@ async function* streamBridgeSession(args) {
8965
9404
  * receipt carries no reasoning counter at all, so the codex hazard of adding a reasoning count to
8966
9405
  * an output total that already contains it cannot arise on this path.
8967
9406
  */
9407
+ /**
9408
+ * Open the harness store named on the seam, or nothing when the caller named none.
9409
+ *
9410
+ * A harness with no reader is REFUSED loudly rather than read with codex's decoder. Silently
9411
+ * ignoring it would hand back the same `{0, 0}` the store was configured to fix, with no signal
9412
+ * that the configuration did nothing.
9413
+ */
9414
+ function openBridgeHarnessStore(store) {
9415
+ if (store === void 0) return void 0;
9416
+ if (store.harness !== "codex") throw new ValidationError(`bridgeExecutor: harnessStore.harness ${JSON.stringify(store.harness)} has no store reader; only "codex" is readable today`);
9417
+ return createCodexRolloutStoreReader({
9418
+ root: store.root,
9419
+ ...store.workspaceRoot === void 0 ? {} : { workspaceRoot: store.workspaceRoot }
9420
+ });
9421
+ }
9422
+ /**
9423
+ * Read one turn's worth of the harness store.
9424
+ *
9425
+ * A read that fails is noted on the live activity log and returns nothing: the store is additional
9426
+ * evidence, and a filesystem error on it must never end a turn whose work already happened.
9427
+ */
9428
+ async function readHarnessStoreDelta(reader, observation) {
9429
+ try {
9430
+ return await reader.read();
9431
+ } catch (err) {
9432
+ observation.activity.push({
9433
+ at: Date.now(),
9434
+ kind: "note",
9435
+ label: "harness-store-unreadable",
9436
+ detail: err instanceof Error ? err.message : String(err)
9437
+ });
9438
+ return;
9439
+ }
9440
+ }
8968
9441
  function readBridgeReceiptTokens(usage) {
8969
9442
  if (usage === void 0) return { reason: "usage-unreadable: the turn receipt carried no bridge inference observation" };
8970
9443
  const input = usage.inputTokens;
@@ -10589,6 +11062,8 @@ function meterUsageEvent(totals, ev) {
10589
11062
  if (ev.kind === "tokens") {
10590
11063
  addTokenUsage(totals.tokens, ev);
10591
11064
  if (ev.tokensKnown === false) totals.tokensKnown = false;
11065
+ const source = ev.provenance ?? "stream-receipt";
11066
+ totals.tokensProvenance = totals.tokensProvenance === void 0 || totals.tokensProvenance === source ? source : "mixed";
10592
11067
  return;
10593
11068
  }
10594
11069
  if (ev.kind === "cost") {
@@ -10611,6 +11086,7 @@ function spendFromUsageTotals(totals) {
10611
11086
  usd: totals.usd,
10612
11087
  ...totals.usdKnown ? {} : { usdKnown: false },
10613
11088
  ...totals.usdEstimated > 0 ? { usdEstimated: totals.usdEstimated } : {},
11089
+ ...totals.tokensProvenance === void 0 || totals.tokensProvenance === "stream-receipt" ? {} : { tokensProvenance: totals.tokensProvenance },
10614
11090
  ms: 0
10615
11091
  };
10616
11092
  }
@@ -10867,7 +11343,7 @@ async function teardownExecutor(executor, grace, deadlineAtMs, now) {
10867
11343
  if (timer !== void 0) clearTimeout(timer);
10868
11344
  }
10869
11345
  }
10870
- if (!receipt.destroyed) throw new ValidationError("executor teardown reported destroyed=false");
11346
+ if (!receipt.destroyed) throw new ValidationError(`executor teardown reported destroyed=false${receipt.detail ? `: ${receipt.detail}` : ""}`);
10871
11347
  }
10872
11348
  //#endregion
10873
11349
  //#region src/runtime/supervise/dispatch.ts
@@ -14400,6 +14876,7 @@ async function foldStream(stream, onProgress, signal) {
14400
14876
  ...totals.tokensKnown ? {} : { tokensKnown: false },
14401
14877
  usd: totals.usd,
14402
14878
  ...totals.usdKnown ? {} : { usdKnown: false },
14879
+ ...totals.tokensProvenance === void 0 || totals.tokensProvenance === "stream-receipt" ? {} : { tokensProvenance: totals.tokensProvenance },
14403
14880
  ms: 0
14404
14881
  });
14405
14882
  }
@@ -14427,7 +14904,8 @@ function preserveUnknownTelemetry(streamed, terminal) {
14427
14904
  ms: terminal.ms,
14428
14905
  ...terminal.boxMinutes !== void 0 ? { boxMinutes: terminal.boxMinutes } : {},
14429
14906
  ...terminal.boxMinutesKnown !== void 0 ? { boxMinutesKnown: terminal.boxMinutesKnown } : {},
14430
- ...terminal.boxMinutesProvenance !== void 0 ? { boxMinutesProvenance: terminal.boxMinutesProvenance } : {}
14907
+ ...terminal.boxMinutesProvenance !== void 0 ? { boxMinutesProvenance: terminal.boxMinutesProvenance } : {},
14908
+ ...(streamed.tokensProvenance ?? terminal.tokensProvenance) === void 0 ? {} : { tokensProvenance: streamed.tokensProvenance ?? terminal.tokensProvenance }
14431
14909
  };
14432
14910
  }
14433
14911
  async function awaitAbortable(work, signal) {
@@ -15668,6 +16146,85 @@ function isNonEmptySpend(s) {
15668
16146
  return s.iterations > 0 || s.tokens.input > 0 || s.tokens.output > 0 || s.usd > 0 || s.ms > 0 || s.tokensKnown === false || s.usdKnown === false;
15669
16147
  }
15670
16148
  //#endregion
15671
- export { bridgeModelRouteRefusal as $, INTELLIGENCE_WIRE_VERSION as $t, readWorkerInteractiveBinding as A, controlProfileMaterialization as An, peerMailVerbNames as At, retainedCreateMaterial as B, sandboxActProfileMaterialization as Bn, createSandboxLineage as Bt, timerAt as C, LOCAL_HARNESSES as Cn, AUTHORITY_MARKERS as Ct, readWorkerInteractiveAdmissions as D, CodexExecutionDiagnosticError as Dn, createPeerMailbox as Dt, interactiveAdmissionSeamKey as E, parseCodexTokenUsage as En, claimsAuthority as Et, startRetainedInteractiveRun as F, promptModelProfileMaterialization as Fn, TERMINAL_DECISIONS as Ft, rollingDispatch as G, routerBrain as Gt, effectiveConcurrency as H, validateProfileMaterialization as Hn, acquireSandbox as Ht, reconnectRetainedRun as I, promptOnlyProfileMaterialization as In, createSandboxForSpec as It, assertValidBudget as J, observedModelMatchesDeclared as Jt, DEFAULT_SUCCESSFUL_SHUTDOWN_MS as K, runBrainLoop as Kt, recoverRetainedRun as L, promptResourceProfileMaterialization as Ln, defaultSelectWinner as Lt, workerInteractiveBindingsDir as M, fullProfileMaterialization as Mn, isTerminalNodeStatus as Mt, reconnectRetainedInteractiveRun as N, profileMaterializationAxes$1 as Nn, createInPlaceCliExecutor as Nt, workerInteractiveAdmissionFile as O, AGENT_PROFILE_MATERIALIZATION_AXES as On, isPeerMailEnvelope as Ot, recoverRetainedInteractiveRun as P, promptControlProfileMaterialization as Pn, taskToPrompt as Pt, bridgeAdmissionRead as Q, traceContextToEnv as Qt, startRetainedRun as R, renderProfileMaterializationIssues as Rn, isTerminalDecision as Rt, pollFor as S, DEFAULT_LOCAL_HARNESS as Sn, createInbox as St, waitUntil as T, localHarnessExecutable as Tn, PEER_MAIL_WIRE_KEY as Tt, freeSlots as U, worktreeCliProfileMaterialization as Un, assertBoxlessPromptOptions as Ut, destroyInteractiveEnvironment as V, unsupportedProfileDimensions as Vn, probeSandboxCapabilities as Vt, queueOf as W, readPromptOptions as Wt, spendFromUsageEvents as X, mergeTraceEnv as Xt, createBudgetPool as Y, createPropagatingTraceEmitter as Yt, bindReusableExecutorExecutionId as Z, readTraceContextFromEnv as Zt, recordScopeOwnerMaterialization as _, runSettledCommand as _n, decodeToolPart as _t, uncertainSpawnBudgets as a, exportEvalRuns as an, createExecutor as at, createWaitProbes as b, createWorktree as bn, createActivityLog as bt, pickBestDelivered as c, loopEventToOtelSpan as cn, createWorktreeCliExecutor as ct, driverChild as d, toOtelAttributes as dn, workerTraceEnv as dt, buildLoopOtelSpans as en, bridgeRuntimeAttachmentsKey as et, withDriverExecutor as f, createRuntimeEventCollector as fn, workerTraceHeaders as ft, meterRuntimeOwnedProviderAttempt as g, sanitizeRuntimeStreamEvent as gn, createPushTraceSource as gt, meterRuntimeOwnedAccounting as h, sanitizeKnowledgeReadinessReport as hn, createSteerableSandboxSession as ht, sumMeasuredSpendFromEvents as i, createOtelExporter as in, cliWorktreeExecutor as it, workerInteractiveBindingFile as j, defineProfileMaterializationContract as jn, isLiveNodeStatus as jt, attachWorker as k, assertProfileMaterialization as kn, peerMailTools as kt, runFinalizer as l, padSpanId as ln, WORKER_TRACE_PROPAGATION as lt, deriveNodeExecutionIdentity as m, sanitizeAgentRuntimeEvent as mn, DEFAULT_SANDBOX_STEERING_MAX_TURNS as mt, createSupervisor as n, buildRuntimeEventOtelSpans as nn, captureReusableExecutorConfig as nt, bestDelivered as o, flatOtelSpan as on, createExecutorRegistry as ot, createScope as p, createRuntimeStreamEventCollector as pn, workerTraceSeamKey as pt, teardownExecutor as q, canonicalObservedModel as qt, maxSeqOf as r, createOpenInferenceFileExporter as rn, cliInPlaceExecutor as rt, collectDelivered as s, generateSpanId as sn, snapshotExecutorConfig as st, createRootHandle as t, buildLoopSpanNodes as tn, bridgeStopSignalKey as tt, runTree as u, padTraceId as un, readWorkerTraceContext as ut, scopeOwnerExecutorNodeContext as v, runWorktreeHarness as vn, sandboxSessionTraceSource as vt, validateWaitSpec as w, harnessSupportsReasoningEffort as wn, DEFAULT_PEER_MAIL_LIMITS as wt, isWaitOutcome as x, removeWorktree as xn, readWorkerProgress as xt, settledToIteration as y, captureWorktreeDiff as yn, DEFAULT_STALL_AFTER_MS as yt, startRetainedRunInEnvironment as z, renderUnsupported as zn, runAgentRounds as zt };
16149
+ //#region src/redact.ts
16150
+ const redactedMarker = "[redacted]";
16151
+ /** Secret-bearing key names: when an object key matches, its value is fully
16152
+ * replaced regardless of the value's own content. Lowercased compare. */
16153
+ const secretKeyPattern = /(api[-_]?key|secret|token|password|passwd|authorization|auth|private[-_]?key|credential|access[-_]?key|client[-_]?secret|session[-_]?(id|token)|cookie|bearer)/i;
16154
+ /** In-value secret/PII patterns scrubbed from any string, regardless of key. */
16155
+ const valuePatterns = [
16156
+ /\bBearer\s+[A-Za-z0-9._\-+/=]{8,}/gi,
16157
+ /\b(?:sk|pk|rk|ak)[-_][A-Za-z0-9_-]{12,}/g,
16158
+ /\bgh[pousr]_[A-Za-z0-9]{20,}/g,
16159
+ /\bAKIA[0-9A-Z]{16}\b/g,
16160
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
16161
+ /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g
16162
+ ];
16163
+ /** Secret assignments embedded inside an otherwise opaque string, including
16164
+ * serialized JSON and log-style `key=value` text. */
16165
+ const secretAssignmentPattern = /((?:"|')?(?:api[-_]?key|secret|token|password|passwd|authorization|auth|private[-_]?key|credential|access[-_]?key|client[-_]?secret|session[-_]?(?:id|token)|cookie|bearer)(?:"|')?\s*[:=]\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,;}]+)/gi;
16166
+ /** Scrub a single string of in-value secret/PII patterns. */
16167
+ function scrubString(input) {
16168
+ let out = input;
16169
+ for (const pattern of valuePatterns) out = out.replace(pattern, redactedMarker);
16170
+ return out.replace(secretAssignmentPattern, `$1${redactedMarker}`);
16171
+ }
16172
+ /**
16173
+ * The built-in redactor. Walks objects and arrays; replaces values under
16174
+ * secret-bearing keys wholesale; scrubs in-value patterns from every string.
16175
+ * Cycle-safe (a seen-set short-circuits self-referential payloads to
16176
+ * `'[circular]'`), depth-bounded, and total — never throws on customer input.
16177
+ */
16178
+ function defaultRedactor(value) {
16179
+ return walk(value, /* @__PURE__ */ new WeakSet(), 0);
16180
+ }
16181
+ const maxDepth = 32;
16182
+ function walk(value, seen, depth) {
16183
+ if (depth > maxDepth) return "[truncated]";
16184
+ if (typeof value === "string") return scrubString(value);
16185
+ if (value === null || typeof value !== "object") return value;
16186
+ if (seen.has(value)) return "[circular]";
16187
+ seen.add(value);
16188
+ if (Array.isArray(value)) return value.map((item) => walk(item, seen, depth + 1));
16189
+ const out = {};
16190
+ for (const [key, v] of Object.entries(value)) {
16191
+ if (secretKeyPattern.test(key)) {
16192
+ out[key] = redactedMarker;
16193
+ continue;
16194
+ }
16195
+ out[key] = walk(v, seen, depth + 1);
16196
+ }
16197
+ return out;
16198
+ }
16199
+ /** Stable identity input for saved work that depends on built-in redaction behavior. */
16200
+ function defaultRedactorIdentityMaterial() {
16201
+ const patternIdentity = (pattern) => ({
16202
+ source: pattern.source,
16203
+ flags: pattern.flags
16204
+ });
16205
+ return {
16206
+ marker: redactedMarker,
16207
+ secretKeyPattern: patternIdentity(secretKeyPattern),
16208
+ valuePatterns: valuePatterns.map(patternIdentity),
16209
+ secretAssignmentPattern: patternIdentity(secretAssignmentPattern),
16210
+ maxDepth,
16211
+ scrubString: Function.prototype.toString.call(scrubString),
16212
+ walk: Function.prototype.toString.call(walk),
16213
+ defaultRedactor: Function.prototype.toString.call(defaultRedactor)
16214
+ };
16215
+ }
16216
+ /**
16217
+ * Resolve the redactor a client uses. A caller-supplied hook handles
16218
+ * domain-specific values first, then the built-in scrubber still removes
16219
+ * common credentials and email addresses. Returning `false` is the explicit
16220
+ * opt-out for already-reviewed public values.
16221
+ */
16222
+ function resolveRedactor(redact) {
16223
+ if (redact === false) return (value) => value;
16224
+ if (!redact) return defaultRedactor;
16225
+ return (value) => defaultRedactor(redact(value));
16226
+ }
16227
+ //#endregion
16228
+ export { spendFromUsageEvents as $, createCodexRolloutStoreReader as $t, readWorkerInteractiveAdmissions as A, LOCAL_HARNESSES as An, createPeerMailbox as At, recoverRetainedRun as B, profileMaterializationAxes$1 as Bn, defaultSelectWinner as Bt, createWaitProbes as C, sanitizeRuntimeStreamEvent as Cn, createActivityLog as Ct, validateWaitSpec as D, createWorktree as Dn, DEFAULT_PEER_MAIL_LIMITS as Dt, timerAt as E, captureWorktreeDiff as En, AUTHORITY_MARKERS as Et, workerInteractiveBindingsDir as F, AGENT_PROFILE_MATERIALIZATION_AXES as Fn, isTerminalNodeStatus as Ft, effectiveConcurrency as G, renderProfileMaterializationIssues as Gn, acquireSandbox as Gt, startRetainedRunInEnvironment as H, promptModelProfileMaterialization as Hn, runAgentRounds as Ht, reconnectRetainedInteractiveRun as I, assertProfileMaterialization as In, createInPlaceCliExecutor as It, rollingDispatch as J, unsupportedProfileDimensions as Jn, routerBrain as Jt, freeSlots as K, renderUnsupported as Kn, assertBoxlessPromptOptions as Kt, recoverRetainedInteractiveRun as L, controlProfileMaterialization as Ln, taskToPrompt as Lt, attachWorker as M, localHarnessExecutable as Mn, peerMailTools as Mt, readWorkerInteractiveBinding as N, parseCodexTokenUsage as Nn, peerMailVerbNames as Nt, waitUntil as O, removeWorktree as On, PEER_MAIL_WIRE_KEY as Ot, workerInteractiveBindingFile as P, CodexExecutionDiagnosticError as Pn, isLiveNodeStatus as Pt, createBudgetPool as Q, addHarnessUsage as Qt, startRetainedInteractiveRun as R, defineProfileMaterializationContract as Rn, TERMINAL_DECISIONS as Rt, settledToIteration as S, sanitizeKnowledgeReadinessReport as Sn, DEFAULT_STALL_AFTER_MS as St, pollFor as T, runWorktreeHarness as Tn, createInbox as Tt, retainedCreateMaterial as U, promptOnlyProfileMaterialization as Un, createSandboxLineage as Ut, startRetainedRun as V, promptControlProfileMaterialization as Vn, isTerminalDecision as Vt, destroyInteractiveEnvironment as W, promptResourceProfileMaterialization as Wn, probeSandboxCapabilities as Wt, teardownExecutor as X, worktreeCliProfileMaterialization as Xn, canonicalObservedModel as Xt, DEFAULT_SUCCESSFUL_SHUTDOWN_MS as Y, validateProfileMaterialization as Yn, runBrainLoop as Yt, assertValidBudget as Z, observedModelMatchesDeclared as Zt, deriveNodeExecutionIdentity as _, padTraceId as _n, DEFAULT_SANDBOX_STEERING_MAX_TURNS as _t, createSupervisor as a, traceContextToEnv as an, captureReusableExecutorConfig as at, recordScopeOwnerMaterialization as b, createRuntimeStreamEventCollector as bn, decodeToolPart as bt, uncertainSpawnBudgets as c, buildLoopSpanNodes as cn, createExecutor as ct, pickBestDelivered as d, createOtelExporter as dn, createWorktreeCliExecutor as dt, harnessUsageIsEmpty as en, bindReusableExecutorExecutionId as et, runFinalizer as f, exportEvalRuns as fn, WORKER_TRACE_PROPAGATION as ft, createScope as g, padSpanId as gn, workerTraceSeamKey as gt, withDriverExecutor as h, loopEventToOtelSpan as hn, workerTraceHeaders as ht, createRootHandle as i, readTraceContextFromEnv as in, bridgeStopSignalKey as it, workerInteractiveAdmissionFile as j, harnessSupportsReasoningEffort as jn, isPeerMailEnvelope as jt, interactiveAdmissionSeamKey as k, DEFAULT_LOCAL_HARNESS as kn, claimsAuthority as kt, bestDelivered as l, buildRuntimeEventOtelSpans as ln, createExecutorRegistry as lt, driverChild as m, generateSpanId as mn, workerTraceEnv as mt, defaultRedactorIdentityMaterial as n, createPropagatingTraceEmitter as nn, bridgeModelRouteRefusal as nt, maxSeqOf as o, INTELLIGENCE_WIRE_VERSION as on, cliInPlaceExecutor as ot, runTree as p, flatOtelSpan as pn, readWorkerTraceContext as pt, queueOf as q, sandboxActProfileMaterialization as qn, readPromptOptions as qt, resolveRedactor as r, mergeTraceEnv as rn, bridgeRuntimeAttachmentsKey as rt, sumMeasuredSpendFromEvents as s, buildLoopOtelSpans as sn, cliWorktreeExecutor as st, defaultRedactor as t, readCodexRolloutSession as tn, bridgeAdmissionRead as tt, collectDelivered as u, createOpenInferenceFileExporter as un, snapshotExecutorConfig as ut, meterRuntimeOwnedAccounting as v, toOtelAttributes as vn, createSteerableSandboxSession as vt, isWaitOutcome as w, runSettledCommand as wn, readWorkerProgress as wt, scopeOwnerExecutorNodeContext as x, sanitizeAgentRuntimeEvent as xn, sandboxSessionTraceSource as xt, meterRuntimeOwnedProviderAttempt as y, createRuntimeEventCollector as yn, createPushTraceSource as yt, reconnectRetainedRun as z, fullProfileMaterialization as zn, createSandboxForSpec as zt };
15672
16229
 
15673
- //# sourceMappingURL=supervisor-BSNkaM2a.js.map
16230
+ //# sourceMappingURL=redact-BP8Xn2A3.js.map