@tangle-network/agent-runtime 0.138.0 → 0.139.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 (119) hide show
  1. package/dist/{activation-BHoMDzMv.js → activation-eLJ6uRlP.js} +3 -3
  2. package/dist/{activation-BHoMDzMv.js.map → activation-eLJ6uRlP.js.map} +1 -1
  3. package/dist/agent.d.ts +4 -4
  4. package/dist/agent.js +3 -3
  5. package/dist/{analyst-loop-Dk6_xfhI.js → analyst-loop-DtOEXGzR.js} +3 -3
  6. package/dist/{analyst-loop-Dk6_xfhI.js.map → analyst-loop-DtOEXGzR.js.map} +1 -1
  7. package/dist/analyst-loop.d.ts +1 -1
  8. package/dist/analyst-loop.js +1 -1
  9. package/dist/{authoring-rEOOEWn6.js → authoring-J93uFAwd.js} +3 -3
  10. package/dist/{authoring-rEOOEWn6.js.map → authoring-J93uFAwd.js.map} +1 -1
  11. package/dist/candidate-execution/index.d.ts +3 -3
  12. package/dist/candidate-execution/index.js +4 -4
  13. package/dist/{candidate-execution-CyCLYLfK.js → candidate-execution-uuUeFSc6.js} +5 -5
  14. package/dist/{candidate-execution-CyCLYLfK.js.map → candidate-execution-uuUeFSc6.js.map} +1 -1
  15. package/dist/{conversation-DIUtiLkC.js → conversation-C3eZCvLd.js} +8 -6
  16. package/dist/conversation-C3eZCvLd.js.map +1 -0
  17. package/dist/conversation.d.ts +1 -1
  18. package/dist/conversation.js +1 -1
  19. package/dist/durable.d.ts +34 -1
  20. package/dist/durable.js +82 -1
  21. package/dist/durable.js.map +1 -1
  22. package/dist/{environment-provider-CLNVqp6H.js → environment-provider-BAO8wt1_.js} +147 -48
  23. package/dist/environment-provider-BAO8wt1_.js.map +1 -0
  24. package/dist/{environment-provider-DA8LqBV-.d.ts → environment-provider-Bu3S3v78.d.ts} +3 -3
  25. package/dist/environment-provider.d.ts +1 -1
  26. package/dist/environment-provider.js +1 -1
  27. package/dist/{errors-CVIDr7GQ.js → errors-CDZ8XsVj.js} +34 -9
  28. package/dist/errors-CDZ8XsVj.js.map +1 -0
  29. package/dist/{graph-yaEG0ZiR.js → graph-BbMjq7-x.js} +5 -5
  30. package/dist/{graph-yaEG0ZiR.js.map → graph-BbMjq7-x.js.map} +1 -1
  31. package/dist/{improvement-cycle-BeVj-EGJ.js → improvement-cycle-D6rhMJR0.js} +67 -66
  32. package/dist/improvement-cycle-D6rhMJR0.js.map +1 -0
  33. package/dist/{index-Bdgpx2Dx.d.ts → index-C6yfz0QN.d.ts} +5 -5
  34. package/dist/{index-BOgzou1U.d.ts → index-COnuT0h7.d.ts} +263 -82
  35. package/dist/{index-CETQJlqT.d.ts → index-CTz17pH6.d.ts} +11 -11
  36. package/dist/{index-DQxQgKDs.d.ts → index-DQv7iCeE.d.ts} +6 -6
  37. package/dist/index.d.ts +85 -15
  38. package/dist/index.js +109 -18
  39. package/dist/index.js.map +1 -1
  40. package/dist/intelligence.d.ts +736 -681
  41. package/dist/intelligence.js +113 -8
  42. package/dist/intelligence.js.map +1 -1
  43. package/dist/jsonl-file-DtxhdAkZ.js +57 -0
  44. package/dist/jsonl-file-DtxhdAkZ.js.map +1 -0
  45. package/dist/kernel.d.ts +7 -7
  46. package/dist/kernel.js +12 -12
  47. package/dist/{knowledge-C1TcOBf6.js → knowledge-CD-_FbJT.js} +7 -7
  48. package/dist/{knowledge-C1TcOBf6.js.map → knowledge-CD-_FbJT.js.map} +1 -1
  49. package/dist/knowledge.d.ts +1 -1
  50. package/dist/knowledge.js +1 -1
  51. package/dist/{loop-runner-bin-DhUWzpNp.js → loop-runner-bin-BBz_ACfQ.js} +5 -5
  52. package/dist/{loop-runner-bin-DhUWzpNp.js.map → loop-runner-bin-BBz_ACfQ.js.map} +1 -1
  53. package/dist/{loop-runner-bin-OH61zEVw.d.ts → loop-runner-bin-DUNxyuaG.d.ts} +3 -3
  54. package/dist/loop-runner-bin.d.ts +1 -1
  55. package/dist/loop-runner-bin.js +1 -1
  56. package/dist/{materialization-BP5zspr2.js → materialization-CrdcfWXp.js} +4 -4
  57. package/dist/{materialization-BP5zspr2.js.map → materialization-CrdcfWXp.js.map} +1 -1
  58. package/dist/mcp/bin.js +4 -4
  59. package/dist/mcp/index.d.ts +5 -5
  60. package/dist/mcp/index.js +8 -8
  61. package/dist/mcp/memory-bin.js +1 -1
  62. package/dist/{memory-server-Cdpy7Uu8.js → memory-server-DsKOhzGf.js} +3 -3
  63. package/dist/{memory-server-Cdpy7Uu8.js.map → memory-server-DsKOhzGf.js.map} +1 -1
  64. package/dist/{model-policy-UTTc9Z-A.js → model-policy-DgRJIJse.js} +2 -2
  65. package/dist/{model-policy-UTTc9Z-A.js.map → model-policy-DgRJIJse.js.map} +1 -1
  66. package/dist/{openai-tools-K38wcStR.js → openai-tools-DIKr72_l.js} +2 -2
  67. package/dist/{openai-tools-K38wcStR.js.map → openai-tools-DIKr72_l.js.map} +1 -1
  68. package/dist/{openai-tools-DU3TZvFY.d.ts → openai-tools-yoRRzAUW.d.ts} +2 -2
  69. package/dist/{prepare-Czki1LBy.js → prepare-DK1qnk7-.js} +3 -3
  70. package/dist/{prepare-Czki1LBy.js.map → prepare-DK1qnk7-.js.map} +1 -1
  71. package/dist/primeintellect/index.d.ts +1 -1
  72. package/dist/profiles.d.ts +1 -1
  73. package/dist/profiles.js +1 -1
  74. package/dist/{protected-model-port-DEsTWOFs.d.ts → protected-model-port-B8ssMyUg.d.ts} +7 -7
  75. package/dist/{protected-model-port-OhS0l_6m.js → protected-model-port-DHeCm_UF.js} +2 -2
  76. package/dist/{protected-model-port-OhS0l_6m.js.map → protected-model-port-DHeCm_UF.js.map} +1 -1
  77. package/dist/{redact-BwEdhuVH.d.ts → redact-CLw2B7Qj.d.ts} +9 -9
  78. package/dist/{researcher-DBfKdnAz.js → researcher-CiSY6Wzb.js} +3 -3
  79. package/dist/{researcher-DBfKdnAz.js.map → researcher-CiSY6Wzb.js.map} +1 -1
  80. package/dist/retained-run-binding-Dp2e8xne.js +268 -0
  81. package/dist/retained-run-binding-Dp2e8xne.js.map +1 -0
  82. package/dist/{runtime-DhPCNvuH.d.ts → runtime-CVNWEw16.d.ts} +4 -4
  83. package/dist/{runtime-yCuqlhou.js → runtime-tTA2iCZQ.js} +650 -222
  84. package/dist/runtime-tTA2iCZQ.js.map +1 -0
  85. package/dist/{sandbox-events-CA2amHoA.js → sandbox-events-DPmXlcKw.js} +24 -2
  86. package/dist/sandbox-events-DPmXlcKw.js.map +1 -0
  87. package/dist/{snapshot-BOIprwBk.js → snapshot-cK9K420n.js} +2 -2
  88. package/dist/{snapshot-BOIprwBk.js.map → snapshot-cK9K420n.js.map} +1 -1
  89. package/dist/{spawn-journal-ZKEKel8N.js → spawn-journal-DGXei3xG.js} +5 -58
  90. package/dist/spawn-journal-DGXei3xG.js.map +1 -0
  91. package/dist/{stream-agent-turn-Q5ellSUu.js → stream-agent-turn-4kUH8Nnn.js} +77 -34
  92. package/dist/stream-agent-turn-4kUH8Nnn.js.map +1 -0
  93. package/dist/{stream-agent-turn-DhPlvHwp.d.ts → stream-agent-turn-RjrKGk6S.d.ts} +5 -8
  94. package/dist/{structural-rollout-2Z6J5ttt.js → structural-rollout-7LP9Ex0F.js} +9 -9
  95. package/dist/structural-rollout-7LP9Ex0F.js.map +1 -0
  96. package/dist/{supervise-to2ynnCG.js → supervise-Cx1QY_hj.js} +10 -9
  97. package/dist/{supervise-to2ynnCG.js.map → supervise-Cx1QY_hj.js.map} +1 -1
  98. package/dist/{supervisor-BfJNS2Z3.js → supervisor-BV72aDmP.js} +13 -9
  99. package/dist/supervisor-BV72aDmP.js.map +1 -0
  100. package/dist/testing.d.ts +2 -2
  101. package/dist/testing.js +12 -12
  102. package/dist/{tool-server-Dh-NcbHr.js → tool-server-DEmLr9YY.js} +2 -2
  103. package/dist/{tool-server-Dh-NcbHr.js.map → tool-server-DEmLr9YY.js.map} +1 -1
  104. package/dist/{types-CxU37Uzr.d.ts → types-19ZOddS3.d.ts} +2 -2
  105. package/dist/{types-BBwGSiAj.d.ts → types-C244Huc9.d.ts} +16 -7
  106. package/dist/{types-BCkweg3w.d.ts → types-D4arYjUl.d.ts} +6 -6
  107. package/dist/{workspace-archive-B_JDld25.js → workspace-archive-HYlsPhfm.js} +2 -2
  108. package/dist/{workspace-archive-B_JDld25.js.map → workspace-archive-HYlsPhfm.js.map} +1 -1
  109. package/package.json +4 -4
  110. package/dist/conversation-DIUtiLkC.js.map +0 -1
  111. package/dist/environment-provider-CLNVqp6H.js.map +0 -1
  112. package/dist/errors-CVIDr7GQ.js.map +0 -1
  113. package/dist/improvement-cycle-BeVj-EGJ.js.map +0 -1
  114. package/dist/runtime-yCuqlhou.js.map +0 -1
  115. package/dist/sandbox-events-CA2amHoA.js.map +0 -1
  116. package/dist/spawn-journal-ZKEKel8N.js.map +0 -1
  117. package/dist/stream-agent-turn-Q5ellSUu.js.map +0 -1
  118. package/dist/structural-rollout-2Z6J5ttt.js.map +0 -1
  119. package/dist/supervisor-BfJNS2Z3.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"sandbox-events-CA2amHoA.js","names":[],"sources":["../src/runtime/timestamps.ts","../src/runtime/sandbox-transport-events.ts","../src/runtime/sandbox-events.ts"],"sourcesContent":["import { RuntimeEventEnvelopeSchema } from '@tangle-network/agent-interface'\n\nconst validTimestamp = '2026-01-01T00:00:00.000Z'\n\n/** Validate a timestamp with the public runtime envelope contract. */\nexport function assertRuntimeTimestamp(value: unknown, label: string): asserts value is string {\n try {\n RuntimeEventEnvelopeSchema.parse({\n runId: 'runtime',\n eventId: 'event',\n sequence: 0,\n occurredAt: value,\n receivedAt: validTimestamp,\n event: { type: 'status', status: 'processing' },\n })\n } catch (error) {\n throw new Error(`${label} must be a valid ISO timestamp`, { cause: error })\n }\n}\n\n/** Return whether a value satisfies the public runtime timestamp contract. */\nexport function isRuntimeTimestamp(value: unknown): value is string {\n try {\n assertRuntimeTimestamp(value, 'occurredAt')\n return true\n } catch {\n return false\n }\n}\n","import { CanonicalStreamEventSchema, type StreamEvent } from '@tangle-network/agent-interface'\nimport { assertRuntimeTimestamp } from './timestamps'\n\n/** Parse canonical payload fields without treating transport identity as event data. */\nexport function parseCanonicalTransportEvent(\n type: unknown,\n data: Record<string, unknown>,\n normalized: unknown,\n source: string,\n): StreamEvent | undefined {\n if (!isRecord(data)) {\n throw new Error(`${source} emitted a canonical event without an object payload`)\n }\n const outerType = String(type ?? '')\n if (normalized !== undefined) {\n if (\n typeof normalized === 'object' &&\n normalized !== null &&\n 'type' in normalized &&\n typeof normalized.type === 'string' &&\n normalized.type !== outerType\n ) {\n throw new Error(\n `${source} canonical event type \"${normalized.type}\" does not match transport type \"${outerType}\"`,\n )\n }\n const candidate = CanonicalStreamEventSchema.safeParse(normalized)\n if (!candidate.success) {\n throw new Error(`${source} emitted an invalid normalized canonical event`, {\n cause: candidate.error,\n })\n }\n return candidate.data\n }\n const {\n type: embeddedType,\n eventId: _eventId,\n cursor: _cursor,\n sequence: _sequence,\n occurredAt: _occurredAt,\n normalized: _normalized,\n ...payload\n } = data\n if (embeddedType !== undefined && embeddedType !== outerType) {\n throw new Error(\n `${source} canonical event type \"${String(embeddedType)}\" does not match transport type \"${outerType}\"`,\n )\n }\n const candidate = CanonicalStreamEventSchema.safeParse({ ...payload, type: outerType })\n return candidate.success ? candidate.data : undefined\n}\n\n/** Identity fields carried by either the transport envelope or its data payload. */\nexport interface TransportEventIdentity {\n readonly eventId?: string\n readonly cursor?: string\n readonly sequence?: number\n readonly occurredAt?: string\n}\n\n/** Extract shared event identity without privileging one provider wire shape. */\nexport function extractTransportEventIdentity(event: unknown): TransportEventIdentity {\n const record = isRecord(event) ? event : {}\n const data = isRecord(record.data) ? record.data : {}\n const providerEvent = isRecord(record.providerEvent) ? record.providerEvent : {}\n const providerData = isRecord(providerEvent.data) ? providerEvent.data : {}\n const eventId = stableString(\n record.id ??\n record.eventId ??\n data.eventId ??\n providerEvent.id ??\n providerEvent.eventId ??\n providerData.eventId,\n )\n const cursor = stableString(\n record.cursor ?? data.cursor ?? providerEvent.cursor ?? providerData.cursor,\n )\n const sequence = optionalSequence(\n record.sequence ?? data.sequence ?? providerEvent.sequence ?? providerData.sequence,\n )\n const occurredAt = optionalTimestamp(\n record.occurredAt ?? data.occurredAt ?? providerEvent.occurredAt ?? providerData.occurredAt,\n )\n return {\n ...(eventId === undefined ? {} : { eventId }),\n ...(cursor === undefined ? {} : { cursor }),\n ...(sequence === undefined ? {} : { sequence }),\n ...(occurredAt === undefined ? {} : { occurredAt }),\n }\n}\n\nfunction stableString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 && value.trim() === value ? value : undefined\n}\n\nfunction finiteNonNegativeInteger(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\nfunction optionalSequence(value: unknown): number | undefined {\n if (value === undefined) return undefined\n if (finiteNonNegativeInteger(value) === undefined) {\n throw new Error('transport event sequence must be a non-negative safe integer')\n }\n return value as number\n}\n\nfunction optionalTimestamp(value: unknown): string | undefined {\n if (value === undefined) return undefined\n assertRuntimeTimestamp(value, 'occurredAt')\n return value\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","/**\n * Sandbox-event → runtime-event mapping.\n *\n * The sandbox SDK emits a polymorphic `SandboxEvent = { type, data, id? }`\n * whose `type` vocabulary is backend-determined (opencode, etc.) rather than\n * enumerated by the SDK. Two consumers project it:\n * - the loop kernel's cost ledger (`extractLlmCallEvent`) — sums usage off\n * every cost-bearing event, regardless of stream shape;\n * - the `AgentRuntime.act` streaming contract (`mapSandboxEvent`) — projects\n * incremental events to the `RuntimeStreamEvent` chat-UX vocabulary.\n *\n * Both live here so the empirically-observed `type` vocabulary has one home.\n */\n\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport type { RuntimeStreamEvent } from '../types'\n\n/**\n * Forward a sandbox event to an optional observer without letting observer\n * behavior affect the run. The observer receives a defensive copy, synchronous\n * throws are swallowed, and returned promises are deliberately not awaited.\n */\nexport function notifySandboxEventObserver<Meta>(\n event: SandboxEvent,\n observer: ((event: SandboxEvent, meta: Meta) => void | PromiseLike<void>) | undefined,\n meta: Meta,\n): void {\n if (!observer) return\n try {\n const result = observer(cloneEventForObserver(event), meta)\n if (result && typeof result.then === 'function') {\n void result.then(undefined, () => {})\n }\n } catch {\n // Live observation is optional and must never interrupt the event stream.\n }\n}\n\nfunction cloneEventForObserver(event: SandboxEvent): SandboxEvent {\n try {\n return structuredClone(event)\n } catch {\n return copyPlainSpine(event, new WeakMap()) as SandboxEvent\n }\n}\n\nfunction copyPlainSpine(value: unknown, seen: WeakMap<object, unknown>): unknown {\n if (value === null || typeof value !== 'object') return value\n const existing = seen.get(value)\n if (existing !== undefined) return existing\n if (Array.isArray(value)) {\n const copy: unknown[] = []\n seen.set(value, copy)\n for (const item of value) copy.push(copyPlainSpine(item, seen))\n return copy\n }\n const proto = Object.getPrototypeOf(value)\n if (proto !== Object.prototype && proto !== null) return {}\n const copy: Record<string, unknown> = {}\n seen.set(value, copy)\n for (const [key, child] of Object.entries(value)) {\n copy[key] = copyPlainSpine(child, seen)\n }\n return copy\n}\n\n/**\n * Extract a `RuntimeStreamEvent`-shaped `llm_call` from a sandbox event when\n * the event carries usage/cost data. Returns `undefined` for non-cost events\n * so the kernel can iterate the full stream without branching.\n *\n * Canonical cost-carrying types observed in the wild:\n * - `llm_call` — `data: { model, tokensIn, tokensOut, costUsd, ... }`\n * - `message.completed` / `result` — `data: { usage: { inputTokens,\n * outputTokens, totalCostUsd? } }`\n * - `cost.usage` / `usage` — same shape under a dedicated type\n *\n * Numeric coercion is strict: `Number.isFinite` gates every accumulator write\n * so a sentinel `NaN` from a misbehaving backend cannot poison the ledger.\n */\nexport function extractLlmCallEvent(\n event: SandboxEvent,\n agentRunName: string,\n): (RuntimeStreamEvent & { type: 'llm_call' }) | undefined {\n if (!event || typeof event !== 'object') return undefined\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n\n if (type === 'llm_call' || type === 'cost.usage' || type === 'usage') {\n return buildLlmCall(data, agentRunName)\n }\n if (type === 'message.completed' || type === 'result' || type === 'final') {\n const usage = data.usage as Record<string, unknown> | undefined\n if (!usage || typeof usage !== 'object') return undefined\n return buildLlmCall({ ...usage, model: data.model ?? usage.model }, agentRunName)\n }\n // sandbox 0.4.0 terminal event: `data = { tokenUsage: { inputTokens, outputTokens,\n // reasoningTokens, cacheReadInputTokens }, totalCostUsd }`. Usage lives under\n // `tokenUsage` (not `usage`) and the cost is top-level — neither matched the\n // branches above, so an in-process loopDispatch run reported {0,0} and the\n // backend-integrity guard misread a real run as a stub. Reasoning tokens are\n // billed output (reasoning models), so they fold into the output count. The prompt-cache\n // counters are read off the SAME `tokenUsage` record rather than re-derived, because only\n // that record states what the provider billed.\n if (type === 'done') {\n const usage = data.tokenUsage as Record<string, unknown> | undefined\n if (!usage || typeof usage !== 'object') return undefined\n const out = pickFiniteNumber(usage, ['outputTokens', 'completion_tokens', 'tokensOut'])\n const reasoning = pickFiniteNumber(usage, ['reasoningTokens'])\n const mergedOut =\n out !== undefined || reasoning !== undefined ? (out ?? 0) + (reasoning ?? 0) : undefined\n const cache = readPromptCacheUsage(usage)\n return buildLlmCall(\n {\n inputTokens: usage.inputTokens,\n outputTokens: mergedOut,\n totalCostUsd: data.totalCostUsd,\n model: data.model ?? usage.model,\n ...(cache !== undefined ? { promptCache: cache } : {}),\n },\n agentRunName,\n )\n }\n return undefined\n}\n\n/**\n * Sum the token usage + USD cost of a sandbox turn's events — the one honest way to meter an\n * `openSandboxRun` cell. Folds `extractLlmCallEvent` over the stream (which reads usage off EVERY backend\n * event shape), so a `runProfileMatrix` dispatch can report it to `ctx.cost`:\n *\n * receipt: (turn) => {\n * const u = sumSandboxUsage(turn.events)\n * return { model, inputTokens: u.input, outputTokens: u.output,\n * ...(u.tokensKnown === false ? { usageUnknown: true } : {}),\n * ...(u.usdKnown !== false && u.costUsd > 0 ? { actualCostUsd: u.costUsd } : {}),\n * ...(u.usdKnown === false ? { costUnknown: true } : {}),\n * ...(u.estimatedCostUsd !== undefined ? { estimatedCostUsd: u.estimatedCostUsd } : {}) }\n * }\n *\n * Without this a cell reads `{tokens:0, cost:0}` and the backend-integrity guard correctly aborts the\n * matrix as a stub. `agentRunName` is the fallback model label for cost-only events (default `'agent'`).\n */\nexport function sumSandboxUsage(\n events: readonly SandboxEvent[],\n agentRunName = 'agent',\n): {\n input: number\n output: number\n costUsd: number\n tokensKnown?: false\n usdKnown?: false\n estimatedCostUsd?: number\n} {\n let input = 0\n let output = 0\n let costUsd = 0\n let estimatedCostUsd = 0\n let sawEstimate = false\n let sawCall = false\n let tokensKnown = true\n let usdKnown = true\n for (const ev of events) {\n const call = extractLlmCallEvent(ev, agentRunName)\n if (!call) continue\n sawCall = true\n input += call.tokensIn ?? 0\n output += call.tokensOut ?? 0\n costUsd += call.costUsd ?? 0\n if (call.tokensKnown === false) tokensKnown = false\n if (call.usdKnown === false) usdKnown = false\n if (call.estimatedCostUsd !== undefined) {\n estimatedCostUsd += call.estimatedCostUsd\n sawEstimate = true\n }\n }\n return {\n input,\n output,\n costUsd,\n ...(sawCall && tokensKnown ? {} : { tokensKnown: false as const }),\n ...(sawCall && usdKnown ? {} : { usdKnown: false as const }),\n ...(sawEstimate ? { estimatedCostUsd } : {}),\n }\n}\n\nfunction buildLlmCall(\n data: Record<string, unknown>,\n agentRunName: string,\n): (RuntimeStreamEvent & { type: 'llm_call' }) | undefined {\n const tokensIn = pickFiniteNumber(data, ['tokensIn', 'inputTokens', 'prompt_tokens'])\n const outputTokens = pickFiniteNumber(data, ['tokensOut', 'outputTokens', 'completion_tokens'])\n const reasoningTokens = pickFiniteNumber(data, ['reasoningTokens'])\n const tokensOut =\n outputTokens !== undefined || reasoningTokens !== undefined\n ? (outputTokens ?? 0) + (reasoningTokens ?? 0)\n : undefined\n const reportedCostUsd = pickFiniteNumber(data, ['costUsd', 'totalCostUsd', 'cost_usd', 'cost'])\n const explicitTokensKnown = data.tokensKnown ?? data.tokens_known\n const explicitCostKnown = data.costKnown ?? data.cost_known ?? data.usdKnown ?? data.usd_known\n const costProvenance = data.costProvenance ?? data.cost_provenance\n const explicitEstimate = pickFiniteNumber(data, ['estimatedCostUsd', 'estimated_cost_usd'])\n const catalogEstimate =\n costProvenance === 'catalog-estimate' ? (explicitEstimate ?? reportedCostUsd) : explicitEstimate\n const costUsd = costProvenance === 'catalog-estimate' ? undefined : reportedCostUsd\n const promptCache = readPromptCacheUsage(data)\n const tokensKnown =\n explicitTokensKnown !== false && tokensIn !== undefined && tokensOut !== undefined\n // Sandbox's canonical terminal `totalCostUsd` is already the provider-reported receipt. The\n // current SDK carries no provenance tag, so absence means the canonical receipt rather than\n // \"unknown\". Explicit estimates and explicit false-known markers remain unknown.\n const usdKnown =\n explicitCostKnown !== false &&\n costUsd !== undefined &&\n (costProvenance === undefined ||\n costProvenance === 'provider-receipt' ||\n costProvenance === 'billing-receipt')\n if (\n tokensIn === undefined &&\n tokensOut === undefined &&\n costUsd === undefined &&\n catalogEstimate === undefined &&\n promptCache === undefined &&\n explicitTokensKnown !== false &&\n explicitCostKnown !== false\n ) {\n return undefined\n }\n const model = typeof data.model === 'string' && data.model.length > 0 ? data.model : agentRunName\n const event: RuntimeStreamEvent & { type: 'llm_call' } = {\n type: 'llm_call',\n model,\n }\n if (tokensIn !== undefined) event.tokensIn = tokensIn\n if (tokensOut !== undefined) event.tokensOut = tokensOut\n if (!tokensKnown) event.tokensKnown = false\n if (costUsd !== undefined) event.costUsd = costUsd\n if (!usdKnown) event.usdKnown = false\n if (catalogEstimate !== undefined) event.estimatedCostUsd = catalogEstimate\n if (promptCache !== undefined) event.promptCache = promptCache\n return event\n}\n\n/**\n * Every wire spelling of a prompt-cache READ counter, in precedence order: the canonical name\n * first, then the spellings observed on the paths that reach this extractor — the sandbox terminal\n * `tokenUsage` record, the cli-bridge OpenAI-compatible usage object (which normalizes every\n * backend to Anthropic's `cache_read_input_tokens`), Anthropic verbatim, OpenAI's\n * `prompt_tokens_details.cached_tokens`, and DeepSeek's `prompt_cache_hit_tokens`.\n */\nconst PROMPT_CACHE_READ_KEYS = [\n 'readTokens',\n 'read_tokens',\n 'cacheReadInputTokens',\n 'cache_read_input_tokens',\n 'cacheRead',\n 'cache_read',\n 'cachedInputTokens',\n 'cachedTokens',\n 'cached_tokens',\n 'prompt_cache_hit_tokens',\n]\n\n/**\n * Every wire spelling of a prompt-cache WRITE counter. OpenAI reports no write counter at all, so\n * an OpenAI-shaped usage record matches nothing here and the write stays absent — which is the\n * point: absent is not zero.\n */\nconst PROMPT_CACHE_WRITE_KEYS = [\n 'writeTokens',\n 'write_tokens',\n 'cacheWriteInputTokens',\n 'cache_write_input_tokens',\n 'cacheCreationInputTokens',\n 'cache_creation_input_tokens',\n 'cacheWrite',\n 'cache_write',\n]\n\nconst PROMPT_CACHE_MISS_KEYS = ['missTokens', 'miss_tokens', 'prompt_cache_miss_tokens']\n\nconst PROMPT_CACHE_SAVINGS_KEYS = ['readSavingsUsd', 'read_savings_usd']\n\n/**\n * Read the provider's own prompt-cache accounting off one usage-bearing event payload, in the\n * `PromptCacheUsage` vocabulary the router, driver, and chat-client paths already speak.\n *\n * Two sources, one record. A payload that already carries a `promptCache` / `prompt_cache` object\n * is forwarded VERBATIM — those fields are the provider's own report, and an unrecognized one must\n * stay visible rather than be bucketed away. On top of that, flat provider counters are translated\n * to the canonical names, filling only the names the verbatim object did not already define.\n *\n * A counter the payload does not carry is left out. Defaulting it to zero would assert the provider\n * measured no cache, which is a different fact from a provider that reported nothing — and it is\n * the fact the budget reads to decide whether its charge is a measurement or a bound.\n */\nfunction readPromptCacheUsage(\n data: Record<string, unknown>,\n): Record<string, number | string> | undefined {\n const declared = finiteMetadata(data.promptCache ?? data.prompt_cache)\n const nested = plainRecord(data.promptCache) ?? plainRecord(data.prompt_cache)\n const details = plainRecord(data.prompt_tokens_details)\n const sources = [nested, data, details].filter(\n (s): s is Record<string, unknown> => s !== undefined,\n )\n\n const canonical: Record<string, number | string> = {}\n const readTokens = pickTokenCount(sources, PROMPT_CACHE_READ_KEYS)\n const writeTokens = pickTokenCount(sources, PROMPT_CACHE_WRITE_KEYS)\n const missTokens = pickTokenCount(sources, PROMPT_CACHE_MISS_KEYS)\n const readSavingsUsd = pickNonNegativeNumber(sources, PROMPT_CACHE_SAVINGS_KEYS)\n const status =\n nested !== undefined && typeof nested.status === 'string' ? nested.status : undefined\n if (readTokens !== undefined) canonical.readTokens = readTokens\n if (writeTokens !== undefined) canonical.writeTokens = writeTokens\n if (missTokens !== undefined) canonical.missTokens = missTokens\n if (readSavingsUsd !== undefined) canonical.readSavingsUsd = readSavingsUsd\n if (status !== undefined) canonical.status = status\n\n const merged = { ...canonical, ...declared }\n return Object.keys(merged).length > 0 ? merged : undefined\n}\n\nfunction plainRecord(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n}\n\nfunction pickTokenCount(\n sources: readonly Record<string, unknown>[],\n keys: readonly string[],\n): number | undefined {\n for (const key of keys) {\n for (const source of sources) {\n const value = source[key]\n if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) return value\n }\n }\n return undefined\n}\n\nfunction pickNonNegativeNumber(\n sources: readonly Record<string, unknown>[],\n keys: readonly string[],\n): number | undefined {\n for (const key of keys) {\n for (const source of sources) {\n const value = source[key]\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return value\n }\n }\n return undefined\n}\n\nfunction finiteMetadata(value: unknown): Record<string, number | string> | undefined {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined\n const result: Record<string, number | string> = {}\n for (const [key, entry] of Object.entries(value)) {\n if ((typeof entry === 'number' && Number.isFinite(entry)) || typeof entry === 'string') {\n result[key] = entry\n }\n }\n return Object.keys(result).length > 0 ? result : undefined\n}\n\nfunction pickFiniteNumber(data: Record<string, unknown>, keys: string[]): number | undefined {\n for (const key of keys) {\n const value = data[key]\n if (typeof value === 'number' && Number.isFinite(value)) return value\n }\n return undefined\n}\n\n/**\n * Cross-event state for {@link mapSandboxToolEvent}. Sandbox backends emit a\n * tool invocation as MANY `message.part.updated` frames on the same call id\n * (pending → running → completed), so faithful projection needs per-call\n * status memory: one `tool_call` on first sighting, at most one `tool_result`\n * on the terminal transition, nothing on intermediate re-frames. Create one\n * state per turn via {@link createSandboxToolPartState}.\n *\n * @experimental\n */\nexport interface SandboxToolPartState {\n /** Last seen status per tool call id. A terminal status is sticky — later\n * frames on a settled call project to nothing. */\n statusByCall: Map<string, string>\n /** Sequence for synthesized call ids when an event carries none. */\n seq: number\n}\n\n/**\n * Fresh per-turn {@link SandboxToolPartState} for {@link mapSandboxToolEvent} — an\n * empty call-status map so each turn projects tool frames independently.\n *\n * @experimental\n */\nexport function createSandboxToolPartState(): SandboxToolPartState {\n return { statusByCall: new Map(), seq: 0 }\n}\n\n/** Terminal tool statuses that are failures (everything here settles the call). */\nconst TERMINAL_TOOL_FAILURE =\n /^(error|errored|failed|failure|cancelled|canceled|timeout|timed_out)$/i\n\n/**\n * Project one `SandboxEvent` onto the `tool_call` / `tool_result` variants of\n * `RuntimeStreamEvent` — the tool-part projection `mapSandboxEvent`\n * deliberately does NOT perform. Opt-in and additive: `mapSandboxEvent`'s\n * default vocabulary (text/reasoning deltas + `llm_call`) is unchanged;\n * consumers that need the tool surface (chat UIs rendering tool activity)\n * compose this projector alongside it — `streamAgentTurn` does exactly that\n * under its `preserveToolParts` option.\n *\n * Handled shapes (observed on the opencode / claude-code sandbox backends):\n * - `message.part.updated` with `part.type === 'tool'` — stateful: a\n * `tool_call` on the call id's first frame (args from `state.input` or\n * `state.metadata.input`), a `tool_result` when the status transitions to\n * `completed` (result from `state.output` / `metadata.output`) or to a\n * terminal failure (result is `{ error, status, output? }` — the error\n * surfaced in-band, never dropped).\n * - bare `tool*` event types (`tool.call`, `tool_result`, …) — stateless:\n * `*result*` types project to `tool_result`, the rest to `tool_call`.\n *\n * Returns `[]` for every non-tool event.\n *\n * @experimental\n */\nexport function mapSandboxToolEvent(\n event: SandboxEvent,\n state: SandboxToolPartState,\n): (RuntimeStreamEvent & { type: 'tool_call' | 'tool_result' })[] {\n if (!event || typeof event !== 'object') return []\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n\n if (type === 'message.part.updated') {\n const part =\n data.part && typeof data.part === 'object' ? (data.part as Record<string, unknown>) : {}\n if (String(part.type ?? '') !== 'tool') return []\n return projectToolPart(part, state, typeof event.id === 'string' ? event.id : undefined)\n }\n\n if (type.includes('tool')) {\n const callId =\n pickString(data, ['toolCallId', 'tool_use_id', 'id']) ??\n (typeof event.id === 'string' ? event.id : undefined) ??\n `sandbox-tool-${++state.seq}`\n const toolName = pickString(data, ['name', 'toolName', 'tool']) ?? 'sandbox_tool'\n if (type.includes('result')) {\n return [\n {\n type: 'tool_result',\n toolName,\n toolCallId: callId,\n result: data.output ?? data.result ?? data.content ?? data,\n },\n ]\n }\n return [\n { type: 'tool_call', toolName, toolCallId: callId, args: data.input ?? data.args ?? {} },\n ]\n }\n\n return []\n}\n\nfunction projectToolPart(\n part: Record<string, unknown>,\n state: SandboxToolPartState,\n eventId: string | undefined,\n): (RuntimeStreamEvent & { type: 'tool_call' | 'tool_result' })[] {\n const callId =\n pickString(part, ['callID', 'callId', 'toolCallId', 'id']) ??\n eventId ??\n `sandbox-tool-${++state.seq}`\n const toolName = pickString(part, ['tool', 'toolName', 'name']) ?? 'sandbox_tool'\n const toolState =\n part.state && typeof part.state === 'object' ? (part.state as Record<string, unknown>) : {}\n const metadata =\n toolState.metadata && typeof toolState.metadata === 'object'\n ? (toolState.metadata as Record<string, unknown>)\n : {}\n const status = pickString(toolState, ['status']) ?? 'updated'\n\n const previous = state.statusByCall.get(callId)\n const settled =\n previous === 'completed' || (previous !== undefined && TERMINAL_TOOL_FAILURE.test(previous))\n if (settled) return []\n\n const out: (RuntimeStreamEvent & { type: 'tool_call' | 'tool_result' })[] = []\n if (previous === undefined) {\n out.push({\n type: 'tool_call',\n toolName,\n toolCallId: callId,\n args: toolState.input ?? metadata.input ?? {},\n })\n }\n state.statusByCall.set(callId, status)\n\n if (status === 'completed') {\n out.push({\n type: 'tool_result',\n toolName,\n toolCallId: callId,\n result: toolState.output ?? metadata.output ?? '',\n })\n } else if (TERMINAL_TOOL_FAILURE.test(status)) {\n const message =\n pickString(toolState, ['error', 'message']) ??\n pickString(metadata, ['error', 'message']) ??\n `sandbox tool ended with status ${status}`\n const output = toolState.output ?? metadata.output\n out.push({\n type: 'tool_result',\n toolName,\n toolCallId: callId,\n result: { error: message, status, ...(output !== undefined ? { output } : {}) },\n })\n }\n return out\n}\n\nfunction pickString(data: Record<string, unknown>, keys: string[]): string | undefined {\n for (const key of keys) {\n const value = data[key]\n if (typeof value === 'string' && value.length > 0) return value\n }\n return undefined\n}\n\n/**\n * Project one `SandboxEvent` onto the `RuntimeStreamEvent` chat-UX vocabulary,\n * for runtimes that bridge a sandbox `streamPrompt` into the\n * `AgentRuntime.act` streaming contract. Returns `undefined` for events that\n * have no faithful projection — the raw stream is preserved separately for the\n * `OutputAdapter`, so an unmapped event never loses data.\n *\n * Mapped (the task-optional incremental variants — no synthesized task\n * lifecycle, no guessed tool-part shapes):\n * - `message.part.updated` text part → `text_delta`\n * - `message.part.updated` reasoning/thinking part → `reasoning_delta`\n * - cost-bearing events → `llm_call` (shared with the ledger extractor)\n *\n * Tool parts are deliberately NOT mapped here (unchanged default) — compose\n * {@link mapSandboxToolEvent} alongside when a consumer needs them.\n *\n * The opencode backend emits incremental text as\n * `{ type: 'message.part.updated', data: { part: { type, text }, delta } }`;\n * `delta` is the increment, `part.text` the running accumulation.\n */\nexport function mapSandboxEvent(\n event: SandboxEvent,\n opts: { agentRunName?: string } = {},\n): RuntimeStreamEvent | undefined {\n if (!event || typeof event !== 'object') return undefined\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n\n if (type === 'message.part.updated') {\n const part =\n data.part && typeof data.part === 'object' ? (data.part as Record<string, unknown>) : {}\n const partType = String(part.type ?? '')\n const delta = typeof data.delta === 'string' ? data.delta : undefined\n const text = delta ?? (typeof part.text === 'string' ? part.text : undefined)\n if (text === undefined) return undefined\n if (partType === 'text') return { type: 'text_delta', text }\n if (partType === 'reasoning' || partType === 'thinking')\n return { type: 'reasoning_delta', text }\n return undefined\n }\n\n return extractLlmCallEvent(event, opts.agentRunName ?? 'agent')\n}\n\nexport {\n extractTransportEventIdentity,\n parseCanonicalTransportEvent,\n type TransportEventIdentity,\n} from './sandbox-transport-events'\n"],"mappings":";;AAEA,MAAM,iBAAiB;;AAGvB,SAAgB,uBAAuB,OAAgB,OAAwC;CAC7F,IAAI;EACF,2BAA2B,MAAM;GAC/B,OAAO;GACP,SAAS;GACT,UAAU;GACV,YAAY;GACZ,YAAY;GACZ,OAAO;IAAE,MAAM;IAAU,QAAQ;GAAa;EAChD,CAAC;CACH,SAAS,OAAO;EACd,MAAM,IAAI,MAAM,GAAG,MAAM,iCAAiC,EAAE,OAAO,MAAM,CAAC;CAC5E;AACF;;;;ACdA,SAAgB,6BACd,MACA,MACA,YACA,QACyB;CACzB,IAAI,CAAC,SAAS,IAAI,GAChB,MAAM,IAAI,MAAM,GAAG,OAAO,qDAAqD;CAEjF,MAAM,YAAY,OAAO,QAAQ,EAAE;CACnC,IAAI,eAAe,KAAA,GAAW;EAC5B,IACE,OAAO,eAAe,YACtB,eAAe,QACf,UAAU,cACV,OAAO,WAAW,SAAS,YAC3B,WAAW,SAAS,WAEpB,MAAM,IAAI,MACR,GAAG,OAAO,yBAAyB,WAAW,KAAK,mCAAmC,UAAU,EAClG;EAEF,MAAM,YAAY,2BAA2B,UAAU,UAAU;EACjE,IAAI,CAA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,KAAA;EAC/B,IAAI,aAAa,QAAQ,OAAO;GAAE,MAAM;GAAc;EAAK;EAC3D,IAAI,aAAa,eAAe,aAAa,YAC3C,OAAO;GAAE,MAAM;GAAmB;EAAK;EACzC;CACF;CAEA,OAAO,oBAAoB,OAAO,KAAK,gBAAgB,OAAO;AAChE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"spawn-journal-ZKEKel8N.js","names":["isNoEntError"],"sources":["../src/durable/content-address.ts","../src/runtime/supervise/trace-evidence.ts","../src/runtime/supervise/tree-key.ts","../src/durable/jsonl-file.ts","../src/durable/spawn-journal.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\n\n/** Stable content address shared by result and trace artifacts. */\nexport function contentAddress(artifact: unknown): string {\n const hex = createHash('sha256').update(stableStringify(artifact), 'utf-8').digest('hex')\n return `sha256:${hex}`\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null'\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(',')}}`\n}\n","/**\n * Durable structured tool evidence for supervised workers.\n *\n * The executor-owned `TraceSource` is collected before teardown, snapshotted into the shared\n * content-addressed blob store, and only then referenced by a settlement. Analysis reconstructs\n * agent-eval's bounded `TraceAnalysisStore` from those exact bytes. Worker output is never accepted\n * as a substitute for tool evidence.\n *\n * @experimental\n */\n\nimport {\n isToolSpan,\n type Span,\n type ToolSpan,\n type TraceAnalysisStore,\n toolSpansToTraceAnalysisStore,\n} from '@tangle-network/agent-eval'\nimport { contentAddress } from '../../durable/content-address'\nimport { ValidationError } from '../../errors'\nimport type { TraceSource } from './trace-source'\nimport type { ResultBlobStore, WorkerTraceEvidence } from './types'\n\n/** Schema version for content-addressed worker tool-trace artifacts. */\nexport const WORKER_TOOL_TRACE_SCHEMA_VERSION = 1 as const\n\n/** Bytes stored under `WorkerTraceEvidence.traceRef`. */\nexport interface WorkerToolTraceArtifact {\n readonly schemaVersion: typeof WORKER_TOOL_TRACE_SCHEMA_VERSION\n readonly spans: ReadonlyArray<ToolSpan>\n}\n\n/** Structural guard for the official bounded trace-analysis read contract. */\nexport function isTraceAnalysisStore(value: unknown): value is TraceAnalysisStore {\n if (value === null || typeof value !== 'object') return false\n const store = value as Partial<Record<keyof TraceAnalysisStore, unknown>>\n return (\n typeof store.getOverview === 'function' &&\n typeof store.queryTraces === 'function' &&\n typeof store.countTraces === 'function' &&\n typeof store.viewTrace === 'function' &&\n typeof store.viewSpans === 'function' &&\n typeof store.searchTrace === 'function' &&\n typeof store.searchSpan === 'function'\n )\n}\n\n/** Collect and persist one executor's structured tool trace without changing its task outcome. */\nexport async function captureWorkerTraceEvidence(\n readSource: (() => TraceSource | undefined) | undefined,\n blobs: ResultBlobStore,\n executed: boolean,\n): Promise<WorkerTraceEvidence> {\n if (!executed) return unavailable('execution-did-not-start')\n if (readSource === undefined) return unavailable('executor-did-not-expose-trace-source')\n\n let source: TraceSource | undefined\n try {\n source = readSource()\n } catch {\n return unavailable('trace-source-unavailable')\n }\n if (source === undefined) return unavailable('trace-source-unavailable')\n\n let collected: unknown\n try {\n collected = await source.collect()\n } catch {\n return unavailable('trace-collection-failed')\n }\n if (!Array.isArray(collected) || collected.some((span) => !isToolSpanValue(span))) {\n return unavailable('invalid-tool-spans')\n }\n if (collected.length === 0) return unavailable('no-tool-spans-captured')\n\n let artifact: WorkerToolTraceArtifact\n let traceRef: string\n try {\n const snapshot = structuredClone(collected) as ToolSpan[]\n // Use agent-eval's canonical adapter as the full integrity check before the durable receipt\n // claims these spans are analyzable. `isToolSpan` only narrows the discriminated union.\n toolSpansToTraceAnalysisStore(snapshot)\n artifact = {\n schemaVersion: WORKER_TOOL_TRACE_SCHEMA_VERSION,\n spans: snapshot,\n }\n traceRef = contentAddress(artifact)\n } catch {\n return unavailable('invalid-tool-spans')\n }\n try {\n await blobs.put(traceRef, artifact)\n } catch {\n return unavailable('trace-persistence-failed')\n }\n return Object.freeze({ status: 'available', traceRef, spanCount: artifact.spans.length })\n}\n\n/** Rehydrate exact persisted spans through agent-eval's one bounded trace-analysis adapter. */\nexport async function workerTraceAnalysisStore(\n evidence: WorkerTraceEvidence,\n blobs: Pick<ResultBlobStore, 'get'>,\n): Promise<TraceAnalysisStore> {\n if (evidence.status === 'unavailable') {\n // The published adapter owns the missing-evidence error and its classification.\n return toolSpansToTraceAnalysisStore(undefined)\n }\n const raw = await blobs.get(evidence.traceRef)\n if (raw === undefined) {\n throw new ValidationError(\n `worker trace blob '${evidence.traceRef}' is missing; the settlement evidence is incomplete`,\n )\n }\n const artifact = parseWorkerToolTraceArtifact(raw, evidence.traceRef)\n if (artifact.spans.length !== evidence.spanCount) {\n throw new ValidationError(\n `worker trace blob '${evidence.traceRef}' has ${artifact.spans.length} spans but its settlement records ${evidence.spanCount}`,\n )\n }\n return toolSpansToTraceAnalysisStore(artifact.spans)\n}\n\n/** Validate a stored trace artifact before an analyst or replay trusts it. */\nexport function parseWorkerToolTraceArtifact(\n value: unknown,\n traceRef = '<unknown>',\n): WorkerToolTraceArtifact {\n if (\n value === null ||\n typeof value !== 'object' ||\n (value as { schemaVersion?: unknown }).schemaVersion !== WORKER_TOOL_TRACE_SCHEMA_VERSION ||\n !Array.isArray((value as { spans?: unknown }).spans)\n ) {\n throw new ValidationError(\n `worker trace blob '${traceRef}' is not a version-${WORKER_TOOL_TRACE_SCHEMA_VERSION} tool trace artifact`,\n )\n }\n const spans = (value as { spans: unknown[] }).spans\n if (spans.length === 0) {\n // Missing spans cannot prove a tool-free run; preserve agent-eval's explicit integrity error.\n return {\n schemaVersion: WORKER_TOOL_TRACE_SCHEMA_VERSION,\n spans: spans as ToolSpan[],\n }\n }\n if (spans.some((span) => !isToolSpanValue(span))) {\n throw new ValidationError(`worker trace blob '${traceRef}' contains a non-tool span`)\n }\n return {\n schemaVersion: WORKER_TOOL_TRACE_SCHEMA_VERSION,\n spans: spans as ToolSpan[],\n }\n}\n\nfunction unavailable(reason: Extract<WorkerTraceEvidence, { status: 'unavailable' }>['reason']) {\n return Object.freeze({ status: 'unavailable' as const, reason })\n}\n\nfunction isToolSpanValue(value: unknown): value is ToolSpan {\n try {\n return isToolSpan(value as Span)\n } catch {\n return false\n }\n}\n","import type { NodeId } from './types'\n\n/** Runtime tag used only for a child that owns another supervised scope. */\nexport const driverRuntime = 'driver' as const\n\n// Recursive ownership is an executor capability, not a Runtime string. `Runtime` is deliberately\n// open, so a caller-owned leaf may also call itself \"driver\". Keep the capability on the exact\n// Runtime-created executor object and never expose a public lookalike property that a leaf can set.\nconst nestedDriverTreeOwners = new WeakSet<object>()\n\n/** Canonical journal key for the scope owned by one nested driver node. */\nexport function nestedDriverTreeRoot(parentTreeRoot: NodeId, driverNodeId: NodeId): NodeId {\n return `${parentTreeRoot}/${driverNodeId}`\n}\n\n/** Privately mark the exact recursive executor that will create a nested journal tree. */\nexport function attestNestedDriverTreeOwner<T extends object>(owner: T): T {\n nestedDriverTreeOwners.add(owner)\n return owner\n}\n\n/** Return the canonical owned tree only for an exact privately marked recursive executor. */\nexport function runtimeOwnedNestedDriverTreeRoot(\n owner: object,\n parentTreeRoot: NodeId,\n driverNodeId: NodeId,\n): NodeId | undefined {\n return nestedDriverTreeOwners.has(owner)\n ? nestedDriverTreeRoot(parentTreeRoot, driverNodeId)\n : undefined\n}\n","import type { FileHandle } from 'node:fs/promises'\n\n/** Parse an append-only JSONL file without treating a torn final write as committed data.\n * A malformed newline-terminated or non-final record is corruption and fails loud. */\nexport function parseCommittedJsonLines<T>(text: string, source: string): T[] {\n const lines = text.split('\\n')\n const finalIndex = lines.length - 1\n const records: T[] = []\n\n for (const [index, line] of lines.entries()) {\n if (line.length === 0) continue\n try {\n records.push(JSON.parse(line) as T)\n } catch (cause) {\n const isInvalidUnterminatedTail = index === finalIndex && !text.endsWith('\\n')\n if (isInvalidUnterminatedTail) break\n throw new Error(`${source}: malformed JSONL record at line ${index + 1}`, { cause })\n }\n }\n\n return records\n}\n\n/** FileHandle.write may legally make a short write. Loop until every byte is appended. */\nexport async function writeAllBytes(\n handle: Pick<FileHandle, 'write'>,\n value: string | Uint8Array,\n): Promise<void> {\n const bytes = typeof value === 'string' ? Buffer.from(value) : Buffer.from(value)\n let offset = 0\n while (offset < bytes.byteLength) {\n const { bytesWritten } = await handle.write(bytes, offset, bytes.byteLength - offset, null)\n if (bytesWritten <= 0) {\n throw new Error(`append-only file write made no progress at byte ${offset}`)\n }\n offset += bytesWritten\n }\n}\n\n/** Prepare a recovered JSONL file for its next append. A valid unterminated final value is retained\n * and needs a separator; an invalid unterminated tail was never committed and is truncated. */\nexport async function prepareJsonlAppend(path: string): Promise<boolean> {\n const fs = await import('node:fs/promises')\n let bytes: Buffer\n try {\n bytes = await fs.readFile(path)\n } catch (error) {\n if (isNoEntError(error)) return false\n throw error\n }\n if (bytes.byteLength === 0 || bytes[bytes.byteLength - 1] === 0x0a) return false\n\n const lastNewline = bytes.lastIndexOf(0x0a)\n const tail = bytes.subarray(lastNewline + 1).toString('utf8')\n try {\n JSON.parse(tail)\n return true\n } catch {\n await fs.truncate(path, lastNewline + 1)\n return false\n }\n}\n\nfunction isNoEntError(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code: unknown }).code === 'ENOENT'\n )\n}\n","/**\n *\n * Event-sourced spawn journal for the recursive execution atom (build steps 3 + 7).\n *\n * The supervision tree is journaled as an append-only event log: every `spawned`,\n * `settled`, and `cancelled` is recorded AFTER it is observed-committed (never\n * speculative), mirroring `ConversationJournal`'s begin/append/load shape. The log\n * holds only the THIN decision record — ids, parentage, budget, the spend a decision\n * consumed, and a content-addressed `outRef`. The payloads the driver branched on\n * (the `out` artifacts) live in a separate `ResultBlobStore`, keyed by `outRef`, so\n * the journal stays small (decisions) and replay rehydrates the exact `Settled` from\n * the blob store (evidence). This is the decision/payload split the replay argument\n * rests on (B1/B2).\n *\n * Replay determinism (B2): `seq` is the monotonic cursor order `scope.next()` yielded\n * each settlement — NOT wall-clock. `replaySpawnTree` sorts strictly by `seq` before\n * touching the blob store, so the order in which rehydration `get`s resolve can never\n * reorder the replayed `Settled[]`; the result is identical regardless of blob latency.\n *\n * @stable\n */\n\nimport { detachedSnapshot } from '../runtime/supervise/snapshot'\nimport { workerTraceAnalysisStore } from '../runtime/supervise/trace-evidence'\nimport { nestedDriverTreeRoot } from '../runtime/supervise/tree-key'\nimport type {\n NodeExecutionIdentity,\n NodeId,\n NodeSnapshot,\n NodeStatus,\n ProviderModelAttemptEvidence,\n ProviderModelExecutionEvidence,\n ResultBlobStore,\n Runtime,\n Settled,\n SpawnEvent,\n SpawnJournal,\n Spend,\n TreeView,\n} from '../runtime/supervise/types'\nimport type { PendingWait } from '../runtime/supervise/wait'\nimport { addTokenUsage, cloneTokenUsage, usdEstimatedOf, zeroTokenUsage } from '../runtime/util'\nimport { contentAddress } from './content-address'\nimport { parseCommittedJsonLines, prepareJsonlAppend, writeAllBytes } from './jsonl-file'\n\nexport { contentAddress } from './content-address'\n\n/** One journal tree in a recursively loaded supervision forest. */\nexport interface SpawnForestTree {\n readonly root: NodeId\n /** Driver node that owns this tree; absent for the requested root tree. */\n readonly ownerNodeId?: NodeId\n /** Journal tree containing `ownerNodeId`; absent for the requested root tree. */\n readonly parentTreeRoot?: NodeId\n readonly events: ReadonlyArray<SpawnEvent>\n readonly view: TreeView\n}\n\n/** One event with the journal tree that establishes its cursor namespace. */\nexport interface SpawnForestEvent {\n readonly treeRoot: NodeId\n readonly event: SpawnEvent\n}\n\n/** One flattened node with the journal tree that owns its records. */\nexport interface SpawnForestNode extends NodeSnapshot {\n readonly treeRoot: NodeId\n}\n\n/** A spawned worker with no terminal record in a cold snapshot. Resume treats the same state as\n * in-doubt and conservatively retains its reservation. Root nodes and armed waits are excluded. */\nexport interface SpawnForestInDoubtNode {\n readonly treeRoot: NodeId\n readonly nodeId: NodeId\n readonly label: string\n readonly runtime: Runtime\n}\n\n/** A driver spawn whose owned journal tree was never begun before the process stopped. */\nexport interface SpawnForestMissingTree {\n readonly parentTreeRoot: NodeId\n readonly ownerNodeId: NodeId\n readonly root: NodeId\n}\n\n/** Complete cold-readable view of one recursive supervision run. */\nexport interface SpawnForest {\n readonly root: NodeId\n readonly trees: ReadonlyArray<SpawnForestTree>\n readonly nodes: ReadonlyArray<SpawnForestNode>\n readonly events: ReadonlyArray<SpawnForestEvent>\n readonly inDoubt: ReadonlyArray<SpawnForestInDoubtNode>\n readonly missingTrees: ReadonlyArray<SpawnForestMissingTree>\n}\n\n// ── Content addressing ──────────────────────────────────────────────────────\n\n/**\n * Mint the content-addressed `outRef` for a result artifact: `sha256:<hex>` over a\n * stable JSON encoding. Producers call this to derive the `outRef` they journal and\n * `put`; the FS/in-mem stores re-derive it on `put` to verify the supplied ref\n * matches (fail loud on a mismatch — a forged ref breaks the replay invariant).\n *\n * Stable encoding: object keys are sorted recursively so two structurally-equal\n * artifacts hash identically regardless of key insertion order.\n */\n// ── Result blob store ─────────────────────────────────────────────────────────\n\n/**\n * In-memory `ResultBlobStore`. Content-addressed: `put` verifies the supplied\n * `outRef` matches the artifact's hash so a stale/forged ref fails loud rather than\n * silently rehydrating the wrong payload. Idempotent on an identical re-put.\n *\n * @stable\n */\nexport class InMemoryResultBlobStore implements ResultBlobStore {\n private readonly blobs = new Map<string, unknown>()\n\n async put(outRef: string, artifact: unknown): Promise<void> {\n assertContentAddress(outRef, artifact)\n this.blobs.set(outRef, artifact)\n }\n\n async get(outRef: string): Promise<unknown | undefined> {\n return this.blobs.has(outRef) ? this.blobs.get(outRef) : undefined\n }\n}\n\n/**\n * FS `ResultBlobStore`. One JSON file per artifact under `dir`, named by a\n * filesystem-safe encoding of the `outRef` (`sha256:<hex>` → `sha256-<hex>.json`).\n * `put` fsyncs so a crash between writes never loses an acknowledged blob.\n *\n * @stable\n */\nexport class FileResultBlobStore implements ResultBlobStore {\n constructor(private readonly dir: string) {}\n\n async put(outRef: string, artifact: unknown): Promise<void> {\n assertContentAddress(outRef, artifact)\n const fs = await import('node:fs/promises')\n await fs.mkdir(this.dir, { recursive: true })\n const fh = await fs.open(this.blobPath(outRef), 'w')\n try {\n await fh.write(JSON.stringify(artifact))\n await fh.sync()\n } finally {\n await fh.close()\n }\n }\n\n async get(outRef: string): Promise<unknown | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.blobPath(outRef), 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n return JSON.parse(text)\n }\n\n private blobPath(outRef: string): string {\n return `${this.dir}/${outRef.replace(/:/g, '-')}.json`\n }\n}\n\nfunction assertContentAddress(outRef: string, artifact: unknown): void {\n const expected = contentAddress(artifact)\n if (outRef !== expected) {\n throw new Error(\n `blob outRef '${outRef}' does not match the artifact content hash '${expected}'; ` +\n 'a content-addressed store refuses a mismatched ref (breaks the replay invariant)',\n )\n }\n}\n\n// ── Spawn journal ──────────────────────────────────────────────────────────────\n\n/**\n * In-memory `SpawnJournal`. Appends are observed-committed only; the impl enforces\n * the corruption guards a durable replay rests on:\n * - an event before `beginTree` is a corrupted tree (fail loud),\n * - a duplicate `seq` within a tree is a corrupted cursor (fail loud) — two\n * settlements cannot share the cursor position replay orders by.\n *\n * @stable\n */\nexport class InMemorySpawnJournal implements SpawnJournal {\n private readonly trees = new Map<NodeId, { begunAt: string; events: SpawnEvent[] }>()\n\n async loadTree(root: NodeId): Promise<SpawnEvent[] | undefined> {\n const tree = this.trees.get(root)\n if (!tree) return undefined\n return tree.events.map((ev) => ({ ...ev }))\n }\n\n async beginTree(root: NodeId, at: string): Promise<void> {\n const existing = this.trees.get(root)\n if (existing) {\n if (existing.begunAt !== at) {\n throw new Error(\n `spawn tree '${root}' already begun at ${existing.begunAt}; refusing to overwrite with ${at}`,\n )\n }\n return\n }\n this.trees.set(root, { begunAt: at, events: [] })\n }\n\n async appendEvent(root: NodeId, ev: SpawnEvent): Promise<void> {\n const tree = this.trees.get(root)\n if (!tree) {\n throw new Error(`appendEvent called for unknown spawn tree '${root}'; call beginTree first`)\n }\n assertSeqUnique(root, tree.events, ev)\n tree.events.push({ ...ev })\n }\n}\n\n/**\n * JSONL on disk. One line per record: the first record is `begin`, subsequent records\n * are `event` envelopes wrapping a `SpawnEvent`. `loadTree` replays the whole file,\n * filtering by `root`, and applies the same begin-precedes-events + unique-seq\n * corruption guards as the in-memory impl. Each append fsyncs so a crash between\n * writes never loses an acknowledged event.\n *\n * @stable\n */\nexport class FileSpawnJournal implements SpawnJournal {\n private appendTail: Promise<void> = Promise.resolve()\n\n constructor(private readonly path: string) {}\n\n async loadTree(root: NodeId): Promise<SpawnEvent[] | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.path, 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n let begun = false\n const events: SpawnEvent[] = []\n for (const record of parseCommittedJsonLines<SpawnJournalRecord>(text, this.path)) {\n if (record.root !== root) continue\n if (record.kind === 'begin') {\n begun = true\n } else {\n if (!begun) {\n throw new Error(\n `spawn journal corrupted: event for tree '${root}' precedes its begin record`,\n )\n }\n assertSeqUnique(root, events, record.event)\n events.push(record.event)\n }\n }\n return begun ? events : undefined\n }\n\n async beginTree(root: NodeId, at: string): Promise<void> {\n const existing = await this.loadTreeBegin(root)\n if (existing) {\n if (existing !== at) {\n throw new Error(\n `spawn tree '${root}' already begun in ${this.path} at ${existing}; refusing to overwrite with ${at}`,\n )\n }\n return\n }\n await this.appendRecord({ kind: 'begin', root, at })\n }\n\n async appendEvent(root: NodeId, ev: SpawnEvent): Promise<void> {\n const events = await this.loadTree(root)\n if (events === undefined) {\n throw new Error(`appendEvent called for unknown spawn tree '${root}'; call beginTree first`)\n }\n assertSeqUnique(root, events, ev)\n await this.appendRecord({ kind: 'event', root, event: ev })\n }\n\n private async loadTreeBegin(root: NodeId): Promise<string | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.path, 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n for (const record of parseCommittedJsonLines<SpawnJournalRecord>(text, this.path)) {\n if (record.root === root && record.kind === 'begin') return record.at\n }\n return undefined\n }\n\n private async appendRecord(record: SpawnJournalRecord): Promise<void> {\n const append = this.appendTail.then(() => this.writeRecord(record))\n this.appendTail = append.catch(() => undefined)\n return append\n }\n\n private async writeRecord(record: SpawnJournalRecord): Promise<void> {\n const fs = await import('node:fs/promises')\n const path = await import('node:path')\n await fs.mkdir(path.dirname(this.path), { recursive: true })\n const needsSeparator = await prepareJsonlAppend(this.path)\n const fh = await fs.open(this.path, 'a')\n try {\n await writeAllBytes(fh, `${needsSeparator ? '\\n' : ''}${JSON.stringify(record)}\\n`)\n await fh.sync()\n } finally {\n await fh.close()\n }\n }\n}\n\n/**\n * Load every journal tree owned by one recursive supervision run and flatten its nodes/events.\n *\n * Nested driver tree keys are a Runtime implementation detail; callers should use this reader\n * instead of deriving or scanning keys themselves. The reader follows only the explicit\n * `ownedTreeRoot` written after Runtime privately attested a recursive executor; the open runtime\n * string `driver` is never treated as ownership. Legacy records without `ownedTreeRoot` are\n * intentionally treated as leaves rather than guessing or scanning convention-derived keys.\n * This preserves each tree's independent cursor namespace on flattened events.\n * A driver whose subtree was never begun is reported in `missingTrees`; any spawned non-root node\n * without a terminal record is reported in `inDoubt`, matching resume's conservative lost-work\n * interpretation.\n *\n * This is a cold/quiescent reader, not a transaction across an actively mutating file. Every value\n * returned is a detached immutable snapshot, so later journal writes or caller mutation cannot\n * change the result already observed.\n */\nexport async function loadSpawnForest(journal: SpawnJournal, root: NodeId): Promise<SpawnForest> {\n const rootEvents = await journal.loadTree(root)\n if (rootEvents === undefined) {\n throw new Error(`loadSpawnForest: no journaled tree for root '${root}'`)\n }\n\n const trees: SpawnForestTree[] = []\n const nodes: SpawnForestNode[] = []\n const events: SpawnForestEvent[] = []\n const inDoubt: SpawnForestInDoubtNode[] = []\n const missingTrees: SpawnForestMissingTree[] = []\n const visited = new Set<NodeId>()\n const queue: Array<{\n readonly root: NodeId\n readonly events: SpawnEvent[]\n readonly ownerNodeId?: NodeId\n readonly parentTreeRoot?: NodeId\n /** Parent-tree spawn that establishes the root node omitted from an owned journal tree. */\n readonly ownerSpawn?: Extract<SpawnEvent, { kind: 'spawned' }>\n }> = [{ root, events: rootEvents }]\n\n for (let cursor = 0; cursor < queue.length; cursor += 1) {\n const current = queue[cursor]!\n if (visited.has(current.root)) {\n throw new Error(`loadSpawnForest: recursive journal tree '${current.root}' was reached twice`)\n }\n visited.add(current.root)\n const stableEvents = detachedSnapshot(\n current.events,\n `loadSpawnForest tree ${JSON.stringify(current.root)}`,\n )\n const viewEvents =\n current.ownerSpawn === undefined ||\n stableEvents.some((event) => event.kind === 'spawned' && event.id === current.ownerSpawn?.id)\n ? [...stableEvents]\n : [ownedTreeRootSpawn(current.ownerSpawn), ...stableEvents]\n const view = detachedSnapshot(\n materializeTreeView(viewEvents),\n `loadSpawnForest view ${JSON.stringify(current.root)}`,\n )\n trees.push({\n root: current.root,\n ...(current.ownerNodeId === undefined ? {} : { ownerNodeId: current.ownerNodeId }),\n ...(current.parentTreeRoot === undefined ? {} : { parentTreeRoot: current.parentTreeRoot }),\n events: stableEvents,\n view,\n })\n // The owner is already a real node in its parent tree. Keep it in this tree's local view so\n // metered root events have a node, but omit the synthetic duplicate from the flattened list.\n nodes.push(\n ...view.nodes\n .filter((node) => current.ownerNodeId === undefined || node.id !== current.ownerNodeId)\n .map((node) => ({ treeRoot: current.root, ...node })),\n )\n events.push(...stableEvents.map((event) => ({ treeRoot: current.root, event })))\n\n const terminal = new Set<NodeId>()\n for (const event of stableEvents) {\n if (event.kind === 'settled' || event.kind === 'cancelled') terminal.add(event.id)\n }\n const spawns = stableEvents\n .filter(\n (event): event is Extract<SpawnEvent, { kind: 'spawned' }> => event.kind === 'spawned',\n )\n .sort((a, b) => a.seq - b.seq || a.id.localeCompare(b.id))\n for (const spawn of spawns) {\n if (spawn.parent !== undefined && !terminal.has(spawn.id)) {\n inDoubt.push({\n treeRoot: current.root,\n nodeId: spawn.id,\n label: spawn.label,\n runtime: spawn.runtime,\n })\n }\n if (spawn.ownedTreeRoot === undefined) continue\n const expectedRoot = nestedDriverTreeRoot(current.root, spawn.id)\n if (spawn.ownedTreeRoot !== expectedRoot) {\n throw new Error(\n `loadSpawnForest: node '${spawn.id}' owns non-canonical tree '${spawn.ownedTreeRoot}'; expected '${expectedRoot}'`,\n )\n }\n const nestedRoot = spawn.ownedTreeRoot\n const nestedEvents = await journal.loadTree(nestedRoot)\n if (nestedEvents === undefined) {\n missingTrees.push({\n parentTreeRoot: current.root,\n ownerNodeId: spawn.id,\n root: nestedRoot,\n })\n continue\n }\n queue.push({\n root: nestedRoot,\n events: nestedEvents,\n ownerNodeId: spawn.id,\n parentTreeRoot: current.root,\n ownerSpawn: spawn,\n })\n }\n }\n\n return detachedSnapshot(\n { root, trees, nodes, events, inDoubt, missingTrees },\n 'loadSpawnForest result',\n )\n}\n\n/** Owned journal trees record the owner's turns and descendants, but the owner's spawn belongs to\n * the parent tree. Supply a view-only parentless copy so strict materialization can fold root\n * metering without weakening its missing-spawn corruption check for ordinary event lists. */\nfunction ownedTreeRootSpawn(\n spawn: Extract<SpawnEvent, { kind: 'spawned' }>,\n): Extract<SpawnEvent, { kind: 'spawned' }> {\n const { parent: _parent, ownedTreeRoot: _ownedTreeRoot, ...root } = spawn\n return root\n}\n\n/**\n * Aggregate provider-served model evidence across one recursively owned journal forest.\n *\n * The parent tree records an owned driver's terminal summary, while that driver's own inference\n * and descendants live in its owned tree. This reducer follows the forest reader's explicit tree\n * edges and consumes each tree's metered attempts plus terminal leaf settlements exactly once.\n * A summary node is skipped because its owned tree supplies the source records. Plan materialization\n * is intentionally not read: it proves only what Runtime requested, not what a provider served.\n *\n * Missing legacy evidence, an unfinished node, an unopened owned tree, an identity conflict, and a\n * paid attempt without a qualified served snapshot all return unknown. An explicit\n * `providerDispatch: \"not_started\"` arm and Runtime accounting-only metered records are ignored\n * for served-model identity, while absent or malformed legacy data remains unknown here.\n */\nexport function aggregateProviderModelEvidence(\n forest: SpawnForest,\n): ProviderModelExecutionEvidence {\n const attempts: ProviderModelAttemptEvidence[] = []\n const observedModels = new Set<string>()\n const canonicalModels = new Set<string>()\n const nodes = new Map<string, SpawnForestNode>()\n let reason: 'provider-model-missing' | 'provider-model-conflict' | undefined\n let sawProviderEvidence = false\n\n for (const node of forest.nodes) nodes.set(forestNodeKey(node.treeRoot, node.id), node)\n if (forest.missingTrees.length > 0 || forest.inDoubt.length > 0) {\n reason = 'provider-model-missing'\n }\n\n const markMissing = () => {\n reason ??= 'provider-model-missing'\n }\n const markConflict = () => {\n reason = 'provider-model-conflict'\n }\n\n const append = (raw: unknown): void => {\n sawProviderEvidence = true\n if (!isProviderEvidenceObject(raw)) {\n markMissing()\n return\n }\n if (raw.status === 'unknown') {\n if (raw.reason === 'provider-model-conflict') {\n markConflict()\n } else if (!hasOnlyNotStartedAttempts(raw)) {\n markMissing()\n }\n } else if (raw.status !== 'known') {\n markMissing()\n return\n }\n if (!Array.isArray(raw.attempts) || !Array.isArray(raw.models)) {\n markMissing()\n return\n }\n\n const declared = new Set<string>()\n for (const model of raw.models) {\n if (typeof model !== 'string' || model.length === 0) {\n markMissing()\n } else {\n declared.add(model)\n }\n }\n const observedInRecord = new Set<string>()\n for (const rawAttempt of raw.attempts) {\n if (!isProviderAttemptEvidence(rawAttempt)) {\n markMissing()\n continue\n }\n if (rawAttempt.identityConflict === true) markConflict()\n const observations = [...rawAttempt.observations]\n if (rawAttempt.providerDispatch === 'not_started') {\n if (observations.length > 0) markMissing()\n attempts.push(\n Object.freeze({\n observations: Object.freeze([]),\n providerDispatch: 'not_started' as const,\n ...(rawAttempt.identityConflict === true ? { identityConflict: true } : {}),\n }),\n )\n continue\n }\n if (observations.length === 0) {\n markMissing()\n attempts.push(\n Object.freeze({\n observations: Object.freeze([]),\n ...(rawAttempt.identityConflict === true ? { identityConflict: true } : {}),\n }),\n )\n continue\n }\n let base: string | undefined\n let snapshot: string | undefined\n for (const model of observations) {\n if (typeof model !== 'string' || model.length === 0) {\n markMissing()\n continue\n }\n observedInRecord.add(model)\n observedModels.add(model)\n const identity = servedIdentityParts(model)\n if (identity === undefined) {\n markMissing()\n continue\n }\n if (base !== undefined && base !== identity.base) markConflict()\n if (\n snapshot !== undefined &&\n identity.snapshot !== undefined &&\n snapshot !== identity.snapshot\n ) {\n markConflict()\n }\n base = identity.base\n snapshot ??= identity.snapshot\n if (identity.snapshot !== undefined) {\n canonicalModels.add(`${identity.base}@${identity.snapshot}`)\n if (canonicalModels.size > 1) markConflict()\n }\n }\n if (base === undefined || snapshot === undefined) markMissing()\n attempts.push(\n Object.freeze({\n observations: Object.freeze(observations),\n ...(rawAttempt.identityConflict === true ? { identityConflict: true } : {}),\n }),\n )\n }\n if (\n declared.size !== observedInRecord.size ||\n [...declared].some((model) => !observedInRecord.has(model))\n ) {\n markMissing()\n }\n }\n\n const terminal = (\n treeRoot: NodeId,\n event: Extract<SpawnEvent, { kind: 'settled' | 'cancelled' }>,\n ) => {\n const node = nodes.get(forestNodeKey(treeRoot, event.id))\n if (node === undefined) {\n markMissing()\n return\n }\n // This event is a parent-side summary. Its owned tree is the authoritative source and is\n // traversed above; consuming its summary here would count nested attempts twice.\n if (node.ownedTreeRoot !== undefined) return\n if (event.kind === 'cancelled') {\n markMissing()\n return\n }\n append(event.providerModel ?? node.providerModel)\n }\n\n for (const tree of forest.trees) {\n for (const event of tree.events) {\n if (event.kind === 'metered') {\n if (event.accountingOnly === true) {\n if (event.providerModel !== undefined) markMissing()\n continue\n }\n // The parent scope re-homes a driver's nested metered spend onto the driver's parent node.\n // Its owned tree carries the provider attempts; consuming this summary would both\n // double-count and treat the spend-only legacy summary as missing identity evidence.\n const summaryNode = nodes.get(forestNodeKey(tree.root, event.id))\n if (summaryNode?.ownedTreeRoot !== undefined) continue\n const evidence = (event as SpawnEvent & { providerModel?: unknown }).providerModel\n if (evidence === undefined) markMissing()\n else append(evidence)\n } else if (event.kind === 'settled' || event.kind === 'cancelled') {\n terminal(tree.root, event)\n }\n }\n }\n\n if (!sawProviderEvidence || attempts.length === 0 || observedModels.size === 0) {\n reason ??= 'provider-model-missing'\n }\n const models = Object.freeze([...observedModels])\n const frozenAttempts = Object.freeze(attempts)\n return Object.freeze(\n reason === undefined\n ? { status: 'known' as const, attempts: frozenAttempts, models }\n : { status: 'unknown' as const, attempts: frozenAttempts, models, reason },\n )\n}\n\nfunction forestNodeKey(treeRoot: NodeId, nodeId: NodeId): string {\n return `${treeRoot}\\u0000${nodeId}`\n}\n\nfunction isProviderEvidenceObject(value: unknown): value is ProviderModelExecutionEvidence {\n return typeof value === 'object' && value !== null && !Array.isArray(value) && 'status' in value\n}\n\nfunction hasOnlyNotStartedAttempts(evidence: ProviderModelExecutionEvidence): boolean {\n return (\n Array.isArray(evidence.attempts) &&\n evidence.attempts.length > 0 &&\n evidence.attempts.every(\n (attempt) =>\n isProviderAttemptEvidence(attempt) &&\n attempt.providerDispatch === 'not_started' &&\n attempt.observations.length === 0 &&\n attempt.identityConflict !== true,\n )\n )\n}\n\nfunction isProviderAttemptEvidence(value: unknown): value is ProviderModelAttemptEvidence {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n Array.isArray((value as { observations?: unknown }).observations) &&\n ((value as { providerDispatch?: unknown }).providerDispatch === undefined ||\n (value as { providerDispatch?: unknown }).providerDispatch === 'not_started')\n )\n}\n\nfunction servedIdentityParts(\n model: string,\n): { readonly base: string; readonly snapshot?: string } | undefined {\n const at = model.lastIndexOf('@')\n const rawBase = at < 0 ? model : model.slice(0, at)\n const base = rawBase.slice(rawBase.lastIndexOf('/') + 1)\n if (base.length === 0) return undefined\n const snapshot = at < 0 ? undefined : model.slice(at + 1)\n if (snapshot !== undefined && snapshot.length === 0) return undefined\n return snapshot === undefined ? { base } : { base, snapshot }\n}\n\ntype SpawnJournalRecord =\n | { kind: 'begin'; root: NodeId; at: string }\n | { kind: 'event'; root: NodeId; event: SpawnEvent }\n\n/**\n * Two `seq` namespaces share the journal: a `spawned` event's `seq` is the spawn ordinal\n * (the order children were created), and a `settled`/`cancelled` event's `seq` is the\n * monotonic CURSOR order `scope.next()` yielded that settlement (B2). The uniqueness\n * replay rests on is the cursor namespace — two settlements cannot share the position\n * replay orders by — so the guard checks only settled/cancelled events. A `spawned`\n * ordinal legitimately equals a later `settled` cursor seq and is not a collision.\n */\nfunction assertSeqUnique(root: NodeId, events: SpawnEvent[], ev: SpawnEvent): void {\n if (ev.kind === 'materialized') {\n if (events.some((event) => event.kind === 'materialized' && event.id === ev.id)) {\n throw new Error(\n `spawn journal corrupted: duplicate materialization receipt for node '${ev.id}' in tree '${root}'`,\n )\n }\n if (!events.some((event) => event.kind === 'spawned' && event.id === ev.id)) {\n throw new Error(\n `spawn journal corrupted: materialization for node '${ev.id}' precedes its spawn in tree '${root}'`,\n )\n }\n }\n if (ev.kind === 'execution-bound') {\n if (\n events.some(\n (event) =>\n event.kind === 'execution-bound' &&\n event.id === ev.id &&\n event.binding.attemptId === ev.binding.attemptId,\n )\n ) {\n throw new Error(\n `spawn journal corrupted: duplicate execution binding for node '${ev.id}' attempt '${ev.binding.attemptId}' in tree '${root}'`,\n )\n }\n if (!events.some((event) => event.kind === 'materialized' && event.id === ev.id)) {\n throw new Error(\n `spawn journal corrupted: execution binding for node '${ev.id}' precedes materialization in tree '${root}'`,\n )\n }\n }\n // `spawned` (ordinal namespace), `waiting` (the wait-ordinal namespace — it CREATES a node, it\n // does not settle one), and `metered` (informational spend, no settlement order) live outside\n // the cursor-uniqueness namespace replay relies on. `woken` IS a settlement and does not.\n if (outsideCursorNamespace(ev)) return\n if (events.some((e) => !outsideCursorNamespace(e) && e.seq === ev.seq)) {\n throw new Error(\n `spawn journal corrupted: duplicate cursor seq ${ev.seq} in tree '${root}'; ` +\n 'the cursor order replay relies on is not unique',\n )\n }\n}\n\n/** Node-CREATION and informational records — outside the cursor namespace whose uniqueness replay\n * ordering rests on. The single predicate both the guard's sides read, so a new event kind is\n * classified once. */\nfunction outsideCursorNamespace(ev: SpawnEvent): boolean {\n return (\n ev.kind === 'spawned' ||\n ev.kind === 'waiting' ||\n ev.kind === 'metered' ||\n ev.kind === 'materialized' ||\n ev.kind === 'execution-bound' ||\n ev.kind === 'edge' ||\n ev.kind === 'trace-unpropagated'\n )\n}\n\n// ── Replay executor (build step 7) ───────────────────────────────────────────────\n\n/**\n * Re-feed a journaled spawn tree in strict `seq` order, rehydrating each settled\n * child's `out` from the blob store by `outRef`, and return the `Settled[]` exactly\n * as `scope.next()` originally delivered them.\n *\n * Determinism (B2): the events are sorted by `seq` BEFORE any blob `get`, so the\n * replay order is the recorded cursor order regardless of how fast each rehydration\n * resolves. `at` (wall-clock) is never a replay input. Fail loud on a tree that was\n * never begun, a settled-done event missing its `outRef`, or a blob the store can't\n * rehydrate — a silent gap would let `act` branch on the wrong evidence.\n *\n * @stable\n */\nexport async function replaySpawnTree(\n journal: SpawnJournal,\n blobs: ResultBlobStore,\n root: NodeId,\n): Promise<Settled<unknown>[]> {\n const events = await journal.loadTree(root)\n if (events === undefined) {\n throw new Error(`replaySpawnTree: no journaled tree for root '${root}'`)\n }\n const ordered = [...events].sort((a, b) => a.seq - b.seq)\n const labels = new Map<NodeId, string>()\n const assignmentIds = new Map<NodeId, string>()\n const identities = new Map<NodeId, NodeExecutionIdentity>()\n const materializations = new Map<NodeId, NodeSnapshot['materialization']>()\n const executionBindings = new Map<\n NodeId,\n NonNullable<NodeSnapshot['executionBindings']>[number][]\n >()\n for (const ev of ordered) {\n if (ev.kind === 'spawned' || ev.kind === 'waiting') labels.set(ev.id, ev.label)\n if (ev.kind === 'spawned' && ev.assignmentId !== undefined) {\n assignmentIds.set(ev.id, ev.assignmentId)\n }\n if (ev.kind === 'spawned' && ev.identity !== undefined) {\n identities.set(ev.id, copyFrozenIdentity(ev.identity))\n }\n if (ev.kind === 'materialized') materializations.set(ev.id, ev.receipt)\n if (ev.kind === 'execution-bound') {\n const bindings = executionBindings.get(ev.id) ?? []\n bindings.push(ev.binding)\n executionBindings.set(ev.id, bindings)\n }\n }\n const handleFor = (id: NodeId, status: NodeStatus) =>\n replayHandle(id, labels.get(id) ?? id, status, {\n assignmentId: assignmentIds.get(id),\n identity: identities.get(id),\n materialization: materializations.get(id),\n executionBindings: executionBindings.get(id),\n })\n const settlementTime = (at: string): { readonly settledAt?: number } => {\n const settledAt = Date.parse(at)\n return Number.isFinite(settledAt) ? { settledAt } : {}\n }\n const settled: Settled<unknown>[] = []\n for (const ev of ordered) {\n if (ev.kind === 'spawned') continue\n if (ev.kind === 'waiting') continue // arms a wait node; `woken` is its settlement\n if (ev.kind === 'metered') continue // a spend record, not a settlement — irrelevant to replay\n if (ev.kind === 'materialized') continue // wire receipt, not a settlement\n if (ev.kind === 'execution-bound') continue // attempt transport, not a settlement\n if (ev.kind === 'edge') continue // edge-ledger observability, not a settlement\n if (ev.kind === 'trace-unpropagated') continue // severed-hop marker, not a settlement\n if (ev.kind === 'woken') {\n // A wait that was cancelled carries no outcome blob — it replays as a `down`, exactly as a\n // cancelled worker does. A fired/timed-out wait rehydrates its `WaitOutcome` and costs zero.\n if (ev.by === 'cancelled' || ev.outRef === undefined) {\n settled.push({\n kind: 'down',\n handle: handleFor(ev.id, 'cancelled'),\n reason: 'wait cancelled',\n infra: false,\n restartCount: 0,\n trace: { status: 'unavailable', reason: 'not-an-executor' },\n ...settlementTime(ev.at),\n seq: ev.seq,\n })\n continue\n }\n const outcome = await blobs.get(ev.outRef)\n if (outcome === undefined) {\n throw new Error(\n `replaySpawnTree: blob store has no wait outcome for outRef '${ev.outRef}' (node '${ev.id}', seq ${ev.seq})`,\n )\n }\n settled.push({\n kind: 'done',\n handle: handleFor(ev.id, 'done'),\n out: outcome,\n outRef: ev.outRef,\n spent: zeroSpend(),\n trace: { status: 'unavailable', reason: 'not-an-executor' },\n ...settlementTime(ev.at),\n seq: ev.seq,\n })\n continue\n }\n if (ev.kind === 'cancelled') {\n settled.push({\n kind: 'down',\n handle: handleFor(ev.id, 'cancelled'),\n reason: ev.reason,\n infra: false,\n restartCount: 0,\n trace: { status: 'unavailable', reason: 'execution-did-not-start' },\n ...settlementTime(ev.at),\n seq: ev.seq,\n })\n continue\n }\n if (ev.status === 'down') {\n const trace = traceEvidenceFor(ev)\n if (trace.status === 'available') await workerTraceAnalysisStore(trace, blobs)\n settled.push({\n kind: 'down',\n handle: handleFor(ev.id, 'failed'),\n // `reason` is written by every current scope. The verdict fallback preserves the\n // pre-field convention and the generic text keeps still-older reasonless journals usable.\n reason: ev.reason ?? ev.verdict?.notes ?? 'child down',\n infra: ev.infra === true,\n restartCount: 0,\n ...(ev.providerModel === undefined\n ? {}\n : { providerModel: copyProviderModelEvidence(ev.providerModel) }),\n trace,\n ...settlementTime(ev.at),\n seq: ev.seq,\n })\n continue\n }\n if (ev.outRef === undefined) {\n throw new Error(\n `replaySpawnTree: settled-done event for '${ev.id}' (seq ${ev.seq}) has no outRef; ` +\n 'cannot rehydrate the result the driver branched on',\n )\n }\n const out = await blobs.get(ev.outRef)\n if (out === undefined) {\n throw new Error(\n `replaySpawnTree: blob store has no artifact for outRef '${ev.outRef}' (node '${ev.id}', seq ${ev.seq})`,\n )\n }\n const trace = traceEvidenceFor(ev)\n if (trace.status === 'available') await workerTraceAnalysisStore(trace, blobs)\n settled.push({\n kind: 'done',\n handle: handleFor(ev.id, 'done'),\n out,\n outRef: ev.outRef,\n verdict: ev.verdict,\n spent: cloneJournalSpend(ev.spent),\n ...(ev.providerModel === undefined\n ? {}\n : { providerModel: copyProviderModelEvidence(ev.providerModel) }),\n trace,\n ...settlementTime(ev.at),\n seq: ev.seq,\n })\n }\n return settled\n}\n\nfunction replayHandle(\n id: NodeId,\n label: string,\n status: NodeStatus,\n evidence: {\n readonly assignmentId?: string\n readonly identity?: NodeExecutionIdentity\n readonly materialization?: NodeSnapshot['materialization']\n readonly executionBindings?: ReadonlyArray<\n NonNullable<NodeSnapshot['executionBindings']>[number]\n >\n } = {},\n) {\n return Object.freeze({\n id,\n label,\n status,\n ...(evidence.assignmentId === undefined ? {} : { assignmentId: evidence.assignmentId }),\n ...(evidence.identity === undefined ? {} : { identity: evidence.identity }),\n ...(evidence.materialization === undefined\n ? {}\n : { materialization: evidence.materialization }),\n ...(evidence.executionBindings === undefined\n ? {}\n : { executionBindings: Object.freeze([...evidence.executionBindings]) }),\n abort() {\n throw new Error(`cannot abort node '${id}': replayed handles are terminal, not live`)\n },\n })\n}\n\n/** A replayed handle must not retain mutable references into the loaded journal event. */\nfunction copyFrozenIdentity(identity: NodeExecutionIdentity): NodeExecutionIdentity {\n const correlation =\n identity.correlation === undefined ? undefined : Object.freeze({ ...identity.correlation })\n return Object.freeze({\n ...(identity.profileDigest === undefined ? {} : { profileDigest: identity.profileDigest }),\n ...(identity.taskDigest === undefined ? {} : { taskDigest: identity.taskDigest }),\n ...(identity.candidateDigest === undefined\n ? {}\n : { candidateDigest: identity.candidateDigest }),\n ...(correlation === undefined ? {} : { correlation }),\n })\n}\n\n/**\n * Materialize a recorded `TreeView` from a journaled event list for inspection. Folds\n * `spawned`/`settled`/`cancelled` into a per-node snapshot in `seq` order, then adds each\n * `metered` event's driver-inference spend onto its node in a separate additive pass so the view\n * matches the recorded cursor. It does not recover live executors or driver state after restart.\n */\nexport function materializeTreeView(events: SpawnEvent[]): TreeView {\n const nodes = new Map<NodeId, MutableSnapshot>()\n let root: NodeId | undefined\n // `spawned` (ordinal namespace) and `settled`/`cancelled` (cursor namespace) carry\n // overlapping `seq` values, so create every node before any update — process spawns in\n // ordinal order, then settlements/cancellations in cursor order. A settle/cancel for an\n // un-spawned node is a corrupted log (fail loud via requireNode).\n const spawns = events\n .filter(\n (ev): ev is Extract<SpawnEvent, { kind: 'spawned' | 'waiting' }> =>\n ev.kind === 'spawned' || ev.kind === 'waiting',\n )\n .sort((a, b) => a.seq - b.seq)\n const settlements = events\n .filter(\n (ev) =>\n ev.kind !== 'spawned' &&\n ev.kind !== 'waiting' &&\n ev.kind !== 'metered' &&\n ev.kind !== 'materialized' &&\n ev.kind !== 'execution-bound' &&\n ev.kind !== 'edge' &&\n ev.kind !== 'trace-unpropagated',\n )\n .sort((a, b) => a.seq - b.seq)\n for (const ev of spawns) {\n if (ev.kind === 'waiting') {\n // An ARMED wait reads `waiting` until a `woken` event lands. That is the whole durability\n // claim: a materialized tree from a journal whose process died mid-wait still shows the wait.\n nodes.set(ev.id, {\n id: ev.id,\n parent: ev.parent,\n label: ev.label,\n status: 'waiting',\n runtime: 'wait',\n budget: { maxIterations: 0, maxTokens: 0 },\n spent: zeroSpend(),\n })\n continue\n }\n if (ev.parent === undefined && root === undefined) root = ev.id\n nodes.set(ev.id, {\n id: ev.id,\n parent: ev.parent,\n label: ev.label,\n status: 'pending',\n runtime: ev.runtime,\n budget: ev.budget,\n ...(ev.ownedTreeRoot === undefined ? {} : { ownedTreeRoot: ev.ownedTreeRoot }),\n ...(ev.assignmentId === undefined ? {} : { assignmentId: ev.assignmentId }),\n ...(ev.identity ? { identity: ev.identity } : {}),\n spent: zeroSpend(),\n })\n }\n for (const ev of settlements) {\n if (ev.kind === 'settled') {\n const node = requireNode(nodes, ev.id)\n node.status = ev.status === 'done' ? 'done' : 'failed'\n node.spent = cloneJournalSpend(ev.spent)\n node.providerModel = copyProviderModelEvidence(ev.providerModel)\n node.outRef = ev.outRef\n node.trace = traceEvidenceFor(ev)\n const settledAt = Date.parse(ev.at)\n if (Number.isFinite(settledAt)) node.settledAt = settledAt\n } else if (ev.kind === 'woken') {\n const node = requireNode(nodes, ev.id)\n node.status = ev.by === 'cancelled' ? 'cancelled' : 'done'\n node.outRef = ev.outRef\n node.trace = { status: 'unavailable', reason: 'not-an-executor' }\n const settledAt = Date.parse(ev.at)\n if (Number.isFinite(settledAt)) node.settledAt = settledAt\n } else {\n const node = requireNode(nodes, ev.id)\n node.status = 'cancelled'\n node.trace = { status: 'unavailable', reason: 'execution-did-not-start' }\n const settledAt = Date.parse(ev.at)\n if (Number.isFinite(settledAt)) node.settledAt = settledAt\n }\n }\n // Materialization is node evidence, not a settlement. Fold it after node creation and before\n // freezing the view; exactly one receipt per node is enforced by the journal corruption guard.\n for (const ev of events) {\n if (ev.kind !== 'materialized') continue\n const node = requireNode(nodes, ev.id)\n node.materialization = ev.receipt\n node.runtime = ev.receipt.runtime\n }\n for (const ev of events) {\n if (ev.kind !== 'execution-bound') continue\n const node = requireNode(nodes, ev.id)\n node.executionBindings ??= []\n node.executionBindings.push(ev.binding)\n }\n // Driver inference: a separate pass so it accumulates ONTO the settled child-work base (no\n // dependence on metered-vs-settled seq order) without touching node status.\n for (const ev of events) {\n if (ev.kind !== 'metered') continue\n const node = requireNode(nodes, ev.id)\n node.spent = addJournalSpend(node.spent, ev.spend)\n }\n const snapshots = [...nodes.values()].map(freezeSnapshot)\n return {\n root: root ?? snapshots[0]?.id ?? '',\n nodes: snapshots,\n inFlight: snapshots.filter((n) => n.status === 'running' || n.status === 'acquiring').length,\n waiting: snapshots.filter((n) => n.status === 'waiting').length,\n }\n}\n\n/**\n * The waits a journaled tree shows as ARMED but never woken — what a resumed run re-arms with the\n * ORIGINAL absolute deadline. Reading it from the journal (rather than from any live state) is\n * what makes \"SIGKILL a waiting tree, a new process keeps waiting to the same instant\" true.\n */\nexport function pendingWaits(events: SpawnEvent[]): PendingWait[] {\n const woken = new Set<NodeId>()\n for (const ev of events) if (ev.kind === 'woken') woken.add(ev.id)\n const pending: PendingWait[] = []\n for (const ev of events) {\n if (ev.kind !== 'waiting' || woken.has(ev.id)) continue\n pending.push({\n id: ev.id,\n label: ev.label,\n spec: ev.spec,\n armedAt: ev.armedAt,\n ordinal: ev.seq,\n })\n }\n return pending.sort((a, b) => a.ordinal - b.ordinal)\n}\n\ninterface MutableSnapshot {\n id: NodeId\n parent?: NodeId\n label: string\n status: NodeStatus\n runtime: Runtime\n budget: NodeSnapshot['budget']\n ownedTreeRoot?: NodeSnapshot['ownedTreeRoot']\n assignmentId?: string\n identity?: NodeSnapshot['identity']\n materialization?: NodeSnapshot['materialization']\n executionBindings?: NonNullable<NodeSnapshot['executionBindings']>[number][]\n spent: Spend\n providerModel?: NodeSnapshot['providerModel']\n outRef?: string\n trace?: NodeSnapshot['trace']\n settledAt?: number\n}\n\nfunction zeroSpend(): Spend {\n return { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 }\n}\n\n/** Copy a durable spend into a read model without dropping cache completeness. */\nfunction cloneJournalSpend(spend: Spend): Spend {\n return {\n iterations: spend.iterations,\n tokens: cloneTokenUsage(spend.tokens),\n ...(spend.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: spend.usd,\n ...(spend.usdKnown === false ? { usdKnown: false } : {}),\n ...(spend.usdEstimated !== undefined ? { usdEstimated: spend.usdEstimated } : {}),\n ms: spend.ms,\n }\n}\n\n/** Copy provider evidence at the journal boundary so replay never exposes mutable event state. */\nfunction copyProviderModelEvidence(\n evidence: NodeSnapshot['providerModel'],\n): NodeSnapshot['providerModel'] {\n if (evidence === undefined) return undefined\n const attempts = Object.freeze(\n evidence.attempts.map((attempt) =>\n Object.freeze({\n observations: Object.freeze([...attempt.observations]),\n ...(attempt.identityConflict ? { identityConflict: true } : {}),\n ...(attempt.providerDispatch === 'not_started'\n ? { providerDispatch: 'not_started' as const }\n : {}),\n }),\n ),\n )\n const models = Object.freeze([...evidence.models])\n return Object.freeze(\n evidence.status === 'unknown'\n ? { status: 'unknown' as const, attempts, models, reason: evidence.reason }\n : { status: 'known' as const, attempts, models },\n )\n}\n\n/** Add a `metered` spend record onto a node's accumulated spend (per channel). */\nfunction addJournalSpend(a: Spend, b: Spend): Spend {\n return {\n iterations: a.iterations + b.iterations,\n tokens: (() => {\n const tokens = cloneTokenUsage(a.tokens)\n addTokenUsage(tokens, b.tokens)\n return tokens\n })(),\n ...(a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: a.usd + b.usd,\n ...(a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {}),\n ...usdEstimatedOf(a, b),\n ms: a.ms + b.ms,\n }\n}\n\nfunction requireNode(nodes: Map<NodeId, MutableSnapshot>, id: NodeId): MutableSnapshot {\n const node = nodes.get(id)\n if (!node) {\n throw new Error(`spawn journal corrupted: settle/cancel for node '${id}' with no prior spawn`)\n }\n return node\n}\n\nfunction freezeSnapshot(node: MutableSnapshot): NodeSnapshot {\n return {\n id: node.id,\n parent: node.parent,\n label: node.label,\n status: node.status,\n runtime: node.runtime,\n budget: node.budget,\n ownedTreeRoot: node.ownedTreeRoot,\n assignmentId: node.assignmentId,\n identity: node.identity,\n materialization: node.materialization,\n executionBindings:\n node.executionBindings === undefined ? undefined : Object.freeze([...node.executionBindings]),\n spent: node.spent,\n providerModel: node.providerModel,\n outRef: node.outRef,\n trace: node.trace,\n settledAt: node.settledAt,\n }\n}\n\nfunction traceEvidenceFor(\n event: Extract<SpawnEvent, { kind: 'settled' }>,\n): NonNullable<NodeSnapshot['trace']> {\n return (\n event.trace ?? {\n status: 'unavailable',\n reason: 'legacy-settlement-without-trace-evidence',\n }\n )\n}\n\nfunction isNoEntError(err: unknown): boolean {\n return (\n typeof err === 'object' &&\n err !== null &&\n 'code' in err &&\n (err as { code: unknown }).code === 'ENOENT'\n )\n}\n"],"mappings":";;;;;;;AAGA,SAAgB,eAAe,UAA2B;CAExD,OAAO,UADK,WAAW,QAAQ,CAAC,CAAC,OAAO,gBAAgB,QAAQ,GAAG,OAAO,CAAC,CAAC,OAAO,KAChE;AACrB;AAEA,SAAS,gBAAgB,OAAwB;CAC/C,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO,KAAK,UAAU,KAAK,KAAK;CACjF,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,IAAI,MAAM,IAAI,eAAe,CAAC,CAAC,KAAK,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EACtB,IAAI,EAAE,KAAK,EAAE;CACf;AACF;AAEA,SAAS,YAAY,OAAqC,IAA6B;CACrF,MAAM,OAAO,MAAM,IAAI,EAAE;CACzB,IAAI,CAAC,MACH,MAAM,IAAI,MAAM,oDAAoD,GAAG,sBAAsB;CAE/F,OAAO;AACT;AAEA,SAAS,eAAe,MAAqC;CAC3D,OAAO;EACL,IAAI,KAAK;EACT,QAAQ,KAAK;EACb,OAAO,KAAK;EACZ,QAAQ,KAAK;EACb,SAAS,KAAK;EACd,QAAQ,KAAK;EACb,eAAe,KAAK;EACpB,cAAc,KAAK;EACnB,UAAU,KAAK;EACf,iBAAiB,KAAK;EACtB,mBACE,KAAK,sBAAsB,KAAA,IAAY,KAAA,IAAY,OAAO,OAAO,CAAC,GAAG,KAAK,iBAAiB,CAAC;EAC9F,OAAO,KAAK;EACZ,eAAe,KAAK;EACpB,QAAQ,KAAK;EACb,OAAO,KAAK;EACZ,WAAW,KAAK;CAClB;AACF;AAEA,SAAS,iBACP,OACoC;CACpC,OACE,MAAM,SAAS;EACb,QAAQ;EACR,QAAQ;CACV;AAEJ;AAEA,SAAS,aAAa,KAAuB;CAC3C,OACE,OAAO,QAAQ,YACf,QAAQ,QACR,UAAU,OACT,IAA0B,SAAS;AAExC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"stream-agent-turn-Q5ellSUu.js","names":["taskInput"],"sources":["../src/sessions.ts","../src/backends.ts","../src/runtime/stream-agent-turn.ts"],"sourcesContent":["/**\n *\n * Session helpers + an in-memory `RuntimeSessionStore` implementation suitable\n * for tests, scratch processes, and per-request scratch storage in serverless\n * runtimes. Durable stores (D1, postgres, Durable Objects) implement the same\n * interface from `./types`.\n *\n * @stable\n */\n\nimport { SessionMismatchError } from './errors'\nimport type {\n AgentBackendContext,\n AgentBackendInput,\n AgentExecutionBackend,\n RuntimeSession,\n RuntimeSessionStore,\n RuntimeStreamEvent,\n} from './types'\n\n/** @internal */\nexport function newRuntimeSession(\n backend: string,\n requestedId?: string,\n metadata?: Record<string, unknown>,\n): RuntimeSession {\n const now = nowIso()\n return {\n id: requestedId || crypto.randomUUID(),\n backend,\n status: 'active',\n createdAt: now,\n updatedAt: now,\n metadata,\n }\n}\n\n/** @internal */\nexport function touchSession(session: RuntimeSession): RuntimeSession {\n return { ...session, updatedAt: nowIso() }\n}\n\n/** @internal */\nexport function nowIso(): string {\n return new Date().toISOString()\n}\n\ninterface StartOrResumeRuntimeSessionOptions<TInput extends AgentBackendInput> {\n backend: AgentExecutionBackend<TInput>\n input: TInput | (() => TInput)\n /** Smaller input used only when the backend can continue its native session. */\n continuationInput?: TInput | (() => TInput)\n context: Omit<AgentBackendContext, 'session'>\n store?: RuntimeSessionStore\n sessionId?: string\n resume?: boolean\n validateSession?: (session: RuntimeSession) => void\n}\n\ninterface RuntimeSessionCall<TInput extends AgentBackendInput> {\n session: RuntimeSession\n input: TInput\n resumed: boolean\n}\n\n/** Start or resume one backend session and persist its current identity. @internal */\nexport async function startOrResumeRuntimeSession<TInput extends AgentBackendInput>(\n options: StartOrResumeRuntimeSessionOptions<TInput>,\n): Promise<RuntimeSessionCall<TInput>> {\n const existing =\n options.resume && options.sessionId ? await options.store?.get(options.sessionId) : undefined\n if (!existing) {\n const input = resolveSessionInput(options.input)\n const session = options.backend.start\n ? await options.backend.start(input, {\n ...options.context,\n requestedSessionId: options.sessionId,\n })\n : newRuntimeSession(options.backend.kind, options.sessionId)\n assertSessionBackend(session, options.backend.kind)\n options.validateSession?.(session)\n await options.store?.put(session)\n return { session, input, resumed: false }\n }\n\n assertSessionBackend(existing, options.backend.kind)\n const continued = options.backend.resume !== undefined\n const input = resolveSessionInput(\n continued ? (options.continuationInput ?? options.input) : options.input,\n )\n const session = options.backend.resume\n ? await options.backend.resume(existing, input, options.context)\n : touchSession({ ...existing, status: 'active' })\n assertSessionBackend(session, options.backend.kind)\n options.validateSession?.(session)\n await options.store?.put(session)\n return { session, input, resumed: true }\n}\n\nfunction resolveSessionInput<TInput extends AgentBackendInput>(\n input: TInput | (() => TInput),\n): TInput {\n return typeof input === 'function' ? input() : input\n}\n\nfunction assertSessionBackend(session: RuntimeSession, backend: string): void {\n if (session.backend !== backend) throw new SessionMismatchError(session.backend, backend)\n}\n\n/** In-memory `RuntimeSessionStore` for single-process use and tests. @stable */\nexport class InMemoryRuntimeSessionStore implements RuntimeSessionStore {\n private readonly sessions = new Map<string, RuntimeSession>()\n private readonly events = new Map<string, RuntimeStreamEvent[]>()\n\n get(sessionId: string): RuntimeSession | undefined {\n return this.sessions.get(sessionId)\n }\n\n put(session: RuntimeSession): void {\n this.sessions.set(session.id, session)\n }\n\n appendEvent(sessionId: string, event: RuntimeStreamEvent): void {\n const existing = this.events.get(sessionId) ?? []\n existing.push(event)\n this.events.set(sessionId, existing)\n }\n\n listEvents(sessionId: string): RuntimeStreamEvent[] {\n return [...(this.events.get(sessionId) ?? [])]\n }\n}\n","/**\n * Provider-neutral backend adapters for `runAgentTaskStream`.\n *\n * Model inference is deliberately absent. Paid model work enters the Runtime executor with an\n * exact `AgentProfile`; these adapters only normalize a caller-owned iterable or sandbox stream.\n *\n * @stable\n */\n\nimport { newRuntimeSession, nowIso, touchSession } from './sessions'\nimport type {\n AgentBackendContext,\n AgentBackendInput,\n AgentExecutionBackend,\n RuntimeSession,\n RuntimeStreamEvent,\n} from './types'\n\n/** Wrap any custom async-iterable stream into a typed `AgentExecutionBackend`. @stable */\nexport function createIterableBackend<TInput extends AgentBackendInput>(options: {\n kind: string\n start?: AgentExecutionBackend<TInput>['start']\n resume?: AgentExecutionBackend<TInput>['resume']\n stream: AgentExecutionBackend<TInput>['stream']\n stop?: AgentExecutionBackend<TInput>['stop']\n}): AgentExecutionBackend<TInput> {\n return options\n}\n\n/** Build an `AgentExecutionBackend` backed by a sandbox/sidecar `streamPrompt` call. @stable */\nexport function createSandboxPromptBackend<\n TBox,\n TInput extends AgentBackendInput = AgentBackendInput,\n>(options: {\n kind?: string\n getBox(input: TInput, context: Omit<AgentBackendContext, 'session'>): Promise<TBox> | TBox\n streamPrompt(box: TBox, message: string, context: AgentBackendContext): AsyncIterable<unknown>\n mapEvent?: (event: unknown, context: AgentBackendContext) => RuntimeStreamEvent | undefined\n getSessionId?: (box: TBox, input: TInput) => string | undefined\n}): AgentExecutionBackend<TInput> {\n const kind = options.kind ?? 'sandbox'\n return {\n kind,\n async start(input, context) {\n const box = await options.getBox(input, context)\n return newRuntimeSession(\n kind,\n options.getSessionId?.(box, input) ?? context.requestedSessionId,\n { resumable: true },\n )\n },\n resume(session) {\n return touchSession({ ...session, status: 'active' })\n },\n async *stream(input, context) {\n const box = await options.getBox(input, context)\n const message = input.message ?? input.messages?.at(-1)?.content ?? context.task.intent\n for await (const event of options.streamPrompt(box, message, context)) {\n const mapped = options.mapEvent?.(event, context) ?? mapCommonBackendEvent(event, context)\n if (mapped) yield mapped\n }\n },\n }\n}\n\n/** @internal */\nexport function normalizeBackendStreamEvent(\n event: RuntimeStreamEvent,\n task: AgentBackendContext['task'],\n session: RuntimeSession,\n): RuntimeStreamEvent {\n if (\n 'task' in event &&\n event.task &&\n 'session' in event &&\n event.session &&\n 'timestamp' in event &&\n event.timestamp\n ) {\n return event\n }\n return {\n ...event,\n task: 'task' in event && event.task ? event.task : task,\n session: 'session' in event && event.session ? event.session : session,\n timestamp: 'timestamp' in event && event.timestamp ? event.timestamp : nowIso(),\n } as RuntimeStreamEvent\n}\n\nfunction mapCommonBackendEvent(\n event: unknown,\n context: AgentBackendContext,\n): RuntimeStreamEvent | undefined {\n if (!event || typeof event !== 'object') return undefined\n const record = event as Record<string, unknown>\n const type = String(record.type ?? '')\n const data =\n record.data && typeof record.data === 'object'\n ? (record.data as Record<string, unknown>)\n : record\n if (type === 'message.part.updated' || type === 'text_delta' || type === 'delta') {\n const part = data.part as Record<string, unknown> | undefined\n const partText =\n part !== undefined &&\n typeof part === 'object' &&\n (part.type === 'text' || part.type === undefined)\n ? stringValue(part.text)\n : undefined\n const text =\n stringValue(data.text) ?? stringValue(data.delta) ?? stringValue(record.text) ?? partText\n return text\n ? {\n type: 'text_delta',\n task: context.task,\n session: context.session,\n text,\n timestamp: nowIso(),\n }\n : undefined\n }\n if (type === 'reasoning_delta') {\n const text = stringValue(data.text) ?? stringValue(record.text)\n return text\n ? {\n type: 'reasoning_delta',\n task: context.task,\n session: context.session,\n text,\n timestamp: nowIso(),\n }\n : undefined\n }\n if (type === 'tool_call') {\n return {\n type: 'tool_call',\n task: context.task,\n session: context.session,\n toolName: stringValue(data.name) ?? stringValue(record.toolName) ?? 'tool',\n toolCallId: stringValue(data.id) ?? stringValue(record.toolCallId),\n args: data.args ?? data.input ?? record.args,\n timestamp: nowIso(),\n }\n }\n if (type === 'tool_result') {\n return {\n type: 'tool_result',\n task: context.task,\n session: context.session,\n toolName: stringValue(data.name) ?? stringValue(record.toolName) ?? 'tool',\n toolCallId: stringValue(data.id) ?? stringValue(record.toolCallId),\n result: data.result ?? data.output ?? record.result,\n timestamp: nowIso(),\n }\n }\n if (type === 'artifact') {\n const artifactId =\n stringValue(data.artifactId) ?? stringValue(data.id) ?? stringValue(record.artifactId)\n if (!artifactId) return undefined\n return {\n type: 'artifact',\n task: context.task,\n session: context.session,\n artifactId,\n name: stringValue(data.name) ?? stringValue(record.name),\n mimeType: stringValue(data.mimeType) ?? stringValue(record.mimeType),\n uri: stringValue(data.uri) ?? stringValue(record.uri),\n content: stringValue(data.content) ?? stringValue(data.body) ?? stringValue(record.content),\n metadata:\n data.metadata && typeof data.metadata === 'object'\n ? (data.metadata as Record<string, unknown>)\n : undefined,\n timestamp: nowIso(),\n }\n }\n if (type === 'proposal_created' || type === 'proposal' || type === 'filing') {\n const proposalId =\n stringValue(data.proposalId) ?? stringValue(data.id) ?? stringValue(record.proposalId)\n if (!proposalId) return undefined\n const status = stringValue(data.status) ?? stringValue(record.status)\n return {\n type: 'proposal_created',\n task: context.task,\n session: context.session,\n proposalId,\n title: stringValue(data.title) ?? stringValue(record.title) ?? proposalId,\n status:\n status === 'pending' || status === 'approved' || status === 'rejected' ? status : undefined,\n content: stringValue(data.content) ?? stringValue(data.body) ?? stringValue(record.content),\n timestamp: nowIso(),\n }\n }\n if (type === 'result' || type === 'final') {\n const text = stringValue(data.finalText) ?? stringValue(data.text) ?? stringValue(record.text)\n return text\n ? {\n type: 'text_delta',\n task: context.task,\n session: context.session,\n text,\n timestamp: nowIso(),\n }\n : undefined\n }\n return undefined\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n","/**\n * `streamAgentTurn` — the ONE run-a-turn event-stream contract over every\n * execution substrate: a sandbox box (`SandboxInstance.streamPrompt`), a\n * one-shot Runtime-owned `Executor` (cli-bridge / router / sandbox, via\n * `ExecutorFactory`), and an in-process `AgentExecutionBackend`.\n *\n * One function, one vocabulary: every backend kind yields the existing\n * `RuntimeStreamEvent` union incrementally and ALWAYS terminates with a\n * `final` event whose `text` is the turn's final text and whose\n * `metadata.tokenUsage` / `metadata.costUsd` / `metadata.model` carry the\n * turn's metered usage. `collectAgentTurn` drains a stream into that terminal\n * summary plus the full event list.\n *\n * This is a UNIFICATION seam, not a new stream parser — each kind is a thin\n * adapter over code that already exists and is already hardened:\n * - `box` — `mapSandboxEvent` + `extractLlmCallEvent` (sandbox-events.ts)\n * project the sandbox event stream; its requested profile is\n * explicitly recorded as unverified because the box already exists.\n * - `executor` — Runtime materializes the exact `AgentProfile`, records its\n * identity receipts, drives the executor once, and tears it\n * down after capturing the terminal artifact.\n * - `chat` — the backend's own `stream()` surface, normalized by\n * `normalizeBackendStreamEvent`; its requested profile is likewise\n * unverified because an arbitrary backend cannot attest its setup.\n *\n * Distinct from `openSandboxRun` (box-only, session resume over one persistent\n * artifact, raw `SandboxEvent` deliverables) and from `runAgentTaskStream`\n * (full task lifecycle: knowledge preflight, session store, resume). This is\n * the minimal turn primitive underneath both worlds: prompt in, one normalized\n * event stream out, terminal result+usage guaranteed on every non-thrown path.\n *\n * Stream envelope: `backend_start` → incremental events → (`backend_error` on\n * failure) → `final`. A caller-initiated abort terminates with\n * `final.status: 'aborted'`; an expired `timeoutMs` deadline with\n * `final.status: 'failed'` — so cancellation stays distinguishable from a\n * blown deadline.\n *\n * Mid-stream lifecycle work needs NO extra API: the generator is pull-based,\n * so the producer is suspended between yields and resumes only when the caller\n * pulls again. A consumer can therefore run arbitrary async work between\n * events — sync state on each `tool_result`, decide a no-op retry after\n * draining, run a pre-`done` flush when it receives `final` and BEFORE it\n * forwards its own terminal event downstream. The interleaving is guaranteed\n * (and locked by test): nothing is produced past the event the caller is\n * holding.\n *\n * @stable\n */\n\nimport { scoreKnowledgeReadiness } from '@tangle-network/agent-eval'\nimport { type AgentProfile, canonicalCandidateDigest } from '@tangle-network/agent-interface'\nimport type { PromptOptions, SandboxEvent, SandboxInstance } from '@tangle-network/sandbox'\nimport { normalizeBackendStreamEvent } from '../backends'\nimport { BackendTransportError, ValidationError } from '../errors'\nimport { newRuntimeSession, nowIso } from '../sessions'\nimport type {\n AgentBackendInput,\n AgentExecutionBackend,\n AgentTaskSpec,\n AgentTaskStatus,\n BackendErrorDetail,\n RuntimeSession,\n RuntimeStreamEvent,\n} from '../types'\nimport { createSandboxToolPartState, mapSandboxEvent, mapSandboxToolEvent } from './sandbox-events'\nimport { executableAgentProfileSnapshot } from './supervise/executable-spec'\nimport {\n authoredProfileDigest,\n knownExecutionBindingReceipt,\n knownMaterializationReceipt,\n runtimeOwnedExecutorExecutionBinding,\n runtimeOwnedExecutorMaterialization,\n runtimeOwnedPendingExecutorMaterialization,\n unknownExecutionBindingReceipt,\n unknownMaterializationReceipt,\n} from './supervise/materialization'\nimport {\n concreteModelId,\n profileBridgeWireModel,\n profileProviderModel,\n} from './supervise/model-policy'\nimport type {\n ExecutionBindingReceipt,\n Executor,\n ExecutorFactory,\n ExecutorResult,\n NodeExecutionIdentity,\n ProfileMaterializationReceipt,\n UsageEvent,\n} from './supervise/types'\n\n/**\n * The execution substrate one turn runs on — a closed discriminated union over\n * the three stream surfaces the runtime already owns.\n *\n * @stable\n */\nexport type AgentTurnBackend = {\n /** A Runtime-owned executor factory materialized from this exact canonical profile. */\n kind: 'executor'\n factory: ExecutorFactory<unknown>\n /** Exact canonical identity materialized by the executor. */\n profile: AgentProfile\n /** Model label stamped on cost-only `llm_call` events. Default `'agent'`. */\n agentRunName?: string\n}\n\n/** Lower-level observation adapters. They normalize an already-created execution surface but do\n * not bind an AgentProfile to it, so they are deliberately absent from the public kernel export. */\ntype ObservedAgentTurnBackend =\n | {\n /** A live sandbox box: the turn is one `box.streamPrompt(prompt)` call. */\n kind: 'box'\n box: SandboxInstance\n /**\n * Per-turn `PromptOptions` forwarded verbatim to `streamPrompt`\n * (`sessionId`, `turnId`, `model`, `backend` profile, `timeoutMs`, …).\n * The turn's derived abort signal (caller `signal` + `timeoutMs`\n * deadline) is always installed as `signal` — pass cancellation through\n * `StreamAgentTurnOptions`, not here.\n */\n options?: Omit<PromptOptions, 'signal'>\n /** Model label stamped on cost-only `llm_call` events. Default `'agent'`. */\n agentRunName?: string\n }\n | {\n /**\n * A caller-supplied in-process `AgentExecutionBackend`: the turn is one\n * `backend.stream()` call.\n */\n kind: 'chat'\n backend: AgentExecutionBackend\n }\n\n/** One prompt or an exact OpenAI-compatible conversation carried as the turn input. */\nexport type AgentTurnInput =\n | string\n | { readonly messages: ReadonlyArray<Readonly<Record<string, unknown>>> }\n\n/** @stable */\nexport interface StreamAgentTurnOptions {\n /** Caller-initiated cancellation. Terminates the stream with `final.status: 'aborted'`. */\n signal?: AbortSignal\n /**\n * Wall-clock deadline for the whole turn in ms. An expired deadline aborts\n * the backend and terminates the stream with `final.status: 'failed'`\n * (a blown deadline is a turn failure, not a caller cancellation).\n */\n timeoutMs?: number\n /** Stable logical paid-call id, forwarded as the provider idempotency key and retained in evidence. */\n callId?: string\n /** Caller trace tag retained in evidence and forwarded when the transport supports it. */\n correlationId?: string\n /**\n * Opt-in tool-part projection for box and executor backends: sandbox tool\n * parts additionally surface in-stream as\n * `tool_call` / `tool_result` events (`mapSandboxToolEvent`), so a consumer\n * rendering tool activity needs no bespoke sandbox-event parser. Default\n * off — the stream vocabulary existing consumers see is unchanged. No-op\n * for the `chat` kind (its backend emits `RuntimeStreamEvent`s directly,\n * tool events included when the backend produces them).\n */\n preserveToolParts?: boolean\n /**\n * Raw-event tap for box-kind backends: called (and awaited) with every\n * unmapped `SandboxEvent` BEFORE it is projected, so a consumer can read\n * parts the chat-UX projection drops (part ids, step markers, custom\n * backend events) without forking the mapper. Purely observational — it\n * cannot alter the mapped stream. Never called for the `chat` kind, which\n * has no sandbox events.\n */\n onRawEvent?: (event: SandboxEvent) => void | Promise<void>\n}\n\nfunction turnIntent(input: AgentTurnInput): string {\n if (typeof input === 'string') return input\n for (let index = input.messages.length - 1; index >= 0; index -= 1) {\n const message = input.messages[index]\n if (message?.role === 'user' && typeof message.content === 'string') return message.content\n }\n return 'structured agent turn'\n}\n\nfunction turnBackendInput(task: AgentTaskSpec, input: AgentTurnInput): AgentBackendInput {\n if (typeof input === 'string') return { task, message: input }\n return {\n task,\n messages: input.messages.map((message) => ({ ...message })) as AgentBackendInput['messages'],\n }\n}\n\nfunction executorEvidence(\n executor: Executor<unknown>,\n profile: AgentProfile,\n attemptId: string,\n): {\n materialization: ProfileMaterializationReceipt\n executionBinding: ExecutionBindingReceipt\n} {\n const profileDigest = authoredProfileDigest(profile)\n const declaration = runtimeOwnedExecutorMaterialization(executor)\n if (!profileDigest || !declaration) {\n const materialization = unknownMaterializationReceipt({\n ...(profileDigest ? { authoredProfileDigest: profileDigest } : {}),\n runtime: executor.runtime,\n reason: declaration ? 'invalid-executor-report' : 'executor-did-not-report',\n })\n return {\n materialization,\n executionBinding: unknownExecutionBindingReceipt(\n materialization,\n attemptId,\n declaration ? 'invalid-executor-report' : 'executor-did-not-report',\n ),\n }\n }\n try {\n const materialization = knownMaterializationReceipt({\n authoredProfileDigest: profileDigest,\n runtime: executor.runtime,\n declaration,\n })\n const binding = runtimeOwnedExecutorExecutionBinding(executor)\n if (!binding || binding.attemptId !== attemptId) throw new Error('executor attempt id mismatch')\n return {\n materialization,\n executionBinding: knownExecutionBindingReceipt(materialization, binding),\n }\n } catch {\n const materialization = unknownMaterializationReceipt({\n authoredProfileDigest: profileDigest,\n runtime: executor.runtime,\n reason: 'invalid-executor-report',\n })\n return {\n materialization,\n executionBinding: unknownExecutionBindingReceipt(\n materialization,\n attemptId,\n 'invalid-executor-report',\n ),\n }\n }\n}\n\n/** Exact turns require the model-bearing profile to be the sole behavioral authority. Runtime\n * checks the trusted declaration before execution so a seam fallback cannot hide behind the same\n * profile digest. */\nfunction assertExactExecutorDeclaration(executor: Executor<unknown>, profile: AgentProfile): void {\n const profileModel = profileProviderModel(profile)\n if (!profileModel) {\n throw new ValidationError(\n 'streamAgentTurn: exact AgentProfile.model.default must name the concrete model',\n )\n }\n const declaration =\n runtimeOwnedExecutorMaterialization(executor) ??\n runtimeOwnedPendingExecutorMaterialization(executor)?.declaration\n if (!declaration) return\n if (declaration.model.status !== 'known') {\n throw new ValidationError(\n 'streamAgentTurn: exact executor did not materialize a known model identity',\n )\n }\n if (declaration.backend === 'router' || declaration.backend === 'router-tools') {\n const plan = declaration.plan as {\n configuredModel?: unknown\n configuredReasoningEffort?: unknown\n reasoningEffort?: unknown\n }\n if (declaration.model.id !== profileModel) {\n throw new ValidationError(\n 'streamAgentTurn: Router executor model differs from AgentProfile.model.default',\n )\n }\n if (\n plan.configuredModel !== null &&\n plan.configuredModel !== undefined &&\n concreteModelId(String(plan.configuredModel)) !== profileModel\n ) {\n throw new ValidationError(\n 'streamAgentTurn: configured Router model conflicts with AgentProfile.model.default',\n )\n }\n const expectedEffort = profile.model?.reasoningEffort ?? null\n if (\n plan.configuredReasoningEffort !== null &&\n plan.configuredReasoningEffort !== undefined &&\n plan.configuredReasoningEffort !== expectedEffort\n ) {\n throw new ValidationError(\n 'streamAgentTurn: configured Router reasoning conflicts with AgentProfile.model.reasoningEffort',\n )\n }\n if ((plan.reasoningEffort ?? null) !== expectedEffort) {\n throw new ValidationError(\n 'streamAgentTurn: Router reasoning effort must come from AgentProfile.model.reasoningEffort',\n )\n }\n }\n if (declaration.backend === 'bridge' || declaration.backend === 'bridge-worktree') {\n const expectedWireModel = profileBridgeWireModel(profile)\n if (!expectedWireModel || declaration.model.id !== expectedWireModel) {\n throw new ValidationError(\n 'streamAgentTurn: bridge executor model differs from the AgentProfile harness/provider/model wire id',\n )\n }\n const plan = declaration.plan as { configuredModel?: unknown }\n if (\n plan.configuredModel !== null &&\n plan.configuredModel !== undefined &&\n concreteModelId(String(plan.configuredModel)) !== expectedWireModel\n ) {\n throw new ValidationError(\n 'streamAgentTurn: configured bridge model conflicts with the AgentProfile harness/provider/model wire id',\n )\n }\n }\n}\n\nfunction turnProvenance(\n startedAt: number,\n timeoutMs: number | undefined,\n profileDigest: string | undefined,\n taskDigest: string,\n materialization: ProfileMaterializationReceipt | undefined,\n executionBinding: ExecutionBindingReceipt | undefined,\n correlation: Readonly<Record<string, string>>,\n): Record<string, unknown> {\n const endedAt = Date.now()\n return {\n ...(profileDigest\n ? {\n identity: {\n profileDigest,\n taskDigest,\n ...(Object.keys(correlation).length > 0 ? { correlation } : {}),\n },\n }\n : { taskDigest }),\n ...(materialization ? { materialization } : {}),\n ...(executionBinding ? { executionBindings: [executionBinding] } : {}),\n budget: { timeoutMs: timeoutMs ?? null },\n timing: {\n startedAt: new Date(startedAt).toISOString(),\n endedAt: new Date(endedAt).toISOString(),\n durationMs: endedAt - startedAt,\n },\n }\n}\n\n/**\n * Metered usage of one turn, summed over every cost-bearing event the backend\n * emitted. `input`/`output` are token counts and are accompanied by\n * `tokensKnown: false` when the backend did not report them. `costUsd`/`model`\n * are present only when the backend actually reported them.\n *\n * @stable\n */\nexport interface AgentTurnUsage {\n input: number\n output: number\n /** Present when a real turn ran but the provider did not report token usage. */\n tokensKnown?: false\n costUsd?: number\n /** Present when Runtime could not prove the full dollar amount. */\n usdKnown?: false\n /** Separately-labelled local/catalog estimate; never billed spend. */\n estimatedCostUsd?: number\n /** Provider-reported prompt-cache fields; absent fields remain unknown. */\n promptCache?: Readonly<Record<string, number | string>>\n /** Provider-reported reasoning-token subset of output, when available. */\n reasoningTokens?: number\n model?: string\n}\n\n/**\n * A drained turn: the terminal summary plus every event the stream yielded.\n * `status`/`error` mirror the terminal `final` event so a failed or aborted\n * turn stays inspectable without re-scanning `events`.\n *\n * @stable\n */\nexport interface CollectedAgentTurn {\n finalText: string\n /** Exact terminal artifact output from a Runtime-owned executor. */\n output?: unknown\n usage: AgentTurnUsage\n /** Exact underlying transport calls when the Runtime-owned executor reports them. */\n transportAttempts?: number\n toolCalls: Array<{ id?: string; name: string; arguments: string }>\n events: RuntimeStreamEvent[]\n status: AgentTaskStatus\n error?: BackendErrorDetail\n}\n\n/** Mutable per-turn accumulator threaded through the backend adapters. */\ninterface TurnAccumulator {\n /** Concatenated incremental text (`text_delta` events). */\n deltaText: string\n /** Final text read off a terminal `result`/`done`/`final` event, when the\n * backend emitted one. Preferred over `deltaText` for box streams, whose\n * `message.part.updated` fallback carries running accumulations. */\n terminalText?: string\n input: number\n output: number\n costUsd: number\n estimatedCostUsd: number\n sawEstimatedCost: boolean\n promptCache: Record<string, number | string>\n reasoningTokens?: number\n tokensKnown: boolean\n usdKnown: boolean\n sawLlmCall: boolean\n model?: string\n stopReason?: string\n transportAttempts?: number\n result?: ExecutorResult<unknown>\n}\n\n/**\n * Run ONE agent turn on any backend kind and stream its events. Yields the\n * `RuntimeStreamEvent` vocabulary incrementally and always ends with a `final`\n * event carrying the turn's text and usage (`metadata.tokenUsage`,\n * `metadata.costUsd?`, `metadata.model?`) — on success, failure, abort, and\n * timeout alike. The generator never throws; failures surface in-band as\n * `backend_error` + `final` with a typed `error` detail.\n *\n * @stable\n */\nexport async function* streamAgentTurn(\n backend: AgentTurnBackend,\n input: AgentTurnInput,\n opts: StreamAgentTurnOptions = {},\n): AsyncGenerator<RuntimeStreamEvent> {\n assertTurnTimeout(opts.timeoutMs)\n if ((backend as { kind?: unknown }).kind !== 'executor') {\n throw new ValidationError(\n \"streamAgentTurn: exact execution accepts only kind 'executor'; use Runtime-owned creation\",\n )\n }\n yield* streamAgentTurnInternal(backend, input, opts)\n}\n\n/** @internal Normalize a pre-created box/chat stream without asserting an AgentProfile identity. */\nexport async function* streamObservedAgentTurn(\n backend: ObservedAgentTurnBackend,\n input: AgentTurnInput,\n opts: StreamAgentTurnOptions = {},\n): AsyncGenerator<RuntimeStreamEvent> {\n assertTurnTimeout(opts.timeoutMs)\n yield* streamAgentTurnInternal(backend, input, opts)\n}\n\nfunction assertTurnTimeout(timeoutMs: number | undefined): void {\n if (timeoutMs === undefined) return\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2_147_483_647) {\n throw new ValidationError('streamAgentTurn: timeoutMs must be an integer from 1 to 2147483647')\n }\n}\n\nfunction assertTurnIdentity(value: string | undefined, field: string): void {\n if (value !== undefined && (typeof value !== 'string' || value.trim().length === 0)) {\n throw new ValidationError(`streamAgentTurn: ${field} must be a non-empty string`)\n }\n}\n\nasync function* streamAgentTurnInternal(\n backend: AgentTurnBackend | ObservedAgentTurnBackend,\n input: AgentTurnInput,\n opts: StreamAgentTurnOptions,\n): AsyncGenerator<RuntimeStreamEvent> {\n const label = backend.kind === 'chat' ? backend.backend.kind : backend.kind\n const profile =\n backend.kind === 'executor'\n ? executableAgentProfileSnapshot(backend.profile, 'streamAgentTurn')\n : undefined\n const profileDigest = profile ? authoredProfileDigest(profile) : undefined\n assertTurnIdentity(opts.callId, 'callId')\n assertTurnIdentity(opts.correlationId, 'correlationId')\n const correlation = {\n ...(opts.callId ? { callId: opts.callId } : {}),\n ...(opts.correlationId ? { correlationId: opts.correlationId } : {}),\n }\n const taskInput = input\n const taskDigest = canonicalCandidateDigest(taskInput)\n const task: AgentTaskSpec = {\n id: `turn-${crypto.randomUUID()}`,\n intent: turnIntent(input),\n ...(profileDigest\n ? {\n metadata: {\n identity: {\n profileDigest,\n taskDigest,\n ...(Object.keys(correlation).length > 0 ? { correlation } : {}),\n } satisfies NodeExecutionIdentity,\n },\n }\n : {}),\n }\n const acc: TurnAccumulator = {\n deltaText: '',\n input: 0,\n output: 0,\n costUsd: 0,\n estimatedCostUsd: 0,\n sawEstimatedCost: false,\n promptCache: {},\n tokensKnown: false,\n usdKnown: false,\n sawLlmCall: false,\n }\n const deadline = deriveTurnSignal(opts.signal, opts.timeoutMs ?? 0)\n const startedAt = Date.now()\n\n let session: RuntimeSession | undefined\n let executor: Executor<unknown> | undefined\n let materialization: ProfileMaterializationReceipt | undefined\n let executionBinding: ExecutionBindingReceipt | undefined\n try {\n const nodeId = task.id\n const attemptId = `${nodeId}:attempt:${crypto.randomUUID()}`\n if (backend.kind === 'executor') {\n executor = backend.factory(\n { profile: profile!, harness: null },\n {\n signal: deadline.signal,\n seams: {},\n node: {\n rootId: nodeId,\n parentId: nodeId,\n nodeId,\n attemptId,\n identity: {\n profileDigest: profileDigest!,\n taskDigest,\n ...(Object.keys(correlation).length > 0 ? { correlation } : {}),\n },\n },\n },\n )\n assertExactExecutorDeclaration(executor, profile!)\n const pending = runtimeOwnedPendingExecutorMaterialization(executor)\n if (pending !== undefined) {\n if (pending.runtime !== executor.runtime || pending.binding.attemptId !== attemptId) {\n throw new ValidationError(\n 'streamAgentTurn: pending executor did not bind the kernel-minted attempt',\n )\n }\n if (authoredProfileDigest(pending.declaration.effectiveProfile) !== profileDigest) {\n throw new ValidationError(\n 'streamAgentTurn: pending executor changed the authored AgentProfile before execution',\n )\n }\n materialization = unknownMaterializationReceipt({\n authoredProfileDigest: profileDigest!,\n runtime: executor.runtime,\n reason: 'executor-receipt-pending',\n })\n executionBinding = unknownExecutionBindingReceipt(\n materialization,\n attemptId,\n 'executor-receipt-pending',\n )\n } else {\n ;({ materialization, executionBinding } = executorEvidence(executor, profile!, attemptId))\n assertExactExecutorEvidence(materialization, executionBinding)\n }\n } else {\n materialization = unknownMaterializationReceipt({\n runtime: backend.kind === 'box' ? 'sandbox' : label,\n reason: 'executor-did-not-report',\n })\n executionBinding = unknownExecutionBindingReceipt(\n materialization,\n attemptId,\n 'executor-did-not-report',\n )\n }\n session = await startTurnSession(backend, task, input, deadline.signal, label)\n yield {\n type: 'backend_start',\n task,\n session,\n backend: executor?.runtime ?? label,\n metadata: {\n ...(profileDigest\n ? {\n identity: {\n profileDigest,\n taskDigest,\n ...(Object.keys(correlation).length > 0 ? { correlation } : {}),\n },\n }\n : { taskDigest }),\n ...(materialization ? { materialization } : {}),\n ...(executionBinding ? { executionBindings: [executionBinding] } : {}),\n budget: { timeoutMs: opts.timeoutMs ?? null },\n timing: { startedAt: new Date(startedAt).toISOString() },\n },\n timestamp: nowIso(),\n }\n\n const inner =\n backend.kind === 'chat'\n ? driveChatTurn(backend.backend, task, session, input, deadline.signal, acc)\n : backend.kind === 'executor'\n ? driveExecutorTurn(\n executor!,\n task,\n session,\n input,\n deadline.signal,\n acc,\n materializedModel(materialization, profile!),\n )\n : driveBoxTurn(\n backend.box,\n turnIntent(input),\n deadline.signal,\n backend.agentRunName ?? 'agent',\n acc,\n {\n ...(backend.options ? { options: backend.options } : {}),\n preserveToolParts: opts.preserveToolParts === true,\n ...(opts.onRawEvent ? { onRawEvent: opts.onRawEvent } : {}),\n },\n )\n for await (const event of inner) {\n yield event\n throwIfAborted(deadline.signal)\n }\n\n if (backend.kind === 'executor') {\n ;({ materialization, executionBinding } = executorEvidence(executor!, profile!, attemptId))\n assertExactExecutorEvidence(materialization, executionBinding)\n }\n\n yield buildFinalEvent(\n task,\n session,\n acc,\n { status: 'completed', reason: 'turn completed' },\n turnProvenance(\n startedAt,\n opts.timeoutMs,\n profileDigest,\n taskDigest,\n materialization,\n executionBinding,\n correlation,\n ),\n )\n } catch (err) {\n // The turn is over, so a pending receipt cannot still resolve. `backend_start` already\n // carried the pending value, where it was true; the final event must name the terminal\n // outcome instead of a wait that has ended.\n if (\n materialization?.status === 'unknown' &&\n materialization.reason === 'executor-receipt-pending' &&\n executionBinding?.status === 'unknown'\n ) {\n const terminal = unknownMaterializationReceipt({\n ...(materialization.authoredProfileDigest === undefined\n ? {}\n : { authoredProfileDigest: materialization.authoredProfileDigest }),\n runtime: materialization.runtime,\n reason: 'executor-failed-before-receipt',\n })\n executionBinding = unknownExecutionBindingReceipt(\n terminal,\n executionBinding.attemptId,\n 'executor-failed-before-receipt',\n )\n materialization = terminal\n }\n const callerAborted = opts.signal?.aborted === true\n const status: AgentTaskStatus = callerAborted ? 'aborted' : 'failed'\n const message = err instanceof Error ? err.message : String(err)\n const error: BackendErrorDetail =\n err instanceof BackendTransportError\n ? { kind: 'transport', message, status: err.status, body: err.body }\n : { kind: 'backend', message }\n yield {\n type: 'backend_error',\n task,\n ...(session ? { session } : {}),\n backend: label,\n message,\n recoverable: !callerAborted,\n error,\n timestamp: nowIso(),\n }\n yield buildFinalEvent(\n task,\n session,\n acc,\n { status, reason: message, error },\n turnProvenance(\n startedAt,\n opts.timeoutMs,\n profileDigest,\n taskDigest,\n materialization,\n executionBinding,\n correlation,\n ),\n )\n } finally {\n await executor?.teardown('brutalKill').catch(() => undefined)\n deadline.dispose()\n }\n}\n\nfunction assertExactExecutorEvidence(\n materialization: ProfileMaterializationReceipt,\n executionBinding: ExecutionBindingReceipt,\n): void {\n if (materialization.status !== 'known' || executionBinding.status !== 'known') {\n throw new ValidationError(\n 'streamAgentTurn: exact profile execution requires terminally validated Runtime materialization and execution binding evidence',\n )\n }\n if (materialization.effectiveProfileDigest !== materialization.authoredProfileDigest) {\n throw new ValidationError(\n 'streamAgentTurn: executor changed the authored AgentProfile; exact turn execution refuses profile overlays',\n )\n }\n}\n\n/**\n * Drain a `streamAgentTurn` stream (or any `RuntimeStreamEvent` stream that\n * honors its terminal contract) into the turn summary plus the full event\n * list. Fail-loud: throws when the stream ends without a terminal `final`\n * event — a stream that violates the contract must not read as an empty turn.\n *\n * @stable\n */\nexport async function collectAgentTurn(\n stream: AsyncIterable<RuntimeStreamEvent>,\n): Promise<CollectedAgentTurn> {\n const events: RuntimeStreamEvent[] = []\n for await (const event of stream) events.push(event)\n const final = events.at(-1)\n if (final?.type !== 'final') {\n throw new Error(\n `collectAgentTurn: stream ended without a terminal 'final' event (last: ${final ? final.type : 'none'})`,\n )\n }\n const metadata = final.metadata ?? {}\n const resultMetadata =\n metadata.result && typeof metadata.result === 'object'\n ? (metadata.result as Record<string, unknown>)\n : undefined\n const tokenUsage =\n metadata.tokenUsage && typeof metadata.tokenUsage === 'object'\n ? (metadata.tokenUsage as Record<string, unknown>)\n : {}\n const usage: AgentTurnUsage = {\n input: finiteNumber(tokenUsage.input) ?? 0,\n output: finiteNumber(tokenUsage.output) ?? 0,\n ...(metadata.tokensKnown === false ? { tokensKnown: false as const } : {}),\n }\n const costUsd = finiteNumber(metadata.costUsd)\n if (costUsd !== undefined) usage.costUsd = costUsd\n if (metadata.usdKnown === false) usage.usdKnown = false\n const estimatedCostUsd = finiteNumber(metadata.estimatedCostUsd)\n if (estimatedCostUsd !== undefined) usage.estimatedCostUsd = estimatedCostUsd\n if (metadata.promptCache && typeof metadata.promptCache === 'object') {\n usage.promptCache = metadata.promptCache as Record<string, number | string>\n }\n const reasoningTokens = finiteNumber(metadata.reasoningTokens)\n if (reasoningTokens !== undefined) usage.reasoningTokens = reasoningTokens\n if (typeof metadata.model === 'string' && metadata.model.length > 0) {\n usage.model = metadata.model\n }\n const transportAttempts = finiteNumber(metadata.transportAttempts)\n const toolCalls = events\n .filter((event) => event.type === 'tool_call')\n .map((event) => ({\n ...(event.toolCallId ? { id: event.toolCallId } : {}),\n name: event.toolName,\n arguments: typeof event.args === 'string' ? event.args : JSON.stringify(event.args ?? {}),\n }))\n return {\n finalText: final.text ?? '',\n ...(resultMetadata && 'output' in resultMetadata ? { output: resultMetadata.output } : {}),\n usage,\n ...(transportAttempts !== undefined ? { transportAttempts } : {}),\n toolCalls,\n events,\n status: final.status,\n ...(final.error ? { error: final.error } : {}),\n }\n}\n\n/** Start the backend's session when it owns one (`chat` kind); mint a local\n * correlation session otherwise. Box/executor turns carry no server session\n * here — resume lives in `openSandboxRun`/`SandboxLineage`, not this primitive. */\nasync function startTurnSession(\n backend: AgentTurnBackend | ObservedAgentTurnBackend,\n task: AgentTaskSpec,\n input: AgentTurnInput,\n signal: AbortSignal,\n label: string,\n): Promise<RuntimeSession> {\n if (backend.kind === 'chat' && backend.backend.start) {\n return backend.backend.start(turnBackendInput(task, input), {\n task,\n knowledge: emptyReadiness(task),\n signal,\n })\n }\n return newRuntimeSession(label)\n}\n\n/** Box-drive configuration derived from the backend kind + turn options. */\ninterface BoxTurnConfig {\n /** Caller `PromptOptions` forwarded to `streamPrompt`; the turn's derived\n * signal is installed over any caller value. */\n options?: Omit<PromptOptions, 'signal'>\n /** Project tool parts to `tool_call`/`tool_result` (see `mapSandboxToolEvent`). */\n preserveToolParts: boolean\n /** Awaited raw-event tap, before projection. */\n onRawEvent?: (event: SandboxEvent) => void | Promise<void>\n}\n\n/**\n * One turn over a box: `box.streamPrompt` projected through the existing\n * `mapSandboxEvent` (text/reasoning deltas +\n * cost-bearing `llm_call`s), plus the opt-in `mapSandboxToolEvent` tool-part\n * projection. Usage accumulates off the mapped `llm_call` events — the same\n * fold `sumSandboxUsage` applies. Final text prefers the terminal\n * `result`/`done`/`final` payload over concatenated deltas, because the\n * sandbox `message.part.updated` fallback may carry running accumulations.\n */\nasync function* driveBoxTurn(\n box: SandboxInstance,\n prompt: string,\n signal: AbortSignal,\n agentRunName: string,\n acc: TurnAccumulator,\n cfg: BoxTurnConfig,\n): AsyncGenerator<RuntimeStreamEvent> {\n const callOptions: PromptOptions = { ...(cfg.options ?? {}), signal }\n const stream = box.streamPrompt(prompt, callOptions)\n const toolParts = cfg.preserveToolParts ? createSandboxToolPartState() : undefined\n for await (const event of stream) {\n if (cfg.onRawEvent) await cfg.onRawEvent(event)\n const terminalText = terminalTextFromSandboxEvent(event)\n if (terminalText !== undefined) acc.terminalText = terminalText\n if (toolParts) {\n for (const toolEvent of mapSandboxToolEvent(event, toolParts)) yield toolEvent\n }\n const mapped = mapSandboxEvent(event, { agentRunName })\n if (!mapped) continue\n // `mapSandboxEvent` stamps `agentRunName` as the model label when the\n // event carried none — a run label, not a reported model. Exclude it from\n // the terminal usage so `usage.model` is never a fabricated value.\n foldEvent(mapped, acc, agentRunName)\n yield mapped\n }\n}\n\n/** One turn over an in-process backend: its own `stream()` surface, projected\n * through the same `normalizeBackendStreamEvent` the task lifecycle applies. */\nasync function* driveChatTurn(\n backend: AgentExecutionBackend,\n task: AgentTaskSpec,\n session: RuntimeSession,\n input: AgentTurnInput,\n signal: AbortSignal,\n acc: TurnAccumulator,\n): AsyncGenerator<RuntimeStreamEvent> {\n const backendInput = turnBackendInput(task, input)\n const context = { task, knowledge: emptyReadiness(task), session, signal }\n for await (const raw of backend.stream(backendInput, context)) {\n const event = normalizeBackendStreamEvent(raw, task, session)\n foldEvent(event, acc)\n yield event\n }\n}\n\nasync function* driveExecutorTurn(\n executor: Executor<unknown>,\n task: AgentTaskSpec,\n session: RuntimeSession,\n input: AgentTurnInput,\n signal: AbortSignal,\n acc: TurnAccumulator,\n declaredModel: string | undefined,\n): AsyncGenerator<RuntimeStreamEvent> {\n const taskValue = typeof input === 'string' ? input : { messages: input.messages }\n const run = executor.execute(taskValue, signal)\n let result: ExecutorResult<unknown>\n if (isAsyncIterable(run)) {\n for await (const _usage of run) {\n throwIfAborted(signal)\n }\n result = executor.resultArtifact()\n } else {\n result = await run\n }\n acc.result = result\n acc.terminalText = executorResultText(result.out)\n acc.input = result.spent.tokens.input\n acc.output = result.spent.tokens.output\n acc.costUsd = result.spent.usd\n const estimatedCostUsd = executorResultEstimatedCost(result.out)\n if (estimatedCostUsd !== undefined) {\n acc.estimatedCostUsd = estimatedCostUsd\n acc.sawEstimatedCost = true\n }\n Object.assign(acc.promptCache, executorResultPromptCache(result.out))\n acc.reasoningTokens = executorResultReasoningTokens(result.out)\n acc.tokensKnown = result.spent.tokensKnown !== false\n acc.usdKnown = result.spent.usdKnown !== false\n acc.sawLlmCall = true\n\n // Usage model identity is observational: the executor must report what answered. The profile's\n // declared model remains available in materialization evidence, but it is not fabricated into\n // `usage.model` when the provider/transport omitted an actual response model.\n const model = executorResultModel(result.out)\n if (model) acc.model = model\n acc.stopReason = executorResultStopReason(result.out)\n acc.transportAttempts = executorResultTransportAttempts(result.out)\n const latencyMs = result.spent.ms\n yield {\n type: 'llm_call',\n task,\n session,\n model: model ?? declaredModel ?? executor.runtime,\n ...(acc.tokensKnown ? { tokensIn: acc.input, tokensOut: acc.output } : {}),\n ...(acc.usdKnown ? { costUsd: acc.costUsd } : {}),\n ...(acc.tokensKnown ? {} : { tokensKnown: false }),\n ...(acc.usdKnown ? {} : { usdKnown: false }),\n ...(acc.sawEstimatedCost ? { estimatedCostUsd: acc.estimatedCostUsd } : {}),\n ...(Object.keys(acc.promptCache).length > 0 ? { promptCache: acc.promptCache } : {}),\n latencyMs,\n timestamp: nowIso(),\n }\n for (const call of executorResultToolCalls(result.out)) {\n yield {\n type: 'tool_call',\n task,\n session,\n toolName: call.name,\n ...(call.id ? { toolCallId: call.id } : {}),\n args: call.arguments,\n timestamp: nowIso(),\n }\n }\n yield {\n type: 'artifact',\n task,\n session,\n artifactId: result.outRef,\n name: 'agent-turn-result',\n metadata: {\n spend: result.spent,\n ...(result.verdict ? { verdict: result.verdict } : {}),\n },\n timestamp: nowIso(),\n }\n}\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterable<UsageEvent> {\n return typeof value === 'object' && value !== null && Symbol.asyncIterator in value\n}\n\nfunction executorResultText(value: unknown): string {\n if (typeof value === 'string') return value\n if (!value || typeof value !== 'object') return ''\n const content = (value as Record<string, unknown>).content\n return typeof content === 'string' ? content : ''\n}\n\nfunction executorResultModel(value: unknown): string | undefined {\n if (!value || typeof value !== 'object') return undefined\n const model = (value as Record<string, unknown>).model\n return typeof model === 'string' && model.length > 0 ? model : undefined\n}\n\nfunction executorResultStopReason(value: unknown): string | undefined {\n if (!value || typeof value !== 'object') return undefined\n const reason = (value as Record<string, unknown>).finishReason\n return typeof reason === 'string' && reason.length > 0 ? reason : undefined\n}\n\nfunction executorResultTransportAttempts(value: unknown): number | undefined {\n if (!value || typeof value !== 'object') return undefined\n const attempts = (value as Record<string, unknown>).transportAttempts\n return typeof attempts === 'number' && Number.isSafeInteger(attempts) && attempts > 0\n ? attempts\n : undefined\n}\n\nfunction executorResultEstimatedCost(value: unknown): number | undefined {\n if (!value || typeof value !== 'object') return undefined\n return finiteNumber((value as Record<string, unknown>).estimatedCostUsd)\n}\n\nfunction executorResultPromptCache(value: unknown): Record<string, number | string> {\n if (!value || typeof value !== 'object') return {}\n const raw = (value as Record<string, unknown>).promptCache\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}\n const cache: Record<string, number | string> = {}\n for (const [key, entry] of Object.entries(raw)) {\n if ((typeof entry === 'number' && Number.isFinite(entry)) || typeof entry === 'string') {\n cache[key] = entry\n }\n }\n return cache\n}\n\nfunction executorResultReasoningTokens(value: unknown): number | undefined {\n if (!value || typeof value !== 'object') return undefined\n const count = (value as Record<string, unknown>).reasoningTokens\n return Number.isSafeInteger(count) && (count as number) >= 0 ? (count as number) : undefined\n}\n\nfunction executorResultToolCalls(\n value: unknown,\n): Array<{ id?: string; name: string; arguments: string }> {\n if (!value || typeof value !== 'object') return []\n const raw = (value as Record<string, unknown>).toolCalls\n if (!Array.isArray(raw)) return []\n return raw.flatMap((entry) => {\n if (!entry || typeof entry !== 'object') return []\n const call = entry as Record<string, unknown>\n if (typeof call.name !== 'string') return []\n return [\n {\n ...(typeof call.id === 'string' ? { id: call.id } : {}),\n name: call.name,\n arguments:\n typeof call.arguments === 'string'\n ? call.arguments\n : JSON.stringify(call.arguments ?? {}),\n },\n ]\n })\n}\n\n/** Fold one normalized event into the turn accumulator (text + usage).\n * `fallbackModelLabel` — a mapper-stamped run label to exclude from\n * `usage.model` (it is not a backend-reported model). */\nfunction foldEvent(\n event: RuntimeStreamEvent,\n acc: TurnAccumulator,\n fallbackModelLabel?: string,\n): void {\n if (event.type === 'text_delta') {\n acc.deltaText += event.text\n return\n }\n if (event.type === 'llm_call') {\n const tokensReported =\n event.tokensKnown !== false && event.tokensIn !== undefined && event.tokensOut !== undefined\n const usdReported = event.usdKnown !== false && event.costUsd !== undefined\n if (!acc.sawLlmCall) {\n acc.tokensKnown = tokensReported\n acc.usdKnown = usdReported\n acc.sawLlmCall = true\n } else {\n acc.tokensKnown &&= tokensReported\n acc.usdKnown &&= usdReported\n }\n acc.input += event.tokensIn ?? 0\n acc.output += event.tokensOut ?? 0\n acc.costUsd += event.costUsd ?? 0\n if (event.estimatedCostUsd !== undefined) {\n acc.estimatedCostUsd += event.estimatedCostUsd\n acc.sawEstimatedCost = true\n }\n if (event.promptCache) Object.assign(acc.promptCache, event.promptCache)\n if (event.model && event.model !== fallbackModelLabel) acc.model = event.model\n }\n}\n\n/** Read the final text off a terminal sandbox event, when present. */\nfunction terminalTextFromSandboxEvent(event: SandboxEvent): string | undefined {\n if (!event || typeof event !== 'object') return undefined\n const type = String(event.type ?? '')\n if (type !== 'result' && type !== 'done' && type !== 'final') return undefined\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n for (const key of ['finalText', 'text', 'response', 'content']) {\n const value = data[key]\n if (typeof value === 'string') return value\n }\n return undefined\n}\n\nfunction buildFinalEvent(\n task: AgentTaskSpec,\n session: RuntimeSession | undefined,\n acc: TurnAccumulator,\n outcome: { status: AgentTaskStatus; reason: string; error?: BackendErrorDetail },\n provenance: Record<string, unknown>,\n): RuntimeStreamEvent {\n const finalText = acc.terminalText ?? acc.deltaText\n return {\n type: 'final',\n task,\n ...(session ? { session } : {}),\n status: outcome.status,\n reason: outcome.status === 'completed' ? (acc.stopReason ?? outcome.reason) : outcome.reason,\n ...(finalText ? { text: finalText } : {}),\n metadata: {\n tokenUsage: { input: acc.input, output: acc.output },\n ...(acc.tokensKnown ? {} : { tokensKnown: false }),\n ...(acc.usdKnown ? { costUsd: acc.costUsd } : { usdKnown: false }),\n ...(acc.sawEstimatedCost ? { estimatedCostUsd: acc.estimatedCostUsd } : {}),\n ...(Object.keys(acc.promptCache).length > 0 ? { promptCache: acc.promptCache } : {}),\n ...(acc.reasoningTokens !== undefined ? { reasoningTokens: acc.reasoningTokens } : {}),\n ...(acc.model ? { model: acc.model } : {}),\n ...(acc.stopReason ? { stopReason: acc.stopReason } : {}),\n ...(acc.transportAttempts !== undefined ? { transportAttempts: acc.transportAttempts } : {}),\n ...(acc.result\n ? {\n result: {\n outRef: acc.result.outRef,\n output: acc.result.out,\n ...(acc.result.verdict ? { verdict: acc.result.verdict } : {}),\n spent: acc.result.spent,\n },\n }\n : {}),\n ...provenance,\n },\n ...(outcome.error ? { error: outcome.error } : {}),\n timestamp: nowIso(),\n }\n}\n\nfunction materializedModel(\n receipt: ProfileMaterializationReceipt | undefined,\n profile: AgentProfile,\n): string | undefined {\n if (receipt?.status === 'known' && receipt.model.status === 'known') return receipt.model.id\n const fallback = profile.model?.default\n return typeof fallback === 'string' && fallback.length > 0 ? fallback : undefined\n}\n\n/** Minimal ready-by-construction readiness report for a requirement-free turn. */\nfunction emptyReadiness(task: AgentTaskSpec) {\n return scoreKnowledgeReadiness({ taskId: task.id, requirements: [] })\n}\n\nfunction finiteNumber(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n if (!signal.aborted) return\n throw signal.reason instanceof Error ? signal.reason : new Error(String(signal.reason))\n}\n\n/**\n * Derive the turn's effective abort signal: fires when EITHER the caller's\n * signal aborts OR the `timeoutMs` deadline elapses. `dispose()` clears the\n * timer so a finished turn never leaks a pending timeout. `timeoutMs <= 0`\n * disables the deadline. Node-portable (no `AbortSignal.any`, which needs\n * >=20.3 — the package floor is >=20).\n */\nfunction deriveTurnSignal(\n callerSignal: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; dispose: () => void } {\n const controller = new AbortController()\n const timer =\n timeoutMs > 0\n ? setTimeout(\n () => controller.abort(new Error(`agent turn timed out after ${timeoutMs}ms`)),\n timeoutMs,\n )\n : undefined\n if (timer && typeof (timer as { unref?: () => void }).unref === 'function') {\n ;(timer as { unref: () => void }).unref()\n }\n const onCallerAbort = () =>\n controller.abort(callerSignal?.reason ?? new Error('agent turn aborted'))\n if (callerSignal) {\n if (callerSignal.aborted) onCallerAbort()\n else callerSignal.addEventListener('abort', onCallerAbort, { once: true })\n }\n return {\n signal: controller.signal,\n dispose: () => {\n if (timer) clearTimeout(timer)\n callerSignal?.removeEventListener('abort', onCallerAbort)\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAqBA,SAAgB,kBACd,SACA,aACA,UACgB;CAChB,MAAM,MAAM,OAAO;CACnB,OAAO;EACL,IAAI,eAAe,OAAO,WAAW;EACrC;EACA,QAAQ;EACR,WAAW;EACX,WAAW;EACX;CACF;AACF;;AAGA,SAAgB,aAAa,SAAyC;CACpE,OAAO;EAAE,GAAG;EAAS,WAAW,OAAO;CAAE;AAC3C;;AAGA,SAAgB,SAAiB;CAC/B,wBAAO,IAAI,KAAK,EAAA,CAAE,YAAY;AAChC;;AAqBA,eAAsB,4BACpB,SACqC;CACrC,MAAM,WACJ,QAAQ,UAAU,QAAQ,YAAY,MAAM,QAAQ,OAAO,IAAI,QAAQ,SAAS,IAAI,KAAA;CACtF,IAAI,CAAC,UAAU;EACb,MAAM,QAAQ,oBAAoB,QAAQ,KAAK;EAC/C,MAAM,UAAU,QAAQ,QAAQ,QAC5B,MAAM,QAAQ,QAAQ,MAAM,OAAO;GACjC,GAAG,QAAQ;GACX,oBAAoB,QAAQ;EAC9B,CAAC,IACD,kBAAkB,QAAQ,QAAQ,MAAM,QAAQ,SAAS;EAC7D,qBAAqB,SAAS,QAAQ,QAAQ,IAAI;EAClD,QAAQ,kBAAkB,OAAO;EACjC,MAAM,QAAQ,OAAO,IA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