@ponythewhite/base-context 1.0.8 → 1.0.10
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.
- package/CHANGELOG.md +13 -0
- package/dist/base-context-runtime/pyproject.toml +1 -1
- package/dist/base-context-runtime/uv.lock +1 -1
- package/dist/build-info.json +1 -1
- package/dist/bundle/{bundled-modules-IGMJH2MU.js → bundled-modules-MX6YNAM2.js} +2 -2
- package/dist/bundle/{chunk-EXEFSSF4.js → chunk-CDXQNS5P.js} +176 -37
- package/dist/bundle/{chunk-RVJVXZCS.js → chunk-UHLGPYMI.js} +20 -40
- package/dist/bundle/{cli-main-BUK7QTHO.js → cli-main-D7W3WWCV.js} +2 -2
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/{main-2FWHT2WZ.js → main-5J3QBZ5Y.js} +2 -2
- package/dist/core/agent-session.d.ts +3 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +48 -5
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/canonical-context.d.ts.map +1 -1
- package/dist/core/canonical-context.js +115 -30
- package/dist/core/canonical-context.js.map +1 -1
- package/dist/core/context-epoch.d.ts +14 -3
- package/dist/core/context-epoch.d.ts.map +1 -1
- package/dist/core/context-epoch.js +5 -1
- package/dist/core/context-epoch.js.map +1 -1
- package/dist/core/inference-coordinator.d.ts +1 -1
- package/dist/core/inference-coordinator.d.ts.map +1 -1
- package/dist/core/inference-coordinator.js +2 -2
- package/dist/core/inference-coordinator.js.map +1 -1
- package/dist/core/public-context.d.ts.map +1 -1
- package/dist/core/public-context.js +20 -8
- package/dist/core/public-context.js.map +1 -1
- package/dist/core/request-view-selection.d.ts +4 -2
- package/dist/core/request-view-selection.d.ts.map +1 -1
- package/dist/core/request-view-selection.js +7 -4
- package/dist/core/request-view-selection.js.map +1 -1
- package/dist/core/session-manager.d.ts +2 -0
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +38 -13
- package/dist/core/session-manager.js.map +1 -1
- package/dist/modes/daemon/daemon-mode.d.ts.map +1 -1
- package/dist/modes/daemon/daemon-mode.js +15 -30
- package/dist/modes/daemon/daemon-mode.js.map +1 -1
- package/dist/modes/daemon/daemon-socket.d.ts +5 -0
- package/dist/modes/daemon/daemon-socket.d.ts.map +1 -1
- package/dist/modes/daemon/daemon-socket.js +19 -0
- package/dist/modes/daemon/daemon-socket.js.map +1 -1
- package/dist/modes/daemon/daemon-supervisor.d.ts.map +1 -1
- package/dist/modes/daemon/daemon-supervisor.js +6 -7
- package/dist/modes/daemon/daemon-supervisor.js.map +1 -1
- package/dist/modes/daemon/daemon-worker-client.d.ts.map +1 -1
- package/dist/modes/daemon/daemon-worker-client.js +5 -5
- package/dist/modes/daemon/daemon-worker-client.js.map +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"canonical-context.d.ts","sourceRoot":"","sources":["../../src/core/canonical-context.ts"],"names":[],"mappings":"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","sourcesContent":["import type { AgentMessage } from \"@ponythewhite/base-context-agent\";\nimport { stringifyBoundedJson } from \"./bounded-json.js\";\nimport {\n\tCONTEXT_EPOCH_DETAIL,\n\tCONTEXT_EPOCH_RENDERER,\n\tCONTEXT_POLICY_EPOCH_RENDERER,\n\tCONTEXT_SKILL_EPOCH_RENDERER,\n\tCONTEXT_TOOL_EPOCH_RENDERER,\n\tCONTEXT_TOOL_SUMMARY_RENDERER,\n\ttype ContextEpochCheckpoint,\n\ttype ContextMode,\n\ttype ContextReplayContract,\n\tcontextEpochMode,\n\ttype EpochViewReference,\n\treadContextEpoch,\n\tretainedContextRequestContract,\n\tsnapshotContextEpoch,\n\ttype ToolContinuationGroup,\n} from \"./context-epoch.js\";\nimport type {\n\tContextManifestCursor,\n\tContextManifestPage,\n\tContextRef,\n\tContextUpdateRef,\n\tContextUpdateTarget,\n\tIndexedSourceEvent,\n} from \"./history-index.js\";\nimport { createCompactionSummaryMessage, createCustomMessage } from \"./messages.js\";\nimport {\n\tPUBLIC_CONTEXT_RENDERER,\n\tPUBLIC_TOOL_CONTINUATION_RENDERER,\n\trenderPublicHistory,\n\trenderToolContinuation,\n} from \"./public-context.js\";\nimport type { ContextEpochEntryRef, SourceSnapshotRef } from \"./request-events.js\";\nimport { type OwnedResourceCapture, renderResourceView } from \"./resource-view.js\";\nimport { isNativeSkillSelection, type SelectedSkillReference, selectedSkillCapture } from \"./selected-skills.js\";\nimport { orderContextToolResults, sessionEntryMessage } from \"./session-context-messages.js\";\nimport {\n\tappendSentAgentMessageToToolResult,\n\tparsePersistedIpythonSentAgentMessage,\n} from \"./session-context-updates.js\";\nimport { hydrateCapturedHistoryEntry, type SessionHistoryReadView } from \"./session-history-index.js\";\nimport type { SessionEntry } from \"./session-manager.js\";\nimport { type CompiledTaskFrame, compileTaskFrame, type TaskFrameLimits, taskFrameLimits } from \"./task-frame.js\";\nimport { TaskStateReadCache } from \"./task-state-reader.js\";\nimport { cloneUsage } from \"./usage.js\";\nimport { bindMessageReplayUnits, closeViewSelection, type ViewUnit, type ViewUnitLimits } from \"./view-units.js\";\n\nexport interface CanonicalContextLimits {\n\tmaxMessages: number;\n\t/** Canonical frame bytes, not a tokenizer or an estimate of JavaScript heap size. */\n\tmaxSourceBytes: number;\n}\n\ninterface CanonicalMessageSource {\n\treadonly sessionId: string;\n\treadonly sessionFile: string | undefined;\n\treadonly entryId: string;\n}\n\nconst messageSources = new WeakMap<AgentMessage, CanonicalMessageSource>();\nexport interface CanonicalViewSelectionSource {\n\treadonly source: SourceSnapshotRef;\n\treadonly units: readonly ViewUnit[];\n\treadonly limits: ViewUnitLimits;\n\treadonly pendingPublicMessageGroups?: readonly (readonly number[])[];\n\t/** A new base or retained epoch must be ACKed before native transport, even without a token budget. */\n\treadonly requiresEpoch?: true;\n}\n\nconst compiledViewUnits = new WeakMap<\n\treadonly AgentMessage[],\n\t{\n\t\tunits: readonly ViewUnit[];\n\t\tselection: CanonicalViewSelectionSource;\n\t}\n>();\n\n/** Detached rendering metadata only; reading it never changes a compiler or epoch. */\nexport function getCanonicalViewUnits(messages: readonly AgentMessage[]): readonly ViewUnit[] | undefined {\n\tconst units = compiledViewUnits.get(messages)?.units;\n\treturn units ? structuredClone(units) : undefined;\n}\n\n/** Intrinsic dependencies for an explicitly supported native epoch boundary, never the default view policy. */\nexport function getCanonicalViewSelectionSource(\n\tmessages: readonly AgentMessage[],\n): CanonicalViewSelectionSource | undefined {\n\tconst selection = compiledViewUnits.get(messages)?.selection;\n\treturn selection ? structuredClone(selection) : undefined;\n}\n\n/** Correlate a detached compiled message with its captured source, without retaining its body. */\nexport function getCanonicalMessageSource(message: AgentMessage): CanonicalMessageSource | undefined {\n\tconst source = messageSources.get(message);\n\treturn source ? { ...source } : undefined;\n}\n\ninterface CompiledEpochContext {\n\t/** A captured observation or summary input never authorizes a MAIN epoch. */\n\treadonly readOnly?: true;\n\treadonly mode: ContextMode;\n\treadonly source: SourceSnapshotRef;\n\treadonly checkpoint?: ContextEpochCheckpoint;\n\treadonly checkpointEntry?: ContextEpochEntryRef;\n\treadonly selectedSkills?: readonly SelectedSkillReference[];\n\treadonly taskFrame?: CompiledTaskFrame;\n\treadonly taskFrameRebased?: true;\n\treadonly resourceRevision?: string;\n\treadonly references: readonly (EpochViewReference | null)[];\n\t/** Uncommitted public candidate plan; never a fabricated accepted checkpoint. */\n\treadonly continuation?: ContextEpochCheckpoint[\"continuation\"];\n\treadonly toolContinuations?: readonly ToolContinuationGroup[];\n}\nconst compiledEpochContexts = new WeakMap<readonly AgentMessage[], CompiledEpochContext>();\n\nexport function getCanonicalEpochContext(messages: readonly AgentMessage[]): CompiledEpochContext | undefined {\n\tconst context = compiledEpochContexts.get(messages);\n\treturn context ? structuredClone(context) : undefined;\n}\n\n/** Detach the request view while keeping its existing captured rendering metadata. */\nexport function captureCanonicalRequestMessages(messages: readonly AgentMessage[]): AgentMessage[] {\n\tconst views = compiledViewUnits.get(messages);\n\tconst epoch = compiledEpochContexts.get(messages);\n\tif (!views || !epoch || views.units.length !== messages.length || epoch.references.length !== messages.length)\n\t\tthrow new Error(\"Request view boundary requires compiled canonical messages\");\n\tconst captured = structuredClone([...messages]);\n\tcompiledViewUnits.set(captured, structuredClone(views));\n\tcompiledEpochContexts.set(captured, structuredClone(epoch));\n\tfor (const [index, message] of messages.entries()) {\n\t\tconst source = messageSources.get(message);\n\t\tif (source) messageSources.set(captured[index], { ...source });\n\t}\n\treturn captured;\n}\n\n/** Called only for the actual current adapter's mandatory whole-group public candidate. */\nexport function prepareToolContinuationWindow(messages: readonly AgentMessage[]): {\n\tmessages: AgentMessage[];\n\treplacements: readonly { messageIndex: number; text: string }[];\n} {\n\tif (compiledEpochContexts.get(messages)?.readOnly)\n\t\tthrow new Error(\"Read-only context cannot authorize a provider epoch\");\n\treturn renderToolContinuationWindow(messages);\n}\n\n/** Source-backed public facts shared by observations, summaries, and measured request candidates. */\nfunction renderToolContinuationWindow(messages: readonly AgentMessage[]): {\n\tmessages: AgentMessage[];\n\treplacements: readonly { messageIndex: number; text: string }[];\n} {\n\tconst captured = captureCanonicalRequestMessages(messages);\n\tconst views = compiledViewUnits.get(captured)!;\n\tconst epoch = compiledEpochContexts.get(captured)!;\n\tconst groups = views.selection.pendingPublicMessageGroups;\n\tif (!groups?.length || groups.length !== epoch.toolContinuations?.length)\n\t\tthrow new Error(\"Tool continuation requires its captured native source plan\");\n\tconst maxBytes = views.selection.limits.maxMetadataBytes;\n\tconst references = [...epoch.references];\n\tconst replacements: { messageIndex: number; text: string }[] = [];\n\tconst markers = new Set(groups.map((group) => `public-tool-continuation:${views.units[group[0]].id}`));\n\tconst renderedGroups = new Map<number, ToolContinuationGroup>();\n\tfor (const [groupIndex, members] of groups.entries()) {\n\t\tconst group = epoch.toolContinuations![groupIndex];\n\t\tif (references[members[0]]?.ref.entryId !== group.assistantEntryId)\n\t\t\tthrow new Error(\"Tool continuation original group changed\");\n\t\tfor (const index of members) {\n\t\t\tconst reference = references[index];\n\t\t\tif (!reference) throw new Error(\"Tool continuation source is unavailable\");\n\t\t\tconst original = captured[index];\n\t\t\tconst rendered = renderToolContinuation(original, reference.ref.entryId, epoch.source, group, maxBytes);\n\t\t\tconst source = messageSources.get(original);\n\t\t\tif (source) messageSources.set(rendered, source);\n\t\t\tcaptured[index] = rendered;\n\t\t\treferences[index] = { ...reference, rendering: PUBLIC_TOOL_CONTINUATION_RENDERER };\n\t\t\treplacements.push({ messageIndex: index, text: rendered.content });\n\t\t\trenderedGroups.set(index, group);\n\t\t}\n\t}\n\tstringifyBoundedJson(captured, maxBytes);\n\t// Reads need whole tool groups, not the unadmittable request's whole-context dependency star.\n\tconst units = epoch.readOnly\n\t\t? bindMessageReplayUnits(captured, views.selection.units, views.selection.limits, \"message-groups\", groups)\n\t\t: views.units;\n\tconst publicUnits = units.map(\n\t\t(unit, index): ViewUnit => ({\n\t\t\t...unit,\n\t\t\tsourceRevision: renderedGroups.has(index)\n\t\t\t\t? JSON.stringify([unit.sourceRevision, PUBLIC_TOOL_CONTINUATION_RENDERER, renderedGroups.get(index)])\n\t\t\t\t: unit.sourceRevision,\n\t\t\tunavailableDependencies: unit.unavailableDependencies?.filter((id) => !markers.has(id)),\n\t\t}),\n\t);\n\tcompiledViewUnits.set(captured, {\n\t\tunits: publicUnits,\n\t\tselection: { ...views.selection, units: publicUnits, pendingPublicMessageGroups: undefined },\n\t});\n\tcompiledEpochContexts.set(captured, { ...epoch, references });\n\treturn { messages: captured, replacements };\n}\n\n/** Deterministic public data only. The actual adapter must permit and accept this candidate. */\nexport function preparePublicContextWindow(\n\tmessages: readonly AgentMessage[],\n\tfirstMessageIndex = 0,\n):\n\t| {\n\t\t\tmessages: AgentMessage[];\n\t\t\treplacements: readonly { messageIndex: number; text: string }[];\n\t }\n\t| undefined {\n\tconst captured = captureCanonicalRequestMessages(messages);\n\tconst views = compiledViewUnits.get(captured)!;\n\tconst epoch = compiledEpochContexts.get(captured)!;\n\tconst maxBytes = views.selection.limits.maxMetadataBytes;\n\tconst references = [...epoch.references];\n\tconst replacements: { messageIndex: number; text: string }[] = [];\n\tfor (const [index, message] of captured.entries()) {\n\t\tif (index < firstMessageIndex || (message.role !== \"assistant\" && message.role !== \"toolResult\")) continue;\n\t\t// Public v1 has no media representation. Do not disturb an otherwise valid native request.\n\t\tif (message.content.some((part) => ![\"text\", \"toolCall\", \"thinking\"].includes(part.type))) return;\n\t\tconst reference = references[index];\n\t\tif (!reference) throw new Error(\"Public request view requires its captured source\");\n\t\tconst rendered = renderPublicHistory(message, reference.ref.entryId, maxBytes);\n\t\tif (rendered.role !== \"custom\" || typeof rendered.content !== \"string\")\n\t\t\tthrow new Error(\"Public request view has no standalone text\");\n\t\tconst source = messageSources.get(message);\n\t\tif (source) messageSources.set(rendered, source);\n\t\tcaptured[index] = rendered;\n\t\treferences[index] = { ...reference, rendering: PUBLIC_CONTEXT_RENDERER };\n\t\treplacements.push({ messageIndex: index, text: rendered.content });\n\t}\n\tif (!replacements.length) return;\n\tstringifyBoundedJson(captured, maxBytes);\n\tconst publicIndices = new Set(replacements.map((replacement) => replacement.messageIndex));\n\tconst renderedUnit = (unit: ViewUnit, index: number): ViewUnit =>\n\t\tpublicIndices.has(index)\n\t\t\t? { ...unit, sourceRevision: JSON.stringify([unit.sourceRevision, PUBLIC_CONTEXT_RENDERER]) }\n\t\t\t: unit;\n\tcompiledViewUnits.set(captured, {\n\t\tunits: views.units.map(renderedUnit),\n\t\tselection: { ...views.selection, units: views.selection.units.map(renderedUnit) },\n\t});\n\tcompiledEpochContexts.set(captured, {\n\t\t...epoch,\n\t\treferences,\n\t\tcontinuation: { kind: \"portable-checkpoint\", publicTailThrough: epoch.source },\n\t});\n\treturn { messages: captured, replacements };\n}\n\n/** Read mode only from the same qualified compaction owner used by the compiler. */\nexport async function readCanonicalContextMode(\n\tview: SessionHistoryReadView,\n\tmaxBytes: number,\n\tinitial: ContextMode,\n): Promise<ContextMode> {\n\tconst manifest = await view.contextManifest({ limit: 1 });\n\tif (manifest.selection !== \"known\") throw new Error(\"Context mode source is unavailable\");\n\tif (!manifest.summaryRef) return initial;\n\tconst metadata = await view.get(manifest.summaryRef.entryId);\n\tif (!metadata) throw new Error(\"Context mode checkpoint is unavailable\");\n\tconst hydrated = await hydrateCapturedHistoryEntry(metadata, maxBytes, view.readPayload);\n\tif (!hydrated || hydrated.entry.type !== \"compaction\") throw new Error(\"Context mode checkpoint is unavailable\");\n\tconst details = hydrated.entry.details;\n\tif (!details || typeof details !== \"object\" || !(CONTEXT_EPOCH_DETAIL in details)) return initial;\n\tif (hydrated.source.qualification !== \"native-context-epoch\" || hydrated.source.retention === \"retained-import\")\n\t\tthrow new Error(\"Context mode checkpoint is not qualified on this source\");\n\treturn contextEpochMode(readContextEpoch(details, maxBytes), initial);\n}\n\n/** Literal suffixes follow source append order, not the restored tool-call display order. */\nfunction latestLiteralReference(references: readonly (EpochViewReference | null)[]): EpochViewReference | undefined {\n\tlet latest: EpochViewReference | undefined;\n\tfor (const reference of references) {\n\t\tif (reference && reference.ref.kind !== \"compaction\" && (!latest || reference.ref.sequence > latest.ref.sequence))\n\t\t\tlatest = reference;\n\t}\n\treturn latest;\n}\n\n/** Policy changes retain the current recipe; generated overlays are not archived conversation. */\nexport function prepareContextModeEpoch(\n\tmessages: readonly AgentMessage[],\n\tmode: ContextMode,\n\tmaxBytes: number,\n\tfreshContextContract = false,\n): { checkpoint: ContextEpochCheckpoint; messages: AgentMessage[] } {\n\tconst context = compiledEpochContexts.get(messages);\n\tconst units = getCanonicalViewUnits(messages);\n\tif (!context || !units || units.length !== messages.length)\n\t\tthrow new Error(\"Context mode requires captured canonical views\");\n\tif (context.toolContinuations?.length)\n\t\tthrow new Error(\"Tool continuation cannot enter a policy-only context checkpoint\");\n\tconst chosen = messages.filter(\n\t\t(_, index) => units[index].kind !== \"task-frame\" && units[index].kind !== \"resource-view\",\n\t);\n\tconst tail = latestLiteralReference(context.references);\n\tconst views = context.references.filter(\n\t\t(reference): reference is EpochViewReference => reference !== null && reference !== tail,\n\t);\n\t// A metadata-only fresh branch uses its existing source leaf; no fake user input is appended.\n\tconst literalTailId = tail?.ref.entryId ?? context.source.leafId;\n\tif (!literalTailId) throw new Error(\"Context mode requires a canonical source boundary\");\n\treturn {\n\t\tcheckpoint: snapshotContextEpoch(\n\t\t\t{\n\t\t\t\tversion: 5,\n\t\t\t\trenderer: context.selectedSkills?.length ? CONTEXT_SKILL_EPOCH_RENDERER : CONTEXT_POLICY_EPOCH_RENDERER,\n\t\t\t\t...(context.selectedSkills?.length ? { selectedSkills: context.selectedSkills } : {}),\n\t\t\t\tmode,\n\t\t\t\tpolicyOnly: true,\n\t\t\t\trepresentation: null,\n\t\t\t\tsource: context.source,\n\t\t\t\tviews,\n\t\t\t\tliteralTailId,\n\t\t\t\trequestContract: retainedContextRequestContract(context.checkpoint),\n\t\t\t\t...(mode === \"off\" && !context.checkpoint && freshContextContract\n\t\t\t\t\t? { pendingRequestContract: true as const }\n\t\t\t\t\t: {}),\n\t\t\t\treplayContract: context.checkpoint?.replayContract,\n\t\t\t\tpublicWindow: context.checkpoint?.publicWindow,\n\t\t\t\tcontinuation: context.checkpoint?.continuation,\n\t\t\t\t// Retain the existing bounded anchor recipe for explicit re-enable; off never injects it.\n\t\t\t\ttaskFrame: context.taskFrame ?? context.checkpoint?.taskFrame,\n\t\t\t},\n\t\t\tmaxBytes,\n\t\t),\n\t\tmessages: [...chosen],\n\t};\n}\n\n/** A candidate only. The caller must ACK the canonical checkpoint before adoption or send. */\nexport function prepareCanonicalEpoch(\n\tmessages: readonly AgentMessage[],\n\tselectedUnitIds: readonly string[],\n\trepresentation: string,\n\tmaxBytes: number,\n\treplayContract: ContextReplayContract = \"complete-context\",\n\tpublicWindow = false,\n): {\n\tcheckpoint: ContextEpochCheckpoint & { readonly version: 4 | 6; readonly representation: string };\n\tmessages: AgentMessage[];\n} {\n\tconst context = compiledEpochContexts.get(messages);\n\tconst units = getCanonicalViewUnits(messages);\n\tif (!context || !units || units.length !== messages.length || context.references.length !== messages.length)\n\t\tthrow new Error(\"Context epoch requires its captured compiler output\");\n\tif (context.readOnly) throw new Error(\"Read-only context cannot authorize a provider epoch\");\n\tif (compiledViewUnits.get(messages)?.selection.pendingPublicMessageGroups?.length)\n\t\tthrow new Error(\"Tool continuation requires its accepted public representation\");\n\tif (context.toolContinuations?.length && (!publicWindow || replayContract !== \"message-groups\"))\n\t\tthrow new Error(\"Tool continuation epoch requires its actual public replay contract\");\n\tconst selected = new Set(selectedUnitIds);\n\tif (selected.size !== selectedUnitIds.length || [...selected].some((id) => !units.some((unit) => unit.id === id)))\n\t\tthrow new Error(\"Context epoch selection has an unknown or repeated unit\");\n\tconst chosen: AgentMessage[] = [];\n\tconst views: EpochViewReference[] = [];\n\tfor (const [index, unit] of units.entries()) {\n\t\tif (!selected.has(unit.id)) {\n\t\t\tif (unit.kind === \"task-frame\") throw new Error(\"Context epoch cannot omit its task frame\");\n\t\t\tif (unit.kind === \"resource-view\") throw new Error(\"Context epoch cannot omit its current resource view\");\n\t\t\tif (unit.id === \"native-selected-skill-versions\")\n\t\t\t\tthrow new Error(\"Context epoch cannot omit its selected skill references\");\n\t\t\tcontinue;\n\t\t}\n\t\tchosen.push(messages[index]);\n\t\tconst reference = context.references[index];\n\t\tif (reference) views.push(reference);\n\t}\n\tconst tail = latestLiteralReference(context.references);\n\tif (!tail) throw new Error(\"Context epoch literal tail is unavailable\");\n\tconst tailIndex = views.indexOf(tail);\n\tif (tailIndex < 0) throw new Error(\"Context epoch cannot omit the current literal tail\");\n\tviews.splice(tailIndex, 1);\n\treturn {\n\t\tcheckpoint: snapshotContextEpoch(\n\t\t\t{\n\t\t\t\tversion: context.toolContinuations?.length ? 6 : 4,\n\t\t\t\trenderer: context.selectedSkills?.length\n\t\t\t\t\t? CONTEXT_SKILL_EPOCH_RENDERER\n\t\t\t\t\t: context.toolContinuations?.length\n\t\t\t\t\t\t? CONTEXT_TOOL_EPOCH_RENDERER\n\t\t\t\t\t\t: CONTEXT_EPOCH_RENDERER,\n\t\t\t\t...(context.selectedSkills?.length ? { selectedSkills: context.selectedSkills } : {}),\n\t\t\t\t...(context.toolContinuations?.length ? { toolContinuations: context.toolContinuations } : {}),\n\t\t\t\tsource: context.source,\n\t\t\t\trepresentation,\n\t\t\t\treplayContract,\n\t\t\t\t...(publicWindow ? { publicWindow: true as const } : {}),\n\t\t\t\t...((context.continuation ?? context.checkpoint?.continuation)\n\t\t\t\t\t? { continuation: context.continuation ?? context.checkpoint?.continuation }\n\t\t\t\t\t: {}),\n\t\t\t\tviews,\n\t\t\t\ttaskFrame: context.taskFrame,\n\t\t\t\tresourceRevision: context.resourceRevision,\n\t\t\t\tliteralTailId: tail.ref.entryId,\n\t\t\t},\n\t\t\tmaxBytes,\n\t\t),\n\t\tmessages: chosen,\n\t};\n}\n\n/** Use only a replay contract granted to these recovery results by an actual accepted request. */\nexport function canonicalRecoveryBoundary(messages: readonly AgentMessage[]): string | undefined {\n\tconst context = compiledEpochContexts.get(messages);\n\tconst units = getCanonicalViewUnits(messages);\n\tif (!context || !units) throw new Error(\"Recovery compaction requires captured canonical views\");\n\tif (context.toolContinuations?.length && !context.readOnly)\n\t\tthrow new Error(\"Tool continuation summary requires its captured public read view\");\n\tconst recoveries = units.flatMap((unit, index) => (unit.kind === \"recovery\" ? [context.references[index]] : []));\n\tif (!recoveries.length) return;\n\tconst checkpoint = context.checkpoint;\n\tif (\n\t\t!checkpoint?.representation ||\n\t\tcheckpoint.replayContract !== \"message-groups\" ||\n\t\trecoveries.some((reference) => !reference || reference.ref.sequence > checkpoint.source.sourceSequence)\n\t)\n\t\tthrow new Error(\"Recovery compaction requires an accepted replay contract for its selected results\");\n\treturn checkpoint.literalTailId;\n}\n\n/** Retain exact recovery evidence. An accepted public-window transition replaces whole old protocol groups. */\nexport function prepareRecoveryCompaction(\n\tmessages: readonly AgentMessage[],\n\tfirstKeptEntryId: string,\n\tmaxBytes: number,\n): ContextEpochCheckpoint | undefined {\n\tconst boundary = canonicalRecoveryBoundary(messages);\n\tconst context = compiledEpochContexts.get(messages);\n\tconst publicWindow =\n\t\tcontext?.checkpoint?.publicWindow === true && context.checkpoint.replayContract === \"message-groups\";\n\tif (!boundary && !publicWindow && !context?.selectedSkills?.length && !context?.toolContinuations?.length) return;\n\tif (!context) throw new Error(\"Recovery compaction requires captured canonical views\");\n\tconst selection = getCanonicalViewSelectionSource(messages)!;\n\tconst cut = context.references.findIndex((reference) => reference?.ref.entryId === firstKeptEntryId);\n\tconst lastProved = boundary\n\t\t? context.references.findIndex((reference) => reference?.ref.entryId === boundary)\n\t\t: messages.length - 1;\n\tif (cut < 0 || lastProved < 0 || cut > lastProved)\n\t\tthrow new Error(\"Recovery compaction must retain its unmeasured literal tail\");\n\tconst units = bindMessageReplayUnits(messages, selection.units, selection.limits, \"message-groups\");\n\t// A mode transition cannot strand any outstanding native call, including one in the retained tail.\n\tcloseViewSelection(\n\t\tunits,\n\t\tunits.map((unit) => unit.id),\n\t\tselection.limits,\n\t);\n\tconst toolGroups = new Set(context.toolContinuations?.map((group) => group.assistantEntryId));\n\tconst roots = units\n\t\t.filter((unit, index) => unit.kind === \"recovery\" || toolGroups.has(context.references[index]?.ref.entryId ?? \"\"))\n\t\t.map((unit) => unit.id);\n\tconst closed = new Set(closeViewSelection(units, roots, selection.limits).map((unit) => unit.id));\n\tlet renderedBytes = 0;\n\tconst views = context.references.flatMap((reference, index): EpochViewReference[] => {\n\t\tif (!reference || (index < cut && !closed.has(units[index].id))) return [];\n\t\tconst message = messages[index];\n\t\tconst rendered = publicWindow ? renderPublicHistory(message, reference.ref.entryId, maxBytes) : message;\n\t\tif (publicWindow) {\n\t\t\trenderedBytes += Buffer.byteLength(JSON.stringify(rendered), \"utf8\");\n\t\t\tif (renderedBytes > maxBytes) throw new Error(\"Public summary view byte budget exceeded\");\n\t\t}\n\t\treturn index < cut\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\t...reference,\n\t\t\t\t\t\t...(rendered !== message ? { rendering: PUBLIC_CONTEXT_RENDERER } : {}),\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: [];\n\t});\n\tif (!views.length && !publicWindow && !context.selectedSkills?.length && !toolGroups.size) return;\n\treturn snapshotContextEpoch(\n\t\t{\n\t\t\t...(toolGroups.size ? { version: 8 as const, mode: context.mode } : { version: 4 as const }),\n\t\t\trenderer: toolGroups.size\n\t\t\t\t? CONTEXT_TOOL_SUMMARY_RENDERER\n\t\t\t\t: context.selectedSkills?.length\n\t\t\t\t\t? CONTEXT_SKILL_EPOCH_RENDERER\n\t\t\t\t\t: CONTEXT_EPOCH_RENDERER,\n\t\t\t...(toolGroups.size ? { toolContinuations: context.toolContinuations } : {}),\n\t\t\t...(context.selectedSkills?.length ? { selectedSkills: context.selectedSkills } : {}),\n\t\t\tsource: context.source,\n\t\t\trepresentation: null,\n\t\t\tincludeSummary: true,\n\t\t\t...(toolGroups.size && publicWindow ? { publicWindow: true as const } : {}),\n\t\t\treplayContract:\n\t\t\t\tboundary || publicWindow ? \"message-groups\" : (context.checkpoint?.replayContract ?? \"complete-context\"),\n\t\t\t...(publicWindow\n\t\t\t\t? {\n\t\t\t\t\t\tcontinuation: {\n\t\t\t\t\t\t\tkind: \"harness-summary\" as const,\n\t\t\t\t\t\t\tpublicTailThrough: context.source,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\tviews,\n\t\t\tresourceRevision: context.resourceRevision,\n\t\t\tliteralTailId: firstKeptEntryId,\n\t\t},\n\t\tmaxBytes,\n\t);\n}\n\ninterface CachedEntry {\n\trevision: string;\n\tentry: SessionEntry;\n}\n\ntype KnownManifest = Extract<ContextManifestPage, { selection: \"known\" }>;\n\n/** Exact active-context reconstruction. It never silently chooses a last-N transcript. */\nexport class CanonicalContextCompiler {\n\tprivate source?: SourceSnapshotRef;\n\tprivate entries = new Map<string, CachedEntry>();\n\tprivate sourceBytes = 0;\n\tprivate messageCount = 0;\n\tprivate taskFrame?: CompiledTaskFrame;\n\tprivate taskBoundary?: string;\n\tprivate readonly taskState = new TaskStateReadCache();\n\tprivate generation = 0;\n\tprivate forceTaskFrameRebase = false;\n\n\trequestTaskFrameRebase(): void {\n\t\tthis.forceTaskFrameRebase = true;\n\t}\n\n\tclear(): void {\n\t\tthis.generation++;\n\t\tthis.taskState.clear();\n\t\tthis.forceTaskFrameRebase = false;\n\t\tthis.entries.clear();\n\t\tthis.source = undefined;\n\t\tthis.sourceBytes = 0;\n\t\tthis.messageCount = 0;\n\t\tthis.taskFrame = undefined;\n\t\tthis.taskBoundary = undefined;\n\t}\n\n\t/** Membership in the last successful active-source cache, including explicitly omitted responses. */\n\thasActiveEntry(entryId: string): boolean {\n\t\treturn this.entries.has(entryId);\n\t}\n\n\tasync compile(\n\t\tview: SessionHistoryReadView,\n\t\tlimits: CanonicalContextLimits,\n\t\tomittedAssistantIds: ReadonlySet<string> = new Set(),\n\t\tframeOptions: Partial<TaskFrameLimits> = {},\n\t\tresourceCapture?: OwnedResourceCapture,\n\t\tinitialContextMode: ContextMode = \"on\",\n\t\tallowPendingToolPublic = false,\n\t\tpurpose: \"request\" | \"read\" = \"request\",\n\t): Promise<AgentMessage[]> {\n\t\tconst generation = this.generation;\n\t\tconst frameLimits = taskFrameLimits(frameOptions);\n\t\tconst previousSource = this.source;\n\t\tconst previousFrame = this.taskFrame;\n\t\tconst previousBoundary = this.taskBoundary;\n\t\tconst omitted = new Set(omittedAssistantIds);\n\t\tconst { maxMessages, maxSourceBytes } = limits;\n\t\tif (\n\t\t\t!Number.isSafeInteger(maxMessages) ||\n\t\t\tmaxMessages <= 0 ||\n\t\t\t!Number.isSafeInteger(maxSourceBytes) ||\n\t\t\tmaxSourceBytes <= 0\n\t\t)\n\t\t\tthrow new Error(\"Invalid canonical context limits\");\n\t\tif (\n\t\t\tthis.source?.sessionId !== view.source.sessionId ||\n\t\t\tthis.source?.sessionFile !== view.source.sessionFile ||\n\t\t\tthis.messageCount > maxMessages ||\n\t\t\tthis.sourceBytes > maxSourceBytes\n\t\t) {\n\t\t\tthis.entries.clear();\n\t\t\tthis.sourceBytes = 0;\n\t\t\tthis.messageCount = 0;\n\t\t}\n\t\tlet first: KnownManifest | undefined;\n\t\tlet cursor: ContextManifestCursor | undefined;\n\t\tlet expected = 0;\n\t\tlet sourceBytes = 0;\n\t\tconst refs: ContextRef[] = [];\n\t\tconst sourceOrder = new Map<string, number>();\n\t\tconst countBytes = (ref: Pick<ContextRef, \"locator\">) => {\n\t\t\tsourceBytes += ref.locator.length;\n\t\t\tif (sourceBytes > maxSourceBytes) throw new Error(\"Canonical context source byte budget exceeded\");\n\t\t};\n\t\tfor (;;) {\n\t\t\tconst page = await view.contextManifest({ cursor, limit: 128 });\n\t\t\tif (page.selection !== \"known\") throw new Error(`Canonical context selection is ${page.selection}`);\n\t\t\tif (!first) {\n\t\t\t\tfirst = page;\n\t\t\t\tif (page.activeMessageCount + (page.summaryRef ? 1 : 0) > maxMessages)\n\t\t\t\t\tthrow new Error(\"Canonical context message budget exceeded\");\n\t\t\t\texpected = page.activeBase + 1;\n\t\t\t\tif (page.summaryRef) countBytes(page.summaryRef);\n\t\t\t} else if (\n\t\t\t\tpage.activeBase !== first.activeBase ||\n\t\t\t\tpage.activeMessageCount !== first.activeMessageCount ||\n\t\t\t\tpage.retainedMessageCount !== first.retainedMessageCount ||\n\t\t\t\tpage.summaryRef?.entryId !== first.summaryRef?.entryId ||\n\t\t\t\tpage.summaryRef?.revision !== first.summaryRef?.revision\n\t\t\t) {\n\t\t\t\tthrow new Error(\"Canonical context manifest changed during its captured read\");\n\t\t\t}\n\t\t\tfor (const ref of page.refs) {\n\t\t\t\tif (ref.ordinal !== expected++) throw new Error(\"Canonical context manifest skipped an active message\");\n\t\t\t\tcountBytes(ref);\n\t\t\t\trefs.push(ref);\n\t\t\t\tsourceOrder.set(ref.entryId, ref.sequence);\n\t\t\t}\n\t\t\tif (!page.nextCursor) break;\n\t\t\tif (!page.refs.length || page.nextCursor.nextOrdinal !== expected)\n\t\t\t\tthrow new Error(\"Canonical context manifest did not advance\");\n\t\t\tcursor = page.nextCursor;\n\t\t}\n\t\tif (refs.length !== first.activeMessageCount) throw new Error(\"Canonical context manifest is incomplete\");\n\n\t\tconst next = new Map<string, CachedEntry>();\n\t\tconst hydrate = async (\n\t\t\tref: ContextRef | ContextUpdateRef,\n\t\t\ttarget?: ContextUpdateTarget,\n\t\t\treadView: SessionHistoryReadView = view,\n\t\t): Promise<SessionEntry> => {\n\t\t\tconst cached = this.entries.get(ref.entryId);\n\t\t\tif (cached?.revision === ref.revision) {\n\t\t\t\tnext.set(ref.entryId, cached);\n\t\t\t\treturn cached.entry;\n\t\t\t}\n\t\t\tconst fragments: string[] = [];\n\t\t\tlet offset = 0;\n\t\t\tlet part = target\n\t\t\t\t? await readView.readContextUpdatePayload(ref.entryId, target)\n\t\t\t\t: await readView.readPayload(ref.entryId);\n\t\t\tfor (;;) {\n\t\t\t\tif (!part || part.byteOffset !== offset || part.byteLength <= 0)\n\t\t\t\t\tthrow new Error(\"Canonical context payload is unavailable or incomplete\");\n\t\t\t\toffset += part.byteLength;\n\t\t\t\tif (offset > ref.locator.length) throw new Error(\"Canonical context payload exceeds its source locator\");\n\t\t\t\tfragments.push(part.text);\n\t\t\t\tif (!part.nextCursor) break;\n\t\t\t\tpart = target\n\t\t\t\t\t? await readView.readContextUpdatePayload(ref.entryId, target, { cursor: part.nextCursor })\n\t\t\t\t\t: await readView.readPayload(ref.entryId, { cursor: part.nextCursor });\n\t\t\t}\n\t\t\tconst value: unknown = JSON.parse(fragments.join(\"\"));\n\t\t\tif (\n\t\t\t\t!value ||\n\t\t\t\ttypeof value !== \"object\" ||\n\t\t\t\t!(\"id\" in value) ||\n\t\t\t\tvalue.id !== ref.entryId ||\n\t\t\t\t!(\"type\" in value) ||\n\t\t\t\tvalue.type !== ref.kind\n\t\t\t)\n\t\t\t\tthrow new Error(\"Canonical context payload does not match its source reference\");\n\t\t\tconst entry = value as SessionEntry;\n\t\t\tnext.set(ref.entryId, { revision: ref.revision, entry });\n\t\t\treturn entry;\n\t\t};\n\t\tlet checkpoint: ContextEpochCheckpoint | undefined;\n\t\tlet summaryEntry: SessionEntry | undefined;\n\t\tif (first.summaryRef) {\n\t\t\tsummaryEntry = await hydrate(first.summaryRef);\n\t\t\tif (summaryEntry.type !== \"compaction\") throw new Error(\"Canonical context summary has the wrong source kind\");\n\t\t\tif (\n\t\t\t\tsummaryEntry.details &&\n\t\t\t\ttypeof summaryEntry.details === \"object\" &&\n\t\t\t\tCONTEXT_EPOCH_DETAIL in summaryEntry.details\n\t\t\t) {\n\t\t\t\tconst source = await view.get(first.summaryRef.entryId);\n\t\t\t\tif (source?.qualification !== \"native-context-epoch\" || source.retention === \"retained-import\")\n\t\t\t\t\tthrow new Error(\"Context epoch checkpoint is not qualified on this source\");\n\t\t\t\tcheckpoint = readContextEpoch(summaryEntry.details, maxSourceBytes);\n\t\t\t\tif (\n\t\t\t\t\t!checkpoint ||\n\t\t\t\t\tcheckpoint.literalTailId !== summaryEntry.firstKeptEntryId ||\n\t\t\t\t\tcheckpoint.views.length + first.activeMessageCount > maxMessages\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Context epoch checkpoint does not match its retained boundary\");\n\t\t\t}\n\t\t}\n\t\tconst mode = contextEpochMode(checkpoint, initialContextMode);\n\t\tconst selectedSkills = new Map((checkpoint?.selectedSkills ?? []).map((skill) => [skill.name, skill]));\n\t\tfor (const skill of selectedSkills.values()) {\n\t\t\tif (!view.atSnapshot) throw new Error(\"Selected skill epoch requires its original prefix\");\n\t\t\tconst prefix = await view.atSnapshot(skill.view.source);\n\t\t\tconst actual = await prefix.get(skill.view.ref.entryId);\n\t\t\tif (\n\t\t\t\t!actual ||\n\t\t\t\tactual.kind !== skill.view.ref.kind ||\n\t\t\t\t![\"custom_message\", \"custom\"].includes(actual.kind) ||\n\t\t\t\tactual.qualification !== \"native-recovery\" ||\n\t\t\t\tactual.revision !== skill.view.ref.revision ||\n\t\t\t\tactual.sequence !== skill.view.ref.sequence ||\n\t\t\t\tJSON.stringify(actual.locator) !== JSON.stringify(skill.view.ref.locator) ||\n\t\t\t\tskill.view.sourceRevision !== JSON.stringify([actual.revision])\n\t\t\t)\n\t\t\t\tthrow new Error(\"Selected skill epoch source is unavailable\");\n\t\t}\n\t\tconst toolSourceIds = new Set(\n\t\t\tcheckpoint?.toolContinuations?.flatMap((group) => [\n\t\t\t\tgroup.assistantEntryId,\n\t\t\t\t...group.calls.flatMap((call) => (call.result ? [call.result.id] : [])),\n\t\t\t]),\n\t\t);\n\t\tconst publicTail = checkpoint?.continuation?.publicTailThrough;\n\t\tif (publicTail) {\n\t\t\tif (!view.atSnapshot) throw new Error(\"Public summary transition requires its captured source\");\n\t\t\tawait view.atSnapshot(publicTail);\n\t\t}\n\t\tlet publicBytes = 0;\n\t\tconst boundary = JSON.stringify([first.summaryRef?.entryId ?? null, first.summaryRef?.revision ?? null]);\n\t\tlet resetFrame =\n\t\t\tpreviousSource?.sessionId !== view.source.sessionId ||\n\t\t\tpreviousSource?.sessionFile !== view.source.sessionFile ||\n\t\t\tpreviousBoundary !== boundary ||\n\t\t\t(previousSource !== undefined && previousSource.sourceSequence > view.source.sourceSequence);\n\t\tif (!resetFrame && previousFrame && previousSource?.leafId && previousSource.leafId !== view.source.leafId)\n\t\t\tresetFrame = !(await view.get(previousSource.leafId));\n\t\tconst tasks =\n\t\t\tmode === \"off\"\n\t\t\t\t? undefined\n\t\t\t\t: await this.taskState.read(view, {\n\t\t\t\t\t\tmaxItems: maxMessages,\n\t\t\t\t\t\tmaxSourceBytes,\n\t\t\t\t\t\tmaxViewBytes: maxSourceBytes,\n\t\t\t\t\t});\n\t\tlet taskSequence = -1;\n\t\tfor (const { event } of tasks?.items ?? []) {\n\t\t\tif (event.source.sequence === taskSequence) continue;\n\t\t\ttaskSequence = event.source.sequence;\n\t\t\t// The task reader has already required an exact locator for every represented frame.\n\t\t\tcountBytes({ locator: event.source.locator! });\n\t\t}\n\t\tconst referenceFrame = resetFrame ? checkpoint?.taskFrame : previousFrame;\n\t\tif (resetFrame || (referenceFrame && referenceFrame.messages.length <= 1)) this.forceTaskFrameRebase = false;\n\t\tconst forceRebase = purpose === \"request\" && this.forceTaskFrameRebase;\n\t\tlet taskFrame = tasks\n\t\t\t? compileTaskFrame(tasks, frameLimits, forceRebase ? undefined : referenceFrame)\n\t\t\t: undefined;\n\t\tconst taskFrameRebased = Boolean(\n\t\t\tmode === \"on\" &&\n\t\t\t\treferenceFrame &&\n\t\t\t\ttaskFrame !== referenceFrame &&\n\t\t\t\t(!taskFrame || taskFrame.messages.length === 1),\n\t\t);\n\t\tconst resource =\n\t\t\tmode === \"on\" && resourceCapture && (resourceCapture.enabled || checkpoint)\n\t\t\t\t? renderResourceView(resourceCapture)\n\t\t\t\t: undefined;\n\t\tif (resource) {\n\t\t\tsourceBytes += resource.bytes;\n\t\t\tif (sourceBytes > maxSourceBytes) throw new Error(\"Canonical context source byte budget exceeded\");\n\t\t}\n\t\tconst messageCount =\n\t\t\tfirst.activeMessageCount +\n\t\t\t(checkpoint ? checkpoint.views.length + (checkpoint.includeSummary ? 1 : 0) : first.summaryRef ? 1 : 0) +\n\t\t\t(taskFrame?.messages.length ?? 0) +\n\t\t\t(resource ? 1 : 0);\n\t\tif (messageCount > maxMessages) throw new Error(\"Canonical context message budget exceeded\");\n\n\t\tconst messages: AgentMessage[] = [];\n\t\tconst renderedMessages = new Map<AgentMessage, AgentMessage>();\n\t\tconst literalSources = new Map<AgentMessage, string>();\n\t\tconst unitSources = new Map<AgentMessage, ViewUnit>();\n\t\tconst epochReferences = new Map<AgentMessage, EpochViewReference>();\n\t\tconst sourceUnit = (ref: ContextRef, kind: ViewUnit[\"kind\"]): ViewUnit => ({\n\t\t\tid: JSON.stringify([view.source.sessionId, view.source.sessionFile, ref.entryId]),\n\t\t\tsourceRevision: ref.revision,\n\t\t\tkind,\n\t\t\texactSources: [ref.entryId],\n\t\t\trequiredVisibleDependencies: [],\n\t\t\tauthority:\n\t\t\t\tkind === \"recovery\"\n\t\t\t\t\t? \"tool-data\"\n\t\t\t\t\t: ref.authority === \"user\"\n\t\t\t\t\t\t? \"user\"\n\t\t\t\t\t\t: ref.authority === \"assistant\"\n\t\t\t\t\t\t\t? \"assistant-public\"\n\t\t\t\t\t\t\t: ref.authority === \"runtime\"\n\t\t\t\t\t\t\t\t? \"tool-data\"\n\t\t\t\t\t\t\t\t: \"unrecorded\",\n\t\t\ttokenEstimate: null,\n\t\t\timmutableWithinEpoch: true,\n\t\t});\n\t\tconst addSummary = async (ref: ContextRef, readView: SessionHistoryReadView, retainedMessageCount: number) => {\n\t\t\tconst summary = await hydrate(ref, undefined, readView);\n\t\t\tif (summary.type !== \"compaction\") throw new Error(\"Canonical context summary has the wrong source kind\");\n\t\t\tconst message = createCompactionSummaryMessage(\n\t\t\t\tsummary.summary,\n\t\t\t\tsummary.tokensBefore,\n\t\t\t\tsummary.timestamp,\n\t\t\t\tsummary.customInstructions,\n\t\t\t\tretainedMessageCount,\n\t\t\t);\n\t\t\tmessages.push(message);\n\t\t\tliteralSources.set(message, ref.entryId);\n\t\t\tunitSources.set(message, sourceUnit(ref, \"fixed-view\"));\n\t\t\tepochReferences.set(message, {\n\t\t\t\tsource: readView.source,\n\t\t\t\tref,\n\t\t\t\tsourceRevision: ref.revision,\n\t\t\t\tretainedMessageCount,\n\t\t\t});\n\t\t\tsourceOrder.set(ref.entryId, -1);\n\t\t};\n\t\tif (first.summaryRef && (!checkpoint || checkpoint.includeSummary))\n\t\t\tawait addSummary(first.summaryRef, view, first.retainedMessageCount);\n\t\tconst addLiteral = async (ref: ContextRef, readView: SessionHistoryReadView, pinned?: EpochViewReference) => {\n\t\t\tconst entry = await hydrate(ref, undefined, readView);\n\t\t\t// Internal capture records never interrupt a native assistant/tool-result group.\n\t\t\t// Retained records remain recoverable data, but cannot mint a new selection.\n\t\t\tconst skill = ref.qualification === \"native-recovery\" ? selectedSkillCapture(entry) : undefined;\n\t\t\tif (skill) {\n\t\t\t\tif (\n\t\t\t\t\tskill.producer === \"model\" &&\n\t\t\t\t\tisNativeSkillSelection(ref) &&\n\t\t\t\t\t(!checkpoint || ref.sequence > checkpoint.source.sourceSequence)\n\t\t\t\t) {\n\t\t\t\t\tselectedSkills.set(skill.descriptor.name, {\n\t\t\t\t\t\tname: skill.descriptor.name,\n\t\t\t\t\t\tview: {\n\t\t\t\t\t\t\tsource: view.source,\n\t\t\t\t\t\t\tref: { ...ref, kind: \"custom_message\" },\n\t\t\t\t\t\t\tsourceRevision: JSON.stringify([ref.revision]),\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst origin = entry.type === \"message\" || entry.type === \"custom_message\" ? entry.nativeOrigin : undefined;\n\t\t\tif (\n\t\t\t\tref.qualification === \"native-admission\" &&\n\t\t\t\tref.retention !== \"retained-import\" &&\n\t\t\t\torigin?.kind === \"input\" &&\n\t\t\t\torigin.recordRole === \"primary\" &&\n\t\t\t\torigin.selectedSkillRef &&\n\t\t\t\t(!checkpoint || ref.sequence > checkpoint.source.sourceSequence) &&\n\t\t\t\t![...selectedSkills.values()].some((skill) => skill.view.ref.entryId === origin.selectedSkillRef?.entryId)\n\t\t\t) {\n\t\t\t\tif (\n\t\t\t\t\torigin.selectedSkillRef.sessionId !== view.source.sessionId ||\n\t\t\t\t\torigin.selectedSkillRef.sessionFile !== view.source.sessionFile\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Admitted skill selection belongs to another source\");\n\t\t\t\tconst actual = await view.get(origin.selectedSkillRef.entryId);\n\t\t\t\tif (\n\t\t\t\t\t!actual ||\n\t\t\t\t\t(actual.kind !== \"custom\" && actual.kind !== \"custom_message\") ||\n\t\t\t\t\tactual.qualification !== \"native-recovery\"\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Admitted input selected skill source is unavailable\");\n\t\t\t\tcountBytes(actual);\n\t\t\t\tconst captured = await hydrateCapturedHistoryEntry(actual, actual.locator.length, view.readPayload);\n\t\t\t\tconst selected = captured ? selectedSkillCapture(captured.entry) : undefined;\n\t\t\t\tif (!selected) throw new Error(\"Admitted input has no captured skill version\");\n\t\t\t\tselectedSkills.set(selected.descriptor.name, {\n\t\t\t\t\tname: selected.descriptor.name,\n\t\t\t\t\tview: {\n\t\t\t\t\t\tsource: view.source,\n\t\t\t\t\t\tsourceRevision: JSON.stringify([actual.revision]),\n\t\t\t\t\t\tref: {\n\t\t\t\t\t\t\tentryId: actual.id,\n\t\t\t\t\t\t\tsequence: actual.sequence,\n\t\t\t\t\t\t\tkind: actual.kind,\n\t\t\t\t\t\t\tlocator: actual.locator,\n\t\t\t\t\t\t\trevision: actual.revision,\n\t\t\t\t\t\t\tauthority: actual.authority,\n\t\t\t\t\t\t\tqualification: actual.qualification,\n\t\t\t\t\t\t\tretention: actual.retention,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst original = sessionEntryMessage(entry);\n\t\t\tif (!original) throw new Error(\"Canonical context reference is not a visible context entry\");\n\t\t\t// These IDs come from actual native retry controls, not inferred transcript membership or stop reasons.\n\t\t\tif (original.role === \"assistant\" && omitted.has(ref.entryId)) return;\n\t\t\t// Neither canonical updates nor replaceable transforms may mutate cached source entries.\n\t\t\tconst message = structuredClone(original);\n\t\t\tconst revisions = [ref.revision];\n\t\t\tconst exactSources = [ref.entryId];\n\t\t\tif (message.role === \"assistant\") {\n\t\t\t\tconst target: ContextUpdateTarget = { kind: \"assistant-usage\", targetId: ref.entryId };\n\t\t\t\tfor (const update of (await readView.contextUpdates(target)).refs) {\n\t\t\t\t\tcountBytes(update);\n\t\t\t\t\tconst entry = await hydrate(update, target, readView);\n\t\t\t\t\trevisions.push(update.revision);\n\t\t\t\t\texactSources.push(update.entryId);\n\t\t\t\t\tif (entry.type !== \"child_usage_attributed\") throw new Error(\"Canonical usage update kind mismatch\");\n\t\t\t\t\tmessage.usage = cloneUsage(entry.aggregateUsage);\n\t\t\t\t}\n\t\t\t} else if (message.role === \"toolResult\" && message.toolName === \"ipython\") {\n\t\t\t\tconst target: ContextUpdateTarget = { kind: \"ipython-sent-message\", toolCallId: message.toolCallId };\n\t\t\t\tfor (const update of (await readView.contextUpdates(target)).refs) {\n\t\t\t\t\tcountBytes(update); // Charge each application, even when the source record is cached.\n\t\t\t\t\tconst entry = await hydrate(update, target, readView);\n\t\t\t\t\trevisions.push(update.revision);\n\t\t\t\t\texactSources.push(update.entryId);\n\t\t\t\t\tconst sent = entry.type === \"custom\" ? parsePersistedIpythonSentAgentMessage(entry.data) : undefined;\n\t\t\t\t\tif (!sent || sent.toolCallId !== message.toolCallId)\n\t\t\t\t\t\tthrow new Error(\"Canonical sent-message update mismatch\");\n\t\t\t\t\tappendSentAgentMessageToToolResult(message, message.toolCallId, sent.message);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst publicHistory =\n\t\t\t\t!toolSourceIds.has(ref.entryId) &&\n\t\t\t\t(pinned?.rendering === PUBLIC_CONTEXT_RENDERER ||\n\t\t\t\t\t(!pinned && publicTail !== undefined && ref.sequence <= publicTail.sourceSequence));\n\t\t\tconst rendered = publicHistory ? renderPublicHistory(message, ref.entryId, maxSourceBytes) : message;\n\t\t\tif (publicHistory) {\n\t\t\t\tpublicBytes += Buffer.byteLength(JSON.stringify(rendered), \"utf8\");\n\t\t\t\tif (publicBytes > maxSourceBytes) throw new Error(\"Public summary view byte budget exceeded\");\n\t\t\t}\n\t\t\tif (message.role === \"assistant\")\n\t\t\t\tmessageSources.set(rendered, {\n\t\t\t\t\tsessionId: view.source.sessionId,\n\t\t\t\t\tsessionFile: view.source.sessionFile,\n\t\t\t\t\tentryId: ref.entryId,\n\t\t\t\t});\n\t\t\tmessages.push(message);\n\t\t\trenderedMessages.set(message, rendered);\n\t\t\tliteralSources.set(rendered, ref.entryId);\n\t\t\tunitSources.set(rendered, {\n\t\t\t\t...sourceUnit(\n\t\t\t\t\tref,\n\t\t\t\t\tmessage.role === \"toolResult\" &&\n\t\t\t\t\t\tref.qualification === \"native-recovery\" &&\n\t\t\t\t\t\tref.retention !== \"retained-import\"\n\t\t\t\t\t\t? \"recovery\"\n\t\t\t\t\t\t: message.role === \"toolResult\" ||\n\t\t\t\t\t\t\t\t(message.role === \"assistant\" && message.content.some((part) => part.type === \"toolCall\"))\n\t\t\t\t\t\t\t? \"replay-group\"\n\t\t\t\t\t\t\t: \"literal\",\n\t\t\t\t),\n\t\t\t\tsourceRevision: JSON.stringify(rendered !== message ? [...revisions, PUBLIC_CONTEXT_RENDERER] : revisions),\n\t\t\t\texactSources,\n\t\t\t});\n\t\t\tconst revision = JSON.stringify(revisions);\n\t\t\tif (pinned && pinned.sourceRevision !== revision)\n\t\t\t\tthrow new Error(\"Context epoch view no longer matches its frozen source revisions\");\n\t\t\tif (pinned && unitSources.get(rendered)!.kind !== \"recovery\")\n\t\t\t\tunitSources.set(rendered, { ...unitSources.get(rendered)!, kind: \"fixed-view\" });\n\t\t\tepochReferences.set(rendered, {\n\t\t\t\tsource: readView.source,\n\t\t\t\tref,\n\t\t\t\tsourceRevision: revision,\n\t\t\t\t...(rendered !== message ? { rendering: PUBLIC_CONTEXT_RENDERER } : {}),\n\t\t\t});\n\t\t\tsourceOrder.set(ref.entryId, ref.sequence);\n\t\t};\n\t\tif (checkpoint) {\n\t\t\tif (!view.atSnapshot) throw new Error(\"Context epoch requires a captured native prefix reader\");\n\t\t\tconst prefixViews = new Map<string, SessionHistoryReadView>();\n\t\t\tconst seen = new Set<string>();\n\t\t\tfor (const pinned of checkpoint.views) {\n\t\t\t\tif (\n\t\t\t\t\tpinned.rendering !== undefined &&\n\t\t\t\t\t((pinned.rendering === PUBLIC_TOOL_CONTINUATION_RENDERER\n\t\t\t\t\t\t? checkpoint.version !== 6 && checkpoint.version !== 8\n\t\t\t\t\t\t: pinned.rendering !== PUBLIC_CONTEXT_RENDERER ||\n\t\t\t\t\t\t\t(checkpoint.version !== 3 &&\n\t\t\t\t\t\t\t\tcheckpoint.version !== 4 &&\n\t\t\t\t\t\t\t\tcheckpoint.version !== 5 &&\n\t\t\t\t\t\t\t\tcheckpoint.version !== 6 &&\n\t\t\t\t\t\t\t\tcheckpoint.version !== 8)) ||\n\t\t\t\t\t\tpinned.ref.kind === \"compaction\")\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Unsupported context epoch view rendering\");\n\t\t\t\tif (seen.has(pinned.ref.entryId) || refs.some((ref) => ref.entryId === pinned.ref.entryId))\n\t\t\t\t\tthrow new Error(\"Context epoch view overlaps its literal tail\");\n\t\t\t\tseen.add(pinned.ref.entryId);\n\t\t\t\tcountBytes(pinned.ref);\n\t\t\t\tconst key = JSON.stringify(pinned.source);\n\t\t\t\tlet prefix = prefixViews.get(key);\n\t\t\t\tif (!prefix) {\n\t\t\t\t\tprefix = await view.atSnapshot(pinned.source);\n\t\t\t\t\tprefixViews.set(key, prefix);\n\t\t\t\t}\n\t\t\t\tconst actual = await prefix.get(pinned.ref.entryId);\n\t\t\t\tif (\n\t\t\t\t\t!actual ||\n\t\t\t\t\tactual.revision !== pinned.ref.revision ||\n\t\t\t\t\tactual.kind !== pinned.ref.kind ||\n\t\t\t\t\tactual.sequence !== pinned.ref.sequence ||\n\t\t\t\t\tJSON.stringify(actual.locator) !== JSON.stringify(pinned.ref.locator)\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Context epoch view source is unavailable\");\n\t\t\t\tif (pinned.ref.kind === \"compaction\") {\n\t\t\t\t\tif (pinned.retainedMessageCount === undefined)\n\t\t\t\t\t\tthrow new Error(\"Context epoch summary count is unavailable\");\n\t\t\t\t\tawait addSummary(pinned.ref, prefix, pinned.retainedMessageCount);\n\t\t\t\t} else await addLiteral(pinned.ref, prefix, pinned);\n\t\t\t}\n\t\t}\n\t\tfor (const ref of refs) await addLiteral(ref, view);\n\t\t// Public renderings hide tool roles; restore call order while the source roles are still available.\n\t\torderContextToolResults(messages);\n\t\tfor (const [index, message] of messages.entries()) messages[index] = renderedMessages.get(message) ?? message;\n\t\tif (taskFrame) {\n\t\t\tif (referenceFrame && taskFrame !== referenceFrame && !taskFrameRebased) {\n\t\t\t\tconst last = messages.at(-1);\n\t\t\t\tconst anchor = last\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tentryId: literalSources.get(last)!,\n\t\t\t\t\t\t\tside: last.role === \"user\" || last.role === \"custom\" ? (\"before\" as const) : (\"after\" as const),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null;\n\t\t\t\ttaskFrame = { ...taskFrame, anchors: [...taskFrame.anchors.slice(0, -1), anchor] };\n\t\t\t}\n\t\t\tconst [base, ...revisions] = structuredClone(taskFrame.messages);\n\t\t\tconst frames = [base, ...revisions];\n\t\t\tconst frameIds = frames.map((_, index) => JSON.stringify([\"task-frame\", taskFrame!.origins[index], index]));\n\t\t\tfor (const [index, frame] of frames.entries()) {\n\t\t\t\tunitSources.set(frame, {\n\t\t\t\t\tid: frameIds[index],\n\t\t\t\t\tsourceRevision: frameIds[index],\n\t\t\t\t\tkind: \"task-frame\",\n\t\t\t\t\texactSources: [JSON.stringify(taskFrame.origins[index])],\n\t\t\t\t\trequiredVisibleDependencies: index ? [frameIds[index - 1]] : [],\n\t\t\t\t\tauthority: \"tool-data\",\n\t\t\t\t\ttokenEstimate: null,\n\t\t\t\t\timmutableWithinEpoch: true,\n\t\t\t\t});\n\t\t\t}\n\t\t\tfor (const anchor of taskFrame.anchors) {\n\t\t\t\tif (!anchor || sourceOrder.has(anchor.entryId)) continue;\n\t\t\t\tconst origin = await view.get(anchor.entryId);\n\t\t\t\tif (!origin) throw new Error(\"Task frame insertion source is unavailable\");\n\t\t\t\tsourceOrder.set(anchor.entryId, origin.sequence);\n\t\t\t}\n\t\t\tconst positions = new Map(messages.map((message, index) => [literalSources.get(message)!, index]));\n\t\t\tconst slots = new Map<number, AgentMessage[]>();\n\t\t\tfor (const [index, revision] of revisions.entries()) {\n\t\t\t\tconst anchor = taskFrame.anchors[index];\n\t\t\t\tlet at = 0;\n\t\t\t\tif (anchor) {\n\t\t\t\t\tconst position = positions.get(anchor.entryId);\n\t\t\t\t\tif (position !== undefined) at = position + (anchor.side === \"after\" ? 1 : 0);\n\t\t\t\t\telse {\n\t\t\t\t\t\t// A later retry may omit that assistant. Keep its source slot, not the newest input slot.\n\t\t\t\t\t\tconst ordinal = sourceOrder.get(anchor.entryId);\n\t\t\t\t\t\tif (ordinal === undefined) throw new Error(\"Task frame insertion source is unavailable\");\n\t\t\t\t\t\tat = messages.findIndex((message) => sourceOrder.get(literalSources.get(message)!)! > ordinal);\n\t\t\t\t\t\tif (at < 0) at = messages.length;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst group = slots.get(at) ?? [];\n\t\t\t\tgroup.push(revision);\n\t\t\t\tslots.set(at, group);\n\t\t\t}\n\t\t\tconst literal = messages.splice(0);\n\t\t\tmessages.push(base);\n\t\t\tfor (let at = 0; at <= literal.length; at++) {\n\t\t\t\tmessages.push(...(slots.get(at) ?? []));\n\t\t\t\tif (at < literal.length) messages.push(literal[at]);\n\t\t\t}\n\t\t}\n\t\tif (resource) {\n\t\t\t// Current owned display is regenerated; a stored acceptance marker is never a live view.\n\t\t\tconst at = messages[0] && unitSources.get(messages[0])?.kind === \"task-frame\" ? 1 : 0;\n\t\t\tmessages.splice(at, 0, resource.message);\n\t\t\tunitSources.set(resource.message, resource.unit);\n\t\t}\n\t\tif (selectedSkills.size) {\n\t\t\tconst selections = [...selectedSkills.values()];\n\t\t\tconst content = `Selected Skill versions (canonical source references):\\n${JSON.stringify(\n\t\t\t\tselections.map((skill) => ({\n\t\t\t\t\tname: skill.name,\n\t\t\t\t\tref: skill.view.ref.entryId,\n\t\t\t\t\trevision: skill.view.ref.revision,\n\t\t\t\t\tsourceSessionId: skill.view.source.sessionId,\n\t\t\t\t})),\n\t\t\t)}`;\n\t\t\tconst message = createCustomMessage(\n\t\t\t\t\"base-context-selected-skill-versions\",\n\t\t\t\tcontent,\n\t\t\t\tfalse,\n\t\t\t\tundefined,\n\t\t\t\t\"1970-01-01T00:00:00.000Z\",\n\t\t\t);\n\t\t\tmessages.unshift(message);\n\t\t\tunitSources.set(message, {\n\t\t\t\tid: \"native-selected-skill-versions\",\n\t\t\t\tsourceRevision: JSON.stringify(selections),\n\t\t\t\tkind: \"literal\",\n\t\t\t\texactSources: selections.map((skill) => skill.view.ref.entryId),\n\t\t\t\trequiredVisibleDependencies: [],\n\t\t\t\tauthority: \"tool-data\",\n\t\t\t\ttokenEstimate: null,\n\t\t\t\timmutableWithinEpoch: true,\n\t\t\t});\n\t\t}\n\t\tconst unitLimits = {\n\t\t\tmaxUnits: maxMessages,\n\t\t\tmaxDependencies: Math.min(Number.MAX_SAFE_INTEGER, maxMessages * 4),\n\t\t\tmaxMetadataBytes: maxSourceBytes,\n\t\t};\n\t\tconst sourceUnits = messages.map((message) => {\n\t\t\tconst unit = unitSources.get(message);\n\t\t\tif (!unit) throw new Error(\"Compiled view unit has no captured source\");\n\t\t\treturn unit;\n\t\t});\n\t\tif (selectedSkills.size) {\n\t\t\tconst tailIndex = messages\n\t\t\t\t.map((message, index) => (epochReferences.has(message) ? index : -1))\n\t\t\t\t.filter((index) => index >= 0)\n\t\t\t\t.at(-1);\n\t\t\tif (tailIndex !== undefined) {\n\t\t\t\tconst tail = sourceUnits[tailIndex];\n\t\t\t\tsourceUnits[tailIndex] = {\n\t\t\t\t\t...tail,\n\t\t\t\t\trequiredVisibleDependencies: [\n\t\t\t\t\t\t...new Set([...tail.requiredVisibleDependencies, \"native-selected-skill-versions\"]),\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tconst replayUnits = bindMessageReplayUnits(messages, sourceUnits, unitLimits);\n\t\tconst frozenGroups = checkpoint?.toolContinuations ?? [];\n\t\tconst candidates = messages.flatMap((message, index) => {\n\t\t\tif (message.role !== \"assistant\") return [];\n\t\t\tconst reference = epochReferences.get(message);\n\t\t\tconst prior = frozenGroups.find((group) => group.assistantEntryId === reference?.ref.entryId);\n\t\t\tif (!prior && !replayUnits[index].unavailableDependencies?.some((id) => id.startsWith(\"tool-result:\")))\n\t\t\t\treturn [];\n\t\t\tif (!reference || reference.ref.retention === \"retained-import\")\n\t\t\t\tthrow new Error(\"Tool continuation requires its original assistant source\");\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tmessage,\n\t\t\t\t\tindex,\n\t\t\t\t\treference,\n\t\t\t\t\tprior,\n\t\t\t\t\tintents: new Map<number, Awaited<ReturnType<typeof hydrateCapturedHistoryEntry>>>(),\n\t\t\t\t},\n\t\t\t];\n\t\t});\n\t\tif (frozenGroups.length !== candidates.filter((candidate) => candidate.prior).length)\n\t\t\tthrow new Error(\"Committed tool continuation lost its original group\");\n\t\tif (purpose === \"request\" && candidates.length && (!allowPendingToolPublic || mode === \"off\"))\n\t\t\tthrow new Error(\"Tool continuation requires an enabled native public request boundary\");\n\t\tconst readToolEvidence = async (metadata: IndexedSourceEvent) => {\n\t\t\tconst cached = next.get(metadata.id);\n\t\t\tif (cached?.revision === metadata.revision) return { entry: cached.entry, source: metadata };\n\t\t\tcountBytes(metadata);\n\t\t\treturn hydrateCapturedHistoryEntry(metadata, maxSourceBytes, view.readPayload);\n\t\t};\n\t\tconst acceptIntent = async (metadata: IndexedSourceEvent) => {\n\t\t\tif (\n\t\t\t\tmetadata.kind !== \"tool_intent\" ||\n\t\t\t\tmetadata.qualification !== \"native-tool-execution\" ||\n\t\t\t\tmetadata.retention === \"retained-import\"\n\t\t\t)\n\t\t\t\treturn;\n\t\t\tconst hydrated = await readToolEvidence(metadata);\n\t\t\tconst entry = hydrated.entry;\n\t\t\tif (\n\t\t\t\tentry.type !== \"tool_intent\" ||\n\t\t\t\tentry.assistant?.sessionId !== view.source.sessionId ||\n\t\t\t\tentry.assistant.sessionFile !== view.source.sessionFile\n\t\t\t)\n\t\t\t\treturn;\n\t\t\tconst candidate = candidates.find((item) => item.reference.ref.entryId === entry.assistant?.entryId);\n\t\t\tif (!candidate) return;\n\t\t\tconst invocation = entry.invocation;\n\t\t\tconst call = candidate.message.content.filter((part) => part.type === \"toolCall\")[invocation.sourceOrder];\n\t\t\tif (\n\t\t\t\t!Number.isSafeInteger(invocation.sourceOrder) ||\n\t\t\t\t!call ||\n\t\t\t\tcall.id !== invocation.toolCallId ||\n\t\t\t\tcall.name !== invocation.toolName ||\n\t\t\t\t!invocation.executionId ||\n\t\t\t\tentry.id !== `${invocation.executionId}:intent` ||\n\t\t\t\tmetadata.sequence <= candidate.reference.ref.sequence ||\n\t\t\t\tcandidate.intents.has(invocation.sourceOrder)\n\t\t\t)\n\t\t\t\tthrow new Error(\"Tool continuation has ambiguous original intent\");\n\t\t\tcandidate.intents.set(invocation.sourceOrder, hydrated);\n\t\t};\n\t\tfor (const candidate of candidates) {\n\t\t\tif (!candidate.prior) continue;\n\t\t\tif (!Array.isArray(candidate.prior.calls)) throw new Error(\"Invalid committed tool continuation\");\n\t\t\tfor (const call of candidate.prior.calls) {\n\t\t\t\tconst actual = await view.get(call.intent.id);\n\t\t\t\tif (!actual || actual.revision !== call.intent.revision || actual.sequence !== call.intent.sequence)\n\t\t\t\t\tthrow new Error(\"Committed tool intent is unavailable on this captured branch\");\n\t\t\t\tawait acceptIntent(actual);\n\t\t\t}\n\t\t}\n\t\tconst newGroups = candidates.filter((candidate) => !candidate.prior);\n\t\tif (newGroups.length) {\n\t\t\tlet after = Math.min(...newGroups.map((candidate) => candidate.reference.ref.sequence));\n\t\t\tlet scanned = 0;\n\t\t\tfor (;;) {\n\t\t\t\tconst page = await view.page(after, Math.min(128, maxMessages - scanned + 1));\n\t\t\t\tscanned += page.events.length;\n\t\t\t\tif (scanned > maxMessages) throw new Error(\"Tool continuation source item budget exceeded\");\n\t\t\t\tif (page.coverage !== \"complete\") throw new Error(\"Tool continuation source coverage is incomplete\");\n\t\t\t\tfor (const metadata of page.events) {\n\t\t\t\t\t// Frozen intent refs were already read exactly; do not count them twice as another execution.\n\t\t\t\t\tif (\n\t\t\t\t\t\t!candidates.some((candidate) => candidate.prior?.calls.some((call) => call.intent.id === metadata.id))\n\t\t\t\t\t)\n\t\t\t\t\t\tawait acceptIntent(metadata);\n\t\t\t\t}\n\t\t\t\tif (page.nextAfter === null) break;\n\t\t\t\tif (page.nextAfter <= after) throw new Error(\"Tool continuation source page did not advance\");\n\t\t\t\tafter = page.nextAfter;\n\t\t\t}\n\t\t}\n\t\tconst toolContinuations: ToolContinuationGroup[] = [];\n\t\tconst pendingPublicMessageGroups: number[][] = [];\n\t\tfor (const candidate of candidates) {\n\t\t\tconst toolCalls = candidate.message.content.filter((part) => part.type === \"toolCall\");\n\t\t\tif (\n\t\t\t\t!toolCalls.length ||\n\t\t\t\tcandidate.intents.size !== toolCalls.length ||\n\t\t\t\t(candidate.prior && candidate.prior.calls.length !== toolCalls.length)\n\t\t\t)\n\t\t\t\tthrow new Error(\"View-unit replay group is incomplete: original tool owner is unqualified\");\n\t\t\tconst members = [candidate.index];\n\t\t\tconst calls: ToolContinuationGroup[\"calls\"][number][] = [];\n\t\t\tfor (let order = 0; order < toolCalls.length; order++) {\n\t\t\t\tconst intent = candidate.intents.get(order)!;\n\t\t\t\tif (intent.entry.type !== \"tool_intent\") throw new Error(\"Invalid native tool intent\");\n\t\t\t\tconst invocation = intent.entry.invocation;\n\t\t\t\tconst original = candidate.prior?.calls[order];\n\t\t\t\tif (\n\t\t\t\t\toriginal &&\n\t\t\t\t\t(original.executionId !== invocation.executionId || original.intent.id !== intent.source.id)\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Committed tool execution identity changed\");\n\t\t\t\tconst actual = await view.get(invocation.executionId);\n\t\t\t\tlet outcome: ToolContinuationGroup[\"calls\"][number][\"outcome\"] = \"outcome_unknown\";\n\t\t\t\tif (actual) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tactual.kind !== \"message\" ||\n\t\t\t\t\t\tactual.retention === \"retained-import\" ||\n\t\t\t\t\t\t(actual.qualification !== \"native-tool-execution\" && actual.qualification !== \"native-recovery\") ||\n\t\t\t\t\t\tactual.sequence <= intent.source.sequence\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new Error(\"Tool outcome lacks its original finalized owner\");\n\t\t\t\t\tconst { entry } = await readToolEvidence(actual);\n\t\t\t\t\tif (\n\t\t\t\t\t\tentry.type !== \"message\" ||\n\t\t\t\t\t\tentry.message.role !== \"toolResult\" ||\n\t\t\t\t\t\tentry.execution?.executionId !== invocation.executionId ||\n\t\t\t\t\t\t!(\"invocationId\" in entry.execution) ||\n\t\t\t\t\t\tentry.execution.invocationId !== intent.source.id ||\n\t\t\t\t\t\tentry.execution.sourceOrder !== order ||\n\t\t\t\t\t\tentry.execution.toolCallId !== invocation.toolCallId ||\n\t\t\t\t\t\tentry.execution.toolName !== invocation.toolName ||\n\t\t\t\t\t\tentry.message.toolCallId !== invocation.toolCallId ||\n\t\t\t\t\t\tentry.message.toolName !== invocation.toolName ||\n\t\t\t\t\t\t![\"not_started\", \"completed\", \"failed\", \"outcome_unknown\"].includes(entry.execution.executionOutcome)\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new Error(\"Tool outcome does not match its original captured intent\");\n\t\t\t\t\toutcome = entry.execution.executionOutcome;\n\t\t\t\t\tconst index = messages.findIndex((message) => {\n\t\t\t\t\t\tconst ref = epochReferences.get(message)?.ref;\n\t\t\t\t\t\treturn ref?.entryId === actual.id && ref.revision === actual.revision;\n\t\t\t\t\t});\n\t\t\t\t\tif (index <= candidate.index)\n\t\t\t\t\t\tthrow new Error(\"Finalized tool outcome is absent from its whole public group\");\n\t\t\t\t\tmembers.push(index);\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\toriginal?.result &&\n\t\t\t\t\t(!actual ||\n\t\t\t\t\t\toriginal.result.id !== actual.id ||\n\t\t\t\t\t\toriginal.result.sequence !== actual.sequence ||\n\t\t\t\t\t\toriginal.result.revision !== actual.revision)\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Committed finalized tool outcome is unavailable on this captured branch\");\n\t\t\t\tcalls.push({\n\t\t\t\t\texecutionId: invocation.executionId,\n\t\t\t\t\tintent: { id: intent.source.id, sequence: intent.source.sequence, revision: intent.source.revision },\n\t\t\t\t\toutcome,\n\t\t\t\t\t...(actual ? { result: { id: actual.id, sequence: actual.sequence, revision: actual.revision } } : {}),\n\t\t\t\t});\n\t\t\t}\n\t\t\ttoolContinuations.push({ assistantEntryId: candidate.reference.ref.entryId, calls });\n\t\t\tpendingPublicMessageGroups.push(members.sort((left, right) => left - right));\n\t\t}\n\t\tconst publicSourceIds = new Set(\n\t\t\tpendingPublicMessageGroups.flatMap((group) =>\n\t\t\t\tgroup.map((index) => epochReferences.get(messages[index])!.ref.entryId),\n\t\t\t),\n\t\t);\n\t\tif (\n\t\t\tcheckpoint?.views.some(\n\t\t\t\t(pinned) =>\n\t\t\t\t\tpinned.rendering === PUBLIC_TOOL_CONTINUATION_RENDERER && !publicSourceIds.has(pinned.ref.entryId),\n\t\t\t)\n\t\t)\n\t\t\tthrow new Error(\"Committed tool rendering has no matching whole-group recipe\");\n\t\tstringifyBoundedJson(toolContinuations, maxSourceBytes);\n\t\tconst units = pendingPublicMessageGroups.length\n\t\t\t? bindMessageReplayUnits(messages, sourceUnits, unitLimits, \"complete-context\", pendingPublicMessageGroups)\n\t\t\t: replayUnits;\n\t\tconst pendingMarkers = new Set(\n\t\t\tpendingPublicMessageGroups.map((group) => `public-tool-continuation:${units[group[0]].id}`),\n\t\t);\n\t\t// Check every ordinary dependency now. Return the original unadmittable units, not native replay permission.\n\t\tcloseViewSelection(\n\t\t\tunits.map((unit) => ({\n\t\t\t\t...unit,\n\t\t\t\tunavailableDependencies: unit.unavailableDependencies?.filter((id) => !pendingMarkers.has(id)),\n\t\t\t})),\n\t\t\tunits.map((unit) => unit.id),\n\t\t\tunitLimits,\n\t\t);\n\t\tconst closedUnits = units;\n\t\tconst messagesByUnit = new Map(units.map((unit, index) => [unit.id, messages[index]]));\n\t\tconst closedMessages = closedUnits.map((unit) => messagesByUnit.get(unit.id)!);\n\t\t// A frozen literal is immutable inside this epoch, not permanently mandatory at its next ACK boundary.\n\t\tconst selectionUnits = sourceUnits.map((unit, index): ViewUnit => {\n\t\t\tconst message = messages[index];\n\t\t\tif (unit.kind !== \"fixed-view\" || message.role !== \"assistant\") return unit;\n\t\t\treturn {\n\t\t\t\t...unit,\n\t\t\t\tkind: message.content.some((part) => part.type === \"toolCall\") ? \"replay-group\" : \"literal\",\n\t\t\t};\n\t\t});\n\t\tcompiledViewUnits.set(closedMessages, {\n\t\t\tunits: closedUnits,\n\t\t\tselection: {\n\t\t\t\tsource: { ...view.source },\n\t\t\t\tunits: selectionUnits,\n\t\t\t\tlimits: unitLimits,\n\t\t\t\t...(mode === \"on\" && (taskFrameRebased || checkpoint) ? { requiresEpoch: true as const } : {}),\n\t\t\t\t...(pendingPublicMessageGroups.length ? { pendingPublicMessageGroups } : {}),\n\t\t\t},\n\t\t});\n\t\tcompiledEpochContexts.set(closedMessages, {\n\t\t\t...(purpose === \"read\" ? { readOnly: true as const } : {}),\n\t\t\tmode,\n\t\t\tsource: { ...view.source },\n\t\t\tcheckpoint,\n\t\t\tcheckpointEntry:\n\t\t\t\tcheckpoint && first.summaryRef\n\t\t\t\t\t? { sessionId: view.source.sessionId, entryId: first.summaryRef.entryId }\n\t\t\t\t\t: undefined,\n\t\t\ttaskFrame,\n\t\t\t...(taskFrameRebased ? { taskFrameRebased: true as const } : {}),\n\t\t\tresourceRevision: resource?.revision,\n\t\t\treferences: closedMessages.map((message) => epochReferences.get(message) ?? null),\n\t\t\t...(selectedSkills.size ? { selectedSkills: [...selectedSkills.values()] } : {}),\n\t\t\t...(toolContinuations.length ? { toolContinuations } : {}),\n\t\t});\n\t\tif (generation !== this.generation) throw new Error(\"Canonical context owner changed during compilation\");\n\t\tthis.entries = next;\n\t\t// A rebased candidate is not the committed prefix. Adopt it from the next ACKed checkpoint.\n\t\tthis.taskFrame = taskFrameRebased ? referenceFrame : taskFrame;\n\t\tthis.taskBoundary = boundary;\n\t\tthis.source = view.source;\n\t\tthis.sourceBytes = sourceBytes;\n\t\tthis.messageCount = messageCount;\n\t\treturn purpose === \"read\" && pendingPublicMessageGroups.length\n\t\t\t? renderToolContinuationWindow(closedMessages).messages\n\t\t\t: closedMessages;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"canonical-context.d.ts","sourceRoot":"","sources":["../../src/core/canonical-context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AAErE,OAAO,EAQN,KAAK,sBAAsB,EAC3B,KAAK,WAAW,EAChB,KAAK,qBAAqB,EAE1B,KAAK,kBAAkB,EAIvB,KAAK,qBAAqB,EAC1B,MAAM,oBAAoB,CAAC;AAgB5B,OAAO,KAAK,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACnF,OAAO,EAAE,KAAK,oBAAoB,EAAsB,MAAM,oBAAoB,CAAC;AACnF,OAAO,EAA0B,KAAK,sBAAsB,EAAwB,MAAM,sBAAsB,CAAC;AAMjH,OAAO,EAA+B,KAAK,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAEtG,OAAO,EAAE,KAAK,iBAAiB,EAAoB,KAAK,eAAe,EAAmB,MAAM,iBAAiB,CAAC;AAGlH,OAAO,EAA8C,KAAK,QAAQ,EAAE,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAEjH,MAAM,WAAW,sBAAsB;IACtC,WAAW,EAAE,MAAM,CAAC;IACpB,qFAAqF;IACrF,cAAc,EAAE,MAAM,CAAC;CACvB;AAED,UAAU,sBAAsB;IAC/B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IACzC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CACzB;AAGD,MAAM,WAAW,4BAA4B;IAC5C,QAAQ,CAAC,MAAM,EAAE,iBAAiB,CAAC;IACnC,QAAQ,CAAC,KAAK,EAAE,SAAS,QAAQ,EAAE,CAAC;IACpC,QAAQ,CAAC,MAAM,EAAE,cAAc,CAAC;IAChC,QAAQ,CAAC,0BAA0B,CAAC,EAAE,SAAS,CAAC,SAAS,MAAM,EAAE,CAAC,EAAE,CAAC;IACrE,uGAAuG;IACvG,QAAQ,CAAC,aAAa,CAAC,EAAE,IAAI,CAAC;CAC9B;AAUD,sFAAsF;AACtF,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,SAAS,QAAQ,EAAE,GAAG,SAAS,CAGxG;AAED,+GAA+G;AAC/G,wBAAgB,+BAA+B,CAC9C,QAAQ,EAAE,SAAS,YAAY,EAAE,GAC/B,4BAA4B,GAAG,SAAS,CAG1C;AAED,kGAAkG;AAClG,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,YAAY,GAAG,sBAAsB,GAAG,SAAS,CAGnG;AAED,UAAU,oBAAoB;IAC7B,6EAA6E;IAC7E,QAAQ,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC;IACzB,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;IAC3B,QAAQ,CAAC,MAAM,EAAE,iBAAiB,CAAC;IACnC,QAAQ,CAAC,UAAU,CAAC,EAAE,sBAAsB,CAAC;IAC7C,QAAQ,CAAC,eAAe,CAAC,EAAE,oBAAoB,CAAC;IAChD,QAAQ,CAAC,cAAc,CAAC,EAAE,SAAS,sBAAsB,EAAE,CAAC;IAC5D,QAAQ,CAAC,SAAS,CAAC,EAAE,iBAAiB,CAAC;IACvC,QAAQ,CAAC,gBAAgB,CAAC,EAAE,IAAI,CAAC;IACjC,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IACnC,QAAQ,CAAC,UAAU,EAAE,SAAS,CAAC,kBAAkB,GAAG,IAAI,CAAC,EAAE,CAAC;IAC5D,iFAAiF;IACjF,QAAQ,CAAC,YAAY,CAAC,EAAE,sBAAsB,CAAC,cAAc,CAAC,CAAC;IAC/D,QAAQ,CAAC,iBAAiB,CAAC,EAAE,SAAS,qBAAqB,EAAE,CAAC;CAC9D;AAGD,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,oBAAoB,GAAG,SAAS,CAG5G;AAED,sFAAsF;AACtF,wBAAgB,+BAA+B,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,YAAY,EAAE,CAajG;AAED,2FAA2F;AAC3F,wBAAgB,6BAA6B,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG;IACjF,QAAQ,EAAE,YAAY,EAAE,CAAC;IACzB,YAAY,EAAE,SAAS;QAAE,YAAY,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;CAChE,CAIA;AAyDD,gGAAgG;AAChG,wBAAgB,0BAA0B,CACzC,QAAQ,EAAE,SAAS,YAAY,EAAE,EACjC,iBAAiB,SAAI,GAEnB;IACA,QAAQ,EAAE,YAAY,EAAE,CAAC;IACzB,YAAY,EAAE,SAAS;QAAE,YAAY,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;CAC/D,GACD,SAAS,CAuCX;AAED,oFAAoF;AACpF,wBAAsB,wBAAwB,CAC7C,IAAI,EAAE,sBAAsB,EAC5B,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,WAAW,GAClB,OAAO,CAAC,WAAW,CAAC,CAatB;AAYD,kGAAkG;AAClG,wBAAgB,uBAAuB,CACtC,QAAQ,EAAE,SAAS,YAAY,EAAE,EACjC,IAAI,EAAE,WAAW,EACjB,QAAQ,EAAE,MAAM,EAChB,oBAAoB,UAAQ,GAC1B;IAAE,UAAU,EAAE,sBAAsB,CAAC;IAAC,QAAQ,EAAE,YAAY,EAAE,CAAA;CAAE,CA2ClE;AAED,8FAA8F;AAC9F,wBAAgB,qBAAqB,CACpC,QAAQ,EAAE,SAAS,YAAY,EAAE,EACjC,eAAe,EAAE,SAAS,MAAM,EAAE,EAClC,cAAc,EAAE,MAAM,EACtB,QAAQ,EAAE,MAAM,EAChB,cAAc,GAAE,qBAA0C,EAC1D,YAAY,UAAQ,GAClB;IACF,UAAU,EAAE,sBAAsB,GAAG;QAAE,QAAQ,CAAC,OAAO,EAAE,CAAC,GAAG,CAAC,CAAC;QAAC,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAA;KAAE,CAAC;IAClG,QAAQ,EAAE,YAAY,EAAE,CAAC;CACzB,CA+DA;AAED,kGAAkG;AAClG,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,MAAM,GAAG,SAAS,CAgB/F;AAED,+GAA+G;AAC/G,wBAAgB,yBAAyB,CACxC,QAAQ,EAAE,SAAS,YAAY,EAAE,EACjC,gBAAgB,EAAE,MAAM,EACxB,QAAQ,EAAE,MAAM,GACd,sBAAsB,GAAG,SAAS,CA6EpC;AASD,0FAA0F;AAC1F,qBAAa,wBAAwB;IACpC,OAAO,CAAC,MAAM,CAAC,CAAoB;IACnC,OAAO,CAAC,OAAO,CAAkC;IACjD,OAAO,CAAC,WAAW,CAAK;IACxB,OAAO,CAAC,YAAY,CAAK;IACzB,OAAO,CAAC,SAAS,CAAC,CAAoB;IACtC,OAAO,CAAC,YAAY,CAAC,CAAS;IAC9B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA4B;IACtD,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,oBAAoB,CAAS;IAErC,sBAAsB,IAAI,IAAI,CAE7B;IAED,KAAK,IAAI,IAAI,CAUZ;IAED,qGAAqG;IACrG,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAEvC;IAEK,OAAO,CACZ,IAAI,EAAE,sBAAsB,EAC5B,MAAM,EAAE,sBAAsB,EAC9B,mBAAmB,GAAE,WAAW,CAAC,MAAM,CAAa,EACpD,YAAY,GAAE,OAAO,CAAC,eAAe,CAAM,EAC3C,eAAe,CAAC,EAAE,oBAAoB,EACtC,kBAAkB,GAAE,WAAkB,EACtC,sBAAsB,UAAQ,EAC9B,OAAO,GAAE,SAAS,GAAG,MAAkB,GACrC,OAAO,CAAC,YAAY,EAAE,CAAC,CAo4BzB;CACD","sourcesContent":["import type { AgentMessage } from \"@ponythewhite/base-context-agent\";\nimport { stringifyBoundedJson } from \"./bounded-json.js\";\nimport {\n\tCONTEXT_EPOCH_DETAIL,\n\tCONTEXT_EPOCH_RENDERER,\n\tCONTEXT_INTERRUPTED_TOOL_RENDERER,\n\tCONTEXT_POLICY_EPOCH_RENDERER,\n\tCONTEXT_SKILL_EPOCH_RENDERER,\n\tCONTEXT_TOOL_EPOCH_RENDERER,\n\tCONTEXT_TOOL_SUMMARY_RENDERER,\n\ttype ContextEpochCheckpoint,\n\ttype ContextMode,\n\ttype ContextReplayContract,\n\tcontextEpochMode,\n\ttype EpochViewReference,\n\treadContextEpoch,\n\tretainedContextRequestContract,\n\tsnapshotContextEpoch,\n\ttype ToolContinuationGroup,\n} from \"./context-epoch.js\";\nimport type {\n\tContextManifestCursor,\n\tContextManifestPage,\n\tContextRef,\n\tContextUpdateRef,\n\tContextUpdateTarget,\n\tIndexedSourceEvent,\n} from \"./history-index.js\";\nimport { createCompactionSummaryMessage, createCustomMessage } from \"./messages.js\";\nimport {\n\tPUBLIC_CONTEXT_RENDERER,\n\tPUBLIC_TOOL_CONTINUATION_RENDERER,\n\trenderPublicHistory,\n\trenderToolContinuation,\n} from \"./public-context.js\";\nimport type { ContextEpochEntryRef, SourceSnapshotRef } from \"./request-events.js\";\nimport { type OwnedResourceCapture, renderResourceView } from \"./resource-view.js\";\nimport { isNativeSkillSelection, type SelectedSkillReference, selectedSkillCapture } from \"./selected-skills.js\";\nimport { orderContextToolResults, sessionEntryMessage } from \"./session-context-messages.js\";\nimport {\n\tappendSentAgentMessageToToolResult,\n\tparsePersistedIpythonSentAgentMessage,\n} from \"./session-context-updates.js\";\nimport { hydrateCapturedHistoryEntry, type SessionHistoryReadView } from \"./session-history-index.js\";\nimport type { SessionEntry } from \"./session-manager.js\";\nimport { type CompiledTaskFrame, compileTaskFrame, type TaskFrameLimits, taskFrameLimits } from \"./task-frame.js\";\nimport { TaskStateReadCache } from \"./task-state-reader.js\";\nimport { cloneUsage } from \"./usage.js\";\nimport { bindMessageReplayUnits, closeViewSelection, type ViewUnit, type ViewUnitLimits } from \"./view-units.js\";\n\nexport interface CanonicalContextLimits {\n\tmaxMessages: number;\n\t/** Canonical frame bytes, not a tokenizer or an estimate of JavaScript heap size. */\n\tmaxSourceBytes: number;\n}\n\ninterface CanonicalMessageSource {\n\treadonly sessionId: string;\n\treadonly sessionFile: string | undefined;\n\treadonly entryId: string;\n}\n\nconst messageSources = new WeakMap<AgentMessage, CanonicalMessageSource>();\nexport interface CanonicalViewSelectionSource {\n\treadonly source: SourceSnapshotRef;\n\treadonly units: readonly ViewUnit[];\n\treadonly limits: ViewUnitLimits;\n\treadonly pendingPublicMessageGroups?: readonly (readonly number[])[];\n\t/** A new base or retained epoch must be ACKed before native transport, even without a token budget. */\n\treadonly requiresEpoch?: true;\n}\n\nconst compiledViewUnits = new WeakMap<\n\treadonly AgentMessage[],\n\t{\n\t\tunits: readonly ViewUnit[];\n\t\tselection: CanonicalViewSelectionSource;\n\t}\n>();\n\n/** Detached rendering metadata only; reading it never changes a compiler or epoch. */\nexport function getCanonicalViewUnits(messages: readonly AgentMessage[]): readonly ViewUnit[] | undefined {\n\tconst units = compiledViewUnits.get(messages)?.units;\n\treturn units ? structuredClone(units) : undefined;\n}\n\n/** Intrinsic dependencies for an explicitly supported native epoch boundary, never the default view policy. */\nexport function getCanonicalViewSelectionSource(\n\tmessages: readonly AgentMessage[],\n): CanonicalViewSelectionSource | undefined {\n\tconst selection = compiledViewUnits.get(messages)?.selection;\n\treturn selection ? structuredClone(selection) : undefined;\n}\n\n/** Correlate a detached compiled message with its captured source, without retaining its body. */\nexport function getCanonicalMessageSource(message: AgentMessage): CanonicalMessageSource | undefined {\n\tconst source = messageSources.get(message);\n\treturn source ? { ...source } : undefined;\n}\n\ninterface CompiledEpochContext {\n\t/** A captured observation or summary input never authorizes a MAIN epoch. */\n\treadonly readOnly?: true;\n\treadonly mode: ContextMode;\n\treadonly source: SourceSnapshotRef;\n\treadonly checkpoint?: ContextEpochCheckpoint;\n\treadonly checkpointEntry?: ContextEpochEntryRef;\n\treadonly selectedSkills?: readonly SelectedSkillReference[];\n\treadonly taskFrame?: CompiledTaskFrame;\n\treadonly taskFrameRebased?: true;\n\treadonly resourceRevision?: string;\n\treadonly references: readonly (EpochViewReference | null)[];\n\t/** Uncommitted public candidate plan; never a fabricated accepted checkpoint. */\n\treadonly continuation?: ContextEpochCheckpoint[\"continuation\"];\n\treadonly toolContinuations?: readonly ToolContinuationGroup[];\n}\nconst compiledEpochContexts = new WeakMap<readonly AgentMessage[], CompiledEpochContext>();\n\nexport function getCanonicalEpochContext(messages: readonly AgentMessage[]): CompiledEpochContext | undefined {\n\tconst context = compiledEpochContexts.get(messages);\n\treturn context ? structuredClone(context) : undefined;\n}\n\n/** Detach the request view while keeping its existing captured rendering metadata. */\nexport function captureCanonicalRequestMessages(messages: readonly AgentMessage[]): AgentMessage[] {\n\tconst views = compiledViewUnits.get(messages);\n\tconst epoch = compiledEpochContexts.get(messages);\n\tif (!views || !epoch || views.units.length !== messages.length || epoch.references.length !== messages.length)\n\t\tthrow new Error(\"Request view boundary requires compiled canonical messages\");\n\tconst captured = structuredClone([...messages]);\n\tcompiledViewUnits.set(captured, structuredClone(views));\n\tcompiledEpochContexts.set(captured, structuredClone(epoch));\n\tfor (const [index, message] of messages.entries()) {\n\t\tconst source = messageSources.get(message);\n\t\tif (source) messageSources.set(captured[index], { ...source });\n\t}\n\treturn captured;\n}\n\n/** Called only for the actual current adapter's mandatory whole-group public candidate. */\nexport function prepareToolContinuationWindow(messages: readonly AgentMessage[]): {\n\tmessages: AgentMessage[];\n\treplacements: readonly { messageIndex: number; text: string }[];\n} {\n\tif (compiledEpochContexts.get(messages)?.readOnly)\n\t\tthrow new Error(\"Read-only context cannot authorize a provider epoch\");\n\treturn renderToolContinuationWindow(messages);\n}\n\n/** Source-backed public facts shared by observations, summaries, and measured request candidates. */\nfunction renderToolContinuationWindow(messages: readonly AgentMessage[]): {\n\tmessages: AgentMessage[];\n\treplacements: readonly { messageIndex: number; text: string }[];\n} {\n\tconst captured = captureCanonicalRequestMessages(messages);\n\tconst views = compiledViewUnits.get(captured)!;\n\tconst epoch = compiledEpochContexts.get(captured)!;\n\tconst groups = views.selection.pendingPublicMessageGroups;\n\tif (!groups?.length || groups.length !== epoch.toolContinuations?.length)\n\t\tthrow new Error(\"Tool continuation requires its captured native source plan\");\n\tconst maxBytes = views.selection.limits.maxMetadataBytes;\n\tconst references = [...epoch.references];\n\tconst replacements: { messageIndex: number; text: string }[] = [];\n\tconst markers = new Set(groups.map((group) => `public-tool-continuation:${views.units[group[0]].id}`));\n\tconst renderedGroups = new Map<number, ToolContinuationGroup>();\n\tfor (const [groupIndex, members] of groups.entries()) {\n\t\tconst group = epoch.toolContinuations![groupIndex];\n\t\tif (references[members[0]]?.ref.entryId !== group.assistantEntryId)\n\t\t\tthrow new Error(\"Tool continuation original group changed\");\n\t\tfor (const index of members) {\n\t\t\tconst reference = references[index];\n\t\t\tif (!reference) throw new Error(\"Tool continuation source is unavailable\");\n\t\t\tconst original = captured[index];\n\t\t\tconst rendered = renderToolContinuation(original, reference.ref.entryId, epoch.source, group, maxBytes);\n\t\t\tconst source = messageSources.get(original);\n\t\t\tif (source) messageSources.set(rendered, source);\n\t\t\tcaptured[index] = rendered;\n\t\t\treferences[index] = { ...reference, rendering: PUBLIC_TOOL_CONTINUATION_RENDERER };\n\t\t\treplacements.push({ messageIndex: index, text: rendered.content });\n\t\t\trenderedGroups.set(index, group);\n\t\t}\n\t}\n\tstringifyBoundedJson(captured, maxBytes);\n\t// Reads need whole tool groups, not the unadmittable request's whole-context dependency star.\n\tconst units = epoch.readOnly\n\t\t? bindMessageReplayUnits(captured, views.selection.units, views.selection.limits, \"message-groups\", groups)\n\t\t: views.units;\n\tconst publicUnits = units.map(\n\t\t(unit, index): ViewUnit => ({\n\t\t\t...unit,\n\t\t\tsourceRevision: renderedGroups.has(index)\n\t\t\t\t? JSON.stringify([unit.sourceRevision, PUBLIC_TOOL_CONTINUATION_RENDERER, renderedGroups.get(index)])\n\t\t\t\t: unit.sourceRevision,\n\t\t\tunavailableDependencies: unit.unavailableDependencies?.filter((id) => !markers.has(id)),\n\t\t}),\n\t);\n\tcompiledViewUnits.set(captured, {\n\t\tunits: publicUnits,\n\t\tselection: { ...views.selection, units: publicUnits, pendingPublicMessageGroups: undefined },\n\t});\n\tcompiledEpochContexts.set(captured, { ...epoch, references });\n\treturn { messages: captured, replacements };\n}\n\n/** Deterministic public data only. The actual adapter must permit and accept this candidate. */\nexport function preparePublicContextWindow(\n\tmessages: readonly AgentMessage[],\n\tfirstMessageIndex = 0,\n):\n\t| {\n\t\t\tmessages: AgentMessage[];\n\t\t\treplacements: readonly { messageIndex: number; text: string }[];\n\t }\n\t| undefined {\n\tconst captured = captureCanonicalRequestMessages(messages);\n\tconst views = compiledViewUnits.get(captured)!;\n\tconst epoch = compiledEpochContexts.get(captured)!;\n\tconst maxBytes = views.selection.limits.maxMetadataBytes;\n\tconst references = [...epoch.references];\n\tconst replacements: { messageIndex: number; text: string }[] = [];\n\tfor (const [index, message] of captured.entries()) {\n\t\tif (index < firstMessageIndex || (message.role !== \"assistant\" && message.role !== \"toolResult\")) continue;\n\t\t// Public v1 has no media representation. Do not disturb an otherwise valid native request.\n\t\tif (message.content.some((part) => ![\"text\", \"toolCall\", \"thinking\"].includes(part.type))) return;\n\t\tconst reference = references[index];\n\t\tif (!reference) throw new Error(\"Public request view requires its captured source\");\n\t\tconst rendered = renderPublicHistory(message, reference.ref.entryId, maxBytes);\n\t\tif (rendered.role !== \"custom\" || typeof rendered.content !== \"string\")\n\t\t\tthrow new Error(\"Public request view has no standalone text\");\n\t\tconst source = messageSources.get(message);\n\t\tif (source) messageSources.set(rendered, source);\n\t\tcaptured[index] = rendered;\n\t\treferences[index] = { ...reference, rendering: PUBLIC_CONTEXT_RENDERER };\n\t\treplacements.push({ messageIndex: index, text: rendered.content });\n\t}\n\tif (!replacements.length) return;\n\tstringifyBoundedJson(captured, maxBytes);\n\tconst publicIndices = new Set(replacements.map((replacement) => replacement.messageIndex));\n\tconst renderedUnit = (unit: ViewUnit, index: number): ViewUnit =>\n\t\tpublicIndices.has(index)\n\t\t\t? { ...unit, sourceRevision: JSON.stringify([unit.sourceRevision, PUBLIC_CONTEXT_RENDERER]) }\n\t\t\t: unit;\n\tcompiledViewUnits.set(captured, {\n\t\tunits: views.units.map(renderedUnit),\n\t\tselection: { ...views.selection, units: views.selection.units.map(renderedUnit) },\n\t});\n\tcompiledEpochContexts.set(captured, {\n\t\t...epoch,\n\t\treferences,\n\t\tcontinuation: { kind: \"portable-checkpoint\", publicTailThrough: epoch.source },\n\t});\n\treturn { messages: captured, replacements };\n}\n\n/** Read mode only from the same qualified compaction owner used by the compiler. */\nexport async function readCanonicalContextMode(\n\tview: SessionHistoryReadView,\n\tmaxBytes: number,\n\tinitial: ContextMode,\n): Promise<ContextMode> {\n\tconst manifest = await view.contextManifest({ limit: 1 });\n\tif (manifest.selection !== \"known\") throw new Error(\"Context mode source is unavailable\");\n\tif (!manifest.summaryRef) return initial;\n\tconst metadata = await view.get(manifest.summaryRef.entryId);\n\tif (!metadata) throw new Error(\"Context mode checkpoint is unavailable\");\n\tconst hydrated = await hydrateCapturedHistoryEntry(metadata, maxBytes, view.readPayload);\n\tif (!hydrated || hydrated.entry.type !== \"compaction\") throw new Error(\"Context mode checkpoint is unavailable\");\n\tconst details = hydrated.entry.details;\n\tif (!details || typeof details !== \"object\" || !(CONTEXT_EPOCH_DETAIL in details)) return initial;\n\tif (hydrated.source.qualification !== \"native-context-epoch\" || hydrated.source.retention === \"retained-import\")\n\t\tthrow new Error(\"Context mode checkpoint is not qualified on this source\");\n\treturn contextEpochMode(readContextEpoch(details, maxBytes), initial);\n}\n\n/** Literal suffixes follow source append order, not the restored tool-call display order. */\nfunction latestLiteralReference(references: readonly (EpochViewReference | null)[]): EpochViewReference | undefined {\n\tlet latest: EpochViewReference | undefined;\n\tfor (const reference of references) {\n\t\tif (reference && reference.ref.kind !== \"compaction\" && (!latest || reference.ref.sequence > latest.ref.sequence))\n\t\t\tlatest = reference;\n\t}\n\treturn latest;\n}\n\n/** Policy changes retain the current recipe; generated overlays are not archived conversation. */\nexport function prepareContextModeEpoch(\n\tmessages: readonly AgentMessage[],\n\tmode: ContextMode,\n\tmaxBytes: number,\n\tfreshContextContract = false,\n): { checkpoint: ContextEpochCheckpoint; messages: AgentMessage[] } {\n\tconst context = compiledEpochContexts.get(messages);\n\tconst units = getCanonicalViewUnits(messages);\n\tif (!context || !units || units.length !== messages.length)\n\t\tthrow new Error(\"Context mode requires captured canonical views\");\n\tif (context.toolContinuations?.length)\n\t\tthrow new Error(\"Tool continuation cannot enter a policy-only context checkpoint\");\n\tconst chosen = messages.filter(\n\t\t(_, index) => units[index].kind !== \"task-frame\" && units[index].kind !== \"resource-view\",\n\t);\n\tconst tail = latestLiteralReference(context.references);\n\tconst views = context.references.filter(\n\t\t(reference): reference is EpochViewReference => reference !== null && reference !== tail,\n\t);\n\t// A metadata-only fresh branch uses its existing source leaf; no fake user input is appended.\n\tconst literalTailId = tail?.ref.entryId ?? context.source.leafId;\n\tif (!literalTailId) throw new Error(\"Context mode requires a canonical source boundary\");\n\treturn {\n\t\tcheckpoint: snapshotContextEpoch(\n\t\t\t{\n\t\t\t\tversion: 5,\n\t\t\t\trenderer: context.selectedSkills?.length ? CONTEXT_SKILL_EPOCH_RENDERER : CONTEXT_POLICY_EPOCH_RENDERER,\n\t\t\t\t...(context.selectedSkills?.length ? { selectedSkills: context.selectedSkills } : {}),\n\t\t\t\tmode,\n\t\t\t\tpolicyOnly: true,\n\t\t\t\trepresentation: null,\n\t\t\t\tsource: context.source,\n\t\t\t\tviews,\n\t\t\t\tliteralTailId,\n\t\t\t\trequestContract: retainedContextRequestContract(context.checkpoint),\n\t\t\t\t...(mode === \"off\" && !context.checkpoint && freshContextContract\n\t\t\t\t\t? { pendingRequestContract: true as const }\n\t\t\t\t\t: {}),\n\t\t\t\treplayContract: context.checkpoint?.replayContract,\n\t\t\t\tpublicWindow: context.checkpoint?.publicWindow,\n\t\t\t\tcontinuation: context.checkpoint?.continuation,\n\t\t\t\t// Retain the existing bounded anchor recipe for explicit re-enable; off never injects it.\n\t\t\t\ttaskFrame: context.taskFrame ?? context.checkpoint?.taskFrame,\n\t\t\t},\n\t\t\tmaxBytes,\n\t\t),\n\t\tmessages: [...chosen],\n\t};\n}\n\n/** A candidate only. The caller must ACK the canonical checkpoint before adoption or send. */\nexport function prepareCanonicalEpoch(\n\tmessages: readonly AgentMessage[],\n\tselectedUnitIds: readonly string[],\n\trepresentation: string,\n\tmaxBytes: number,\n\treplayContract: ContextReplayContract = \"complete-context\",\n\tpublicWindow = false,\n): {\n\tcheckpoint: ContextEpochCheckpoint & { readonly version: 4 | 6; readonly representation: string };\n\tmessages: AgentMessage[];\n} {\n\tconst context = compiledEpochContexts.get(messages);\n\tconst units = getCanonicalViewUnits(messages);\n\tif (!context || !units || units.length !== messages.length || context.references.length !== messages.length)\n\t\tthrow new Error(\"Context epoch requires its captured compiler output\");\n\tif (context.readOnly) throw new Error(\"Read-only context cannot authorize a provider epoch\");\n\tif (compiledViewUnits.get(messages)?.selection.pendingPublicMessageGroups?.length)\n\t\tthrow new Error(\"Tool continuation requires its accepted public representation\");\n\tif (context.toolContinuations?.length && (!publicWindow || replayContract !== \"message-groups\"))\n\t\tthrow new Error(\"Tool continuation epoch requires its actual public replay contract\");\n\tconst selected = new Set(selectedUnitIds);\n\tif (selected.size !== selectedUnitIds.length || [...selected].some((id) => !units.some((unit) => unit.id === id)))\n\t\tthrow new Error(\"Context epoch selection has an unknown or repeated unit\");\n\tconst chosen: AgentMessage[] = [];\n\tconst views: EpochViewReference[] = [];\n\tfor (const [index, unit] of units.entries()) {\n\t\tif (!selected.has(unit.id)) {\n\t\t\tif (unit.kind === \"task-frame\") throw new Error(\"Context epoch cannot omit its task frame\");\n\t\t\tif (unit.kind === \"resource-view\") throw new Error(\"Context epoch cannot omit its current resource view\");\n\t\t\tif (unit.id === \"native-selected-skill-versions\")\n\t\t\t\tthrow new Error(\"Context epoch cannot omit its selected skill references\");\n\t\t\tcontinue;\n\t\t}\n\t\tchosen.push(messages[index]);\n\t\tconst reference = context.references[index];\n\t\tif (reference) views.push(reference);\n\t}\n\tconst tail = latestLiteralReference(context.references);\n\tif (!tail) throw new Error(\"Context epoch literal tail is unavailable\");\n\tconst tailIndex = views.indexOf(tail);\n\tif (tailIndex < 0) throw new Error(\"Context epoch cannot omit the current literal tail\");\n\tviews.splice(tailIndex, 1);\n\treturn {\n\t\tcheckpoint: snapshotContextEpoch(\n\t\t\t{\n\t\t\t\tversion: context.toolContinuations?.length ? 6 : 4,\n\t\t\t\trenderer: context.toolContinuations?.some((group) =>\n\t\t\t\t\tgroup.calls.some((call) => call.admission === \"absent\"),\n\t\t\t\t)\n\t\t\t\t\t? CONTEXT_INTERRUPTED_TOOL_RENDERER\n\t\t\t\t\t: context.selectedSkills?.length\n\t\t\t\t\t\t? CONTEXT_SKILL_EPOCH_RENDERER\n\t\t\t\t\t\t: context.toolContinuations?.length\n\t\t\t\t\t\t\t? CONTEXT_TOOL_EPOCH_RENDERER\n\t\t\t\t\t\t\t: CONTEXT_EPOCH_RENDERER,\n\t\t\t\t...(context.selectedSkills?.length ? { selectedSkills: context.selectedSkills } : {}),\n\t\t\t\t...(context.toolContinuations?.length ? { toolContinuations: context.toolContinuations } : {}),\n\t\t\t\tsource: context.source,\n\t\t\t\trepresentation,\n\t\t\t\treplayContract,\n\t\t\t\t...(publicWindow ? { publicWindow: true as const } : {}),\n\t\t\t\t...((context.continuation ?? context.checkpoint?.continuation)\n\t\t\t\t\t? { continuation: context.continuation ?? context.checkpoint?.continuation }\n\t\t\t\t\t: {}),\n\t\t\t\tviews,\n\t\t\t\ttaskFrame: context.taskFrame,\n\t\t\t\tresourceRevision: context.resourceRevision,\n\t\t\t\tliteralTailId: tail.ref.entryId,\n\t\t\t},\n\t\t\tmaxBytes,\n\t\t),\n\t\tmessages: chosen,\n\t};\n}\n\n/** Use only a replay contract granted to these recovery results by an actual accepted request. */\nexport function canonicalRecoveryBoundary(messages: readonly AgentMessage[]): string | undefined {\n\tconst context = compiledEpochContexts.get(messages);\n\tconst units = getCanonicalViewUnits(messages);\n\tif (!context || !units) throw new Error(\"Recovery compaction requires captured canonical views\");\n\tif (context.toolContinuations?.length && !context.readOnly)\n\t\tthrow new Error(\"Tool continuation summary requires its captured public read view\");\n\tconst recoveries = units.flatMap((unit, index) => (unit.kind === \"recovery\" ? [context.references[index]] : []));\n\tif (!recoveries.length) return;\n\tconst checkpoint = context.checkpoint;\n\tif (\n\t\t!checkpoint?.representation ||\n\t\tcheckpoint.replayContract !== \"message-groups\" ||\n\t\trecoveries.some((reference) => !reference || reference.ref.sequence > checkpoint.source.sourceSequence)\n\t)\n\t\tthrow new Error(\"Recovery compaction requires an accepted replay contract for its selected results\");\n\treturn checkpoint.literalTailId;\n}\n\n/** Retain exact recovery evidence. An accepted public-window transition replaces whole old protocol groups. */\nexport function prepareRecoveryCompaction(\n\tmessages: readonly AgentMessage[],\n\tfirstKeptEntryId: string,\n\tmaxBytes: number,\n): ContextEpochCheckpoint | undefined {\n\tconst boundary = canonicalRecoveryBoundary(messages);\n\tconst context = compiledEpochContexts.get(messages);\n\tconst publicWindow =\n\t\tcontext?.checkpoint?.publicWindow === true && context.checkpoint.replayContract === \"message-groups\";\n\tif (!boundary && !publicWindow && !context?.selectedSkills?.length && !context?.toolContinuations?.length) return;\n\tif (!context) throw new Error(\"Recovery compaction requires captured canonical views\");\n\tconst selection = getCanonicalViewSelectionSource(messages)!;\n\tconst cut = context.references.findIndex((reference) => reference?.ref.entryId === firstKeptEntryId);\n\tconst lastProved = boundary\n\t\t? context.references.findIndex((reference) => reference?.ref.entryId === boundary)\n\t\t: messages.length - 1;\n\tif (cut < 0 || lastProved < 0 || cut > lastProved)\n\t\tthrow new Error(\"Recovery compaction must retain its unmeasured literal tail\");\n\tconst units = bindMessageReplayUnits(messages, selection.units, selection.limits, \"message-groups\");\n\t// A mode transition cannot strand any outstanding native call, including one in the retained tail.\n\tcloseViewSelection(\n\t\tunits,\n\t\tunits.map((unit) => unit.id),\n\t\tselection.limits,\n\t);\n\tconst toolGroups = new Set(context.toolContinuations?.map((group) => group.assistantEntryId));\n\tconst roots = units\n\t\t.filter((unit, index) => unit.kind === \"recovery\" || toolGroups.has(context.references[index]?.ref.entryId ?? \"\"))\n\t\t.map((unit) => unit.id);\n\tconst closed = new Set(closeViewSelection(units, roots, selection.limits).map((unit) => unit.id));\n\tlet renderedBytes = 0;\n\tconst views = context.references.flatMap((reference, index): EpochViewReference[] => {\n\t\tif (!reference || (index < cut && !closed.has(units[index].id))) return [];\n\t\tconst message = messages[index];\n\t\tconst rendered = publicWindow ? renderPublicHistory(message, reference.ref.entryId, maxBytes) : message;\n\t\tif (publicWindow) {\n\t\t\trenderedBytes += Buffer.byteLength(JSON.stringify(rendered), \"utf8\");\n\t\t\tif (renderedBytes > maxBytes) throw new Error(\"Public summary view byte budget exceeded\");\n\t\t}\n\t\treturn index < cut\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\t...reference,\n\t\t\t\t\t\t...(rendered !== message ? { rendering: PUBLIC_CONTEXT_RENDERER } : {}),\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: [];\n\t});\n\tif (!views.length && !publicWindow && !context.selectedSkills?.length && !toolGroups.size) return;\n\treturn snapshotContextEpoch(\n\t\t{\n\t\t\t...(toolGroups.size ? { version: 8 as const, mode: context.mode } : { version: 4 as const }),\n\t\t\trenderer: context.toolContinuations?.some((group) => group.calls.some((call) => call.admission === \"absent\"))\n\t\t\t\t? CONTEXT_INTERRUPTED_TOOL_RENDERER\n\t\t\t\t: toolGroups.size\n\t\t\t\t\t? CONTEXT_TOOL_SUMMARY_RENDERER\n\t\t\t\t\t: context.selectedSkills?.length\n\t\t\t\t\t\t? CONTEXT_SKILL_EPOCH_RENDERER\n\t\t\t\t\t\t: CONTEXT_EPOCH_RENDERER,\n\t\t\t...(toolGroups.size ? { toolContinuations: context.toolContinuations } : {}),\n\t\t\t...(context.selectedSkills?.length ? { selectedSkills: context.selectedSkills } : {}),\n\t\t\tsource: context.source,\n\t\t\trepresentation: null,\n\t\t\tincludeSummary: true,\n\t\t\t...(toolGroups.size && publicWindow ? { publicWindow: true as const } : {}),\n\t\t\treplayContract:\n\t\t\t\tboundary || publicWindow ? \"message-groups\" : (context.checkpoint?.replayContract ?? \"complete-context\"),\n\t\t\t...(publicWindow\n\t\t\t\t? {\n\t\t\t\t\t\tcontinuation: {\n\t\t\t\t\t\t\tkind: \"harness-summary\" as const,\n\t\t\t\t\t\t\tpublicTailThrough: context.source,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\tviews,\n\t\t\tresourceRevision: context.resourceRevision,\n\t\t\tliteralTailId: firstKeptEntryId,\n\t\t},\n\t\tmaxBytes,\n\t);\n}\n\ninterface CachedEntry {\n\trevision: string;\n\tentry: SessionEntry;\n}\n\ntype KnownManifest = Extract<ContextManifestPage, { selection: \"known\" }>;\n\n/** Exact active-context reconstruction. It never silently chooses a last-N transcript. */\nexport class CanonicalContextCompiler {\n\tprivate source?: SourceSnapshotRef;\n\tprivate entries = new Map<string, CachedEntry>();\n\tprivate sourceBytes = 0;\n\tprivate messageCount = 0;\n\tprivate taskFrame?: CompiledTaskFrame;\n\tprivate taskBoundary?: string;\n\tprivate readonly taskState = new TaskStateReadCache();\n\tprivate generation = 0;\n\tprivate forceTaskFrameRebase = false;\n\n\trequestTaskFrameRebase(): void {\n\t\tthis.forceTaskFrameRebase = true;\n\t}\n\n\tclear(): void {\n\t\tthis.generation++;\n\t\tthis.taskState.clear();\n\t\tthis.forceTaskFrameRebase = false;\n\t\tthis.entries.clear();\n\t\tthis.source = undefined;\n\t\tthis.sourceBytes = 0;\n\t\tthis.messageCount = 0;\n\t\tthis.taskFrame = undefined;\n\t\tthis.taskBoundary = undefined;\n\t}\n\n\t/** Membership in the last successful active-source cache, including explicitly omitted responses. */\n\thasActiveEntry(entryId: string): boolean {\n\t\treturn this.entries.has(entryId);\n\t}\n\n\tasync compile(\n\t\tview: SessionHistoryReadView,\n\t\tlimits: CanonicalContextLimits,\n\t\tomittedAssistantIds: ReadonlySet<string> = new Set(),\n\t\tframeOptions: Partial<TaskFrameLimits> = {},\n\t\tresourceCapture?: OwnedResourceCapture,\n\t\tinitialContextMode: ContextMode = \"on\",\n\t\tallowPendingToolPublic = false,\n\t\tpurpose: \"request\" | \"read\" = \"request\",\n\t): Promise<AgentMessage[]> {\n\t\tconst generation = this.generation;\n\t\tconst frameLimits = taskFrameLimits(frameOptions);\n\t\tconst previousSource = this.source;\n\t\tconst previousFrame = this.taskFrame;\n\t\tconst previousBoundary = this.taskBoundary;\n\t\tconst omitted = new Set(omittedAssistantIds);\n\t\tconst { maxMessages, maxSourceBytes } = limits;\n\t\tif (\n\t\t\t!Number.isSafeInteger(maxMessages) ||\n\t\t\tmaxMessages <= 0 ||\n\t\t\t!Number.isSafeInteger(maxSourceBytes) ||\n\t\t\tmaxSourceBytes <= 0\n\t\t)\n\t\t\tthrow new Error(\"Invalid canonical context limits\");\n\t\tif (\n\t\t\tthis.source?.sessionId !== view.source.sessionId ||\n\t\t\tthis.source?.sessionFile !== view.source.sessionFile ||\n\t\t\tthis.messageCount > maxMessages ||\n\t\t\tthis.sourceBytes > maxSourceBytes\n\t\t) {\n\t\t\tthis.entries.clear();\n\t\t\tthis.sourceBytes = 0;\n\t\t\tthis.messageCount = 0;\n\t\t}\n\t\tlet first: KnownManifest | undefined;\n\t\tlet cursor: ContextManifestCursor | undefined;\n\t\tlet expected = 0;\n\t\tlet sourceBytes = 0;\n\t\tconst refs: ContextRef[] = [];\n\t\tconst sourceOrder = new Map<string, number>();\n\t\tconst countBytes = (ref: Pick<ContextRef, \"locator\">) => {\n\t\t\tsourceBytes += ref.locator.length;\n\t\t\tif (sourceBytes > maxSourceBytes) throw new Error(\"Canonical context source byte budget exceeded\");\n\t\t};\n\t\tfor (;;) {\n\t\t\tconst page = await view.contextManifest({ cursor, limit: 128 });\n\t\t\tif (page.selection !== \"known\") throw new Error(`Canonical context selection is ${page.selection}`);\n\t\t\tif (!first) {\n\t\t\t\tfirst = page;\n\t\t\t\tif (page.activeMessageCount + (page.summaryRef ? 1 : 0) > maxMessages)\n\t\t\t\t\tthrow new Error(\"Canonical context message budget exceeded\");\n\t\t\t\texpected = page.activeBase + 1;\n\t\t\t\tif (page.summaryRef) countBytes(page.summaryRef);\n\t\t\t} else if (\n\t\t\t\tpage.activeBase !== first.activeBase ||\n\t\t\t\tpage.activeMessageCount !== first.activeMessageCount ||\n\t\t\t\tpage.retainedMessageCount !== first.retainedMessageCount ||\n\t\t\t\tpage.summaryRef?.entryId !== first.summaryRef?.entryId ||\n\t\t\t\tpage.summaryRef?.revision !== first.summaryRef?.revision\n\t\t\t) {\n\t\t\t\tthrow new Error(\"Canonical context manifest changed during its captured read\");\n\t\t\t}\n\t\t\tfor (const ref of page.refs) {\n\t\t\t\tif (ref.ordinal !== expected++) throw new Error(\"Canonical context manifest skipped an active message\");\n\t\t\t\tcountBytes(ref);\n\t\t\t\trefs.push(ref);\n\t\t\t\tsourceOrder.set(ref.entryId, ref.sequence);\n\t\t\t}\n\t\t\tif (!page.nextCursor) break;\n\t\t\tif (!page.refs.length || page.nextCursor.nextOrdinal !== expected)\n\t\t\t\tthrow new Error(\"Canonical context manifest did not advance\");\n\t\t\tcursor = page.nextCursor;\n\t\t}\n\t\tif (refs.length !== first.activeMessageCount) throw new Error(\"Canonical context manifest is incomplete\");\n\n\t\tconst next = new Map<string, CachedEntry>();\n\t\tconst hydrate = async (\n\t\t\tref: ContextRef | ContextUpdateRef,\n\t\t\ttarget?: ContextUpdateTarget,\n\t\t\treadView: SessionHistoryReadView = view,\n\t\t): Promise<SessionEntry> => {\n\t\t\tconst cached = this.entries.get(ref.entryId);\n\t\t\tif (cached?.revision === ref.revision) {\n\t\t\t\tnext.set(ref.entryId, cached);\n\t\t\t\treturn cached.entry;\n\t\t\t}\n\t\t\tconst fragments: string[] = [];\n\t\t\tlet offset = 0;\n\t\t\tlet part = target\n\t\t\t\t? await readView.readContextUpdatePayload(ref.entryId, target)\n\t\t\t\t: await readView.readPayload(ref.entryId);\n\t\t\tfor (;;) {\n\t\t\t\tif (!part || part.byteOffset !== offset || part.byteLength <= 0)\n\t\t\t\t\tthrow new Error(\"Canonical context payload is unavailable or incomplete\");\n\t\t\t\toffset += part.byteLength;\n\t\t\t\tif (offset > ref.locator.length) throw new Error(\"Canonical context payload exceeds its source locator\");\n\t\t\t\tfragments.push(part.text);\n\t\t\t\tif (!part.nextCursor) break;\n\t\t\t\tpart = target\n\t\t\t\t\t? await readView.readContextUpdatePayload(ref.entryId, target, { cursor: part.nextCursor })\n\t\t\t\t\t: await readView.readPayload(ref.entryId, { cursor: part.nextCursor });\n\t\t\t}\n\t\t\tconst value: unknown = JSON.parse(fragments.join(\"\"));\n\t\t\tif (\n\t\t\t\t!value ||\n\t\t\t\ttypeof value !== \"object\" ||\n\t\t\t\t!(\"id\" in value) ||\n\t\t\t\tvalue.id !== ref.entryId ||\n\t\t\t\t!(\"type\" in value) ||\n\t\t\t\tvalue.type !== ref.kind\n\t\t\t)\n\t\t\t\tthrow new Error(\"Canonical context payload does not match its source reference\");\n\t\t\tconst entry = value as SessionEntry;\n\t\t\tnext.set(ref.entryId, { revision: ref.revision, entry });\n\t\t\treturn entry;\n\t\t};\n\t\tlet checkpoint: ContextEpochCheckpoint | undefined;\n\t\tlet summaryEntry: SessionEntry | undefined;\n\t\tif (first.summaryRef) {\n\t\t\tsummaryEntry = await hydrate(first.summaryRef);\n\t\t\tif (summaryEntry.type !== \"compaction\") throw new Error(\"Canonical context summary has the wrong source kind\");\n\t\t\tif (\n\t\t\t\tsummaryEntry.details &&\n\t\t\t\ttypeof summaryEntry.details === \"object\" &&\n\t\t\t\tCONTEXT_EPOCH_DETAIL in summaryEntry.details\n\t\t\t) {\n\t\t\t\tconst source = await view.get(first.summaryRef.entryId);\n\t\t\t\tif (source?.qualification !== \"native-context-epoch\" || source.retention === \"retained-import\")\n\t\t\t\t\tthrow new Error(\"Context epoch checkpoint is not qualified on this source\");\n\t\t\t\tcheckpoint = readContextEpoch(summaryEntry.details, maxSourceBytes);\n\t\t\t\tif (\n\t\t\t\t\t!checkpoint ||\n\t\t\t\t\tcheckpoint.literalTailId !== summaryEntry.firstKeptEntryId ||\n\t\t\t\t\tcheckpoint.views.length + first.activeMessageCount > maxMessages\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Context epoch checkpoint does not match its retained boundary\");\n\t\t\t}\n\t\t}\n\t\tconst mode = contextEpochMode(checkpoint, initialContextMode);\n\t\tconst selectedSkills = new Map((checkpoint?.selectedSkills ?? []).map((skill) => [skill.name, skill]));\n\t\tfor (const skill of selectedSkills.values()) {\n\t\t\tif (!view.atSnapshot) throw new Error(\"Selected skill epoch requires its original prefix\");\n\t\t\tconst prefix = await view.atSnapshot(skill.view.source);\n\t\t\tconst actual = await prefix.get(skill.view.ref.entryId);\n\t\t\tif (\n\t\t\t\t!actual ||\n\t\t\t\tactual.kind !== skill.view.ref.kind ||\n\t\t\t\t![\"custom_message\", \"custom\"].includes(actual.kind) ||\n\t\t\t\tactual.qualification !== \"native-recovery\" ||\n\t\t\t\tactual.revision !== skill.view.ref.revision ||\n\t\t\t\tactual.sequence !== skill.view.ref.sequence ||\n\t\t\t\tJSON.stringify(actual.locator) !== JSON.stringify(skill.view.ref.locator) ||\n\t\t\t\tskill.view.sourceRevision !== JSON.stringify([actual.revision])\n\t\t\t)\n\t\t\t\tthrow new Error(\"Selected skill epoch source is unavailable\");\n\t\t}\n\t\tconst toolSourceIds = new Set(\n\t\t\tcheckpoint?.toolContinuations?.flatMap((group) => [\n\t\t\t\tgroup.assistantEntryId,\n\t\t\t\t...group.calls.flatMap((call) => (call.result ? [call.result.id] : [])),\n\t\t\t]),\n\t\t);\n\t\tconst publicTail = checkpoint?.continuation?.publicTailThrough;\n\t\tif (publicTail) {\n\t\t\tif (!view.atSnapshot) throw new Error(\"Public summary transition requires its captured source\");\n\t\t\tawait view.atSnapshot(publicTail);\n\t\t}\n\t\tlet publicBytes = 0;\n\t\tconst boundary = JSON.stringify([first.summaryRef?.entryId ?? null, first.summaryRef?.revision ?? null]);\n\t\tlet resetFrame =\n\t\t\tpreviousSource?.sessionId !== view.source.sessionId ||\n\t\t\tpreviousSource?.sessionFile !== view.source.sessionFile ||\n\t\t\tpreviousBoundary !== boundary ||\n\t\t\t(previousSource !== undefined && previousSource.sourceSequence > view.source.sourceSequence);\n\t\tif (!resetFrame && previousFrame && previousSource?.leafId && previousSource.leafId !== view.source.leafId)\n\t\t\tresetFrame = !(await view.get(previousSource.leafId));\n\t\tconst tasks =\n\t\t\tmode === \"off\"\n\t\t\t\t? undefined\n\t\t\t\t: await this.taskState.read(view, {\n\t\t\t\t\t\tmaxItems: maxMessages,\n\t\t\t\t\t\tmaxSourceBytes,\n\t\t\t\t\t\tmaxViewBytes: maxSourceBytes,\n\t\t\t\t\t});\n\t\tlet taskSequence = -1;\n\t\tfor (const { event } of tasks?.items ?? []) {\n\t\t\tif (event.source.sequence === taskSequence) continue;\n\t\t\ttaskSequence = event.source.sequence;\n\t\t\t// The task reader has already required an exact locator for every represented frame.\n\t\t\tcountBytes({ locator: event.source.locator! });\n\t\t}\n\t\tconst referenceFrame = resetFrame ? checkpoint?.taskFrame : previousFrame;\n\t\tif (resetFrame || (referenceFrame && referenceFrame.messages.length <= 1)) this.forceTaskFrameRebase = false;\n\t\tconst forceRebase = purpose === \"request\" && this.forceTaskFrameRebase;\n\t\tlet taskFrame = tasks\n\t\t\t? compileTaskFrame(tasks, frameLimits, forceRebase ? undefined : referenceFrame)\n\t\t\t: undefined;\n\t\tconst taskFrameRebased = Boolean(\n\t\t\tmode === \"on\" &&\n\t\t\t\treferenceFrame &&\n\t\t\t\ttaskFrame !== referenceFrame &&\n\t\t\t\t(!taskFrame || taskFrame.messages.length === 1),\n\t\t);\n\t\tconst resource =\n\t\t\tmode === \"on\" && resourceCapture && (resourceCapture.enabled || checkpoint)\n\t\t\t\t? renderResourceView(resourceCapture)\n\t\t\t\t: undefined;\n\t\tif (resource) {\n\t\t\tsourceBytes += resource.bytes;\n\t\t\tif (sourceBytes > maxSourceBytes) throw new Error(\"Canonical context source byte budget exceeded\");\n\t\t}\n\t\tconst messageCount =\n\t\t\tfirst.activeMessageCount +\n\t\t\t(checkpoint ? checkpoint.views.length + (checkpoint.includeSummary ? 1 : 0) : first.summaryRef ? 1 : 0) +\n\t\t\t(taskFrame?.messages.length ?? 0) +\n\t\t\t(resource ? 1 : 0);\n\t\tif (messageCount > maxMessages) throw new Error(\"Canonical context message budget exceeded\");\n\n\t\tconst messages: AgentMessage[] = [];\n\t\tconst renderedMessages = new Map<AgentMessage, AgentMessage>();\n\t\tconst literalSources = new Map<AgentMessage, string>();\n\t\tconst unitSources = new Map<AgentMessage, ViewUnit>();\n\t\tconst epochReferences = new Map<AgentMessage, EpochViewReference>();\n\t\tconst sourceUnit = (ref: ContextRef, kind: ViewUnit[\"kind\"]): ViewUnit => ({\n\t\t\tid: JSON.stringify([view.source.sessionId, view.source.sessionFile, ref.entryId]),\n\t\t\tsourceRevision: ref.revision,\n\t\t\tkind,\n\t\t\texactSources: [ref.entryId],\n\t\t\trequiredVisibleDependencies: [],\n\t\t\tauthority:\n\t\t\t\tkind === \"recovery\"\n\t\t\t\t\t? \"tool-data\"\n\t\t\t\t\t: ref.authority === \"user\"\n\t\t\t\t\t\t? \"user\"\n\t\t\t\t\t\t: ref.authority === \"assistant\"\n\t\t\t\t\t\t\t? \"assistant-public\"\n\t\t\t\t\t\t\t: ref.authority === \"runtime\"\n\t\t\t\t\t\t\t\t? \"tool-data\"\n\t\t\t\t\t\t\t\t: \"unrecorded\",\n\t\t\ttokenEstimate: null,\n\t\t\timmutableWithinEpoch: true,\n\t\t});\n\t\tconst addSummary = async (ref: ContextRef, readView: SessionHistoryReadView, retainedMessageCount: number) => {\n\t\t\tconst summary = await hydrate(ref, undefined, readView);\n\t\t\tif (summary.type !== \"compaction\") throw new Error(\"Canonical context summary has the wrong source kind\");\n\t\t\tconst message = createCompactionSummaryMessage(\n\t\t\t\tsummary.summary,\n\t\t\t\tsummary.tokensBefore,\n\t\t\t\tsummary.timestamp,\n\t\t\t\tsummary.customInstructions,\n\t\t\t\tretainedMessageCount,\n\t\t\t);\n\t\t\tmessages.push(message);\n\t\t\tliteralSources.set(message, ref.entryId);\n\t\t\tunitSources.set(message, sourceUnit(ref, \"fixed-view\"));\n\t\t\tepochReferences.set(message, {\n\t\t\t\tsource: readView.source,\n\t\t\t\tref,\n\t\t\t\tsourceRevision: ref.revision,\n\t\t\t\tretainedMessageCount,\n\t\t\t});\n\t\t\tsourceOrder.set(ref.entryId, -1);\n\t\t};\n\t\tif (first.summaryRef && (!checkpoint || checkpoint.includeSummary))\n\t\t\tawait addSummary(first.summaryRef, view, first.retainedMessageCount);\n\t\tconst addLiteral = async (ref: ContextRef, readView: SessionHistoryReadView, pinned?: EpochViewReference) => {\n\t\t\tconst entry = await hydrate(ref, undefined, readView);\n\t\t\t// Internal capture records never interrupt a native assistant/tool-result group.\n\t\t\t// Retained records remain recoverable data, but cannot mint a new selection.\n\t\t\tconst skill = ref.qualification === \"native-recovery\" ? selectedSkillCapture(entry) : undefined;\n\t\t\tif (skill) {\n\t\t\t\tif (\n\t\t\t\t\tskill.producer === \"model\" &&\n\t\t\t\t\tisNativeSkillSelection(ref) &&\n\t\t\t\t\t(!checkpoint || ref.sequence > checkpoint.source.sourceSequence)\n\t\t\t\t) {\n\t\t\t\t\tselectedSkills.set(skill.descriptor.name, {\n\t\t\t\t\t\tname: skill.descriptor.name,\n\t\t\t\t\t\tview: {\n\t\t\t\t\t\t\tsource: view.source,\n\t\t\t\t\t\t\tref: { ...ref, kind: \"custom_message\" },\n\t\t\t\t\t\t\tsourceRevision: JSON.stringify([ref.revision]),\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst origin = entry.type === \"message\" || entry.type === \"custom_message\" ? entry.nativeOrigin : undefined;\n\t\t\tif (\n\t\t\t\tref.qualification === \"native-admission\" &&\n\t\t\t\tref.retention !== \"retained-import\" &&\n\t\t\t\torigin?.kind === \"input\" &&\n\t\t\t\torigin.recordRole === \"primary\" &&\n\t\t\t\torigin.selectedSkillRef &&\n\t\t\t\t(!checkpoint || ref.sequence > checkpoint.source.sourceSequence) &&\n\t\t\t\t![...selectedSkills.values()].some((skill) => skill.view.ref.entryId === origin.selectedSkillRef?.entryId)\n\t\t\t) {\n\t\t\t\tif (\n\t\t\t\t\torigin.selectedSkillRef.sessionId !== view.source.sessionId ||\n\t\t\t\t\torigin.selectedSkillRef.sessionFile !== view.source.sessionFile\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Admitted skill selection belongs to another source\");\n\t\t\t\tconst actual = await view.get(origin.selectedSkillRef.entryId);\n\t\t\t\tif (\n\t\t\t\t\t!actual ||\n\t\t\t\t\t(actual.kind !== \"custom\" && actual.kind !== \"custom_message\") ||\n\t\t\t\t\tactual.qualification !== \"native-recovery\"\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Admitted input selected skill source is unavailable\");\n\t\t\t\tcountBytes(actual);\n\t\t\t\tconst captured = await hydrateCapturedHistoryEntry(actual, actual.locator.length, view.readPayload);\n\t\t\t\tconst selected = captured ? selectedSkillCapture(captured.entry) : undefined;\n\t\t\t\tif (!selected) throw new Error(\"Admitted input has no captured skill version\");\n\t\t\t\tselectedSkills.set(selected.descriptor.name, {\n\t\t\t\t\tname: selected.descriptor.name,\n\t\t\t\t\tview: {\n\t\t\t\t\t\tsource: view.source,\n\t\t\t\t\t\tsourceRevision: JSON.stringify([actual.revision]),\n\t\t\t\t\t\tref: {\n\t\t\t\t\t\t\tentryId: actual.id,\n\t\t\t\t\t\t\tsequence: actual.sequence,\n\t\t\t\t\t\t\tkind: actual.kind,\n\t\t\t\t\t\t\tlocator: actual.locator,\n\t\t\t\t\t\t\trevision: actual.revision,\n\t\t\t\t\t\t\tauthority: actual.authority,\n\t\t\t\t\t\t\tqualification: actual.qualification,\n\t\t\t\t\t\t\tretention: actual.retention,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst original = sessionEntryMessage(entry);\n\t\t\tif (!original) throw new Error(\"Canonical context reference is not a visible context entry\");\n\t\t\t// These IDs come from actual native retry controls, not inferred transcript membership or stop reasons.\n\t\t\tif (original.role === \"assistant\" && omitted.has(ref.entryId)) return;\n\t\t\t// Neither canonical updates nor replaceable transforms may mutate cached source entries.\n\t\t\tconst message = structuredClone(original);\n\t\t\tconst revisions = [ref.revision];\n\t\t\tconst exactSources = [ref.entryId];\n\t\t\tif (message.role === \"assistant\") {\n\t\t\t\tconst target: ContextUpdateTarget = { kind: \"assistant-usage\", targetId: ref.entryId };\n\t\t\t\tfor (const update of (await readView.contextUpdates(target)).refs) {\n\t\t\t\t\tcountBytes(update);\n\t\t\t\t\tconst entry = await hydrate(update, target, readView);\n\t\t\t\t\trevisions.push(update.revision);\n\t\t\t\t\texactSources.push(update.entryId);\n\t\t\t\t\tif (entry.type !== \"child_usage_attributed\") throw new Error(\"Canonical usage update kind mismatch\");\n\t\t\t\t\tmessage.usage = cloneUsage(entry.aggregateUsage);\n\t\t\t\t}\n\t\t\t} else if (message.role === \"toolResult\" && message.toolName === \"ipython\") {\n\t\t\t\tconst target: ContextUpdateTarget = { kind: \"ipython-sent-message\", toolCallId: message.toolCallId };\n\t\t\t\tfor (const update of (await readView.contextUpdates(target)).refs) {\n\t\t\t\t\tcountBytes(update); // Charge each application, even when the source record is cached.\n\t\t\t\t\tconst entry = await hydrate(update, target, readView);\n\t\t\t\t\trevisions.push(update.revision);\n\t\t\t\t\texactSources.push(update.entryId);\n\t\t\t\t\tconst sent = entry.type === \"custom\" ? parsePersistedIpythonSentAgentMessage(entry.data) : undefined;\n\t\t\t\t\tif (!sent || sent.toolCallId !== message.toolCallId)\n\t\t\t\t\t\tthrow new Error(\"Canonical sent-message update mismatch\");\n\t\t\t\t\tappendSentAgentMessageToToolResult(message, message.toolCallId, sent.message);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst publicHistory =\n\t\t\t\t!toolSourceIds.has(ref.entryId) &&\n\t\t\t\t(pinned?.rendering === PUBLIC_CONTEXT_RENDERER ||\n\t\t\t\t\t(!pinned && publicTail !== undefined && ref.sequence <= publicTail.sourceSequence));\n\t\t\tconst rendered = publicHistory ? renderPublicHistory(message, ref.entryId, maxSourceBytes) : message;\n\t\t\tif (publicHistory) {\n\t\t\t\tpublicBytes += Buffer.byteLength(JSON.stringify(rendered), \"utf8\");\n\t\t\t\tif (publicBytes > maxSourceBytes) throw new Error(\"Public summary view byte budget exceeded\");\n\t\t\t}\n\t\t\tif (message.role === \"assistant\")\n\t\t\t\tmessageSources.set(rendered, {\n\t\t\t\t\tsessionId: view.source.sessionId,\n\t\t\t\t\tsessionFile: view.source.sessionFile,\n\t\t\t\t\tentryId: ref.entryId,\n\t\t\t\t});\n\t\t\tmessages.push(message);\n\t\t\trenderedMessages.set(message, rendered);\n\t\t\tliteralSources.set(rendered, ref.entryId);\n\t\t\tunitSources.set(rendered, {\n\t\t\t\t...sourceUnit(\n\t\t\t\t\tref,\n\t\t\t\t\tmessage.role === \"toolResult\" &&\n\t\t\t\t\t\tref.qualification === \"native-recovery\" &&\n\t\t\t\t\t\tref.retention !== \"retained-import\"\n\t\t\t\t\t\t? \"recovery\"\n\t\t\t\t\t\t: message.role === \"toolResult\" ||\n\t\t\t\t\t\t\t\t(message.role === \"assistant\" && message.content.some((part) => part.type === \"toolCall\"))\n\t\t\t\t\t\t\t? \"replay-group\"\n\t\t\t\t\t\t\t: \"literal\",\n\t\t\t\t),\n\t\t\t\tsourceRevision: JSON.stringify(rendered !== message ? [...revisions, PUBLIC_CONTEXT_RENDERER] : revisions),\n\t\t\t\texactSources,\n\t\t\t});\n\t\t\tconst revision = JSON.stringify(revisions);\n\t\t\tif (pinned && pinned.sourceRevision !== revision)\n\t\t\t\tthrow new Error(\"Context epoch view no longer matches its frozen source revisions\");\n\t\t\tif (pinned && unitSources.get(rendered)!.kind !== \"recovery\")\n\t\t\t\tunitSources.set(rendered, { ...unitSources.get(rendered)!, kind: \"fixed-view\" });\n\t\t\tepochReferences.set(rendered, {\n\t\t\t\tsource: readView.source,\n\t\t\t\tref,\n\t\t\t\tsourceRevision: revision,\n\t\t\t\t...(rendered !== message ? { rendering: PUBLIC_CONTEXT_RENDERER } : {}),\n\t\t\t});\n\t\t\tsourceOrder.set(ref.entryId, ref.sequence);\n\t\t};\n\t\tif (checkpoint) {\n\t\t\tif (!view.atSnapshot) throw new Error(\"Context epoch requires a captured native prefix reader\");\n\t\t\tconst prefixViews = new Map<string, SessionHistoryReadView>();\n\t\t\tconst seen = new Set<string>();\n\t\t\tfor (const pinned of checkpoint.views) {\n\t\t\t\tif (\n\t\t\t\t\tpinned.rendering !== undefined &&\n\t\t\t\t\t((pinned.rendering === PUBLIC_TOOL_CONTINUATION_RENDERER\n\t\t\t\t\t\t? checkpoint.version !== 6 && checkpoint.version !== 8\n\t\t\t\t\t\t: pinned.rendering !== PUBLIC_CONTEXT_RENDERER ||\n\t\t\t\t\t\t\t(checkpoint.version !== 3 &&\n\t\t\t\t\t\t\t\tcheckpoint.version !== 4 &&\n\t\t\t\t\t\t\t\tcheckpoint.version !== 5 &&\n\t\t\t\t\t\t\t\tcheckpoint.version !== 6 &&\n\t\t\t\t\t\t\t\tcheckpoint.version !== 8)) ||\n\t\t\t\t\t\tpinned.ref.kind === \"compaction\")\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Unsupported context epoch view rendering\");\n\t\t\t\tif (seen.has(pinned.ref.entryId) || refs.some((ref) => ref.entryId === pinned.ref.entryId))\n\t\t\t\t\tthrow new Error(\"Context epoch view overlaps its literal tail\");\n\t\t\t\tseen.add(pinned.ref.entryId);\n\t\t\t\tcountBytes(pinned.ref);\n\t\t\t\tconst key = JSON.stringify(pinned.source);\n\t\t\t\tlet prefix = prefixViews.get(key);\n\t\t\t\tif (!prefix) {\n\t\t\t\t\tprefix = await view.atSnapshot(pinned.source);\n\t\t\t\t\tprefixViews.set(key, prefix);\n\t\t\t\t}\n\t\t\t\tconst actual = await prefix.get(pinned.ref.entryId);\n\t\t\t\tif (\n\t\t\t\t\t!actual ||\n\t\t\t\t\tactual.revision !== pinned.ref.revision ||\n\t\t\t\t\tactual.kind !== pinned.ref.kind ||\n\t\t\t\t\tactual.sequence !== pinned.ref.sequence ||\n\t\t\t\t\tJSON.stringify(actual.locator) !== JSON.stringify(pinned.ref.locator)\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Context epoch view source is unavailable\");\n\t\t\t\tif (pinned.ref.kind === \"compaction\") {\n\t\t\t\t\tif (pinned.retainedMessageCount === undefined)\n\t\t\t\t\t\tthrow new Error(\"Context epoch summary count is unavailable\");\n\t\t\t\t\tawait addSummary(pinned.ref, prefix, pinned.retainedMessageCount);\n\t\t\t\t} else await addLiteral(pinned.ref, prefix, pinned);\n\t\t\t}\n\t\t}\n\t\tfor (const ref of refs) await addLiteral(ref, view);\n\t\t// Public renderings hide tool roles; restore call order while the source roles are still available.\n\t\torderContextToolResults(messages);\n\t\tfor (const [index, message] of messages.entries()) messages[index] = renderedMessages.get(message) ?? message;\n\t\tif (taskFrame) {\n\t\t\tif (referenceFrame && taskFrame !== referenceFrame && !taskFrameRebased) {\n\t\t\t\tconst last = messages.at(-1);\n\t\t\t\tconst anchor = last\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tentryId: literalSources.get(last)!,\n\t\t\t\t\t\t\tside: last.role === \"user\" || last.role === \"custom\" ? (\"before\" as const) : (\"after\" as const),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null;\n\t\t\t\ttaskFrame = { ...taskFrame, anchors: [...taskFrame.anchors.slice(0, -1), anchor] };\n\t\t\t}\n\t\t\tconst [base, ...revisions] = structuredClone(taskFrame.messages);\n\t\t\tconst frames = [base, ...revisions];\n\t\t\tconst frameIds = frames.map((_, index) => JSON.stringify([\"task-frame\", taskFrame!.origins[index], index]));\n\t\t\tfor (const [index, frame] of frames.entries()) {\n\t\t\t\tunitSources.set(frame, {\n\t\t\t\t\tid: frameIds[index],\n\t\t\t\t\tsourceRevision: frameIds[index],\n\t\t\t\t\tkind: \"task-frame\",\n\t\t\t\t\texactSources: [JSON.stringify(taskFrame.origins[index])],\n\t\t\t\t\trequiredVisibleDependencies: index ? [frameIds[index - 1]] : [],\n\t\t\t\t\tauthority: \"tool-data\",\n\t\t\t\t\ttokenEstimate: null,\n\t\t\t\t\timmutableWithinEpoch: true,\n\t\t\t\t});\n\t\t\t}\n\t\t\tfor (const anchor of taskFrame.anchors) {\n\t\t\t\tif (!anchor || sourceOrder.has(anchor.entryId)) continue;\n\t\t\t\tconst origin = await view.get(anchor.entryId);\n\t\t\t\tif (!origin) throw new Error(\"Task frame insertion source is unavailable\");\n\t\t\t\tsourceOrder.set(anchor.entryId, origin.sequence);\n\t\t\t}\n\t\t\tconst positions = new Map(messages.map((message, index) => [literalSources.get(message)!, index]));\n\t\t\tconst slots = new Map<number, AgentMessage[]>();\n\t\t\tfor (const [index, revision] of revisions.entries()) {\n\t\t\t\tconst anchor = taskFrame.anchors[index];\n\t\t\t\tlet at = 0;\n\t\t\t\tif (anchor) {\n\t\t\t\t\tconst position = positions.get(anchor.entryId);\n\t\t\t\t\tif (position !== undefined) at = position + (anchor.side === \"after\" ? 1 : 0);\n\t\t\t\t\telse {\n\t\t\t\t\t\t// A later retry may omit that assistant. Keep its source slot, not the newest input slot.\n\t\t\t\t\t\tconst ordinal = sourceOrder.get(anchor.entryId);\n\t\t\t\t\t\tif (ordinal === undefined) throw new Error(\"Task frame insertion source is unavailable\");\n\t\t\t\t\t\tat = messages.findIndex((message) => sourceOrder.get(literalSources.get(message)!)! > ordinal);\n\t\t\t\t\t\tif (at < 0) at = messages.length;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst group = slots.get(at) ?? [];\n\t\t\t\tgroup.push(revision);\n\t\t\t\tslots.set(at, group);\n\t\t\t}\n\t\t\tconst literal = messages.splice(0);\n\t\t\tmessages.push(base);\n\t\t\tfor (let at = 0; at <= literal.length; at++) {\n\t\t\t\tmessages.push(...(slots.get(at) ?? []));\n\t\t\t\tif (at < literal.length) messages.push(literal[at]);\n\t\t\t}\n\t\t}\n\t\tif (resource) {\n\t\t\t// Current owned display is regenerated; a stored acceptance marker is never a live view.\n\t\t\tconst at = messages[0] && unitSources.get(messages[0])?.kind === \"task-frame\" ? 1 : 0;\n\t\t\tmessages.splice(at, 0, resource.message);\n\t\t\tunitSources.set(resource.message, resource.unit);\n\t\t}\n\t\tif (selectedSkills.size) {\n\t\t\tconst selections = [...selectedSkills.values()];\n\t\t\tconst content = `Selected Skill versions (canonical source references):\\n${JSON.stringify(\n\t\t\t\tselections.map((skill) => ({\n\t\t\t\t\tname: skill.name,\n\t\t\t\t\tref: skill.view.ref.entryId,\n\t\t\t\t\trevision: skill.view.ref.revision,\n\t\t\t\t\tsourceSessionId: skill.view.source.sessionId,\n\t\t\t\t})),\n\t\t\t)}`;\n\t\t\tconst message = createCustomMessage(\n\t\t\t\t\"base-context-selected-skill-versions\",\n\t\t\t\tcontent,\n\t\t\t\tfalse,\n\t\t\t\tundefined,\n\t\t\t\t\"1970-01-01T00:00:00.000Z\",\n\t\t\t);\n\t\t\tmessages.unshift(message);\n\t\t\tunitSources.set(message, {\n\t\t\t\tid: \"native-selected-skill-versions\",\n\t\t\t\tsourceRevision: JSON.stringify(selections),\n\t\t\t\tkind: \"literal\",\n\t\t\t\texactSources: selections.map((skill) => skill.view.ref.entryId),\n\t\t\t\trequiredVisibleDependencies: [],\n\t\t\t\tauthority: \"tool-data\",\n\t\t\t\ttokenEstimate: null,\n\t\t\t\timmutableWithinEpoch: true,\n\t\t\t});\n\t\t}\n\t\tconst unitLimits = {\n\t\t\tmaxUnits: maxMessages,\n\t\t\tmaxDependencies: Math.min(Number.MAX_SAFE_INTEGER, maxMessages * 4),\n\t\t\tmaxMetadataBytes: maxSourceBytes,\n\t\t};\n\t\tconst sourceUnits = messages.map((message) => {\n\t\t\tconst unit = unitSources.get(message);\n\t\t\tif (!unit) throw new Error(\"Compiled view unit has no captured source\");\n\t\t\treturn unit;\n\t\t});\n\t\tif (selectedSkills.size) {\n\t\t\tconst tailIndex = messages\n\t\t\t\t.map((message, index) => (epochReferences.has(message) ? index : -1))\n\t\t\t\t.filter((index) => index >= 0)\n\t\t\t\t.at(-1);\n\t\t\tif (tailIndex !== undefined) {\n\t\t\t\tconst tail = sourceUnits[tailIndex];\n\t\t\t\tsourceUnits[tailIndex] = {\n\t\t\t\t\t...tail,\n\t\t\t\t\trequiredVisibleDependencies: [\n\t\t\t\t\t\t...new Set([...tail.requiredVisibleDependencies, \"native-selected-skill-versions\"]),\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tconst replayUnits = bindMessageReplayUnits(messages, sourceUnits, unitLimits);\n\t\tconst frozenGroups = checkpoint?.toolContinuations ?? [];\n\t\tconst assistantSequences = messages\n\t\t\t.flatMap((message) => {\n\t\t\t\tconst reference = epochReferences.get(message);\n\t\t\t\treturn message.role === \"assistant\" && reference ? [reference.ref.sequence] : [];\n\t\t\t})\n\t\t\t.sort((left, right) => left - right);\n\t\tconst candidates = messages.flatMap((message, index) => {\n\t\t\tif (message.role !== \"assistant\") return [];\n\t\t\tconst reference = epochReferences.get(message);\n\t\t\tconst prior = frozenGroups.find((group) => group.assistantEntryId === reference?.ref.entryId);\n\t\t\tif (!prior && !replayUnits[index].unavailableDependencies?.some((id) => id.startsWith(\"tool-result:\")))\n\t\t\t\treturn [];\n\t\t\tif (!reference || reference.ref.retention === \"retained-import\")\n\t\t\t\tthrow new Error(\"Tool continuation requires its original assistant source\");\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tmessage,\n\t\t\t\t\tindex,\n\t\t\t\t\treference,\n\t\t\t\t\tprior,\n\t\t\t\t\tnextAssistantSequence:\n\t\t\t\t\t\tassistantSequences.find((sequence) => sequence > reference.ref.sequence) ?? Infinity,\n\t\t\t\t\tunqualifiedIntent: false,\n\t\t\t\t\tintents: new Map<number, Awaited<ReturnType<typeof hydrateCapturedHistoryEntry>>>(),\n\t\t\t\t},\n\t\t\t];\n\t\t});\n\t\tif (frozenGroups.length !== candidates.filter((candidate) => candidate.prior).length)\n\t\t\tthrow new Error(\"Committed tool continuation lost its original group\");\n\t\tif (purpose === \"request\" && candidates.length && (!allowPendingToolPublic || mode === \"off\"))\n\t\t\tthrow new Error(\"Tool continuation requires an enabled native public request boundary\");\n\t\tconst readToolEvidence = async (metadata: IndexedSourceEvent) => {\n\t\t\tconst cached = next.get(metadata.id);\n\t\t\tif (cached?.revision === metadata.revision) return { entry: cached.entry, source: metadata };\n\t\t\tcountBytes(metadata);\n\t\t\treturn hydrateCapturedHistoryEntry(metadata, maxSourceBytes, view.readPayload);\n\t\t};\n\t\tconst acceptIntent = async (metadata: IndexedSourceEvent, selected = candidates) => {\n\t\t\tif (metadata.kind !== \"tool_intent\") return;\n\t\t\tconst hydrated = await readToolEvidence(metadata);\n\t\t\tconst entry = hydrated.entry;\n\t\t\tif (entry.type !== \"tool_intent\") return;\n\t\t\tconst invocation = entry.invocation;\n\t\t\tconst ownerMatch = selected.find((item) => item.reference.ref.entryId === entry.assistant?.entryId);\n\t\t\tconst candidate =\n\t\t\t\townerMatch ??\n\t\t\t\tselected.find(\n\t\t\t\t\t(item) =>\n\t\t\t\t\t\tmetadata.sequence > item.reference.ref.sequence &&\n\t\t\t\t\t\tmetadata.sequence < item.nextAssistantSequence &&\n\t\t\t\t\t\titem.message.content.some(\n\t\t\t\t\t\t\t(part) =>\n\t\t\t\t\t\t\t\tpart.type === \"toolCall\" &&\n\t\t\t\t\t\t\t\tpart.id === invocation.toolCallId &&\n\t\t\t\t\t\t\t\tpart.name === invocation.toolName,\n\t\t\t\t\t\t),\n\t\t\t\t);\n\t\t\tif (!candidate) return;\n\t\t\t// A present but unqualified/copied intent is not an absence of admission.\n\t\t\tif (\n\t\t\t\tmetadata.qualification !== \"native-tool-execution\" ||\n\t\t\t\tmetadata.retention === \"retained-import\" ||\n\t\t\t\tentry.assistant?.sessionId !== view.source.sessionId ||\n\t\t\t\tentry.assistant.sessionFile !== view.source.sessionFile ||\n\t\t\t\tentry.assistant.entryId !== candidate.reference.ref.entryId\n\t\t\t) {\n\t\t\t\tcandidate.unqualifiedIntent = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst call = candidate.message.content.filter((part) => part.type === \"toolCall\")[invocation.sourceOrder];\n\t\t\tif (\n\t\t\t\t!Number.isSafeInteger(invocation.sourceOrder) ||\n\t\t\t\t!call ||\n\t\t\t\tcall.id !== invocation.toolCallId ||\n\t\t\t\tcall.name !== invocation.toolName ||\n\t\t\t\t!invocation.executionId ||\n\t\t\t\tentry.id !== `${invocation.executionId}:intent` ||\n\t\t\t\tmetadata.sequence <= candidate.reference.ref.sequence ||\n\t\t\t\tcandidate.intents.has(invocation.sourceOrder)\n\t\t\t)\n\t\t\t\tthrow new Error(\"Tool continuation has ambiguous original intent\");\n\t\t\tcandidate.intents.set(invocation.sourceOrder, hydrated);\n\t\t};\n\t\tconst absentPrefixes = new Map<string, { source: SourceSnapshotRef; candidates: typeof candidates }>();\n\t\tfor (const candidate of candidates) {\n\t\t\tif (!candidate.prior) continue;\n\t\t\tif (!Array.isArray(candidate.prior.calls)) throw new Error(\"Invalid committed tool continuation\");\n\t\t\tfor (const call of candidate.prior.calls) {\n\t\t\t\tif (call.admission === \"absent\") {\n\t\t\t\t\tif (\n\t\t\t\t\t\tcheckpoint?.renderer !== CONTEXT_INTERRUPTED_TOOL_RENDERER ||\n\t\t\t\t\t\t!call.source ||\n\t\t\t\t\t\tcall.source.sourceSequence < candidate.reference.ref.sequence ||\n\t\t\t\t\t\tcall.intent !== undefined ||\n\t\t\t\t\t\tcall.executionId !== undefined ||\n\t\t\t\t\t\tcall.outcome !== undefined ||\n\t\t\t\t\t\tcall.result !== undefined\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new Error(\"Invalid committed absent tool admission\");\n\t\t\t\t\tconst key = JSON.stringify(call.source);\n\t\t\t\t\tconst prefix = absentPrefixes.get(key) ?? { source: call.source, candidates: [] as typeof candidates };\n\t\t\t\t\tif (!prefix.candidates.includes(candidate)) prefix.candidates.push(candidate);\n\t\t\t\t\tabsentPrefixes.set(key, prefix);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst actual = await view.get(call.intent.id);\n\t\t\t\tif (!actual || actual.revision !== call.intent.revision || actual.sequence !== call.intent.sequence)\n\t\t\t\t\tthrow new Error(\"Committed tool intent is unavailable on this captured branch\");\n\t\t\t\tawait acceptIntent(actual, [candidate]);\n\t\t\t}\n\t\t}\n\t\tconst scanIntents = async (readView: SessionHistoryReadView, selected: typeof candidates) => {\n\t\t\tlet after = Math.min(...selected.map((candidate) => candidate.reference.ref.sequence));\n\t\t\tlet scanned = 0;\n\t\t\tfor (;;) {\n\t\t\t\tconst page = await readView.page(after, Math.min(128, maxMessages - scanned + 1));\n\t\t\t\tscanned += page.events.length;\n\t\t\t\tif (scanned > maxMessages) throw new Error(\"Tool continuation source item budget exceeded\");\n\t\t\t\tif (page.coverage !== \"complete\") throw new Error(\"Tool continuation source coverage is incomplete\");\n\t\t\t\tfor (const metadata of page.events) {\n\t\t\t\t\t// Frozen qualified refs were already checked exactly, not another execution.\n\t\t\t\t\tif (\n\t\t\t\t\t\t!selected.some((candidate) =>\n\t\t\t\t\t\t\t[...candidate.intents.values()].some((intent) => intent.source.id === metadata.id),\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t\t\tawait acceptIntent(metadata, selected);\n\t\t\t\t}\n\t\t\t\tif (page.nextAfter === null) break;\n\t\t\t\tif (page.nextAfter <= after) throw new Error(\"Tool continuation source page did not advance\");\n\t\t\t\tafter = page.nextAfter;\n\t\t\t}\n\t\t};\n\t\tconst newGroups = candidates.filter((candidate) => !candidate.prior);\n\t\tif (newGroups.length) await scanIntents(view, newGroups);\n\t\tfor (const prefix of absentPrefixes.values()) {\n\t\t\tif (!view.atSnapshot) throw new Error(\"Absent tool admission requires its captured source\");\n\t\t\tawait scanIntents(await view.atSnapshot(prefix.source), prefix.candidates);\n\t\t}\n\t\tconst checkAbsentScope = async (candidate: (typeof candidates)[number]) => {\n\t\t\tconst entry = next.get(candidate.reference.ref.entryId)?.entry;\n\t\t\tconst output = entry?.type === \"message\" ? entry.requestOutput : undefined;\n\t\t\t// This correlation limits the public-history scope. It never qualifies a tool owner or outcome.\n\t\t\tif (\n\t\t\t\t!output ||\n\t\t\t\ttypeof output.operationId !== \"string\" ||\n\t\t\t\t!output.operationId ||\n\t\t\t\t!Array.isArray(output.attemptIds) ||\n\t\t\t\toutput.attemptIds.some((id) => typeof id !== \"string\") ||\n\t\t\t\t!output.source ||\n\t\t\t\toutput.source.sessionId !== view.source.sessionId ||\n\t\t\t\toutput.source.sessionFile !== view.source.sessionFile ||\n\t\t\t\t!output.source.persistent ||\n\t\t\t\t!Number.isSafeInteger(output.source.sourceSequence) ||\n\t\t\t\toutput.source.sourceSequence >= candidate.reference.ref.sequence ||\n\t\t\t\t!view.atSnapshot\n\t\t\t)\n\t\t\t\tthrow new Error(\"View-unit replay group is incomplete: original tool owner is unqualified\");\n\t\t\tawait view.atSnapshot(output.source);\n\t\t};\n\t\tconst toolContinuations: ToolContinuationGroup[] = [];\n\t\tconst pendingPublicMessageGroups: number[][] = [];\n\t\tfor (const candidate of candidates) {\n\t\t\tconst toolCalls = candidate.message.content.filter((part) => part.type === \"toolCall\");\n\t\t\tif (\n\t\t\t\t!toolCalls.length ||\n\t\t\t\tcandidate.unqualifiedIntent ||\n\t\t\t\t(candidate.prior && candidate.prior.calls.length !== toolCalls.length)\n\t\t\t)\n\t\t\t\tthrow new Error(\"View-unit replay group is incomplete: original tool owner is unqualified\");\n\t\t\tif (candidate.intents.size !== toolCalls.length) await checkAbsentScope(candidate);\n\t\t\tconst members = [candidate.index];\n\t\t\tconst calls: ToolContinuationGroup[\"calls\"][number][] = [];\n\t\t\tfor (let order = 0; order < toolCalls.length; order++) {\n\t\t\t\tconst intent = candidate.intents.get(order);\n\t\t\t\tconst original = candidate.prior?.calls[order];\n\t\t\t\tif (!intent) {\n\t\t\t\t\tif (original && original.admission !== \"absent\")\n\t\t\t\t\t\tthrow new Error(\"Committed tool intent is unavailable on this captured branch\");\n\t\t\t\t\tif (\n\t\t\t\t\t\tmessages.some((message) => {\n\t\t\t\t\t\t\tconst sequence = epochReferences.get(message)?.ref.sequence;\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\tmessage.role === \"toolResult\" &&\n\t\t\t\t\t\t\t\tmessage.toolCallId === toolCalls[order].id &&\n\t\t\t\t\t\t\t\tsequence !== undefined &&\n\t\t\t\t\t\t\t\tsequence > candidate.reference.ref.sequence &&\n\t\t\t\t\t\t\t\tsequence < candidate.nextAssistantSequence\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new Error(\"Tool outcome lacks its original finalized owner\");\n\t\t\t\t\tcalls.push(original ?? { admission: \"absent\", source: { ...view.source } });\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (original?.admission === \"absent\") throw new Error(\"Committed absent tool admission changed\");\n\t\t\t\tif (intent.entry.type !== \"tool_intent\") throw new Error(\"Invalid native tool intent\");\n\t\t\t\tconst invocation = intent.entry.invocation;\n\t\t\t\tif (\n\t\t\t\t\toriginal &&\n\t\t\t\t\t(original.executionId !== invocation.executionId || original.intent.id !== intent.source.id)\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Committed tool execution identity changed\");\n\t\t\t\tconst actual = await view.get(invocation.executionId);\n\t\t\t\tlet outcome: Exclude<ToolContinuationGroup[\"calls\"][number][\"outcome\"], undefined> = \"outcome_unknown\";\n\t\t\t\tif (actual) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tactual.kind !== \"message\" ||\n\t\t\t\t\t\tactual.retention === \"retained-import\" ||\n\t\t\t\t\t\t(actual.qualification !== \"native-tool-execution\" && actual.qualification !== \"native-recovery\") ||\n\t\t\t\t\t\tactual.sequence <= intent.source.sequence\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new Error(\"Tool outcome lacks its original finalized owner\");\n\t\t\t\t\tconst { entry } = await readToolEvidence(actual);\n\t\t\t\t\tif (\n\t\t\t\t\t\tentry.type !== \"message\" ||\n\t\t\t\t\t\tentry.message.role !== \"toolResult\" ||\n\t\t\t\t\t\tentry.execution?.executionId !== invocation.executionId ||\n\t\t\t\t\t\t!(\"invocationId\" in entry.execution) ||\n\t\t\t\t\t\tentry.execution.invocationId !== intent.source.id ||\n\t\t\t\t\t\tentry.execution.sourceOrder !== order ||\n\t\t\t\t\t\tentry.execution.toolCallId !== invocation.toolCallId ||\n\t\t\t\t\t\tentry.execution.toolName !== invocation.toolName ||\n\t\t\t\t\t\tentry.message.toolCallId !== invocation.toolCallId ||\n\t\t\t\t\t\tentry.message.toolName !== invocation.toolName ||\n\t\t\t\t\t\t![\"not_started\", \"completed\", \"failed\", \"outcome_unknown\"].includes(entry.execution.executionOutcome)\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new Error(\"Tool outcome does not match its original captured intent\");\n\t\t\t\t\toutcome = entry.execution.executionOutcome;\n\t\t\t\t\tconst index = messages.findIndex((message) => {\n\t\t\t\t\t\tconst ref = epochReferences.get(message)?.ref;\n\t\t\t\t\t\treturn ref?.entryId === actual.id && ref.revision === actual.revision;\n\t\t\t\t\t});\n\t\t\t\t\tif (index <= candidate.index)\n\t\t\t\t\t\tthrow new Error(\"Finalized tool outcome is absent from its whole public group\");\n\t\t\t\t\tmembers.push(index);\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\toriginal?.result &&\n\t\t\t\t\t(!actual ||\n\t\t\t\t\t\toriginal.result.id !== actual.id ||\n\t\t\t\t\t\toriginal.result.sequence !== actual.sequence ||\n\t\t\t\t\t\toriginal.result.revision !== actual.revision)\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Committed finalized tool outcome is unavailable on this captured branch\");\n\t\t\t\tcalls.push({\n\t\t\t\t\texecutionId: invocation.executionId,\n\t\t\t\t\tintent: { id: intent.source.id, sequence: intent.source.sequence, revision: intent.source.revision },\n\t\t\t\t\toutcome,\n\t\t\t\t\t...(actual ? { result: { id: actual.id, sequence: actual.sequence, revision: actual.revision } } : {}),\n\t\t\t\t});\n\t\t\t}\n\t\t\ttoolContinuations.push({ assistantEntryId: candidate.reference.ref.entryId, calls });\n\t\t\tpendingPublicMessageGroups.push(members.sort((left, right) => left - right));\n\t\t}\n\t\tconst publicSourceIds = new Set(\n\t\t\tpendingPublicMessageGroups.flatMap((group) =>\n\t\t\t\tgroup.map((index) => epochReferences.get(messages[index])!.ref.entryId),\n\t\t\t),\n\t\t);\n\t\tif (\n\t\t\tcheckpoint?.views.some(\n\t\t\t\t(pinned) =>\n\t\t\t\t\tpinned.rendering === PUBLIC_TOOL_CONTINUATION_RENDERER && !publicSourceIds.has(pinned.ref.entryId),\n\t\t\t)\n\t\t)\n\t\t\tthrow new Error(\"Committed tool rendering has no matching whole-group recipe\");\n\t\tstringifyBoundedJson(toolContinuations, maxSourceBytes);\n\t\tconst units = pendingPublicMessageGroups.length\n\t\t\t? bindMessageReplayUnits(messages, sourceUnits, unitLimits, \"complete-context\", pendingPublicMessageGroups)\n\t\t\t: replayUnits;\n\t\tconst pendingMarkers = new Set(\n\t\t\tpendingPublicMessageGroups.map((group) => `public-tool-continuation:${units[group[0]].id}`),\n\t\t);\n\t\t// Check every ordinary dependency now. Return the original unadmittable units, not native replay permission.\n\t\tcloseViewSelection(\n\t\t\tunits.map((unit) => ({\n\t\t\t\t...unit,\n\t\t\t\tunavailableDependencies: unit.unavailableDependencies?.filter((id) => !pendingMarkers.has(id)),\n\t\t\t})),\n\t\t\tunits.map((unit) => unit.id),\n\t\t\tunitLimits,\n\t\t);\n\t\tconst closedUnits = units;\n\t\tconst messagesByUnit = new Map(units.map((unit, index) => [unit.id, messages[index]]));\n\t\tconst closedMessages = closedUnits.map((unit) => messagesByUnit.get(unit.id)!);\n\t\t// A frozen literal is immutable inside this epoch, not permanently mandatory at its next ACK boundary.\n\t\tconst selectionUnits = sourceUnits.map((unit, index): ViewUnit => {\n\t\t\tconst message = messages[index];\n\t\t\tif (unit.kind !== \"fixed-view\" || message.role !== \"assistant\") return unit;\n\t\t\treturn {\n\t\t\t\t...unit,\n\t\t\t\tkind: message.content.some((part) => part.type === \"toolCall\") ? \"replay-group\" : \"literal\",\n\t\t\t};\n\t\t});\n\t\tcompiledViewUnits.set(closedMessages, {\n\t\t\tunits: closedUnits,\n\t\t\tselection: {\n\t\t\t\tsource: { ...view.source },\n\t\t\t\tunits: selectionUnits,\n\t\t\t\tlimits: unitLimits,\n\t\t\t\t...(mode === \"on\" && (taskFrameRebased || checkpoint) ? { requiresEpoch: true as const } : {}),\n\t\t\t\t...(pendingPublicMessageGroups.length ? { pendingPublicMessageGroups } : {}),\n\t\t\t},\n\t\t});\n\t\tcompiledEpochContexts.set(closedMessages, {\n\t\t\t...(purpose === \"read\" ? { readOnly: true as const } : {}),\n\t\t\tmode,\n\t\t\tsource: { ...view.source },\n\t\t\tcheckpoint,\n\t\t\tcheckpointEntry:\n\t\t\t\tcheckpoint && first.summaryRef\n\t\t\t\t\t? { sessionId: view.source.sessionId, entryId: first.summaryRef.entryId }\n\t\t\t\t\t: undefined,\n\t\t\ttaskFrame,\n\t\t\t...(taskFrameRebased ? { taskFrameRebased: true as const } : {}),\n\t\t\tresourceRevision: resource?.revision,\n\t\t\treferences: closedMessages.map((message) => epochReferences.get(message) ?? null),\n\t\t\t...(selectedSkills.size ? { selectedSkills: [...selectedSkills.values()] } : {}),\n\t\t\t...(toolContinuations.length ? { toolContinuations } : {}),\n\t\t});\n\t\tif (generation !== this.generation) throw new Error(\"Canonical context owner changed during compilation\");\n\t\tthis.entries = next;\n\t\t// A rebased candidate is not the committed prefix. Adopt it from the next ACKed checkpoint.\n\t\tthis.taskFrame = taskFrameRebased ? referenceFrame : taskFrame;\n\t\tthis.taskBoundary = boundary;\n\t\tthis.source = view.source;\n\t\tthis.sourceBytes = sourceBytes;\n\t\tthis.messageCount = messageCount;\n\t\treturn purpose === \"read\" && pendingPublicMessageGroups.length\n\t\t\t? renderToolContinuationWindow(closedMessages).messages\n\t\t\t: closedMessages;\n\t}\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { stringifyBoundedJson } from "./bounded-json.js";
|
|
2
|
-
import { CONTEXT_EPOCH_DETAIL, CONTEXT_EPOCH_RENDERER, CONTEXT_POLICY_EPOCH_RENDERER, CONTEXT_SKILL_EPOCH_RENDERER, CONTEXT_TOOL_EPOCH_RENDERER, CONTEXT_TOOL_SUMMARY_RENDERER, contextEpochMode, readContextEpoch, retainedContextRequestContract, snapshotContextEpoch, } from "./context-epoch.js";
|
|
2
|
+
import { CONTEXT_EPOCH_DETAIL, CONTEXT_EPOCH_RENDERER, CONTEXT_INTERRUPTED_TOOL_RENDERER, CONTEXT_POLICY_EPOCH_RENDERER, CONTEXT_SKILL_EPOCH_RENDERER, CONTEXT_TOOL_EPOCH_RENDERER, CONTEXT_TOOL_SUMMARY_RENDERER, contextEpochMode, readContextEpoch, retainedContextRequestContract, snapshotContextEpoch, } from "./context-epoch.js";
|
|
3
3
|
import { createCompactionSummaryMessage, createCustomMessage } from "./messages.js";
|
|
4
4
|
import { PUBLIC_CONTEXT_RENDERER, PUBLIC_TOOL_CONTINUATION_RENDERER, renderPublicHistory, renderToolContinuation, } from "./public-context.js";
|
|
5
5
|
import { renderResourceView } from "./resource-view.js";
|
|
@@ -261,11 +261,13 @@ export function prepareCanonicalEpoch(messages, selectedUnitIds, representation,
|
|
|
261
261
|
return {
|
|
262
262
|
checkpoint: snapshotContextEpoch({
|
|
263
263
|
version: context.toolContinuations?.length ? 6 : 4,
|
|
264
|
-
renderer: context.
|
|
265
|
-
?
|
|
266
|
-
: context.
|
|
267
|
-
?
|
|
268
|
-
:
|
|
264
|
+
renderer: context.toolContinuations?.some((group) => group.calls.some((call) => call.admission === "absent"))
|
|
265
|
+
? CONTEXT_INTERRUPTED_TOOL_RENDERER
|
|
266
|
+
: context.selectedSkills?.length
|
|
267
|
+
? CONTEXT_SKILL_EPOCH_RENDERER
|
|
268
|
+
: context.toolContinuations?.length
|
|
269
|
+
? CONTEXT_TOOL_EPOCH_RENDERER
|
|
270
|
+
: CONTEXT_EPOCH_RENDERER,
|
|
269
271
|
...(context.selectedSkills?.length ? { selectedSkills: context.selectedSkills } : {}),
|
|
270
272
|
...(context.toolContinuations?.length ? { toolContinuations: context.toolContinuations } : {}),
|
|
271
273
|
source: context.source,
|
|
@@ -349,11 +351,13 @@ export function prepareRecoveryCompaction(messages, firstKeptEntryId, maxBytes)
|
|
|
349
351
|
return;
|
|
350
352
|
return snapshotContextEpoch({
|
|
351
353
|
...(toolGroups.size ? { version: 8, mode: context.mode } : { version: 4 }),
|
|
352
|
-
renderer:
|
|
353
|
-
?
|
|
354
|
-
:
|
|
355
|
-
?
|
|
356
|
-
:
|
|
354
|
+
renderer: context.toolContinuations?.some((group) => group.calls.some((call) => call.admission === "absent"))
|
|
355
|
+
? CONTEXT_INTERRUPTED_TOOL_RENDERER
|
|
356
|
+
: toolGroups.size
|
|
357
|
+
? CONTEXT_TOOL_SUMMARY_RENDERER
|
|
358
|
+
: context.selectedSkills?.length
|
|
359
|
+
? CONTEXT_SKILL_EPOCH_RENDERER
|
|
360
|
+
: CONTEXT_EPOCH_RENDERER,
|
|
357
361
|
...(toolGroups.size ? { toolContinuations: context.toolContinuations } : {}),
|
|
358
362
|
...(context.selectedSkills?.length ? { selectedSkills: context.selectedSkills } : {}),
|
|
359
363
|
source: context.source,
|
|
@@ -947,6 +951,12 @@ export class CanonicalContextCompiler {
|
|
|
947
951
|
}
|
|
948
952
|
const replayUnits = bindMessageReplayUnits(messages, sourceUnits, unitLimits);
|
|
949
953
|
const frozenGroups = checkpoint?.toolContinuations ?? [];
|
|
954
|
+
const assistantSequences = messages
|
|
955
|
+
.flatMap((message) => {
|
|
956
|
+
const reference = epochReferences.get(message);
|
|
957
|
+
return message.role === "assistant" && reference ? [reference.ref.sequence] : [];
|
|
958
|
+
})
|
|
959
|
+
.sort((left, right) => left - right);
|
|
950
960
|
const candidates = messages.flatMap((message, index) => {
|
|
951
961
|
if (message.role !== "assistant")
|
|
952
962
|
return [];
|
|
@@ -962,6 +972,8 @@ export class CanonicalContextCompiler {
|
|
|
962
972
|
index,
|
|
963
973
|
reference,
|
|
964
974
|
prior,
|
|
975
|
+
nextAssistantSequence: assistantSequences.find((sequence) => sequence > reference.ref.sequence) ?? Infinity,
|
|
976
|
+
unqualifiedIntent: false,
|
|
965
977
|
intents: new Map(),
|
|
966
978
|
},
|
|
967
979
|
];
|
|
@@ -977,21 +989,32 @@ export class CanonicalContextCompiler {
|
|
|
977
989
|
countBytes(metadata);
|
|
978
990
|
return hydrateCapturedHistoryEntry(metadata, maxSourceBytes, view.readPayload);
|
|
979
991
|
};
|
|
980
|
-
const acceptIntent = async (metadata) => {
|
|
981
|
-
if (metadata.kind !== "tool_intent"
|
|
982
|
-
metadata.qualification !== "native-tool-execution" ||
|
|
983
|
-
metadata.retention === "retained-import")
|
|
992
|
+
const acceptIntent = async (metadata, selected = candidates) => {
|
|
993
|
+
if (metadata.kind !== "tool_intent")
|
|
984
994
|
return;
|
|
985
995
|
const hydrated = await readToolEvidence(metadata);
|
|
986
996
|
const entry = hydrated.entry;
|
|
987
|
-
if (entry.type !== "tool_intent"
|
|
988
|
-
entry.assistant?.sessionId !== view.source.sessionId ||
|
|
989
|
-
entry.assistant.sessionFile !== view.source.sessionFile)
|
|
997
|
+
if (entry.type !== "tool_intent")
|
|
990
998
|
return;
|
|
991
|
-
const
|
|
999
|
+
const invocation = entry.invocation;
|
|
1000
|
+
const ownerMatch = selected.find((item) => item.reference.ref.entryId === entry.assistant?.entryId);
|
|
1001
|
+
const candidate = ownerMatch ??
|
|
1002
|
+
selected.find((item) => metadata.sequence > item.reference.ref.sequence &&
|
|
1003
|
+
metadata.sequence < item.nextAssistantSequence &&
|
|
1004
|
+
item.message.content.some((part) => part.type === "toolCall" &&
|
|
1005
|
+
part.id === invocation.toolCallId &&
|
|
1006
|
+
part.name === invocation.toolName));
|
|
992
1007
|
if (!candidate)
|
|
993
1008
|
return;
|
|
994
|
-
|
|
1009
|
+
// A present but unqualified/copied intent is not an absence of admission.
|
|
1010
|
+
if (metadata.qualification !== "native-tool-execution" ||
|
|
1011
|
+
metadata.retention === "retained-import" ||
|
|
1012
|
+
entry.assistant?.sessionId !== view.source.sessionId ||
|
|
1013
|
+
entry.assistant.sessionFile !== view.source.sessionFile ||
|
|
1014
|
+
entry.assistant.entryId !== candidate.reference.ref.entryId) {
|
|
1015
|
+
candidate.unqualifiedIntent = true;
|
|
1016
|
+
return;
|
|
1017
|
+
}
|
|
995
1018
|
const call = candidate.message.content.filter((part) => part.type === "toolCall")[invocation.sourceOrder];
|
|
996
1019
|
if (!Number.isSafeInteger(invocation.sourceOrder) ||
|
|
997
1020
|
!call ||
|
|
@@ -1004,33 +1027,49 @@ export class CanonicalContextCompiler {
|
|
|
1004
1027
|
throw new Error("Tool continuation has ambiguous original intent");
|
|
1005
1028
|
candidate.intents.set(invocation.sourceOrder, hydrated);
|
|
1006
1029
|
};
|
|
1030
|
+
const absentPrefixes = new Map();
|
|
1007
1031
|
for (const candidate of candidates) {
|
|
1008
1032
|
if (!candidate.prior)
|
|
1009
1033
|
continue;
|
|
1010
1034
|
if (!Array.isArray(candidate.prior.calls))
|
|
1011
1035
|
throw new Error("Invalid committed tool continuation");
|
|
1012
1036
|
for (const call of candidate.prior.calls) {
|
|
1037
|
+
if (call.admission === "absent") {
|
|
1038
|
+
if (checkpoint?.renderer !== CONTEXT_INTERRUPTED_TOOL_RENDERER ||
|
|
1039
|
+
!call.source ||
|
|
1040
|
+
call.source.sourceSequence < candidate.reference.ref.sequence ||
|
|
1041
|
+
call.intent !== undefined ||
|
|
1042
|
+
call.executionId !== undefined ||
|
|
1043
|
+
call.outcome !== undefined ||
|
|
1044
|
+
call.result !== undefined)
|
|
1045
|
+
throw new Error("Invalid committed absent tool admission");
|
|
1046
|
+
const key = JSON.stringify(call.source);
|
|
1047
|
+
const prefix = absentPrefixes.get(key) ?? { source: call.source, candidates: [] };
|
|
1048
|
+
if (!prefix.candidates.includes(candidate))
|
|
1049
|
+
prefix.candidates.push(candidate);
|
|
1050
|
+
absentPrefixes.set(key, prefix);
|
|
1051
|
+
continue;
|
|
1052
|
+
}
|
|
1013
1053
|
const actual = await view.get(call.intent.id);
|
|
1014
1054
|
if (!actual || actual.revision !== call.intent.revision || actual.sequence !== call.intent.sequence)
|
|
1015
1055
|
throw new Error("Committed tool intent is unavailable on this captured branch");
|
|
1016
|
-
await acceptIntent(actual);
|
|
1056
|
+
await acceptIntent(actual, [candidate]);
|
|
1017
1057
|
}
|
|
1018
1058
|
}
|
|
1019
|
-
const
|
|
1020
|
-
|
|
1021
|
-
let after = Math.min(...newGroups.map((candidate) => candidate.reference.ref.sequence));
|
|
1059
|
+
const scanIntents = async (readView, selected) => {
|
|
1060
|
+
let after = Math.min(...selected.map((candidate) => candidate.reference.ref.sequence));
|
|
1022
1061
|
let scanned = 0;
|
|
1023
1062
|
for (;;) {
|
|
1024
|
-
const page = await
|
|
1063
|
+
const page = await readView.page(after, Math.min(128, maxMessages - scanned + 1));
|
|
1025
1064
|
scanned += page.events.length;
|
|
1026
1065
|
if (scanned > maxMessages)
|
|
1027
1066
|
throw new Error("Tool continuation source item budget exceeded");
|
|
1028
1067
|
if (page.coverage !== "complete")
|
|
1029
1068
|
throw new Error("Tool continuation source coverage is incomplete");
|
|
1030
1069
|
for (const metadata of page.events) {
|
|
1031
|
-
// Frozen
|
|
1032
|
-
if (!
|
|
1033
|
-
await acceptIntent(metadata);
|
|
1070
|
+
// Frozen qualified refs were already checked exactly, not another execution.
|
|
1071
|
+
if (!selected.some((candidate) => [...candidate.intents.values()].some((intent) => intent.source.id === metadata.id)))
|
|
1072
|
+
await acceptIntent(metadata, selected);
|
|
1034
1073
|
}
|
|
1035
1074
|
if (page.nextAfter === null)
|
|
1036
1075
|
break;
|
|
@@ -1038,23 +1077,69 @@ export class CanonicalContextCompiler {
|
|
|
1038
1077
|
throw new Error("Tool continuation source page did not advance");
|
|
1039
1078
|
after = page.nextAfter;
|
|
1040
1079
|
}
|
|
1080
|
+
};
|
|
1081
|
+
const newGroups = candidates.filter((candidate) => !candidate.prior);
|
|
1082
|
+
if (newGroups.length)
|
|
1083
|
+
await scanIntents(view, newGroups);
|
|
1084
|
+
for (const prefix of absentPrefixes.values()) {
|
|
1085
|
+
if (!view.atSnapshot)
|
|
1086
|
+
throw new Error("Absent tool admission requires its captured source");
|
|
1087
|
+
await scanIntents(await view.atSnapshot(prefix.source), prefix.candidates);
|
|
1041
1088
|
}
|
|
1089
|
+
const checkAbsentScope = async (candidate) => {
|
|
1090
|
+
const entry = next.get(candidate.reference.ref.entryId)?.entry;
|
|
1091
|
+
const output = entry?.type === "message" ? entry.requestOutput : undefined;
|
|
1092
|
+
// This correlation limits the public-history scope. It never qualifies a tool owner or outcome.
|
|
1093
|
+
if (!output ||
|
|
1094
|
+
typeof output.operationId !== "string" ||
|
|
1095
|
+
!output.operationId ||
|
|
1096
|
+
!Array.isArray(output.attemptIds) ||
|
|
1097
|
+
output.attemptIds.some((id) => typeof id !== "string") ||
|
|
1098
|
+
!output.source ||
|
|
1099
|
+
output.source.sessionId !== view.source.sessionId ||
|
|
1100
|
+
output.source.sessionFile !== view.source.sessionFile ||
|
|
1101
|
+
!output.source.persistent ||
|
|
1102
|
+
!Number.isSafeInteger(output.source.sourceSequence) ||
|
|
1103
|
+
output.source.sourceSequence >= candidate.reference.ref.sequence ||
|
|
1104
|
+
!view.atSnapshot)
|
|
1105
|
+
throw new Error("View-unit replay group is incomplete: original tool owner is unqualified");
|
|
1106
|
+
await view.atSnapshot(output.source);
|
|
1107
|
+
};
|
|
1042
1108
|
const toolContinuations = [];
|
|
1043
1109
|
const pendingPublicMessageGroups = [];
|
|
1044
1110
|
for (const candidate of candidates) {
|
|
1045
1111
|
const toolCalls = candidate.message.content.filter((part) => part.type === "toolCall");
|
|
1046
1112
|
if (!toolCalls.length ||
|
|
1047
|
-
candidate.
|
|
1113
|
+
candidate.unqualifiedIntent ||
|
|
1048
1114
|
(candidate.prior && candidate.prior.calls.length !== toolCalls.length))
|
|
1049
1115
|
throw new Error("View-unit replay group is incomplete: original tool owner is unqualified");
|
|
1116
|
+
if (candidate.intents.size !== toolCalls.length)
|
|
1117
|
+
await checkAbsentScope(candidate);
|
|
1050
1118
|
const members = [candidate.index];
|
|
1051
1119
|
const calls = [];
|
|
1052
1120
|
for (let order = 0; order < toolCalls.length; order++) {
|
|
1053
1121
|
const intent = candidate.intents.get(order);
|
|
1122
|
+
const original = candidate.prior?.calls[order];
|
|
1123
|
+
if (!intent) {
|
|
1124
|
+
if (original && original.admission !== "absent")
|
|
1125
|
+
throw new Error("Committed tool intent is unavailable on this captured branch");
|
|
1126
|
+
if (messages.some((message) => {
|
|
1127
|
+
const sequence = epochReferences.get(message)?.ref.sequence;
|
|
1128
|
+
return (message.role === "toolResult" &&
|
|
1129
|
+
message.toolCallId === toolCalls[order].id &&
|
|
1130
|
+
sequence !== undefined &&
|
|
1131
|
+
sequence > candidate.reference.ref.sequence &&
|
|
1132
|
+
sequence < candidate.nextAssistantSequence);
|
|
1133
|
+
}))
|
|
1134
|
+
throw new Error("Tool outcome lacks its original finalized owner");
|
|
1135
|
+
calls.push(original ?? { admission: "absent", source: { ...view.source } });
|
|
1136
|
+
continue;
|
|
1137
|
+
}
|
|
1138
|
+
if (original?.admission === "absent")
|
|
1139
|
+
throw new Error("Committed absent tool admission changed");
|
|
1054
1140
|
if (intent.entry.type !== "tool_intent")
|
|
1055
1141
|
throw new Error("Invalid native tool intent");
|
|
1056
1142
|
const invocation = intent.entry.invocation;
|
|
1057
|
-
const original = candidate.prior?.calls[order];
|
|
1058
1143
|
if (original &&
|
|
1059
1144
|
(original.executionId !== invocation.executionId || original.intent.id !== intent.source.id))
|
|
1060
1145
|
throw new Error("Committed tool execution identity changed");
|