@ponythewhite/base-context 1.0.9 → 1.0.11
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 +19 -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-5JRM6P4T.js → bundled-modules-PEFT72QN.js} +2 -2
- package/dist/bundle/{chunk-VVI3UKGR.js → chunk-JZHGOOFM.js} +87 -57
- package/dist/bundle/{chunk-NEHLB7JV.js → chunk-TOOVREMP.js} +596 -102
- package/dist/bundle/{cli-main-YUDBEYE2.js → cli-main-BRXGYTGK.js} +2 -2
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/{main-ZLGGAAGU.js → main-POUXGEL6.js} +2 -2
- package/dist/core/agent-session.d.ts +0 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +85 -45
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/canonical-context.d.ts +19 -3
- package/dist/core/canonical-context.d.ts.map +1 -1
- package/dist/core/canonical-context.js +245 -39
- package/dist/core/canonical-context.js.map +1 -1
- package/dist/core/context-epoch-copy.d.ts +1 -1
- package/dist/core/context-epoch-copy.d.ts.map +1 -1
- package/dist/core/context-epoch-copy.js +18 -7
- package/dist/core/context-epoch-copy.js.map +1 -1
- package/dist/core/context-epoch.d.ts +18 -3
- package/dist/core/context-epoch.d.ts.map +1 -1
- package/dist/core/context-epoch.js +13 -2
- package/dist/core/context-epoch.js.map +1 -1
- package/dist/core/context-tree.d.ts +1 -1
- package/dist/core/context-tree.d.ts.map +1 -1
- package/dist/core/context-tree.js +98 -8
- package/dist/core/context-tree.js.map +1 -1
- package/dist/core/history-index-worker.d.ts.map +1 -1
- package/dist/core/history-index-worker.js +59 -6
- package/dist/core/history-index-worker.js.map +1 -1
- package/dist/core/history-index.d.ts +17 -0
- package/dist/core/history-index.d.ts.map +1 -1
- package/dist/core/history-index.js +22 -0
- package/dist/core/history-index.js.map +1 -1
- package/dist/core/inference-coordinator.d.ts.map +1 -1
- package/dist/core/inference-coordinator.js +5 -1
- 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 +2 -1
- package/dist/core/request-view-selection.d.ts.map +1 -1
- package/dist/core/request-view-selection.js +29 -2
- package/dist/core/request-view-selection.js.map +1 -1
- package/dist/core/session-fork-messages.d.ts +5 -0
- package/dist/core/session-fork-messages.d.ts.map +1 -1
- package/dist/core/session-fork-messages.js +44 -0
- package/dist/core/session-fork-messages.js.map +1 -1
- package/dist/core/session-history-index.d.ts +5 -0
- package/dist/core/session-history-index.d.ts.map +1 -1
- package/dist/core/session-history-index.js +7 -0
- package/dist/core/session-history-index.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 +155 -13
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/session-tree.d.ts +9 -0
- package/dist/core/session-tree.d.ts.map +1 -1
- package/dist/core/session-tree.js +71 -11
- package/dist/core/session-tree.js.map +1 -1
- package/dist/modes/agent-connection/in-process-agent-connection.d.ts.map +1 -1
- package/dist/modes/agent-connection/in-process-agent-connection.js +4 -4
- package/dist/modes/agent-connection/in-process-agent-connection.js.map +1 -1
- package/dist/modes/daemon/daemon-mode.d.ts.map +1 -1
- package/dist/modes/daemon/daemon-mode.js +19 -34
- 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;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,EAAE,MAAM,EACtB,eAAe,CAAC,EAAE,CAAC,QAAQ,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AO,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"]}
|
|
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,KAAK,+BAA+B,EACpC,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,E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yB,EACrC,MAAM,EAAE,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,CA8P7B","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\ttype RecoveryCompactionAuthorization,\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\n// Only publicBudgetFailure can grant this authority to the exact error it creates.\n// Constructing a public error or copying its descriptive fields grants nothing.\nconst recoveryCompactionAuthorizations = new WeakMap<PublicContextBudgetError, RecoveryCompactionAuthorization>();\n\nexport function getRecoveryCompactionAuthorization(\n\terror: PublicContextBudgetError | undefined,\n): RecoveryCompactionAuthorization | undefined {\n\treturn error ? recoveryCompactionAuthorizations.get(error) : undefined;\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\tconst error = 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\tif (projection.replayContract === \"message-groups\") {\n\t\tconst originalContext = getCanonicalEpochContext(boundary.messages)!;\n\t\tconst recoveries = boundary.units.flatMap((unit, index) =>\n\t\t\tunit.kind === \"recovery\" && originalContext.references[index] ? [originalContext.references[index]!] : [],\n\t\t);\n\t\tif (recoveries.length) {\n\t\t\trecoveryCompactionAuthorizations.set(error, {\n\t\t\t\tsource: originalContext.source,\n\t\t\t\trecoveries,\n\t\t\t\tresourceRevision: originalContext.resourceRevision,\n\t\t\t\t// Do not extend a partial public conversion to native groups the encoder did not replace.\n\t\t\t\tpublicWindow:\n\t\t\t\t\tmessages !== boundary.messages &&\n\t\t\t\t\tprojection.publicWindow === true &&\n\t\t\t\t\tboundary.units.every(\n\t\t\t\t\t\t(unit, index) =>\n\t\t\t\t\t\t\t![\"recovery\", \"replay-group\"].includes(unit.kind) ||\n\t\t\t\t\t\t\tcontext.references[index]?.rendering !== undefined,\n\t\t\t\t\t),\n\t\t\t\tisSourceCurrent: boundary.isSourceCurrent,\n\t\t\t});\n\t\t}\n\t}\n\treturn error;\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 (\n\t\t!budget &&\n\t\t!boundary.requiresEpoch &&\n\t\t!boundary.recoveryContractRequested &&\n\t\t!boundary.pendingPublicMessageGroups?.length\n\t)\n\t\treturn;\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"]}
|
|
@@ -32,6 +32,12 @@ export class PublicContextBudgetError extends RequestTokenBudgetError {
|
|
|
32
32
|
this.#summaryCapacity = summaryCapacity;
|
|
33
33
|
}
|
|
34
34
|
}
|
|
35
|
+
// Only publicBudgetFailure can grant this authority to the exact error it creates.
|
|
36
|
+
// Constructing a public error or copying its descriptive fields grants nothing.
|
|
37
|
+
const recoveryCompactionAuthorizations = new WeakMap();
|
|
38
|
+
export function getRecoveryCompactionAuthorization(error) {
|
|
39
|
+
return error ? recoveryCompactionAuthorizations.get(error) : undefined;
|
|
40
|
+
}
|
|
35
41
|
export function captureRequestViewBoundary(messages, commit, validate, fixedPrepare, isSourceCurrent) {
|
|
36
42
|
const source = getCanonicalViewSelectionSource(messages);
|
|
37
43
|
if (!source)
|
|
@@ -162,7 +168,7 @@ function publicBudgetFailure(boundary, messages, request, projection, budget, as
|
|
|
162
168
|
});
|
|
163
169
|
};
|
|
164
170
|
const minimum = withRequestBody(request, JSON.stringify({ ...body, [inputKey]: retainedInput(new Set()) }));
|
|
165
|
-
|
|
171
|
+
const error = new PublicContextBudgetError(boundary.source, assessment, original, budget.measure(minimum), (context.taskFrame?.messages.length ?? 0) > 1, JSON.stringify([
|
|
166
172
|
boundary.source.sessionId,
|
|
167
173
|
boundary.source.sessionFile,
|
|
168
174
|
source.units.map((unit) => [unit.id, unit.sourceRevision]),
|
|
@@ -188,6 +194,24 @@ function publicBudgetFailure(boundary, messages, request, projection, budget, as
|
|
|
188
194
|
? undefined
|
|
189
195
|
: Math.floor(measured.availableInputTokens - measured.estimatedInputTokens);
|
|
190
196
|
}, boundary.isSourceCurrent);
|
|
197
|
+
if (projection.replayContract === "message-groups") {
|
|
198
|
+
const originalContext = getCanonicalEpochContext(boundary.messages);
|
|
199
|
+
const recoveries = boundary.units.flatMap((unit, index) => unit.kind === "recovery" && originalContext.references[index] ? [originalContext.references[index]] : []);
|
|
200
|
+
if (recoveries.length) {
|
|
201
|
+
recoveryCompactionAuthorizations.set(error, {
|
|
202
|
+
source: originalContext.source,
|
|
203
|
+
recoveries,
|
|
204
|
+
resourceRevision: originalContext.resourceRevision,
|
|
205
|
+
// Do not extend a partial public conversion to native groups the encoder did not replace.
|
|
206
|
+
publicWindow: messages !== boundary.messages &&
|
|
207
|
+
projection.publicWindow === true &&
|
|
208
|
+
boundary.units.every((unit, index) => !["recovery", "replay-group"].includes(unit.kind) ||
|
|
209
|
+
context.references[index]?.rendering !== undefined),
|
|
210
|
+
isSourceCurrent: boundary.isSourceCurrent,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return error;
|
|
191
215
|
}
|
|
192
216
|
/** Check the actual final mapping without selecting, converting, or committing another view. */
|
|
193
217
|
export async function prepareFixedRequestView(boundary, request, projection, assessment) {
|
|
@@ -284,7 +308,10 @@ export async function selectRequestView(boundary, request, projection, budget, a
|
|
|
284
308
|
const inputKey = requestInputKey(request, projection);
|
|
285
309
|
if ((budget && full?.limitSource !== "explicit-profile") || !inputKey)
|
|
286
310
|
return;
|
|
287
|
-
if (!budget &&
|
|
311
|
+
if (!budget &&
|
|
312
|
+
!boundary.requiresEpoch &&
|
|
313
|
+
!boundary.recoveryContractRequested &&
|
|
314
|
+
!boundary.pendingPublicMessageGroups?.length)
|
|
288
315
|
return;
|
|
289
316
|
const payload = JSON.parse(request.body);
|
|
290
317
|
const input = payload[inputKey];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request-view-selection.js","sourceRoot":"","sources":["../../src/core/request-view-selection.ts"],"names":[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;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"]}
|
|
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,GAE7B,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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AE,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAC7B,OAAO,CAAC,OAAO,EACf,OAAO,CAAC,UAAU,EAClB,UAAU,EACV,UAAU,CAAC,QAAQ,CACnB,CAAC;QACF,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC;IAAA,CAC5B,CAAC;IACF,IAAI,IAAI,CAAC,MAAM,KAAK,iBAAiB,EAAE,CAAC;QACvC,MAAM,MAAM,GAAG,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;QAC7D,MAAM,KAAK,CACV,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,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\ttype RecoveryCompactionAuthorization,\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\n// Only publicBudgetFailure can grant this authority to the exact error it creates.\n// Constructing a public error or copying its descriptive fields grants nothing.\nconst recoveryCompactionAuthorizations = new WeakMap<PublicContextBudgetError, RecoveryCompactionAuthorization>();\n\nexport function getRecoveryCompactionAuthorization(\n\terror: PublicContextBudgetError | undefined,\n): RecoveryCompactionAuthorization | undefined {\n\treturn error ? recoveryCompactionAuthorizations.get(error) : undefined;\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\tconst error = 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\tif (projection.replayContract === \"message-groups\") {\n\t\tconst originalContext = getCanonicalEpochContext(boundary.messages)!;\n\t\tconst recoveries = boundary.units.flatMap((unit, index) =>\n\t\t\tunit.kind === \"recovery\" && originalContext.references[index] ? [originalContext.references[index]!] : [],\n\t\t);\n\t\tif (recoveries.length) {\n\t\t\trecoveryCompactionAuthorizations.set(error, {\n\t\t\t\tsource: originalContext.source,\n\t\t\t\trecoveries,\n\t\t\t\tresourceRevision: originalContext.resourceRevision,\n\t\t\t\t// Do not extend a partial public conversion to native groups the encoder did not replace.\n\t\t\t\tpublicWindow:\n\t\t\t\t\tmessages !== boundary.messages &&\n\t\t\t\t\tprojection.publicWindow === true &&\n\t\t\t\t\tboundary.units.every(\n\t\t\t\t\t\t(unit, index) =>\n\t\t\t\t\t\t\t![\"recovery\", \"replay-group\"].includes(unit.kind) ||\n\t\t\t\t\t\t\tcontext.references[index]?.rendering !== undefined,\n\t\t\t\t\t),\n\t\t\t\tisSourceCurrent: boundary.isSourceCurrent,\n\t\t\t});\n\t\t}\n\t}\n\treturn error;\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 (\n\t\t!budget &&\n\t\t!boundary.requiresEpoch &&\n\t\t!boundary.recoveryContractRequested &&\n\t\t!boundary.pendingPublicMessageGroups?.length\n\t)\n\t\treturn;\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"]}
|
|
@@ -10,4 +10,9 @@ export declare function readUserMessagesForForking(manager: ReadonlySessionManag
|
|
|
10
10
|
entryId: string;
|
|
11
11
|
text: string;
|
|
12
12
|
}>>;
|
|
13
|
+
/** UI picker limits cover user-message candidates, not unrelated archive payloads. */
|
|
14
|
+
export declare function readVisibleUserMessagesForForking(manager: ReadonlySessionManager, limits?: SessionHistoryReadLimits): Promise<Array<{
|
|
15
|
+
entryId: string;
|
|
16
|
+
text: string;
|
|
17
|
+
}>>;
|
|
13
18
|
//# sourceMappingURL=session-fork-messages.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-fork-messages.d.ts","sourceRoot":"","sources":["../../src/core/session-fork-messages.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AAC3E,OAAO,KAAK,EAAE,sBAAsB,
|
|
1
|
+
{"version":3,"file":"session-fork-messages.d.ts","sourceRoot":"","sources":["../../src/core/session-fork-messages.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AAC3E,OAAO,KAAK,EAAE,sBAAsB,EAAgB,MAAM,sBAAsB,CAAC;AAEjF,eAAO,MAAM,2BAA2B,EAAE,QAAQ,CAAC,wBAAwB,CAGzE,CAAC;AAEH;;;;GAIG;AACH,wBAAsB,0BAA0B,CAC/C,OAAO,EAAE,sBAAsB,EAC/B,MAAM,GAAE,wBAAsD,GAC5D,OAAO,CAAC,KAAK,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC,CAMnD;AAoBD,sFAAsF;AACtF,wBAAsB,iCAAiC,CACtD,OAAO,EAAE,sBAAsB,EAC/B,MAAM,GAAE,wBAAsD,GAC5D,OAAO,CAAC,KAAK,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC,CAwCnD","sourcesContent":["import type { SessionHistoryReadLimits } from \"./session-history-index.js\";\nimport type { ReadonlySessionManager, SessionEntry } from \"./session-manager.js\";\n\nexport const DEFAULT_FORK_MESSAGE_LIMITS: Readonly<SessionHistoryReadLimits> = Object.freeze({\n\tmaxEntries: 16_384,\n\tmaxSourceBytes: 64 * 1024 * 1024,\n});\n\n/**\n * Complete source order, including other branches; refuse rather than return a clipped picker.\n * Limits count all entries before text filtering. Native bytes are frame bytes;\n * resident bytes are serialized header/entry JSON, not a heap estimate.\n */\nexport async function readUserMessagesForForking(\n\tmanager: ReadonlySessionManager,\n\tlimits: SessionHistoryReadLimits = DEFAULT_FORK_MESSAGE_LIMITS,\n): Promise<Array<{ entryId: string; text: string }>> {\n\tconst capturedLimits = { ...limits };\n\tconst entries = manager.supportsCapturedHistoryReads()\n\t\t? (await manager.materializeSourceHistory(capturedLimits)).entries.map(({ entry }) => entry)\n\t\t: manager.materializeResidentHistory(capturedLimits).entries;\n\treturn projectUserMessages(entries);\n}\n\nfunction projectUserMessages(entries: readonly SessionEntry[]): Array<{ entryId: string; text: string }> {\n\tconst result: Array<{ entryId: string; text: string }> = [];\n\tfor (const entry of entries) {\n\t\tif (entry.type !== \"message\" || entry.message.role !== \"user\") continue;\n\t\tconst content = entry.message.content;\n\t\tlet text = \"\";\n\t\tif (typeof content === \"string\") text = content;\n\t\telse if (Array.isArray(content)) {\n\t\t\ttext = content\n\t\t\t\t.filter((part) => part.type === \"text\")\n\t\t\t\t.map((part) => part.text)\n\t\t\t\t.join(\"\");\n\t\t}\n\t\tif (text) result.push({ entryId: entry.id, text });\n\t}\n\treturn result;\n}\n\n/** UI picker limits cover user-message candidates, not unrelated archive payloads. */\nexport async function readVisibleUserMessagesForForking(\n\tmanager: ReadonlySessionManager,\n\tlimits: SessionHistoryReadLimits = DEFAULT_FORK_MESSAGE_LIMITS,\n): Promise<Array<{ entryId: string; text: string }>> {\n\tconst { maxEntries, maxSourceBytes } = limits;\n\tif (\n\t\t!Number.isSafeInteger(maxEntries) ||\n\t\tmaxEntries <= 0 ||\n\t\t!Number.isSafeInteger(maxSourceBytes) ||\n\t\tmaxSourceBytes <= 0\n\t)\n\t\tthrow new Error(\"Invalid history materialization limits\");\n\tif (!manager.supportsCapturedHistoryReads())\n\t\treturn readUserMessagesForForking(manager, { maxEntries, maxSourceBytes });\n\treturn manager.readSourceHistory(async (history) => {\n\t\tconst entries: SessionEntry[] = [];\n\t\tlet sourceBytes = 0;\n\t\tlet after = 0;\n\t\tfor (;;) {\n\t\t\tconst page = await history.page(after);\n\t\t\tif (page.indexedThrough < history.source.sourceSequence)\n\t\t\t\tthrow new Error(\"Captured history has incomplete index coverage\");\n\t\t\tfor (const reference of page.events) {\n\t\t\t\t// The index classifies assistant/runtime messages; hydrated user roles are still checked below.\n\t\t\t\tif (\n\t\t\t\t\treference.kind !== \"message\" ||\n\t\t\t\t\treference.authority === \"assistant\" ||\n\t\t\t\t\treference.authority === \"runtime\"\n\t\t\t\t)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (entries.length >= maxEntries) throw new Error(\"History entry budget exceeded\");\n\t\t\t\tif (sourceBytes + reference.locator.length > maxSourceBytes)\n\t\t\t\t\tthrow new Error(\"History source byte budget exceeded\");\n\t\t\t\tconst hydrated = await history.hydrateEntry(reference.id, maxSourceBytes - sourceBytes);\n\t\t\t\tif (!hydrated) throw new Error(\"Fork message source is unavailable\");\n\t\t\t\tsourceBytes += reference.locator.length;\n\t\t\t\tentries.push(hydrated.entry);\n\t\t\t}\n\t\t\tif (page.nextAfter === null) break;\n\t\t\tafter = page.nextAfter;\n\t\t}\n\t\treturn projectUserMessages(entries);\n\t});\n}\n"]}
|
|
@@ -12,6 +12,9 @@ export async function readUserMessagesForForking(manager, limits = DEFAULT_FORK_
|
|
|
12
12
|
const entries = manager.supportsCapturedHistoryReads()
|
|
13
13
|
? (await manager.materializeSourceHistory(capturedLimits)).entries.map(({ entry }) => entry)
|
|
14
14
|
: manager.materializeResidentHistory(capturedLimits).entries;
|
|
15
|
+
return projectUserMessages(entries);
|
|
16
|
+
}
|
|
17
|
+
function projectUserMessages(entries) {
|
|
15
18
|
const result = [];
|
|
16
19
|
for (const entry of entries) {
|
|
17
20
|
if (entry.type !== "message" || entry.message.role !== "user")
|
|
@@ -31,4 +34,45 @@ export async function readUserMessagesForForking(manager, limits = DEFAULT_FORK_
|
|
|
31
34
|
}
|
|
32
35
|
return result;
|
|
33
36
|
}
|
|
37
|
+
/** UI picker limits cover user-message candidates, not unrelated archive payloads. */
|
|
38
|
+
export async function readVisibleUserMessagesForForking(manager, limits = DEFAULT_FORK_MESSAGE_LIMITS) {
|
|
39
|
+
const { maxEntries, maxSourceBytes } = limits;
|
|
40
|
+
if (!Number.isSafeInteger(maxEntries) ||
|
|
41
|
+
maxEntries <= 0 ||
|
|
42
|
+
!Number.isSafeInteger(maxSourceBytes) ||
|
|
43
|
+
maxSourceBytes <= 0)
|
|
44
|
+
throw new Error("Invalid history materialization limits");
|
|
45
|
+
if (!manager.supportsCapturedHistoryReads())
|
|
46
|
+
return readUserMessagesForForking(manager, { maxEntries, maxSourceBytes });
|
|
47
|
+
return manager.readSourceHistory(async (history) => {
|
|
48
|
+
const entries = [];
|
|
49
|
+
let sourceBytes = 0;
|
|
50
|
+
let after = 0;
|
|
51
|
+
for (;;) {
|
|
52
|
+
const page = await history.page(after);
|
|
53
|
+
if (page.indexedThrough < history.source.sourceSequence)
|
|
54
|
+
throw new Error("Captured history has incomplete index coverage");
|
|
55
|
+
for (const reference of page.events) {
|
|
56
|
+
// The index classifies assistant/runtime messages; hydrated user roles are still checked below.
|
|
57
|
+
if (reference.kind !== "message" ||
|
|
58
|
+
reference.authority === "assistant" ||
|
|
59
|
+
reference.authority === "runtime")
|
|
60
|
+
continue;
|
|
61
|
+
if (entries.length >= maxEntries)
|
|
62
|
+
throw new Error("History entry budget exceeded");
|
|
63
|
+
if (sourceBytes + reference.locator.length > maxSourceBytes)
|
|
64
|
+
throw new Error("History source byte budget exceeded");
|
|
65
|
+
const hydrated = await history.hydrateEntry(reference.id, maxSourceBytes - sourceBytes);
|
|
66
|
+
if (!hydrated)
|
|
67
|
+
throw new Error("Fork message source is unavailable");
|
|
68
|
+
sourceBytes += reference.locator.length;
|
|
69
|
+
entries.push(hydrated.entry);
|
|
70
|
+
}
|
|
71
|
+
if (page.nextAfter === null)
|
|
72
|
+
break;
|
|
73
|
+
after = page.nextAfter;
|
|
74
|
+
}
|
|
75
|
+
return projectUserMessages(entries);
|
|
76
|
+
});
|
|
77
|
+
}
|
|
34
78
|
//# sourceMappingURL=session-fork-messages.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-fork-messages.js","sourceRoot":"","sources":["../../src/core/session-fork-messages.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,MAAM,2BAA2B,GAAuC,MAAM,CAAC,MAAM,CAAC;IAC5F,UAAU,EAAE,MAAM;IAClB,cAAc,EAAE,EAAE,GAAG,IAAI,GAAG,IAAI;CAChC,CAAC,CAAC;AAEH;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAC/C,OAA+B,EAC/B,MAAM,GAA6B,2BAA2B,EACV;IACpD,MAAM,cAAc,GAAG,EAAE,GAAG,MAAM,EAAE,CAAC;IACrC,MAAM,OAAO,GAAG,OAAO,CAAC,4BAA4B,EAAE;QACrD,CAAC,CAAC,CAAC,MAAM,OAAO,CAAC,wBAAwB,CAAC,cAAc,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC;QAC5F,CAAC,CAAC,OAAO,CAAC,0BAA0B,CAAC,cAAc,CAAC,CAAC,OAAO,CAAC;IAC9D,MAAM,MAAM,GAA6C,EAAE,CAAC;IAC5D,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM;YAAE,SAAS;QACxE,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC;QACtC,IAAI,IAAI,GAAG,EAAE,CAAC;QACd,IAAI,OAAO,OAAO,KAAK,QAAQ;YAAE,IAAI,GAAG,OAAO,CAAC;aAC3C,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;YACjC,IAAI,GAAG,OAAO;iBACZ,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC;iBACtC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC;iBACxB,IAAI,CAAC,EAAE,CAAC,CAAC;QACZ,CAAC;QACD,IAAI,IAAI;YAAE,MAAM,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;IACpD,CAAC;IACD,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["import type { SessionHistoryReadLimits } from \"./session-history-index.js\";\nimport type { ReadonlySessionManager } from \"./session-manager.js\";\n\nexport const DEFAULT_FORK_MESSAGE_LIMITS: Readonly<SessionHistoryReadLimits> = Object.freeze({\n\tmaxEntries: 16_384,\n\tmaxSourceBytes: 64 * 1024 * 1024,\n});\n\n/**\n * Complete source order, including other branches; refuse rather than return a clipped picker.\n * Limits count all entries before text filtering. Native bytes are frame bytes;\n * resident bytes are serialized header/entry JSON, not a heap estimate.\n */\nexport async function readUserMessagesForForking(\n\tmanager: ReadonlySessionManager,\n\tlimits: SessionHistoryReadLimits = DEFAULT_FORK_MESSAGE_LIMITS,\n): Promise<Array<{ entryId: string; text: string }>> {\n\tconst capturedLimits = { ...limits };\n\tconst entries = manager.supportsCapturedHistoryReads()\n\t\t? (await manager.materializeSourceHistory(capturedLimits)).entries.map(({ entry }) => entry)\n\t\t: manager.materializeResidentHistory(capturedLimits).entries;\n\tconst result: Array<{ entryId: string; text: string }> = [];\n\tfor (const entry of entries) {\n\t\tif (entry.type !== \"message\" || entry.message.role !== \"user\") continue;\n\t\tconst content = entry.message.content;\n\t\tlet text = \"\";\n\t\tif (typeof content === \"string\") text = content;\n\t\telse if (Array.isArray(content)) {\n\t\t\ttext = content\n\t\t\t\t.filter((part) => part.type === \"text\")\n\t\t\t\t.map((part) => part.text)\n\t\t\t\t.join(\"\");\n\t\t}\n\t\tif (text) result.push({ entryId: entry.id, text });\n\t}\n\treturn result;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"session-fork-messages.js","sourceRoot":"","sources":["../../src/core/session-fork-messages.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,MAAM,2BAA2B,GAAuC,MAAM,CAAC,MAAM,CAAC;IAC5F,UAAU,EAAE,MAAM;IAClB,cAAc,EAAE,EAAE,GAAG,IAAI,GAAG,IAAI;CAChC,CAAC,CAAC;AAEH;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAC/C,OAA+B,EAC/B,MAAM,GAA6B,2BAA2B,EACV;IACpD,MAAM,cAAc,GAAG,EAAE,GAAG,MAAM,EAAE,CAAC;IACrC,MAAM,OAAO,GAAG,OAAO,CAAC,4BAA4B,EAAE;QACrD,CAAC,CAAC,CAAC,MAAM,OAAO,CAAC,wBAAwB,CAAC,cAAc,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC;QAC5F,CAAC,CAAC,OAAO,CAAC,0BAA0B,CAAC,cAAc,CAAC,CAAC,OAAO,CAAC;IAC9D,OAAO,mBAAmB,CAAC,OAAO,CAAC,CAAC;AAAA,CACpC;AAED,SAAS,mBAAmB,CAAC,OAAgC,EAA4C;IACxG,MAAM,MAAM,GAA6C,EAAE,CAAC;IAC5D,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM;YAAE,SAAS;QACxE,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC;QACtC,IAAI,IAAI,GAAG,EAAE,CAAC;QACd,IAAI,OAAO,OAAO,KAAK,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KAAK,CAAC,CAAC;YACvC,IAAI,IAAI,CAAC,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC,cAAc;gBACtD,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;YACnE,KAAK,MAAM,SAAS,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;gBACrC,gGAAgG;gBAChG,IACC,SAAS,CAAC,IAAI,KAAK,SAAS;oBAC5B,SAAS,CAAC,SAAS,KAAK,WAAW;oBACnC,SAAS,CAAC,SAAS,KAAK,SAAS;oBAEjC,SAAS;gBACV,IAAI,OAAO,CAAC,MAAM,IAAI,UAAU;oBAAE,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;gBACnF,IAAI,WAAW,GAAG,SAAS,CAAC,OAAO,CAAC,MAAM,GAAG,cAAc;oBAC1D,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;gBACxD,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,YAAY,CAAC,SAAS,CAAC,EAAE,EAAE,cAAc,GAAG,WAAW,CAAC,CAAC;gBACxF,IAAI,CAAC,QAAQ;oBAAE,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;gBACrE,WAAW,IAAI,SAAS,CAAC,OAAO,CAAC,MAAM,CAAC;gBACxC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;YAC9B,CAAC;YACD,IAAI,IAAI,CAAC,SAAS,KAAK,IAAI;gBAAE,MAAM;YACnC,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC;QACxB,CAAC;QACD,OAAO,mBAAmB,CAAC,OAAO,CAAC,CAAC;IAAA,CACpC,CAAC,CAAC;AAAA,CACH","sourcesContent":["import type { SessionHistoryReadLimits } from \"./session-history-index.js\";\nimport type { ReadonlySessionManager, SessionEntry } from \"./session-manager.js\";\n\nexport const DEFAULT_FORK_MESSAGE_LIMITS: Readonly<SessionHistoryReadLimits> = Object.freeze({\n\tmaxEntries: 16_384,\n\tmaxSourceBytes: 64 * 1024 * 1024,\n});\n\n/**\n * Complete source order, including other branches; refuse rather than return a clipped picker.\n * Limits count all entries before text filtering. Native bytes are frame bytes;\n * resident bytes are serialized header/entry JSON, not a heap estimate.\n */\nexport async function readUserMessagesForForking(\n\tmanager: ReadonlySessionManager,\n\tlimits: SessionHistoryReadLimits = DEFAULT_FORK_MESSAGE_LIMITS,\n): Promise<Array<{ entryId: string; text: string }>> {\n\tconst capturedLimits = { ...limits };\n\tconst entries = manager.supportsCapturedHistoryReads()\n\t\t? (await manager.materializeSourceHistory(capturedLimits)).entries.map(({ entry }) => entry)\n\t\t: manager.materializeResidentHistory(capturedLimits).entries;\n\treturn projectUserMessages(entries);\n}\n\nfunction projectUserMessages(entries: readonly SessionEntry[]): Array<{ entryId: string; text: string }> {\n\tconst result: Array<{ entryId: string; text: string }> = [];\n\tfor (const entry of entries) {\n\t\tif (entry.type !== \"message\" || entry.message.role !== \"user\") continue;\n\t\tconst content = entry.message.content;\n\t\tlet text = \"\";\n\t\tif (typeof content === \"string\") text = content;\n\t\telse if (Array.isArray(content)) {\n\t\t\ttext = content\n\t\t\t\t.filter((part) => part.type === \"text\")\n\t\t\t\t.map((part) => part.text)\n\t\t\t\t.join(\"\");\n\t\t}\n\t\tif (text) result.push({ entryId: entry.id, text });\n\t}\n\treturn result;\n}\n\n/** UI picker limits cover user-message candidates, not unrelated archive payloads. */\nexport async function readVisibleUserMessagesForForking(\n\tmanager: ReadonlySessionManager,\n\tlimits: SessionHistoryReadLimits = DEFAULT_FORK_MESSAGE_LIMITS,\n): Promise<Array<{ entryId: string; text: string }>> {\n\tconst { maxEntries, maxSourceBytes } = limits;\n\tif (\n\t\t!Number.isSafeInteger(maxEntries) ||\n\t\tmaxEntries <= 0 ||\n\t\t!Number.isSafeInteger(maxSourceBytes) ||\n\t\tmaxSourceBytes <= 0\n\t)\n\t\tthrow new Error(\"Invalid history materialization limits\");\n\tif (!manager.supportsCapturedHistoryReads())\n\t\treturn readUserMessagesForForking(manager, { maxEntries, maxSourceBytes });\n\treturn manager.readSourceHistory(async (history) => {\n\t\tconst entries: SessionEntry[] = [];\n\t\tlet sourceBytes = 0;\n\t\tlet after = 0;\n\t\tfor (;;) {\n\t\t\tconst page = await history.page(after);\n\t\t\tif (page.indexedThrough < history.source.sourceSequence)\n\t\t\t\tthrow new Error(\"Captured history has incomplete index coverage\");\n\t\t\tfor (const reference of page.events) {\n\t\t\t\t// The index classifies assistant/runtime messages; hydrated user roles are still checked below.\n\t\t\t\tif (\n\t\t\t\t\treference.kind !== \"message\" ||\n\t\t\t\t\treference.authority === \"assistant\" ||\n\t\t\t\t\treference.authority === \"runtime\"\n\t\t\t\t)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (entries.length >= maxEntries) throw new Error(\"History entry budget exceeded\");\n\t\t\t\tif (sourceBytes + reference.locator.length > maxSourceBytes)\n\t\t\t\t\tthrow new Error(\"History source byte budget exceeded\");\n\t\t\t\tconst hydrated = await history.hydrateEntry(reference.id, maxSourceBytes - sourceBytes);\n\t\t\t\tif (!hydrated) throw new Error(\"Fork message source is unavailable\");\n\t\t\t\tsourceBytes += reference.locator.length;\n\t\t\t\tentries.push(hydrated.entry);\n\t\t\t}\n\t\t\tif (page.nextAfter === null) break;\n\t\t\tafter = page.nextAfter;\n\t\t}\n\t\treturn projectUserMessages(entries);\n\t});\n}\n"]}
|