@ponythewhite/base-context 1.0.8 → 1.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/dist/base-context-runtime/pyproject.toml +1 -1
- package/dist/base-context-runtime/uv.lock +1 -1
- package/dist/build-info.json +1 -1
- package/dist/bundle/{bundled-modules-IGMJH2MU.js → bundled-modules-MX6YNAM2.js} +2 -2
- package/dist/bundle/{chunk-EXEFSSF4.js → chunk-CDXQNS5P.js} +176 -37
- package/dist/bundle/{chunk-RVJVXZCS.js → chunk-UHLGPYMI.js} +20 -40
- package/dist/bundle/{cli-main-BUK7QTHO.js → cli-main-D7W3WWCV.js} +2 -2
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/{main-2FWHT2WZ.js → main-5J3QBZ5Y.js} +2 -2
- package/dist/core/agent-session.d.ts +3 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +48 -5
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/canonical-context.d.ts.map +1 -1
- package/dist/core/canonical-context.js +115 -30
- package/dist/core/canonical-context.js.map +1 -1
- package/dist/core/context-epoch.d.ts +14 -3
- package/dist/core/context-epoch.d.ts.map +1 -1
- package/dist/core/context-epoch.js +5 -1
- package/dist/core/context-epoch.js.map +1 -1
- package/dist/core/inference-coordinator.d.ts +1 -1
- package/dist/core/inference-coordinator.d.ts.map +1 -1
- package/dist/core/inference-coordinator.js +2 -2
- package/dist/core/inference-coordinator.js.map +1 -1
- package/dist/core/public-context.d.ts.map +1 -1
- package/dist/core/public-context.js +20 -8
- package/dist/core/public-context.js.map +1 -1
- package/dist/core/request-view-selection.d.ts +4 -2
- package/dist/core/request-view-selection.d.ts.map +1 -1
- package/dist/core/request-view-selection.js +7 -4
- package/dist/core/request-view-selection.js.map +1 -1
- package/dist/core/session-manager.d.ts +2 -0
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +38 -13
- package/dist/core/session-manager.js.map +1 -1
- package/dist/modes/daemon/daemon-mode.d.ts.map +1 -1
- package/dist/modes/daemon/daemon-mode.js +15 -30
- package/dist/modes/daemon/daemon-mode.js.map +1 -1
- package/dist/modes/daemon/daemon-socket.d.ts +5 -0
- package/dist/modes/daemon/daemon-socket.d.ts.map +1 -1
- package/dist/modes/daemon/daemon-socket.js +19 -0
- package/dist/modes/daemon/daemon-socket.js.map +1 -1
- package/dist/modes/daemon/daemon-supervisor.d.ts.map +1 -1
- package/dist/modes/daemon/daemon-supervisor.js +6 -7
- package/dist/modes/daemon/daemon-supervisor.js.map +1 -1
- package/dist/modes/daemon/daemon-worker-client.d.ts.map +1 -1
- package/dist/modes/daemon/daemon-worker-client.js +5 -5
- package/dist/modes/daemon/daemon-worker-client.js.map +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request-view-selection.d.ts","sourceRoot":"","sources":["../../src/core/request-view-selection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AACrE,OAAO,EACN,KAAK,OAAO,EACZ,KAAK,yBAAyB,EAE9B,KAAK,6BAA6B,EAClC,KAAK,sBAAsB,EAC3B,uBAAuB,EACvB,KAAK,2BAA2B,EAEhC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACN,KAAK,4BAA4B,EAMjC,MAAM,wBAAwB,CAAC;AAEhC,OAAO,KAAK,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAGnF,wFAAwF;AACxF,qBAAa,wBAAyB,SAAQ,uBAAuB;;IAgBnE,QAAQ,CAAC,kBAAkB,EAAE,sBAAsB;IACnD,QAAQ,CAAC,mBAAmB,CAAC;IAC7B,QAAQ,CAAC,wBAAwB;IAjBlC,QAAQ,CAAC,MAAM,EAAE,iBAAiB,CAAC;IAInC,sBAAsB,CAAC,QAAQ,EAAE,WAAW,CAAC,MA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E,2BAA2B,GAAG,SAAS,EAC/C,WAAW,EAAE,OAAO,EACpB,mBAAmB,CAAC,EAAE,CACrB,OAAO,EAAE,6BAA6B,EACtC,UAAU,EAAE,sBAAsB,GAAG,SAAS,KAC1C,OAAO,CAAC,sBAAsB,GAAG,SAAS,CAAC,GAC9C,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAwP7B","sourcesContent":["import type { AgentMessage } from \"@ponythewhite/base-context-agent\";\nimport {\n\ttype Context,\n\ttype ProviderRequestProjection,\n\ttype ProviderRequestPublicMessage,\n\ttype ProviderRequestRepresentation,\n\ttype RequestTokenAssessment,\n\tRequestTokenBudgetError,\n\ttype RequestTokenBudgetEvaluator,\n\twithRequestBody,\n} from \"@ponythewhite/base-context-ai\";\nimport {\n\ttype CanonicalViewSelectionSource,\n\tcaptureCanonicalRequestMessages,\n\tgetCanonicalEpochContext,\n\tgetCanonicalViewSelectionSource,\n\tpreparePublicContextWindow,\n\tprepareToolContinuationWindow,\n} from \"./canonical-context.js\";\nimport { convertToLlm } from \"./messages.js\";\nimport type { ContextEpochEntryRef, SourceSnapshotRef } from \"./request-events.js\";\nimport { bindMessageReplayUnits, closeViewSelection, prepareViewSelection } from \"./view-units.js\";\n\n/** Actual adapter-public measurement, not a verdict about the opaque native request. */\nexport class PublicContextBudgetError extends RequestTokenBudgetError {\n\treadonly source: SourceSnapshotRef;\n\t#compactionKey?: string;\n\t#summaryCapacity?: (retained: ReadonlySet<string>, wrapper: string) => number | undefined;\n\n\tremainingSummaryTokens(retained: ReadonlySet<string>, wrapper: string): number | undefined {\n\t\treturn this.#summaryCapacity?.(retained, wrapper);\n\t}\n\n\tgetCompactionKey(): string | undefined {\n\t\treturn this.#compactionKey;\n\t}\n\n\tconstructor(\n\t\tsource: SourceSnapshotRef,\n\t\tassessment: RequestTokenAssessment,\n\t\treadonly originalAssessment: RequestTokenAssessment,\n\t\treadonly mandatoryAssessment?: RequestTokenAssessment,\n\t\treadonly taskFrameRebaseAvailable = false,\n\t\tcompactionKey?: string,\n\t\tsummaryCapacity?: (retained: ReadonlySet<string>, wrapper: string) => number | undefined,\n\t) {\n\t\tsuper(assessment);\n\t\tthis.name = \"PublicContextBudgetError\";\n\t\tif (mandatoryAssessment?.status === \"over-budget\")\n\t\t\tthis.message =\n\t\t\t\t\"Context capacity exceeded: instructions, tools, mandatory evidence and output allowance cannot fit. Summarizing unrelated history cannot resolve this request.\";\n\t\tthis.source = Object.freeze({ ...source });\n\t\tthis.#compactionKey = compactionKey;\n\t\tthis.#summaryCapacity = summaryCapacity;\n\t}\n}\n\nexport interface RequestViewCandidate {\n\t/** Session-local Responses ID namespace; a new owner requires a fresh representation. */\n\treadonly responseItemIdentity?: string;\n\treadonly source: SourceSnapshotRef;\n\treadonly selectedUnitIds: readonly string[];\n\treadonly request: ProviderRequestRepresentation;\n\treadonly projection: ProviderRequestProjection;\n\t// Absent only for mandatory full-view admission without a configured token budget.\n\treadonly assessment: RequestTokenAssessment | undefined;\n\treadonly originalAssessment: RequestTokenAssessment | undefined;\n\t/** Exact public messages represented by the accepted candidate, with captured source recipes. */\n\treadonly publicMessages?: readonly AgentMessage[];\n}\n\n/** Root resolves only after its canonical epoch checkpoint ACK. This module owns no epoch state. */\nexport type RequestViewCommit = (\n\tcandidate: RequestViewCandidate,\n) => Promise<ContextEpochEntryRef | undefined> | Promise<void>;\nexport type RequestViewValidate = (\n\trequest: ProviderRequestRepresentation,\n\tassessment: RequestTokenAssessment | undefined,\n) => void;\n\nexport type RequestViewFixedPrepare = (\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tassessment: RequestTokenAssessment | undefined,\n) => ContextEpochEntryRef | void | Promise<ContextEpochEntryRef | undefined> | Promise<void>;\n\nexport interface CapturedRequestViewBoundary extends CanonicalViewSelectionSource {\n\treadonly responseItemIdentity?: string;\n\treadonly messages: readonly AgentMessage[];\n\t/** Provider logical positions mapped to the unchanged canonical messages/units. */\n\treadonly providerMessageIndices: readonly number[];\n\treadonly providerPendingPublicMessageGroups?: readonly (readonly number[])[];\n\treadonly commit: RequestViewCommit;\n\treadonly validate?: RequestViewValidate;\n\treadonly fixedPrepare?: RequestViewFixedPrepare;\n}\n\nexport function captureRequestViewBoundary(\n\tmessages: readonly AgentMessage[],\n\tcommit: RequestViewCommit,\n\tvalidate?: RequestViewValidate,\n\tfixedPrepare?: RequestViewFixedPrepare,\n): CapturedRequestViewBoundary {\n\tconst source = getCanonicalViewSelectionSource(messages);\n\tif (!source) throw new Error(\"Request view boundary requires compiled canonical messages\");\n\tconst providerMessageIndices = messages.flatMap((message, index) => convertToLlm([message]).map(() => index));\n\treturn {\n\t\t...source,\n\t\tmessages: captureCanonicalRequestMessages(messages),\n\t\tproviderMessageIndices,\n\t\t...(source.pendingPublicMessageGroups\n\t\t\t? {\n\t\t\t\t\tproviderPendingPublicMessageGroups: source.pendingPublicMessageGroups.map((group) =>\n\t\t\t\t\t\tgroup.map((index) => providerMessageIndex(providerMessageIndices, index)),\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t\tcommit,\n\t\tvalidate,\n\t\tfixedPrepare,\n\t};\n}\n\nfunction providerMessageIndex(indices: readonly number[], canonicalIndex: number): number {\n\tconst index = indices.indexOf(canonicalIndex);\n\tif (index < 0) throw new Error(\"Provider projection cannot address a filtered canonical message\");\n\treturn index;\n}\n\n/** Keep canonical UI barriers while translating the native serializer's provider-only positions. */\nfunction canonicalRequestProjection(\n\tboundary: CapturedRequestViewBoundary,\n\tprojection: ProviderRequestProjection,\n): ProviderRequestProjection {\n\tconst indices = boundary.providerMessageIndices;\n\tif (indices.length === boundary.messages.length) return projection;\n\tconst canonicalIndex = (index: number): number => {\n\t\tconst canonical = indices[index];\n\t\tif (canonical === undefined) throw new Error(\"Provider projection message index is outside its captured view\");\n\t\treturn canonical;\n\t};\n\treturn {\n\t\t...projection,\n\t\tmessageIndices: projection.messageIndices.map((index) => (index === null ? null : canonicalIndex(index))),\n\t\t...(projection.optionalMessageIndices\n\t\t\t? { optionalMessageIndices: projection.optionalMessageIndices.map(canonicalIndex) }\n\t\t\t: {}),\n\t\t...(projection.generatedMessageIndices\n\t\t\t? { generatedMessageIndices: projection.generatedMessageIndices.map(canonicalIndex) }\n\t\t\t: {}),\n\t\t...(projection.publicMessageGroups\n\t\t\t? { publicMessageGroups: projection.publicMessageGroups.map((group) => group.map(canonicalIndex)) }\n\t\t\t: {}),\n\t\t...(projection.pendingPublicMessageGroups\n\t\t\t? {\n\t\t\t\t\tpendingPublicMessageGroups: projection.pendingPublicMessageGroups.map((group) =>\n\t\t\t\t\t\tgroup.map(canonicalIndex),\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t\t...(projection.encodePublicWindow\n\t\t\t? {\n\t\t\t\t\tencodePublicWindow: (replacements: readonly ProviderRequestPublicMessage[]) => {\n\t\t\t\t\t\tconst encoded = projection.encodePublicWindow!(\n\t\t\t\t\t\t\treplacements.map((replacement) => ({\n\t\t\t\t\t\t\t\t...replacement,\n\t\t\t\t\t\t\t\tmessageIndex: providerMessageIndex(indices, replacement.messageIndex),\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\tencoded && { ...encoded, projection: canonicalRequestProjection(boundary, encoded.projection) }\n\t\t\t\t\t\t);\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\nexport function matchesRequestView(\n\tboundary: CapturedRequestViewBoundary,\n\tsource: SourceSnapshotRef,\n\tcontext: Context,\n): boolean {\n\tconst expected = boundary.source;\n\tif (\n\t\texpected.sessionId !== source.sessionId ||\n\t\texpected.sessionFile !== source.sessionFile ||\n\t\texpected.leafId !== source.leafId ||\n\t\texpected.sourceSequence !== source.sourceSequence\n\t)\n\t\treturn false;\n\tconst rendered = convertToLlm([...boundary.messages]);\n\treturn (\n\t\tboundary.messages.length === boundary.units.length &&\n\t\trendered.length === boundary.providerMessageIndices.length &&\n\t\tJSON.stringify(rendered) === JSON.stringify(context.messages)\n\t);\n}\n\n/** Projection kinds describe their actual provider body, never an OpenAI-format route alias. */\nfunction requestInputKey(\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n): \"input\" | \"messages\" | undefined {\n\tif (\n\t\t(request.api === \"openai-responses\" || request.api === \"openai-codex-responses\") &&\n\t\t(projection.kind === \"openai-responses-text-v1\" || projection.kind === \"openai-responses-replay-v1\")\n\t)\n\t\treturn \"input\";\n\tif (\n\t\trequest.api === \"openai-completions\" &&\n\t\trequest.provider === \"deepseek\" &&\n\t\trequest.url === \"https://api.deepseek.com/chat/completions\" &&\n\t\tprojection.kind === \"deepseek-completions-text-tools-v1\" &&\n\t\trequest.body !== undefined &&\n\t\tJSON.parse(request.body).model === \"deepseek-flash\"\n\t)\n\t\treturn \"messages\";\n\treturn undefined;\n}\n\n/** A lower bound for compaction: fixed policy, current tail and required recorded evidence. */\nfunction publicBudgetFailure(\n\tboundary: CapturedRequestViewBoundary,\n\tmessages: readonly AgentMessage[],\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tbudget: RequestTokenBudgetEvaluator,\n\tassessment: RequestTokenAssessment,\n\toriginal: RequestTokenAssessment,\n): PublicContextBudgetError {\n\tconst context = getCanonicalEpochContext(messages)!;\n\tconst source = getCanonicalViewSelectionSource(messages)!;\n\tconst toolEntries = new Set(\n\t\tcontext.toolContinuations?.flatMap((group) => [\n\t\t\tgroup.assistantEntryId,\n\t\t\t...group.calls.flatMap((call) => (call.result ? [call.result.id] : [])),\n\t\t]),\n\t);\n\tlet tailSequence = -1;\n\tfor (const reference of context.references)\n\t\tif (reference && reference.ref.kind !== \"compaction\")\n\t\t\ttailSequence = Math.max(tailSequence, reference.ref.sequence);\n\tconst required = new Set(\n\t\tsource.units.flatMap((unit, index) => {\n\t\t\tconst reference = context.references[index];\n\t\t\treturn [\"task-frame\", \"resource-view\", \"recovery\"].includes(unit.kind) ||\n\t\t\t\tunit.id === \"native-selected-skill-versions\" ||\n\t\t\t\t(reference && (reference.ref.sequence === tailSequence || toolEntries.has(reference.ref.entryId)))\n\t\t\t\t? [index]\n\t\t\t\t: [];\n\t\t}),\n\t);\n\tconst inputKey = requestInputKey(request, projection)!;\n\tconst body = JSON.parse(request.body!) as Record<string, unknown>;\n\tconst input = body[inputKey];\n\tif (!Array.isArray(input) || input.length !== projection.messageIndices.length)\n\t\treturn new PublicContextBudgetError(boundary.source, assessment, original);\n\tconst graph = prepareViewSelection(source.units, boundary.limits);\n\tconst retainedInput = (retained: ReadonlySet<string>) => {\n\t\tconst roots = source.units\n\t\t\t.filter((_, index) => required.has(index) || retained.has(context.references[index]?.ref.entryId ?? \"\"))\n\t\t\t.map((unit) => unit.id);\n\t\tconst selected = new Set(graph.close(roots).map((unit) => unit.id));\n\t\treturn input.filter((_, index) => {\n\t\t\tconst messageIndex = projection.messageIndices[index];\n\t\t\treturn messageIndex === null || selected.has(source.units[messageIndex].id);\n\t\t});\n\t};\n\tconst minimum = withRequestBody(request, JSON.stringify({ ...body, [inputKey]: retainedInput(new Set()) }));\n\treturn new PublicContextBudgetError(\n\t\tboundary.source,\n\t\tassessment,\n\t\toriginal,\n\t\tbudget.measure(minimum),\n\t\t(context.taskFrame?.messages.length ?? 0) > 1,\n\t\tJSON.stringify([\n\t\t\tboundary.source.sessionId,\n\t\t\tboundary.source.sessionFile,\n\t\t\tsource.units.map((unit) => [unit.id, unit.sourceRevision]),\n\t\t\tassessment.api,\n\t\t\tassessment.provider,\n\t\t\tassessment.model,\n\t\t\tassessment.route,\n\t\t\tassessment.profile,\n\t\t\tassessment.availableInputTokens,\n\t\t\tassessment.outputReserveTokens,\n\t\t]),\n\t\t(retained, wrapper) => {\n\t\t\t// Meter only; this synthetic empty summary is never admitted or sent.\n\t\t\tconst summary =\n\t\t\t\tinputKey === \"messages\"\n\t\t\t\t\t? { role: \"user\", content: wrapper }\n\t\t\t\t\t: { role: \"user\", content: [{ type: \"input_text\", text: wrapper }] };\n\t\t\tconst kept = retainedInput(retained);\n\t\t\tconst position = kept.findIndex((item) => item?.role !== \"system\" && item?.role !== \"developer\");\n\t\t\tkept.splice(position < 0 ? kept.length : position, 0, summary);\n\t\t\tconst measured = budget.measure(withRequestBody(request, JSON.stringify({ ...body, [inputKey]: kept })));\n\t\t\treturn measured.status === \"unknown\" ||\n\t\t\t\tmeasured.availableInputTokens === null ||\n\t\t\t\tmeasured.estimatedInputTokens === null\n\t\t\t\t? undefined\n\t\t\t\t: Math.floor(measured.availableInputTokens - measured.estimatedInputTokens);\n\t\t},\n\t);\n}\n\n/** Check the actual final mapping without selecting, converting, or committing another view. */\nexport async function prepareFixedRequestView(\n\tboundary: CapturedRequestViewBoundary,\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tassessment: RequestTokenAssessment | undefined,\n) {\n\tprojection = canonicalRequestProjection(boundary, projection);\n\tconst inputKey = requestInputKey(request, projection);\n\tconst payload = JSON.parse(request.body!) as Record<string, unknown> | null;\n\tconst input = inputKey && payload ? payload[inputKey] : undefined;\n\tif (!Array.isArray(input) || input.length !== projection.messageIndices.length)\n\t\tthrow new Error(\"Fixed context requires its final provider projection\");\n\tif (\n\t\tprojection.kind === \"openai-responses-text-v1\" &&\n\t\tboundary.messages.some(\n\t\t\t(message) =>\n\t\t\t\tmessage.role === \"toolResult\" ||\n\t\t\t\t(message.role === \"assistant\" && (message.content.length !== 1 || message.content[0].type !== \"text\")),\n\t\t)\n\t)\n\t\tthrow new Error(\"Fixed context requires its native replay adapter\");\n\tconst units = bindMessageReplayUnits(\n\t\tboundary.messages,\n\t\tboundary.units,\n\t\tboundary.limits,\n\t\tprojection.replayContract ?? \"complete-context\",\n\t);\n\tcloseViewSelection(\n\t\tunits,\n\t\tunits.map((unit) => unit.id),\n\t\tboundary.limits,\n\t);\n\treturn await boundary.fixedPrepare!(request, projection, assessment);\n}\n\n/** Reuse the same legal omission policy for native and already-converted public requests. */\nasync function offerOptionalSubset(\n\tmessages: readonly AgentMessage[],\n\tunits: CanonicalViewSelectionSource[\"units\"],\n\tselection: ReturnType<typeof prepareViewSelection>,\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tbudget: RequestTokenBudgetEvaluator,\n\toffer: (\n\t\tids: readonly string[],\n\t\trequest: ProviderRequestRepresentation,\n\t\tprojection: ProviderRequestProjection,\n\t\tassessment: RequestTokenAssessment,\n\t) => Promise<unknown>,\n): Promise<string | undefined> {\n\tconst inputKey = requestInputKey(request, projection);\n\tif (!inputKey) return;\n\tconst payload = JSON.parse(request.body!) as Record<string, unknown>;\n\tconst input = payload[inputKey];\n\tif (!Array.isArray(input) || input.length !== projection.messageIndices.length) return;\n\tlet latestAssistant = -1;\n\tfor (const [index, message] of messages.entries()) if (message.role === \"assistant\") latestAssistant = index;\n\tconst retained = new Set(projection.messageIndices.slice(0, request.retainedPrefix?.inputItems ?? 0));\n\tconst projectedOptional =\n\t\tprojection.kind !== \"openai-responses-text-v1\" ? new Set(projection.optionalMessageIndices ?? []) : undefined;\n\tconst optional = units.filter((unit, index) => {\n\t\tconst message = messages[index];\n\t\treturn (\n\t\t\tindex !== latestAssistant &&\n\t\t\t!retained.has(index) &&\n\t\t\t(!projectedOptional || projectedOptional.has(index)) &&\n\t\t\tunit.kind === \"literal\" &&\n\t\t\tunit.authority === \"assistant-public\" &&\n\t\t\tmessage.role === \"assistant\" &&\n\t\t\tmessage.stopReason === \"stop\" &&\n\t\t\tmessage.content.length === 1 &&\n\t\t\tmessage.content[0].type === \"text\"\n\t\t);\n\t});\n\tconst generatedPositions = new Map<string, number>();\n\tconst generated =\n\t\tprojection.generatedMessageIndices ??\n\t\tmessages.flatMap((message, index) =>\n\t\t\tmessage.role === \"assistant\" &&\n\t\t\tmessage.content.some((block) => block.type === \"text\" && block.textSignature === undefined)\n\t\t\t\t? [index]\n\t\t\t\t: [],\n\t\t);\n\tfor (const index of generated) generatedPositions.set(units[index].id, index);\n\t// All user inputs, the latest assistant, fixed/TaskFrame/recovery units and errors stay selected.\n\tconst selected = new Set(units.map((unit) => unit.id));\n\tfor (const unit of optional) {\n\t\tselected.delete(unit.id);\n\t\tconst closed = selection.close([...selected]);\n\t\t// Normal Responses rendering uses msg_<message index> for unsigned assistants.\n\t\t// Reject any subset that would change a retained generated item ID on reconstruction.\n\t\tif (closed.some((item, index) => generatedPositions.has(item.id) && generatedPositions.get(item.id) !== index))\n\t\t\tcontinue;\n\t\tconst closedIds = new Set(closed.map((item) => item.id));\n\t\tconst keepItem = (index: number) => {\n\t\t\tconst messageIndex = projection.messageIndices[index];\n\t\t\treturn messageIndex === null || closedIds.has(units[messageIndex].id);\n\t\t};\n\t\tconst body = JSON.stringify({ ...payload, [inputKey]: input.filter((_, index) => keepItem(index)) });\n\t\tconst candidateRequest = { ...request, body };\n\t\tconst assessment = budget.measure(candidateRequest);\n\t\tif (assessment.status !== \"within-estimate\") continue;\n\t\tawait offer(\n\t\t\tclosed.map((item) => item.id),\n\t\t\tcandidateRequest,\n\t\t\t{\n\t\t\t\t...projection,\n\t\t\t\tmessageIndices: projection.messageIndices.filter((_, index) => keepItem(index)),\n\t\t\t\t...(projection.optionalMessageIndices\n\t\t\t\t\t? {\n\t\t\t\t\t\t\toptionalMessageIndices: projection.optionalMessageIndices.filter((index) =>\n\t\t\t\t\t\t\t\tclosedIds.has(units[index].id),\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...(projection.generatedMessageIndices\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tgeneratedMessageIndices: projection.generatedMessageIndices.filter((index) =>\n\t\t\t\t\t\t\t\tclosedIds.has(units[index].id),\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},\n\t\t\tassessment,\n\t\t);\n\t\treturn body;\n\t}\n\treturn;\n}\n\n/** Only the actual serializer's established replay contract authorizes historical-literal omission. */\nexport async function selectRequestView(\n\tboundary: CapturedRequestViewBoundary,\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tbudget: RequestTokenBudgetEvaluator | undefined,\n\tallowShrink: boolean,\n\tfinalizeMeasurement?: (\n\t\trequest: ProviderRequestRepresentation,\n\t\tassessment: RequestTokenAssessment | undefined,\n\t) => Promise<RequestTokenAssessment | undefined>,\n): Promise<string | undefined> {\n\tprojection = canonicalRequestProjection(boundary, projection);\n\tlet full = budget?.measure(request);\n\tconst inputKey = requestInputKey(request, projection);\n\tif ((budget && full?.limitSource !== \"explicit-profile\") || !inputKey) return;\n\tif (!budget && !boundary.requiresEpoch && !boundary.pendingPublicMessageGroups?.length) return;\n\tconst payload = JSON.parse(request.body!) as Record<string, unknown>;\n\tconst input = payload[inputKey];\n\tif (!Array.isArray(input) || input.length !== projection.messageIndices.length) return;\n\t// Resolve a near-limit estimate before discarding a stable native prefix. Original\n\t// protected tool groups must first pass their public conversion below.\n\tif (\n\t\tfull?.status === \"over-budget\" &&\n\t\t!boundary.pendingPublicMessageGroups?.length &&\n\t\t!projection.pendingPublicMessageGroups?.length\n\t)\n\t\tfull = (await finalizeMeasurement?.(request, full)) ?? full;\n\n\t// Absence is complete-context; a profile or tool-shaped message is never group authority.\n\tconst replayContract = projection.replayContract ?? \"complete-context\";\n\tif (\n\t\tprojection.kind === \"openai-responses-text-v1\" &&\n\t\tboundary.messages.some(\n\t\t\t(message) =>\n\t\t\t\tmessage.role === \"toolResult\" ||\n\t\t\t\t(message.role === \"assistant\" && (message.content.length !== 1 || message.content[0].type !== \"text\")),\n\t\t)\n\t)\n\t\treturn;\n\tconst units = bindMessageReplayUnits(\n\t\tboundary.messages,\n\t\tboundary.units,\n\t\tboundary.limits,\n\t\treplayContract,\n\t\tboundary.pendingPublicMessageGroups,\n\t);\n\tconst selection = prepareViewSelection(units, boundary.limits);\n\tconst offer = async (\n\t\tselectedUnitIds: readonly string[],\n\t\tcandidateRequest: ProviderRequestRepresentation,\n\t\tcandidateProjection: ProviderRequestProjection,\n\t\tassessment: RequestTokenAssessment | undefined,\n\t\tpublicMessages?: readonly AgentMessage[],\n\t) => {\n\t\tassessment = (await finalizeMeasurement?.(candidateRequest, assessment)) ?? assessment;\n\t\tif (budget && assessment) {\n\t\t\tif (assessment.status === \"over-budget\" && full)\n\t\t\t\tthrow publicBudgetFailure(\n\t\t\t\t\tboundary,\n\t\t\t\t\tpublicMessages ?? boundary.messages,\n\t\t\t\t\tcandidateRequest,\n\t\t\t\t\tcandidateProjection,\n\t\t\t\t\tbudget,\n\t\t\t\t\tassessment,\n\t\t\t\t\tfull,\n\t\t\t\t);\n\t\t\tbudget.assert(assessment);\n\t\t}\n\t\treturn boundary.commit(\n\t\t\tObject.freeze({\n\t\t\t\t...(boundary.responseItemIdentity ? { responseItemIdentity: boundary.responseItemIdentity } : {}),\n\t\t\t\tsource: Object.freeze({ ...boundary.source }),\n\t\t\t\tselectedUnitIds: Object.freeze([...selectedUnitIds]),\n\t\t\t\trequest: Object.freeze({ ...candidateRequest }),\n\t\t\t\tprojection: Object.freeze({\n\t\t\t\t\t...candidateProjection,\n\t\t\t\t\treplayContract,\n\t\t\t\t\tmessageIndices: Object.freeze([...candidateProjection.messageIndices]),\n\t\t\t\t\t...(candidateProjection.optionalMessageIndices\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\toptionalMessageIndices: Object.freeze([...candidateProjection.optionalMessageIndices]),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(candidateProjection.generatedMessageIndices\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tgeneratedMessageIndices: Object.freeze([...candidateProjection.generatedMessageIndices]),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t}),\n\t\t\t\tassessment,\n\t\t\t\toriginalAssessment: full,\n\t\t\t\t...(publicMessages ? { publicMessages } : {}),\n\t\t\t}),\n\t\t);\n\t};\n\tconst offerPublicSubset = async (\n\t\tmessages: readonly AgentMessage[],\n\t\trequest: ProviderRequestRepresentation,\n\t\tprojection: ProviderRequestProjection,\n\t): Promise<string | undefined> => {\n\t\tif (!allowShrink || !budget || replayContract !== \"message-groups\") return;\n\t\tconst source = getCanonicalViewSelectionSource(messages)!;\n\t\tconst units = bindMessageReplayUnits(messages, source.units, boundary.limits, replayContract);\n\t\treturn offerOptionalSubset(\n\t\t\tmessages,\n\t\t\tunits,\n\t\t\tprepareViewSelection(units, boundary.limits),\n\t\t\trequest,\n\t\t\tprojection,\n\t\t\tbudget,\n\t\t\t(ids, candidate, mapping, assessment) => offer(ids, candidate, mapping, assessment, messages),\n\t\t);\n\t};\n\tif (boundary.pendingPublicMessageGroups?.length) {\n\t\tif (\n\t\t\treplayContract !== \"message-groups\" ||\n\t\t\t!projection.publicWindow ||\n\t\t\t!projection.encodePublicWindow ||\n\t\t\tJSON.stringify(projection.pendingPublicMessageGroups) !== JSON.stringify(boundary.pendingPublicMessageGroups)\n\t\t)\n\t\t\tthrow new Error(\"Original tool group requires current native adapter public conversion\");\n\t\tconst publicView = prepareToolContinuationWindow(boundary.messages);\n\t\tconst encoded = projection.encodePublicWindow(publicView.replacements);\n\t\tif (!encoded || encoded.projection.pendingPublicMessageGroups?.length)\n\t\t\tthrow new Error(\"Native adapter did not convert the whole required tool group\");\n\t\tconst publicSource = getCanonicalViewSelectionSource(publicView.messages)!;\n\t\tconst publicUnits = bindMessageReplayUnits(\n\t\t\tpublicView.messages,\n\t\t\tpublicSource.units,\n\t\t\tboundary.limits,\n\t\t\treplayContract,\n\t\t);\n\t\tconst closed = closeViewSelection(\n\t\t\tpublicUnits,\n\t\t\tpublicUnits.map((unit) => unit.id),\n\t\t\tboundary.limits,\n\t\t);\n\t\tlet assessment = budget?.measure(encoded.request);\n\t\tif (assessment?.status === \"over-budget\")\n\t\t\tassessment = (await finalizeMeasurement?.(encoded.request, assessment)) ?? assessment;\n\t\tif (assessment && full) {\n\t\t\tif (assessment.status === \"over-budget\") {\n\t\t\t\tconst subset = await offerPublicSubset(publicView.messages, encoded.request, encoded.projection);\n\t\t\t\tif (subset !== undefined) return subset;\n\t\t\t\tthrow publicBudgetFailure(\n\t\t\t\t\tboundary,\n\t\t\t\t\tpublicView.messages,\n\t\t\t\t\tencoded.request,\n\t\t\t\t\tencoded.projection,\n\t\t\t\t\tbudget!,\n\t\t\t\t\tassessment,\n\t\t\t\t\tfull,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (assessment.status !== \"within-estimate\")\n\t\t\t\tthrow new Error(\"Tool continuation public request exceeds its token budget\");\n\t\t}\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\tencoded.request,\n\t\t\tencoded.projection,\n\t\t\tassessment,\n\t\t\tpublicView.messages,\n\t\t);\n\t\treturn encoded.request.body;\n\t}\n\tif (projection.pendingPublicMessageGroups?.length)\n\t\tthrow new Error(\"Adapter pending group has no original owned source plan\");\n\t// Without a configured budget, admit only the exact full native view. Never shrink it.\n\tif (!budget) {\n\t\tconst closed = selection.close(units.map((unit) => unit.id));\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\trequest,\n\t\t\tprojection,\n\t\t\tundefined,\n\t\t);\n\t\treturn request.body;\n\t}\n\tif (!full) return;\n\tconst offerPublicWindow = async (): Promise<string | undefined> => {\n\t\tif (\n\t\t\t!allowShrink ||\n\t\t\treplayContract !== \"message-groups\" ||\n\t\t\t!projection.publicWindow ||\n\t\t\t!projection.encodePublicWindow\n\t\t)\n\t\t\treturn;\n\t\tconst closed = selection.close(units.map((unit) => unit.id));\n\t\tlet firstMessageIndex = 0;\n\t\tif (\n\t\t\tfull.status === \"unknown\" &&\n\t\t\tfull.unknown.length === 1 &&\n\t\t\tfull.unknown[0] === \"media, opaque or unsupported replay token coverage unknown\"\n\t\t) {\n\t\t\t// Credited items are not part of the unknown input. Keep original projection indices.\n\t\t\tconst firstUnmeteredItem = request.retainedPrefix?.inputItems ?? 0;\n\t\t\tconst reasoningItemIndex = input.findIndex(\n\t\t\t\t(item, index) => index >= firstUnmeteredItem && item?.type === \"reasoning\",\n\t\t\t);\n\t\t\tconst messageIndex = projection.messageIndices[reasoningItemIndex];\n\t\t\tconst group =\n\t\t\t\tmessageIndex == null\n\t\t\t\t\t? undefined\n\t\t\t\t\t: projection.publicMessageGroups?.find((members) => members.includes(messageIndex));\n\t\t\t// The adapter still accepts only complete groups; earlier meterable groups stay native.\n\t\t\tfirstMessageIndex = group ? Math.min(...group) : 0;\n\t\t}\n\t\tconst publicView = preparePublicContextWindow(boundary.messages, firstMessageIndex);\n\t\tif (!publicView) {\n\t\t\t// Keep the original measured refusal when no public conversion can be offered.\n\t\t\t// This is not a new recovery signal or permission to reprepare again.\n\t\t\tif (full.status === \"over-budget\") throw new RequestTokenBudgetError(full);\n\t\t\treturn;\n\t\t}\n\t\tconst encoded = projection.encodePublicWindow(publicView.replacements);\n\t\tif (!encoded) return;\n\t\tlet assessment = budget.measure(encoded.request);\n\t\tif (assessment.status === \"over-budget\")\n\t\t\tassessment = (await finalizeMeasurement?.(encoded.request, assessment)) ?? assessment;\n\t\tif (assessment.status === \"over-budget\") {\n\t\t\tconst subset = await offerPublicSubset(publicView.messages, encoded.request, encoded.projection);\n\t\t\tif (subset !== undefined) return subset;\n\t\t\tthrow publicBudgetFailure(\n\t\t\t\tboundary,\n\t\t\t\tpublicView.messages,\n\t\t\t\tencoded.request,\n\t\t\t\tencoded.projection,\n\t\t\t\tbudget,\n\t\t\t\tassessment,\n\t\t\t\tfull,\n\t\t\t);\n\t\t}\n\t\tif (assessment.status !== \"within-estimate\") return;\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\tencoded.request,\n\t\t\tencoded.projection,\n\t\t\tassessment,\n\t\t\tpublicView.messages,\n\t\t);\n\t\treturn encoded.request.body;\n\t};\n\tif (full.status === \"within-estimate\") {\n\t\tconst closed = selection.close(units.map((unit) => unit.id));\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\trequest,\n\t\t\tprojection,\n\t\t\tfull,\n\t\t);\n\t\treturn request.body;\n\t}\n\tif (!allowShrink || replayContract !== \"message-groups\") return;\n\tif (full.status !== \"over-budget\") return offerPublicWindow();\n\tconst subset = await offerOptionalSubset(boundary.messages, units, selection, request, projection, budget, offer);\n\tif (subset !== undefined) return subset;\n\treturn offerPublicWindow();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"request-view-selection.d.ts","sourceRoot":"","sources":["../../src/core/request-view-selection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AACrE,OAAO,EACN,KAAK,OAAO,EACZ,KAAK,yBAAyB,EAE9B,KAAK,6BAA6B,EAClC,KAAK,sBAAsB,EAC3B,uBAAuB,EACvB,KAAK,2BAA2B,EAEhC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACN,KAAK,4BAA4B,EAMjC,MAAM,wBAAwB,CAAC;AAEhC,OAAO,KAAK,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAGnF,wFAAwF;AACxF,qBAAa,wBAAyB,SAAQ,uBAAuB;;IAgBnE,QAAQ,CAAC,kBAAkB,EAAE,sBAAsB;IACnD,QAAQ,CAAC,mBAAmB,CAAC;IAC7B,QAAQ,CAAC,wBAAwB;IAGjC,QAAQ,CAAC,eAAe,CAAC;IApB1B,QAAQ,CAAC,MAAM,EAAE,iBAAiB,CAAC;IAInC,sBAAsB,CAAC,QAAQ,EAAE,WAAW,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAEzF;IAED,gBAAgB,IAAI,MAAM,GAAG,SAAS,CAErC;IAED,YACC,MAAM,EAAE,iBAAiB,EACzB,UAAU,EAAE,sBAAsB,EACzB,kBAAkB,EAAE,sBAAsB,EAC1C,mBAAmB,CAAC,oCAAwB,EAC5C,wBAAwB,UAAQ,EACzC,aAAa,CAAC,E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OAAO,CAAC,sBAAsB,GAAG,SAAS,CAAC,GAC9C,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAwP7B","sourcesContent":["import type { AgentMessage } from \"@ponythewhite/base-context-agent\";\nimport {\n\ttype Context,\n\ttype ProviderRequestProjection,\n\ttype ProviderRequestPublicMessage,\n\ttype ProviderRequestRepresentation,\n\ttype RequestTokenAssessment,\n\tRequestTokenBudgetError,\n\ttype RequestTokenBudgetEvaluator,\n\twithRequestBody,\n} from \"@ponythewhite/base-context-ai\";\nimport {\n\ttype CanonicalViewSelectionSource,\n\tcaptureCanonicalRequestMessages,\n\tgetCanonicalEpochContext,\n\tgetCanonicalViewSelectionSource,\n\tpreparePublicContextWindow,\n\tprepareToolContinuationWindow,\n} from \"./canonical-context.js\";\nimport { convertToLlm } from \"./messages.js\";\nimport type { ContextEpochEntryRef, SourceSnapshotRef } from \"./request-events.js\";\nimport { bindMessageReplayUnits, closeViewSelection, prepareViewSelection } from \"./view-units.js\";\n\n/** Actual adapter-public measurement, not a verdict about the opaque native request. */\nexport class PublicContextBudgetError extends RequestTokenBudgetError {\n\treadonly source: SourceSnapshotRef;\n\t#compactionKey?: string;\n\t#summaryCapacity?: (retained: ReadonlySet<string>, wrapper: string) => number | undefined;\n\n\tremainingSummaryTokens(retained: ReadonlySet<string>, wrapper: string): number | undefined {\n\t\treturn this.#summaryCapacity?.(retained, wrapper);\n\t}\n\n\tgetCompactionKey(): string | undefined {\n\t\treturn this.#compactionKey;\n\t}\n\n\tconstructor(\n\t\tsource: SourceSnapshotRef,\n\t\tassessment: RequestTokenAssessment,\n\t\treadonly originalAssessment: RequestTokenAssessment,\n\t\treadonly mandatoryAssessment?: RequestTokenAssessment,\n\t\treadonly taskFrameRebaseAvailable = false,\n\t\tcompactionKey?: string,\n\t\tsummaryCapacity?: (retained: ReadonlySet<string>, wrapper: string) => number | undefined,\n\t\treadonly isSourceCurrent?: () => boolean,\n\t) {\n\t\tsuper(assessment);\n\t\tthis.name = \"PublicContextBudgetError\";\n\t\tif (mandatoryAssessment?.status === \"over-budget\")\n\t\t\tthis.message =\n\t\t\t\t\"Context capacity exceeded: instructions, tools, mandatory evidence and output allowance cannot fit. Summarizing unrelated history cannot resolve this request.\";\n\t\tthis.source = Object.freeze({ ...source });\n\t\tthis.#compactionKey = compactionKey;\n\t\tthis.#summaryCapacity = summaryCapacity;\n\t}\n}\n\nexport interface RequestViewCandidate {\n\t/** Session-local Responses ID namespace; a new owner requires a fresh representation. */\n\treadonly responseItemIdentity?: string;\n\treadonly source: SourceSnapshotRef;\n\treadonly selectedUnitIds: readonly string[];\n\treadonly request: ProviderRequestRepresentation;\n\treadonly projection: ProviderRequestProjection;\n\t// Absent only for mandatory full-view admission without a configured token budget.\n\treadonly assessment: RequestTokenAssessment | undefined;\n\treadonly originalAssessment: RequestTokenAssessment | undefined;\n\t/** Exact public messages represented by the accepted candidate, with captured source recipes. */\n\treadonly publicMessages?: readonly AgentMessage[];\n}\n\n/** Root resolves only after its canonical epoch checkpoint ACK. This module owns no epoch state. */\nexport type RequestViewCommit = (\n\tcandidate: RequestViewCandidate,\n) => Promise<ContextEpochEntryRef | undefined> | Promise<void>;\nexport type RequestViewValidate = (\n\trequest: ProviderRequestRepresentation,\n\tassessment: RequestTokenAssessment | undefined,\n) => void;\n\nexport type RequestViewFixedPrepare = (\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tassessment: RequestTokenAssessment | undefined,\n) => ContextEpochEntryRef | void | Promise<ContextEpochEntryRef | undefined> | Promise<void>;\n\nexport interface CapturedRequestViewBoundary extends CanonicalViewSelectionSource {\n\treadonly responseItemIdentity?: string;\n\treadonly messages: readonly AgentMessage[];\n\t/** Provider logical positions mapped to the unchanged canonical messages/units. */\n\treadonly providerMessageIndices: readonly number[];\n\treadonly providerPendingPublicMessageGroups?: readonly (readonly number[])[];\n\treadonly commit: RequestViewCommit;\n\treadonly validate?: RequestViewValidate;\n\treadonly fixedPrepare?: RequestViewFixedPrepare;\n\treadonly isSourceCurrent?: () => boolean;\n}\n\nexport function captureRequestViewBoundary(\n\tmessages: readonly AgentMessage[],\n\tcommit: RequestViewCommit,\n\tvalidate?: RequestViewValidate,\n\tfixedPrepare?: RequestViewFixedPrepare,\n\tisSourceCurrent?: () => boolean,\n): CapturedRequestViewBoundary {\n\tconst source = getCanonicalViewSelectionSource(messages);\n\tif (!source) throw new Error(\"Request view boundary requires compiled canonical messages\");\n\tconst providerMessageIndices = messages.flatMap((message, index) => convertToLlm([message]).map(() => index));\n\treturn {\n\t\t...source,\n\t\tmessages: captureCanonicalRequestMessages(messages),\n\t\tproviderMessageIndices,\n\t\t...(source.pendingPublicMessageGroups\n\t\t\t? {\n\t\t\t\t\tproviderPendingPublicMessageGroups: source.pendingPublicMessageGroups.map((group) =>\n\t\t\t\t\t\tgroup.map((index) => providerMessageIndex(providerMessageIndices, index)),\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t\tcommit,\n\t\tvalidate,\n\t\tfixedPrepare,\n\t\tisSourceCurrent,\n\t};\n}\n\nfunction providerMessageIndex(indices: readonly number[], canonicalIndex: number): number {\n\tconst index = indices.indexOf(canonicalIndex);\n\tif (index < 0) throw new Error(\"Provider projection cannot address a filtered canonical message\");\n\treturn index;\n}\n\n/** Keep canonical UI barriers while translating the native serializer's provider-only positions. */\nfunction canonicalRequestProjection(\n\tboundary: CapturedRequestViewBoundary,\n\tprojection: ProviderRequestProjection,\n): ProviderRequestProjection {\n\tconst indices = boundary.providerMessageIndices;\n\tif (indices.length === boundary.messages.length) return projection;\n\tconst canonicalIndex = (index: number): number => {\n\t\tconst canonical = indices[index];\n\t\tif (canonical === undefined) throw new Error(\"Provider projection message index is outside its captured view\");\n\t\treturn canonical;\n\t};\n\treturn {\n\t\t...projection,\n\t\tmessageIndices: projection.messageIndices.map((index) => (index === null ? null : canonicalIndex(index))),\n\t\t...(projection.optionalMessageIndices\n\t\t\t? { optionalMessageIndices: projection.optionalMessageIndices.map(canonicalIndex) }\n\t\t\t: {}),\n\t\t...(projection.generatedMessageIndices\n\t\t\t? { generatedMessageIndices: projection.generatedMessageIndices.map(canonicalIndex) }\n\t\t\t: {}),\n\t\t...(projection.publicMessageGroups\n\t\t\t? { publicMessageGroups: projection.publicMessageGroups.map((group) => group.map(canonicalIndex)) }\n\t\t\t: {}),\n\t\t...(projection.pendingPublicMessageGroups\n\t\t\t? {\n\t\t\t\t\tpendingPublicMessageGroups: projection.pendingPublicMessageGroups.map((group) =>\n\t\t\t\t\t\tgroup.map(canonicalIndex),\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t\t...(projection.encodePublicWindow\n\t\t\t? {\n\t\t\t\t\tencodePublicWindow: (replacements: readonly ProviderRequestPublicMessage[]) => {\n\t\t\t\t\t\tconst encoded = projection.encodePublicWindow!(\n\t\t\t\t\t\t\treplacements.map((replacement) => ({\n\t\t\t\t\t\t\t\t...replacement,\n\t\t\t\t\t\t\t\tmessageIndex: providerMessageIndex(indices, replacement.messageIndex),\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\tencoded && { ...encoded, projection: canonicalRequestProjection(boundary, encoded.projection) }\n\t\t\t\t\t\t);\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\nexport function matchesRequestView(\n\tboundary: CapturedRequestViewBoundary,\n\tsource: SourceSnapshotRef,\n\tcontext: Context,\n): boolean {\n\tconst expected = boundary.source;\n\tif (\n\t\texpected.sessionId !== source.sessionId ||\n\t\texpected.sessionFile !== source.sessionFile ||\n\t\texpected.leafId !== source.leafId ||\n\t\texpected.sourceSequence !== source.sourceSequence\n\t)\n\t\treturn false;\n\tconst rendered = convertToLlm([...boundary.messages]);\n\treturn (\n\t\tboundary.messages.length === boundary.units.length &&\n\t\trendered.length === boundary.providerMessageIndices.length &&\n\t\tJSON.stringify(rendered) === JSON.stringify(context.messages)\n\t);\n}\n\n/** Projection kinds describe their actual provider body, never an OpenAI-format route alias. */\nfunction requestInputKey(\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n): \"input\" | \"messages\" | undefined {\n\tif (\n\t\t(request.api === \"openai-responses\" || request.api === \"openai-codex-responses\") &&\n\t\t(projection.kind === \"openai-responses-text-v1\" || projection.kind === \"openai-responses-replay-v1\")\n\t)\n\t\treturn \"input\";\n\tif (\n\t\trequest.api === \"openai-completions\" &&\n\t\trequest.provider === \"deepseek\" &&\n\t\trequest.url === \"https://api.deepseek.com/chat/completions\" &&\n\t\tprojection.kind === \"deepseek-completions-text-tools-v1\" &&\n\t\trequest.body !== undefined &&\n\t\tJSON.parse(request.body).model === \"deepseek-flash\"\n\t)\n\t\treturn \"messages\";\n\treturn undefined;\n}\n\n/** A lower bound for compaction: fixed policy, current tail and required recorded evidence. */\nfunction publicBudgetFailure(\n\tboundary: CapturedRequestViewBoundary,\n\tmessages: readonly AgentMessage[],\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tbudget: RequestTokenBudgetEvaluator,\n\tassessment: RequestTokenAssessment,\n\toriginal: RequestTokenAssessment,\n): PublicContextBudgetError {\n\tconst context = getCanonicalEpochContext(messages)!;\n\tconst source = getCanonicalViewSelectionSource(messages)!;\n\tconst toolEntries = new Set(\n\t\tcontext.toolContinuations?.flatMap((group) => [\n\t\t\tgroup.assistantEntryId,\n\t\t\t...group.calls.flatMap((call) => (call.result ? [call.result.id] : [])),\n\t\t]),\n\t);\n\tlet tailSequence = -1;\n\tfor (const reference of context.references)\n\t\tif (reference && reference.ref.kind !== \"compaction\")\n\t\t\ttailSequence = Math.max(tailSequence, reference.ref.sequence);\n\tconst required = new Set(\n\t\tsource.units.flatMap((unit, index) => {\n\t\t\tconst reference = context.references[index];\n\t\t\treturn [\"task-frame\", \"resource-view\", \"recovery\"].includes(unit.kind) ||\n\t\t\t\tunit.id === \"native-selected-skill-versions\" ||\n\t\t\t\t(reference && (reference.ref.sequence === tailSequence || toolEntries.has(reference.ref.entryId)))\n\t\t\t\t? [index]\n\t\t\t\t: [];\n\t\t}),\n\t);\n\tconst inputKey = requestInputKey(request, projection)!;\n\tconst body = JSON.parse(request.body!) as Record<string, unknown>;\n\tconst input = body[inputKey];\n\tif (!Array.isArray(input) || input.length !== projection.messageIndices.length)\n\t\treturn new PublicContextBudgetError(\n\t\t\tboundary.source,\n\t\t\tassessment,\n\t\t\toriginal,\n\t\t\tundefined,\n\t\t\tfalse,\n\t\t\tundefined,\n\t\t\tundefined,\n\t\t\tboundary.isSourceCurrent,\n\t\t);\n\tconst graph = prepareViewSelection(source.units, boundary.limits);\n\tconst retainedInput = (retained: ReadonlySet<string>) => {\n\t\tconst roots = source.units\n\t\t\t.filter((_, index) => required.has(index) || retained.has(context.references[index]?.ref.entryId ?? \"\"))\n\t\t\t.map((unit) => unit.id);\n\t\tconst selected = new Set(graph.close(roots).map((unit) => unit.id));\n\t\treturn input.filter((_, index) => {\n\t\t\tconst messageIndex = projection.messageIndices[index];\n\t\t\treturn messageIndex === null || selected.has(source.units[messageIndex].id);\n\t\t});\n\t};\n\tconst minimum = withRequestBody(request, JSON.stringify({ ...body, [inputKey]: retainedInput(new Set()) }));\n\treturn new PublicContextBudgetError(\n\t\tboundary.source,\n\t\tassessment,\n\t\toriginal,\n\t\tbudget.measure(minimum),\n\t\t(context.taskFrame?.messages.length ?? 0) > 1,\n\t\tJSON.stringify([\n\t\t\tboundary.source.sessionId,\n\t\t\tboundary.source.sessionFile,\n\t\t\tsource.units.map((unit) => [unit.id, unit.sourceRevision]),\n\t\t\tassessment.api,\n\t\t\tassessment.provider,\n\t\t\tassessment.model,\n\t\t\tassessment.route,\n\t\t\tassessment.profile,\n\t\t\tassessment.availableInputTokens,\n\t\t\tassessment.outputReserveTokens,\n\t\t]),\n\t\t(retained, wrapper) => {\n\t\t\t// Meter only; this synthetic empty summary is never admitted or sent.\n\t\t\tconst summary =\n\t\t\t\tinputKey === \"messages\"\n\t\t\t\t\t? { role: \"user\", content: wrapper }\n\t\t\t\t\t: { role: \"user\", content: [{ type: \"input_text\", text: wrapper }] };\n\t\t\tconst kept = retainedInput(retained);\n\t\t\tconst position = kept.findIndex((item) => item?.role !== \"system\" && item?.role !== \"developer\");\n\t\t\tkept.splice(position < 0 ? kept.length : position, 0, summary);\n\t\t\tconst measured = budget.measure(withRequestBody(request, JSON.stringify({ ...body, [inputKey]: kept })));\n\t\t\treturn measured.status === \"unknown\" ||\n\t\t\t\tmeasured.availableInputTokens === null ||\n\t\t\t\tmeasured.estimatedInputTokens === null\n\t\t\t\t? undefined\n\t\t\t\t: Math.floor(measured.availableInputTokens - measured.estimatedInputTokens);\n\t\t},\n\t\tboundary.isSourceCurrent,\n\t);\n}\n\n/** Check the actual final mapping without selecting, converting, or committing another view. */\nexport async function prepareFixedRequestView(\n\tboundary: CapturedRequestViewBoundary,\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tassessment: RequestTokenAssessment | undefined,\n) {\n\tprojection = canonicalRequestProjection(boundary, projection);\n\tconst inputKey = requestInputKey(request, projection);\n\tconst payload = JSON.parse(request.body!) as Record<string, unknown> | null;\n\tconst input = inputKey && payload ? payload[inputKey] : undefined;\n\tif (!Array.isArray(input) || input.length !== projection.messageIndices.length)\n\t\tthrow new Error(\"Fixed context requires its final provider projection\");\n\tif (\n\t\tprojection.kind === \"openai-responses-text-v1\" &&\n\t\tboundary.messages.some(\n\t\t\t(message) =>\n\t\t\t\tmessage.role === \"toolResult\" ||\n\t\t\t\t(message.role === \"assistant\" && (message.content.length !== 1 || message.content[0].type !== \"text\")),\n\t\t)\n\t)\n\t\tthrow new Error(\"Fixed context requires its native replay adapter\");\n\tconst units = bindMessageReplayUnits(\n\t\tboundary.messages,\n\t\tboundary.units,\n\t\tboundary.limits,\n\t\tprojection.replayContract ?? \"complete-context\",\n\t);\n\tcloseViewSelection(\n\t\tunits,\n\t\tunits.map((unit) => unit.id),\n\t\tboundary.limits,\n\t);\n\treturn await boundary.fixedPrepare!(request, projection, assessment);\n}\n\n/** Reuse the same legal omission policy for native and already-converted public requests. */\nasync function offerOptionalSubset(\n\tmessages: readonly AgentMessage[],\n\tunits: CanonicalViewSelectionSource[\"units\"],\n\tselection: ReturnType<typeof prepareViewSelection>,\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tbudget: RequestTokenBudgetEvaluator,\n\toffer: (\n\t\tids: readonly string[],\n\t\trequest: ProviderRequestRepresentation,\n\t\tprojection: ProviderRequestProjection,\n\t\tassessment: RequestTokenAssessment,\n\t) => Promise<unknown>,\n): Promise<string | undefined> {\n\tconst inputKey = requestInputKey(request, projection);\n\tif (!inputKey) return;\n\tconst payload = JSON.parse(request.body!) as Record<string, unknown>;\n\tconst input = payload[inputKey];\n\tif (!Array.isArray(input) || input.length !== projection.messageIndices.length) return;\n\tlet latestAssistant = -1;\n\tfor (const [index, message] of messages.entries()) if (message.role === \"assistant\") latestAssistant = index;\n\tconst retained = new Set(projection.messageIndices.slice(0, request.retainedPrefix?.inputItems ?? 0));\n\tconst projectedOptional =\n\t\tprojection.kind !== \"openai-responses-text-v1\" ? new Set(projection.optionalMessageIndices ?? []) : undefined;\n\tconst optional = units.filter((unit, index) => {\n\t\tconst message = messages[index];\n\t\treturn (\n\t\t\tindex !== latestAssistant &&\n\t\t\t!retained.has(index) &&\n\t\t\t(!projectedOptional || projectedOptional.has(index)) &&\n\t\t\tunit.kind === \"literal\" &&\n\t\t\tunit.authority === \"assistant-public\" &&\n\t\t\tmessage.role === \"assistant\" &&\n\t\t\tmessage.stopReason === \"stop\" &&\n\t\t\tmessage.content.length === 1 &&\n\t\t\tmessage.content[0].type === \"text\"\n\t\t);\n\t});\n\tconst generatedPositions = new Map<string, number>();\n\tconst generated =\n\t\tprojection.generatedMessageIndices ??\n\t\tmessages.flatMap((message, index) =>\n\t\t\tmessage.role === \"assistant\" &&\n\t\t\tmessage.content.some((block) => block.type === \"text\" && block.textSignature === undefined)\n\t\t\t\t? [index]\n\t\t\t\t: [],\n\t\t);\n\tfor (const index of generated) generatedPositions.set(units[index].id, index);\n\t// All user inputs, the latest assistant, fixed/TaskFrame/recovery units and errors stay selected.\n\tconst selected = new Set(units.map((unit) => unit.id));\n\tfor (const unit of optional) {\n\t\tselected.delete(unit.id);\n\t\tconst closed = selection.close([...selected]);\n\t\t// Normal Responses rendering uses msg_<message index> for unsigned assistants.\n\t\t// Reject any subset that would change a retained generated item ID on reconstruction.\n\t\tif (closed.some((item, index) => generatedPositions.has(item.id) && generatedPositions.get(item.id) !== index))\n\t\t\tcontinue;\n\t\tconst closedIds = new Set(closed.map((item) => item.id));\n\t\tconst keepItem = (index: number) => {\n\t\t\tconst messageIndex = projection.messageIndices[index];\n\t\t\treturn messageIndex === null || closedIds.has(units[messageIndex].id);\n\t\t};\n\t\tconst body = JSON.stringify({ ...payload, [inputKey]: input.filter((_, index) => keepItem(index)) });\n\t\tconst candidateRequest = { ...request, body };\n\t\tconst assessment = budget.measure(candidateRequest);\n\t\tif (assessment.status !== \"within-estimate\") continue;\n\t\tawait offer(\n\t\t\tclosed.map((item) => item.id),\n\t\t\tcandidateRequest,\n\t\t\t{\n\t\t\t\t...projection,\n\t\t\t\tmessageIndices: projection.messageIndices.filter((_, index) => keepItem(index)),\n\t\t\t\t...(projection.optionalMessageIndices\n\t\t\t\t\t? {\n\t\t\t\t\t\t\toptionalMessageIndices: projection.optionalMessageIndices.filter((index) =>\n\t\t\t\t\t\t\t\tclosedIds.has(units[index].id),\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...(projection.generatedMessageIndices\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tgeneratedMessageIndices: projection.generatedMessageIndices.filter((index) =>\n\t\t\t\t\t\t\t\tclosedIds.has(units[index].id),\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},\n\t\t\tassessment,\n\t\t);\n\t\treturn body;\n\t}\n\treturn;\n}\n\n/** Only the actual serializer's established replay contract authorizes historical-literal omission. */\nexport async function selectRequestView(\n\tboundary: CapturedRequestViewBoundary,\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tbudget: RequestTokenBudgetEvaluator | undefined,\n\tallowShrink: boolean,\n\tfinalizeMeasurement?: (\n\t\trequest: ProviderRequestRepresentation,\n\t\tassessment: RequestTokenAssessment | undefined,\n\t) => Promise<RequestTokenAssessment | undefined>,\n): Promise<string | undefined> {\n\tprojection = canonicalRequestProjection(boundary, projection);\n\tlet full = budget?.measure(request);\n\tconst inputKey = requestInputKey(request, projection);\n\tif ((budget && full?.limitSource !== \"explicit-profile\") || !inputKey) return;\n\tif (!budget && !boundary.requiresEpoch && !boundary.pendingPublicMessageGroups?.length) return;\n\tconst payload = JSON.parse(request.body!) as Record<string, unknown>;\n\tconst input = payload[inputKey];\n\tif (!Array.isArray(input) || input.length !== projection.messageIndices.length) return;\n\t// Resolve a near-limit estimate before discarding a stable native prefix. Original\n\t// protected tool groups must first pass their public conversion below.\n\tif (\n\t\tfull?.status === \"over-budget\" &&\n\t\t!boundary.pendingPublicMessageGroups?.length &&\n\t\t!projection.pendingPublicMessageGroups?.length\n\t)\n\t\tfull = (await finalizeMeasurement?.(request, full)) ?? full;\n\n\t// Absence is complete-context; a profile or tool-shaped message is never group authority.\n\tconst replayContract = projection.replayContract ?? \"complete-context\";\n\tif (\n\t\tprojection.kind === \"openai-responses-text-v1\" &&\n\t\tboundary.messages.some(\n\t\t\t(message) =>\n\t\t\t\tmessage.role === \"toolResult\" ||\n\t\t\t\t(message.role === \"assistant\" && (message.content.length !== 1 || message.content[0].type !== \"text\")),\n\t\t)\n\t)\n\t\treturn;\n\tconst units = bindMessageReplayUnits(\n\t\tboundary.messages,\n\t\tboundary.units,\n\t\tboundary.limits,\n\t\treplayContract,\n\t\tboundary.pendingPublicMessageGroups,\n\t);\n\tconst selection = prepareViewSelection(units, boundary.limits);\n\tconst offer = async (\n\t\tselectedUnitIds: readonly string[],\n\t\tcandidateRequest: ProviderRequestRepresentation,\n\t\tcandidateProjection: ProviderRequestProjection,\n\t\tassessment: RequestTokenAssessment | undefined,\n\t\tpublicMessages?: readonly AgentMessage[],\n\t) => {\n\t\tassessment = (await finalizeMeasurement?.(candidateRequest, assessment)) ?? assessment;\n\t\tif (budget && assessment) {\n\t\t\tif (assessment.status === \"over-budget\" && full)\n\t\t\t\tthrow publicBudgetFailure(\n\t\t\t\t\tboundary,\n\t\t\t\t\tpublicMessages ?? boundary.messages,\n\t\t\t\t\tcandidateRequest,\n\t\t\t\t\tcandidateProjection,\n\t\t\t\t\tbudget,\n\t\t\t\t\tassessment,\n\t\t\t\t\tfull,\n\t\t\t\t);\n\t\t\tbudget.assert(assessment);\n\t\t}\n\t\treturn boundary.commit(\n\t\t\tObject.freeze({\n\t\t\t\t...(boundary.responseItemIdentity ? { responseItemIdentity: boundary.responseItemIdentity } : {}),\n\t\t\t\tsource: Object.freeze({ ...boundary.source }),\n\t\t\t\tselectedUnitIds: Object.freeze([...selectedUnitIds]),\n\t\t\t\trequest: Object.freeze({ ...candidateRequest }),\n\t\t\t\tprojection: Object.freeze({\n\t\t\t\t\t...candidateProjection,\n\t\t\t\t\treplayContract,\n\t\t\t\t\tmessageIndices: Object.freeze([...candidateProjection.messageIndices]),\n\t\t\t\t\t...(candidateProjection.optionalMessageIndices\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\toptionalMessageIndices: Object.freeze([...candidateProjection.optionalMessageIndices]),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(candidateProjection.generatedMessageIndices\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tgeneratedMessageIndices: Object.freeze([...candidateProjection.generatedMessageIndices]),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t}),\n\t\t\t\tassessment,\n\t\t\t\toriginalAssessment: full,\n\t\t\t\t...(publicMessages ? { publicMessages } : {}),\n\t\t\t}),\n\t\t);\n\t};\n\tconst offerPublicSubset = async (\n\t\tmessages: readonly AgentMessage[],\n\t\trequest: ProviderRequestRepresentation,\n\t\tprojection: ProviderRequestProjection,\n\t): Promise<string | undefined> => {\n\t\tif (!allowShrink || !budget || replayContract !== \"message-groups\") return;\n\t\tconst source = getCanonicalViewSelectionSource(messages)!;\n\t\tconst units = bindMessageReplayUnits(messages, source.units, boundary.limits, replayContract);\n\t\treturn offerOptionalSubset(\n\t\t\tmessages,\n\t\t\tunits,\n\t\t\tprepareViewSelection(units, boundary.limits),\n\t\t\trequest,\n\t\t\tprojection,\n\t\t\tbudget,\n\t\t\t(ids, candidate, mapping, assessment) => offer(ids, candidate, mapping, assessment, messages),\n\t\t);\n\t};\n\tif (boundary.pendingPublicMessageGroups?.length) {\n\t\tif (\n\t\t\treplayContract !== \"message-groups\" ||\n\t\t\t!projection.publicWindow ||\n\t\t\t!projection.encodePublicWindow ||\n\t\t\tJSON.stringify(projection.pendingPublicMessageGroups) !== JSON.stringify(boundary.pendingPublicMessageGroups)\n\t\t)\n\t\t\tthrow new Error(\"Original tool group requires current native adapter public conversion\");\n\t\tconst publicView = prepareToolContinuationWindow(boundary.messages);\n\t\tconst encoded = projection.encodePublicWindow(publicView.replacements);\n\t\tif (!encoded || encoded.projection.pendingPublicMessageGroups?.length)\n\t\t\tthrow new Error(\"Native adapter did not convert the whole required tool group\");\n\t\tconst publicSource = getCanonicalViewSelectionSource(publicView.messages)!;\n\t\tconst publicUnits = bindMessageReplayUnits(\n\t\t\tpublicView.messages,\n\t\t\tpublicSource.units,\n\t\t\tboundary.limits,\n\t\t\treplayContract,\n\t\t);\n\t\tconst closed = closeViewSelection(\n\t\t\tpublicUnits,\n\t\t\tpublicUnits.map((unit) => unit.id),\n\t\t\tboundary.limits,\n\t\t);\n\t\tlet assessment = budget?.measure(encoded.request);\n\t\tif (assessment?.status === \"over-budget\")\n\t\t\tassessment = (await finalizeMeasurement?.(encoded.request, assessment)) ?? assessment;\n\t\tif (assessment && full) {\n\t\t\tif (assessment.status === \"over-budget\") {\n\t\t\t\tconst subset = await offerPublicSubset(publicView.messages, encoded.request, encoded.projection);\n\t\t\t\tif (subset !== undefined) return subset;\n\t\t\t\tthrow publicBudgetFailure(\n\t\t\t\t\tboundary,\n\t\t\t\t\tpublicView.messages,\n\t\t\t\t\tencoded.request,\n\t\t\t\t\tencoded.projection,\n\t\t\t\t\tbudget!,\n\t\t\t\t\tassessment,\n\t\t\t\t\tfull,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (assessment.status !== \"within-estimate\")\n\t\t\t\tthrow new Error(\"Tool continuation public request exceeds its token budget\");\n\t\t}\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\tencoded.request,\n\t\t\tencoded.projection,\n\t\t\tassessment,\n\t\t\tpublicView.messages,\n\t\t);\n\t\treturn encoded.request.body;\n\t}\n\tif (projection.pendingPublicMessageGroups?.length)\n\t\tthrow new Error(\"Adapter pending group has no original owned source plan\");\n\t// Without a configured budget, admit only the exact full native view. Never shrink it.\n\tif (!budget) {\n\t\tconst closed = selection.close(units.map((unit) => unit.id));\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\trequest,\n\t\t\tprojection,\n\t\t\tundefined,\n\t\t);\n\t\treturn request.body;\n\t}\n\tif (!full) return;\n\tconst offerPublicWindow = async (): Promise<string | undefined> => {\n\t\tif (\n\t\t\t!allowShrink ||\n\t\t\treplayContract !== \"message-groups\" ||\n\t\t\t!projection.publicWindow ||\n\t\t\t!projection.encodePublicWindow\n\t\t)\n\t\t\treturn;\n\t\tconst closed = selection.close(units.map((unit) => unit.id));\n\t\tlet firstMessageIndex = 0;\n\t\tif (\n\t\t\tfull.status === \"unknown\" &&\n\t\t\tfull.unknown.length === 1 &&\n\t\t\tfull.unknown[0] === \"media, opaque or unsupported replay token coverage unknown\"\n\t\t) {\n\t\t\t// Credited items are not part of the unknown input. Keep original projection indices.\n\t\t\tconst firstUnmeteredItem = request.retainedPrefix?.inputItems ?? 0;\n\t\t\tconst reasoningItemIndex = input.findIndex(\n\t\t\t\t(item, index) => index >= firstUnmeteredItem && item?.type === \"reasoning\",\n\t\t\t);\n\t\t\tconst messageIndex = projection.messageIndices[reasoningItemIndex];\n\t\t\tconst group =\n\t\t\t\tmessageIndex == null\n\t\t\t\t\t? undefined\n\t\t\t\t\t: projection.publicMessageGroups?.find((members) => members.includes(messageIndex));\n\t\t\t// The adapter still accepts only complete groups; earlier meterable groups stay native.\n\t\t\tfirstMessageIndex = group ? Math.min(...group) : 0;\n\t\t}\n\t\tconst publicView = preparePublicContextWindow(boundary.messages, firstMessageIndex);\n\t\tif (!publicView) {\n\t\t\t// Keep the original measured refusal when no public conversion can be offered.\n\t\t\t// This is not a new recovery signal or permission to reprepare again.\n\t\t\tif (full.status === \"over-budget\") throw new RequestTokenBudgetError(full);\n\t\t\treturn;\n\t\t}\n\t\tconst encoded = projection.encodePublicWindow(publicView.replacements);\n\t\tif (!encoded) return;\n\t\tlet assessment = budget.measure(encoded.request);\n\t\tif (assessment.status === \"over-budget\")\n\t\t\tassessment = (await finalizeMeasurement?.(encoded.request, assessment)) ?? assessment;\n\t\tif (assessment.status === \"over-budget\") {\n\t\t\tconst subset = await offerPublicSubset(publicView.messages, encoded.request, encoded.projection);\n\t\t\tif (subset !== undefined) return subset;\n\t\t\tthrow publicBudgetFailure(\n\t\t\t\tboundary,\n\t\t\t\tpublicView.messages,\n\t\t\t\tencoded.request,\n\t\t\t\tencoded.projection,\n\t\t\t\tbudget,\n\t\t\t\tassessment,\n\t\t\t\tfull,\n\t\t\t);\n\t\t}\n\t\tif (assessment.status !== \"within-estimate\") return;\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\tencoded.request,\n\t\t\tencoded.projection,\n\t\t\tassessment,\n\t\t\tpublicView.messages,\n\t\t);\n\t\treturn encoded.request.body;\n\t};\n\tif (full.status === \"within-estimate\") {\n\t\tconst closed = selection.close(units.map((unit) => unit.id));\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\trequest,\n\t\t\tprojection,\n\t\t\tfull,\n\t\t);\n\t\treturn request.body;\n\t}\n\tif (!allowShrink || replayContract !== \"message-groups\") return;\n\tif (full.status !== \"over-budget\") return offerPublicWindow();\n\tconst subset = await offerOptionalSubset(boundary.messages, units, selection, request, projection, budget, offer);\n\tif (subset !== undefined) return subset;\n\treturn offerPublicWindow();\n}\n"]}
|
|
@@ -7,6 +7,7 @@ export class PublicContextBudgetError extends RequestTokenBudgetError {
|
|
|
7
7
|
originalAssessment;
|
|
8
8
|
mandatoryAssessment;
|
|
9
9
|
taskFrameRebaseAvailable;
|
|
10
|
+
isSourceCurrent;
|
|
10
11
|
source;
|
|
11
12
|
#compactionKey;
|
|
12
13
|
#summaryCapacity;
|
|
@@ -16,11 +17,12 @@ export class PublicContextBudgetError extends RequestTokenBudgetError {
|
|
|
16
17
|
getCompactionKey() {
|
|
17
18
|
return this.#compactionKey;
|
|
18
19
|
}
|
|
19
|
-
constructor(source, assessment, originalAssessment, mandatoryAssessment, taskFrameRebaseAvailable = false, compactionKey, summaryCapacity) {
|
|
20
|
+
constructor(source, assessment, originalAssessment, mandatoryAssessment, taskFrameRebaseAvailable = false, compactionKey, summaryCapacity, isSourceCurrent) {
|
|
20
21
|
super(assessment);
|
|
21
22
|
this.originalAssessment = originalAssessment;
|
|
22
23
|
this.mandatoryAssessment = mandatoryAssessment;
|
|
23
24
|
this.taskFrameRebaseAvailable = taskFrameRebaseAvailable;
|
|
25
|
+
this.isSourceCurrent = isSourceCurrent;
|
|
24
26
|
this.name = "PublicContextBudgetError";
|
|
25
27
|
if (mandatoryAssessment?.status === "over-budget")
|
|
26
28
|
this.message =
|
|
@@ -30,7 +32,7 @@ export class PublicContextBudgetError extends RequestTokenBudgetError {
|
|
|
30
32
|
this.#summaryCapacity = summaryCapacity;
|
|
31
33
|
}
|
|
32
34
|
}
|
|
33
|
-
export function captureRequestViewBoundary(messages, commit, validate, fixedPrepare) {
|
|
35
|
+
export function captureRequestViewBoundary(messages, commit, validate, fixedPrepare, isSourceCurrent) {
|
|
34
36
|
const source = getCanonicalViewSelectionSource(messages);
|
|
35
37
|
if (!source)
|
|
36
38
|
throw new Error("Request view boundary requires compiled canonical messages");
|
|
@@ -47,6 +49,7 @@ export function captureRequestViewBoundary(messages, commit, validate, fixedPrep
|
|
|
47
49
|
commit,
|
|
48
50
|
validate,
|
|
49
51
|
fixedPrepare,
|
|
52
|
+
isSourceCurrent,
|
|
50
53
|
};
|
|
51
54
|
}
|
|
52
55
|
function providerMessageIndex(indices, canonicalIndex) {
|
|
@@ -146,7 +149,7 @@ function publicBudgetFailure(boundary, messages, request, projection, budget, as
|
|
|
146
149
|
const body = JSON.parse(request.body);
|
|
147
150
|
const input = body[inputKey];
|
|
148
151
|
if (!Array.isArray(input) || input.length !== projection.messageIndices.length)
|
|
149
|
-
return new PublicContextBudgetError(boundary.source, assessment, original);
|
|
152
|
+
return new PublicContextBudgetError(boundary.source, assessment, original, undefined, false, undefined, undefined, boundary.isSourceCurrent);
|
|
150
153
|
const graph = prepareViewSelection(source.units, boundary.limits);
|
|
151
154
|
const retainedInput = (retained) => {
|
|
152
155
|
const roots = source.units
|
|
@@ -184,7 +187,7 @@ function publicBudgetFailure(boundary, messages, request, projection, budget, as
|
|
|
184
187
|
measured.estimatedInputTokens === null
|
|
185
188
|
? undefined
|
|
186
189
|
: Math.floor(measured.availableInputTokens - measured.estimatedInputTokens);
|
|
187
|
-
});
|
|
190
|
+
}, boundary.isSourceCurrent);
|
|
188
191
|
}
|
|
189
192
|
/** Check the actual final mapping without selecting, converting, or committing another view. */
|
|
190
193
|
export async function prepareFixedRequestView(boundary, request, projection, assessment) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request-view-selection.js","sourceRoot":"","sources":["../../src/core/request-view-selection.ts"],"names":[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MAAM,EAAE,KAAK,CAAC,CAAC;IAClH,IAAI,MAAM,KAAK,SAAS;QAAE,OAAO,MAAM,CAAC;IACxC,OAAO,iBAAiB,EAAE,CAAC;AAAA,CAC3B","sourcesContent":["import type { AgentMessage } from \"@ponythewhite/base-context-agent\";\nimport {\n\ttype Context,\n\ttype ProviderRequestProjection,\n\ttype ProviderRequestPublicMessage,\n\ttype ProviderRequestRepresentation,\n\ttype RequestTokenAssessment,\n\tRequestTokenBudgetError,\n\ttype RequestTokenBudgetEvaluator,\n\twithRequestBody,\n} from \"@ponythewhite/base-context-ai\";\nimport {\n\ttype CanonicalViewSelectionSource,\n\tcaptureCanonicalRequestMessages,\n\tgetCanonicalEpochContext,\n\tgetCanonicalViewSelectionSource,\n\tpreparePublicContextWindow,\n\tprepareToolContinuationWindow,\n} from \"./canonical-context.js\";\nimport { convertToLlm } from \"./messages.js\";\nimport type { ContextEpochEntryRef, SourceSnapshotRef } from \"./request-events.js\";\nimport { bindMessageReplayUnits, closeViewSelection, prepareViewSelection } from \"./view-units.js\";\n\n/** Actual adapter-public measurement, not a verdict about the opaque native request. */\nexport class PublicContextBudgetError extends RequestTokenBudgetError {\n\treadonly source: SourceSnapshotRef;\n\t#compactionKey?: string;\n\t#summaryCapacity?: (retained: ReadonlySet<string>, wrapper: string) => number | undefined;\n\n\tremainingSummaryTokens(retained: ReadonlySet<string>, wrapper: string): number | undefined {\n\t\treturn this.#summaryCapacity?.(retained, wrapper);\n\t}\n\n\tgetCompactionKey(): string | undefined {\n\t\treturn this.#compactionKey;\n\t}\n\n\tconstructor(\n\t\tsource: SourceSnapshotRef,\n\t\tassessment: RequestTokenAssessment,\n\t\treadonly originalAssessment: RequestTokenAssessment,\n\t\treadonly mandatoryAssessment?: RequestTokenAssessment,\n\t\treadonly taskFrameRebaseAvailable = false,\n\t\tcompactionKey?: string,\n\t\tsummaryCapacity?: (retained: ReadonlySet<string>, wrapper: string) => number | undefined,\n\t) {\n\t\tsuper(assessment);\n\t\tthis.name = \"PublicContextBudgetError\";\n\t\tif (mandatoryAssessment?.status === \"over-budget\")\n\t\t\tthis.message =\n\t\t\t\t\"Context capacity exceeded: instructions, tools, mandatory evidence and output allowance cannot fit. Summarizing unrelated history cannot resolve this request.\";\n\t\tthis.source = Object.freeze({ ...source });\n\t\tthis.#compactionKey = compactionKey;\n\t\tthis.#summaryCapacity = summaryCapacity;\n\t}\n}\n\nexport interface RequestViewCandidate {\n\t/** Session-local Responses ID namespace; a new owner requires a fresh representation. */\n\treadonly responseItemIdentity?: string;\n\treadonly source: SourceSnapshotRef;\n\treadonly selectedUnitIds: readonly string[];\n\treadonly request: ProviderRequestRepresentation;\n\treadonly projection: ProviderRequestProjection;\n\t// Absent only for mandatory full-view admission without a configured token budget.\n\treadonly assessment: RequestTokenAssessment | undefined;\n\treadonly originalAssessment: RequestTokenAssessment | undefined;\n\t/** Exact public messages represented by the accepted candidate, with captured source recipes. */\n\treadonly publicMessages?: readonly AgentMessage[];\n}\n\n/** Root resolves only after its canonical epoch checkpoint ACK. This module owns no epoch state. */\nexport type RequestViewCommit = (\n\tcandidate: RequestViewCandidate,\n) => Promise<ContextEpochEntryRef | undefined> | Promise<void>;\nexport type RequestViewValidate = (\n\trequest: ProviderRequestRepresentation,\n\tassessment: RequestTokenAssessment | undefined,\n) => void;\n\nexport type RequestViewFixedPrepare = (\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tassessment: RequestTokenAssessment | undefined,\n) => ContextEpochEntryRef | void | Promise<ContextEpochEntryRef | undefined> | Promise<void>;\n\nexport interface CapturedRequestViewBoundary extends CanonicalViewSelectionSource {\n\treadonly responseItemIdentity?: string;\n\treadonly messages: readonly AgentMessage[];\n\t/** Provider logical positions mapped to the unchanged canonical messages/units. */\n\treadonly providerMessageIndices: readonly number[];\n\treadonly providerPendingPublicMessageGroups?: readonly (readonly number[])[];\n\treadonly commit: RequestViewCommit;\n\treadonly validate?: RequestViewValidate;\n\treadonly fixedPrepare?: RequestViewFixedPrepare;\n}\n\nexport function captureRequestViewBoundary(\n\tmessages: readonly AgentMessage[],\n\tcommit: RequestViewCommit,\n\tvalidate?: RequestViewValidate,\n\tfixedPrepare?: RequestViewFixedPrepare,\n): CapturedRequestViewBoundary {\n\tconst source = getCanonicalViewSelectionSource(messages);\n\tif (!source) throw new Error(\"Request view boundary requires compiled canonical messages\");\n\tconst providerMessageIndices = messages.flatMap((message, index) => convertToLlm([message]).map(() => index));\n\treturn {\n\t\t...source,\n\t\tmessages: captureCanonicalRequestMessages(messages),\n\t\tproviderMessageIndices,\n\t\t...(source.pendingPublicMessageGroups\n\t\t\t? {\n\t\t\t\t\tproviderPendingPublicMessageGroups: source.pendingPublicMessageGroups.map((group) =>\n\t\t\t\t\t\tgroup.map((index) => providerMessageIndex(providerMessageIndices, index)),\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t\tcommit,\n\t\tvalidate,\n\t\tfixedPrepare,\n\t};\n}\n\nfunction providerMessageIndex(indices: readonly number[], canonicalIndex: number): number {\n\tconst index = indices.indexOf(canonicalIndex);\n\tif (index < 0) throw new Error(\"Provider projection cannot address a filtered canonical message\");\n\treturn index;\n}\n\n/** Keep canonical UI barriers while translating the native serializer's provider-only positions. */\nfunction canonicalRequestProjection(\n\tboundary: CapturedRequestViewBoundary,\n\tprojection: ProviderRequestProjection,\n): ProviderRequestProjection {\n\tconst indices = boundary.providerMessageIndices;\n\tif (indices.length === boundary.messages.length) return projection;\n\tconst canonicalIndex = (index: number): number => {\n\t\tconst canonical = indices[index];\n\t\tif (canonical === undefined) throw new Error(\"Provider projection message index is outside its captured view\");\n\t\treturn canonical;\n\t};\n\treturn {\n\t\t...projection,\n\t\tmessageIndices: projection.messageIndices.map((index) => (index === null ? null : canonicalIndex(index))),\n\t\t...(projection.optionalMessageIndices\n\t\t\t? { optionalMessageIndices: projection.optionalMessageIndices.map(canonicalIndex) }\n\t\t\t: {}),\n\t\t...(projection.generatedMessageIndices\n\t\t\t? { generatedMessageIndices: projection.generatedMessageIndices.map(canonicalIndex) }\n\t\t\t: {}),\n\t\t...(projection.publicMessageGroups\n\t\t\t? { publicMessageGroups: projection.publicMessageGroups.map((group) => group.map(canonicalIndex)) }\n\t\t\t: {}),\n\t\t...(projection.pendingPublicMessageGroups\n\t\t\t? {\n\t\t\t\t\tpendingPublicMessageGroups: projection.pendingPublicMessageGroups.map((group) =>\n\t\t\t\t\t\tgroup.map(canonicalIndex),\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t\t...(projection.encodePublicWindow\n\t\t\t? {\n\t\t\t\t\tencodePublicWindow: (replacements: readonly ProviderRequestPublicMessage[]) => {\n\t\t\t\t\t\tconst encoded = projection.encodePublicWindow!(\n\t\t\t\t\t\t\treplacements.map((replacement) => ({\n\t\t\t\t\t\t\t\t...replacement,\n\t\t\t\t\t\t\t\tmessageIndex: providerMessageIndex(indices, replacement.messageIndex),\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\tencoded && { ...encoded, projection: canonicalRequestProjection(boundary, encoded.projection) }\n\t\t\t\t\t\t);\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\nexport function matchesRequestView(\n\tboundary: CapturedRequestViewBoundary,\n\tsource: SourceSnapshotRef,\n\tcontext: Context,\n): boolean {\n\tconst expected = boundary.source;\n\tif (\n\t\texpected.sessionId !== source.sessionId ||\n\t\texpected.sessionFile !== source.sessionFile ||\n\t\texpected.leafId !== source.leafId ||\n\t\texpected.sourceSequence !== source.sourceSequence\n\t)\n\t\treturn false;\n\tconst rendered = convertToLlm([...boundary.messages]);\n\treturn (\n\t\tboundary.messages.length === boundary.units.length &&\n\t\trendered.length === boundary.providerMessageIndices.length &&\n\t\tJSON.stringify(rendered) === JSON.stringify(context.messages)\n\t);\n}\n\n/** Projection kinds describe their actual provider body, never an OpenAI-format route alias. */\nfunction requestInputKey(\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n): \"input\" | \"messages\" | undefined {\n\tif (\n\t\t(request.api === \"openai-responses\" || request.api === \"openai-codex-responses\") &&\n\t\t(projection.kind === \"openai-responses-text-v1\" || projection.kind === \"openai-responses-replay-v1\")\n\t)\n\t\treturn \"input\";\n\tif (\n\t\trequest.api === \"openai-completions\" &&\n\t\trequest.provider === \"deepseek\" &&\n\t\trequest.url === \"https://api.deepseek.com/chat/completions\" &&\n\t\tprojection.kind === \"deepseek-completions-text-tools-v1\" &&\n\t\trequest.body !== undefined &&\n\t\tJSON.parse(request.body).model === \"deepseek-flash\"\n\t)\n\t\treturn \"messages\";\n\treturn undefined;\n}\n\n/** A lower bound for compaction: fixed policy, current tail and required recorded evidence. */\nfunction publicBudgetFailure(\n\tboundary: CapturedRequestViewBoundary,\n\tmessages: readonly AgentMessage[],\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tbudget: RequestTokenBudgetEvaluator,\n\tassessment: RequestTokenAssessment,\n\toriginal: RequestTokenAssessment,\n): PublicContextBudgetError {\n\tconst context = getCanonicalEpochContext(messages)!;\n\tconst source = getCanonicalViewSelectionSource(messages)!;\n\tconst toolEntries = new Set(\n\t\tcontext.toolContinuations?.flatMap((group) => [\n\t\t\tgroup.assistantEntryId,\n\t\t\t...group.calls.flatMap((call) => (call.result ? [call.result.id] : [])),\n\t\t]),\n\t);\n\tlet tailSequence = -1;\n\tfor (const reference of context.references)\n\t\tif (reference && reference.ref.kind !== \"compaction\")\n\t\t\ttailSequence = Math.max(tailSequence, reference.ref.sequence);\n\tconst required = new Set(\n\t\tsource.units.flatMap((unit, index) => {\n\t\t\tconst reference = context.references[index];\n\t\t\treturn [\"task-frame\", \"resource-view\", \"recovery\"].includes(unit.kind) ||\n\t\t\t\tunit.id === \"native-selected-skill-versions\" ||\n\t\t\t\t(reference && (reference.ref.sequence === tailSequence || toolEntries.has(reference.ref.entryId)))\n\t\t\t\t? [index]\n\t\t\t\t: [];\n\t\t}),\n\t);\n\tconst inputKey = requestInputKey(request, projection)!;\n\tconst body = JSON.parse(request.body!) as Record<string, unknown>;\n\tconst input = body[inputKey];\n\tif (!Array.isArray(input) || input.length !== projection.messageIndices.length)\n\t\treturn new PublicContextBudgetError(boundary.source, assessment, original);\n\tconst graph = prepareViewSelection(source.units, boundary.limits);\n\tconst retainedInput = (retained: ReadonlySet<string>) => {\n\t\tconst roots = source.units\n\t\t\t.filter((_, index) => required.has(index) || retained.has(context.references[index]?.ref.entryId ?? \"\"))\n\t\t\t.map((unit) => unit.id);\n\t\tconst selected = new Set(graph.close(roots).map((unit) => unit.id));\n\t\treturn input.filter((_, index) => {\n\t\t\tconst messageIndex = projection.messageIndices[index];\n\t\t\treturn messageIndex === null || selected.has(source.units[messageIndex].id);\n\t\t});\n\t};\n\tconst minimum = withRequestBody(request, JSON.stringify({ ...body, [inputKey]: retainedInput(new Set()) }));\n\treturn new PublicContextBudgetError(\n\t\tboundary.source,\n\t\tassessment,\n\t\toriginal,\n\t\tbudget.measure(minimum),\n\t\t(context.taskFrame?.messages.length ?? 0) > 1,\n\t\tJSON.stringify([\n\t\t\tboundary.source.sessionId,\n\t\t\tboundary.source.sessionFile,\n\t\t\tsource.units.map((unit) => [unit.id, unit.sourceRevision]),\n\t\t\tassessment.api,\n\t\t\tassessment.provider,\n\t\t\tassessment.model,\n\t\t\tassessment.route,\n\t\t\tassessment.profile,\n\t\t\tassessment.availableInputTokens,\n\t\t\tassessment.outputReserveTokens,\n\t\t]),\n\t\t(retained, wrapper) => {\n\t\t\t// Meter only; this synthetic empty summary is never admitted or sent.\n\t\t\tconst summary =\n\t\t\t\tinputKey === \"messages\"\n\t\t\t\t\t? { role: \"user\", content: wrapper }\n\t\t\t\t\t: { role: \"user\", content: [{ type: \"input_text\", text: wrapper }] };\n\t\t\tconst kept = retainedInput(retained);\n\t\t\tconst position = kept.findIndex((item) => item?.role !== \"system\" && item?.role !== \"developer\");\n\t\t\tkept.splice(position < 0 ? kept.length : position, 0, summary);\n\t\t\tconst measured = budget.measure(withRequestBody(request, JSON.stringify({ ...body, [inputKey]: kept })));\n\t\t\treturn measured.status === \"unknown\" ||\n\t\t\t\tmeasured.availableInputTokens === null ||\n\t\t\t\tmeasured.estimatedInputTokens === null\n\t\t\t\t? undefined\n\t\t\t\t: Math.floor(measured.availableInputTokens - measured.estimatedInputTokens);\n\t\t},\n\t);\n}\n\n/** Check the actual final mapping without selecting, converting, or committing another view. */\nexport async function prepareFixedRequestView(\n\tboundary: CapturedRequestViewBoundary,\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tassessment: RequestTokenAssessment | undefined,\n) {\n\tprojection = canonicalRequestProjection(boundary, projection);\n\tconst inputKey = requestInputKey(request, projection);\n\tconst payload = JSON.parse(request.body!) as Record<string, unknown> | null;\n\tconst input = inputKey && payload ? payload[inputKey] : undefined;\n\tif (!Array.isArray(input) || input.length !== projection.messageIndices.length)\n\t\tthrow new Error(\"Fixed context requires its final provider projection\");\n\tif (\n\t\tprojection.kind === \"openai-responses-text-v1\" &&\n\t\tboundary.messages.some(\n\t\t\t(message) =>\n\t\t\t\tmessage.role === \"toolResult\" ||\n\t\t\t\t(message.role === \"assistant\" && (message.content.length !== 1 || message.content[0].type !== \"text\")),\n\t\t)\n\t)\n\t\tthrow new Error(\"Fixed context requires its native replay adapter\");\n\tconst units = bindMessageReplayUnits(\n\t\tboundary.messages,\n\t\tboundary.units,\n\t\tboundary.limits,\n\t\tprojection.replayContract ?? \"complete-context\",\n\t);\n\tcloseViewSelection(\n\t\tunits,\n\t\tunits.map((unit) => unit.id),\n\t\tboundary.limits,\n\t);\n\treturn await boundary.fixedPrepare!(request, projection, assessment);\n}\n\n/** Reuse the same legal omission policy for native and already-converted public requests. */\nasync function offerOptionalSubset(\n\tmessages: readonly AgentMessage[],\n\tunits: CanonicalViewSelectionSource[\"units\"],\n\tselection: ReturnType<typeof prepareViewSelection>,\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tbudget: RequestTokenBudgetEvaluator,\n\toffer: (\n\t\tids: readonly string[],\n\t\trequest: ProviderRequestRepresentation,\n\t\tprojection: ProviderRequestProjection,\n\t\tassessment: RequestTokenAssessment,\n\t) => Promise<unknown>,\n): Promise<string | undefined> {\n\tconst inputKey = requestInputKey(request, projection);\n\tif (!inputKey) return;\n\tconst payload = JSON.parse(request.body!) as Record<string, unknown>;\n\tconst input = payload[inputKey];\n\tif (!Array.isArray(input) || input.length !== projection.messageIndices.length) return;\n\tlet latestAssistant = -1;\n\tfor (const [index, message] of messages.entries()) if (message.role === \"assistant\") latestAssistant = index;\n\tconst retained = new Set(projection.messageIndices.slice(0, request.retainedPrefix?.inputItems ?? 0));\n\tconst projectedOptional =\n\t\tprojection.kind !== \"openai-responses-text-v1\" ? new Set(projection.optionalMessageIndices ?? []) : undefined;\n\tconst optional = units.filter((unit, index) => {\n\t\tconst message = messages[index];\n\t\treturn (\n\t\t\tindex !== latestAssistant &&\n\t\t\t!retained.has(index) &&\n\t\t\t(!projectedOptional || projectedOptional.has(index)) &&\n\t\t\tunit.kind === \"literal\" &&\n\t\t\tunit.authority === \"assistant-public\" &&\n\t\t\tmessage.role === \"assistant\" &&\n\t\t\tmessage.stopReason === \"stop\" &&\n\t\t\tmessage.content.length === 1 &&\n\t\t\tmessage.content[0].type === \"text\"\n\t\t);\n\t});\n\tconst generatedPositions = new Map<string, number>();\n\tconst generated =\n\t\tprojection.generatedMessageIndices ??\n\t\tmessages.flatMap((message, index) =>\n\t\t\tmessage.role === \"assistant\" &&\n\t\t\tmessage.content.some((block) => block.type === \"text\" && block.textSignature === undefined)\n\t\t\t\t? [index]\n\t\t\t\t: [],\n\t\t);\n\tfor (const index of generated) generatedPositions.set(units[index].id, index);\n\t// All user inputs, the latest assistant, fixed/TaskFrame/recovery units and errors stay selected.\n\tconst selected = new Set(units.map((unit) => unit.id));\n\tfor (const unit of optional) {\n\t\tselected.delete(unit.id);\n\t\tconst closed = selection.close([...selected]);\n\t\t// Normal Responses rendering uses msg_<message index> for unsigned assistants.\n\t\t// Reject any subset that would change a retained generated item ID on reconstruction.\n\t\tif (closed.some((item, index) => generatedPositions.has(item.id) && generatedPositions.get(item.id) !== index))\n\t\t\tcontinue;\n\t\tconst closedIds = new Set(closed.map((item) => item.id));\n\t\tconst keepItem = (index: number) => {\n\t\t\tconst messageIndex = projection.messageIndices[index];\n\t\t\treturn messageIndex === null || closedIds.has(units[messageIndex].id);\n\t\t};\n\t\tconst body = JSON.stringify({ ...payload, [inputKey]: input.filter((_, index) => keepItem(index)) });\n\t\tconst candidateRequest = { ...request, body };\n\t\tconst assessment = budget.measure(candidateRequest);\n\t\tif (assessment.status !== \"within-estimate\") continue;\n\t\tawait offer(\n\t\t\tclosed.map((item) => item.id),\n\t\t\tcandidateRequest,\n\t\t\t{\n\t\t\t\t...projection,\n\t\t\t\tmessageIndices: projection.messageIndices.filter((_, index) => keepItem(index)),\n\t\t\t\t...(projection.optionalMessageIndices\n\t\t\t\t\t? {\n\t\t\t\t\t\t\toptionalMessageIndices: projection.optionalMessageIndices.filter((index) =>\n\t\t\t\t\t\t\t\tclosedIds.has(units[index].id),\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...(projection.generatedMessageIndices\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tgeneratedMessageIndices: projection.generatedMessageIndices.filter((index) =>\n\t\t\t\t\t\t\t\tclosedIds.has(units[index].id),\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},\n\t\t\tassessment,\n\t\t);\n\t\treturn body;\n\t}\n\treturn;\n}\n\n/** Only the actual serializer's established replay contract authorizes historical-literal omission. */\nexport async function selectRequestView(\n\tboundary: CapturedRequestViewBoundary,\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tbudget: RequestTokenBudgetEvaluator | undefined,\n\tallowShrink: boolean,\n\tfinalizeMeasurement?: (\n\t\trequest: ProviderRequestRepresentation,\n\t\tassessment: RequestTokenAssessment | undefined,\n\t) => Promise<RequestTokenAssessment | undefined>,\n): Promise<string | undefined> {\n\tprojection = canonicalRequestProjection(boundary, projection);\n\tlet full = budget?.measure(request);\n\tconst inputKey = requestInputKey(request, projection);\n\tif ((budget && full?.limitSource !== \"explicit-profile\") || !inputKey) return;\n\tif (!budget && !boundary.requiresEpoch && !boundary.pendingPublicMessageGroups?.length) return;\n\tconst payload = JSON.parse(request.body!) as Record<string, unknown>;\n\tconst input = payload[inputKey];\n\tif (!Array.isArray(input) || input.length !== projection.messageIndices.length) return;\n\t// Resolve a near-limit estimate before discarding a stable native prefix. Original\n\t// protected tool groups must first pass their public conversion below.\n\tif (\n\t\tfull?.status === \"over-budget\" &&\n\t\t!boundary.pendingPublicMessageGroups?.length &&\n\t\t!projection.pendingPublicMessageGroups?.length\n\t)\n\t\tfull = (await finalizeMeasurement?.(request, full)) ?? full;\n\n\t// Absence is complete-context; a profile or tool-shaped message is never group authority.\n\tconst replayContract = projection.replayContract ?? \"complete-context\";\n\tif (\n\t\tprojection.kind === \"openai-responses-text-v1\" &&\n\t\tboundary.messages.some(\n\t\t\t(message) =>\n\t\t\t\tmessage.role === \"toolResult\" ||\n\t\t\t\t(message.role === \"assistant\" && (message.content.length !== 1 || message.content[0].type !== \"text\")),\n\t\t)\n\t)\n\t\treturn;\n\tconst units = bindMessageReplayUnits(\n\t\tboundary.messages,\n\t\tboundary.units,\n\t\tboundary.limits,\n\t\treplayContract,\n\t\tboundary.pendingPublicMessageGroups,\n\t);\n\tconst selection = prepareViewSelection(units, boundary.limits);\n\tconst offer = async (\n\t\tselectedUnitIds: readonly string[],\n\t\tcandidateRequest: ProviderRequestRepresentation,\n\t\tcandidateProjection: ProviderRequestProjection,\n\t\tassessment: RequestTokenAssessment | undefined,\n\t\tpublicMessages?: readonly AgentMessage[],\n\t) => {\n\t\tassessment = (await finalizeMeasurement?.(candidateRequest, assessment)) ?? assessment;\n\t\tif (budget && assessment) {\n\t\t\tif (assessment.status === \"over-budget\" && full)\n\t\t\t\tthrow publicBudgetFailure(\n\t\t\t\t\tboundary,\n\t\t\t\t\tpublicMessages ?? boundary.messages,\n\t\t\t\t\tcandidateRequest,\n\t\t\t\t\tcandidateProjection,\n\t\t\t\t\tbudget,\n\t\t\t\t\tassessment,\n\t\t\t\t\tfull,\n\t\t\t\t);\n\t\t\tbudget.assert(assessment);\n\t\t}\n\t\treturn boundary.commit(\n\t\t\tObject.freeze({\n\t\t\t\t...(boundary.responseItemIdentity ? { responseItemIdentity: boundary.responseItemIdentity } : {}),\n\t\t\t\tsource: Object.freeze({ ...boundary.source }),\n\t\t\t\tselectedUnitIds: Object.freeze([...selectedUnitIds]),\n\t\t\t\trequest: Object.freeze({ ...candidateRequest }),\n\t\t\t\tprojection: Object.freeze({\n\t\t\t\t\t...candidateProjection,\n\t\t\t\t\treplayContract,\n\t\t\t\t\tmessageIndices: Object.freeze([...candidateProjection.messageIndices]),\n\t\t\t\t\t...(candidateProjection.optionalMessageIndices\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\toptionalMessageIndices: Object.freeze([...candidateProjection.optionalMessageIndices]),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(candidateProjection.generatedMessageIndices\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tgeneratedMessageIndices: Object.freeze([...candidateProjection.generatedMessageIndices]),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t}),\n\t\t\t\tassessment,\n\t\t\t\toriginalAssessment: full,\n\t\t\t\t...(publicMessages ? { publicMessages } : {}),\n\t\t\t}),\n\t\t);\n\t};\n\tconst offerPublicSubset = async (\n\t\tmessages: readonly AgentMessage[],\n\t\trequest: ProviderRequestRepresentation,\n\t\tprojection: ProviderRequestProjection,\n\t): Promise<string | undefined> => {\n\t\tif (!allowShrink || !budget || replayContract !== \"message-groups\") return;\n\t\tconst source = getCanonicalViewSelectionSource(messages)!;\n\t\tconst units = bindMessageReplayUnits(messages, source.units, boundary.limits, replayContract);\n\t\treturn offerOptionalSubset(\n\t\t\tmessages,\n\t\t\tunits,\n\t\t\tprepareViewSelection(units, boundary.limits),\n\t\t\trequest,\n\t\t\tprojection,\n\t\t\tbudget,\n\t\t\t(ids, candidate, mapping, assessment) => offer(ids, candidate, mapping, assessment, messages),\n\t\t);\n\t};\n\tif (boundary.pendingPublicMessageGroups?.length) {\n\t\tif (\n\t\t\treplayContract !== \"message-groups\" ||\n\t\t\t!projection.publicWindow ||\n\t\t\t!projection.encodePublicWindow ||\n\t\t\tJSON.stringify(projection.pendingPublicMessageGroups) !== JSON.stringify(boundary.pendingPublicMessageGroups)\n\t\t)\n\t\t\tthrow new Error(\"Original tool group requires current native adapter public conversion\");\n\t\tconst publicView = prepareToolContinuationWindow(boundary.messages);\n\t\tconst encoded = projection.encodePublicWindow(publicView.replacements);\n\t\tif (!encoded || encoded.projection.pendingPublicMessageGroups?.length)\n\t\t\tthrow new Error(\"Native adapter did not convert the whole required tool group\");\n\t\tconst publicSource = getCanonicalViewSelectionSource(publicView.messages)!;\n\t\tconst publicUnits = bindMessageReplayUnits(\n\t\t\tpublicView.messages,\n\t\t\tpublicSource.units,\n\t\t\tboundary.limits,\n\t\t\treplayContract,\n\t\t);\n\t\tconst closed = closeViewSelection(\n\t\t\tpublicUnits,\n\t\t\tpublicUnits.map((unit) => unit.id),\n\t\t\tboundary.limits,\n\t\t);\n\t\tlet assessment = budget?.measure(encoded.request);\n\t\tif (assessment?.status === \"over-budget\")\n\t\t\tassessment = (await finalizeMeasurement?.(encoded.request, assessment)) ?? assessment;\n\t\tif (assessment && full) {\n\t\t\tif (assessment.status === \"over-budget\") {\n\t\t\t\tconst subset = await offerPublicSubset(publicView.messages, encoded.request, encoded.projection);\n\t\t\t\tif (subset !== undefined) return subset;\n\t\t\t\tthrow publicBudgetFailure(\n\t\t\t\t\tboundary,\n\t\t\t\t\tpublicView.messages,\n\t\t\t\t\tencoded.request,\n\t\t\t\t\tencoded.projection,\n\t\t\t\t\tbudget!,\n\t\t\t\t\tassessment,\n\t\t\t\t\tfull,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (assessment.status !== \"within-estimate\")\n\t\t\t\tthrow new Error(\"Tool continuation public request exceeds its token budget\");\n\t\t}\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\tencoded.request,\n\t\t\tencoded.projection,\n\t\t\tassessment,\n\t\t\tpublicView.messages,\n\t\t);\n\t\treturn encoded.request.body;\n\t}\n\tif (projection.pendingPublicMessageGroups?.length)\n\t\tthrow new Error(\"Adapter pending group has no original owned source plan\");\n\t// Without a configured budget, admit only the exact full native view. Never shrink it.\n\tif (!budget) {\n\t\tconst closed = selection.close(units.map((unit) => unit.id));\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\trequest,\n\t\t\tprojection,\n\t\t\tundefined,\n\t\t);\n\t\treturn request.body;\n\t}\n\tif (!full) return;\n\tconst offerPublicWindow = async (): Promise<string | undefined> => {\n\t\tif (\n\t\t\t!allowShrink ||\n\t\t\treplayContract !== \"message-groups\" ||\n\t\t\t!projection.publicWindow ||\n\t\t\t!projection.encodePublicWindow\n\t\t)\n\t\t\treturn;\n\t\tconst closed = selection.close(units.map((unit) => unit.id));\n\t\tlet firstMessageIndex = 0;\n\t\tif (\n\t\t\tfull.status === \"unknown\" &&\n\t\t\tfull.unknown.length === 1 &&\n\t\t\tfull.unknown[0] === \"media, opaque or unsupported replay token coverage unknown\"\n\t\t) {\n\t\t\t// Credited items are not part of the unknown input. Keep original projection indices.\n\t\t\tconst firstUnmeteredItem = request.retainedPrefix?.inputItems ?? 0;\n\t\t\tconst reasoningItemIndex = input.findIndex(\n\t\t\t\t(item, index) => index >= firstUnmeteredItem && item?.type === \"reasoning\",\n\t\t\t);\n\t\t\tconst messageIndex = projection.messageIndices[reasoningItemIndex];\n\t\t\tconst group =\n\t\t\t\tmessageIndex == null\n\t\t\t\t\t? undefined\n\t\t\t\t\t: projection.publicMessageGroups?.find((members) => members.includes(messageIndex));\n\t\t\t// The adapter still accepts only complete groups; earlier meterable groups stay native.\n\t\t\tfirstMessageIndex = group ? Math.min(...group) : 0;\n\t\t}\n\t\tconst publicView = preparePublicContextWindow(boundary.messages, firstMessageIndex);\n\t\tif (!publicView) {\n\t\t\t// Keep the original measured refusal when no public conversion can be offered.\n\t\t\t// This is not a new recovery signal or permission to reprepare again.\n\t\t\tif (full.status === \"over-budget\") throw new RequestTokenBudgetError(full);\n\t\t\treturn;\n\t\t}\n\t\tconst encoded = projection.encodePublicWindow(publicView.replacements);\n\t\tif (!encoded) return;\n\t\tlet assessment = budget.measure(encoded.request);\n\t\tif (assessment.status === \"over-budget\")\n\t\t\tassessment = (await finalizeMeasurement?.(encoded.request, assessment)) ?? assessment;\n\t\tif (assessment.status === \"over-budget\") {\n\t\t\tconst subset = await offerPublicSubset(publicView.messages, encoded.request, encoded.projection);\n\t\t\tif (subset !== undefined) return subset;\n\t\t\tthrow publicBudgetFailure(\n\t\t\t\tboundary,\n\t\t\t\tpublicView.messages,\n\t\t\t\tencoded.request,\n\t\t\t\tencoded.projection,\n\t\t\t\tbudget,\n\t\t\t\tassessment,\n\t\t\t\tfull,\n\t\t\t);\n\t\t}\n\t\tif (assessment.status !== \"within-estimate\") return;\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\tencoded.request,\n\t\t\tencoded.projection,\n\t\t\tassessment,\n\t\t\tpublicView.messages,\n\t\t);\n\t\treturn encoded.request.body;\n\t};\n\tif (full.status === \"within-estimate\") {\n\t\tconst closed = selection.close(units.map((unit) => unit.id));\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\trequest,\n\t\t\tprojection,\n\t\t\tfull,\n\t\t);\n\t\treturn request.body;\n\t}\n\tif (!allowShrink || replayContract !== \"message-groups\") return;\n\tif (full.status !== \"over-budget\") return offerPublicWindow();\n\tconst subset = await offerOptionalSubset(boundary.messages, units, selection, request, projection, budget, offer);\n\tif (subset !== undefined) return subset;\n\treturn offerPublicWindow();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"request-view-selection.js","sourceRoot":"","sources":["../../src/core/request-view-selection.ts"],"names":[],"mappings":"AACA,OAAO,EAMN,uBAAuB,EAEvB,eAAe,GACf,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAEN,+BAA+B,EAC/B,wBAAwB,EACxB,+BAA+B,EAC/B,0BAA0B,EAC1B,6BAA6B,GAC7B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAE7C,OAAO,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAEnG,wFAAwF;AACxF,MAAM,OAAO,wBAAyB,SAAQ,uBAAuB;IAgB1D,kBAAkB;IAClB,mBAAmB;IACnB,wBAAwB;IAGxB,eAAe;IApBhB,MAAM,CAAoB;IACnC,cAAc,CAAU;IACxB,gBAAgB,CAA0E;IAE1F,sBAAsB,CAAC,QAA6B,EAAE,OAAe,EAAsB;QAC1F,OAAO,IAAI,CAAC,gBAAgB,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IAAA,CAClD;IAED,gBAAgB,GAAuB;QACtC,OAAO,IAAI,CAAC,cAAc,CAAC;IAAA,CAC3B;IAED,YACC,MAAyB,EACzB,UAAkC,EACzB,kBAA0C,EAC1C,mBAA4C,EAC5C,wBAAwB,GAAG,KAAK,EACzC,aAAsB,EACtB,eAAwF,EAC/E,eAA+B,EACvC;QACD,KAAK,CAAC,UAAU,CAAC,CAAC;kCAPT,kBAAkB;mCAClB,mBAAmB;wCACnB,wBAAwB;+BAGxB,eAAe;QAGxB,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;QACvC,IAAI,mBAAmB,EAAE,MAAM,KAAK,a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AAC,EAAE,CAAC,EAC7B,OAAO,EACP,UAAU,EACV,IAAI,CACJ,CAAC;QACF,OAAO,OAAO,CAAC,IAAI,CAAC;IACrB,CAAC;IACD,IAAI,CAAC,WAAW,IAAI,cAAc,KAAK,gBAAgB;QAAE,OAAO;IAChE,IAAI,IAAI,CAAC,MAAM,KAAK,aAAa;QAAE,OAAO,iBAAiB,EAAE,CAAC;IAC9D,MAAM,MAAM,GAAG,MAAM,mBAAmB,CAAC,QAAQ,CAAC,QAAQ,EAAE,KAAK,EAAE,SAAS,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;IAClH,IAAI,MAAM,KAAK,SAAS;QAAE,OAAO,MAAM,CAAC;IACxC,OAAO,iBAAiB,EAAE,CAAC;AAAA,CAC3B","sourcesContent":["import type { AgentMessage } from \"@ponythewhite/base-context-agent\";\nimport {\n\ttype Context,\n\ttype ProviderRequestProjection,\n\ttype ProviderRequestPublicMessage,\n\ttype ProviderRequestRepresentation,\n\ttype RequestTokenAssessment,\n\tRequestTokenBudgetError,\n\ttype RequestTokenBudgetEvaluator,\n\twithRequestBody,\n} from \"@ponythewhite/base-context-ai\";\nimport {\n\ttype CanonicalViewSelectionSource,\n\tcaptureCanonicalRequestMessages,\n\tgetCanonicalEpochContext,\n\tgetCanonicalViewSelectionSource,\n\tpreparePublicContextWindow,\n\tprepareToolContinuationWindow,\n} from \"./canonical-context.js\";\nimport { convertToLlm } from \"./messages.js\";\nimport type { ContextEpochEntryRef, SourceSnapshotRef } from \"./request-events.js\";\nimport { bindMessageReplayUnits, closeViewSelection, prepareViewSelection } from \"./view-units.js\";\n\n/** Actual adapter-public measurement, not a verdict about the opaque native request. */\nexport class PublicContextBudgetError extends RequestTokenBudgetError {\n\treadonly source: SourceSnapshotRef;\n\t#compactionKey?: string;\n\t#summaryCapacity?: (retained: ReadonlySet<string>, wrapper: string) => number | undefined;\n\n\tremainingSummaryTokens(retained: ReadonlySet<string>, wrapper: string): number | undefined {\n\t\treturn this.#summaryCapacity?.(retained, wrapper);\n\t}\n\n\tgetCompactionKey(): string | undefined {\n\t\treturn this.#compactionKey;\n\t}\n\n\tconstructor(\n\t\tsource: SourceSnapshotRef,\n\t\tassessment: RequestTokenAssessment,\n\t\treadonly originalAssessment: RequestTokenAssessment,\n\t\treadonly mandatoryAssessment?: RequestTokenAssessment,\n\t\treadonly taskFrameRebaseAvailable = false,\n\t\tcompactionKey?: string,\n\t\tsummaryCapacity?: (retained: ReadonlySet<string>, wrapper: string) => number | undefined,\n\t\treadonly isSourceCurrent?: () => boolean,\n\t) {\n\t\tsuper(assessment);\n\t\tthis.name = \"PublicContextBudgetError\";\n\t\tif (mandatoryAssessment?.status === \"over-budget\")\n\t\t\tthis.message =\n\t\t\t\t\"Context capacity exceeded: instructions, tools, mandatory evidence and output allowance cannot fit. Summarizing unrelated history cannot resolve this request.\";\n\t\tthis.source = Object.freeze({ ...source });\n\t\tthis.#compactionKey = compactionKey;\n\t\tthis.#summaryCapacity = summaryCapacity;\n\t}\n}\n\nexport interface RequestViewCandidate {\n\t/** Session-local Responses ID namespace; a new owner requires a fresh representation. */\n\treadonly responseItemIdentity?: string;\n\treadonly source: SourceSnapshotRef;\n\treadonly selectedUnitIds: readonly string[];\n\treadonly request: ProviderRequestRepresentation;\n\treadonly projection: ProviderRequestProjection;\n\t// Absent only for mandatory full-view admission without a configured token budget.\n\treadonly assessment: RequestTokenAssessment | undefined;\n\treadonly originalAssessment: RequestTokenAssessment | undefined;\n\t/** Exact public messages represented by the accepted candidate, with captured source recipes. */\n\treadonly publicMessages?: readonly AgentMessage[];\n}\n\n/** Root resolves only after its canonical epoch checkpoint ACK. This module owns no epoch state. */\nexport type RequestViewCommit = (\n\tcandidate: RequestViewCandidate,\n) => Promise<ContextEpochEntryRef | undefined> | Promise<void>;\nexport type RequestViewValidate = (\n\trequest: ProviderRequestRepresentation,\n\tassessment: RequestTokenAssessment | undefined,\n) => void;\n\nexport type RequestViewFixedPrepare = (\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tassessment: RequestTokenAssessment | undefined,\n) => ContextEpochEntryRef | void | Promise<ContextEpochEntryRef | undefined> | Promise<void>;\n\nexport interface CapturedRequestViewBoundary extends CanonicalViewSelectionSource {\n\treadonly responseItemIdentity?: string;\n\treadonly messages: readonly AgentMessage[];\n\t/** Provider logical positions mapped to the unchanged canonical messages/units. */\n\treadonly providerMessageIndices: readonly number[];\n\treadonly providerPendingPublicMessageGroups?: readonly (readonly number[])[];\n\treadonly commit: RequestViewCommit;\n\treadonly validate?: RequestViewValidate;\n\treadonly fixedPrepare?: RequestViewFixedPrepare;\n\treadonly isSourceCurrent?: () => boolean;\n}\n\nexport function captureRequestViewBoundary(\n\tmessages: readonly AgentMessage[],\n\tcommit: RequestViewCommit,\n\tvalidate?: RequestViewValidate,\n\tfixedPrepare?: RequestViewFixedPrepare,\n\tisSourceCurrent?: () => boolean,\n): CapturedRequestViewBoundary {\n\tconst source = getCanonicalViewSelectionSource(messages);\n\tif (!source) throw new Error(\"Request view boundary requires compiled canonical messages\");\n\tconst providerMessageIndices = messages.flatMap((message, index) => convertToLlm([message]).map(() => index));\n\treturn {\n\t\t...source,\n\t\tmessages: captureCanonicalRequestMessages(messages),\n\t\tproviderMessageIndices,\n\t\t...(source.pendingPublicMessageGroups\n\t\t\t? {\n\t\t\t\t\tproviderPendingPublicMessageGroups: source.pendingPublicMessageGroups.map((group) =>\n\t\t\t\t\t\tgroup.map((index) => providerMessageIndex(providerMessageIndices, index)),\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t\tcommit,\n\t\tvalidate,\n\t\tfixedPrepare,\n\t\tisSourceCurrent,\n\t};\n}\n\nfunction providerMessageIndex(indices: readonly number[], canonicalIndex: number): number {\n\tconst index = indices.indexOf(canonicalIndex);\n\tif (index < 0) throw new Error(\"Provider projection cannot address a filtered canonical message\");\n\treturn index;\n}\n\n/** Keep canonical UI barriers while translating the native serializer's provider-only positions. */\nfunction canonicalRequestProjection(\n\tboundary: CapturedRequestViewBoundary,\n\tprojection: ProviderRequestProjection,\n): ProviderRequestProjection {\n\tconst indices = boundary.providerMessageIndices;\n\tif (indices.length === boundary.messages.length) return projection;\n\tconst canonicalIndex = (index: number): number => {\n\t\tconst canonical = indices[index];\n\t\tif (canonical === undefined) throw new Error(\"Provider projection message index is outside its captured view\");\n\t\treturn canonical;\n\t};\n\treturn {\n\t\t...projection,\n\t\tmessageIndices: projection.messageIndices.map((index) => (index === null ? null : canonicalIndex(index))),\n\t\t...(projection.optionalMessageIndices\n\t\t\t? { optionalMessageIndices: projection.optionalMessageIndices.map(canonicalIndex) }\n\t\t\t: {}),\n\t\t...(projection.generatedMessageIndices\n\t\t\t? { generatedMessageIndices: projection.generatedMessageIndices.map(canonicalIndex) }\n\t\t\t: {}),\n\t\t...(projection.publicMessageGroups\n\t\t\t? { publicMessageGroups: projection.publicMessageGroups.map((group) => group.map(canonicalIndex)) }\n\t\t\t: {}),\n\t\t...(projection.pendingPublicMessageGroups\n\t\t\t? {\n\t\t\t\t\tpendingPublicMessageGroups: projection.pendingPublicMessageGroups.map((group) =>\n\t\t\t\t\t\tgroup.map(canonicalIndex),\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t\t...(projection.encodePublicWindow\n\t\t\t? {\n\t\t\t\t\tencodePublicWindow: (replacements: readonly ProviderRequestPublicMessage[]) => {\n\t\t\t\t\t\tconst encoded = projection.encodePublicWindow!(\n\t\t\t\t\t\t\treplacements.map((replacement) => ({\n\t\t\t\t\t\t\t\t...replacement,\n\t\t\t\t\t\t\t\tmessageIndex: providerMessageIndex(indices, replacement.messageIndex),\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\tencoded && { ...encoded, projection: canonicalRequestProjection(boundary, encoded.projection) }\n\t\t\t\t\t\t);\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\nexport function matchesRequestView(\n\tboundary: CapturedRequestViewBoundary,\n\tsource: SourceSnapshotRef,\n\tcontext: Context,\n): boolean {\n\tconst expected = boundary.source;\n\tif (\n\t\texpected.sessionId !== source.sessionId ||\n\t\texpected.sessionFile !== source.sessionFile ||\n\t\texpected.leafId !== source.leafId ||\n\t\texpected.sourceSequence !== source.sourceSequence\n\t)\n\t\treturn false;\n\tconst rendered = convertToLlm([...boundary.messages]);\n\treturn (\n\t\tboundary.messages.length === boundary.units.length &&\n\t\trendered.length === boundary.providerMessageIndices.length &&\n\t\tJSON.stringify(rendered) === JSON.stringify(context.messages)\n\t);\n}\n\n/** Projection kinds describe their actual provider body, never an OpenAI-format route alias. */\nfunction requestInputKey(\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n): \"input\" | \"messages\" | undefined {\n\tif (\n\t\t(request.api === \"openai-responses\" || request.api === \"openai-codex-responses\") &&\n\t\t(projection.kind === \"openai-responses-text-v1\" || projection.kind === \"openai-responses-replay-v1\")\n\t)\n\t\treturn \"input\";\n\tif (\n\t\trequest.api === \"openai-completions\" &&\n\t\trequest.provider === \"deepseek\" &&\n\t\trequest.url === \"https://api.deepseek.com/chat/completions\" &&\n\t\tprojection.kind === \"deepseek-completions-text-tools-v1\" &&\n\t\trequest.body !== undefined &&\n\t\tJSON.parse(request.body).model === \"deepseek-flash\"\n\t)\n\t\treturn \"messages\";\n\treturn undefined;\n}\n\n/** A lower bound for compaction: fixed policy, current tail and required recorded evidence. */\nfunction publicBudgetFailure(\n\tboundary: CapturedRequestViewBoundary,\n\tmessages: readonly AgentMessage[],\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tbudget: RequestTokenBudgetEvaluator,\n\tassessment: RequestTokenAssessment,\n\toriginal: RequestTokenAssessment,\n): PublicContextBudgetError {\n\tconst context = getCanonicalEpochContext(messages)!;\n\tconst source = getCanonicalViewSelectionSource(messages)!;\n\tconst toolEntries = new Set(\n\t\tcontext.toolContinuations?.flatMap((group) => [\n\t\t\tgroup.assistantEntryId,\n\t\t\t...group.calls.flatMap((call) => (call.result ? [call.result.id] : [])),\n\t\t]),\n\t);\n\tlet tailSequence = -1;\n\tfor (const reference of context.references)\n\t\tif (reference && reference.ref.kind !== \"compaction\")\n\t\t\ttailSequence = Math.max(tailSequence, reference.ref.sequence);\n\tconst required = new Set(\n\t\tsource.units.flatMap((unit, index) => {\n\t\t\tconst reference = context.references[index];\n\t\t\treturn [\"task-frame\", \"resource-view\", \"recovery\"].includes(unit.kind) ||\n\t\t\t\tunit.id === \"native-selected-skill-versions\" ||\n\t\t\t\t(reference && (reference.ref.sequence === tailSequence || toolEntries.has(reference.ref.entryId)))\n\t\t\t\t? [index]\n\t\t\t\t: [];\n\t\t}),\n\t);\n\tconst inputKey = requestInputKey(request, projection)!;\n\tconst body = JSON.parse(request.body!) as Record<string, unknown>;\n\tconst input = body[inputKey];\n\tif (!Array.isArray(input) || input.length !== projection.messageIndices.length)\n\t\treturn new PublicContextBudgetError(\n\t\t\tboundary.source,\n\t\t\tassessment,\n\t\t\toriginal,\n\t\t\tundefined,\n\t\t\tfalse,\n\t\t\tundefined,\n\t\t\tundefined,\n\t\t\tboundary.isSourceCurrent,\n\t\t);\n\tconst graph = prepareViewSelection(source.units, boundary.limits);\n\tconst retainedInput = (retained: ReadonlySet<string>) => {\n\t\tconst roots = source.units\n\t\t\t.filter((_, index) => required.has(index) || retained.has(context.references[index]?.ref.entryId ?? \"\"))\n\t\t\t.map((unit) => unit.id);\n\t\tconst selected = new Set(graph.close(roots).map((unit) => unit.id));\n\t\treturn input.filter((_, index) => {\n\t\t\tconst messageIndex = projection.messageIndices[index];\n\t\t\treturn messageIndex === null || selected.has(source.units[messageIndex].id);\n\t\t});\n\t};\n\tconst minimum = withRequestBody(request, JSON.stringify({ ...body, [inputKey]: retainedInput(new Set()) }));\n\treturn new PublicContextBudgetError(\n\t\tboundary.source,\n\t\tassessment,\n\t\toriginal,\n\t\tbudget.measure(minimum),\n\t\t(context.taskFrame?.messages.length ?? 0) > 1,\n\t\tJSON.stringify([\n\t\t\tboundary.source.sessionId,\n\t\t\tboundary.source.sessionFile,\n\t\t\tsource.units.map((unit) => [unit.id, unit.sourceRevision]),\n\t\t\tassessment.api,\n\t\t\tassessment.provider,\n\t\t\tassessment.model,\n\t\t\tassessment.route,\n\t\t\tassessment.profile,\n\t\t\tassessment.availableInputTokens,\n\t\t\tassessment.outputReserveTokens,\n\t\t]),\n\t\t(retained, wrapper) => {\n\t\t\t// Meter only; this synthetic empty summary is never admitted or sent.\n\t\t\tconst summary =\n\t\t\t\tinputKey === \"messages\"\n\t\t\t\t\t? { role: \"user\", content: wrapper }\n\t\t\t\t\t: { role: \"user\", content: [{ type: \"input_text\", text: wrapper }] };\n\t\t\tconst kept = retainedInput(retained);\n\t\t\tconst position = kept.findIndex((item) => item?.role !== \"system\" && item?.role !== \"developer\");\n\t\t\tkept.splice(position < 0 ? kept.length : position, 0, summary);\n\t\t\tconst measured = budget.measure(withRequestBody(request, JSON.stringify({ ...body, [inputKey]: kept })));\n\t\t\treturn measured.status === \"unknown\" ||\n\t\t\t\tmeasured.availableInputTokens === null ||\n\t\t\t\tmeasured.estimatedInputTokens === null\n\t\t\t\t? undefined\n\t\t\t\t: Math.floor(measured.availableInputTokens - measured.estimatedInputTokens);\n\t\t},\n\t\tboundary.isSourceCurrent,\n\t);\n}\n\n/** Check the actual final mapping without selecting, converting, or committing another view. */\nexport async function prepareFixedRequestView(\n\tboundary: CapturedRequestViewBoundary,\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tassessment: RequestTokenAssessment | undefined,\n) {\n\tprojection = canonicalRequestProjection(boundary, projection);\n\tconst inputKey = requestInputKey(request, projection);\n\tconst payload = JSON.parse(request.body!) as Record<string, unknown> | null;\n\tconst input = inputKey && payload ? payload[inputKey] : undefined;\n\tif (!Array.isArray(input) || input.length !== projection.messageIndices.length)\n\t\tthrow new Error(\"Fixed context requires its final provider projection\");\n\tif (\n\t\tprojection.kind === \"openai-responses-text-v1\" &&\n\t\tboundary.messages.some(\n\t\t\t(message) =>\n\t\t\t\tmessage.role === \"toolResult\" ||\n\t\t\t\t(message.role === \"assistant\" && (message.content.length !== 1 || message.content[0].type !== \"text\")),\n\t\t)\n\t)\n\t\tthrow new Error(\"Fixed context requires its native replay adapter\");\n\tconst units = bindMessageReplayUnits(\n\t\tboundary.messages,\n\t\tboundary.units,\n\t\tboundary.limits,\n\t\tprojection.replayContract ?? \"complete-context\",\n\t);\n\tcloseViewSelection(\n\t\tunits,\n\t\tunits.map((unit) => unit.id),\n\t\tboundary.limits,\n\t);\n\treturn await boundary.fixedPrepare!(request, projection, assessment);\n}\n\n/** Reuse the same legal omission policy for native and already-converted public requests. */\nasync function offerOptionalSubset(\n\tmessages: readonly AgentMessage[],\n\tunits: CanonicalViewSelectionSource[\"units\"],\n\tselection: ReturnType<typeof prepareViewSelection>,\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tbudget: RequestTokenBudgetEvaluator,\n\toffer: (\n\t\tids: readonly string[],\n\t\trequest: ProviderRequestRepresentation,\n\t\tprojection: ProviderRequestProjection,\n\t\tassessment: RequestTokenAssessment,\n\t) => Promise<unknown>,\n): Promise<string | undefined> {\n\tconst inputKey = requestInputKey(request, projection);\n\tif (!inputKey) return;\n\tconst payload = JSON.parse(request.body!) as Record<string, unknown>;\n\tconst input = payload[inputKey];\n\tif (!Array.isArray(input) || input.length !== projection.messageIndices.length) return;\n\tlet latestAssistant = -1;\n\tfor (const [index, message] of messages.entries()) if (message.role === \"assistant\") latestAssistant = index;\n\tconst retained = new Set(projection.messageIndices.slice(0, request.retainedPrefix?.inputItems ?? 0));\n\tconst projectedOptional =\n\t\tprojection.kind !== \"openai-responses-text-v1\" ? new Set(projection.optionalMessageIndices ?? []) : undefined;\n\tconst optional = units.filter((unit, index) => {\n\t\tconst message = messages[index];\n\t\treturn (\n\t\t\tindex !== latestAssistant &&\n\t\t\t!retained.has(index) &&\n\t\t\t(!projectedOptional || projectedOptional.has(index)) &&\n\t\t\tunit.kind === \"literal\" &&\n\t\t\tunit.authority === \"assistant-public\" &&\n\t\t\tmessage.role === \"assistant\" &&\n\t\t\tmessage.stopReason === \"stop\" &&\n\t\t\tmessage.content.length === 1 &&\n\t\t\tmessage.content[0].type === \"text\"\n\t\t);\n\t});\n\tconst generatedPositions = new Map<string, number>();\n\tconst generated =\n\t\tprojection.generatedMessageIndices ??\n\t\tmessages.flatMap((message, index) =>\n\t\t\tmessage.role === \"assistant\" &&\n\t\t\tmessage.content.some((block) => block.type === \"text\" && block.textSignature === undefined)\n\t\t\t\t? [index]\n\t\t\t\t: [],\n\t\t);\n\tfor (const index of generated) generatedPositions.set(units[index].id, index);\n\t// All user inputs, the latest assistant, fixed/TaskFrame/recovery units and errors stay selected.\n\tconst selected = new Set(units.map((unit) => unit.id));\n\tfor (const unit of optional) {\n\t\tselected.delete(unit.id);\n\t\tconst closed = selection.close([...selected]);\n\t\t// Normal Responses rendering uses msg_<message index> for unsigned assistants.\n\t\t// Reject any subset that would change a retained generated item ID on reconstruction.\n\t\tif (closed.some((item, index) => generatedPositions.has(item.id) && generatedPositions.get(item.id) !== index))\n\t\t\tcontinue;\n\t\tconst closedIds = new Set(closed.map((item) => item.id));\n\t\tconst keepItem = (index: number) => {\n\t\t\tconst messageIndex = projection.messageIndices[index];\n\t\t\treturn messageIndex === null || closedIds.has(units[messageIndex].id);\n\t\t};\n\t\tconst body = JSON.stringify({ ...payload, [inputKey]: input.filter((_, index) => keepItem(index)) });\n\t\tconst candidateRequest = { ...request, body };\n\t\tconst assessment = budget.measure(candidateRequest);\n\t\tif (assessment.status !== \"within-estimate\") continue;\n\t\tawait offer(\n\t\t\tclosed.map((item) => item.id),\n\t\t\tcandidateRequest,\n\t\t\t{\n\t\t\t\t...projection,\n\t\t\t\tmessageIndices: projection.messageIndices.filter((_, index) => keepItem(index)),\n\t\t\t\t...(projection.optionalMessageIndices\n\t\t\t\t\t? {\n\t\t\t\t\t\t\toptionalMessageIndices: projection.optionalMessageIndices.filter((index) =>\n\t\t\t\t\t\t\t\tclosedIds.has(units[index].id),\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...(projection.generatedMessageIndices\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tgeneratedMessageIndices: projection.generatedMessageIndices.filter((index) =>\n\t\t\t\t\t\t\t\tclosedIds.has(units[index].id),\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},\n\t\t\tassessment,\n\t\t);\n\t\treturn body;\n\t}\n\treturn;\n}\n\n/** Only the actual serializer's established replay contract authorizes historical-literal omission. */\nexport async function selectRequestView(\n\tboundary: CapturedRequestViewBoundary,\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tbudget: RequestTokenBudgetEvaluator | undefined,\n\tallowShrink: boolean,\n\tfinalizeMeasurement?: (\n\t\trequest: ProviderRequestRepresentation,\n\t\tassessment: RequestTokenAssessment | undefined,\n\t) => Promise<RequestTokenAssessment | undefined>,\n): Promise<string | undefined> {\n\tprojection = canonicalRequestProjection(boundary, projection);\n\tlet full = budget?.measure(request);\n\tconst inputKey = requestInputKey(request, projection);\n\tif ((budget && full?.limitSource !== \"explicit-profile\") || !inputKey) return;\n\tif (!budget && !boundary.requiresEpoch && !boundary.pendingPublicMessageGroups?.length) return;\n\tconst payload = JSON.parse(request.body!) as Record<string, unknown>;\n\tconst input = payload[inputKey];\n\tif (!Array.isArray(input) || input.length !== projection.messageIndices.length) return;\n\t// Resolve a near-limit estimate before discarding a stable native prefix. Original\n\t// protected tool groups must first pass their public conversion below.\n\tif (\n\t\tfull?.status === \"over-budget\" &&\n\t\t!boundary.pendingPublicMessageGroups?.length &&\n\t\t!projection.pendingPublicMessageGroups?.length\n\t)\n\t\tfull = (await finalizeMeasurement?.(request, full)) ?? full;\n\n\t// Absence is complete-context; a profile or tool-shaped message is never group authority.\n\tconst replayContract = projection.replayContract ?? \"complete-context\";\n\tif (\n\t\tprojection.kind === \"openai-responses-text-v1\" &&\n\t\tboundary.messages.some(\n\t\t\t(message) =>\n\t\t\t\tmessage.role === \"toolResult\" ||\n\t\t\t\t(message.role === \"assistant\" && (message.content.length !== 1 || message.content[0].type !== \"text\")),\n\t\t)\n\t)\n\t\treturn;\n\tconst units = bindMessageReplayUnits(\n\t\tboundary.messages,\n\t\tboundary.units,\n\t\tboundary.limits,\n\t\treplayContract,\n\t\tboundary.pendingPublicMessageGroups,\n\t);\n\tconst selection = prepareViewSelection(units, boundary.limits);\n\tconst offer = async (\n\t\tselectedUnitIds: readonly string[],\n\t\tcandidateRequest: ProviderRequestRepresentation,\n\t\tcandidateProjection: ProviderRequestProjection,\n\t\tassessment: RequestTokenAssessment | undefined,\n\t\tpublicMessages?: readonly AgentMessage[],\n\t) => {\n\t\tassessment = (await finalizeMeasurement?.(candidateRequest, assessment)) ?? assessment;\n\t\tif (budget && assessment) {\n\t\t\tif (assessment.status === \"over-budget\" && full)\n\t\t\t\tthrow publicBudgetFailure(\n\t\t\t\t\tboundary,\n\t\t\t\t\tpublicMessages ?? boundary.messages,\n\t\t\t\t\tcandidateRequest,\n\t\t\t\t\tcandidateProjection,\n\t\t\t\t\tbudget,\n\t\t\t\t\tassessment,\n\t\t\t\t\tfull,\n\t\t\t\t);\n\t\t\tbudget.assert(assessment);\n\t\t}\n\t\treturn boundary.commit(\n\t\t\tObject.freeze({\n\t\t\t\t...(boundary.responseItemIdentity ? { responseItemIdentity: boundary.responseItemIdentity } : {}),\n\t\t\t\tsource: Object.freeze({ ...boundary.source }),\n\t\t\t\tselectedUnitIds: Object.freeze([...selectedUnitIds]),\n\t\t\t\trequest: Object.freeze({ ...candidateRequest }),\n\t\t\t\tprojection: Object.freeze({\n\t\t\t\t\t...candidateProjection,\n\t\t\t\t\treplayContract,\n\t\t\t\t\tmessageIndices: Object.freeze([...candidateProjection.messageIndices]),\n\t\t\t\t\t...(candidateProjection.optionalMessageIndices\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\toptionalMessageIndices: Object.freeze([...candidateProjection.optionalMessageIndices]),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(candidateProjection.generatedMessageIndices\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tgeneratedMessageIndices: Object.freeze([...candidateProjection.generatedMessageIndices]),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t}),\n\t\t\t\tassessment,\n\t\t\t\toriginalAssessment: full,\n\t\t\t\t...(publicMessages ? { publicMessages } : {}),\n\t\t\t}),\n\t\t);\n\t};\n\tconst offerPublicSubset = async (\n\t\tmessages: readonly AgentMessage[],\n\t\trequest: ProviderRequestRepresentation,\n\t\tprojection: ProviderRequestProjection,\n\t): Promise<string | undefined> => {\n\t\tif (!allowShrink || !budget || replayContract !== \"message-groups\") return;\n\t\tconst source = getCanonicalViewSelectionSource(messages)!;\n\t\tconst units = bindMessageReplayUnits(messages, source.units, boundary.limits, replayContract);\n\t\treturn offerOptionalSubset(\n\t\t\tmessages,\n\t\t\tunits,\n\t\t\tprepareViewSelection(units, boundary.limits),\n\t\t\trequest,\n\t\t\tprojection,\n\t\t\tbudget,\n\t\t\t(ids, candidate, mapping, assessment) => offer(ids, candidate, mapping, assessment, messages),\n\t\t);\n\t};\n\tif (boundary.pendingPublicMessageGroups?.length) {\n\t\tif (\n\t\t\treplayContract !== \"message-groups\" ||\n\t\t\t!projection.publicWindow ||\n\t\t\t!projection.encodePublicWindow ||\n\t\t\tJSON.stringify(projection.pendingPublicMessageGroups) !== JSON.stringify(boundary.pendingPublicMessageGroups)\n\t\t)\n\t\t\tthrow new Error(\"Original tool group requires current native adapter public conversion\");\n\t\tconst publicView = prepareToolContinuationWindow(boundary.messages);\n\t\tconst encoded = projection.encodePublicWindow(publicView.replacements);\n\t\tif (!encoded || encoded.projection.pendingPublicMessageGroups?.length)\n\t\t\tthrow new Error(\"Native adapter did not convert the whole required tool group\");\n\t\tconst publicSource = getCanonicalViewSelectionSource(publicView.messages)!;\n\t\tconst publicUnits = bindMessageReplayUnits(\n\t\t\tpublicView.messages,\n\t\t\tpublicSource.units,\n\t\t\tboundary.limits,\n\t\t\treplayContract,\n\t\t);\n\t\tconst closed = closeViewSelection(\n\t\t\tpublicUnits,\n\t\t\tpublicUnits.map((unit) => unit.id),\n\t\t\tboundary.limits,\n\t\t);\n\t\tlet assessment = budget?.measure(encoded.request);\n\t\tif (assessment?.status === \"over-budget\")\n\t\t\tassessment = (await finalizeMeasurement?.(encoded.request, assessment)) ?? assessment;\n\t\tif (assessment && full) {\n\t\t\tif (assessment.status === \"over-budget\") {\n\t\t\t\tconst subset = await offerPublicSubset(publicView.messages, encoded.request, encoded.projection);\n\t\t\t\tif (subset !== undefined) return subset;\n\t\t\t\tthrow publicBudgetFailure(\n\t\t\t\t\tboundary,\n\t\t\t\t\tpublicView.messages,\n\t\t\t\t\tencoded.request,\n\t\t\t\t\tencoded.projection,\n\t\t\t\t\tbudget!,\n\t\t\t\t\tassessment,\n\t\t\t\t\tfull,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (assessment.status !== \"within-estimate\")\n\t\t\t\tthrow new Error(\"Tool continuation public request exceeds its token budget\");\n\t\t}\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\tencoded.request,\n\t\t\tencoded.projection,\n\t\t\tassessment,\n\t\t\tpublicView.messages,\n\t\t);\n\t\treturn encoded.request.body;\n\t}\n\tif (projection.pendingPublicMessageGroups?.length)\n\t\tthrow new Error(\"Adapter pending group has no original owned source plan\");\n\t// Without a configured budget, admit only the exact full native view. Never shrink it.\n\tif (!budget) {\n\t\tconst closed = selection.close(units.map((unit) => unit.id));\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\trequest,\n\t\t\tprojection,\n\t\t\tundefined,\n\t\t);\n\t\treturn request.body;\n\t}\n\tif (!full) return;\n\tconst offerPublicWindow = async (): Promise<string | undefined> => {\n\t\tif (\n\t\t\t!allowShrink ||\n\t\t\treplayContract !== \"message-groups\" ||\n\t\t\t!projection.publicWindow ||\n\t\t\t!projection.encodePublicWindow\n\t\t)\n\t\t\treturn;\n\t\tconst closed = selection.close(units.map((unit) => unit.id));\n\t\tlet firstMessageIndex = 0;\n\t\tif (\n\t\t\tfull.status === \"unknown\" &&\n\t\t\tfull.unknown.length === 1 &&\n\t\t\tfull.unknown[0] === \"media, opaque or unsupported replay token coverage unknown\"\n\t\t) {\n\t\t\t// Credited items are not part of the unknown input. Keep original projection indices.\n\t\t\tconst firstUnmeteredItem = request.retainedPrefix?.inputItems ?? 0;\n\t\t\tconst reasoningItemIndex = input.findIndex(\n\t\t\t\t(item, index) => index >= firstUnmeteredItem && item?.type === \"reasoning\",\n\t\t\t);\n\t\t\tconst messageIndex = projection.messageIndices[reasoningItemIndex];\n\t\t\tconst group =\n\t\t\t\tmessageIndex == null\n\t\t\t\t\t? undefined\n\t\t\t\t\t: projection.publicMessageGroups?.find((members) => members.includes(messageIndex));\n\t\t\t// The adapter still accepts only complete groups; earlier meterable groups stay native.\n\t\t\tfirstMessageIndex = group ? Math.min(...group) : 0;\n\t\t}\n\t\tconst publicView = preparePublicContextWindow(boundary.messages, firstMessageIndex);\n\t\tif (!publicView) {\n\t\t\t// Keep the original measured refusal when no public conversion can be offered.\n\t\t\t// This is not a new recovery signal or permission to reprepare again.\n\t\t\tif (full.status === \"over-budget\") throw new RequestTokenBudgetError(full);\n\t\t\treturn;\n\t\t}\n\t\tconst encoded = projection.encodePublicWindow(publicView.replacements);\n\t\tif (!encoded) return;\n\t\tlet assessment = budget.measure(encoded.request);\n\t\tif (assessment.status === \"over-budget\")\n\t\t\tassessment = (await finalizeMeasurement?.(encoded.request, assessment)) ?? assessment;\n\t\tif (assessment.status === \"over-budget\") {\n\t\t\tconst subset = await offerPublicSubset(publicView.messages, encoded.request, encoded.projection);\n\t\t\tif (subset !== undefined) return subset;\n\t\t\tthrow publicBudgetFailure(\n\t\t\t\tboundary,\n\t\t\t\tpublicView.messages,\n\t\t\t\tencoded.request,\n\t\t\t\tencoded.projection,\n\t\t\t\tbudget,\n\t\t\t\tassessment,\n\t\t\t\tfull,\n\t\t\t);\n\t\t}\n\t\tif (assessment.status !== \"within-estimate\") return;\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\tencoded.request,\n\t\t\tencoded.projection,\n\t\t\tassessment,\n\t\t\tpublicView.messages,\n\t\t);\n\t\treturn encoded.request.body;\n\t};\n\tif (full.status === \"within-estimate\") {\n\t\tconst closed = selection.close(units.map((unit) => unit.id));\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\trequest,\n\t\t\tprojection,\n\t\t\tfull,\n\t\t);\n\t\treturn request.body;\n\t}\n\tif (!allowShrink || replayContract !== \"message-groups\") return;\n\tif (full.status !== \"over-budget\") return offerPublicWindow();\n\tconst subset = await offerOptionalSubset(boundary.messages, units, selection, request, projection, budget, offer);\n\tif (subset !== undefined) return subset;\n\treturn offerPublicWindow();\n}\n"]}
|
|
@@ -36,6 +36,8 @@ export interface SessionHeader {
|
|
|
36
36
|
}
|
|
37
37
|
/** One captured branch for summary input, physical requests, and the queued compaction commit. */
|
|
38
38
|
export interface BoundCompactionSink extends BoundSessionRequestSink {
|
|
39
|
+
/** Original ownership and compaction input, including this sink's own acknowledged checkpoint. */
|
|
40
|
+
isCurrent(): boolean;
|
|
39
41
|
/** Internal explicit-copy read on this same held source, never a provider-view capability. */
|
|
40
42
|
[readCopiedEpochSource]<T>(read: (history: SessionHistoryReadScope) => Promise<T>): Promise<T>;
|
|
41
43
|
readBranch(): Promise<SessionEntry[]>;
|