@ponythewhite/base-context 1.0.12 → 1.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/base-context-runtime/pyproject.toml +1 -1
  3. package/dist/base-context-runtime/uv.lock +1 -1
  4. package/dist/build-info.json +1 -1
  5. package/dist/bundle/amazon-bedrock.js +3 -3
  6. package/dist/bundle/{anthropic-BJVPUMPB.js → anthropic-AXUXEET7.js} +1 -1
  7. package/dist/bundle/{azure-openai-responses-ERRMAXK6.js → azure-openai-responses-J3NTJKEO.js} +2 -2
  8. package/dist/bundle/{bundled-modules-WCGPZI2H.js → bundled-modules-UODO7ZR7.js} +5 -5
  9. package/dist/bundle/{chunk-FOGKLC7V.js → chunk-72LSQYUV.js} +1 -1
  10. package/dist/bundle/{chunk-MUFZODP5.js → chunk-EGFIZABJ.js} +1 -1
  11. package/dist/bundle/{chunk-AEMRBMI2.js → chunk-IEM74GZ5.js} +9 -9
  12. package/dist/bundle/{chunk-25VYRAC6.js → chunk-JKKXN6JE.js} +72 -0
  13. package/dist/bundle/{chunk-IAKHCQA2.js → chunk-NLRWERWA.js} +37 -32
  14. package/dist/bundle/{chunk-YGV3Y4AD.js → chunk-SX7CAXWU.js} +23 -5
  15. package/dist/bundle/{chunk-Q6UAHLII.js → chunk-V6LOBH6X.js} +2 -2
  16. package/dist/bundle/{cli-main-CTYDQHFE.js → cli-main-6GXXIMQQ.js} +4 -4
  17. package/dist/bundle/cli.js +1 -1
  18. package/dist/bundle/{google-4GA4YMUX.js → google-QLKV2ZLC.js} +2 -2
  19. package/dist/bundle/{google-vertex-7AMALD7D.js → google-vertex-UGLUZV6B.js} +2 -2
  20. package/dist/bundle/{main-GVGK354K.js → main-HF64B4HM.js} +5 -5
  21. package/dist/bundle/{mistral-74BXMNRM.js → mistral-2ITSLHYF.js} +1 -1
  22. package/dist/bundle/{openai-codex-responses-COXNC4IH.js → openai-codex-responses-FRREQXS3.js} +5 -4
  23. package/dist/bundle/{openai-completions-BCSA5Q6S.js → openai-completions-HF6UPPLW.js} +1 -1
  24. package/dist/bundle/{openai-responses-ONCIZSJS.js → openai-responses-LRTMBDFW.js} +2 -2
  25. package/dist/core/agent-session.d.ts.map +1 -1
  26. package/dist/core/agent-session.js +6 -1
  27. package/dist/core/agent-session.js.map +1 -1
  28. package/dist/core/autonomous.d.ts +2 -0
  29. package/dist/core/autonomous.d.ts.map +1 -1
  30. package/dist/core/autonomous.js +4 -0
  31. package/dist/core/autonomous.js.map +1 -1
  32. package/dist/core/canonical-context.d.ts.map +1 -1
  33. package/dist/core/canonical-context.js +7 -0
  34. package/dist/core/canonical-context.js.map +1 -1
  35. package/dist/core/compaction/compaction.d.ts.map +1 -1
  36. package/dist/core/compaction/compaction.js +1 -1
  37. package/dist/core/compaction/compaction.js.map +1 -1
  38. package/dist/core/public-context.d.ts.map +1 -1
  39. package/dist/core/public-context.js +2 -0
  40. package/dist/core/public-context.js.map +1 -1
  41. package/dist/core/view-units.d.ts.map +1 -1
  42. package/dist/core/view-units.js +3 -0
  43. package/dist/core/view-units.js.map +1 -1
  44. package/dist/main.d.ts.map +1 -1
  45. package/dist/main.js +1 -1
  46. package/dist/main.js.map +1 -1
  47. package/dist/modes/daemon/daemon-mode.d.ts.map +1 -1
  48. package/dist/modes/daemon/daemon-mode.js +4 -3
  49. package/dist/modes/daemon/daemon-mode.js.map +1 -1
  50. package/dist/modes/daemon/daemon-supervisor.d.ts.map +1 -1
  51. package/dist/modes/daemon/daemon-supervisor.js +11 -5
  52. package/dist/modes/daemon/daemon-supervisor.js.map +1 -1
  53. package/dist/modes/daemon/daemon-worker-protocol.d.ts +3 -0
  54. package/dist/modes/daemon/daemon-worker-protocol.d.ts.map +1 -1
  55. package/dist/modes/daemon/daemon-worker-protocol.js +2 -0
  56. package/dist/modes/daemon/daemon-worker-protocol.js.map +1 -1
  57. package/dist/modes/print-mode.d.ts.map +1 -1
  58. package/dist/modes/print-mode.js +24 -21
  59. package/dist/modes/print-mode.js.map +1 -1
  60. package/docs/compaction.md +36 -7
  61. package/docs/context-management.md +16 -10
  62. package/docs/json.md +14 -1
  63. package/docs/long-running-agents.md +23 -2
  64. package/docs/providers.md +17 -0
  65. package/docs/settings.md +20 -11
  66. package/package.json +4 -4
@@ -1 +1 @@
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;IAC9B,qGAAqG;IACrG,QAAQ,CAAC,yBAAyB,CAAC,EAAE,IAAI,CAAC;CAC1C;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,uGAAuG;IACvG,QAAQ,CAAC,yBAAyB,CAAC,EAAE,SAAS,kBAAkB,EAAE,CAAC;IACnE,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,iGAAiG;AACjG,qBAAa,kCAAmC,SAAQ,KAAK;IAC5D,cAGC;CACD;AAED,qGAAqG;AACrG,MAAM,WAAW,+BAA+B;IAC/C,QAAQ,CAAC,MAAM,EAAE,iBAAiB,CAAC;IACnC,QAAQ,CAAC,UAAU,EAAE,SAAS,kBAAkB,EAAE,CAAC;IACnD,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IACnC,QAAQ,CAAC,YAAY,EAAE,OAAO,CAAC;IAC/B,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,OAAO,CAAC;CACzC;AAwBD,sGAAsG;AACtG,wBAAgB,yBAAyB,CACxC,QAAQ,EAAE,SAAS,YAAY,EAAE,EACjC,aAAa,CAAC,EAAE,+BAA+B,GAC7C,MAAM,GAAG,SAAS,CA0CpB;AAED,+GAA+G;AAC/G,wBAAgB,yBAAyB,CACxC,QAAQ,EAAE,SAAS,YAAY,EAAE,EACjC,gBAAgB,EAAE,MAAM,EACxB,QAAQ,EAAE,MAAM,EAChB,aAAa,CAAC,EAAE,+BAA+B,GAC7C,sBAAsB,GAAG,SAAS,CA8EpC;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,CAm9BzB;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\t/** Ask the actual adapter to record replay permission; unsupported full replay remains unchanged. */\n\treadonly recoveryContractRequested?: 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/** Exact retained recovery members of a qualified summary's frozen source, not a sequence interval. */\n\treadonly inheritedRecoveryCoverage?: readonly EpochViewReference[];\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/** Missing prerequisite only; source, closure and projection failures remain ordinary errors. */\nexport class MissingRecoveryReplayContractError extends Error {\n\tconstructor() {\n\t\tsuper(\"Recovery compaction requires an accepted replay contract for its selected results\");\n\t\tthis.name = \"MissingRecoveryReplayContractError\";\n\t}\n}\n\n/** Compaction-only permission captured from a validated native candidate, never a send admission. */\nexport interface RecoveryCompactionAuthorization {\n\treadonly source: SourceSnapshotRef;\n\treadonly recoveries: readonly EpochViewReference[];\n\treadonly resourceRevision?: string;\n\treadonly publicWindow: boolean;\n\treadonly isSourceCurrent?: () => boolean;\n}\n\nfunction sameRecoverySource(left: SourceSnapshotRef, right: SourceSnapshotRef, ownerStillCurrent = false): boolean {\n\treturn (\n\t\tJSON.stringify(left) === JSON.stringify(right) ||\n\t\t(ownerStillCurrent &&\n\t\t\tleft.sessionId === right.sessionId &&\n\t\t\tleft.sessionFile === right.sessionFile &&\n\t\t\tleft.persistent === right.persistent)\n\t);\n}\n\nfunction sameRecoveryReference(\n\tleft: EpochViewReference,\n\tright: EpochViewReference,\n\townerStillCurrent = false,\n): boolean {\n\treturn (\n\t\tsameRecoverySource(left.source, right.source, ownerStillCurrent) &&\n\t\tJSON.stringify(left.ref) === JSON.stringify(right.ref) &&\n\t\tleft.sourceRevision === right.sourceRevision\n\t);\n}\n\n/** Use accepted coverage, or the exact actual-projection permit of a rejected oversized candidate. */\nexport function canonicalRecoveryBoundary(\n\tmessages: readonly AgentMessage[],\n\tauthorization?: RecoveryCompactionAuthorization,\n): 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\tif (authorization) {\n\t\t// The captured native owner may certify bookkeeping-only appends, never new context or a branch change.\n\t\tconst ownerStillCurrent = authorization.isSourceCurrent?.();\n\t\tif (\n\t\t\townerStillCurrent === false ||\n\t\t\t!sameRecoverySource(context.source, authorization.source, ownerStillCurrent === true) ||\n\t\t\tcontext.resourceRevision !== authorization.resourceRevision ||\n\t\t\trecoveries.length !== authorization.recoveries.length ||\n\t\t\trecoveries.some(\n\t\t\t\t(reference) =>\n\t\t\t\t\t!reference ||\n\t\t\t\t\t!authorization.recoveries.some((covered) =>\n\t\t\t\t\t\tsameRecoveryReference(reference, covered, ownerStillCurrent === true),\n\t\t\t\t\t),\n\t\t\t)\n\t\t)\n\t\t\tthrow new Error(\"Recovery compaction authorization no longer matches its captured source\");\n\t\treturn latestLiteralReference(context.references)?.ref.entryId;\n\t}\n\tconst checkpoint = context.checkpoint;\n\tconst inherited = checkpoint?.includeSummary === true && checkpoint.replayContract === \"message-groups\";\n\tif (\n\t\tcheckpoint?.replayContract !== \"message-groups\" ||\n\t\trecoveries.some(\n\t\t\t(reference) =>\n\t\t\t\t!reference ||\n\t\t\t\t(checkpoint.representation\n\t\t\t\t\t? reference.ref.sequence > checkpoint.source.sourceSequence\n\t\t\t\t\t: !inherited ||\n\t\t\t\t\t\t!context.inheritedRecoveryCoverage?.some((covered) => sameRecoveryReference(reference, covered))),\n\t\t)\n\t)\n\t\tthrow new MissingRecoveryReplayContractError();\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\tauthorization?: RecoveryCompactionAuthorization,\n): ContextEpochCheckpoint | undefined {\n\tconst boundary = canonicalRecoveryBoundary(messages, authorization);\n\tconst context = compiledEpochContexts.get(messages);\n\tconst publicWindow = authorization\n\t\t? authorization.publicWindow\n\t\t: context?.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...(mode === \"on\" && sourceUnits.some((unit) => unit.kind === \"recovery\")\n\t\t\t\t\t? { recoveryContractRequested: true as const }\n\t\t\t\t\t: {}),\n\t\t\t\t...(pendingPublicMessageGroups.length ? { pendingPublicMessageGroups } : {}),\n\t\t\t},\n\t\t});\n\t\tconst inheritedRecoveryCoverage: EpochViewReference[] = [];\n\t\tif (\n\t\t\tcheckpoint?.includeSummary &&\n\t\t\tcheckpoint.replayContract === \"message-groups\" &&\n\t\t\tclosedUnits.some((unit) => unit.kind === \"recovery\")\n\t\t) {\n\t\t\tconst prefix = await view.atSnapshot!(checkpoint.source);\n\t\t\tconst suffix = new Map<string, ContextRef>();\n\t\t\tconst frozenViews = new Map<string, EpochViewReference>();\n\t\t\tlet capturedMessages = 0;\n\t\t\tlet retained = false;\n\t\t\tlet cursor: ContextManifestCursor | undefined;\n\t\t\tfor (;;) {\n\t\t\t\tconst page = await prefix.contextManifest({ cursor, limit: 128 });\n\t\t\t\tif (page.selection !== \"known\") throw new Error(\"Summary recovery source is unavailable\");\n\t\t\t\tif (!cursor && page.summaryRef) {\n\t\t\t\t\t// The frozen source may itself have pinned views before its literal manifest.\n\t\t\t\t\tconst entry = await hydrate(page.summaryRef, undefined, prefix);\n\t\t\t\t\tconst metadata = await prefix.get(page.summaryRef.entryId);\n\t\t\t\t\tconst prior =\n\t\t\t\t\t\tentry.type === \"compaction\" &&\n\t\t\t\t\t\tmetadata?.qualification === \"native-context-epoch\" &&\n\t\t\t\t\t\tmetadata.retention !== \"retained-import\"\n\t\t\t\t\t\t\t? readContextEpoch(entry.details, maxSourceBytes)\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\tif ((!prior || prior.includeSummary) && page.summaryRef.entryId === checkpoint.literalTailId)\n\t\t\t\t\t\tretained = true;\n\t\t\t\t\tcapturedMessages += prior?.views.length ?? 0;\n\t\t\t\t\tfor (const pinned of prior?.views ?? []) {\n\t\t\t\t\t\tif (pinned.ref.entryId === checkpoint.literalTailId) retained = true;\n\t\t\t\t\t\tif (retained) {\n\t\t\t\t\t\t\tsuffix.set(pinned.ref.entryId, pinned.ref);\n\t\t\t\t\t\t\tfrozenViews.set(pinned.ref.entryId, pinned);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (const ref of page.refs) {\n\t\t\t\t\tif (ref.entryId === checkpoint.literalTailId) retained = true;\n\t\t\t\t\tif (retained) suffix.set(ref.entryId, ref);\n\t\t\t\t}\n\t\t\t\tcapturedMessages += page.refs.length;\n\t\t\t\tif (capturedMessages > maxMessages) throw new Error(\"Summary recovery source exceeds its message budget\");\n\t\t\t\tif (!page.nextCursor) break;\n\t\t\t\tcursor = page.nextCursor;\n\t\t\t}\n\t\t\tfor (const [index, message] of closedMessages.entries()) {\n\t\t\t\tif (closedUnits[index].kind !== \"recovery\") continue;\n\t\t\t\tconst reference = epochReferences.get(message)!;\n\t\t\t\tif (checkpoint.views.some((covered) => sameRecoveryReference(reference, covered))) {\n\t\t\t\t\tinheritedRecoveryCoverage.push(reference);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst frozen = suffix.get(reference.ref.entryId);\n\t\t\t\tif (!frozen || JSON.stringify(frozen) !== JSON.stringify(reference.ref)) continue;\n\t\t\t\tconst pinned = frozenViews.get(frozen.entryId);\n\t\t\t\tif (pinned) {\n\t\t\t\t\tif (reference.sourceRevision === pinned.sourceRevision) inheritedRecoveryCoverage.push(reference);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst revisions = [frozen.revision];\n\t\t\t\tconst entry = next.get(frozen.entryId)?.entry;\n\t\t\t\tif (\n\t\t\t\t\tentry?.type === \"message\" &&\n\t\t\t\t\tentry.message.role === \"toolResult\" &&\n\t\t\t\t\tentry.message.toolName === \"ipython\"\n\t\t\t\t) {\n\t\t\t\t\tconst updates = await prefix.contextUpdates({\n\t\t\t\t\t\tkind: \"ipython-sent-message\",\n\t\t\t\t\t\ttoolCallId: entry.message.toolCallId,\n\t\t\t\t\t});\n\t\t\t\t\trevisions.push(...updates.refs.map((update) => update.revision));\n\t\t\t\t}\n\t\t\t\tif (reference.sourceRevision === JSON.stringify(revisions)) inheritedRecoveryCoverage.push(reference);\n\t\t\t}\n\t\t}\n\t\tcompiledEpochContexts.set(closedMessages, {\n\t\t\t...(inheritedRecoveryCoverage.length ? { inheritedRecoveryCoverage } : {}),\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":"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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_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\t/** Ask the actual adapter to record replay permission; unsupported full replay remains unchanged. */\n\treadonly recoveryContractRequested?: 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/** Exact retained recovery members of a qualified summary's frozen source, not a sequence interval. */\n\treadonly inheritedRecoveryCoverage?: readonly EpochViewReference[];\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\tif (message.role === \"assistant\" && (message.stopReason === \"error\" || message.stopReason === \"aborted\"))\n\t\t\tcontinue;\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/** Missing prerequisite only; source, closure and projection failures remain ordinary errors. */\nexport class MissingRecoveryReplayContractError extends Error {\n\tconstructor() {\n\t\tsuper(\"Recovery compaction requires an accepted replay contract for its selected results\");\n\t\tthis.name = \"MissingRecoveryReplayContractError\";\n\t}\n}\n\n/** Compaction-only permission captured from a validated native candidate, never a send admission. */\nexport interface RecoveryCompactionAuthorization {\n\treadonly source: SourceSnapshotRef;\n\treadonly recoveries: readonly EpochViewReference[];\n\treadonly resourceRevision?: string;\n\treadonly publicWindow: boolean;\n\treadonly isSourceCurrent?: () => boolean;\n}\n\nfunction sameRecoverySource(left: SourceSnapshotRef, right: SourceSnapshotRef, ownerStillCurrent = false): boolean {\n\treturn (\n\t\tJSON.stringify(left) === JSON.stringify(right) ||\n\t\t(ownerStillCurrent &&\n\t\t\tleft.sessionId === right.sessionId &&\n\t\t\tleft.sessionFile === right.sessionFile &&\n\t\t\tleft.persistent === right.persistent)\n\t);\n}\n\nfunction sameRecoveryReference(\n\tleft: EpochViewReference,\n\tright: EpochViewReference,\n\townerStillCurrent = false,\n): boolean {\n\treturn (\n\t\tsameRecoverySource(left.source, right.source, ownerStillCurrent) &&\n\t\tJSON.stringify(left.ref) === JSON.stringify(right.ref) &&\n\t\tleft.sourceRevision === right.sourceRevision\n\t);\n}\n\n/** Use accepted coverage, or the exact actual-projection permit of a rejected oversized candidate. */\nexport function canonicalRecoveryBoundary(\n\tmessages: readonly AgentMessage[],\n\tauthorization?: RecoveryCompactionAuthorization,\n): 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\tif (authorization) {\n\t\t// The captured native owner may certify bookkeeping-only appends, never new context or a branch change.\n\t\tconst ownerStillCurrent = authorization.isSourceCurrent?.();\n\t\tif (\n\t\t\townerStillCurrent === false ||\n\t\t\t!sameRecoverySource(context.source, authorization.source, ownerStillCurrent === true) ||\n\t\t\tcontext.resourceRevision !== authorization.resourceRevision ||\n\t\t\trecoveries.length !== authorization.recoveries.length ||\n\t\t\trecoveries.some(\n\t\t\t\t(reference) =>\n\t\t\t\t\t!reference ||\n\t\t\t\t\t!authorization.recoveries.some((covered) =>\n\t\t\t\t\t\tsameRecoveryReference(reference, covered, ownerStillCurrent === true),\n\t\t\t\t\t),\n\t\t\t)\n\t\t)\n\t\t\tthrow new Error(\"Recovery compaction authorization no longer matches its captured source\");\n\t\treturn latestLiteralReference(context.references)?.ref.entryId;\n\t}\n\tconst checkpoint = context.checkpoint;\n\tconst inherited = checkpoint?.includeSummary === true && checkpoint.replayContract === \"message-groups\";\n\tif (\n\t\tcheckpoint?.replayContract !== \"message-groups\" ||\n\t\trecoveries.some(\n\t\t\t(reference) =>\n\t\t\t\t!reference ||\n\t\t\t\t(checkpoint.representation\n\t\t\t\t\t? reference.ref.sequence > checkpoint.source.sourceSequence\n\t\t\t\t\t: !inherited ||\n\t\t\t\t\t\t!context.inheritedRecoveryCoverage?.some((covered) => sameRecoveryReference(reference, covered))),\n\t\t)\n\t)\n\t\tthrow new MissingRecoveryReplayContractError();\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\tauthorization?: RecoveryCompactionAuthorization,\n): ContextEpochCheckpoint | undefined {\n\tconst boundary = canonicalRecoveryBoundary(messages, authorization);\n\tconst context = compiledEpochContexts.get(messages);\n\tconst publicWindow = authorization\n\t\t? authorization.publicWindow\n\t\t: context?.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\t// Older summaries can retain an absent-call plan for a failed, provider-filtered reply.\n\t\t\t// Validate its captured absence above, but keep that reply only in canonical history.\n\t\t\tif (\n\t\t\t\t(candidate.message.stopReason === \"error\" || candidate.message.stopReason === \"aborted\") &&\n\t\t\t\tcalls.every((call) => call.admission === \"absent\")\n\t\t\t)\n\t\t\t\tcontinue;\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...(mode === \"on\" && sourceUnits.some((unit) => unit.kind === \"recovery\")\n\t\t\t\t\t? { recoveryContractRequested: true as const }\n\t\t\t\t\t: {}),\n\t\t\t\t...(pendingPublicMessageGroups.length ? { pendingPublicMessageGroups } : {}),\n\t\t\t},\n\t\t});\n\t\tconst inheritedRecoveryCoverage: EpochViewReference[] = [];\n\t\tif (\n\t\t\tcheckpoint?.includeSummary &&\n\t\t\tcheckpoint.replayContract === \"message-groups\" &&\n\t\t\tclosedUnits.some((unit) => unit.kind === \"recovery\")\n\t\t) {\n\t\t\tconst prefix = await view.atSnapshot!(checkpoint.source);\n\t\t\tconst suffix = new Map<string, ContextRef>();\n\t\t\tconst frozenViews = new Map<string, EpochViewReference>();\n\t\t\tlet capturedMessages = 0;\n\t\t\tlet retained = false;\n\t\t\tlet cursor: ContextManifestCursor | undefined;\n\t\t\tfor (;;) {\n\t\t\t\tconst page = await prefix.contextManifest({ cursor, limit: 128 });\n\t\t\t\tif (page.selection !== \"known\") throw new Error(\"Summary recovery source is unavailable\");\n\t\t\t\tif (!cursor && page.summaryRef) {\n\t\t\t\t\t// The frozen source may itself have pinned views before its literal manifest.\n\t\t\t\t\tconst entry = await hydrate(page.summaryRef, undefined, prefix);\n\t\t\t\t\tconst metadata = await prefix.get(page.summaryRef.entryId);\n\t\t\t\t\tconst prior =\n\t\t\t\t\t\tentry.type === \"compaction\" &&\n\t\t\t\t\t\tmetadata?.qualification === \"native-context-epoch\" &&\n\t\t\t\t\t\tmetadata.retention !== \"retained-import\"\n\t\t\t\t\t\t\t? readContextEpoch(entry.details, maxSourceBytes)\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\tif ((!prior || prior.includeSummary) && page.summaryRef.entryId === checkpoint.literalTailId)\n\t\t\t\t\t\tretained = true;\n\t\t\t\t\tcapturedMessages += prior?.views.length ?? 0;\n\t\t\t\t\tfor (const pinned of prior?.views ?? []) {\n\t\t\t\t\t\tif (pinned.ref.entryId === checkpoint.literalTailId) retained = true;\n\t\t\t\t\t\tif (retained) {\n\t\t\t\t\t\t\tsuffix.set(pinned.ref.entryId, pinned.ref);\n\t\t\t\t\t\t\tfrozenViews.set(pinned.ref.entryId, pinned);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (const ref of page.refs) {\n\t\t\t\t\tif (ref.entryId === checkpoint.literalTailId) retained = true;\n\t\t\t\t\tif (retained) suffix.set(ref.entryId, ref);\n\t\t\t\t}\n\t\t\t\tcapturedMessages += page.refs.length;\n\t\t\t\tif (capturedMessages > maxMessages) throw new Error(\"Summary recovery source exceeds its message budget\");\n\t\t\t\tif (!page.nextCursor) break;\n\t\t\t\tcursor = page.nextCursor;\n\t\t\t}\n\t\t\tfor (const [index, message] of closedMessages.entries()) {\n\t\t\t\tif (closedUnits[index].kind !== \"recovery\") continue;\n\t\t\t\tconst reference = epochReferences.get(message)!;\n\t\t\t\tif (checkpoint.views.some((covered) => sameRecoveryReference(reference, covered))) {\n\t\t\t\t\tinheritedRecoveryCoverage.push(reference);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst frozen = suffix.get(reference.ref.entryId);\n\t\t\t\tif (!frozen || JSON.stringify(frozen) !== JSON.stringify(reference.ref)) continue;\n\t\t\t\tconst pinned = frozenViews.get(frozen.entryId);\n\t\t\t\tif (pinned) {\n\t\t\t\t\tif (reference.sourceRevision === pinned.sourceRevision) inheritedRecoveryCoverage.push(reference);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst revisions = [frozen.revision];\n\t\t\t\tconst entry = next.get(frozen.entryId)?.entry;\n\t\t\t\tif (\n\t\t\t\t\tentry?.type === \"message\" &&\n\t\t\t\t\tentry.message.role === \"toolResult\" &&\n\t\t\t\t\tentry.message.toolName === \"ipython\"\n\t\t\t\t) {\n\t\t\t\t\tconst updates = await prefix.contextUpdates({\n\t\t\t\t\t\tkind: \"ipython-sent-message\",\n\t\t\t\t\t\ttoolCallId: entry.message.toolCallId,\n\t\t\t\t\t});\n\t\t\t\t\trevisions.push(...updates.refs.map((update) => update.revision));\n\t\t\t\t}\n\t\t\t\tif (reference.sourceRevision === JSON.stringify(revisions)) inheritedRecoveryCoverage.push(reference);\n\t\t\t}\n\t\t}\n\t\tcompiledEpochContexts.set(closedMessages, {\n\t\t\t...(inheritedRecoveryCoverage.length ? { inheritedRecoveryCoverage } : {}),\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"]}
@@ -117,6 +117,8 @@ export function preparePublicContextWindow(messages, firstMessageIndex = 0) {
117
117
  for (const [index, message] of captured.entries()) {
118
118
  if (index < firstMessageIndex || (message.role !== "assistant" && message.role !== "toolResult"))
119
119
  continue;
120
+ if (message.role === "assistant" && (message.stopReason === "error" || message.stopReason === "aborted"))
121
+ continue;
120
122
  // Public v1 has no media representation. Do not disturb an otherwise valid native request.
121
123
  if (message.content.some((part) => !["text", "toolCall", "thinking"].includes(part.type)))
122
124
  return;
@@ -1223,6 +1225,11 @@ export class CanonicalContextCompiler {
1223
1225
  ...(actual ? { result: { id: actual.id, sequence: actual.sequence, revision: actual.revision } } : {}),
1224
1226
  });
1225
1227
  }
1228
+ // Older summaries can retain an absent-call plan for a failed, provider-filtered reply.
1229
+ // Validate its captured absence above, but keep that reply only in canonical history.
1230
+ if ((candidate.message.stopReason === "error" || candidate.message.stopReason === "aborted") &&
1231
+ calls.every((call) => call.admission === "absent"))
1232
+ continue;
1226
1233
  toolContinuations.push({ assistantEntryId: candidate.reference.ref.entryId, calls });
1227
1234
  pendingPublicMessageGroups.push(members.sort((left, right) => left - right));
1228
1235
  }